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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4d1d72880f13217d55c28fbf09a2e87a777e9412 | app/assets/stylesheets/relaunch/_support.scss | app/assets/stylesheets/relaunch/_support.scss |
.support-form {
margin-top: $headerHeight + 40px;
textarea {
width: 100%;
height: 200px;
}
.help-block {
color: red;
display: inline;
margin-left: 10px;
}
}
|
.support-form {
margin-top: $headerHeight + 40px;
h1 {
margin-bottom: 20px;
}
h5 {
margin: 20px 0 30px 0;
}
textarea {
width: 100%;
height: 200px;
}
.help-block {
color: red;
display: inline;
margin-left: 10px;
}
}
| Set margins to make the lines a bit prettier | Set margins to make the lines a bit prettier
| SCSS | agpl-3.0 | sozialhelden/wheelmap,sozialhelden/wheelmap,sozialhelden/wheelmap,sozialhelden/wheelmap,sozialhelden/wheelmap | scss | ## Code Before:
.support-form {
margin-top: $headerHeight + 40px;
textarea {
width: 100%;
height: 200px;
}
.help-block {
color: red;
display: inline;
margin-left: 10px;
}
}
## Instruction:
Set margins to make the lines a bit prettier
## Code After:
.support-form {
margin-top: $headerHeight + 40px;
h1 {
margin-bottom: 20px;
}
h5 {
margin: 20px 0 30px 0;
}
textarea {
width: 100%;
height: 200px;
}
.help-block {
color: red;
display: inline;
margin-left: 10px;
}
}
|
.support-form {
margin-top: $headerHeight + 40px;
+ h1 {
+ margin-bottom: 20px;
+ }
+
+ h5 {
+ margin: 20px 0 30px 0;
+ }
textarea {
width: 100%;
height: 200px;
}
.help-block {
color: red;
display: inline;
margin-left: 10px;
}
} | 7 | 0.466667 | 7 | 0 |
311b9a7175dcb4e44f72d7ce83519e20902a2fc2 | lib/npm.zsh | lib/npm.zsh | alias npci='npm ci'
alias npi='npm install'
alias npid='npm install -D'
alias npig='npm install -g'
alias npinit='npm init'
alias npinity='npm init -y'
alias npl='npm link'
alias npps='jq .scripts < package.json'
alias npr='npm run'
alias nprb='npm run build'
alias nprc='npm run check'
alias nprd='npm run dev'
alias nprfi='rm -rf node_modules && npm install'
alias nprl='npm run lint'
alias nps='npm start'
alias npsb='npm start build'
alias npsl='npm start lint'
alias npt='npm test'
alias npv='echo "v$(jq -r .version < package.json)"'
alias npv='npm version'
alias npvM='npm version major'
alias npvm='npm version minor'
alias npvp='npm version patch'
function npf() {
jq ".$2" < $(npm ls --parseable "$1")/package.json
}
function nplf() {
jq ".$2" < "./node_modules/$1/package.json"
}
| alias npci='npm ci'
alias npi='npm install'
alias npid='npm install -D'
alias npig='npm install -g'
alias npinit='npm init'
alias npinity='npm init -y'
alias npl='npm link'
alias npps='jq .scripts < package.json'
alias npr='npm run'
alias nprb='npm run build'
alias nprc='npm run check'
alias nprd='npm run dev'
alias nprfi='rm -rf node_modules && npm install'
alias nprl='npm run lint'
alias nps='npm start'
alias npsb='npm start build'
alias npsl='npm start lint'
alias npt='npm test'
alias npv='echo "v$(jq -r .version < package.json)"'
alias npv='npm version'
alias npvM='npm version major'
alias npvm='npm version minor'
alias npvp='npm version patch'
function npf() {
jq ".$2" < $(npm ls --parseable "$1")/package.json
}
function nplf() {
jq ".$2" < "./node_modules/$1/package.json"
}
function npoh() {
open $(npm view $1 homepage)
}
function npon() {
open "https://npm.im/$1"
}
| Add npoh and npon functions. | Add npoh and npon functions.
| Shell | unlicense | KenPowers/dotfiles,knpwrs/dotfiles | shell | ## Code Before:
alias npci='npm ci'
alias npi='npm install'
alias npid='npm install -D'
alias npig='npm install -g'
alias npinit='npm init'
alias npinity='npm init -y'
alias npl='npm link'
alias npps='jq .scripts < package.json'
alias npr='npm run'
alias nprb='npm run build'
alias nprc='npm run check'
alias nprd='npm run dev'
alias nprfi='rm -rf node_modules && npm install'
alias nprl='npm run lint'
alias nps='npm start'
alias npsb='npm start build'
alias npsl='npm start lint'
alias npt='npm test'
alias npv='echo "v$(jq -r .version < package.json)"'
alias npv='npm version'
alias npvM='npm version major'
alias npvm='npm version minor'
alias npvp='npm version patch'
function npf() {
jq ".$2" < $(npm ls --parseable "$1")/package.json
}
function nplf() {
jq ".$2" < "./node_modules/$1/package.json"
}
## Instruction:
Add npoh and npon functions.
## Code After:
alias npci='npm ci'
alias npi='npm install'
alias npid='npm install -D'
alias npig='npm install -g'
alias npinit='npm init'
alias npinity='npm init -y'
alias npl='npm link'
alias npps='jq .scripts < package.json'
alias npr='npm run'
alias nprb='npm run build'
alias nprc='npm run check'
alias nprd='npm run dev'
alias nprfi='rm -rf node_modules && npm install'
alias nprl='npm run lint'
alias nps='npm start'
alias npsb='npm start build'
alias npsl='npm start lint'
alias npt='npm test'
alias npv='echo "v$(jq -r .version < package.json)"'
alias npv='npm version'
alias npvM='npm version major'
alias npvm='npm version minor'
alias npvp='npm version patch'
function npf() {
jq ".$2" < $(npm ls --parseable "$1")/package.json
}
function nplf() {
jq ".$2" < "./node_modules/$1/package.json"
}
function npoh() {
open $(npm view $1 homepage)
}
function npon() {
open "https://npm.im/$1"
}
| alias npci='npm ci'
alias npi='npm install'
alias npid='npm install -D'
alias npig='npm install -g'
alias npinit='npm init'
alias npinity='npm init -y'
alias npl='npm link'
alias npps='jq .scripts < package.json'
alias npr='npm run'
alias nprb='npm run build'
alias nprc='npm run check'
alias nprd='npm run dev'
alias nprfi='rm -rf node_modules && npm install'
alias nprl='npm run lint'
alias nps='npm start'
alias npsb='npm start build'
alias npsl='npm start lint'
alias npt='npm test'
alias npv='echo "v$(jq -r .version < package.json)"'
alias npv='npm version'
alias npvM='npm version major'
alias npvm='npm version minor'
alias npvp='npm version patch'
function npf() {
jq ".$2" < $(npm ls --parseable "$1")/package.json
}
function nplf() {
jq ".$2" < "./node_modules/$1/package.json"
}
+
+ function npoh() {
+ open $(npm view $1 homepage)
+ }
+
+ function npon() {
+ open "https://npm.im/$1"
+ } | 8 | 0.258065 | 8 | 0 |
3b7456b3876155de554c54563788e75ad0be8ac3 | core/media.class.php | core/media.class.php | <?php
/*
* Media class
* Provides functions to get other media types
*/
class Media {
protected $db;
function __construct() {
global $db;
$this->db = $db;
}
/*
* Public: Get photo albums
*
* Returns array of MediaPhoto objects
*/
public function getAlbums($limit = NULL) {
$sql = "SELECT
`id`
FROM `media_photo_album`
WHERE visible = 1
";
if($limit) {
$sql .= "LIMIT 0, ".$limit;
}
$albums = $this->db->get_results($sql);
foreach($albums as $key => $object) {
$output[] = new MediaPhoto($object->id);
}
return $output;
}
}
?>
| <?php
/*
* Media class
* Provides functions to get other media types
*/
class Media {
protected $db;
function __construct() {
global $db;
$this->db = $db;
}
/*
* Public: Get photo albums
*
* Returns array of MediaPhoto objects
*/
public function getAlbums($limit = NULL) {
$sql = "SELECT
`id`
FROM `media_photo_album`
WHERE visible = 1
ORDER BY date DESC
";
if($limit) {
$sql .= "LIMIT 0, ".$limit;
}
$albums = $this->db->get_results($sql);
foreach($albums as $key => $object) {
$output[] = new MediaPhoto($object->id);
}
return $output;
}
}
?>
| Order photo albums by date | Order photo albums by date
| PHP | mit | FelixOnline/FelixOnline,FelixOnline/FelixOnline,FelixOnline/FelixOnline | php | ## Code Before:
<?php
/*
* Media class
* Provides functions to get other media types
*/
class Media {
protected $db;
function __construct() {
global $db;
$this->db = $db;
}
/*
* Public: Get photo albums
*
* Returns array of MediaPhoto objects
*/
public function getAlbums($limit = NULL) {
$sql = "SELECT
`id`
FROM `media_photo_album`
WHERE visible = 1
";
if($limit) {
$sql .= "LIMIT 0, ".$limit;
}
$albums = $this->db->get_results($sql);
foreach($albums as $key => $object) {
$output[] = new MediaPhoto($object->id);
}
return $output;
}
}
?>
## Instruction:
Order photo albums by date
## Code After:
<?php
/*
* Media class
* Provides functions to get other media types
*/
class Media {
protected $db;
function __construct() {
global $db;
$this->db = $db;
}
/*
* Public: Get photo albums
*
* Returns array of MediaPhoto objects
*/
public function getAlbums($limit = NULL) {
$sql = "SELECT
`id`
FROM `media_photo_album`
WHERE visible = 1
ORDER BY date DESC
";
if($limit) {
$sql .= "LIMIT 0, ".$limit;
}
$albums = $this->db->get_results($sql);
foreach($albums as $key => $object) {
$output[] = new MediaPhoto($object->id);
}
return $output;
}
}
?>
| <?php
/*
* Media class
* Provides functions to get other media types
*/
class Media {
protected $db;
function __construct() {
global $db;
$this->db = $db;
}
/*
* Public: Get photo albums
*
* Returns array of MediaPhoto objects
*/
public function getAlbums($limit = NULL) {
$sql = "SELECT
`id`
FROM `media_photo_album`
WHERE visible = 1
+ ORDER BY date DESC
";
if($limit) {
$sql .= "LIMIT 0, ".$limit;
}
$albums = $this->db->get_results($sql);
foreach($albums as $key => $object) {
$output[] = new MediaPhoto($object->id);
}
return $output;
}
}
?> | 1 | 0.028571 | 1 | 0 |
56ffe01657459d41dc62b187903afbad2348e587 | app/assets/javascripts/title_onload.js | app/assets/javascripts/title_onload.js | window.onload = function(){
var headerText = "WriteNow".split("")
animateHeader(headerText);
};
animateHeader = function(text){
current = 0;
header = $(".main_header");
setInterval(function() {
if(current < text.length) {
header.text(header.text() + text[current++]);
}
}, 120);
} | TitleLoader = {
animateHeader: function(text){
current = 0;
header = $(".main_header");
setInterval(function() {
if (current < text.length) {
header.text(header.text() + text[current++]);
}
}, 120);
},
displayTagline: function() {
$(".tagline").fadeIn(4700);
}
}
$(document).ready(function() {
var headerText = "WriteNow".split("");
TitleLoader.animateHeader(headerText);
TitleLoader.displayTagline();
}); | Add TitleLoader namespace for onload functionality. | Add TitleLoader namespace for onload functionality.
| JavaScript | mit | tiger-swallowtails-2014/write-now,tiger-swallowtails-2014/write-now | javascript | ## Code Before:
window.onload = function(){
var headerText = "WriteNow".split("")
animateHeader(headerText);
};
animateHeader = function(text){
current = 0;
header = $(".main_header");
setInterval(function() {
if(current < text.length) {
header.text(header.text() + text[current++]);
}
}, 120);
}
## Instruction:
Add TitleLoader namespace for onload functionality.
## Code After:
TitleLoader = {
animateHeader: function(text){
current = 0;
header = $(".main_header");
setInterval(function() {
if (current < text.length) {
header.text(header.text() + text[current++]);
}
}, 120);
},
displayTagline: function() {
$(".tagline").fadeIn(4700);
}
}
$(document).ready(function() {
var headerText = "WriteNow".split("");
TitleLoader.animateHeader(headerText);
TitleLoader.displayTagline();
}); | - window.onload = function(){
- var headerText = "WriteNow".split("")
- animateHeader(headerText);
- };
+ TitleLoader = {
+ animateHeader: function(text){
+ current = 0;
+ header = $(".main_header");
+ setInterval(function() {
+ if (current < text.length) {
+ header.text(header.text() + text[current++]);
+ }
+ }, 120);
+ },
+ displayTagline: function() {
+ $(".tagline").fadeIn(4700);
+ }
+ }
+ $(document).ready(function() {
+ var headerText = "WriteNow".split("");
+ TitleLoader.animateHeader(headerText);
+ TitleLoader.displayTagline();
+ });
- animateHeader = function(text){
- current = 0;
- header = $(".main_header");
- setInterval(function() {
- if(current < text.length) {
- header.text(header.text() + text[current++]);
- }
- }, 120);
- } | 32 | 2.285714 | 19 | 13 |
1e1217a4a9503a467ae408d75dc4a3b852d395cc | src/app.js | src/app.js | "use strict";
const express = require("express");
const bodyParser = require("body-parser");
const gutibot = require("./gutiBot");
const barelyBot = require("./barelyBot").bot;
const defineBot = require("./defineBot");
const windBot = require("./windBot");
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('Hello! This is gutibot. Are you lost?');
});
app.post("/define", defineBot);
app.post("/doesheknower", gutibot.doSync(barelyBot));
app.post("/wind", gutibot.doSync(windBot));
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, () => console.log("Listening on port " + port));
| "use strict";
const express = require("express");
const bodyParser = require("body-parser");
const gutiBot = require("./gutiBot");
const barelyBot = require("./barelyBot").bot;
const defineBot = require("./defineBot");
const windBot = require("./windBot");
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('Hello! This is gutibot. Are you lost?');
});
app.post("/barely", gutiBot.doSync(barelyBot));
app.post("/define", defineBot);
app.post("/wind", gutiBot.doSync(windBot));
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, () => console.log("Listening on port " + port));
| Use simpler endpoint for barelyBot | Use simpler endpoint for barelyBot
| JavaScript | mit | awseward/gutibot,awseward/silly-slacker | javascript | ## Code Before:
"use strict";
const express = require("express");
const bodyParser = require("body-parser");
const gutibot = require("./gutiBot");
const barelyBot = require("./barelyBot").bot;
const defineBot = require("./defineBot");
const windBot = require("./windBot");
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('Hello! This is gutibot. Are you lost?');
});
app.post("/define", defineBot);
app.post("/doesheknower", gutibot.doSync(barelyBot));
app.post("/wind", gutibot.doSync(windBot));
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, () => console.log("Listening on port " + port));
## Instruction:
Use simpler endpoint for barelyBot
## Code After:
"use strict";
const express = require("express");
const bodyParser = require("body-parser");
const gutiBot = require("./gutiBot");
const barelyBot = require("./barelyBot").bot;
const defineBot = require("./defineBot");
const windBot = require("./windBot");
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('Hello! This is gutibot. Are you lost?');
});
app.post("/barely", gutiBot.doSync(barelyBot));
app.post("/define", defineBot);
app.post("/wind", gutiBot.doSync(windBot));
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, () => console.log("Listening on port " + port));
| "use strict";
const express = require("express");
const bodyParser = require("body-parser");
- const gutibot = require("./gutiBot");
? ^
+ const gutiBot = require("./gutiBot");
? ^
const barelyBot = require("./barelyBot").bot;
const defineBot = require("./defineBot");
const windBot = require("./windBot");
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('Hello! This is gutibot. Are you lost?');
});
+ app.post("/barely", gutiBot.doSync(barelyBot));
app.post("/define", defineBot);
- app.post("/doesheknower", gutibot.doSync(barelyBot));
- app.post("/wind", gutibot.doSync(windBot));
? ^
+ app.post("/wind", gutiBot.doSync(windBot));
? ^
+
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, () => console.log("Listening on port " + port)); | 7 | 0.233333 | 4 | 3 |
07d4b483530e3738d5161b03a2d669dfadfaee7b | lib/css/mod_bulk_commands.css | lib/css/mod_bulk_commands.css | .adminBulkCommands .btn-toolbar {
margin-top: 0;
}
.adminBulkCommands .dropdown-menu li a.adminBulkCommandsHeader {
color: #ccc;
font-weight: bold;
text-transform: uppercase;
pointer-events: none;
cursor: default;
font-size: 11px;
}
.adminBulkCommands .popover-title {
display: none;
}
.adminBulkCommands .popover-content {
background: #fff;
}
.adminBulkCommands .popover .btn {
width: 5em;
}
.adminBulkCommands .popover .btn + .btn {
margin-top: 5px;
} | .adminBulkCommands .btn-toolbar {
margin-top: 0;
}
.adminBulkCommands .dropdown-menu li a.adminBulkCommandsHeader {
color: #ccc;
font-weight: bold;
text-transform: uppercase;
pointer-events: none;
cursor: default;
font-size: 11px;
}
.adminBulkCommands .popover-title {
display: none;
}
.adminBulkCommands .popover-content {
background: #fff;
}
.adminBulkCommands .popover-content:before,
.adminBulkCommands .popover-content:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.adminBulkCommands .popover-content:after {
clear: both;
}
.adminBulkCommands .popover .btn {
width: 5em;
}
.adminBulkCommands .popover .btn + .btn {
margin-top: 5px;
} | Fix height of popover content | Fix height of popover content
| CSS | mit | ArthurClemens/mod_bulk_commands | css | ## Code Before:
.adminBulkCommands .btn-toolbar {
margin-top: 0;
}
.adminBulkCommands .dropdown-menu li a.adminBulkCommandsHeader {
color: #ccc;
font-weight: bold;
text-transform: uppercase;
pointer-events: none;
cursor: default;
font-size: 11px;
}
.adminBulkCommands .popover-title {
display: none;
}
.adminBulkCommands .popover-content {
background: #fff;
}
.adminBulkCommands .popover .btn {
width: 5em;
}
.adminBulkCommands .popover .btn + .btn {
margin-top: 5px;
}
## Instruction:
Fix height of popover content
## Code After:
.adminBulkCommands .btn-toolbar {
margin-top: 0;
}
.adminBulkCommands .dropdown-menu li a.adminBulkCommandsHeader {
color: #ccc;
font-weight: bold;
text-transform: uppercase;
pointer-events: none;
cursor: default;
font-size: 11px;
}
.adminBulkCommands .popover-title {
display: none;
}
.adminBulkCommands .popover-content {
background: #fff;
}
.adminBulkCommands .popover-content:before,
.adminBulkCommands .popover-content:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.adminBulkCommands .popover-content:after {
clear: both;
}
.adminBulkCommands .popover .btn {
width: 5em;
}
.adminBulkCommands .popover .btn + .btn {
margin-top: 5px;
} | .adminBulkCommands .btn-toolbar {
margin-top: 0;
}
.adminBulkCommands .dropdown-menu li a.adminBulkCommandsHeader {
color: #ccc;
font-weight: bold;
text-transform: uppercase;
pointer-events: none;
cursor: default;
font-size: 11px;
}
.adminBulkCommands .popover-title {
display: none;
}
.adminBulkCommands .popover-content {
background: #fff;
}
+ .adminBulkCommands .popover-content:before,
+ .adminBulkCommands .popover-content:after {
+ content: " "; /* 1 */
+ display: table; /* 2 */
+ }
+ .adminBulkCommands .popover-content:after {
+ clear: both;
+ }
+
.adminBulkCommands .popover .btn {
width: 5em;
}
.adminBulkCommands .popover .btn + .btn {
margin-top: 5px;
} | 9 | 0.375 | 9 | 0 |
7b9011224d32f62201d078acf74352dd49b85cb7 | LoginItemController.swift | LoginItemController.swift | //
// LoginItemController.swift
// Barista
//
// Created by Franz Greiling on 19.11.14.
// Copyright (c) 2014 Franz Greiling. All rights reserved.
//
import Foundation
import ServiceManagement
class LoginItemController: NSObject {
var mainBundle: NSBundle
var helperBundle: NSBundle
var enabled: Bool {
didSet {
self.launchAtLogin(self.enabled)
NSUserDefaults.standardUserDefaults().setBool(self.enabled, forKey: "launchOnStart")
}
}
// Singleton Implementation
class var sharedController: LoginItemController {
struct Static {
static let instance: LoginItemController = LoginItemController()
}
return Static.instance
}
override init() {
self.mainBundle = NSBundle.mainBundle()
let path = mainBundle.bundlePath.stringByAppendingPathComponent("Contents/Library/LoginItems/BaristaHelper.app")
self.helperBundle = NSBundle(path: path)!
self.enabled = NSUserDefaults.standardUserDefaults().boolForKey("launchOnStart")
super.init()
}
func launchAtLogin(enabled: Bool) {
// Try to set LoginItem
let flag = (enabled ? 1 : 0) as Boolean
if SMLoginItemSetEnabled(helperBundle.bundleIdentifier, flag) == 0 {
NSLog("SMLoginItemSetEnabled failed")
}
}
} | //
// LoginItemController.swift
// Barista
//
// Created by Franz Greiling on 19.11.14.
// Copyright (c) 2014 Franz Greiling. All rights reserved.
//
import Foundation
import ServiceManagement
class LoginItemController: NSObject {
var mainBundle: NSBundle
var helperBundle: NSBundle
var enabled: Bool {
didSet {
let flag = (self.enabled ? 1 : 0) as Boolean
if SMLoginItemSetEnabled(helperBundle.bundleIdentifier, flag) == 0 {
NSLog("SMLoginItemSetEnabled failed")
}
NSUserDefaults.standardUserDefaults().setBool(self.enabled, forKey: "launchOnStart")
}
}
// Singleton Implementation
class var sharedController: LoginItemController {
struct Static {
static let instance: LoginItemController = LoginItemController()
}
return Static.instance
}
override init() {
self.mainBundle = NSBundle.mainBundle()
let path = mainBundle.bundlePath.stringByAppendingPathComponent(
"Contents/Library/LoginItems/BaristaHelper.app")
self.helperBundle = NSBundle(path: path)!
self.enabled = NSUserDefaults.standardUserDefaults().boolForKey("launchOnStart")
super.init()
}
} | Integrate launchAtLogin function into setter | Integrate launchAtLogin function into setter
| Swift | bsd-2-clause | laerador/barista | swift | ## Code Before:
//
// LoginItemController.swift
// Barista
//
// Created by Franz Greiling on 19.11.14.
// Copyright (c) 2014 Franz Greiling. All rights reserved.
//
import Foundation
import ServiceManagement
class LoginItemController: NSObject {
var mainBundle: NSBundle
var helperBundle: NSBundle
var enabled: Bool {
didSet {
self.launchAtLogin(self.enabled)
NSUserDefaults.standardUserDefaults().setBool(self.enabled, forKey: "launchOnStart")
}
}
// Singleton Implementation
class var sharedController: LoginItemController {
struct Static {
static let instance: LoginItemController = LoginItemController()
}
return Static.instance
}
override init() {
self.mainBundle = NSBundle.mainBundle()
let path = mainBundle.bundlePath.stringByAppendingPathComponent("Contents/Library/LoginItems/BaristaHelper.app")
self.helperBundle = NSBundle(path: path)!
self.enabled = NSUserDefaults.standardUserDefaults().boolForKey("launchOnStart")
super.init()
}
func launchAtLogin(enabled: Bool) {
// Try to set LoginItem
let flag = (enabled ? 1 : 0) as Boolean
if SMLoginItemSetEnabled(helperBundle.bundleIdentifier, flag) == 0 {
NSLog("SMLoginItemSetEnabled failed")
}
}
}
## Instruction:
Integrate launchAtLogin function into setter
## Code After:
//
// LoginItemController.swift
// Barista
//
// Created by Franz Greiling on 19.11.14.
// Copyright (c) 2014 Franz Greiling. All rights reserved.
//
import Foundation
import ServiceManagement
class LoginItemController: NSObject {
var mainBundle: NSBundle
var helperBundle: NSBundle
var enabled: Bool {
didSet {
let flag = (self.enabled ? 1 : 0) as Boolean
if SMLoginItemSetEnabled(helperBundle.bundleIdentifier, flag) == 0 {
NSLog("SMLoginItemSetEnabled failed")
}
NSUserDefaults.standardUserDefaults().setBool(self.enabled, forKey: "launchOnStart")
}
}
// Singleton Implementation
class var sharedController: LoginItemController {
struct Static {
static let instance: LoginItemController = LoginItemController()
}
return Static.instance
}
override init() {
self.mainBundle = NSBundle.mainBundle()
let path = mainBundle.bundlePath.stringByAppendingPathComponent(
"Contents/Library/LoginItems/BaristaHelper.app")
self.helperBundle = NSBundle(path: path)!
self.enabled = NSUserDefaults.standardUserDefaults().boolForKey("launchOnStart")
super.init()
}
} | //
// LoginItemController.swift
// Barista
//
// Created by Franz Greiling on 19.11.14.
// Copyright (c) 2014 Franz Greiling. All rights reserved.
//
import Foundation
import ServiceManagement
class LoginItemController: NSObject {
var mainBundle: NSBundle
var helperBundle: NSBundle
var enabled: Bool {
didSet {
- self.launchAtLogin(self.enabled)
+ let flag = (self.enabled ? 1 : 0) as Boolean
+ if SMLoginItemSetEnabled(helperBundle.bundleIdentifier, flag) == 0 {
+ NSLog("SMLoginItemSetEnabled failed")
+ }
NSUserDefaults.standardUserDefaults().setBool(self.enabled, forKey: "launchOnStart")
}
}
// Singleton Implementation
class var sharedController: LoginItemController {
struct Static {
static let instance: LoginItemController = LoginItemController()
}
return Static.instance
}
override init() {
self.mainBundle = NSBundle.mainBundle()
- let path = mainBundle.bundlePath.stringByAppendingPathComponent("Contents/Library/LoginItems/BaristaHelper.app")
? ------------------------------------------------
+ let path = mainBundle.bundlePath.stringByAppendingPathComponent(
+ "Contents/Library/LoginItems/BaristaHelper.app")
self.helperBundle = NSBundle(path: path)!
self.enabled = NSUserDefaults.standardUserDefaults().boolForKey("launchOnStart")
super.init()
}
-
- func launchAtLogin(enabled: Bool) {
- // Try to set LoginItem
- let flag = (enabled ? 1 : 0) as Boolean
- if SMLoginItemSetEnabled(helperBundle.bundleIdentifier, flag) == 0 {
- NSLog("SMLoginItemSetEnabled failed")
- }
- }
} | 16 | 0.326531 | 6 | 10 |
27aa00ee94dc4ae8f604e4c2f312d33fbcee6529 | setup.cfg | setup.cfg | [flake8]
count = True
format = pylint
ignore = E501,E201,E202,E251,E302,E126,E123,E261,E128,E124
[nosetests]
logging-format = %(pathname)s:%(lineno)d: %(process)d: %(message)s
verbosity = 2
with-coverage = 1
cover-package = parameters
cover-erase = 1
with-doctest = 1
| [flake8]
count = True
format = pylint
ignore = E501,E201,E202,E251,E302,E126,E123,E261,E128,E124
[nosetests]
logging-format = %(pathname)s:%(lineno)d: %(process)d: %(levelname)s %(message)s
verbosity = 2
with-coverage = 1
cover-package = parameters
cover-erase = 1
with-doctest = 1
| Add loglevel to nose logging output. | Add loglevel to nose logging output.
In order to track what information is coming from what log level I've
added the levelname output to nose's logging format.
| INI | mit | alunduil/crumbs | ini | ## Code Before:
[flake8]
count = True
format = pylint
ignore = E501,E201,E202,E251,E302,E126,E123,E261,E128,E124
[nosetests]
logging-format = %(pathname)s:%(lineno)d: %(process)d: %(message)s
verbosity = 2
with-coverage = 1
cover-package = parameters
cover-erase = 1
with-doctest = 1
## Instruction:
Add loglevel to nose logging output.
In order to track what information is coming from what log level I've
added the levelname output to nose's logging format.
## Code After:
[flake8]
count = True
format = pylint
ignore = E501,E201,E202,E251,E302,E126,E123,E261,E128,E124
[nosetests]
logging-format = %(pathname)s:%(lineno)d: %(process)d: %(levelname)s %(message)s
verbosity = 2
with-coverage = 1
cover-package = parameters
cover-erase = 1
with-doctest = 1
| [flake8]
count = True
format = pylint
ignore = E501,E201,E202,E251,E302,E126,E123,E261,E128,E124
[nosetests]
- logging-format = %(pathname)s:%(lineno)d: %(process)d: %(message)s
+ logging-format = %(pathname)s:%(lineno)d: %(process)d: %(levelname)s %(message)s
? ++++++++++++++
verbosity = 2
with-coverage = 1
cover-package = parameters
cover-erase = 1
with-doctest = 1 | 2 | 0.133333 | 1 | 1 |
69f8f66d20b9bf94bd9121a05e05a5492791e052 | ui/assets/js/templates/modals/create-stage.html | ui/assets/js/templates/modals/create-stage.html | <div class="modal-header">
<h3 class="modal-title">Create Stage</h3>
</div>
<div class="modal-body">
<h3>Pipeline: {PIPELINE_NAME}</h3>
<div class="form-group">
<label>Available Stage Types</label>
<select class="form-control" ng-model="stage_id">
<option ng-repeat="stage in stages" value="{{ stage.id }}">
{{ stage.name }}
</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" ng-click="cancel()">Cancel</button>
<button class="btn btn-success" type="button" ng-click="ok()">Create</button>
</div>
| <div class="modal-header">
<h3 class="modal-title">Create Stage</h3>
</div>
<div class="modal-body">
<h3>Pipeline: {PIPELINE_NAME}</h3>
<div class="form-group">
<label>Available Stage Types</label>
<select class="form-control" ng-model="stage_id">
<option ng-repeat="stage in stages" value="{{ stage.id }}">
{{ stage.name }}
</option>
</select>
</div>
<div class="form-group">
<label>Stage Name</label>
<em><small>This is your custom name for this stage. Defaults to stage type name.</small></em>
<input class="form-control" type="text" ng-model="name" />
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" ng-click="cancel()">Cancel</button>
<button class="btn btn-success" type="button" ng-click="ok()">Create</button>
</div>
| Allow users to set custom stage name | Allow users to set custom stage name
| HTML | mit | shrunyan/mc-core,andyfleming/mc-core,andyfleming/mc-core,shrunyan/mc-core | html | ## Code Before:
<div class="modal-header">
<h3 class="modal-title">Create Stage</h3>
</div>
<div class="modal-body">
<h3>Pipeline: {PIPELINE_NAME}</h3>
<div class="form-group">
<label>Available Stage Types</label>
<select class="form-control" ng-model="stage_id">
<option ng-repeat="stage in stages" value="{{ stage.id }}">
{{ stage.name }}
</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" ng-click="cancel()">Cancel</button>
<button class="btn btn-success" type="button" ng-click="ok()">Create</button>
</div>
## Instruction:
Allow users to set custom stage name
## Code After:
<div class="modal-header">
<h3 class="modal-title">Create Stage</h3>
</div>
<div class="modal-body">
<h3>Pipeline: {PIPELINE_NAME}</h3>
<div class="form-group">
<label>Available Stage Types</label>
<select class="form-control" ng-model="stage_id">
<option ng-repeat="stage in stages" value="{{ stage.id }}">
{{ stage.name }}
</option>
</select>
</div>
<div class="form-group">
<label>Stage Name</label>
<em><small>This is your custom name for this stage. Defaults to stage type name.</small></em>
<input class="form-control" type="text" ng-model="name" />
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" ng-click="cancel()">Cancel</button>
<button class="btn btn-success" type="button" ng-click="ok()">Create</button>
</div>
| <div class="modal-header">
<h3 class="modal-title">Create Stage</h3>
</div>
<div class="modal-body">
<h3>Pipeline: {PIPELINE_NAME}</h3>
<div class="form-group">
<label>Available Stage Types</label>
<select class="form-control" ng-model="stage_id">
<option ng-repeat="stage in stages" value="{{ stage.id }}">
{{ stage.name }}
</option>
</select>
</div>
+ <div class="form-group">
+ <label>Stage Name</label>
+ <em><small>This is your custom name for this stage. Defaults to stage type name.</small></em>
+ <input class="form-control" type="text" ng-model="name" />
+ </div>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" ng-click="cancel()">Cancel</button>
<button class="btn btn-success" type="button" ng-click="ok()">Create</button>
</div> | 5 | 0.277778 | 5 | 0 |
13a2e77a038e10983ab69798ac50bba5c1d816b3 | README.md | README.md | - [ ] Append newline to input string inside InputStream instead of caller passing a string ending with newline
- [ ] Only expose Parser to caller and handle InputStream and TokenStream inside Parser
- [ ] Add tests
| Expect great things here very soon.
| Move TODO to github issues | Move TODO to github issues | Markdown | mit | babu-thomas/calculator-parser | markdown | ## Code Before:
- [ ] Append newline to input string inside InputStream instead of caller passing a string ending with newline
- [ ] Only expose Parser to caller and handle InputStream and TokenStream inside Parser
- [ ] Add tests
## Instruction:
Move TODO to github issues
## Code After:
Expect great things here very soon.
| + Expect great things here very soon.
- - [ ] Append newline to input string inside InputStream instead of caller passing a string ending with newline
- - [ ] Only expose Parser to caller and handle InputStream and TokenStream inside Parser
- - [ ] Add tests | 4 | 1.333333 | 1 | 3 |
0bd21f6ac42c86362706bf04ba367720c5324e8c | app/client/store.ts | app/client/store.ts | import { createStore, applyMiddleware, combineReducers } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import reducers from './reducers';
import rootSaga from './sagas';
let reduxStore = null;
const proc = process as any;
const sagaMiddleware = createSagaMiddleware();
function create(apollo, initialState) {
const middlewares = [
sagaMiddleware,
apollo.middleware()
];
const store: any = createStore(
combineReducers({
...reducers,
apollo: apollo.reducer()
}),
initialState,
composeWithDevTools(applyMiddleware(...middlewares))
);
store.sagaTask = sagaMiddleware.run(rootSaga);
return store;
}
export function initRedux(apollo, initialState = {}) {
if (!proc.browser) {
return create(apollo, initialState);
}
// Reuse store on the client-side
if (!reduxStore) {
reduxStore = create(apollo, initialState);
}
return reduxStore;
}
| import { createStore, applyMiddleware, combineReducers } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import reducers from './reducers';
import rootSaga from './sagas';
let reduxStore = null;
const proc = process as any;
const sagaMiddleware = createSagaMiddleware();
function create(apollo, initialState) {
const middlewares = [
sagaMiddleware
];
const store: any = createStore(
combineReducers({...reducers}),
initialState,
composeWithDevTools(applyMiddleware(...middlewares))
);
store.sagaTask = sagaMiddleware.run(rootSaga);
return store;
}
export function initRedux(apollo, initialState = {}) {
if (!proc.browser) {
return create(apollo, initialState);
}
// Reuse store on the client-side
if (!reduxStore) {
reduxStore = create(apollo, initialState);
}
return reduxStore;
}
| Remove apollo middleware and reducer | Remove apollo middleware and reducer
| TypeScript | mit | DashBouquet/react-hipstaplate,DashBouquet/react-hipstaplate | typescript | ## Code Before:
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import reducers from './reducers';
import rootSaga from './sagas';
let reduxStore = null;
const proc = process as any;
const sagaMiddleware = createSagaMiddleware();
function create(apollo, initialState) {
const middlewares = [
sagaMiddleware,
apollo.middleware()
];
const store: any = createStore(
combineReducers({
...reducers,
apollo: apollo.reducer()
}),
initialState,
composeWithDevTools(applyMiddleware(...middlewares))
);
store.sagaTask = sagaMiddleware.run(rootSaga);
return store;
}
export function initRedux(apollo, initialState = {}) {
if (!proc.browser) {
return create(apollo, initialState);
}
// Reuse store on the client-side
if (!reduxStore) {
reduxStore = create(apollo, initialState);
}
return reduxStore;
}
## Instruction:
Remove apollo middleware and reducer
## Code After:
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import reducers from './reducers';
import rootSaga from './sagas';
let reduxStore = null;
const proc = process as any;
const sagaMiddleware = createSagaMiddleware();
function create(apollo, initialState) {
const middlewares = [
sagaMiddleware
];
const store: any = createStore(
combineReducers({...reducers}),
initialState,
composeWithDevTools(applyMiddleware(...middlewares))
);
store.sagaTask = sagaMiddleware.run(rootSaga);
return store;
}
export function initRedux(apollo, initialState = {}) {
if (!proc.browser) {
return create(apollo, initialState);
}
// Reuse store on the client-side
if (!reduxStore) {
reduxStore = create(apollo, initialState);
}
return reduxStore;
}
| import { createStore, applyMiddleware, combineReducers } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import reducers from './reducers';
import rootSaga from './sagas';
let reduxStore = null;
const proc = process as any;
const sagaMiddleware = createSagaMiddleware();
function create(apollo, initialState) {
const middlewares = [
- sagaMiddleware,
? -
+ sagaMiddleware
- apollo.middleware()
];
const store: any = createStore(
- combineReducers({
+ combineReducers({...reducers}),
? ++++++++++++++
- ...reducers,
- apollo: apollo.reducer()
- }),
initialState,
composeWithDevTools(applyMiddleware(...middlewares))
);
store.sagaTask = sagaMiddleware.run(rootSaga);
return store;
}
export function initRedux(apollo, initialState = {}) {
if (!proc.browser) {
return create(apollo, initialState);
}
// Reuse store on the client-side
if (!reduxStore) {
reduxStore = create(apollo, initialState);
}
return reduxStore;
} | 8 | 0.195122 | 2 | 6 |
eb496468d61ff3245adbdec4108a04bc40a357fc | Grid.py | Grid.py | from boomslang.LineStyle import LineStyle
class Grid(object):
def __init__(self, color="#dddddd", style="-", visible=True):
self.color = color
self._lineStyle = LineStyle()
self._lineStyle.style = style
self.visible = visible
@property
def style(self):
return self._lineStyle.style
@style.setter
def style(self, value):
self._lineStyle.style = value
@style.getter
def style(self):
return self._lineStyle.style
def draw(self, fig, axes):
if self.visible:
axes.grid(color=self.color, linestyle=self.style)
# Gridlines should be below plots
axes.set_axisbelow(True)
| from boomslang.LineStyle import LineStyle
class Grid(object):
def __init__(self, color="#dddddd", style="-", visible=True):
self.color = color
self._lineStyle = LineStyle()
self._lineStyle.style = style
self.visible = visible
self.which = 'major'
@property
def style(self):
return self._lineStyle.style
@style.setter
def style(self, value):
self._lineStyle.style = value
@style.getter
def style(self):
return self._lineStyle.style
def draw(self, fig, axes):
if self.visible:
axes.grid(color=self.color, linestyle=self.style,
which=self.which)
# Gridlines should be below plots
axes.set_axisbelow(True)
| Allow gridlines on both major and minor axes. | Allow gridlines on both major and minor axes.
| Python | bsd-3-clause | alexras/boomslang | python | ## Code Before:
from boomslang.LineStyle import LineStyle
class Grid(object):
def __init__(self, color="#dddddd", style="-", visible=True):
self.color = color
self._lineStyle = LineStyle()
self._lineStyle.style = style
self.visible = visible
@property
def style(self):
return self._lineStyle.style
@style.setter
def style(self, value):
self._lineStyle.style = value
@style.getter
def style(self):
return self._lineStyle.style
def draw(self, fig, axes):
if self.visible:
axes.grid(color=self.color, linestyle=self.style)
# Gridlines should be below plots
axes.set_axisbelow(True)
## Instruction:
Allow gridlines on both major and minor axes.
## Code After:
from boomslang.LineStyle import LineStyle
class Grid(object):
def __init__(self, color="#dddddd", style="-", visible=True):
self.color = color
self._lineStyle = LineStyle()
self._lineStyle.style = style
self.visible = visible
self.which = 'major'
@property
def style(self):
return self._lineStyle.style
@style.setter
def style(self, value):
self._lineStyle.style = value
@style.getter
def style(self):
return self._lineStyle.style
def draw(self, fig, axes):
if self.visible:
axes.grid(color=self.color, linestyle=self.style,
which=self.which)
# Gridlines should be below plots
axes.set_axisbelow(True)
| from boomslang.LineStyle import LineStyle
class Grid(object):
def __init__(self, color="#dddddd", style="-", visible=True):
self.color = color
self._lineStyle = LineStyle()
self._lineStyle.style = style
self.visible = visible
+ self.which = 'major'
@property
def style(self):
return self._lineStyle.style
@style.setter
def style(self, value):
self._lineStyle.style = value
@style.getter
def style(self):
return self._lineStyle.style
def draw(self, fig, axes):
if self.visible:
- axes.grid(color=self.color, linestyle=self.style)
? ^
+ axes.grid(color=self.color, linestyle=self.style,
? ^
+ which=self.which)
# Gridlines should be below plots
axes.set_axisbelow(True) | 4 | 0.153846 | 3 | 1 |
5a3c89ca2670e6a00e053366bc6d2d4763210471 | config/common.js | config/common.js | 'use strict';
var fs = require('fs');
var path = require('path');
var merge = require('webpack-merge');
var webpack = require('webpack');
module.exports = function(config) {
return new Promise(function(resolve, reject) {
var cwd = process.cwd();
var parent = path.join(__dirname, '..');
var siteConfig = config.webpack && config.webpack.common;
siteConfig = siteConfig || {};
var corePath = path.join(parent, 'components');
var common = {
corePath: corePath,
parent: parent,
resolve: {
root: path.join(parent, 'node_modules'),
alias: {
'underscore': 'lodash',
'assets': path.join(cwd, 'assets'),
'config': path.join(cwd, 'antwar.config.js'),
'antwar-core': corePath
},
extensions: [
'',
'.js',
'.jsx',
'.json'
],
modulesDirectories: [
path.join(cwd, 'node_modules'),
'node_modules'
]
},
resolveLoader: {
modulesDirectories: [
path.join(parent, 'node_modules'),
'node_modules'
]
},
plugins: [
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(config.buildDev)),
'process.env': {
'NODE_ENV': JSON.stringify(config.buildDev ? 'dev' : 'production')
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin()
]
};
resolve(merge(common, siteConfig));
});
};
| 'use strict';
var fs = require('fs');
var path = require('path');
var merge = require('webpack-merge');
var webpack = require('webpack');
module.exports = function(config) {
return new Promise(function(resolve, reject) {
var cwd = process.cwd();
var parent = path.join(__dirname, '..');
var siteConfig = config.webpack && config.webpack.common;
siteConfig = siteConfig || {};
var corePath = path.join(parent, 'components');
var common = {
corePath: corePath,
parent: parent,
resolve: {
root: path.join(parent, 'node_modules'),
alias: {
'underscore': 'lodash',
'assets': path.join(cwd, 'assets'),
'config': path.join(cwd, 'antwar.config.js'),
'antwar-core': corePath
},
extensions: [
'',
'.js',
'.jsx',
'.json'
],
modulesDirectories: [
path.join(cwd, 'node_modules'),
'node_modules'
]
},
resolveLoader: {
modulesDirectories: [
path.join(parent, 'node_modules'),
'node_modules'
]
},
plugins: [
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(config.buildDev)),
'process.env': {
'NODE_ENV': 'dev'
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin()
]
};
resolve(merge(common, siteConfig));
});
};
| Use dev env while building for production | Use dev env while building for production
This yields better errors.
| JavaScript | mit | antwarjs/antwar | javascript | ## Code Before:
'use strict';
var fs = require('fs');
var path = require('path');
var merge = require('webpack-merge');
var webpack = require('webpack');
module.exports = function(config) {
return new Promise(function(resolve, reject) {
var cwd = process.cwd();
var parent = path.join(__dirname, '..');
var siteConfig = config.webpack && config.webpack.common;
siteConfig = siteConfig || {};
var corePath = path.join(parent, 'components');
var common = {
corePath: corePath,
parent: parent,
resolve: {
root: path.join(parent, 'node_modules'),
alias: {
'underscore': 'lodash',
'assets': path.join(cwd, 'assets'),
'config': path.join(cwd, 'antwar.config.js'),
'antwar-core': corePath
},
extensions: [
'',
'.js',
'.jsx',
'.json'
],
modulesDirectories: [
path.join(cwd, 'node_modules'),
'node_modules'
]
},
resolveLoader: {
modulesDirectories: [
path.join(parent, 'node_modules'),
'node_modules'
]
},
plugins: [
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(config.buildDev)),
'process.env': {
'NODE_ENV': JSON.stringify(config.buildDev ? 'dev' : 'production')
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin()
]
};
resolve(merge(common, siteConfig));
});
};
## Instruction:
Use dev env while building for production
This yields better errors.
## Code After:
'use strict';
var fs = require('fs');
var path = require('path');
var merge = require('webpack-merge');
var webpack = require('webpack');
module.exports = function(config) {
return new Promise(function(resolve, reject) {
var cwd = process.cwd();
var parent = path.join(__dirname, '..');
var siteConfig = config.webpack && config.webpack.common;
siteConfig = siteConfig || {};
var corePath = path.join(parent, 'components');
var common = {
corePath: corePath,
parent: parent,
resolve: {
root: path.join(parent, 'node_modules'),
alias: {
'underscore': 'lodash',
'assets': path.join(cwd, 'assets'),
'config': path.join(cwd, 'antwar.config.js'),
'antwar-core': corePath
},
extensions: [
'',
'.js',
'.jsx',
'.json'
],
modulesDirectories: [
path.join(cwd, 'node_modules'),
'node_modules'
]
},
resolveLoader: {
modulesDirectories: [
path.join(parent, 'node_modules'),
'node_modules'
]
},
plugins: [
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(config.buildDev)),
'process.env': {
'NODE_ENV': 'dev'
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin()
]
};
resolve(merge(common, siteConfig));
});
};
| 'use strict';
var fs = require('fs');
var path = require('path');
var merge = require('webpack-merge');
var webpack = require('webpack');
module.exports = function(config) {
return new Promise(function(resolve, reject) {
var cwd = process.cwd();
var parent = path.join(__dirname, '..');
var siteConfig = config.webpack && config.webpack.common;
siteConfig = siteConfig || {};
var corePath = path.join(parent, 'components');
var common = {
corePath: corePath,
parent: parent,
resolve: {
root: path.join(parent, 'node_modules'),
alias: {
'underscore': 'lodash',
'assets': path.join(cwd, 'assets'),
'config': path.join(cwd, 'antwar.config.js'),
'antwar-core': corePath
},
extensions: [
'',
'.js',
'.jsx',
'.json'
],
modulesDirectories: [
path.join(cwd, 'node_modules'),
'node_modules'
]
},
resolveLoader: {
modulesDirectories: [
path.join(parent, 'node_modules'),
'node_modules'
]
},
plugins: [
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(config.buildDev)),
'process.env': {
- 'NODE_ENV': JSON.stringify(config.buildDev ? 'dev' : 'production')
+ 'NODE_ENV': 'dev'
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin()
]
};
resolve(merge(common, siteConfig));
});
}; | 2 | 0.033898 | 1 | 1 |
dc5da965da358f52af6bd6d0a518b0f37ad1a5b0 | Sources/Tokenizer/Styles/Values/SystemFontWeight.swift | Sources/Tokenizer/Styles/Values/SystemFontWeight.swift | import Foundation
public enum SystemFontWeight: String {
public static let allValues: [SystemFontWeight] = [
.ultralight, .thin, .light, .regular, .medium, .semibold, .bold, .heavy, .black
]
case ultralight
case thin
case light
case regular
case medium
case semibold
case bold
case heavy
case black
public var name: String {
switch self {
case .ultralight:
return "UIFontWeightUltraLight"
case .thin:
return "UIFontWeightThin"
case .light:
return "UIFontWeightLight"
case .regular:
return "UIFontWeightRegular"
case .medium:
return "UIFontWeightMedium"
case .semibold:
return "UIFontWeightSemibold"
case .bold:
return "UIFontWeightBold"
case .heavy:
return "UIFontWeightHeavy"
case .black:
return "UIFontWeightBlack"
}
}
#if ReactantRuntime
public var value: CGFloat {
switch self {
case .ultralight:
return UIFontWeightUltraLight
case .thin:
return UIFontWeightThin
case .light:
return UIFontWeightLight
case .regular:
return UIFontWeightRegular
case .medium:
return UIFontWeightMedium
case .semibold:
return UIFontWeightSemibold
case .bold:
return UIFontWeightBold
case .heavy:
return UIFontWeightHeavy
case .black:
return UIFontWeightBlack
}
}
#endif
}
| import Foundation
public enum SystemFontWeight: String {
public static let allValues: [SystemFontWeight] = [
.thin, .ultralight, .light, .regular, .medium, .semibold, .bold, .heavy, .black
]
case ultralight
case thin
case light
case regular
case medium
case semibold
case bold
case heavy
case black
public var name: String {
switch self {
case .thin:
return "UIFontWeightThin"
case .ultralight:
return "UIFontWeightUltraLight"
case .light:
return "UIFontWeightLight"
case .regular:
return "UIFontWeightRegular"
case .medium:
return "UIFontWeightMedium"
case .semibold:
return "UIFontWeightSemibold"
case .bold:
return "UIFontWeightBold"
case .heavy:
return "UIFontWeightHeavy"
case .black:
return "UIFontWeightBlack"
}
}
#if ReactantRuntime
public var value: CGFloat {
switch self {
case .thin:
return UIFontWeightThin
case .ultralight:
return UIFontWeightUltraLight
case .light:
return UIFontWeightLight
case .regular:
return UIFontWeightRegular
case .medium:
return UIFontWeightMedium
case .semibold:
return UIFontWeightSemibold
case .bold:
return UIFontWeightBold
case .heavy:
return UIFontWeightHeavy
case .black:
return UIFontWeightBlack
}
}
#endif
}
| Correct the order of System Font Weights. | Correct the order of System Font Weights.
| Swift | mit | Brightify/ReactantUI,Brightify/ReactantUI,Brightify/ReactantUI | swift | ## Code Before:
import Foundation
public enum SystemFontWeight: String {
public static let allValues: [SystemFontWeight] = [
.ultralight, .thin, .light, .regular, .medium, .semibold, .bold, .heavy, .black
]
case ultralight
case thin
case light
case regular
case medium
case semibold
case bold
case heavy
case black
public var name: String {
switch self {
case .ultralight:
return "UIFontWeightUltraLight"
case .thin:
return "UIFontWeightThin"
case .light:
return "UIFontWeightLight"
case .regular:
return "UIFontWeightRegular"
case .medium:
return "UIFontWeightMedium"
case .semibold:
return "UIFontWeightSemibold"
case .bold:
return "UIFontWeightBold"
case .heavy:
return "UIFontWeightHeavy"
case .black:
return "UIFontWeightBlack"
}
}
#if ReactantRuntime
public var value: CGFloat {
switch self {
case .ultralight:
return UIFontWeightUltraLight
case .thin:
return UIFontWeightThin
case .light:
return UIFontWeightLight
case .regular:
return UIFontWeightRegular
case .medium:
return UIFontWeightMedium
case .semibold:
return UIFontWeightSemibold
case .bold:
return UIFontWeightBold
case .heavy:
return UIFontWeightHeavy
case .black:
return UIFontWeightBlack
}
}
#endif
}
## Instruction:
Correct the order of System Font Weights.
## Code After:
import Foundation
public enum SystemFontWeight: String {
public static let allValues: [SystemFontWeight] = [
.thin, .ultralight, .light, .regular, .medium, .semibold, .bold, .heavy, .black
]
case ultralight
case thin
case light
case regular
case medium
case semibold
case bold
case heavy
case black
public var name: String {
switch self {
case .thin:
return "UIFontWeightThin"
case .ultralight:
return "UIFontWeightUltraLight"
case .light:
return "UIFontWeightLight"
case .regular:
return "UIFontWeightRegular"
case .medium:
return "UIFontWeightMedium"
case .semibold:
return "UIFontWeightSemibold"
case .bold:
return "UIFontWeightBold"
case .heavy:
return "UIFontWeightHeavy"
case .black:
return "UIFontWeightBlack"
}
}
#if ReactantRuntime
public var value: CGFloat {
switch self {
case .thin:
return UIFontWeightThin
case .ultralight:
return UIFontWeightUltraLight
case .light:
return UIFontWeightLight
case .regular:
return UIFontWeightRegular
case .medium:
return UIFontWeightMedium
case .semibold:
return UIFontWeightSemibold
case .bold:
return UIFontWeightBold
case .heavy:
return UIFontWeightHeavy
case .black:
return UIFontWeightBlack
}
}
#endif
}
| import Foundation
public enum SystemFontWeight: String {
public static let allValues: [SystemFontWeight] = [
- .ultralight, .thin, .light, .regular, .medium, .semibold, .bold, .heavy, .black
? -------
+ .thin, .ultralight, .light, .regular, .medium, .semibold, .bold, .heavy, .black
? +++++++
]
case ultralight
case thin
case light
case regular
case medium
case semibold
case bold
case heavy
case black
public var name: String {
switch self {
+ case .thin:
+ return "UIFontWeightThin"
case .ultralight:
return "UIFontWeightUltraLight"
- case .thin:
- return "UIFontWeightThin"
case .light:
return "UIFontWeightLight"
case .regular:
return "UIFontWeightRegular"
case .medium:
return "UIFontWeightMedium"
case .semibold:
return "UIFontWeightSemibold"
case .bold:
return "UIFontWeightBold"
case .heavy:
return "UIFontWeightHeavy"
case .black:
return "UIFontWeightBlack"
}
}
#if ReactantRuntime
public var value: CGFloat {
switch self {
+ case .thin:
+ return UIFontWeightThin
case .ultralight:
return UIFontWeightUltraLight
- case .thin:
- return UIFontWeightThin
case .light:
return UIFontWeightLight
case .regular:
return UIFontWeightRegular
case .medium:
return UIFontWeightMedium
case .semibold:
return UIFontWeightSemibold
case .bold:
return UIFontWeightBold
case .heavy:
return UIFontWeightHeavy
case .black:
return UIFontWeightBlack
}
}
#endif
} | 10 | 0.153846 | 5 | 5 |
b705b1b67e85df3bd63412a737fb389a8d0b7479 | buildspec.yml | buildspec.yml | version: 0.2
env:
variables:
PRX_LAMBDA_CODE_S3_KEY: "lambda/PRX-tower.radiotopia.fm.zip"
PRX_LAMBDA_CODE_CONFIG_PARAMETERS: "RadiotopiaTowerLambdaCodeS3ObjectVersion"
phases:
build:
runtime-versions:
docker: 18
commands:
- "cd $(ls -d */|head -n 1)"
- "docker build ."
post_build:
commands:
- 'curl -sO "https://raw.githubusercontent.com/PRX/Infrastructure/master/ci/utility/post_build.sh" && chmod +x post_build.sh && bash ./post_build.sh'
| version: 0.2
env:
variables:
PRX_LAMBDA_CODE_S3_KEY: "lambda/PRX-tower.radiotopia.fm.zip"
PRX_LAMBDA_CODE_CONFIG_PARAMETERS: "RadiotopiaTowerLambdaCodeS3ObjectVersion"
phases:
install:
runtime-versions:
docker: 18
build:
commands:
- "cd $(ls -d */|head -n 1)"
- "docker build ."
post_build:
commands:
- 'curl -sO "https://raw.githubusercontent.com/PRX/Infrastructure/master/ci/utility/post_build.sh" && chmod +x post_build.sh && bash ./post_build.sh'
| Move runtime declaration to install phase | Move runtime declaration to install phase
| YAML | agpl-3.0 | PRX/tower.radiotopia.fm | yaml | ## Code Before:
version: 0.2
env:
variables:
PRX_LAMBDA_CODE_S3_KEY: "lambda/PRX-tower.radiotopia.fm.zip"
PRX_LAMBDA_CODE_CONFIG_PARAMETERS: "RadiotopiaTowerLambdaCodeS3ObjectVersion"
phases:
build:
runtime-versions:
docker: 18
commands:
- "cd $(ls -d */|head -n 1)"
- "docker build ."
post_build:
commands:
- 'curl -sO "https://raw.githubusercontent.com/PRX/Infrastructure/master/ci/utility/post_build.sh" && chmod +x post_build.sh && bash ./post_build.sh'
## Instruction:
Move runtime declaration to install phase
## Code After:
version: 0.2
env:
variables:
PRX_LAMBDA_CODE_S3_KEY: "lambda/PRX-tower.radiotopia.fm.zip"
PRX_LAMBDA_CODE_CONFIG_PARAMETERS: "RadiotopiaTowerLambdaCodeS3ObjectVersion"
phases:
install:
runtime-versions:
docker: 18
build:
commands:
- "cd $(ls -d */|head -n 1)"
- "docker build ."
post_build:
commands:
- 'curl -sO "https://raw.githubusercontent.com/PRX/Infrastructure/master/ci/utility/post_build.sh" && chmod +x post_build.sh && bash ./post_build.sh'
| version: 0.2
env:
variables:
PRX_LAMBDA_CODE_S3_KEY: "lambda/PRX-tower.radiotopia.fm.zip"
PRX_LAMBDA_CODE_CONFIG_PARAMETERS: "RadiotopiaTowerLambdaCodeS3ObjectVersion"
phases:
- build:
+ install:
runtime-versions:
docker: 18
+ build:
commands:
- "cd $(ls -d */|head -n 1)"
- "docker build ."
post_build:
commands:
- 'curl -sO "https://raw.githubusercontent.com/PRX/Infrastructure/master/ci/utility/post_build.sh" && chmod +x post_build.sh && bash ./post_build.sh' | 3 | 0.2 | 2 | 1 |
56133272b404f3f1ce38566852c7b36bfd2263ba | gather_loop.sh | gather_loop.sh |
cd "$(dirname "$0")"
# time in seconds with two decimal digits or NaN on error.
function time_get {
t=$(/usr/bin/time --format=%e ./chrome_get.sh $1 2>&1)
if [ $? -eq 0 ]; then
echo $t
else
# wget returned an error
echo "NaN"
fi
}
# Tab-separated URLs to fetch
URLS="http://at.farnell.com/ http://at.rs-online.com/ http://www.mouser.at/ http://www.digikey.at/"
# Write column header
echo "Unixtime $URLS" >> frontpage.csv
# gather loop
while true; do
COLS="$(date +%s)"
for URL in $URLS; do
COLS="$COLS $(time_get $URL)"
done
echo "$COLS" >> frontpage.csv
# Minimum of 60 secs between polls
sleep 60
# Plus some random delay
sleep $((RANDOM % 19))
done
|
cd "$(dirname "$0")"
# time in seconds with two decimal digits or NaN on error.
function time_get {
t=$(/usr/bin/time --format=%e ./chrome_get.sh $1 2>&1)
if [ $? -eq 0 ]; then
echo $t
else
# wget returned an error
echo "NaN"
fi
}
# Tab-separated URLs to fetch
URLS="http://at.farnell.com/ http://at.rs-online.com/ http://www.mouser.at/ http://www.digikey.at/"
# Write column header
echo "Unixtime $URLS" >> frontpage.csv
# gather loop
while true; do
COLS="$(date +%s)"
for URL in $URLS; do
COLS="$COLS $(time_get $URL)"
done
echo "$COLS" >> frontpage.csv
# Minimum of 500 secs between polls
sleep 500
# Plus some random delay => Average is 600 seconds
sleep $((RANDOM % 120))
done
| Increase poll time to 10 minutes | Increase poll time to 10 minutes
| Shell | mit | rfjakob/getcharts,rfjakob/getcharts,rfjakob/getcharts | shell | ## Code Before:
cd "$(dirname "$0")"
# time in seconds with two decimal digits or NaN on error.
function time_get {
t=$(/usr/bin/time --format=%e ./chrome_get.sh $1 2>&1)
if [ $? -eq 0 ]; then
echo $t
else
# wget returned an error
echo "NaN"
fi
}
# Tab-separated URLs to fetch
URLS="http://at.farnell.com/ http://at.rs-online.com/ http://www.mouser.at/ http://www.digikey.at/"
# Write column header
echo "Unixtime $URLS" >> frontpage.csv
# gather loop
while true; do
COLS="$(date +%s)"
for URL in $URLS; do
COLS="$COLS $(time_get $URL)"
done
echo "$COLS" >> frontpage.csv
# Minimum of 60 secs between polls
sleep 60
# Plus some random delay
sleep $((RANDOM % 19))
done
## Instruction:
Increase poll time to 10 minutes
## Code After:
cd "$(dirname "$0")"
# time in seconds with two decimal digits or NaN on error.
function time_get {
t=$(/usr/bin/time --format=%e ./chrome_get.sh $1 2>&1)
if [ $? -eq 0 ]; then
echo $t
else
# wget returned an error
echo "NaN"
fi
}
# Tab-separated URLs to fetch
URLS="http://at.farnell.com/ http://at.rs-online.com/ http://www.mouser.at/ http://www.digikey.at/"
# Write column header
echo "Unixtime $URLS" >> frontpage.csv
# gather loop
while true; do
COLS="$(date +%s)"
for URL in $URLS; do
COLS="$COLS $(time_get $URL)"
done
echo "$COLS" >> frontpage.csv
# Minimum of 500 secs between polls
sleep 500
# Plus some random delay => Average is 600 seconds
sleep $((RANDOM % 120))
done
|
cd "$(dirname "$0")"
# time in seconds with two decimal digits or NaN on error.
function time_get {
t=$(/usr/bin/time --format=%e ./chrome_get.sh $1 2>&1)
if [ $? -eq 0 ]; then
echo $t
else
# wget returned an error
echo "NaN"
fi
}
# Tab-separated URLs to fetch
URLS="http://at.farnell.com/ http://at.rs-online.com/ http://www.mouser.at/ http://www.digikey.at/"
# Write column header
echo "Unixtime $URLS" >> frontpage.csv
# gather loop
while true; do
COLS="$(date +%s)"
for URL in $URLS; do
COLS="$COLS $(time_get $URL)"
done
echo "$COLS" >> frontpage.csv
- # Minimum of 60 secs between polls
? ^
+ # Minimum of 500 secs between polls
? ^^
- sleep 60
? ^
+ sleep 500
? ^ +
- # Plus some random delay
+ # Plus some random delay => Average is 600 seconds
- sleep $((RANDOM % 19))
? ^
+ sleep $((RANDOM % 120))
? ^^
done | 8 | 0.25 | 4 | 4 |
40652e9f8030ddab64a95158e199b099f7747ecc | docs/third-party-libraries-support.md | docs/third-party-libraries-support.md |
If you would like to use [react-native-vector-icons](https://github.com/oblador/react-native-vector-icons) for your Toolbar icons, you can follow [this example](https://github.com/wix/react-native-navigation/issues/43#issuecomment-223907515) or [this](https://gist.github.com/dropfen/4a2209d7274788027f782e8655be198f) gist.
## Redux
Redux can be easily integrated with RNN, follow this great [blog post](https://medium.com/react-native-training/explanation-of-react-native-navigation-wix-with-redux-deabcee8edfc) for instructions.
## Mobx
If you prefer Mobx over Redux, show your interest in this [thread](https://github.com/wix/react-native-navigation/issues/187). Also checkout @mastermoo's [POC](https://github.com/mastermoo/navigation-mobx-example) of using navigation with Mobx.
### MobX (w/ Provider) boilerplate
Check out [this link](https://github.com/kanzitelli/react-native-navigation-mobx-boilerplate) to find a small boilerplate for RNN + MobX (w/ Provider).
|
If you would like to use [react-native-vector-icons](https://github.com/oblador/react-native-vector-icons) for your Toolbar icons, you can follow [this example](https://github.com/wix/react-native-navigation/issues/43#issuecomment-223907515) or [this](https://gist.github.com/dropfen/4a2209d7274788027f782e8655be198f) gist.
## Redux
Redux can be easily integrated with RNN, follow this great [blog post](https://medium.com/react-native-training/explanation-of-react-native-navigation-wix-with-redux-deabcee8edfc) for instructions.
## Mobx
If you prefer Mobx over Redux, show your interest in this [thread](https://github.com/wix/react-native-navigation/issues/187). Also checkout @mastermoo's [POC](https://github.com/mastermoo/navigation-mobx-example) of using navigation with Mobx.
### MobX (w/ Provider) boilerplate
Check out [this link](https://github.com/kanzitelli/react-native-navigation-mobx-boilerplate) to find a small boilerplate for RNN + MobX (w/ Provider).
### redux-persist
Boilerplate for integrating redux-persist can be found [here](https://stackoverflow.com/questions/47732500/react-native-navigation-and-redux-persist).
| Add documentation for third party lib "redux-persist" | Add documentation for third party lib "redux-persist"
| Markdown | mit | chicojasl/react-native-navigation,shahen94/react-native-navigation,3sidedcube/react-native-navigation,wix/react-native-navigation,yusufyildirim/react-native-navigation,3sidedcube/react-native-navigation,Jpoliachik/react-native-navigation,iotize/react-native-navigation,chicojasl/react-native-navigation,wix/react-native-navigation,ceyhuno/react-native-navigation,ceyhuno/react-native-navigation,iotize/react-native-navigation,ceyhuno/react-native-navigation,Jpoliachik/react-native-navigation,iotize/react-native-navigation,chicojasl/react-native-navigation,thanhzusu/react-native-navigation,pqkluan/react-native-navigation,3sidedcube/react-native-navigation,shahen94/react-native-navigation,ceyhuno/react-native-navigation,iotize/react-native-navigation,yusufyildirim/react-native-navigation,Jpoliachik/react-native-navigation,thanhzusu/react-native-navigation,Jpoliachik/react-native-navigation,chicojasl/react-native-navigation,wix/react-native-navigation,thanhzusu/react-native-navigation,pqkluan/react-native-navigation,Jpoliachik/react-native-navigation,shahen94/react-native-navigation,ceyhuno/react-native-navigation,shahen94/react-native-navigation,thanhzusu/react-native-navigation,guyca/react-native-navigation,guyca/react-native-navigation,thanhzusu/react-native-navigation,Jpoliachik/react-native-navigation,guyca/react-native-navigation,guyca/react-native-navigation,ceyhuno/react-native-navigation,pqkluan/react-native-navigation,wix/react-native-navigation,wix/react-native-navigation,yusufyildirim/react-native-navigation,3sidedcube/react-native-navigation,chicojasl/react-native-navigation,pqkluan/react-native-navigation,yusufyildirim/react-native-navigation,chicojasl/react-native-navigation,wix/react-native-navigation,thanhzusu/react-native-navigation | markdown | ## Code Before:
If you would like to use [react-native-vector-icons](https://github.com/oblador/react-native-vector-icons) for your Toolbar icons, you can follow [this example](https://github.com/wix/react-native-navigation/issues/43#issuecomment-223907515) or [this](https://gist.github.com/dropfen/4a2209d7274788027f782e8655be198f) gist.
## Redux
Redux can be easily integrated with RNN, follow this great [blog post](https://medium.com/react-native-training/explanation-of-react-native-navigation-wix-with-redux-deabcee8edfc) for instructions.
## Mobx
If you prefer Mobx over Redux, show your interest in this [thread](https://github.com/wix/react-native-navigation/issues/187). Also checkout @mastermoo's [POC](https://github.com/mastermoo/navigation-mobx-example) of using navigation with Mobx.
### MobX (w/ Provider) boilerplate
Check out [this link](https://github.com/kanzitelli/react-native-navigation-mobx-boilerplate) to find a small boilerplate for RNN + MobX (w/ Provider).
## Instruction:
Add documentation for third party lib "redux-persist"
## Code After:
If you would like to use [react-native-vector-icons](https://github.com/oblador/react-native-vector-icons) for your Toolbar icons, you can follow [this example](https://github.com/wix/react-native-navigation/issues/43#issuecomment-223907515) or [this](https://gist.github.com/dropfen/4a2209d7274788027f782e8655be198f) gist.
## Redux
Redux can be easily integrated with RNN, follow this great [blog post](https://medium.com/react-native-training/explanation-of-react-native-navigation-wix-with-redux-deabcee8edfc) for instructions.
## Mobx
If you prefer Mobx over Redux, show your interest in this [thread](https://github.com/wix/react-native-navigation/issues/187). Also checkout @mastermoo's [POC](https://github.com/mastermoo/navigation-mobx-example) of using navigation with Mobx.
### MobX (w/ Provider) boilerplate
Check out [this link](https://github.com/kanzitelli/react-native-navigation-mobx-boilerplate) to find a small boilerplate for RNN + MobX (w/ Provider).
### redux-persist
Boilerplate for integrating redux-persist can be found [here](https://stackoverflow.com/questions/47732500/react-native-navigation-and-redux-persist).
|
If you would like to use [react-native-vector-icons](https://github.com/oblador/react-native-vector-icons) for your Toolbar icons, you can follow [this example](https://github.com/wix/react-native-navigation/issues/43#issuecomment-223907515) or [this](https://gist.github.com/dropfen/4a2209d7274788027f782e8655be198f) gist.
## Redux
Redux can be easily integrated with RNN, follow this great [blog post](https://medium.com/react-native-training/explanation-of-react-native-navigation-wix-with-redux-deabcee8edfc) for instructions.
## Mobx
If you prefer Mobx over Redux, show your interest in this [thread](https://github.com/wix/react-native-navigation/issues/187). Also checkout @mastermoo's [POC](https://github.com/mastermoo/navigation-mobx-example) of using navigation with Mobx.
### MobX (w/ Provider) boilerplate
Check out [this link](https://github.com/kanzitelli/react-native-navigation-mobx-boilerplate) to find a small boilerplate for RNN + MobX (w/ Provider).
+
+ ### redux-persist
+ Boilerplate for integrating redux-persist can be found [here](https://stackoverflow.com/questions/47732500/react-native-navigation-and-redux-persist). | 3 | 0.272727 | 3 | 0 |
4d7ebd8410a14e13282ce8f60179430d18256279 | src/main/features/linux/mediaKeysDBus.js | src/main/features/linux/mediaKeysDBus.js | import DBus from 'dbus';
try {
const dbus = new DBus();
const session = dbus.getBus('session');
session.getInterface('org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon/MediaKeys',
'org.gnome.SettingsDaemon.MediaKeys', (err, iface) => {
if (!err) {
iface.on('MediaPlayerKeyPressed', (n, keyName) => {
switch (keyName) {
case 'Next': Emitter.sendToGooglePlayMusic('playback:nextTrack'); return;
case 'Previous': Emitter.sendToGooglePlayMusic('playback:previousTrack'); return;
case 'Play': Emitter.sendToGooglePlayMusic('playback:playPause'); return;
case 'Stop': Emitter.sendToGooglePlayMusic('playback:stop'); return;
default: return;
}
iface.GrabMediaPlayerKeys(0, 'org.gnome.SettingsDaemon.MediaKeys'); // eslint-disable-line
});
}
});
} catch (e) {
// do nothing.
}
| import DBus from 'dbus';
try {
const dbus = new DBus();
const session = dbus.getBus('session');
session.getInterface('org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon/MediaKeys',
'org.gnome.SettingsDaemon.MediaKeys', (err, iface) => {
if (!err) {
iface.on('MediaPlayerKeyPressed', (n, keyName) => {
switch (keyName) {
case 'Next': Emitter.sendToGooglePlayMusic('playback:nextTrack'); return;
case 'Previous': Emitter.sendToGooglePlayMusic('playback:previousTrack'); return;
case 'Play': Emitter.sendToGooglePlayMusic('playback:playPause'); return;
case 'Stop': Emitter.sendToGooglePlayMusic('playback:stop'); return;
default: return;
}
});
iface.GrabMediaPlayerKeys(0, 'org.gnome.SettingsDaemon.MediaKeys'); // eslint-disable-line
}
});
} catch (e) {
// do nothing.
}
| Fix bug in media player keys ubuntu | Fix bug in media player keys ubuntu
| JavaScript | mit | MCManuelLP/Google-Play-Music-Desktop-Player-UNOFFICIAL-,MCManuelLP/Google-Play-Music-Desktop-Player-UNOFFICIAL-,MightyPork/Google-Play-Music-Desktop-Player-UNOFFICIAL-,MightyPork/Google-Play-Music-Desktop-Player-UNOFFICIAL-,n4k1/Google-Play-Music-Desktop-Player-UNOFFICIAL-,MightyPork/Google-Play-Music-Desktop-Player-UNOFFICIAL-,petuhovskiy/Google-Play-Music-Desktop-Player-UNOFFICIAL-,mattcfox/Google-Play-Music-Desktop-Player-UNOFFICIAL-,petuhovskiy/Google-Play-Music-Desktop-Player-UNOFFICIAL-,MarshallOfSound/Google-Play-Music-Desktop-Player-UNOFFICIAL-,mattcfox/Google-Play-Music-Desktop-Player-UNOFFICIAL-,MarshallOfSound/Google-Play-Music-Desktop-Player-UNOFFICIAL-,n4k1/Google-Play-Music-Desktop-Player-UNOFFICIAL-,bjohnso5/Google-Play-Music-Desktop-Player-UNOFFICIAL-,bjohnso5/Google-Play-Music-Desktop-Player-UNOFFICIAL-,mattcfox/Google-Play-Music-Desktop-Player-UNOFFICIAL-,MCManuelLP/Google-Play-Music-Desktop-Player-UNOFFICIAL-,n4k1/Google-Play-Music-Desktop-Player-UNOFFICIAL-,bjohnso5/Google-Play-Music-Desktop-Player-UNOFFICIAL-,MarshallOfSound/Google-Play-Music-Desktop-Player-UNOFFICIAL-,petuhovskiy/Google-Play-Music-Desktop-Player-UNOFFICIAL- | javascript | ## Code Before:
import DBus from 'dbus';
try {
const dbus = new DBus();
const session = dbus.getBus('session');
session.getInterface('org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon/MediaKeys',
'org.gnome.SettingsDaemon.MediaKeys', (err, iface) => {
if (!err) {
iface.on('MediaPlayerKeyPressed', (n, keyName) => {
switch (keyName) {
case 'Next': Emitter.sendToGooglePlayMusic('playback:nextTrack'); return;
case 'Previous': Emitter.sendToGooglePlayMusic('playback:previousTrack'); return;
case 'Play': Emitter.sendToGooglePlayMusic('playback:playPause'); return;
case 'Stop': Emitter.sendToGooglePlayMusic('playback:stop'); return;
default: return;
}
iface.GrabMediaPlayerKeys(0, 'org.gnome.SettingsDaemon.MediaKeys'); // eslint-disable-line
});
}
});
} catch (e) {
// do nothing.
}
## Instruction:
Fix bug in media player keys ubuntu
## Code After:
import DBus from 'dbus';
try {
const dbus = new DBus();
const session = dbus.getBus('session');
session.getInterface('org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon/MediaKeys',
'org.gnome.SettingsDaemon.MediaKeys', (err, iface) => {
if (!err) {
iface.on('MediaPlayerKeyPressed', (n, keyName) => {
switch (keyName) {
case 'Next': Emitter.sendToGooglePlayMusic('playback:nextTrack'); return;
case 'Previous': Emitter.sendToGooglePlayMusic('playback:previousTrack'); return;
case 'Play': Emitter.sendToGooglePlayMusic('playback:playPause'); return;
case 'Stop': Emitter.sendToGooglePlayMusic('playback:stop'); return;
default: return;
}
});
iface.GrabMediaPlayerKeys(0, 'org.gnome.SettingsDaemon.MediaKeys'); // eslint-disable-line
}
});
} catch (e) {
// do nothing.
}
| import DBus from 'dbus';
try {
const dbus = new DBus();
const session = dbus.getBus('session');
session.getInterface('org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon/MediaKeys',
'org.gnome.SettingsDaemon.MediaKeys', (err, iface) => {
if (!err) {
iface.on('MediaPlayerKeyPressed', (n, keyName) => {
switch (keyName) {
case 'Next': Emitter.sendToGooglePlayMusic('playback:nextTrack'); return;
case 'Previous': Emitter.sendToGooglePlayMusic('playback:previousTrack'); return;
case 'Play': Emitter.sendToGooglePlayMusic('playback:playPause'); return;
case 'Stop': Emitter.sendToGooglePlayMusic('playback:stop'); return;
default: return;
}
- iface.GrabMediaPlayerKeys(0, 'org.gnome.SettingsDaemon.MediaKeys'); // eslint-disable-line
});
+ iface.GrabMediaPlayerKeys(0, 'org.gnome.SettingsDaemon.MediaKeys'); // eslint-disable-line
}
});
} catch (e) {
// do nothing.
} | 2 | 0.083333 | 1 | 1 |
27feb8f67dc37461e683d340efe2608d3d18af63 | deployment/puppet/vmware/.fixtures.yml | deployment/puppet/vmware/.fixtures.yml | fixtures:
symlinks:
ceilometer: "#{source_dir}/../ceilometer"
pacemaker: "#{source_dir}/../pacemaker"
inifile: "#{source_dir}/../inifile"
nova: "#{source_dir}/../nova"
stdlib: "#{source_dir}/../stdlib"
vmware: "#{source_dir}"
oslo: "#{source_dir}/../oslo"
cinder: "#{source_dir}/../cinder"
| fixtures:
symlinks:
ceilometer: "#{source_dir}/../ceilometer"
pacemaker: "#{source_dir}/../pacemaker"
inifile: "#{source_dir}/../inifile"
nova: "#{source_dir}/../nova"
stdlib: "#{source_dir}/../stdlib"
vmware: "#{source_dir}"
oslo: "#{source_dir}/../oslo"
cinder: "#{source_dir}/../cinder"
openstacklib: "#{source_dir}/../openstacklib"
| Update vmware tests module with openstacklib | Update vmware tests module with openstacklib
The upstream openstack modules have added a dependency on openstacklib
and this needs to be added to the vmware module test fixtures.
Change-Id: I3aeef2baac06986bade4f32a2046ef49783e4827
Close-Bug: #1602881
| YAML | apache-2.0 | stackforge/fuel-library,stackforge/fuel-library,stackforge/fuel-library,stackforge/fuel-library | yaml | ## Code Before:
fixtures:
symlinks:
ceilometer: "#{source_dir}/../ceilometer"
pacemaker: "#{source_dir}/../pacemaker"
inifile: "#{source_dir}/../inifile"
nova: "#{source_dir}/../nova"
stdlib: "#{source_dir}/../stdlib"
vmware: "#{source_dir}"
oslo: "#{source_dir}/../oslo"
cinder: "#{source_dir}/../cinder"
## Instruction:
Update vmware tests module with openstacklib
The upstream openstack modules have added a dependency on openstacklib
and this needs to be added to the vmware module test fixtures.
Change-Id: I3aeef2baac06986bade4f32a2046ef49783e4827
Close-Bug: #1602881
## Code After:
fixtures:
symlinks:
ceilometer: "#{source_dir}/../ceilometer"
pacemaker: "#{source_dir}/../pacemaker"
inifile: "#{source_dir}/../inifile"
nova: "#{source_dir}/../nova"
stdlib: "#{source_dir}/../stdlib"
vmware: "#{source_dir}"
oslo: "#{source_dir}/../oslo"
cinder: "#{source_dir}/../cinder"
openstacklib: "#{source_dir}/../openstacklib"
| fixtures:
symlinks:
ceilometer: "#{source_dir}/../ceilometer"
pacemaker: "#{source_dir}/../pacemaker"
inifile: "#{source_dir}/../inifile"
nova: "#{source_dir}/../nova"
stdlib: "#{source_dir}/../stdlib"
vmware: "#{source_dir}"
oslo: "#{source_dir}/../oslo"
cinder: "#{source_dir}/../cinder"
+ openstacklib: "#{source_dir}/../openstacklib" | 1 | 0.1 | 1 | 0 |
c60b623bc4941fce71c1594db7a554d5ba42a5d4 | webapp/src/components/molecules/highcharts/themes.js | webapp/src/components/molecules/highcharts/themes.js | export default {
standard: {
credits: { enabled: false },
chart: {
style: {
fontFamily: "'proxima', 'Helvetica', sans-serif' "
}
},
title: ''
}
}
| export default {
standard: {
credits: { enabled: false },
chart: {
style: {
fontFamily: "'proxima', 'Helvetica', sans-serif' ",
paddingTop: '20px' // Make room for buttons
}
},
exporting: {
buttons: {
contextButton: {
symbol: null,
text: 'Export',
x: -20,
y: -30,
theme: {
style: {
color: '#039',
textDecoration: 'underline'
}
}
}
}
},
title: ''
}
}
| Move export button in all Highcharts | Move export button in all Highcharts
| JavaScript | agpl-3.0 | unicef/rhizome,unicef/rhizome,unicef/rhizome,unicef/rhizome | javascript | ## Code Before:
export default {
standard: {
credits: { enabled: false },
chart: {
style: {
fontFamily: "'proxima', 'Helvetica', sans-serif' "
}
},
title: ''
}
}
## Instruction:
Move export button in all Highcharts
## Code After:
export default {
standard: {
credits: { enabled: false },
chart: {
style: {
fontFamily: "'proxima', 'Helvetica', sans-serif' ",
paddingTop: '20px' // Make room for buttons
}
},
exporting: {
buttons: {
contextButton: {
symbol: null,
text: 'Export',
x: -20,
y: -30,
theme: {
style: {
color: '#039',
textDecoration: 'underline'
}
}
}
}
},
title: ''
}
}
| export default {
standard: {
credits: { enabled: false },
chart: {
style: {
- fontFamily: "'proxima', 'Helvetica', sans-serif' "
+ fontFamily: "'proxima', 'Helvetica', sans-serif' ",
? +
+ paddingTop: '20px' // Make room for buttons
+ }
+ },
+ exporting: {
+ buttons: {
+ contextButton: {
+ symbol: null,
+ text: 'Export',
+ x: -20,
+ y: -30,
+ theme: {
+ style: {
+ color: '#039',
+ textDecoration: 'underline'
+ }
+ }
+ }
}
},
title: ''
}
} | 19 | 1.727273 | 18 | 1 |
8b598333c06698185762cc98e414853e03c427f2 | src/reviews/resources.py | src/reviews/resources.py | from import_export import fields, resources
from .models import Review
class ReviewResource(resources.ModelResource):
reviewer = fields.Field(
attribute='reviewer__email',
readonly=True,
)
proposal = fields.Field(
attribute='proposal__title',
readonly=True,
)
class Meta:
model = Review
fields = [
'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment',
'discloses_comment', 'appropriateness',
]
export_order = fields
def dehydrate_discloses_comment(self, instance):
return int(instance.discloses_comment)
def dehydrate_appropriateness(self, instance):
return int(instance.appropriateness)
| from import_export import fields, resources
from .models import Review
class ReviewResource(resources.ModelResource):
reviewer = fields.Field(
attribute='reviewer__email',
readonly=True,
)
proposal = fields.Field(
attribute='proposal__title',
readonly=True,
)
stage = fields.Field(
attribute='stage',
readonly=True,
)
vote = fields.Field(
attribute='vote',
readonly=True,
)
comment = fields.Field(
attribute='comment',
readonly=True,
)
discloses_comment = fields.Field(
attribute='discloses_comment',
readonly=True,
)
class Meta:
model = Review
fields = [
'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment',
'discloses_comment', 'appropriateness',
]
export_order = fields
def dehydrate_discloses_comment(self, instance):
return int(instance.discloses_comment)
def dehydrate_appropriateness(self, instance):
return int(instance.appropriateness)
| Mark fields except appropriateness as readonly | Mark fields except appropriateness as readonly
| Python | mit | pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016 | python | ## Code Before:
from import_export import fields, resources
from .models import Review
class ReviewResource(resources.ModelResource):
reviewer = fields.Field(
attribute='reviewer__email',
readonly=True,
)
proposal = fields.Field(
attribute='proposal__title',
readonly=True,
)
class Meta:
model = Review
fields = [
'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment',
'discloses_comment', 'appropriateness',
]
export_order = fields
def dehydrate_discloses_comment(self, instance):
return int(instance.discloses_comment)
def dehydrate_appropriateness(self, instance):
return int(instance.appropriateness)
## Instruction:
Mark fields except appropriateness as readonly
## Code After:
from import_export import fields, resources
from .models import Review
class ReviewResource(resources.ModelResource):
reviewer = fields.Field(
attribute='reviewer__email',
readonly=True,
)
proposal = fields.Field(
attribute='proposal__title',
readonly=True,
)
stage = fields.Field(
attribute='stage',
readonly=True,
)
vote = fields.Field(
attribute='vote',
readonly=True,
)
comment = fields.Field(
attribute='comment',
readonly=True,
)
discloses_comment = fields.Field(
attribute='discloses_comment',
readonly=True,
)
class Meta:
model = Review
fields = [
'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment',
'discloses_comment', 'appropriateness',
]
export_order = fields
def dehydrate_discloses_comment(self, instance):
return int(instance.discloses_comment)
def dehydrate_appropriateness(self, instance):
return int(instance.appropriateness)
| from import_export import fields, resources
from .models import Review
class ReviewResource(resources.ModelResource):
reviewer = fields.Field(
attribute='reviewer__email',
readonly=True,
)
proposal = fields.Field(
attribute='proposal__title',
+ readonly=True,
+ )
+ stage = fields.Field(
+ attribute='stage',
+ readonly=True,
+ )
+ vote = fields.Field(
+ attribute='vote',
+ readonly=True,
+ )
+ comment = fields.Field(
+ attribute='comment',
+ readonly=True,
+ )
+ discloses_comment = fields.Field(
+ attribute='discloses_comment',
readonly=True,
)
class Meta:
model = Review
fields = [
'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment',
'discloses_comment', 'appropriateness',
]
export_order = fields
def dehydrate_discloses_comment(self, instance):
return int(instance.discloses_comment)
def dehydrate_appropriateness(self, instance):
return int(instance.appropriateness) | 16 | 0.551724 | 16 | 0 |
387fae7360786cfd3bb97c1683436ef83b0506b6 | lib/airbrake/rails/middleware/exceptions_catcher.rb | lib/airbrake/rails/middleware/exceptions_catcher.rb | module Airbrake
module Rails
module Middleware
module ExceptionsCatcher
def self.included(base)
base.send(:alias_method_chain,:render_exception,:airbrake)
end
def skip_user_agent?(env)
user_agent = env["HTTP_USER_AGENT"]
::Airbrake.configuration.ignore_user_agent.flatten.any? { |ua| ua === user_agent }
rescue
false
end
def render_exception_with_airbrake(env,exception)
controller = env['action_controller.instance']
env['airbrake.error_id'] = Airbrake.
notify_or_ignore(exception,
controller.airbrake_request_data) unless skip_user_agent?(env)
if defined?(controller.rescue_action_in_public_without_airbrake)
controller.rescue_action_in_public_without_airbrake(exception)
end
render_exception_without_airbrake(env,exception)
end
end
end
end
end
| module Airbrake
module Rails
module Middleware
module ExceptionsCatcher
def self.included(base)
base.send(:alias_method_chain,:render_exception,:airbrake)
end
def skip_user_agent?(env)
user_agent = env["HTTP_USER_AGENT"]
::Airbrake.configuration.ignore_user_agent.flatten.any? { |ua| ua === user_agent }
rescue
false
end
def render_exception_with_airbrake(env,exception)
controller = env['action_controller.instance']
env['airbrake.error_id'] = Airbrake.
notify_or_ignore(exception,
controller.try(:airbrake_request_data) || {:rack_env => env}) unless skip_user_agent?(env)
if defined?(controller.rescue_action_in_public_without_airbrake)
controller.rescue_action_in_public_without_airbrake(exception)
end
render_exception_without_airbrake(env,exception)
end
end
end
end
end
| Fix Airbrake so it actually reports data. | Fix Airbrake so it actually reports data. | Ruby | mit | nick-desteffen/airbrake,airbrake/airbrake,nick-desteffen/airbrake,Shopify/airbrake,airbrake/airbrake,stevecrozz/hydraulic_brake | ruby | ## Code Before:
module Airbrake
module Rails
module Middleware
module ExceptionsCatcher
def self.included(base)
base.send(:alias_method_chain,:render_exception,:airbrake)
end
def skip_user_agent?(env)
user_agent = env["HTTP_USER_AGENT"]
::Airbrake.configuration.ignore_user_agent.flatten.any? { |ua| ua === user_agent }
rescue
false
end
def render_exception_with_airbrake(env,exception)
controller = env['action_controller.instance']
env['airbrake.error_id'] = Airbrake.
notify_or_ignore(exception,
controller.airbrake_request_data) unless skip_user_agent?(env)
if defined?(controller.rescue_action_in_public_without_airbrake)
controller.rescue_action_in_public_without_airbrake(exception)
end
render_exception_without_airbrake(env,exception)
end
end
end
end
end
## Instruction:
Fix Airbrake so it actually reports data.
## Code After:
module Airbrake
module Rails
module Middleware
module ExceptionsCatcher
def self.included(base)
base.send(:alias_method_chain,:render_exception,:airbrake)
end
def skip_user_agent?(env)
user_agent = env["HTTP_USER_AGENT"]
::Airbrake.configuration.ignore_user_agent.flatten.any? { |ua| ua === user_agent }
rescue
false
end
def render_exception_with_airbrake(env,exception)
controller = env['action_controller.instance']
env['airbrake.error_id'] = Airbrake.
notify_or_ignore(exception,
controller.try(:airbrake_request_data) || {:rack_env => env}) unless skip_user_agent?(env)
if defined?(controller.rescue_action_in_public_without_airbrake)
controller.rescue_action_in_public_without_airbrake(exception)
end
render_exception_without_airbrake(env,exception)
end
end
end
end
end
| module Airbrake
module Rails
module Middleware
module ExceptionsCatcher
def self.included(base)
base.send(:alias_method_chain,:render_exception,:airbrake)
end
def skip_user_agent?(env)
user_agent = env["HTTP_USER_AGENT"]
::Airbrake.configuration.ignore_user_agent.flatten.any? { |ua| ua === user_agent }
rescue
false
end
def render_exception_with_airbrake(env,exception)
controller = env['action_controller.instance']
env['airbrake.error_id'] = Airbrake.
notify_or_ignore(exception,
- controller.airbrake_request_data) unless skip_user_agent?(env)
+ controller.try(:airbrake_request_data) || {:rack_env => env}) unless skip_user_agent?(env)
? +++++ +++++++++++++++++++++++
if defined?(controller.rescue_action_in_public_without_airbrake)
controller.rescue_action_in_public_without_airbrake(exception)
end
render_exception_without_airbrake(env,exception)
end
end
end
end
end | 2 | 0.068966 | 1 | 1 |
4ff2403278fa4e4728d867caee10b9fd132e9312 | src/f2d.php | src/f2d.php | <?php
add_action( 'wp_ajax_form_to_disk', 'form_to_disk' );
add_action( 'wp_ajax_nopriv_form_to_disk', 'form_to_disk' );
$f2d_option = get_option( 'f2d_options', '' );
function form_to_disk() {
global $f2d_option;
date_default_timezone_set('America/Los_Angeles');
if ( isset( $_POST[ 'marker' ] ) && 'sweepstakes' == $_POST[ 'marker' ] ) {
$protected_dir = ABSPATH . trailingslashit( $f2d_option[ 'path' ] );
$form_data = $_POST[ 'firstName' ] . ',';
$form_data .= $_POST[ 'lastName' ] . ',';
$form_data .= $_POST[ 'email' ];
$entries = fopen( $protected_dir . $f2d_option[ 'filename' ], 'a' )
or die( 'Unable to process that request' );
$txt = date( 'Ymd' );
$txt .= ',';
$txt .= $form_data;
fwrite( $entries, $txt . PHP_EOL );
fclose( $entries );
die();
}
}
| <?php
add_action( 'wp_ajax_form_to_disk', 'form_to_disk' );
add_action( 'wp_ajax_nopriv_form_to_disk', 'form_to_disk' );
$f2d_option = get_option( 'f2d_options', '' );
function form_to_disk() {
global $f2d_option;
date_default_timezone_set('America/Los_Angeles');
if ( isset( $_POST[ 'marker' ] ) && 'sweepstakes' == $_POST[ 'marker' ] ) {
$protected_dir = ABSPATH . trailingslashit( $f2d_option[ 'path' ] );
$form_data = trim( $_POST[ 'firstName' ] ) . ',';
$form_data .= trim( $_POST[ 'lastName' ] ) . ',';
$form_data .= trim( $_POST[ 'email' ] );
$entries = fopen( $protected_dir . $f2d_option[ 'filename' ], 'a' )
or die( 'Unable to process that request' );
$txt = date( 'Ymd' );
$txt .= ',';
$txt .= $form_data;
fwrite( $entries, $txt . PHP_EOL );
fclose( $entries );
die();
}
}
| Trim whitespace from either side of name / email. | Trim whitespace from either side of name / email.
| PHP | mit | jsoningram/form-to-disk | php | ## Code Before:
<?php
add_action( 'wp_ajax_form_to_disk', 'form_to_disk' );
add_action( 'wp_ajax_nopriv_form_to_disk', 'form_to_disk' );
$f2d_option = get_option( 'f2d_options', '' );
function form_to_disk() {
global $f2d_option;
date_default_timezone_set('America/Los_Angeles');
if ( isset( $_POST[ 'marker' ] ) && 'sweepstakes' == $_POST[ 'marker' ] ) {
$protected_dir = ABSPATH . trailingslashit( $f2d_option[ 'path' ] );
$form_data = $_POST[ 'firstName' ] . ',';
$form_data .= $_POST[ 'lastName' ] . ',';
$form_data .= $_POST[ 'email' ];
$entries = fopen( $protected_dir . $f2d_option[ 'filename' ], 'a' )
or die( 'Unable to process that request' );
$txt = date( 'Ymd' );
$txt .= ',';
$txt .= $form_data;
fwrite( $entries, $txt . PHP_EOL );
fclose( $entries );
die();
}
}
## Instruction:
Trim whitespace from either side of name / email.
## Code After:
<?php
add_action( 'wp_ajax_form_to_disk', 'form_to_disk' );
add_action( 'wp_ajax_nopriv_form_to_disk', 'form_to_disk' );
$f2d_option = get_option( 'f2d_options', '' );
function form_to_disk() {
global $f2d_option;
date_default_timezone_set('America/Los_Angeles');
if ( isset( $_POST[ 'marker' ] ) && 'sweepstakes' == $_POST[ 'marker' ] ) {
$protected_dir = ABSPATH . trailingslashit( $f2d_option[ 'path' ] );
$form_data = trim( $_POST[ 'firstName' ] ) . ',';
$form_data .= trim( $_POST[ 'lastName' ] ) . ',';
$form_data .= trim( $_POST[ 'email' ] );
$entries = fopen( $protected_dir . $f2d_option[ 'filename' ], 'a' )
or die( 'Unable to process that request' );
$txt = date( 'Ymd' );
$txt .= ',';
$txt .= $form_data;
fwrite( $entries, $txt . PHP_EOL );
fclose( $entries );
die();
}
}
| <?php
add_action( 'wp_ajax_form_to_disk', 'form_to_disk' );
add_action( 'wp_ajax_nopriv_form_to_disk', 'form_to_disk' );
$f2d_option = get_option( 'f2d_options', '' );
function form_to_disk() {
global $f2d_option;
date_default_timezone_set('America/Los_Angeles');
if ( isset( $_POST[ 'marker' ] ) && 'sweepstakes' == $_POST[ 'marker' ] ) {
$protected_dir = ABSPATH . trailingslashit( $f2d_option[ 'path' ] );
- $form_data = $_POST[ 'firstName' ] . ',';
+ $form_data = trim( $_POST[ 'firstName' ] ) . ',';
? ++++++ ++
- $form_data .= $_POST[ 'lastName' ] . ',';
+ $form_data .= trim( $_POST[ 'lastName' ] ) . ',';
? ++++++ ++
- $form_data .= $_POST[ 'email' ];
+ $form_data .= trim( $_POST[ 'email' ] );
? ++++++ ++
$entries = fopen( $protected_dir . $f2d_option[ 'filename' ], 'a' )
or die( 'Unable to process that request' );
$txt = date( 'Ymd' );
$txt .= ',';
$txt .= $form_data;
fwrite( $entries, $txt . PHP_EOL );
fclose( $entries );
die();
}
} | 6 | 0.230769 | 3 | 3 |
e170a96859232d1436930be7a0cbfc7f2295c8a7 | main.py | main.py | from twisted.internet import reactor
from twisted.web import server, resource
from teiler.server import FileServerResource
from teiler.client import FileRequestResource
import sys
from twisted.python import log
class HelloResource(resource.Resource):
isLeaf = False
numberRequests = 0
def render_GET(self, request):
self.numberRequests += 1
request.setHeader("content-type", "text/plain")
return "I am request #" + str(self.numberRequests) + "\n"
if __name__ == '__main__':
log.startLogging(sys.stdout)
filesServed = []
transferRequests = []
downloadDirectory = "."
root = resource.Resource()
root.putChild('', HelloResource())
root.putChild('files', FileServerResource(filesServed))
root.putChild('requests', FileRequestResource(transferRequests,
downloadDirectory))
reactor.listenTCP(8080, server.Site(root))
reactor.run()
| from twisted.internet import reactor
from twisted.web import server, resource
from teiler.server import FileServerResource
from teiler.client import FileRequestResource
import sys
from twisted.python import log
class HelloResource(resource.Resource):
isLeaf = False
numberRequests = 0
def render_GET(self, request):
request.setHeader("content-type", "text/plain")
return "Welcome to teiler\n"
if __name__ == '__main__':
log.startLogging(sys.stdout)
filesServed = []
transferRequests = []
downloadDirectory = "."
root = resource.Resource()
root.putChild('', HelloResource())
root.putChild('files', FileServerResource(filesServed))
root.putChild('requests', FileRequestResource(transferRequests,
downloadDirectory))
reactor.listenTCP(8080, server.Site(root))
reactor.run()
| Set root resource to welcome | Set root resource to welcome
| Python | mit | derwolfe/teiler,derwolfe/teiler | python | ## Code Before:
from twisted.internet import reactor
from twisted.web import server, resource
from teiler.server import FileServerResource
from teiler.client import FileRequestResource
import sys
from twisted.python import log
class HelloResource(resource.Resource):
isLeaf = False
numberRequests = 0
def render_GET(self, request):
self.numberRequests += 1
request.setHeader("content-type", "text/plain")
return "I am request #" + str(self.numberRequests) + "\n"
if __name__ == '__main__':
log.startLogging(sys.stdout)
filesServed = []
transferRequests = []
downloadDirectory = "."
root = resource.Resource()
root.putChild('', HelloResource())
root.putChild('files', FileServerResource(filesServed))
root.putChild('requests', FileRequestResource(transferRequests,
downloadDirectory))
reactor.listenTCP(8080, server.Site(root))
reactor.run()
## Instruction:
Set root resource to welcome
## Code After:
from twisted.internet import reactor
from twisted.web import server, resource
from teiler.server import FileServerResource
from teiler.client import FileRequestResource
import sys
from twisted.python import log
class HelloResource(resource.Resource):
isLeaf = False
numberRequests = 0
def render_GET(self, request):
request.setHeader("content-type", "text/plain")
return "Welcome to teiler\n"
if __name__ == '__main__':
log.startLogging(sys.stdout)
filesServed = []
transferRequests = []
downloadDirectory = "."
root = resource.Resource()
root.putChild('', HelloResource())
root.putChild('files', FileServerResource(filesServed))
root.putChild('requests', FileRequestResource(transferRequests,
downloadDirectory))
reactor.listenTCP(8080, server.Site(root))
reactor.run()
| from twisted.internet import reactor
from twisted.web import server, resource
from teiler.server import FileServerResource
from teiler.client import FileRequestResource
import sys
from twisted.python import log
class HelloResource(resource.Resource):
isLeaf = False
numberRequests = 0
def render_GET(self, request):
- self.numberRequests += 1
request.setHeader("content-type", "text/plain")
- return "I am request #" + str(self.numberRequests) + "\n"
+ return "Welcome to teiler\n"
if __name__ == '__main__':
log.startLogging(sys.stdout)
filesServed = []
transferRequests = []
downloadDirectory = "."
root = resource.Resource()
root.putChild('', HelloResource())
root.putChild('files', FileServerResource(filesServed))
root.putChild('requests', FileRequestResource(transferRequests,
downloadDirectory))
reactor.listenTCP(8080, server.Site(root))
reactor.run()
| 3 | 0.09375 | 1 | 2 |
4ef0ace6e35f1b77387f2342ecb8fff614f8f2b2 | frameworks/Java/wicket/setup.sh | frameworks/Java/wicket/setup.sh |
fw_depends java resin maven
sed -i 's|127.0.0.1|'${DBHOST}'|g' src/main/webapp/WEB-INF/resin-web.xml
sed -i 's|localhost|'${DBHOST}'|g' src/main/java/hellowicket/WicketApplication.java
mvn clean compile war:war
rm -rf $RESIN_HOME/webapps/*
cp target/hellowicket-*.war $RESIN_HOME/webapps/wicket.war
resinctl start
|
fw_depends java resin maven
sed -i 's|localhost|'${DBHOST}'|g' src/main/java/hellowicket/WicketApplication.java
mvn clean compile war:war
rm -rf $RESIN_HOME/webapps/*
cp target/hellowicket-*.war $RESIN_HOME/webapps/wicket.war
resinctl start
| Remove sed rule that modifies the content of resin-web.xml. resin-web.xml has been removed. | Remove sed rule that modifies the content of resin-web.xml. resin-web.xml has been removed.
| Shell | bsd-3-clause | methane/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,methane/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,actframework/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zapov/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,methane/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zapov/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,zloster/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zloster/FrameworkBenchmarks,methane/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,zloster/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zloster/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,doom369/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zapov/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zloster/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,zapov/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,methane/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,methane/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zapov/FrameworkBenchmarks,actframework/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,doom369/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jamming/FrameworkBenchmarks,doom369/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zloster/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,sxend/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,methane/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,doom369/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,doom369/FrameworkBenchmarks,sxend/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jamming/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zapov/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,methane/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zapov/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zloster/FrameworkBenchmarks,actframework/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sxend/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,methane/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jamming/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sxend/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,actframework/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,methane/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zapov/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,doom369/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,methane/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,methane/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zloster/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,actframework/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zapov/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sxend/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sxend/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zloster/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,methane/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,actframework/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,doom369/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jamming/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,methane/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jamming/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,actframework/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,doom369/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sxend/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,actframework/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zapov/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zloster/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,sxend/FrameworkBenchmarks,actframework/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,doom369/FrameworkBenchmarks | shell | ## Code Before:
fw_depends java resin maven
sed -i 's|127.0.0.1|'${DBHOST}'|g' src/main/webapp/WEB-INF/resin-web.xml
sed -i 's|localhost|'${DBHOST}'|g' src/main/java/hellowicket/WicketApplication.java
mvn clean compile war:war
rm -rf $RESIN_HOME/webapps/*
cp target/hellowicket-*.war $RESIN_HOME/webapps/wicket.war
resinctl start
## Instruction:
Remove sed rule that modifies the content of resin-web.xml. resin-web.xml has been removed.
## Code After:
fw_depends java resin maven
sed -i 's|localhost|'${DBHOST}'|g' src/main/java/hellowicket/WicketApplication.java
mvn clean compile war:war
rm -rf $RESIN_HOME/webapps/*
cp target/hellowicket-*.war $RESIN_HOME/webapps/wicket.war
resinctl start
|
fw_depends java resin maven
- sed -i 's|127.0.0.1|'${DBHOST}'|g' src/main/webapp/WEB-INF/resin-web.xml
sed -i 's|localhost|'${DBHOST}'|g' src/main/java/hellowicket/WicketApplication.java
mvn clean compile war:war
rm -rf $RESIN_HOME/webapps/*
cp target/hellowicket-*.war $RESIN_HOME/webapps/wicket.war
resinctl start | 1 | 0.1 | 0 | 1 |
426f1cb21476b9694f508a050ba47ba9dbae7cd5 | spec/skimlinks/configuration_spec.rb | spec/skimlinks/configuration_spec.rb | require 'spec_helper'
describe Skimlinks::Configuration do
before do
Skimlinks.configuration.reset
end
describe '.configure' do
Skimlinks::Configuration::VALID_CONFIG_KEYS.each do |key|
it "should set the #{key}" do
Skimlinks.configure do |config|
config.send "#{key}=", key
end
Skimlinks.configuration.send(key).should eq(key)
end
end
end
Skimlinks::Configuration::VALID_CONFIG_KEYS.each do |key|
describe "##{key}" do
it 'should return the default value' do
Skimlinks.configuration.send(key).should eq(Skimlinks::Configuration.const_get("DEFAULT_#{key.upcase}"))
end
end
end
end
| require 'spec_helper'
describe Skimlinks::Configuration do
before do
Skimlinks.configuration.reset
end
describe '.configure' do
Skimlinks::Configuration::VALID_CONFIG_KEYS.each do |key|
it "should set the #{key}" do
valid_values_const_name = "VALID_#{key.to_s.pluralize.upcase}"
value = if Skimlinks::Configuration.const_defined?(valid_values_const_name)
Skimlinks::Configuration.const_get(valid_values_const_name).sample
else
Faker::Lorem.word
end
Skimlinks.configure do |config|
config.send "#{key}=", value
end
Skimlinks.configuration.send(key).should eq(value)
end
end
end
Skimlinks::Configuration::VALID_CONFIG_KEYS.each do |key|
describe "##{key}" do
it 'should return the default value' do
Skimlinks.configuration.send(key).should eq(Skimlinks::Configuration.const_get("DEFAULT_#{key.upcase}"))
end
end
end
end
| Check for Configuration::VALID_FOOS in spec | Check for Configuration::VALID_FOOS in spec
| Ruby | mit | krautcomputing/skimlinks | ruby | ## Code Before:
require 'spec_helper'
describe Skimlinks::Configuration do
before do
Skimlinks.configuration.reset
end
describe '.configure' do
Skimlinks::Configuration::VALID_CONFIG_KEYS.each do |key|
it "should set the #{key}" do
Skimlinks.configure do |config|
config.send "#{key}=", key
end
Skimlinks.configuration.send(key).should eq(key)
end
end
end
Skimlinks::Configuration::VALID_CONFIG_KEYS.each do |key|
describe "##{key}" do
it 'should return the default value' do
Skimlinks.configuration.send(key).should eq(Skimlinks::Configuration.const_get("DEFAULT_#{key.upcase}"))
end
end
end
end
## Instruction:
Check for Configuration::VALID_FOOS in spec
## Code After:
require 'spec_helper'
describe Skimlinks::Configuration do
before do
Skimlinks.configuration.reset
end
describe '.configure' do
Skimlinks::Configuration::VALID_CONFIG_KEYS.each do |key|
it "should set the #{key}" do
valid_values_const_name = "VALID_#{key.to_s.pluralize.upcase}"
value = if Skimlinks::Configuration.const_defined?(valid_values_const_name)
Skimlinks::Configuration.const_get(valid_values_const_name).sample
else
Faker::Lorem.word
end
Skimlinks.configure do |config|
config.send "#{key}=", value
end
Skimlinks.configuration.send(key).should eq(value)
end
end
end
Skimlinks::Configuration::VALID_CONFIG_KEYS.each do |key|
describe "##{key}" do
it 'should return the default value' do
Skimlinks.configuration.send(key).should eq(Skimlinks::Configuration.const_get("DEFAULT_#{key.upcase}"))
end
end
end
end
| require 'spec_helper'
describe Skimlinks::Configuration do
before do
Skimlinks.configuration.reset
end
describe '.configure' do
Skimlinks::Configuration::VALID_CONFIG_KEYS.each do |key|
it "should set the #{key}" do
+ valid_values_const_name = "VALID_#{key.to_s.pluralize.upcase}"
+ value = if Skimlinks::Configuration.const_defined?(valid_values_const_name)
+ Skimlinks::Configuration.const_get(valid_values_const_name).sample
+ else
+ Faker::Lorem.word
+ end
Skimlinks.configure do |config|
- config.send "#{key}=", key
? ^ -
+ config.send "#{key}=", value
? ^^^^
end
- Skimlinks.configuration.send(key).should eq(key)
? ^ -
+ Skimlinks.configuration.send(key).should eq(value)
? ^^^^
end
end
end
Skimlinks::Configuration::VALID_CONFIG_KEYS.each do |key|
describe "##{key}" do
it 'should return the default value' do
Skimlinks.configuration.send(key).should eq(Skimlinks::Configuration.const_get("DEFAULT_#{key.upcase}"))
end
end
end
end | 10 | 0.384615 | 8 | 2 |
622c2f1e0cf8eae161f94f3022694332e1f75495 | oee.rs | oee.rs | extern crate rand;
use rand::Rng;
use std::env;
const CYPHERBYTES: usize = 32;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
println!("usage: {} file-to-encrypt", args[0]);
return
}
let mut rng = rand::thread_rng();
let mut cyphertext = [0u8; CYPHERBYTES];
rng.fill_bytes(&mut cyphertext);
for x in &cyphertext { print!("{:02x}", *x); }
println!("")
}
| extern crate rand;
use rand::Rng;
use std::env;
const CYPHERBYTES: usize = 32;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
println!("usage: {} file-to-encrypt", args[0]);
return
}
let mut csprng = match rand::OsRng::new() {
Ok(g) => g,
Err(e) => panic!("Could not find a cryptographically-secure PRNG on the system. Details: {}", e)
};
let mut cyphertext = [0u8; CYPHERBYTES];
csprng.fill_bytes(&mut cyphertext);
for x in &cyphertext { print!("{:02x}", *x); }
println!("")
}
| Use Cryptographically Secure PRNG instead of Rng | Use Cryptographically Secure PRNG instead of Rng
As stated in the Rust documentation:
> An application that requires an entropy source for cryptographic purposes
> must use OsRng, which reads randomness from the source that the operating
> system provides (e.g. /dev/urandom on Unixes or CryptGenRandom() on Windows).
> The other random number generators provided by this module are not suitable
> for such purposes.
| Rust | unlicense | veorq/oee | rust | ## Code Before:
extern crate rand;
use rand::Rng;
use std::env;
const CYPHERBYTES: usize = 32;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
println!("usage: {} file-to-encrypt", args[0]);
return
}
let mut rng = rand::thread_rng();
let mut cyphertext = [0u8; CYPHERBYTES];
rng.fill_bytes(&mut cyphertext);
for x in &cyphertext { print!("{:02x}", *x); }
println!("")
}
## Instruction:
Use Cryptographically Secure PRNG instead of Rng
As stated in the Rust documentation:
> An application that requires an entropy source for cryptographic purposes
> must use OsRng, which reads randomness from the source that the operating
> system provides (e.g. /dev/urandom on Unixes or CryptGenRandom() on Windows).
> The other random number generators provided by this module are not suitable
> for such purposes.
## Code After:
extern crate rand;
use rand::Rng;
use std::env;
const CYPHERBYTES: usize = 32;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
println!("usage: {} file-to-encrypt", args[0]);
return
}
let mut csprng = match rand::OsRng::new() {
Ok(g) => g,
Err(e) => panic!("Could not find a cryptographically-secure PRNG on the system. Details: {}", e)
};
let mut cyphertext = [0u8; CYPHERBYTES];
csprng.fill_bytes(&mut cyphertext);
for x in &cyphertext { print!("{:02x}", *x); }
println!("")
}
| extern crate rand;
use rand::Rng;
use std::env;
const CYPHERBYTES: usize = 32;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
println!("usage: {} file-to-encrypt", args[0]);
return
}
- let mut rng = rand::thread_rng();
+ let mut csprng = match rand::OsRng::new() {
+ Ok(g) => g,
+ Err(e) => panic!("Could not find a cryptographically-secure PRNG on the system. Details: {}", e)
+ };
let mut cyphertext = [0u8; CYPHERBYTES];
- rng.fill_bytes(&mut cyphertext);
+ csprng.fill_bytes(&mut cyphertext);
? +++
for x in &cyphertext { print!("{:02x}", *x); }
println!("")
} | 7 | 0.35 | 5 | 2 |
856f37d3a099cd3172c987047260382c825a505e | shaq_overflow/app/views/questions/index.html.erb | shaq_overflow/app/views/questions/index.html.erb | <h1>Here are all the questions</h1>
<h3>Click a question to view more</h3>
<% @questions.each do |question| %>
Votes: | <%= question.votes.count %>
Answers: | <%= question.answers.count %>
<%= link_to("#{question.title}", question_path(question)) %>
<% end %> | <h1>Here are all the questions</h1>
<h3>Click a question to view more</h3>
<% @questions.each do |question| %>
Votes: | <%= question.votes.count %>
Answers: | <%= question.answers.count %>
<ol>
<li><%= link_to("#{question.title}", question_path(question)) %></li>
</ol>
<% end %> | Put questions index page in an ordered list | Put questions index page in an ordered list
| HTML+ERB | mit | lucasrsantos1/lucky-ambassador,lucasrsantos1/lucky-ambassador,lucasrsantos1/lucky-ambassador | html+erb | ## Code Before:
<h1>Here are all the questions</h1>
<h3>Click a question to view more</h3>
<% @questions.each do |question| %>
Votes: | <%= question.votes.count %>
Answers: | <%= question.answers.count %>
<%= link_to("#{question.title}", question_path(question)) %>
<% end %>
## Instruction:
Put questions index page in an ordered list
## Code After:
<h1>Here are all the questions</h1>
<h3>Click a question to view more</h3>
<% @questions.each do |question| %>
Votes: | <%= question.votes.count %>
Answers: | <%= question.answers.count %>
<ol>
<li><%= link_to("#{question.title}", question_path(question)) %></li>
</ol>
<% end %> | <h1>Here are all the questions</h1>
<h3>Click a question to view more</h3>
<% @questions.each do |question| %>
Votes: | <%= question.votes.count %>
Answers: | <%= question.answers.count %>
+ <ol>
- <%= link_to("#{question.title}", question_path(question)) %>
+ <li><%= link_to("#{question.title}", question_path(question)) %></li>
? ++++++ +++++
+ </ol>
<% end %> | 4 | 0.5 | 3 | 1 |
516afc233e682bcd78f2ff38a404bb99b42cece1 | app/controllers/cards_controller.rb | app/controllers/cards_controller.rb | class CardsController < ApplicationController
def new
@template = CardTemplate.find(params[:card_template_id])
end
def create
new_card = Card.new(card_params)
if new_card.save
new_card.update(session_id: session.id)
redirect_to card_template_card_url(id: new_card.id)
else
flash[:error] = "Unable to create this card for some reason."
redirect_to new_card_template_card_url
end
end
def show
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
def edit
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
def update
end
private
def card_params
params.require(:card).permit(:custom_message, :signature, :recipient_name,
:street_address, :city, :state, :zip_code, :card_template_id)
end
end
| class CardsController < ApplicationController
def new
@template = CardTemplate.find(params[:card_template_id])
end
def create
new_card = Card.new(card_params)
if new_card.save
new_card.update(session_id: session.id)
redirect_to card_template_card_url(id: new_card.id)
else
flash[:error] = "Unable to create this card for some reason."
redirect_to new_card_template_card_url
end
end
def show
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
def edit
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
def update
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
private
def card_params
params.require(:card).permit(:custom_message, :signature, :recipient_name,
:street_address, :city, :state, :zip_code, :card_template_id)
end
end
| Check session when updating card | Check session when updating card
| Ruby | mit | rasnom/sorryyoufeelthatway,rasnom/sorryyoufeelthatway,rasnom/sorryyoufeelthatway | ruby | ## Code Before:
class CardsController < ApplicationController
def new
@template = CardTemplate.find(params[:card_template_id])
end
def create
new_card = Card.new(card_params)
if new_card.save
new_card.update(session_id: session.id)
redirect_to card_template_card_url(id: new_card.id)
else
flash[:error] = "Unable to create this card for some reason."
redirect_to new_card_template_card_url
end
end
def show
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
def edit
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
def update
end
private
def card_params
params.require(:card).permit(:custom_message, :signature, :recipient_name,
:street_address, :city, :state, :zip_code, :card_template_id)
end
end
## Instruction:
Check session when updating card
## Code After:
class CardsController < ApplicationController
def new
@template = CardTemplate.find(params[:card_template_id])
end
def create
new_card = Card.new(card_params)
if new_card.save
new_card.update(session_id: session.id)
redirect_to card_template_card_url(id: new_card.id)
else
flash[:error] = "Unable to create this card for some reason."
redirect_to new_card_template_card_url
end
end
def show
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
def edit
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
def update
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
private
def card_params
params.require(:card).permit(:custom_message, :signature, :recipient_name,
:street_address, :city, :state, :zip_code, :card_template_id)
end
end
| class CardsController < ApplicationController
def new
@template = CardTemplate.find(params[:card_template_id])
end
def create
new_card = Card.new(card_params)
if new_card.save
new_card.update(session_id: session.id)
redirect_to card_template_card_url(id: new_card.id)
else
flash[:error] = "Unable to create this card for some reason."
redirect_to new_card_template_card_url
end
end
def show
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
def edit
@template = CardTemplate.find(params[:card_template_id])
@card = Card.find(params[:id])
unless @card.session_id == session.id
redirect_to new_card_template_card_url(card_template_id: @template.id)
end
end
def update
+ @template = CardTemplate.find(params[:card_template_id])
+ @card = Card.find(params[:id])
+
+ unless @card.session_id == session.id
+ redirect_to new_card_template_card_url(card_template_id: @template.id)
+ end
end
private
def card_params
params.require(:card).permit(:custom_message, :signature, :recipient_name,
:street_address, :city, :state, :zip_code, :card_template_id)
end
end | 6 | 0.130435 | 6 | 0 |
a985603d92137759f5e8f80a62af12261a8a67d7 | README.md | README.md | ```
.
├── node modules
│ └── dist-build.production.dockerfile
├── src
│ ├── config
│ │ ├── cache-config.ts
│ │ ├── db-config.ts
│ │ ├── logger-config.ts
│ │ ├── session-config.ts
│ │ ├── web-server-config.ts
│ │ └── index.ts
│ ├── modules
│ │ ├── module-name1
│ │ │ ├── business
│ │ │ ├── common
│ │ │ ├── model
│ │ │ └── service
│ │ └── module-name2
│ │ ├── business
│ │ ├── common
│ │ ├── model
│ │ └── service
│ ├── bootstrap.ts
│ └── index.ts
│
.
``` | [](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmission-io%2Fmission.seed?ref=badge_shield)
### Folder Structure
```
.
├── node modules
│ └── dist-build.production.dockerfile
├── src
│ ├── config
│ │ ├── cache-config.ts
│ │ ├── db-config.ts
│ │ ├── logger-config.ts
│ │ ├── session-config.ts
│ │ ├── web-server-config.ts
│ │ └── index.ts
│ ├── modules
│ │ ├── module-name1
│ │ │ ├── business
│ │ │ ├── common
│ │ │ ├── model
│ │ │ └── service
│ │ └── module-name2
│ │ ├── business
│ │ ├── common
│ │ ├── model
│ │ └── service
│ ├── bootstrap.ts
│ └── index.ts
│
.
```
## License
[](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmission-io%2Fmission.seed?ref=badge_large) | Add license scan report and status | Add license scan report and status | Markdown | mit | mission-io/mission.seed | markdown | ## Code Before:
```
.
├── node modules
│ └── dist-build.production.dockerfile
├── src
│ ├── config
│ │ ├── cache-config.ts
│ │ ├── db-config.ts
│ │ ├── logger-config.ts
│ │ ├── session-config.ts
│ │ ├── web-server-config.ts
│ │ └── index.ts
│ ├── modules
│ │ ├── module-name1
│ │ │ ├── business
│ │ │ ├── common
│ │ │ ├── model
│ │ │ └── service
│ │ └── module-name2
│ │ ├── business
│ │ ├── common
│ │ ├── model
│ │ └── service
│ ├── bootstrap.ts
│ └── index.ts
│
.
```
## Instruction:
Add license scan report and status
## Code After:
[](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmission-io%2Fmission.seed?ref=badge_shield)
### Folder Structure
```
.
├── node modules
│ └── dist-build.production.dockerfile
├── src
│ ├── config
│ │ ├── cache-config.ts
│ │ ├── db-config.ts
│ │ ├── logger-config.ts
│ │ ├── session-config.ts
│ │ ├── web-server-config.ts
│ │ └── index.ts
│ ├── modules
│ │ ├── module-name1
│ │ │ ├── business
│ │ │ ├── common
│ │ │ ├── model
│ │ │ └── service
│ │ └── module-name2
│ │ ├── business
│ │ ├── common
│ │ ├── model
│ │ └── service
│ ├── bootstrap.ts
│ └── index.ts
│
.
```
## License
[](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmission-io%2Fmission.seed?ref=badge_large) | + [](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmission-io%2Fmission.seed?ref=badge_shield)
+
+
+
+ ### Folder Structure
```
.
├── node modules
│ └── dist-build.production.dockerfile
├── src
│ ├── config
│ │ ├── cache-config.ts
│ │ ├── db-config.ts
│ │ ├── logger-config.ts
│ │ ├── session-config.ts
│ │ ├── web-server-config.ts
│ │ └── index.ts
│ ├── modules
│ │ ├── module-name1
│ │ │ ├── business
│ │ │ ├── common
│ │ │ ├── model
│ │ │ └── service
│ │ └── module-name2
│ │ ├── business
│ │ ├── common
│ │ ├── model
│ │ └── service
│ ├── bootstrap.ts
│ └── index.ts
│
.
```
+
+ ## License
+ [](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmission-io%2Fmission.seed?ref=badge_large) | 8 | 0.285714 | 8 | 0 |
976d27f59a87e3a5e7f860a6900fcf11d1fe80d5 | src/environments/environment.prod.ts | src/environments/environment.prod.ts | export const environment = {
production: true
};
| export const environment = {
production: true,
firebase: {
projectId: "releaseer-a6183",
apiKey: "AIzaSyA_tWprch4_iJKKcEg3CCAO9VwCjvKxY5I",
authDomain: "releaseer-a6183.firebaseapp.com",
databaseURL: "https://releaseer-a6183.firebaseio.com",
storageBucket: "releaseer-a6183.appspot.com",
messagingSenderId: "454541533417"
}
};
| Upgrade Releaser to Angular 4 | Upgrade Releaser to Angular 4
| TypeScript | mit | Richard87/releaser,Richard87/releaser,Richard87/releaser,Richard87/releaser | typescript | ## Code Before:
export const environment = {
production: true
};
## Instruction:
Upgrade Releaser to Angular 4
## Code After:
export const environment = {
production: true,
firebase: {
projectId: "releaseer-a6183",
apiKey: "AIzaSyA_tWprch4_iJKKcEg3CCAO9VwCjvKxY5I",
authDomain: "releaseer-a6183.firebaseapp.com",
databaseURL: "https://releaseer-a6183.firebaseio.com",
storageBucket: "releaseer-a6183.appspot.com",
messagingSenderId: "454541533417"
}
};
| export const environment = {
- production: true
+ production: true,
? +
+ firebase: {
+ projectId: "releaseer-a6183",
+ apiKey: "AIzaSyA_tWprch4_iJKKcEg3CCAO9VwCjvKxY5I",
+ authDomain: "releaseer-a6183.firebaseapp.com",
+ databaseURL: "https://releaseer-a6183.firebaseio.com",
+ storageBucket: "releaseer-a6183.appspot.com",
+ messagingSenderId: "454541533417"
+ }
}; | 10 | 3.333333 | 9 | 1 |
aebb02f7f9bbe5df1cf1d7017f22149ece33ad92 | src/main/java/com/leviathanstudio/craftstudio/network/CraftStudioBasePacket.java | src/main/java/com/leviathanstudio/craftstudio/network/CraftStudioBasePacket.java | package com.leviathanstudio.craftstudio.network;
import java.util.List;
import java.util.UUID;
import com.leviathanstudio.craftstudio.common.animation.IAnimated;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import io.netty.buffer.ByteBuf;
public class CraftStudioBasePacket implements IMessage
{
protected String animationName;
protected UUID uuid;
public CraftStudioBasePacket()
{
}
public CraftStudioBasePacket(String animationNameIn, IAnimated animated)
{
this.animationName = animationNameIn;
this.uuid = animated.getUUID();
}
@Override
public void fromBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, this.animationName);
buf.writeLong(this.uuid.getMostSignificantBits());
buf.writeLong(this.uuid.getLeastSignificantBits());
}
@Override
public void toBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, this.animationName);
long most = buf.readLong();
long least = buf.readLong();
this.uuid = new UUID(most, least);
}
public Entity getEntityByUUID(List<Entity> list, UUID uuid)
{
for (Entity e : list)
if (e.getPersistentID().equals(uuid))
return e;
return null;
}
}
| package com.leviathanstudio.craftstudio.network;
import java.util.List;
import java.util.UUID;
import com.leviathanstudio.craftstudio.common.animation.IAnimated;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import io.netty.buffer.ByteBuf;
public class CraftStudioBasePacket implements IMessage
{
protected String animationName;
protected UUID uuid;
public CraftStudioBasePacket()
{
}
public CraftStudioBasePacket(String animationNameIn, IAnimated animated)
{
this.animationName = animationNameIn;
this.uuid = animated.getUUID();
}
@Override
public void fromBytes(ByteBuf buf)
{
this.animationName = ByteBufUtils.readUTF8String(buf);
long most = buf.readLong();
long least = buf.readLong();
this.uuid = new UUID(most, least);
}
@Override
public void toBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, this.animationName);
buf.writeLong(this.uuid.getMostSignificantBits());
buf.writeLong(this.uuid.getLeastSignificantBits());
}
public Entity getEntityByUUID(List<Entity> list, UUID uuid)
{
for (Entity e : list)
if (e.getPersistentID().equals(uuid))
return e;
return null;
}
}
| Fix Client crash on server | Fix Client crash on server
| Java | apache-2.0 | Leviathan-Studio/CraftStudioAPI | java | ## Code Before:
package com.leviathanstudio.craftstudio.network;
import java.util.List;
import java.util.UUID;
import com.leviathanstudio.craftstudio.common.animation.IAnimated;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import io.netty.buffer.ByteBuf;
public class CraftStudioBasePacket implements IMessage
{
protected String animationName;
protected UUID uuid;
public CraftStudioBasePacket()
{
}
public CraftStudioBasePacket(String animationNameIn, IAnimated animated)
{
this.animationName = animationNameIn;
this.uuid = animated.getUUID();
}
@Override
public void fromBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, this.animationName);
buf.writeLong(this.uuid.getMostSignificantBits());
buf.writeLong(this.uuid.getLeastSignificantBits());
}
@Override
public void toBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, this.animationName);
long most = buf.readLong();
long least = buf.readLong();
this.uuid = new UUID(most, least);
}
public Entity getEntityByUUID(List<Entity> list, UUID uuid)
{
for (Entity e : list)
if (e.getPersistentID().equals(uuid))
return e;
return null;
}
}
## Instruction:
Fix Client crash on server
## Code After:
package com.leviathanstudio.craftstudio.network;
import java.util.List;
import java.util.UUID;
import com.leviathanstudio.craftstudio.common.animation.IAnimated;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import io.netty.buffer.ByteBuf;
public class CraftStudioBasePacket implements IMessage
{
protected String animationName;
protected UUID uuid;
public CraftStudioBasePacket()
{
}
public CraftStudioBasePacket(String animationNameIn, IAnimated animated)
{
this.animationName = animationNameIn;
this.uuid = animated.getUUID();
}
@Override
public void fromBytes(ByteBuf buf)
{
this.animationName = ByteBufUtils.readUTF8String(buf);
long most = buf.readLong();
long least = buf.readLong();
this.uuid = new UUID(most, least);
}
@Override
public void toBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, this.animationName);
buf.writeLong(this.uuid.getMostSignificantBits());
buf.writeLong(this.uuid.getLeastSignificantBits());
}
public Entity getEntityByUUID(List<Entity> list, UUID uuid)
{
for (Entity e : list)
if (e.getPersistentID().equals(uuid))
return e;
return null;
}
}
| package com.leviathanstudio.craftstudio.network;
import java.util.List;
import java.util.UUID;
import com.leviathanstudio.craftstudio.common.animation.IAnimated;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import io.netty.buffer.ByteBuf;
public class CraftStudioBasePacket implements IMessage
{
protected String animationName;
protected UUID uuid;
public CraftStudioBasePacket()
{
}
public CraftStudioBasePacket(String animationNameIn, IAnimated animated)
{
this.animationName = animationNameIn;
this.uuid = animated.getUUID();
}
@Override
public void fromBytes(ByteBuf buf)
{
- ByteBufUtils.writeUTF8String(buf, this.animationName);
- buf.writeLong(this.uuid.getMostSignificantBits());
- buf.writeLong(this.uuid.getLeastSignificantBits());
+ this.animationName = ByteBufUtils.readUTF8String(buf);
+ long most = buf.readLong();
+ long least = buf.readLong();
+ this.uuid = new UUID(most, least);
}
@Override
public void toBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, this.animationName);
+ buf.writeLong(this.uuid.getMostSignificantBits());
+ buf.writeLong(this.uuid.getLeastSignificantBits());
- long most = buf.readLong();
- long least = buf.readLong();
- this.uuid = new UUID(most, least);
}
public Entity getEntityByUUID(List<Entity> list, UUID uuid)
{
for (Entity e : list)
if (e.getPersistentID().equals(uuid))
return e;
return null;
}
} | 12 | 0.222222 | 6 | 6 |
56c8e069fb8226d004db9254a30c878e3bfd00d3 | packages/ember-intl/app/instance-initializers/ember-intl.js | packages/ember-intl/app/instance-initializers/ember-intl.js | /**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import ENV from '../config/environment';
function filterBy(type) {
return Object.keys(requirejs._eak_seen).filter((key) => {
return key.indexOf(`${ENV.modulePrefix}\/${type}\/`) === 0;
});
}
export function instanceInitializer(instance) {
const container = instance.lookup ? instance : instance.container;
const service = container.lookup('service:intl');
filterBy('cldrs').forEach((key) => {
service.addLocaleData(require(key, null, null, true)['default']);
});
filterBy('translations').forEach((key) => {
const localeSplit = key.split('\/');
const localeName = localeSplit[localeSplit.length - 1];
service.addTranslations(localeName, require(key, null, null, true)['default']);
});
}
export default {
name: 'ember-intl',
initialize: instanceInitializer
}
| /* globals requirejs */
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import ENV from '../config/environment';
import getOwner from 'ember-getowner-polyfill';
function filterBy(type) {
return Object.keys(requirejs._eak_seen).filter((key) => {
return key.indexOf(`${ENV.modulePrefix}\/${type}\/`) === 0;
});
}
export function instanceInitializer(instance) {
const service = getOwner(instance).lookup('service:intl');
filterBy('cldrs').forEach((key) => {
service.addLocaleData(require(key, null, null, true)['default']);
});
filterBy('translations').forEach((key) => {
const localeSplit = key.split('\/');
const localeName = localeSplit[localeSplit.length - 1];
service.addTranslations(localeName, require(key, null, null, true)['default']);
});
}
export default {
name: 'ember-intl',
initialize: instanceInitializer
}
| Use getOwner polyfill in instance initializer | Use getOwner polyfill in instance initializer
| JavaScript | mit | yahoo/ember-intl,ember-intl/ember-intl,jasonmit/ember-intl,null-null-null/ember-intl,yahoo/ember-intl,ember-intl/ember-intl,jasonmit/ember-intl,ember-intl/ember-intl,null-null-null/ember-intl | javascript | ## Code Before:
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import ENV from '../config/environment';
function filterBy(type) {
return Object.keys(requirejs._eak_seen).filter((key) => {
return key.indexOf(`${ENV.modulePrefix}\/${type}\/`) === 0;
});
}
export function instanceInitializer(instance) {
const container = instance.lookup ? instance : instance.container;
const service = container.lookup('service:intl');
filterBy('cldrs').forEach((key) => {
service.addLocaleData(require(key, null, null, true)['default']);
});
filterBy('translations').forEach((key) => {
const localeSplit = key.split('\/');
const localeName = localeSplit[localeSplit.length - 1];
service.addTranslations(localeName, require(key, null, null, true)['default']);
});
}
export default {
name: 'ember-intl',
initialize: instanceInitializer
}
## Instruction:
Use getOwner polyfill in instance initializer
## Code After:
/* globals requirejs */
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import ENV from '../config/environment';
import getOwner from 'ember-getowner-polyfill';
function filterBy(type) {
return Object.keys(requirejs._eak_seen).filter((key) => {
return key.indexOf(`${ENV.modulePrefix}\/${type}\/`) === 0;
});
}
export function instanceInitializer(instance) {
const service = getOwner(instance).lookup('service:intl');
filterBy('cldrs').forEach((key) => {
service.addLocaleData(require(key, null, null, true)['default']);
});
filterBy('translations').forEach((key) => {
const localeSplit = key.split('\/');
const localeName = localeSplit[localeSplit.length - 1];
service.addTranslations(localeName, require(key, null, null, true)['default']);
});
}
export default {
name: 'ember-intl',
initialize: instanceInitializer
}
| + /* globals requirejs */
+
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import ENV from '../config/environment';
+ import getOwner from 'ember-getowner-polyfill';
function filterBy(type) {
return Object.keys(requirejs._eak_seen).filter((key) => {
return key.indexOf(`${ENV.modulePrefix}\/${type}\/`) === 0;
});
}
export function instanceInitializer(instance) {
- const container = instance.lookup ? instance : instance.container;
- const service = container.lookup('service:intl');
? ^^^ ^^
+ const service = getOwner(instance).lookup('service:intl');
? ^^ ^^ ++++++++++
filterBy('cldrs').forEach((key) => {
service.addLocaleData(require(key, null, null, true)['default']);
});
filterBy('translations').forEach((key) => {
const localeSplit = key.split('\/');
const localeName = localeSplit[localeSplit.length - 1];
service.addTranslations(localeName, require(key, null, null, true)['default']);
});
}
export default {
name: 'ember-intl',
initialize: instanceInitializer
} | 6 | 0.1875 | 4 | 2 |
5237cb7f1339eb13b4c01f1c3611448a8f865726 | terms/templatetags/terms.py | terms/templatetags/terms.py |
from django.template import Library
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out
|
from django.template import Library
from django.template.defaultfilters import stringfilter
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
@stringfilter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out
| Make sure the filter arg is a string. | Make sure the filter arg is a string.
| Python | bsd-3-clause | BertrandBordage/django-terms,philippeowagner/django-terms,BertrandBordage/django-terms,philippeowagner/django-terms | python | ## Code Before:
from django.template import Library
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out
## Instruction:
Make sure the filter arg is a string.
## Code After:
from django.template import Library
from django.template.defaultfilters import stringfilter
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
@stringfilter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out
|
from django.template import Library
+ from django.template.defaultfilters import stringfilter
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
+ @stringfilter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out | 2 | 0.166667 | 2 | 0 |
5c9ea2db151545f8dd0a7fecb7ee7860c65ead0e | src/main/java/com/tterrag/blur/config/BlurConfigGui.java | src/main/java/com/tterrag/blur/config/BlurConfigGui.java | package com.tterrag.blur.config;
import javax.annotation.Nonnull;
import com.tterrag.blur.Blur;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.Tessellator;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;
public class BlurConfigGui extends GuiConfig {
public BlurConfigGui(GuiScreen parentScreen) {
super(parentScreen, new ConfigElement(Blur.instance.config.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), Blur.MODID, false, false, Blur.MODID + ".config.title");
}
@Override
public void initGui() {
super.initGui();
this.entryList = new GuiConfigEntries(this, mc) {
@SuppressWarnings({ "unused", "null" })
@Override
protected void drawContainerBackground(@Nonnull Tessellator tessellator) {
if (mc.world == null) {
super.drawContainerBackground(tessellator);
}
}
};
}
@Override
public void drawDefaultBackground() {
drawWorldBackground(0);
}
}
| package com.tterrag.blur.config;
import javax.annotation.Nonnull;
import com.tterrag.blur.Blur;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.Tessellator;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;
public class BlurConfigGui extends GuiConfig {
public BlurConfigGui(GuiScreen parentScreen) {
super(parentScreen, new ConfigElement(Blur.instance.config.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), Blur.MODID, false, false, Blur.MODID + ".config.title");
}
@Override
public void initGui() {
if (this.entryList == null || this.needsRefresh)
{
this.entryList = new GuiConfigEntries(this, mc) {
@SuppressWarnings({ "unused", "null" })
@Override
protected void drawContainerBackground(@Nonnull Tessellator tessellator) {
if (mc.world == null) {
super.drawContainerBackground(tessellator);
}
}
};
this.needsRefresh = false;
}
super.initGui();
}
@Override
public void drawDefaultBackground() {
drawWorldBackground(0);
}
}
| Fix array configs not saving in config GUI | Fix array configs not saving in config GUI | Java | mit | tterrag1098/Blur | java | ## Code Before:
package com.tterrag.blur.config;
import javax.annotation.Nonnull;
import com.tterrag.blur.Blur;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.Tessellator;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;
public class BlurConfigGui extends GuiConfig {
public BlurConfigGui(GuiScreen parentScreen) {
super(parentScreen, new ConfigElement(Blur.instance.config.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), Blur.MODID, false, false, Blur.MODID + ".config.title");
}
@Override
public void initGui() {
super.initGui();
this.entryList = new GuiConfigEntries(this, mc) {
@SuppressWarnings({ "unused", "null" })
@Override
protected void drawContainerBackground(@Nonnull Tessellator tessellator) {
if (mc.world == null) {
super.drawContainerBackground(tessellator);
}
}
};
}
@Override
public void drawDefaultBackground() {
drawWorldBackground(0);
}
}
## Instruction:
Fix array configs not saving in config GUI
## Code After:
package com.tterrag.blur.config;
import javax.annotation.Nonnull;
import com.tterrag.blur.Blur;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.Tessellator;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;
public class BlurConfigGui extends GuiConfig {
public BlurConfigGui(GuiScreen parentScreen) {
super(parentScreen, new ConfigElement(Blur.instance.config.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), Blur.MODID, false, false, Blur.MODID + ".config.title");
}
@Override
public void initGui() {
if (this.entryList == null || this.needsRefresh)
{
this.entryList = new GuiConfigEntries(this, mc) {
@SuppressWarnings({ "unused", "null" })
@Override
protected void drawContainerBackground(@Nonnull Tessellator tessellator) {
if (mc.world == null) {
super.drawContainerBackground(tessellator);
}
}
};
this.needsRefresh = false;
}
super.initGui();
}
@Override
public void drawDefaultBackground() {
drawWorldBackground(0);
}
}
| package com.tterrag.blur.config;
import javax.annotation.Nonnull;
import com.tterrag.blur.Blur;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.Tessellator;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;
public class BlurConfigGui extends GuiConfig {
public BlurConfigGui(GuiScreen parentScreen) {
super(parentScreen, new ConfigElement(Blur.instance.config.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), Blur.MODID, false, false, Blur.MODID + ".config.title");
}
@Override
public void initGui() {
+ if (this.entryList == null || this.needsRefresh)
+ {
+ this.entryList = new GuiConfigEntries(this, mc) {
+ @SuppressWarnings({ "unused", "null" })
+ @Override
+ protected void drawContainerBackground(@Nonnull Tessellator tessellator) {
+ if (mc.world == null) {
+ super.drawContainerBackground(tessellator);
+ }
+ }
+ };
+ this.needsRefresh = false;
+ }
super.initGui();
- this.entryList = new GuiConfigEntries(this, mc) {
- @SuppressWarnings({ "unused", "null" })
- @Override
- protected void drawContainerBackground(@Nonnull Tessellator tessellator) {
- if (mc.world == null) {
- super.drawContainerBackground(tessellator);
- }
- }
- };
}
@Override
public void drawDefaultBackground() {
drawWorldBackground(0);
}
} | 22 | 0.578947 | 13 | 9 |
76137d2c057e97296e3576a70dedbf5324917cbb | lib/views/general/_frontpage_intro_sentence.html.erb | lib/views/general/_frontpage_intro_sentence.html.erb | <h2>
Your <strong>Right to Know</strong>
</h2>
<p>Every citizen has the right to access information held by public bodies. <strong>By law, they have to respond</strong>.</p>
<p><a href="<%= help_about_url %>">Find out more about the Official Information Act.</a></p>
| <h2>
Your <strong>Right to Know</strong>
</h2>
<p>Every citizen has the right to access information held by public bodies. <strong>By law, they have to respond</strong>.</p>
<p><%= link_to "Find out more about the Official Information Act.", help_about_path %></p>
| Use more idiomatic link_to helper | Use more idiomatic link_to helper
| HTML+ERB | mit | nzherald/fyi-theme,olineham/morebetter-theme,nzherald/fyi-theme,nzherald/fyi-theme,olineham/morebetter-theme,olineham/morebetter-theme | html+erb | ## Code Before:
<h2>
Your <strong>Right to Know</strong>
</h2>
<p>Every citizen has the right to access information held by public bodies. <strong>By law, they have to respond</strong>.</p>
<p><a href="<%= help_about_url %>">Find out more about the Official Information Act.</a></p>
## Instruction:
Use more idiomatic link_to helper
## Code After:
<h2>
Your <strong>Right to Know</strong>
</h2>
<p>Every citizen has the right to access information held by public bodies. <strong>By law, they have to respond</strong>.</p>
<p><%= link_to "Find out more about the Official Information Act.", help_about_path %></p>
| <h2>
Your <strong>Right to Know</strong>
</h2>
<p>Every citizen has the right to access information held by public bodies. <strong>By law, they have to respond</strong>.</p>
- <p><a href="<%= help_about_url %>">Find out more about the Official Information Act.</a></p>
+ <p><%= link_to "Find out more about the Official Information Act.", help_about_path %></p> | 2 | 0.4 | 1 | 1 |
23b017ef07aa54ea5ef97fdb09226395ff6d5762 | gem/templates/springster/surveys/surveys_list.html | gem/templates/springster/surveys/surveys_list.html | {% load wagtailcore_tags i18n personalise_extra %}
{% block content %}
{% filter_surveys_by_segments surveys request as filtered_surveys %}
{% if filtered_surveys %}
{% if user.is_authenticated and user.is_active or request.is_preview or self.allow_anonymous_submissions %}
<div class="surveys surveys--call-to-action">
{% for survey in filtered_surveys %}
<div class="identity-image identity-image--survey"></div>
{% include "patterns/basics/headings/sp_variations/heading.html" with type="component" htmltag="h1" title=survey.title %}
{% include "patterns/basics/headings/sp_variations/heading.html" with type="subheading" htmltag="h4" title=survey.intro %}
{% trans "Take Survey" as buttontext %}
{% pageurl survey as the_url %}
{% include "patterns/basics/buttons/sp_variations/button.html" with type="primary" hyperlink=the_url text=buttontext %}
{% endfor %}
</div>
{% else %}
{% include "patterns/components/banners/join-banner.html" %}
{% endif %}
{% endif %}
{% endblock %}
| {% load wagtailcore_tags i18n personalise_extras %}
{% block content %}
{% filter_surveys_by_segments surveys request as filtered_surveys %}
{% if filtered_surveys %}
{% for survey in filtered_surveys %}
{% if user.is_authenticated and user.is_active or request.is_preview or survey.molo_survey_page.allow_anonymous_submissions %}
<div class="surveys surveys--call-to-action">
<div class="identity-image identity-image--survey"></div>
{% include "patterns/basics/headings/sp_variations/heading.html" with type="component" htmltag="h1" title=survey.title %}
{% include "patterns/basics/headings/sp_variations/heading.html" with type="subheading" htmltag="h4" title=survey.intro %}
{% trans "Take Survey" as buttontext %}
{% pageurl survey as the_url %}
{% include "patterns/basics/buttons/sp_variations/button.html" with type="primary" hyperlink=the_url text=buttontext %}
</div>
{% else %}
{% include "patterns/components/banners/join-banner.html" %}
{% endif %}
{% endfor %}
{% endif %}
{% endblock %}
| Move the for loop above if statement | Move the for loop above if statement
| HTML | bsd-2-clause | praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem | html | ## Code Before:
{% load wagtailcore_tags i18n personalise_extra %}
{% block content %}
{% filter_surveys_by_segments surveys request as filtered_surveys %}
{% if filtered_surveys %}
{% if user.is_authenticated and user.is_active or request.is_preview or self.allow_anonymous_submissions %}
<div class="surveys surveys--call-to-action">
{% for survey in filtered_surveys %}
<div class="identity-image identity-image--survey"></div>
{% include "patterns/basics/headings/sp_variations/heading.html" with type="component" htmltag="h1" title=survey.title %}
{% include "patterns/basics/headings/sp_variations/heading.html" with type="subheading" htmltag="h4" title=survey.intro %}
{% trans "Take Survey" as buttontext %}
{% pageurl survey as the_url %}
{% include "patterns/basics/buttons/sp_variations/button.html" with type="primary" hyperlink=the_url text=buttontext %}
{% endfor %}
</div>
{% else %}
{% include "patterns/components/banners/join-banner.html" %}
{% endif %}
{% endif %}
{% endblock %}
## Instruction:
Move the for loop above if statement
## Code After:
{% load wagtailcore_tags i18n personalise_extras %}
{% block content %}
{% filter_surveys_by_segments surveys request as filtered_surveys %}
{% if filtered_surveys %}
{% for survey in filtered_surveys %}
{% if user.is_authenticated and user.is_active or request.is_preview or survey.molo_survey_page.allow_anonymous_submissions %}
<div class="surveys surveys--call-to-action">
<div class="identity-image identity-image--survey"></div>
{% include "patterns/basics/headings/sp_variations/heading.html" with type="component" htmltag="h1" title=survey.title %}
{% include "patterns/basics/headings/sp_variations/heading.html" with type="subheading" htmltag="h4" title=survey.intro %}
{% trans "Take Survey" as buttontext %}
{% pageurl survey as the_url %}
{% include "patterns/basics/buttons/sp_variations/button.html" with type="primary" hyperlink=the_url text=buttontext %}
</div>
{% else %}
{% include "patterns/components/banners/join-banner.html" %}
{% endif %}
{% endfor %}
{% endif %}
{% endblock %}
| - {% load wagtailcore_tags i18n personalise_extra %}
+ {% load wagtailcore_tags i18n personalise_extras %}
? +
{% block content %}
{% filter_surveys_by_segments surveys request as filtered_surveys %}
- {% if filtered_surveys %}
+ {% if filtered_surveys %}
? +
+ {% for survey in filtered_surveys %}
- {% if user.is_authenticated and user.is_active or request.is_preview or self.allow_anonymous_submissions %}
? ^
+ {% if user.is_authenticated and user.is_active or request.is_preview or survey.molo_survey_page.allow_anonymous_submissions %}
? ++ +++ ++++ ^^^^^^^^^^^^^
- <div class="surveys surveys--call-to-action">
+ <div class="surveys surveys--call-to-action">
? ++
- {% for survey in filtered_surveys %}
- <div class="identity-image identity-image--survey"></div>
? ^^^^
+ <div class="identity-image identity-image--survey"></div>
? ^^^^
- {% include "patterns/basics/headings/sp_variations/heading.html" with type="component" htmltag="h1" title=survey.title %}
? ^^^^
+ {% include "patterns/basics/headings/sp_variations/heading.html" with type="component" htmltag="h1" title=survey.title %}
? ^^^^
-
- {% include "patterns/basics/headings/sp_variations/heading.html" with type="subheading" htmltag="h4" title=survey.intro %}
? ^^^^
+ {% include "patterns/basics/headings/sp_variations/heading.html" with type="subheading" htmltag="h4" title=survey.intro %}
? ^^^^
- {% trans "Take Survey" as buttontext %}
? ^^^^
+ {% trans "Take Survey" as buttontext %}
? ^^^^
- {% pageurl survey as the_url %}
? ^^^^
+ {% pageurl survey as the_url %}
? ^^^^
- {% include "patterns/basics/buttons/sp_variations/button.html" with type="primary" hyperlink=the_url text=buttontext %}
? ^^^^
+ {% include "patterns/basics/buttons/sp_variations/button.html" with type="primary" hyperlink=the_url text=buttontext %}
? ^^^^
- {% endfor %}
- </div>
+ </div>
? ++
- {% else %}
+ {% else %}
? ++
- {% include "patterns/components/banners/join-banner.html" %}
? ^^
+ {% include "patterns/components/banners/join-banner.html" %}
? ^^^
+ {% endif %}
+ {% endfor %}
- {% endif %}
+ {% endif %}
? +
- {% endif %}
{% endblock %} | 35 | 1.666667 | 17 | 18 |
500c81ac11eb32552acac1314fd92f8418aba54a | app/models/about_page.rb | app/models/about_page.rb | class AboutPage < ActiveRecord::Base
include Searchable
attr_accessible :body, :name, :summary, :read_more_link_text
belongs_to :subject, polymorphic: true
validates :name, presence: true, uniqueness: true
validates :read_more_link_text, presence: true
validates :summary, presence: true
validates :body, presence: true
searchable title: :name,
link: :search_link,
content: :indexable_content,
description: :summary
def search_link
Whitehall.url_maker.topical_event_about_pages_path(subject.slug)
end
def indexable_content
Govspeak::Document.new(body).to_text
end
end
| class AboutPage < ActiveRecord::Base
include Searchable
attr_accessible :body, :name, :summary, :read_more_link_text
belongs_to :subject, polymorphic: true
validates :name, presence: true, uniqueness: true, length: { maximum: 255 }
validates :read_more_link_text, presence: true, length: { maximum: 255 }
validates :summary, presence: true, length: { maximum: (16.megabytes - 1) }
validates :body, presence: true, length: { maximum: (16.megabytes - 1) }
searchable title: :name,
link: :search_link,
content: :indexable_content,
description: :summary
def search_link
Whitehall.url_maker.topical_event_about_pages_path(subject.slug)
end
def indexable_content
Govspeak::Document.new(body).to_text
end
end
| Add max field length validations for AboutPage | Add max field length validations for AboutPage
| Ruby | mit | robinwhittleton/whitehall,alphagov/whitehall,askl56/whitehall,askl56/whitehall,alphagov/whitehall,YOTOV-LIMITED/whitehall,alphagov/whitehall,alphagov/whitehall,robinwhittleton/whitehall,hotvulcan/whitehall,robinwhittleton/whitehall,YOTOV-LIMITED/whitehall,ggoral/whitehall,hotvulcan/whitehall,askl56/whitehall,hotvulcan/whitehall,robinwhittleton/whitehall,hotvulcan/whitehall,askl56/whitehall,ggoral/whitehall,ggoral/whitehall,YOTOV-LIMITED/whitehall,ggoral/whitehall,YOTOV-LIMITED/whitehall | ruby | ## Code Before:
class AboutPage < ActiveRecord::Base
include Searchable
attr_accessible :body, :name, :summary, :read_more_link_text
belongs_to :subject, polymorphic: true
validates :name, presence: true, uniqueness: true
validates :read_more_link_text, presence: true
validates :summary, presence: true
validates :body, presence: true
searchable title: :name,
link: :search_link,
content: :indexable_content,
description: :summary
def search_link
Whitehall.url_maker.topical_event_about_pages_path(subject.slug)
end
def indexable_content
Govspeak::Document.new(body).to_text
end
end
## Instruction:
Add max field length validations for AboutPage
## Code After:
class AboutPage < ActiveRecord::Base
include Searchable
attr_accessible :body, :name, :summary, :read_more_link_text
belongs_to :subject, polymorphic: true
validates :name, presence: true, uniqueness: true, length: { maximum: 255 }
validates :read_more_link_text, presence: true, length: { maximum: 255 }
validates :summary, presence: true, length: { maximum: (16.megabytes - 1) }
validates :body, presence: true, length: { maximum: (16.megabytes - 1) }
searchable title: :name,
link: :search_link,
content: :indexable_content,
description: :summary
def search_link
Whitehall.url_maker.topical_event_about_pages_path(subject.slug)
end
def indexable_content
Govspeak::Document.new(body).to_text
end
end
| class AboutPage < ActiveRecord::Base
include Searchable
attr_accessible :body, :name, :summary, :read_more_link_text
belongs_to :subject, polymorphic: true
- validates :name, presence: true, uniqueness: true
+ validates :name, presence: true, uniqueness: true, length: { maximum: 255 }
? ++++++++++++++++++++++++++
- validates :read_more_link_text, presence: true
+ validates :read_more_link_text, presence: true, length: { maximum: 255 }
? ++++++++++++++++++++++++++
- validates :summary, presence: true
- validates :body, presence: true
+ validates :summary, presence: true, length: { maximum: (16.megabytes - 1) }
+ validates :body, presence: true, length: { maximum: (16.megabytes - 1) }
searchable title: :name,
link: :search_link,
content: :indexable_content,
description: :summary
def search_link
Whitehall.url_maker.topical_event_about_pages_path(subject.slug)
end
def indexable_content
Govspeak::Document.new(body).to_text
end
end | 8 | 0.32 | 4 | 4 |
a48312e4ec389e9d699fa8eb06b60983e0198f19 | src/misc/camera.js | src/misc/camera.js | import { imageDataFromVideo } from './image-data.js'
import { hasFired } from './promisify.js'
class Camera {
constructor (videoEl, stream) {
this.videoEl = videoEl
this.stream = stream
}
stop () {
this.stream.getTracks().forEach(
track => track.stop()
)
}
captureFrame () {
return imageDataFromVideo(this.videoEl)
}
}
export default async function (constraints, videoEl) {
if (!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) {
throw new Error('WebRTC API not supported in this browser')
}
const stream = await navigator.mediaDevices.getUserMedia(constraints)
const streamLoaded = hasFired(videoEl, 'loadeddata', 'error')
if (videoEl.srcObject !== undefined) {
videoEl.srcObject = stream
} else if (videoEl.mozSrcObject !== undefined) {
videoEl.mozSrcObject = stream
} else if (window.URL.createObjectURL) {
videoEl.src = window.URL.createObjectURL(stream)
} else if (window.webkitURL) {
videoEl.src = window.webkitURL.createObjectURL(stream)
} else {
videoEl.src = stream
}
videoEl.playsInline = true
videoEl.play() // firefox does not emit `loadeddata` if video not playing
await streamLoaded
return new Camera(videoEl, stream)
}
| import { imageDataFromVideo } from './image-data.js'
import { hasFired } from './promisify.js'
class Camera {
constructor (videoEl, stream) {
this.videoEl = videoEl
this.stream = stream
}
stop () {
this.stream.getTracks().forEach(
track => track.stop()
)
}
captureFrame () {
return imageDataFromVideo(this.videoEl)
}
}
export default async function (constraints, videoEl) {
if (!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) {
throw new Error('WebRTC API not supported in this browser')
}
const stream = await navigator.mediaDevices.getUserMedia(constraints)
const streamLoaded = hasFired(videoEl, 'loadeddata', 'error')
if (videoEl.srcObject !== undefined) {
videoEl.srcObject = stream
} else if (videoEl.mozSrcObject !== undefined) {
videoEl.mozSrcObject = stream
} else if (window.URL.createObjectURL) {
videoEl.src = window.URL.createObjectURL(stream)
} else if (window.webkitURL) {
videoEl.src = window.webkitURL.createObjectURL(stream)
} else {
videoEl.src = stream
}
await streamLoaded
return new Camera(videoEl, stream)
}
| Remove programmatically set <video> attributes | Remove programmatically set <video> attributes
Attributes added as HTML in 1a864376aab054ef7a90be41eeb50c28a2e43820
| JavaScript | mit | gruhn/vue-qrcode-reader | javascript | ## Code Before:
import { imageDataFromVideo } from './image-data.js'
import { hasFired } from './promisify.js'
class Camera {
constructor (videoEl, stream) {
this.videoEl = videoEl
this.stream = stream
}
stop () {
this.stream.getTracks().forEach(
track => track.stop()
)
}
captureFrame () {
return imageDataFromVideo(this.videoEl)
}
}
export default async function (constraints, videoEl) {
if (!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) {
throw new Error('WebRTC API not supported in this browser')
}
const stream = await navigator.mediaDevices.getUserMedia(constraints)
const streamLoaded = hasFired(videoEl, 'loadeddata', 'error')
if (videoEl.srcObject !== undefined) {
videoEl.srcObject = stream
} else if (videoEl.mozSrcObject !== undefined) {
videoEl.mozSrcObject = stream
} else if (window.URL.createObjectURL) {
videoEl.src = window.URL.createObjectURL(stream)
} else if (window.webkitURL) {
videoEl.src = window.webkitURL.createObjectURL(stream)
} else {
videoEl.src = stream
}
videoEl.playsInline = true
videoEl.play() // firefox does not emit `loadeddata` if video not playing
await streamLoaded
return new Camera(videoEl, stream)
}
## Instruction:
Remove programmatically set <video> attributes
Attributes added as HTML in 1a864376aab054ef7a90be41eeb50c28a2e43820
## Code After:
import { imageDataFromVideo } from './image-data.js'
import { hasFired } from './promisify.js'
class Camera {
constructor (videoEl, stream) {
this.videoEl = videoEl
this.stream = stream
}
stop () {
this.stream.getTracks().forEach(
track => track.stop()
)
}
captureFrame () {
return imageDataFromVideo(this.videoEl)
}
}
export default async function (constraints, videoEl) {
if (!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) {
throw new Error('WebRTC API not supported in this browser')
}
const stream = await navigator.mediaDevices.getUserMedia(constraints)
const streamLoaded = hasFired(videoEl, 'loadeddata', 'error')
if (videoEl.srcObject !== undefined) {
videoEl.srcObject = stream
} else if (videoEl.mozSrcObject !== undefined) {
videoEl.mozSrcObject = stream
} else if (window.URL.createObjectURL) {
videoEl.src = window.URL.createObjectURL(stream)
} else if (window.webkitURL) {
videoEl.src = window.webkitURL.createObjectURL(stream)
} else {
videoEl.src = stream
}
await streamLoaded
return new Camera(videoEl, stream)
}
| import { imageDataFromVideo } from './image-data.js'
import { hasFired } from './promisify.js'
class Camera {
constructor (videoEl, stream) {
this.videoEl = videoEl
this.stream = stream
}
stop () {
this.stream.getTracks().forEach(
track => track.stop()
)
}
captureFrame () {
return imageDataFromVideo(this.videoEl)
}
}
export default async function (constraints, videoEl) {
if (!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) {
throw new Error('WebRTC API not supported in this browser')
}
const stream = await navigator.mediaDevices.getUserMedia(constraints)
const streamLoaded = hasFired(videoEl, 'loadeddata', 'error')
if (videoEl.srcObject !== undefined) {
videoEl.srcObject = stream
} else if (videoEl.mozSrcObject !== undefined) {
videoEl.mozSrcObject = stream
} else if (window.URL.createObjectURL) {
videoEl.src = window.URL.createObjectURL(stream)
} else if (window.webkitURL) {
videoEl.src = window.webkitURL.createObjectURL(stream)
} else {
videoEl.src = stream
}
- videoEl.playsInline = true
- videoEl.play() // firefox does not emit `loadeddata` if video not playing
-
await streamLoaded
return new Camera(videoEl, stream)
} | 3 | 0.061224 | 0 | 3 |
103bd257d6132c88db1e8b70796e13cbbecbe5a5 | guess.rs | guess.rs | use std::rand::random;
mod guess {
pub fn guessed_correctly(guess: uint, machine: uint) -> bool {
guess == machine
}
}
fn main() {
let random_value = random::<uint>() % 10u;
let mut guess = 0u;
guess += 1;
println!("{}", random_value);
println!("{}", guess::guessed_correctly(guess, random_value));
}
| use std::io;
use std::rand::random;
mod guess {
pub fn guessed_correctly(guess: uint, machine: uint) -> bool {
guess == machine
}
}
#[cfg(not(target_os = "linux"))]
fn test_os() {
println!("You are not running Linux!")
}
fn main() {
test_os();
let random_value = random::<uint>() % 10u;
let mut guess = 0u;
for line in io::stdin().lines() {
// guess = line.unwrap().to_int();
println!("{}", line.unwrap());
}
println!("{}", random_value);
println!("{}", guess);
println!("{}", guess::guessed_correctly(guess, random_value));
}
| Add OS checking using cfg | Add OS checking using cfg
| Rust | bsd-2-clause | ambidextrousTx/ToyRustPrograms | rust | ## Code Before:
use std::rand::random;
mod guess {
pub fn guessed_correctly(guess: uint, machine: uint) -> bool {
guess == machine
}
}
fn main() {
let random_value = random::<uint>() % 10u;
let mut guess = 0u;
guess += 1;
println!("{}", random_value);
println!("{}", guess::guessed_correctly(guess, random_value));
}
## Instruction:
Add OS checking using cfg
## Code After:
use std::io;
use std::rand::random;
mod guess {
pub fn guessed_correctly(guess: uint, machine: uint) -> bool {
guess == machine
}
}
#[cfg(not(target_os = "linux"))]
fn test_os() {
println!("You are not running Linux!")
}
fn main() {
test_os();
let random_value = random::<uint>() % 10u;
let mut guess = 0u;
for line in io::stdin().lines() {
// guess = line.unwrap().to_int();
println!("{}", line.unwrap());
}
println!("{}", random_value);
println!("{}", guess);
println!("{}", guess::guessed_correctly(guess, random_value));
}
| + use std::io;
use std::rand::random;
mod guess {
pub fn guessed_correctly(guess: uint, machine: uint) -> bool {
guess == machine
}
}
+ #[cfg(not(target_os = "linux"))]
+ fn test_os() {
+ println!("You are not running Linux!")
+ }
+
fn main() {
+ test_os();
let random_value = random::<uint>() % 10u;
let mut guess = 0u;
- guess += 1;
+ for line in io::stdin().lines() {
+ // guess = line.unwrap().to_int();
+ println!("{}", line.unwrap());
+ }
+
println!("{}", random_value);
+ println!("{}", guess);
println!("{}", guess::guessed_correctly(guess, random_value));
} | 14 | 0.875 | 13 | 1 |
cdc8ba7e702f4fb61ef1141329ca63dfa69e1da1 | tests/posix.cpp | tests/posix.cpp | /* Copyright (c) 2010 David Bender assigned to Benegon Enterprises LLC
* See the file LICENSE for full license information. */
#include <errno.h>
#include "posix.hh"
FD_Reader::FD_Reader(int fd) throw()
: _fd(fd), _errno(0)
{
}
FD_Reader::~FD_Reader() throw(){
/* Assume file is read only; don't really care about successful close. */
if(-1 != _fd)
close(_fd);
}
int FD_Reader::Read(uint8_t* buff, unsigned len) throw(){
/* If file closed just return 0. */
if(-1 == _fd)
return 0;
/* BLOCKING read until data comes or unrecoverable error. */
while(true){
int ret = read(_fd, buff, len);
if(ret < 0){
if(EINTR == errno)
continue;
_errno = errno;
close(_fd);
_fd = -1;
}
else if(0 == ret){
close(_fd);
_fd = -1;
}
return ret;
}
}
| /* Copyright (c) 2010 David Bender assigned to Benegon Enterprises LLC
* See the file LICENSE for full license information. */
#include <errno.h>
#include <unistd.h>
#include "posix.hh"
FD_Reader::FD_Reader(int fd) throw()
: _fd(fd), _errno(0)
{
}
FD_Reader::~FD_Reader() throw(){
/* Assume file is read only; don't really care about successful close. */
if(-1 != _fd)
close(_fd);
}
int FD_Reader::Read(uint8_t* buff, unsigned len) throw(){
/* If file closed just return 0. */
if(-1 == _fd)
return 0;
/* BLOCKING read until data comes or unrecoverable error. */
while(true){
int ret = read(_fd, buff, len);
if(ret < 0){
if(EINTR == errno)
continue;
_errno = errno;
close(_fd);
_fd = -1;
}
else if(0 == ret){
close(_fd);
_fd = -1;
}
return ret;
}
}
| Add include line that may be required on some platforms | Add include line that may be required on some platforms
| C++ | mit | codehero/benejson,codehero/benejson,codehero/benejson,codehero/benejson | c++ | ## Code Before:
/* Copyright (c) 2010 David Bender assigned to Benegon Enterprises LLC
* See the file LICENSE for full license information. */
#include <errno.h>
#include "posix.hh"
FD_Reader::FD_Reader(int fd) throw()
: _fd(fd), _errno(0)
{
}
FD_Reader::~FD_Reader() throw(){
/* Assume file is read only; don't really care about successful close. */
if(-1 != _fd)
close(_fd);
}
int FD_Reader::Read(uint8_t* buff, unsigned len) throw(){
/* If file closed just return 0. */
if(-1 == _fd)
return 0;
/* BLOCKING read until data comes or unrecoverable error. */
while(true){
int ret = read(_fd, buff, len);
if(ret < 0){
if(EINTR == errno)
continue;
_errno = errno;
close(_fd);
_fd = -1;
}
else if(0 == ret){
close(_fd);
_fd = -1;
}
return ret;
}
}
## Instruction:
Add include line that may be required on some platforms
## Code After:
/* Copyright (c) 2010 David Bender assigned to Benegon Enterprises LLC
* See the file LICENSE for full license information. */
#include <errno.h>
#include <unistd.h>
#include "posix.hh"
FD_Reader::FD_Reader(int fd) throw()
: _fd(fd), _errno(0)
{
}
FD_Reader::~FD_Reader() throw(){
/* Assume file is read only; don't really care about successful close. */
if(-1 != _fd)
close(_fd);
}
int FD_Reader::Read(uint8_t* buff, unsigned len) throw(){
/* If file closed just return 0. */
if(-1 == _fd)
return 0;
/* BLOCKING read until data comes or unrecoverable error. */
while(true){
int ret = read(_fd, buff, len);
if(ret < 0){
if(EINTR == errno)
continue;
_errno = errno;
close(_fd);
_fd = -1;
}
else if(0 == ret){
close(_fd);
_fd = -1;
}
return ret;
}
}
| /* Copyright (c) 2010 David Bender assigned to Benegon Enterprises LLC
* See the file LICENSE for full license information. */
#include <errno.h>
+ #include <unistd.h>
#include "posix.hh"
FD_Reader::FD_Reader(int fd) throw()
: _fd(fd), _errno(0)
{
}
FD_Reader::~FD_Reader() throw(){
/* Assume file is read only; don't really care about successful close. */
if(-1 != _fd)
close(_fd);
}
int FD_Reader::Read(uint8_t* buff, unsigned len) throw(){
/* If file closed just return 0. */
if(-1 == _fd)
return 0;
/* BLOCKING read until data comes or unrecoverable error. */
while(true){
int ret = read(_fd, buff, len);
if(ret < 0){
if(EINTR == errno)
continue;
_errno = errno;
close(_fd);
_fd = -1;
}
else if(0 == ret){
close(_fd);
_fd = -1;
}
return ret;
}
} | 1 | 0.025641 | 1 | 0 |
87da243720352ee26cfeb89fc4241aecd1119bc9 | spec/levenshtein_spec.rb | spec/levenshtein_spec.rb | require 'spec_helper'
describe Levenshtein do
before(:each) do
@fixtures = [
["hello", "hello", 0],
["hello", "helo", 1],
["hello", "jello", 1],
["hello", "helol", 1],
["hello", "hellol", 1],
["hello", "heloll", 2],
["hello", "cheese", 4],
["hello", "saint", 5],
["hello", "", 5],
]
end
it "should calculate correct distances" do
@fixtures.each do |w1, w2, d|
Levenshtein.distance(w1, w2).should == d
Levenshtein.distance(w2, w1).should == d
end
end
end
| require 'spec_helper'
describe Levenshtein do
fixtures = [
["hello", "hello", 0],
["hello", "helo", 1],
["hello", "jello", 1],
["hello", "helol", 1],
["hello", "hellol", 1],
["hello", "heloll", 2],
["hello", "cheese", 4],
["hello", "saint", 5],
["hello", "", 5],
]
fixtures.each do |w1, w2, d|
it "should calculate a distance of #{d} between #{w1} and #{w2}" do
Levenshtein.distance(w1, w2).should == d
Levenshtein.distance(w2, w1).should == d
end
end
end
| Update each spec to be self-contained. | Update each spec to be self-contained.
| Ruby | bsd-2-clause | dbalatero/levenshtein-ffi,dbalatero/levenshtein-ffi,bkeepers/levenshtein-ffi,bkeepers/levenshtein-ffi | ruby | ## Code Before:
require 'spec_helper'
describe Levenshtein do
before(:each) do
@fixtures = [
["hello", "hello", 0],
["hello", "helo", 1],
["hello", "jello", 1],
["hello", "helol", 1],
["hello", "hellol", 1],
["hello", "heloll", 2],
["hello", "cheese", 4],
["hello", "saint", 5],
["hello", "", 5],
]
end
it "should calculate correct distances" do
@fixtures.each do |w1, w2, d|
Levenshtein.distance(w1, w2).should == d
Levenshtein.distance(w2, w1).should == d
end
end
end
## Instruction:
Update each spec to be self-contained.
## Code After:
require 'spec_helper'
describe Levenshtein do
fixtures = [
["hello", "hello", 0],
["hello", "helo", 1],
["hello", "jello", 1],
["hello", "helol", 1],
["hello", "hellol", 1],
["hello", "heloll", 2],
["hello", "cheese", 4],
["hello", "saint", 5],
["hello", "", 5],
]
fixtures.each do |w1, w2, d|
it "should calculate a distance of #{d} between #{w1} and #{w2}" do
Levenshtein.distance(w1, w2).should == d
Levenshtein.distance(w2, w1).should == d
end
end
end
| require 'spec_helper'
describe Levenshtein do
- before(:each) do
- @fixtures = [
? ---
+ fixtures = [
- ["hello", "hello", 0],
? --
+ ["hello", "hello", 0],
- ["hello", "helo", 1],
? --
+ ["hello", "helo", 1],
- ["hello", "jello", 1],
? --
+ ["hello", "jello", 1],
- ["hello", "helol", 1],
? --
+ ["hello", "helol", 1],
- ["hello", "hellol", 1],
? --
+ ["hello", "hellol", 1],
- ["hello", "heloll", 2],
? --
+ ["hello", "heloll", 2],
- ["hello", "cheese", 4],
? --
+ ["hello", "cheese", 4],
- ["hello", "saint", 5],
? --
+ ["hello", "saint", 5],
- ["hello", "", 5],
? --
+ ["hello", "", 5],
- ]
? --
+ ]
- end
- it "should calculate correct distances" do
- @fixtures.each do |w1, w2, d|
? ---
+ fixtures.each do |w1, w2, d|
+ it "should calculate a distance of #{d} between #{w1} and #{w2}" do
Levenshtein.distance(w1, w2).should == d
Levenshtein.distance(w2, w1).should == d
end
end
end | 28 | 1.166667 | 13 | 15 |
77704e80a32fbb2f4c9533778565a92dbb346ab6 | highlander/highlander.py | highlander/highlander.py | from functools import wraps
from logging import getLogger
from os import getcwd, unlink
from os.path import join, realpath, isfile
from psutil import Process
logger = getLogger(__name__)
def one(f):
@wraps(f)
def decorator():
pid_file = realpath(join(getcwd(), '.pid'))
if _is_running(pid_file):
exit(0)
_set_running(pid_file)
try:
f()
finally:
unlink(pid_file)
return decorator
def _is_running():
pass
def _read_pid_file(filename):
with open(filename, 'r') as f:
pid, create_time = f.read().split(',')
return Process(int(pid))
def _set_running(filename):
p = Process()
with open(filename, 'w') as f:
f.write('{},{}'.format(p.pid, p.create_time()))
def _unlink_pid_file(f):
unlink(f)
| from functools import wraps
from logging import getLogger
from os import getcwd, unlink
from os.path import join, realpath, isfile
from psutil import Process
logger = getLogger(__name__)
def one(f):
@wraps(f)
def decorator():
pid_file = realpath(join(getcwd(), '.pid'))
if _is_running(pid_file):
exit(0)
_set_running(pid_file)
try:
f()
finally:
unlink(pid_file)
return decorator
def _is_running():
pass
def _read_pid_file(filename):
if not isfile(str(filename)):
return None
with open(filename, 'r') as f:
pid, create_time = f.read().split(',')
return Process(int(pid))
def _set_running(filename):
p = Process()
with open(filename, 'w') as f:
f.write('{},{}'.format(p.pid, p.create_time()))
def _unlink_pid_file(f):
unlink(f)
| Make sure filename is a string. | Make sure filename is a string.
| Python | mit | chriscannon/highlander | python | ## Code Before:
from functools import wraps
from logging import getLogger
from os import getcwd, unlink
from os.path import join, realpath, isfile
from psutil import Process
logger = getLogger(__name__)
def one(f):
@wraps(f)
def decorator():
pid_file = realpath(join(getcwd(), '.pid'))
if _is_running(pid_file):
exit(0)
_set_running(pid_file)
try:
f()
finally:
unlink(pid_file)
return decorator
def _is_running():
pass
def _read_pid_file(filename):
with open(filename, 'r') as f:
pid, create_time = f.read().split(',')
return Process(int(pid))
def _set_running(filename):
p = Process()
with open(filename, 'w') as f:
f.write('{},{}'.format(p.pid, p.create_time()))
def _unlink_pid_file(f):
unlink(f)
## Instruction:
Make sure filename is a string.
## Code After:
from functools import wraps
from logging import getLogger
from os import getcwd, unlink
from os.path import join, realpath, isfile
from psutil import Process
logger = getLogger(__name__)
def one(f):
@wraps(f)
def decorator():
pid_file = realpath(join(getcwd(), '.pid'))
if _is_running(pid_file):
exit(0)
_set_running(pid_file)
try:
f()
finally:
unlink(pid_file)
return decorator
def _is_running():
pass
def _read_pid_file(filename):
if not isfile(str(filename)):
return None
with open(filename, 'r') as f:
pid, create_time = f.read().split(',')
return Process(int(pid))
def _set_running(filename):
p = Process()
with open(filename, 'w') as f:
f.write('{},{}'.format(p.pid, p.create_time()))
def _unlink_pid_file(f):
unlink(f)
| from functools import wraps
from logging import getLogger
from os import getcwd, unlink
from os.path import join, realpath, isfile
from psutil import Process
logger = getLogger(__name__)
def one(f):
@wraps(f)
def decorator():
pid_file = realpath(join(getcwd(), '.pid'))
if _is_running(pid_file):
exit(0)
_set_running(pid_file)
try:
f()
finally:
unlink(pid_file)
return decorator
def _is_running():
pass
def _read_pid_file(filename):
+ if not isfile(str(filename)):
+ return None
+
with open(filename, 'r') as f:
pid, create_time = f.read().split(',')
return Process(int(pid))
def _set_running(filename):
p = Process()
with open(filename, 'w') as f:
f.write('{},{}'.format(p.pid, p.create_time()))
def _unlink_pid_file(f):
unlink(f) | 3 | 0.068182 | 3 | 0 |
f2a38094222b15580170ef4c486a32d6e620a628 | src/future/either.rs | src/future/either.rs | use {Future, Poll};
/// Combines two different futures yielding the same item and error
/// types into a single type.
pub enum Either<A, B> {
/// First branch of the type
A(A),
/// Second branch of the type
B(B),
}
impl<A, B, Item, Error> Future for Either<A, B>
where A: Future<Item = Item, Error = Error>,
B: Future<Item = Item, Error = Error>
{
type Item = Item;
type Error = Error;
fn poll(&mut self) -> Poll<Item, Error> {
match *self {
Either::A(ref mut a) => a.poll(),
Either::B(ref mut b) => b.poll(),
}
}
}
| use {Future, Poll};
/// Combines two different futures yielding the same item and error
/// types into a single type.
pub enum Either<A, B> {
/// First branch of the type
A(A),
/// Second branch of the type
B(B),
}
impl<A, B> Future for Either<A, B>
where A: Future,
B: Future<Item = A::Item, Error = A::Error>
{
type Item = A::Item;
type Error = A::Error;
fn poll(&mut self) -> Poll<A::Item, A::Error> {
match *self {
Either::A(ref mut a) => a.poll(),
Either::B(ref mut b) => b.poll(),
}
}
}
| Use fewer generics in the Either impl | Use fewer generics in the Either impl
| Rust | apache-2.0 | Idolf/futures-rs,alexcrichton/futures-rs | rust | ## Code Before:
use {Future, Poll};
/// Combines two different futures yielding the same item and error
/// types into a single type.
pub enum Either<A, B> {
/// First branch of the type
A(A),
/// Second branch of the type
B(B),
}
impl<A, B, Item, Error> Future for Either<A, B>
where A: Future<Item = Item, Error = Error>,
B: Future<Item = Item, Error = Error>
{
type Item = Item;
type Error = Error;
fn poll(&mut self) -> Poll<Item, Error> {
match *self {
Either::A(ref mut a) => a.poll(),
Either::B(ref mut b) => b.poll(),
}
}
}
## Instruction:
Use fewer generics in the Either impl
## Code After:
use {Future, Poll};
/// Combines two different futures yielding the same item and error
/// types into a single type.
pub enum Either<A, B> {
/// First branch of the type
A(A),
/// Second branch of the type
B(B),
}
impl<A, B> Future for Either<A, B>
where A: Future,
B: Future<Item = A::Item, Error = A::Error>
{
type Item = A::Item;
type Error = A::Error;
fn poll(&mut self) -> Poll<A::Item, A::Error> {
match *self {
Either::A(ref mut a) => a.poll(),
Either::B(ref mut b) => b.poll(),
}
}
}
| use {Future, Poll};
+
/// Combines two different futures yielding the same item and error
/// types into a single type.
pub enum Either<A, B> {
/// First branch of the type
A(A),
/// Second branch of the type
B(B),
}
- impl<A, B, Item, Error> Future for Either<A, B>
? -------------
+ impl<A, B> Future for Either<A, B>
- where A: Future<Item = Item, Error = Error>,
+ where A: Future,
- B: Future<Item = Item, Error = Error>
+ B: Future<Item = A::Item, Error = A::Error>
? +++ +++
{
- type Item = Item;
+ type Item = A::Item;
? +++
- type Error = Error;
+ type Error = A::Error;
? +++
+
- fn poll(&mut self) -> Poll<Item, Error> {
+ fn poll(&mut self) -> Poll<A::Item, A::Error> {
? +++ +++
match *self {
Either::A(ref mut a) => a.poll(),
Either::B(ref mut b) => b.poll(),
}
}
} | 14 | 0.608696 | 8 | 6 |
bfea6aeb270215725c5243141286274254abcb0a | .travis.yml | .travis.yml | language: go
go_import_path: github.com/MatthewHartstonge/storage
go:
- 1.7
- 1.8
- 1.9
env:
- GO15VENDOREXPERIMENT=1
addons:
apt:
sources:
- sourceline: 'ppa:masterminds/glide'
packages:
- glide
install:
- mkdir -p $GOPATH/bin $GOPATH/pkg $GOPATH/src
- go get github.com/mattn/goveralls
- glide install
script:
- $GOPATH/bin/goveralls -service=travis-ci
services:
- mongodb
| language: go
go_import_path: github.com/MatthewHartstonge/storage
go:
- '1.8'
- '1.9'
- '1.10'
env:
- GO15VENDOREXPERIMENT=1
addons:
apt:
sources:
- sourceline: 'ppa:masterminds/glide'
packages:
- glide
install:
- mkdir -p $GOPATH/bin $GOPATH/pkg $GOPATH/src
- go get github.com/mattn/goveralls
- glide install
script:
- $GOPATH/bin/goveralls -service=travis-ci
services:
- mongodb
| Drop support for golang 1.7, add support for golang 1.10 | :arrow_up: Drop support for golang 1.7, add support for golang 1.10
| YAML | apache-2.0 | MatthewHartstonge/storage | yaml | ## Code Before:
language: go
go_import_path: github.com/MatthewHartstonge/storage
go:
- 1.7
- 1.8
- 1.9
env:
- GO15VENDOREXPERIMENT=1
addons:
apt:
sources:
- sourceline: 'ppa:masterminds/glide'
packages:
- glide
install:
- mkdir -p $GOPATH/bin $GOPATH/pkg $GOPATH/src
- go get github.com/mattn/goveralls
- glide install
script:
- $GOPATH/bin/goveralls -service=travis-ci
services:
- mongodb
## Instruction:
:arrow_up: Drop support for golang 1.7, add support for golang 1.10
## Code After:
language: go
go_import_path: github.com/MatthewHartstonge/storage
go:
- '1.8'
- '1.9'
- '1.10'
env:
- GO15VENDOREXPERIMENT=1
addons:
apt:
sources:
- sourceline: 'ppa:masterminds/glide'
packages:
- glide
install:
- mkdir -p $GOPATH/bin $GOPATH/pkg $GOPATH/src
- go get github.com/mattn/goveralls
- glide install
script:
- $GOPATH/bin/goveralls -service=travis-ci
services:
- mongodb
| language: go
go_import_path: github.com/MatthewHartstonge/storage
go:
- - 1.7
- - 1.8
+ - '1.8'
? + +
- - 1.9
+ - '1.9'
? + +
+ - '1.10'
env:
- GO15VENDOREXPERIMENT=1
addons:
apt:
sources:
- sourceline: 'ppa:masterminds/glide'
packages:
- glide
install:
- mkdir -p $GOPATH/bin $GOPATH/pkg $GOPATH/src
- go get github.com/mattn/goveralls
- glide install
script:
- $GOPATH/bin/goveralls -service=travis-ci
services:
- mongodb | 6 | 0.230769 | 3 | 3 |
126fa0073b5766c59b514a3b6ddcd4f2e623e65b | scripts/sanity_chk/arches/arm.ini | scripts/sanity_chk/arches/arm.ini | [arch]
name = arm
platforms = qemu_cortex_m3 frdm_k64f arduino_due nucleo_f103rb stm32_mini_a15
olimexino_stm32 96b_nitrogen nrf52_pca10040 hexiwear_k64
nrf51_pca10028 nucleo_f401re 96b_carbon nrf51_blenano
arduino_101_ble cc3200_launchxl quark_se_c1000_ble
supported_toolchains = zephyr gccarmemb
[qemu_cortex_m3]
qemu_support = true
| [arch]
name = arm
platforms = qemu_cortex_m3 frdm_k64f arduino_due nucleo_f103rb stm32_mini_a15
olimexino_stm32 96b_nitrogen nrf52_pca10040 hexiwear_k64
nrf51_pca10028 nucleo_f401re 96b_carbon nrf51_blenano
arduino_101_ble cc3200_launchxl quark_se_c1000_ble bbc_microbit
supported_toolchains = zephyr gccarmemb
[qemu_cortex_m3]
qemu_support = true
| Add bbc_microbit to list for platforms | sanitycheck: Add bbc_microbit to list for platforms
Change-Id: I2afd9f04e1a88b0b7c0ec600cffea18c1b86a3e8
Signed-off-by: Kumar Gala <a5e5248af4cd4f0ed8c515f61d40a6e2db46a66e@linaro.org>
| INI | apache-2.0 | nashif/zephyr,nashif/zephyr,nashif/zephyr,finikorg/zephyr,runchip/zephyr-cc3220,punitvara/zephyr,galak/zephyr,bigdinotech/zephyr,mbolivar/zephyr,pklazy/zephyr,sharronliu/zephyr,bigdinotech/zephyr,ldts/zephyr,punitvara/zephyr,Vudentz/zephyr,aceofall/zephyr-iotos,mbolivar/zephyr,fractalclone/zephyr-riscv,runchip/zephyr-cc3220,sharronliu/zephyr,aceofall/zephyr-iotos,galak/zephyr,ldts/zephyr,tidyjiang8/zephyr-doc,runchip/zephyr-cc3200,Vudentz/zephyr,kraj/zephyr,erwango/zephyr,zephyrproject-rtos/zephyr,tidyjiang8/zephyr-doc,erwango/zephyr,zephyriot/zephyr,rsalveti/zephyr,fbsder/zephyr,fbsder/zephyr,rsalveti/zephyr,kraj/zephyr,kraj/zephyr,GiulianoFranchetto/zephyr,ldts/zephyr,fbsder/zephyr,galak/zephyr,aceofall/zephyr-iotos,holtmann/zephyr,erwango/zephyr,kraj/zephyr,ldts/zephyr,holtmann/zephyr,bboozzoo/zephyr,tidyjiang8/zephyr-doc,runchip/zephyr-cc3200,pklazy/zephyr,GiulianoFranchetto/zephyr,zephyriot/zephyr,galak/zephyr,Vudentz/zephyr,runchip/zephyr-cc3220,nashif/zephyr,rsalveti/zephyr,sharronliu/zephyr,bigdinotech/zephyr,GiulianoFranchetto/zephyr,bboozzoo/zephyr,sharronliu/zephyr,erwango/zephyr,kraj/zephyr,finikorg/zephyr,holtmann/zephyr,zephyrproject-rtos/zephyr,bboozzoo/zephyr,explora26/zephyr,holtmann/zephyr,galak/zephyr,zephyriot/zephyr,explora26/zephyr,zephyrproject-rtos/zephyr,Vudentz/zephyr,zephyrproject-rtos/zephyr,zephyriot/zephyr,GiulianoFranchetto/zephyr,bboozzoo/zephyr,fractalclone/zephyr-riscv,fractalclone/zephyr-riscv,GiulianoFranchetto/zephyr,runchip/zephyr-cc3200,nashif/zephyr,pklazy/zephyr,holtmann/zephyr,aceofall/zephyr-iotos,runchip/zephyr-cc3200,mbolivar/zephyr,ldts/zephyr,tidyjiang8/zephyr-doc,rsalveti/zephyr,mbolivar/zephyr,fbsder/zephyr,explora26/zephyr,runchip/zephyr-cc3220,finikorg/zephyr,explora26/zephyr,finikorg/zephyr,finikorg/zephyr,bigdinotech/zephyr,fractalclone/zephyr-riscv,sharronliu/zephyr,runchip/zephyr-cc3220,rsalveti/zephyr,runchip/zephyr-cc3200,erwango/zephyr,punitvara/zephyr,Vudentz/zephyr,pklazy/zephyr,fractalclone/zephyr-riscv,explora26/zephyr,punitvara/zephyr,tidyjiang8/zephyr-doc,pklazy/zephyr,bigdinotech/zephyr,zephyrproject-rtos/zephyr,mbolivar/zephyr,fbsder/zephyr,aceofall/zephyr-iotos,punitvara/zephyr,zephyriot/zephyr,Vudentz/zephyr,bboozzoo/zephyr | ini | ## Code Before:
[arch]
name = arm
platforms = qemu_cortex_m3 frdm_k64f arduino_due nucleo_f103rb stm32_mini_a15
olimexino_stm32 96b_nitrogen nrf52_pca10040 hexiwear_k64
nrf51_pca10028 nucleo_f401re 96b_carbon nrf51_blenano
arduino_101_ble cc3200_launchxl quark_se_c1000_ble
supported_toolchains = zephyr gccarmemb
[qemu_cortex_m3]
qemu_support = true
## Instruction:
sanitycheck: Add bbc_microbit to list for platforms
Change-Id: I2afd9f04e1a88b0b7c0ec600cffea18c1b86a3e8
Signed-off-by: Kumar Gala <a5e5248af4cd4f0ed8c515f61d40a6e2db46a66e@linaro.org>
## Code After:
[arch]
name = arm
platforms = qemu_cortex_m3 frdm_k64f arduino_due nucleo_f103rb stm32_mini_a15
olimexino_stm32 96b_nitrogen nrf52_pca10040 hexiwear_k64
nrf51_pca10028 nucleo_f401re 96b_carbon nrf51_blenano
arduino_101_ble cc3200_launchxl quark_se_c1000_ble bbc_microbit
supported_toolchains = zephyr gccarmemb
[qemu_cortex_m3]
qemu_support = true
| [arch]
name = arm
platforms = qemu_cortex_m3 frdm_k64f arduino_due nucleo_f103rb stm32_mini_a15
olimexino_stm32 96b_nitrogen nrf52_pca10040 hexiwear_k64
nrf51_pca10028 nucleo_f401re 96b_carbon nrf51_blenano
- arduino_101_ble cc3200_launchxl quark_se_c1000_ble
+ arduino_101_ble cc3200_launchxl quark_se_c1000_ble bbc_microbit
? +++++++++++++
supported_toolchains = zephyr gccarmemb
[qemu_cortex_m3]
qemu_support = true
| 2 | 0.181818 | 1 | 1 |
9b52de5d640b5a7a83fd607e9985bee3e4add4dc | app/assets/javascripts/views/event/artists_view.js.coffee | app/assets/javascripts/views/event/artists_view.js.coffee | Yossarian.EventArtistView = Ember.View.extend
tagName: 'img'
attributeBindings: ['src', 'title']
preload: ->
@set('src', @get('content.image.image.large.url'))
@set('title', @get('content.name'))
Yossarian.EventArtistsView = Ember.CollectionView.extend
tagName: 'div'
content: []
currentItem: null
itemViewClass: Yossarian.EventArtistView
didInsertElement: ->
views = @get('childViews')
view.preload() for view in views[0..2]
for view in views[3..(views.length - 1)]
((view) -> setTimeout (-> view.preload()), 3000)(view)
setTimeout (=> @initilizeSlider()), 100
initilizeSlider: ->
@$().nivoSlider
effect: 'slideInRight'
animSpeed: 400
pauseTime: Math.random() * (20000 - 3000) + 3000
directionNav: false
controlNav: false
pauseOnHover: true
startSlide: Math.round(Math.random() * 2)
| Yossarian.EventArtistView = Ember.View.extend
tagName: 'img'
attributeBindings: ['src', 'title']
preload: ->
@set('src', @get('content.image.image.large.url'))
@set('title', @get('content.name'))
Yossarian.EventArtistsView = Ember.CollectionView.extend
tagName: 'div'
content: []
nextSlideView: null
itemViewClass: Yossarian.EventArtistView
didInsertElement: ->
views = @get('childViews')
view.preload() for view in views[0..2]
@set('nextSlideView', views[3])
setTimeout (=> @initilizeSlider()), 100
initilizeSlider: ->
@$().nivoSlider
effect: 'slideInRight'
animSpeed: 400
pauseTime: Math.random() * (20000 - 3000) + 3000
directionNav: false
controlNav: false
pauseOnHover: true
startSlide: Math.round(Math.random() * 2)
afterChange: => @preloadNextSlideView()
preloadNextSlideView: ->
views = @get('childViews')
index = views.indexOf(@get('nextSlideView')) + 1
return if index >= views.length
@set('nextSlideView', views[index])
nextSlideViewDidChange: (->
@get('nextSlideView').preload()
).observes('nextSlideView')
| Add more inteligent image preloading | Add more inteligent image preloading
| CoffeeScript | mit | smolnar/yossarian,smolnar/yossarian,smolnar/yossarian | coffeescript | ## Code Before:
Yossarian.EventArtistView = Ember.View.extend
tagName: 'img'
attributeBindings: ['src', 'title']
preload: ->
@set('src', @get('content.image.image.large.url'))
@set('title', @get('content.name'))
Yossarian.EventArtistsView = Ember.CollectionView.extend
tagName: 'div'
content: []
currentItem: null
itemViewClass: Yossarian.EventArtistView
didInsertElement: ->
views = @get('childViews')
view.preload() for view in views[0..2]
for view in views[3..(views.length - 1)]
((view) -> setTimeout (-> view.preload()), 3000)(view)
setTimeout (=> @initilizeSlider()), 100
initilizeSlider: ->
@$().nivoSlider
effect: 'slideInRight'
animSpeed: 400
pauseTime: Math.random() * (20000 - 3000) + 3000
directionNav: false
controlNav: false
pauseOnHover: true
startSlide: Math.round(Math.random() * 2)
## Instruction:
Add more inteligent image preloading
## Code After:
Yossarian.EventArtistView = Ember.View.extend
tagName: 'img'
attributeBindings: ['src', 'title']
preload: ->
@set('src', @get('content.image.image.large.url'))
@set('title', @get('content.name'))
Yossarian.EventArtistsView = Ember.CollectionView.extend
tagName: 'div'
content: []
nextSlideView: null
itemViewClass: Yossarian.EventArtistView
didInsertElement: ->
views = @get('childViews')
view.preload() for view in views[0..2]
@set('nextSlideView', views[3])
setTimeout (=> @initilizeSlider()), 100
initilizeSlider: ->
@$().nivoSlider
effect: 'slideInRight'
animSpeed: 400
pauseTime: Math.random() * (20000 - 3000) + 3000
directionNav: false
controlNav: false
pauseOnHover: true
startSlide: Math.round(Math.random() * 2)
afterChange: => @preloadNextSlideView()
preloadNextSlideView: ->
views = @get('childViews')
index = views.indexOf(@get('nextSlideView')) + 1
return if index >= views.length
@set('nextSlideView', views[index])
nextSlideViewDidChange: (->
@get('nextSlideView').preload()
).observes('nextSlideView')
| Yossarian.EventArtistView = Ember.View.extend
tagName: 'img'
attributeBindings: ['src', 'title']
preload: ->
@set('src', @get('content.image.image.large.url'))
@set('title', @get('content.name'))
Yossarian.EventArtistsView = Ember.CollectionView.extend
tagName: 'div'
content: []
- currentItem: null
+ nextSlideView: null
itemViewClass: Yossarian.EventArtistView
didInsertElement: ->
views = @get('childViews')
view.preload() for view in views[0..2]
+ @set('nextSlideView', views[3])
- for view in views[3..(views.length - 1)]
- ((view) -> setTimeout (-> view.preload()), 3000)(view)
setTimeout (=> @initilizeSlider()), 100
initilizeSlider: ->
@$().nivoSlider
effect: 'slideInRight'
animSpeed: 400
pauseTime: Math.random() * (20000 - 3000) + 3000
directionNav: false
controlNav: false
pauseOnHover: true
startSlide: Math.round(Math.random() * 2)
+ afterChange: => @preloadNextSlideView()
+
+ preloadNextSlideView: ->
+ views = @get('childViews')
+ index = views.indexOf(@get('nextSlideView')) + 1
+
+ return if index >= views.length
+
+ @set('nextSlideView', views[index])
+
+ nextSlideViewDidChange: (->
+ @get('nextSlideView').preload()
+ ).observes('nextSlideView') | 18 | 0.545455 | 15 | 3 |
595c3d065d99f5b1ecbddba3bf0c279683e872ab | .travis.yml | .travis.yml | language: objective-c
xcode_project: HelloWorld.xcodeproj
xcode_scheme: Framework
| osx_image: xcode8.2
language: objective-c
xcode_project: HelloWorld.xcodeproj
xcode_scheme: Framework
| Update the OSX image to use when building | Update the OSX image to use when building
| YAML | apache-2.0 | graemer957/helloworld-swift-framework,graemer957/helloworld-swift-framework | yaml | ## Code Before:
language: objective-c
xcode_project: HelloWorld.xcodeproj
xcode_scheme: Framework
## Instruction:
Update the OSX image to use when building
## Code After:
osx_image: xcode8.2
language: objective-c
xcode_project: HelloWorld.xcodeproj
xcode_scheme: Framework
| + osx_image: xcode8.2
language: objective-c
xcode_project: HelloWorld.xcodeproj
xcode_scheme: Framework | 1 | 0.333333 | 1 | 0 |
b6fd9d28ef40d1e7184a97db82b94a6471486593 | _includes/schedule.html | _includes/schedule.html | <section class="pad-section schedule" id="schedule">
<div class="container">
<div class="row text-center">
<h2>How & When to Finish Up</h2>
{% assign name = "schedule" %}
{% include quote.html %}
</div><!--.row-->
<div class="row">
<div class="col-lg-5 col-sm-12 left-half">
{% include howitworks.html %}
</div><!--left-half-->
<div class="col-lg-7 col-sm-12 right-half">
{% include schedule-day.html %}
</div><!--right-half-->
</div><!--.row-->
<h3 class="text-center">{{ section.jump }}</h3>
</div><!--container-->
</section><!--.content-section-a-->
| <section class="pad-section schedule" id="schedule">
<div class="container">
{% assign name = "schedule" %}
{% include quote.html %}
<div class="row">
<div class="col-md-8 col-md-offset-2 col-sm-12 right-half">
{% include schedule-day.html %}
</div><!--right-half-->
</div><!--.row-->
<h3 class="text-center">{{ section.jump }}</h3>
</div><!--container-->
</section><!--.content-section-a-->
| Remove the howitworks section. May put it into a different area of the site.. | Remove the howitworks section. May put it into a different area of the
site..
| HTML | apache-2.0 | oaklandfinishup/oaklandfinishup.github.io,oaklandfinishup/oaklandfinishup.github.io | html | ## Code Before:
<section class="pad-section schedule" id="schedule">
<div class="container">
<div class="row text-center">
<h2>How & When to Finish Up</h2>
{% assign name = "schedule" %}
{% include quote.html %}
</div><!--.row-->
<div class="row">
<div class="col-lg-5 col-sm-12 left-half">
{% include howitworks.html %}
</div><!--left-half-->
<div class="col-lg-7 col-sm-12 right-half">
{% include schedule-day.html %}
</div><!--right-half-->
</div><!--.row-->
<h3 class="text-center">{{ section.jump }}</h3>
</div><!--container-->
</section><!--.content-section-a-->
## Instruction:
Remove the howitworks section. May put it into a different area of the
site..
## Code After:
<section class="pad-section schedule" id="schedule">
<div class="container">
{% assign name = "schedule" %}
{% include quote.html %}
<div class="row">
<div class="col-md-8 col-md-offset-2 col-sm-12 right-half">
{% include schedule-day.html %}
</div><!--right-half-->
</div><!--.row-->
<h3 class="text-center">{{ section.jump }}</h3>
</div><!--container-->
</section><!--.content-section-a-->
| <section class="pad-section schedule" id="schedule">
- <div class="container">
? ^
+ <div class="container">
? ^^
- <div class="row text-center">
- <h2>How & When to Finish Up</h2>
- {% assign name = "schedule" %}
? ^^^
+ {% assign name = "schedule" %}
? ^^^^
- {% include quote.html %}
? ^^^
+ {% include quote.html %}
? ^^^^
- </div><!--.row-->
- <div class="row">
? ^^
+ <div class="row">
? ^^^^
+ <div class="col-md-8 col-md-offset-2 col-sm-12 right-half">
- <div class="col-lg-5 col-sm-12 left-half">
- {% include howitworks.html %}
- </div><!--left-half-->
-
- <div class="col-lg-7 col-sm-12 right-half">
- {% include schedule-day.html %}
? ^^^^
+ {% include schedule-day.html %}
? ^^^^^^^^
- </div><!--right-half-->
? ^^^
+ </div><!--right-half-->
? ^^^^^^
- </div><!--.row-->
? ^^
+ </div><!--.row-->
? ^^^^
- <h3 class="text-center">{{ section.jump }}</h3>
? ^^
+ <h3 class="text-center">{{ section.jump }}</h3>
? ^^^^
- </div><!--container-->
? ^
+ </div><!--container-->
? ^^
</section><!--.content-section-a--> | 27 | 1.421053 | 10 | 17 |
7dc466e492239837fc791f14fcd0d5a4fadff1d0 | db/seeds.rb | db/seeds.rb | twitter_client ||= TwitterOAuth::Client.new
%w(appsterdamrs fngtps thijs alloy).each do |user|
if attributes = twitter_client.show(user)
Member.create_with_twitter_user_attributes(attributes)
end
end | def add_work_type(member, type)
types = member.work_types || []
types << type
member.work_types = types
end
Dir.glob(Rails.root + 'db/seeds/*.json').each do |file|
list_name = File.basename(file, '.json').split('-').first
list = JSON.parse(File.read(file))
users = list['users']
users.each do |attributes|
member = Member.find_by_twitter_id(attributes['id']) ||
Member.create_with_twitter_user_attributes(attributes)
case list_name
when 'companies'
member.entity = 'company'
when 'students'
member.entity = 'student'
when 'collectives'
member.entity = 'group'
when 'available'
unless member.entity == 'company'
# NOTE this doesn't need to be true, but just trying to get some dev data right now
member.entity = 'individual'
member.available_for_hire = true
end
when 'hiring'
member.entity = 'company'
member.job_offers_url = attributes['url']
when /appsterdammers/
member.work_location = case attributes['location']
when /appsterdam/i, /amsterdam/i
'appsterdam'
when /nederland/i, /netherlands/i, /holland/i
'applander'
else
'appbroader'
end
when 'designers'
add_work_type(member, 'designer')
when 'developers'
add_work_type(member, 'developer')
when 'founders'
add_work_type(member, 'management-executive')
when 'marketeers'
add_work_type(member, 'marketing')
end
end
end
| Use the actual members data for the db:seed task. | Use the actual members data for the db:seed task.
| Ruby | mit | Appsterdam/Appsterdam-Website,Appsterdam/appsterdam,Appsterdam/appsterdam,Appsterdam/Appsterdam-Website | ruby | ## Code Before:
twitter_client ||= TwitterOAuth::Client.new
%w(appsterdamrs fngtps thijs alloy).each do |user|
if attributes = twitter_client.show(user)
Member.create_with_twitter_user_attributes(attributes)
end
end
## Instruction:
Use the actual members data for the db:seed task.
## Code After:
def add_work_type(member, type)
types = member.work_types || []
types << type
member.work_types = types
end
Dir.glob(Rails.root + 'db/seeds/*.json').each do |file|
list_name = File.basename(file, '.json').split('-').first
list = JSON.parse(File.read(file))
users = list['users']
users.each do |attributes|
member = Member.find_by_twitter_id(attributes['id']) ||
Member.create_with_twitter_user_attributes(attributes)
case list_name
when 'companies'
member.entity = 'company'
when 'students'
member.entity = 'student'
when 'collectives'
member.entity = 'group'
when 'available'
unless member.entity == 'company'
# NOTE this doesn't need to be true, but just trying to get some dev data right now
member.entity = 'individual'
member.available_for_hire = true
end
when 'hiring'
member.entity = 'company'
member.job_offers_url = attributes['url']
when /appsterdammers/
member.work_location = case attributes['location']
when /appsterdam/i, /amsterdam/i
'appsterdam'
when /nederland/i, /netherlands/i, /holland/i
'applander'
else
'appbroader'
end
when 'designers'
add_work_type(member, 'designer')
when 'developers'
add_work_type(member, 'developer')
when 'founders'
add_work_type(member, 'management-executive')
when 'marketeers'
add_work_type(member, 'marketing')
end
end
end
| - twitter_client ||= TwitterOAuth::Client.new
- %w(appsterdamrs fngtps thijs alloy).each do |user|
- if attributes = twitter_client.show(user)
+ def add_work_type(member, type)
+ types = member.work_types || []
+ types << type
+ member.work_types = types
+ end
+
+ Dir.glob(Rails.root + 'db/seeds/*.json').each do |file|
+ list_name = File.basename(file, '.json').split('-').first
+ list = JSON.parse(File.read(file))
+ users = list['users']
+ users.each do |attributes|
+ member = Member.find_by_twitter_id(attributes['id']) ||
- Member.create_with_twitter_user_attributes(attributes)
+ Member.create_with_twitter_user_attributes(attributes)
? +++++++++++
+ case list_name
+ when 'companies'
+ member.entity = 'company'
+ when 'students'
+ member.entity = 'student'
+ when 'collectives'
+ member.entity = 'group'
+ when 'available'
+ unless member.entity == 'company'
+ # NOTE this doesn't need to be true, but just trying to get some dev data right now
+ member.entity = 'individual'
+ member.available_for_hire = true
+ end
+ when 'hiring'
+ member.entity = 'company'
+ member.job_offers_url = attributes['url']
+ when /appsterdammers/
+ member.work_location = case attributes['location']
+ when /appsterdam/i, /amsterdam/i
+ 'appsterdam'
+ when /nederland/i, /netherlands/i, /holland/i
+ 'applander'
+ else
+ 'appbroader'
+ end
+ when 'designers'
+ add_work_type(member, 'designer')
+ when 'developers'
+ add_work_type(member, 'developer')
+ when 'founders'
+ add_work_type(member, 'management-executive')
+ when 'marketeers'
+ add_work_type(member, 'marketing')
+ end
end
end | 51 | 8.5 | 47 | 4 |
33833f1128ae04c7765c9ba0d564aa2ea9007fb6 | config/visual-studio-code/keybindings.json | config/visual-studio-code/keybindings.json | // Place your key bindings in this file to overwrite the defaults
[
{ "key": "ctrl+tab", "command": "workbench.action.nextEditor" },
{ "key": "ctrl+shift+tab", "command": "workbench.action.previousEditor" },
{ "key": "cmd+shift+l", "command": "editor.action.insertCursorAtEndOfEachLineSelected"},
{ "key": "cmd+alt+g", "command": "editor.action.changeAll", "when": "editorTextFocus" }
]
| // Place your key bindings in this file to overwrite the defaults
[
{ "key": "ctrl+tab", "command": "workbench.action.nextEditor" },
{ "key": "ctrl+shift+tab", "command": "workbench.action.previousEditor" },
{ "key": "cmd+shift+l", "command": "editor.action.insertCursorAtEndOfEachLineSelected"},
{ "key": "cmd+alt+g", "command": "editor.action.changeAll", "when": "editorTextFocus" },
{
"key": "ctrl+e",
"command": "editor.emmet.action.expandAbbreviation",
"when": "editorTextFocus && !editorReadonly && !editorTabMovesFocus"
},
{
"key": "cmd+t",
"command": "workbench.action.quickOpen"
},
{
"key": "cmd+r",
"command": "workbench.action.gotoSymbol"
},
{
"key": "cmd+alt+down",
"command": "editor.action.goToDeclaration"
},
{
"key": "cmd+g",
"command": "editor.action.nextMatchFindAction",
"when": "editorTextFocus"
},
{
"key": "cmd+ctrl+g",
"command": "editor.action.selectHighlights",
"when": "editorFocus"
},
{
"key": "cmd+l",
"command": "expandLineSelection",
"when": "editorFocus"
},
{
"key": "cmd+shift+l",
"command": "editor.action.insertCursorAtEndOfEachLineSelected",
"when": "editorTextFocus"
},
{
"key": "cmd+j",
"command": "editor.action.joinLines",
"when": "editorTextFocus"
},
{
"key": "cmd+k cmd+u",
"command": "editor.action.transformToUppercase",
"when": "editorTextFocus"
},
{
"key": "cmd+k cmd+l",
"command": "editor.action.transformToLowercase",
"when": "editorTextFocus"
}
]
| Add more Sublime Text key bindings for VS Code | Add more Sublime Text key bindings for VS Code
| JSON | isc | ThibWeb/dotfiles,ThibWeb/dotfiles,ThibWeb/dotfiles | json | ## Code Before:
// Place your key bindings in this file to overwrite the defaults
[
{ "key": "ctrl+tab", "command": "workbench.action.nextEditor" },
{ "key": "ctrl+shift+tab", "command": "workbench.action.previousEditor" },
{ "key": "cmd+shift+l", "command": "editor.action.insertCursorAtEndOfEachLineSelected"},
{ "key": "cmd+alt+g", "command": "editor.action.changeAll", "when": "editorTextFocus" }
]
## Instruction:
Add more Sublime Text key bindings for VS Code
## Code After:
// Place your key bindings in this file to overwrite the defaults
[
{ "key": "ctrl+tab", "command": "workbench.action.nextEditor" },
{ "key": "ctrl+shift+tab", "command": "workbench.action.previousEditor" },
{ "key": "cmd+shift+l", "command": "editor.action.insertCursorAtEndOfEachLineSelected"},
{ "key": "cmd+alt+g", "command": "editor.action.changeAll", "when": "editorTextFocus" },
{
"key": "ctrl+e",
"command": "editor.emmet.action.expandAbbreviation",
"when": "editorTextFocus && !editorReadonly && !editorTabMovesFocus"
},
{
"key": "cmd+t",
"command": "workbench.action.quickOpen"
},
{
"key": "cmd+r",
"command": "workbench.action.gotoSymbol"
},
{
"key": "cmd+alt+down",
"command": "editor.action.goToDeclaration"
},
{
"key": "cmd+g",
"command": "editor.action.nextMatchFindAction",
"when": "editorTextFocus"
},
{
"key": "cmd+ctrl+g",
"command": "editor.action.selectHighlights",
"when": "editorFocus"
},
{
"key": "cmd+l",
"command": "expandLineSelection",
"when": "editorFocus"
},
{
"key": "cmd+shift+l",
"command": "editor.action.insertCursorAtEndOfEachLineSelected",
"when": "editorTextFocus"
},
{
"key": "cmd+j",
"command": "editor.action.joinLines",
"when": "editorTextFocus"
},
{
"key": "cmd+k cmd+u",
"command": "editor.action.transformToUppercase",
"when": "editorTextFocus"
},
{
"key": "cmd+k cmd+l",
"command": "editor.action.transformToLowercase",
"when": "editorTextFocus"
}
]
| // Place your key bindings in this file to overwrite the defaults
[
{ "key": "ctrl+tab", "command": "workbench.action.nextEditor" },
{ "key": "ctrl+shift+tab", "command": "workbench.action.previousEditor" },
{ "key": "cmd+shift+l", "command": "editor.action.insertCursorAtEndOfEachLineSelected"},
- { "key": "cmd+alt+g", "command": "editor.action.changeAll", "when": "editorTextFocus" }
+ { "key": "cmd+alt+g", "command": "editor.action.changeAll", "when": "editorTextFocus" },
? +
+ {
+ "key": "ctrl+e",
+ "command": "editor.emmet.action.expandAbbreviation",
+ "when": "editorTextFocus && !editorReadonly && !editorTabMovesFocus"
+ },
+ {
+ "key": "cmd+t",
+ "command": "workbench.action.quickOpen"
+ },
+ {
+ "key": "cmd+r",
+ "command": "workbench.action.gotoSymbol"
+ },
+ {
+ "key": "cmd+alt+down",
+ "command": "editor.action.goToDeclaration"
+ },
+ {
+ "key": "cmd+g",
+ "command": "editor.action.nextMatchFindAction",
+ "when": "editorTextFocus"
+ },
+ {
+ "key": "cmd+ctrl+g",
+ "command": "editor.action.selectHighlights",
+ "when": "editorFocus"
+ },
+ {
+ "key": "cmd+l",
+ "command": "expandLineSelection",
+ "when": "editorFocus"
+ },
+ {
+ "key": "cmd+shift+l",
+ "command": "editor.action.insertCursorAtEndOfEachLineSelected",
+ "when": "editorTextFocus"
+ },
+ {
+ "key": "cmd+j",
+ "command": "editor.action.joinLines",
+ "when": "editorTextFocus"
+ },
+ {
+ "key": "cmd+k cmd+u",
+ "command": "editor.action.transformToUppercase",
+ "when": "editorTextFocus"
+ },
+ {
+ "key": "cmd+k cmd+l",
+ "command": "editor.action.transformToLowercase",
+ "when": "editorTextFocus"
+ }
] | 54 | 7.714286 | 53 | 1 |
78428105e97416c90e9491ed2d944eb878ea3602 | frontend/src/components/activity/content/ColumnLayout.vue | frontend/src/components/activity/content/ColumnLayout.vue | <template>
<div class="d-md-flex">
<div v-for="(column, idx) in columns"
:key="idx"
class="flex-md-grow-1"
:class="{ 'mr-md-2': idx < columns.length - 1, 'ml-md-2': idx > 0 }">
<content-node v-for="childNode in columnContents[column.slot]"
:key="childNode.id"
:content-node="childNode" />
</div>
</div>
</template>
<script>
import { groupBy, sortBy } from 'lodash'
export default {
name: 'ColumnLayout',
components: {
// Lazy import necessary due to recursive component structure
ContentNode: () => import('@/components/activity/ContentNode')
},
props: {
contentNode: { type: Object, required: true }
},
computed: {
columns () {
return this.contentNode.jsonConfig?.columns || []
},
columnContents () {
return groupBy(sortBy(this.contentNode.children().items, 'position'), 'slot')
}
}
}
</script>
| <template>
<v-container fluid class="px-0 py-0">
<v-row class="mx-0 my-0">
<v-col v-for="(column, idx) in columns"
:key="idx"
cols="12"
class="col-md">
<content-node v-for="childNode in columnContents[column.slot]"
:key="childNode.id"
:content-node="childNode" />
</v-col>
</v-row>
</v-container>
</template>
<script>
import { groupBy, sortBy } from 'lodash'
export default {
name: 'ColumnLayout',
components: {
// Lazy import necessary due to recursive component structure
ContentNode: () => import('@/components/activity/ContentNode')
},
props: {
contentNode: { type: Object, required: true }
},
computed: {
columns () {
return this.contentNode.jsonConfig?.columns || []
},
columnContents () {
return groupBy(sortBy(this.contentNode.children().items, 'position'), 'slot')
}
}
}
</script>
| Switch to the Vuetify grid system to avoid resizing columns based on content | Switch to the Vuetify grid system to avoid resizing columns based on content
| Vue | agpl-3.0 | pmattmann/ecamp3,ecamp/ecamp3,usu/ecamp3,ecamp/ecamp3,pmattmann/ecamp3,ecamp/ecamp3,usu/ecamp3,usu/ecamp3,pmattmann/ecamp3,ecamp/ecamp3,usu/ecamp3,pmattmann/ecamp3 | vue | ## Code Before:
<template>
<div class="d-md-flex">
<div v-for="(column, idx) in columns"
:key="idx"
class="flex-md-grow-1"
:class="{ 'mr-md-2': idx < columns.length - 1, 'ml-md-2': idx > 0 }">
<content-node v-for="childNode in columnContents[column.slot]"
:key="childNode.id"
:content-node="childNode" />
</div>
</div>
</template>
<script>
import { groupBy, sortBy } from 'lodash'
export default {
name: 'ColumnLayout',
components: {
// Lazy import necessary due to recursive component structure
ContentNode: () => import('@/components/activity/ContentNode')
},
props: {
contentNode: { type: Object, required: true }
},
computed: {
columns () {
return this.contentNode.jsonConfig?.columns || []
},
columnContents () {
return groupBy(sortBy(this.contentNode.children().items, 'position'), 'slot')
}
}
}
</script>
## Instruction:
Switch to the Vuetify grid system to avoid resizing columns based on content
## Code After:
<template>
<v-container fluid class="px-0 py-0">
<v-row class="mx-0 my-0">
<v-col v-for="(column, idx) in columns"
:key="idx"
cols="12"
class="col-md">
<content-node v-for="childNode in columnContents[column.slot]"
:key="childNode.id"
:content-node="childNode" />
</v-col>
</v-row>
</v-container>
</template>
<script>
import { groupBy, sortBy } from 'lodash'
export default {
name: 'ColumnLayout',
components: {
// Lazy import necessary due to recursive component structure
ContentNode: () => import('@/components/activity/ContentNode')
},
props: {
contentNode: { type: Object, required: true }
},
computed: {
columns () {
return this.contentNode.jsonConfig?.columns || []
},
columnContents () {
return groupBy(sortBy(this.contentNode.children().items, 'position'), 'slot')
}
}
}
</script>
| <template>
- <div class="d-md-flex">
+ <v-container fluid class="px-0 py-0">
+ <v-row class="mx-0 my-0">
- <div v-for="(column, idx) in columns"
? --
+ <v-col v-for="(column, idx) in columns"
? ++ ++++
- :key="idx"
+ :key="idx"
? ++++
- class="flex-md-grow-1"
- :class="{ 'mr-md-2': idx < columns.length - 1, 'ml-md-2': idx > 0 }">
+ cols="12"
+ class="col-md">
- <content-node v-for="childNode in columnContents[column.slot]"
+ <content-node v-for="childNode in columnContents[column.slot]"
? ++
- :key="childNode.id"
+ :key="childNode.id"
? ++
- :content-node="childNode" />
+ :content-node="childNode" />
? ++
- </div>
- </div>
+ </v-col>
+ </v-row>
+ </v-container>
</template>
<script>
import { groupBy, sortBy } from 'lodash'
export default {
name: 'ColumnLayout',
components: {
// Lazy import necessary due to recursive component structure
ContentNode: () => import('@/components/activity/ContentNode')
},
props: {
contentNode: { type: Object, required: true }
},
computed: {
columns () {
return this.contentNode.jsonConfig?.columns || []
},
columnContents () {
return groupBy(sortBy(this.contentNode.children().items, 'position'), 'slot')
}
}
}
</script> | 22 | 0.611111 | 12 | 10 |
14b277eb296e9cc90f8d70fc82e07128f432adb2 | addon/component.js | addon/component.js | import ClickOutsideMixin from './mixin';
import Component from '@ember/component';
import { on } from '@ember/object/evented';
import { next, cancel } from '@ember/runloop';
import $ from 'jquery';
export default Component.extend(ClickOutsideMixin, {
clickOutside(e) {
if (this.isDestroying || this.isDestroyed) {
return;
}
const exceptSelector = this.get('except-selector');
if (exceptSelector && $(e.target).closest(exceptSelector).length > 0) {
return;
}
let action = this.get('action');
if (typeof action !== 'undefined') {
action(e);
}
},
_attachClickOutsideHandler: on('didInsertElement', function() {
this._cancelOutsideListenerSetup = next(this, this.addClickOutsideListener);
}),
_removeClickOutsideHandler: on('willDestroyElement', function() {
cancel(this._cancelOutsideListerSetup);
this.removeClickOutsideListener();
})
});
| import ClickOutsideMixin from './mixin';
import Component from '@ember/component';
import { next, cancel } from '@ember/runloop';
import $ from 'jquery';
export default Component.extend(ClickOutsideMixin, {
clickOutside(e) {
if (this.isDestroying || this.isDestroyed) {
return;
}
const exceptSelector = this.get('except-selector');
if (exceptSelector && $(e.target).closest(exceptSelector).length > 0) {
return;
}
let action = this.get('action');
if (typeof action !== 'undefined') {
action(e);
}
},
didInsertElement() {
this._super(...arguments);
this._cancelOutsideListenerSetup = next(this, this.addClickOutsideListener);
},
willDestroyElement() {
cancel(this._cancelOutsideListerSetup);
this.removeClickOutsideListener();
}
});
| Fix lifecycle events to satisfy recommendations | Fix lifecycle events to satisfy recommendations
| JavaScript | mit | zeppelin/ember-click-outside,zeppelin/ember-click-outside | javascript | ## Code Before:
import ClickOutsideMixin from './mixin';
import Component from '@ember/component';
import { on } from '@ember/object/evented';
import { next, cancel } from '@ember/runloop';
import $ from 'jquery';
export default Component.extend(ClickOutsideMixin, {
clickOutside(e) {
if (this.isDestroying || this.isDestroyed) {
return;
}
const exceptSelector = this.get('except-selector');
if (exceptSelector && $(e.target).closest(exceptSelector).length > 0) {
return;
}
let action = this.get('action');
if (typeof action !== 'undefined') {
action(e);
}
},
_attachClickOutsideHandler: on('didInsertElement', function() {
this._cancelOutsideListenerSetup = next(this, this.addClickOutsideListener);
}),
_removeClickOutsideHandler: on('willDestroyElement', function() {
cancel(this._cancelOutsideListerSetup);
this.removeClickOutsideListener();
})
});
## Instruction:
Fix lifecycle events to satisfy recommendations
## Code After:
import ClickOutsideMixin from './mixin';
import Component from '@ember/component';
import { next, cancel } from '@ember/runloop';
import $ from 'jquery';
export default Component.extend(ClickOutsideMixin, {
clickOutside(e) {
if (this.isDestroying || this.isDestroyed) {
return;
}
const exceptSelector = this.get('except-selector');
if (exceptSelector && $(e.target).closest(exceptSelector).length > 0) {
return;
}
let action = this.get('action');
if (typeof action !== 'undefined') {
action(e);
}
},
didInsertElement() {
this._super(...arguments);
this._cancelOutsideListenerSetup = next(this, this.addClickOutsideListener);
},
willDestroyElement() {
cancel(this._cancelOutsideListerSetup);
this.removeClickOutsideListener();
}
});
| import ClickOutsideMixin from './mixin';
import Component from '@ember/component';
- import { on } from '@ember/object/evented';
import { next, cancel } from '@ember/runloop';
import $ from 'jquery';
export default Component.extend(ClickOutsideMixin, {
clickOutside(e) {
if (this.isDestroying || this.isDestroyed) {
return;
}
const exceptSelector = this.get('except-selector');
if (exceptSelector && $(e.target).closest(exceptSelector).length > 0) {
return;
}
let action = this.get('action');
if (typeof action !== 'undefined') {
action(e);
}
},
- _attachClickOutsideHandler: on('didInsertElement', function() {
+ didInsertElement() {
+ this._super(...arguments);
this._cancelOutsideListenerSetup = next(this, this.addClickOutsideListener);
- }),
? -
+ },
- _removeClickOutsideHandler: on('willDestroyElement', function() {
+ willDestroyElement() {
cancel(this._cancelOutsideListerSetup);
this.removeClickOutsideListener();
- })
? -
+ }
}); | 10 | 0.30303 | 5 | 5 |
8170ad6cdfd2346bc24a3d743663b4866416ca83 | Engine.py | Engine.py | import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from shapes import Shape, Cube
#Create a game class
class Game(object):
#Constructor
def __init__(self, title, width, height, bgcolour):
#Initialise pygame
pygame.init()
#Set the size of the window
self.size = self.width, self.height = width, height
#Set the default perspective and clipping distances
self.fov = 45.0
self.aspectratio = width / height
self.minrender = 0.1
self.maxrender = 80
#Set the pygame mode to use double buffering and open gl
pygame.set_mode(self.size, DOUBLEBUF|OPENGL)
#Set the perspective
self.setperspective()
#Create an empty list of shapes to render
self.shapes = []
#Create a function to update the perspective
def setperspective(self):
#Set the perspective
gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender)
| import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from shapes import Shape, Cube
#Create a game class
class Game(object):
#Constructor
def __init__(self, title, width, height, bgcolour):
#Initialise pygame
pygame.init()
#Set the size of the window
self.size = self.width, self.height = width, height
#Set the default perspective and clipping distances
self.fov = 45.0
self.aspectratio = width / height
self.minrender = 0.1
self.maxrender = 80
#Set the pygame mode to use double buffering and open gl
pygame.set_mode(self.size, DOUBLEBUF|OPENGL)
#Set the perspective
self.setperspective()
#Create an empty list of shapes to render
self.shapes = []
#Create a function to update the perspective
def setperspective(self):
#Set the perspective
gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender)
#Create a function to add a shape
def addshape(self, s):
self.shapes.append(s)
#Create a function to render the shapes
def render(self):
#For each of the shapes, check the type and render it
for s in shapes:
#If the shape is a cube, call the rendercube method
if s.type == Shape.CUBE:
rendercube(s)
| Add functions to add shapes and iterate over each shape to render. | Add functions to add shapes and iterate over each shape to render.
| Python | mit | thebillington/pyPhys3D | python | ## Code Before:
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from shapes import Shape, Cube
#Create a game class
class Game(object):
#Constructor
def __init__(self, title, width, height, bgcolour):
#Initialise pygame
pygame.init()
#Set the size of the window
self.size = self.width, self.height = width, height
#Set the default perspective and clipping distances
self.fov = 45.0
self.aspectratio = width / height
self.minrender = 0.1
self.maxrender = 80
#Set the pygame mode to use double buffering and open gl
pygame.set_mode(self.size, DOUBLEBUF|OPENGL)
#Set the perspective
self.setperspective()
#Create an empty list of shapes to render
self.shapes = []
#Create a function to update the perspective
def setperspective(self):
#Set the perspective
gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender)
## Instruction:
Add functions to add shapes and iterate over each shape to render.
## Code After:
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from shapes import Shape, Cube
#Create a game class
class Game(object):
#Constructor
def __init__(self, title, width, height, bgcolour):
#Initialise pygame
pygame.init()
#Set the size of the window
self.size = self.width, self.height = width, height
#Set the default perspective and clipping distances
self.fov = 45.0
self.aspectratio = width / height
self.minrender = 0.1
self.maxrender = 80
#Set the pygame mode to use double buffering and open gl
pygame.set_mode(self.size, DOUBLEBUF|OPENGL)
#Set the perspective
self.setperspective()
#Create an empty list of shapes to render
self.shapes = []
#Create a function to update the perspective
def setperspective(self):
#Set the perspective
gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender)
#Create a function to add a shape
def addshape(self, s):
self.shapes.append(s)
#Create a function to render the shapes
def render(self):
#For each of the shapes, check the type and render it
for s in shapes:
#If the shape is a cube, call the rendercube method
if s.type == Shape.CUBE:
rendercube(s)
| import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from shapes import Shape, Cube
#Create a game class
class Game(object):
#Constructor
def __init__(self, title, width, height, bgcolour):
#Initialise pygame
pygame.init()
#Set the size of the window
self.size = self.width, self.height = width, height
#Set the default perspective and clipping distances
self.fov = 45.0
self.aspectratio = width / height
self.minrender = 0.1
self.maxrender = 80
#Set the pygame mode to use double buffering and open gl
pygame.set_mode(self.size, DOUBLEBUF|OPENGL)
#Set the perspective
self.setperspective()
#Create an empty list of shapes to render
self.shapes = []
#Create a function to update the perspective
def setperspective(self):
#Set the perspective
gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender)
+
+ #Create a function to add a shape
+ def addshape(self, s):
+ self.shapes.append(s)
+
+ #Create a function to render the shapes
+ def render(self):
+ #For each of the shapes, check the type and render it
+ for s in shapes:
+ #If the shape is a cube, call the rendercube method
+ if s.type == Shape.CUBE:
+ rendercube(s)
| 12 | 0.292683 | 12 | 0 |
0f1d10f452066fb304f24006ac641860f4f6b7d9 | bluebottle/utils/migrations/0007_auto_20210825_1018.py | bluebottle/utils/migrations/0007_auto_20210825_1018.py | from django.db import migrations
from bluebottle.clients import properties
def set_default(apps, schema_editor):
try:
Language = apps.get_model('utils', 'Language')
language = Language.objects.get(code=properties.LANGUAGE_CODE)
except Language.DoesNotExist:
language = Language.objects.first()
language.default = True
language.save()
class Migration(migrations.Migration):
dependencies = [
('utils', '0006_auto_20210825_1018'),
]
operations = [
migrations.RunPython(set_default, migrations.RunPython.noop)
]
| from django.db import migrations
from bluebottle.clients import properties
def set_default(apps, schema_editor):
try:
Language = apps.get_model('utils', 'Language')
language = Language.objects.get(code=properties.LANGUAGE_CODE)
except Language.DoesNotExist:
try:
language = Language.objects.get()
except Language.DoesNotExist:
return
language.default = True
language.save()
class Migration(migrations.Migration):
dependencies = [
('utils', '0006_auto_20210825_1018'),
]
operations = [
migrations.RunPython(set_default, migrations.RunPython.noop)
]
| Fix migration if no language exists | Fix migration if no language exists
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | python | ## Code Before:
from django.db import migrations
from bluebottle.clients import properties
def set_default(apps, schema_editor):
try:
Language = apps.get_model('utils', 'Language')
language = Language.objects.get(code=properties.LANGUAGE_CODE)
except Language.DoesNotExist:
language = Language.objects.first()
language.default = True
language.save()
class Migration(migrations.Migration):
dependencies = [
('utils', '0006_auto_20210825_1018'),
]
operations = [
migrations.RunPython(set_default, migrations.RunPython.noop)
]
## Instruction:
Fix migration if no language exists
## Code After:
from django.db import migrations
from bluebottle.clients import properties
def set_default(apps, schema_editor):
try:
Language = apps.get_model('utils', 'Language')
language = Language.objects.get(code=properties.LANGUAGE_CODE)
except Language.DoesNotExist:
try:
language = Language.objects.get()
except Language.DoesNotExist:
return
language.default = True
language.save()
class Migration(migrations.Migration):
dependencies = [
('utils', '0006_auto_20210825_1018'),
]
operations = [
migrations.RunPython(set_default, migrations.RunPython.noop)
]
| from django.db import migrations
from bluebottle.clients import properties
def set_default(apps, schema_editor):
try:
Language = apps.get_model('utils', 'Language')
language = Language.objects.get(code=properties.LANGUAGE_CODE)
except Language.DoesNotExist:
+ try:
- language = Language.objects.first()
? ^^^^
+ language = Language.objects.get()
? ++++ ^^
+ except Language.DoesNotExist:
+ return
language.default = True
language.save()
class Migration(migrations.Migration):
dependencies = [
('utils', '0006_auto_20210825_1018'),
]
operations = [
migrations.RunPython(set_default, migrations.RunPython.noop)
] | 5 | 0.2 | 4 | 1 |
59c66d0e172b23ea7106a70866871d20bbcabe5b | timezones/__init__.py | timezones/__init__.py |
import pytz
TIMEZONE_CHOICES = zip(pytz.all_timezones, pytz.all_timezones)
|
import pytz
TIMEZONE_CHOICES = zip(pytz.common_timezones, pytz.common_timezones)
| Use common timezones and not all timezones pytz provides. | Use common timezones and not all timezones pytz provides.
git-svn-id: 13ea2b4cf383b32e0a7498d153ee882d068671f7@13 86ebb30f-654e-0410-bc0d-7bf82786d749
| Python | bsd-2-clause | mfogel/django-timezone-field,brosner/django-timezones | python | ## Code Before:
import pytz
TIMEZONE_CHOICES = zip(pytz.all_timezones, pytz.all_timezones)
## Instruction:
Use common timezones and not all timezones pytz provides.
git-svn-id: 13ea2b4cf383b32e0a7498d153ee882d068671f7@13 86ebb30f-654e-0410-bc0d-7bf82786d749
## Code After:
import pytz
TIMEZONE_CHOICES = zip(pytz.common_timezones, pytz.common_timezones)
|
import pytz
- TIMEZONE_CHOICES = zip(pytz.all_timezones, pytz.all_timezones)
? ^^^ ^^^
+ TIMEZONE_CHOICES = zip(pytz.common_timezones, pytz.common_timezones)
? ^^^^^^ ^^^^^^
| 2 | 0.5 | 1 | 1 |
b41ac9cd72601edb2cc488c65dd11b514798f613 | nightweb-desktop/src/nightweb/core.clj | nightweb-desktop/src/nightweb/core.clj | (ns nightweb.core
(:use splendid.jfx
nightweb.page)
(:import javafx.scene.layout.VBox
javafx.scene.layout.HBox
javafx.scene.control.TabPane
javafx.scene.control.Tab
javafx.scene.web.WebView
javafx.scene.layout.Priority
javafx.scene.control.Button
javafx.scene.control.TextField
javafx.geometry.Insets
net.i2p.router.Router)
(:gen-class))
(defn start-browser
"Launch the JavaFX browser (non-blocking)."
[]
(jfx (let [window (VBox.)
tab-view (VBox.)
nav-bar (HBox.)
back-btn (Button. "<-")
for-btn (Button. "->")
reload-btn (Button. "Reload")
url-field (TextField.)
tab-bar (TabPane.)
main-tab (Tab. "Main Page")
add-tab (Tab. "+")
web-view (WebView.)]
(.setPadding nav-bar (Insets. 4))
(.setSpacing nav-bar 2)
(add nav-bar [back-btn for-btn reload-btn url-field])
(HBox/setHgrow url-field Priority/ALWAYS)
(add tab-view [nav-bar web-view])
(.setClosable add-tab false)
(.setContent main-tab tab-view)
(.add (.getTabs tab-bar) main-tab)
(.add (.getTabs tab-bar) add-tab)
(.load (.getEngine web-view) "http://localhost:8080")
(VBox/setVgrow tab-bar Priority/ALWAYS)
(add window [tab-bar])
(show window))))
(defn start-router
"Launch the router (blocking)."
[]
(Router/main nil))
(defn -main
"Launch everything."
[& args]
(start-web-server)
(start-browser)
(comment (start-router)))
| (ns nightweb.core
(:use nightweb.page
nightweb.browser)
(:import net.i2p.router.Router)
(:gen-class))
(defn start-router
"Launch the router (blocking)."
[]
(Router/main nil))
(defn -main
"Launch everything."
[& args]
(start-web-server)
(start-browser)
(comment (start-router)))
| Add ability to create tabs. | Add ability to create tabs.
| Clojure | unlicense | oakes/Nightweb,oakes/Nightweb | clojure | ## Code Before:
(ns nightweb.core
(:use splendid.jfx
nightweb.page)
(:import javafx.scene.layout.VBox
javafx.scene.layout.HBox
javafx.scene.control.TabPane
javafx.scene.control.Tab
javafx.scene.web.WebView
javafx.scene.layout.Priority
javafx.scene.control.Button
javafx.scene.control.TextField
javafx.geometry.Insets
net.i2p.router.Router)
(:gen-class))
(defn start-browser
"Launch the JavaFX browser (non-blocking)."
[]
(jfx (let [window (VBox.)
tab-view (VBox.)
nav-bar (HBox.)
back-btn (Button. "<-")
for-btn (Button. "->")
reload-btn (Button. "Reload")
url-field (TextField.)
tab-bar (TabPane.)
main-tab (Tab. "Main Page")
add-tab (Tab. "+")
web-view (WebView.)]
(.setPadding nav-bar (Insets. 4))
(.setSpacing nav-bar 2)
(add nav-bar [back-btn for-btn reload-btn url-field])
(HBox/setHgrow url-field Priority/ALWAYS)
(add tab-view [nav-bar web-view])
(.setClosable add-tab false)
(.setContent main-tab tab-view)
(.add (.getTabs tab-bar) main-tab)
(.add (.getTabs tab-bar) add-tab)
(.load (.getEngine web-view) "http://localhost:8080")
(VBox/setVgrow tab-bar Priority/ALWAYS)
(add window [tab-bar])
(show window))))
(defn start-router
"Launch the router (blocking)."
[]
(Router/main nil))
(defn -main
"Launch everything."
[& args]
(start-web-server)
(start-browser)
(comment (start-router)))
## Instruction:
Add ability to create tabs.
## Code After:
(ns nightweb.core
(:use nightweb.page
nightweb.browser)
(:import net.i2p.router.Router)
(:gen-class))
(defn start-router
"Launch the router (blocking)."
[]
(Router/main nil))
(defn -main
"Launch everything."
[& args]
(start-web-server)
(start-browser)
(comment (start-router)))
| (ns nightweb.core
- (:use splendid.jfx
+ (:use nightweb.page
- nightweb.page)
? ^^^
+ nightweb.browser)
? ^^^^^ +
- (:import javafx.scene.layout.VBox
- javafx.scene.layout.HBox
- javafx.scene.control.TabPane
- javafx.scene.control.Tab
- javafx.scene.web.WebView
- javafx.scene.layout.Priority
- javafx.scene.control.Button
- javafx.scene.control.TextField
- javafx.geometry.Insets
- net.i2p.router.Router)
? ^^^^^^^^
+ (:import net.i2p.router.Router)
? ^^^^^^^^
(:gen-class))
-
- (defn start-browser
- "Launch the JavaFX browser (non-blocking)."
- []
- (jfx (let [window (VBox.)
- tab-view (VBox.)
- nav-bar (HBox.)
- back-btn (Button. "<-")
- for-btn (Button. "->")
- reload-btn (Button. "Reload")
- url-field (TextField.)
- tab-bar (TabPane.)
- main-tab (Tab. "Main Page")
- add-tab (Tab. "+")
- web-view (WebView.)]
- (.setPadding nav-bar (Insets. 4))
- (.setSpacing nav-bar 2)
- (add nav-bar [back-btn for-btn reload-btn url-field])
- (HBox/setHgrow url-field Priority/ALWAYS)
- (add tab-view [nav-bar web-view])
- (.setClosable add-tab false)
- (.setContent main-tab tab-view)
- (.add (.getTabs tab-bar) main-tab)
- (.add (.getTabs tab-bar) add-tab)
- (.load (.getEngine web-view) "http://localhost:8080")
- (VBox/setVgrow tab-bar Priority/ALWAYS)
- (add window [tab-bar])
- (show window))))
(defn start-router
"Launch the router (blocking)."
[]
(Router/main nil))
(defn -main
"Launch everything."
[& args]
(start-web-server)
(start-browser)
(comment (start-router))) | 43 | 0.796296 | 3 | 40 |
3cd1dda45f536a10a34d5301136f8d244e3dce2b | bokeh/src/main/scala/models/Plots.scala | bokeh/src/main/scala/models/Plots.scala | package io.continuum.bokeh
@model class Plot extends Widget {
object title extends Field[String]("")
title = include[TextProps]
outline = include[LineProps]
object x_range extends Field[Range]
object y_range extends Field[Range]
object extra_x_ranges extends Field[Map[String, Range]]
object extra_y_ranges extends Field[Map[String, Range]]
object x_mapper_type extends Field[String]("auto")
object y_mapper_type extends Field[String]("auto")
object renderers extends Field[List[Renderer]]
object tools extends Field[List[Tool]] with ToolsField
object left extends Field[List[PlotObject]]
object right extends Field[List[PlotObject]]
object above extends Field[List[PlotObject]]
object below extends Field[List[PlotObject]]
object toolbar_location extends Field[Location](Location.Above)
object logo extends Field[Logo](Logo.Normal)
object plot_width extends Field[Int](600)
object plot_height extends Field[Int](600)
def width = plot_width
def height = plot_height
object background_fill extends Field[Color](Color.White)
object border_fill extends Field[Color](Color.White)
object min_border_top extends Field[Int]
object min_border_bottom extends Field[Int]
object min_border_left extends Field[Int]
object min_border_right extends Field[Int]
object min_border extends Field[Int]
object h_symmetry extends Field[Boolean](true)
object v_symmetry extends Field[Boolean](false)
}
| package io.continuum.bokeh
@model class Plot extends Widget {
object title extends Field[String]("")
title = include[TextProps]
outline = include[LineProps]
object x_range extends Field[Range]
object y_range extends Field[Range]
object extra_x_ranges extends Field[Map[String, Range]]
object extra_y_ranges extends Field[Map[String, Range]]
object x_mapper_type extends Field[String]("auto")
object y_mapper_type extends Field[String]("auto")
object renderers extends Field[List[Renderer]]
object tools extends Field[List[Tool]] with ToolsField
object left extends Field[List[Renderer]]
object right extends Field[List[Renderer]]
object above extends Field[List[Renderer]]
object below extends Field[List[Renderer]]
object toolbar_location extends Field[Location](Location.Above)
object logo extends Field[Logo](Logo.Normal)
object plot_width extends Field[Int](600)
object plot_height extends Field[Int](600)
def width = plot_width
def height = plot_height
object background_fill extends Field[Color](Color.White)
object border_fill extends Field[Color](Color.White)
object min_border_top extends Field[Int]
object min_border_bottom extends Field[Int]
object min_border_left extends Field[Int]
object min_border_right extends Field[Int]
object min_border extends Field[Int]
object h_symmetry extends Field[Boolean](true)
object v_symmetry extends Field[Boolean](false)
}
| Use more specific types for Plot.{left,right,above,below} | Use more specific types for Plot.{left,right,above,below}
| Scala | mit | bokeh/bokeh-scala,bokeh/bokeh-scala | scala | ## Code Before:
package io.continuum.bokeh
@model class Plot extends Widget {
object title extends Field[String]("")
title = include[TextProps]
outline = include[LineProps]
object x_range extends Field[Range]
object y_range extends Field[Range]
object extra_x_ranges extends Field[Map[String, Range]]
object extra_y_ranges extends Field[Map[String, Range]]
object x_mapper_type extends Field[String]("auto")
object y_mapper_type extends Field[String]("auto")
object renderers extends Field[List[Renderer]]
object tools extends Field[List[Tool]] with ToolsField
object left extends Field[List[PlotObject]]
object right extends Field[List[PlotObject]]
object above extends Field[List[PlotObject]]
object below extends Field[List[PlotObject]]
object toolbar_location extends Field[Location](Location.Above)
object logo extends Field[Logo](Logo.Normal)
object plot_width extends Field[Int](600)
object plot_height extends Field[Int](600)
def width = plot_width
def height = plot_height
object background_fill extends Field[Color](Color.White)
object border_fill extends Field[Color](Color.White)
object min_border_top extends Field[Int]
object min_border_bottom extends Field[Int]
object min_border_left extends Field[Int]
object min_border_right extends Field[Int]
object min_border extends Field[Int]
object h_symmetry extends Field[Boolean](true)
object v_symmetry extends Field[Boolean](false)
}
## Instruction:
Use more specific types for Plot.{left,right,above,below}
## Code After:
package io.continuum.bokeh
@model class Plot extends Widget {
object title extends Field[String]("")
title = include[TextProps]
outline = include[LineProps]
object x_range extends Field[Range]
object y_range extends Field[Range]
object extra_x_ranges extends Field[Map[String, Range]]
object extra_y_ranges extends Field[Map[String, Range]]
object x_mapper_type extends Field[String]("auto")
object y_mapper_type extends Field[String]("auto")
object renderers extends Field[List[Renderer]]
object tools extends Field[List[Tool]] with ToolsField
object left extends Field[List[Renderer]]
object right extends Field[List[Renderer]]
object above extends Field[List[Renderer]]
object below extends Field[List[Renderer]]
object toolbar_location extends Field[Location](Location.Above)
object logo extends Field[Logo](Logo.Normal)
object plot_width extends Field[Int](600)
object plot_height extends Field[Int](600)
def width = plot_width
def height = plot_height
object background_fill extends Field[Color](Color.White)
object border_fill extends Field[Color](Color.White)
object min_border_top extends Field[Int]
object min_border_bottom extends Field[Int]
object min_border_left extends Field[Int]
object min_border_right extends Field[Int]
object min_border extends Field[Int]
object h_symmetry extends Field[Boolean](true)
object v_symmetry extends Field[Boolean](false)
}
| package io.continuum.bokeh
@model class Plot extends Widget {
object title extends Field[String]("")
title = include[TextProps]
outline = include[LineProps]
object x_range extends Field[Range]
object y_range extends Field[Range]
object extra_x_ranges extends Field[Map[String, Range]]
object extra_y_ranges extends Field[Map[String, Range]]
object x_mapper_type extends Field[String]("auto")
object y_mapper_type extends Field[String]("auto")
object renderers extends Field[List[Renderer]]
object tools extends Field[List[Tool]] with ToolsField
- object left extends Field[List[PlotObject]]
? ^^^^^^^ ^^
+ object left extends Field[List[Renderer]]
? ^ ^^^^^^
- object right extends Field[List[PlotObject]]
? ^^^^^^^ ^^
+ object right extends Field[List[Renderer]]
? ^ ^^^^^^
- object above extends Field[List[PlotObject]]
? ^^^^^^^ ^^
+ object above extends Field[List[Renderer]]
? ^ ^^^^^^
- object below extends Field[List[PlotObject]]
? ^^^^^^^ ^^
+ object below extends Field[List[Renderer]]
? ^ ^^^^^^
object toolbar_location extends Field[Location](Location.Above)
object logo extends Field[Logo](Logo.Normal)
object plot_width extends Field[Int](600)
object plot_height extends Field[Int](600)
def width = plot_width
def height = plot_height
object background_fill extends Field[Color](Color.White)
object border_fill extends Field[Color](Color.White)
object min_border_top extends Field[Int]
object min_border_bottom extends Field[Int]
object min_border_left extends Field[Int]
object min_border_right extends Field[Int]
object min_border extends Field[Int]
object h_symmetry extends Field[Boolean](true)
object v_symmetry extends Field[Boolean](false)
} | 8 | 0.173913 | 4 | 4 |
6bef90ccc8dba65e58a150517ea6e13611152d21 | package.json | package.json | {
"name": "roundtree1",
"private": true,
"scripts": {
"start": "meteor run"
},
"dependencies": {
"autoprefixer": "^6.5.1",
"lodash": "^4.16.4",
"material-ui": "^0.16.0",
"meteor-node-stubs": "^0.2.3",
"normalize.css": "^5.0.0",
"react": "^15.3.2",
"react-addons-css-transition-group": "^15.3.2",
"react-addons-pure-render-mixin": "^15.3.2",
"react-dom": "^15.3.2",
"react-router": "^2.8.1",
"react-tap-event-plugin": "^1.0.0"
}
}
| {
"name": "roundtree1",
"private": true,
"scripts": {
"start": "meteor run"
},
"dependencies": {
"autoprefixer": "^6.5.1",
"aws-sdk": "^2.6.9",
"justifiedGallery": "^3.6.2",
"lodash": "^4.16.4",
"material-ui": "^0.16.0",
"meteor-node-stubs": "^0.2.3",
"normalize.css": "^5.0.0",
"react": "^15.3.2",
"react-addons-css-transition-group": "^15.3.2",
"react-addons-pure-render-mixin": "^15.3.2",
"react-dom": "^15.3.2",
"react-router": "^2.8.1",
"react-tap-event-plugin": "^1.0.0"
}
}
| Add justified gallery and AWS SDK | Add justified gallery and AWS SDK
| JSON | mit | carlosbaraza/roundtree1,carlosbaraza/roundtree1 | json | ## Code Before:
{
"name": "roundtree1",
"private": true,
"scripts": {
"start": "meteor run"
},
"dependencies": {
"autoprefixer": "^6.5.1",
"lodash": "^4.16.4",
"material-ui": "^0.16.0",
"meteor-node-stubs": "^0.2.3",
"normalize.css": "^5.0.0",
"react": "^15.3.2",
"react-addons-css-transition-group": "^15.3.2",
"react-addons-pure-render-mixin": "^15.3.2",
"react-dom": "^15.3.2",
"react-router": "^2.8.1",
"react-tap-event-plugin": "^1.0.0"
}
}
## Instruction:
Add justified gallery and AWS SDK
## Code After:
{
"name": "roundtree1",
"private": true,
"scripts": {
"start": "meteor run"
},
"dependencies": {
"autoprefixer": "^6.5.1",
"aws-sdk": "^2.6.9",
"justifiedGallery": "^3.6.2",
"lodash": "^4.16.4",
"material-ui": "^0.16.0",
"meteor-node-stubs": "^0.2.3",
"normalize.css": "^5.0.0",
"react": "^15.3.2",
"react-addons-css-transition-group": "^15.3.2",
"react-addons-pure-render-mixin": "^15.3.2",
"react-dom": "^15.3.2",
"react-router": "^2.8.1",
"react-tap-event-plugin": "^1.0.0"
}
}
| {
"name": "roundtree1",
"private": true,
"scripts": {
"start": "meteor run"
},
"dependencies": {
"autoprefixer": "^6.5.1",
+ "aws-sdk": "^2.6.9",
+ "justifiedGallery": "^3.6.2",
"lodash": "^4.16.4",
"material-ui": "^0.16.0",
"meteor-node-stubs": "^0.2.3",
"normalize.css": "^5.0.0",
"react": "^15.3.2",
"react-addons-css-transition-group": "^15.3.2",
"react-addons-pure-render-mixin": "^15.3.2",
"react-dom": "^15.3.2",
"react-router": "^2.8.1",
"react-tap-event-plugin": "^1.0.0"
}
} | 2 | 0.1 | 2 | 0 |
926be8c1068bcb7e6d51bcb44a4005b453a312f8 | build.sbt | build.sbt | name := "couchbase-crud-scala-starter"
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.11.1"
libraryDependencies ++= Seq(
cache,
"org.reactivecouchbase" %% "reactivecouchbase-play" % "0.3"
)
resolvers += "ReactiveCouchbase" at "https://raw.github.com/ReactiveCouchbase/repository/master/snapshots" | name := "couchbase-crud-scala-starter"
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.11.1"
libraryDependencies ++= Seq(
cache,
"org.reactivecouchbase" %% "reactivecouchbase-play" % "0.4-SNAPSHOT"
)
resolvers += "ReactiveCouchbase" at "https://raw.github.com/ReactiveCouchbase/repository/master/snapshots" | Update to 0.4 SNAPSHOT and use couchbase.akka | Update to 0.4 SNAPSHOT and use couchbase.akka
| Scala | apache-2.0 | ReactiveCouchbase/play-crud-starter-kit,ReactiveCouchbase/play-crud-starter-kit | scala | ## Code Before:
name := "couchbase-crud-scala-starter"
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.11.1"
libraryDependencies ++= Seq(
cache,
"org.reactivecouchbase" %% "reactivecouchbase-play" % "0.3"
)
resolvers += "ReactiveCouchbase" at "https://raw.github.com/ReactiveCouchbase/repository/master/snapshots"
## Instruction:
Update to 0.4 SNAPSHOT and use couchbase.akka
## Code After:
name := "couchbase-crud-scala-starter"
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.11.1"
libraryDependencies ++= Seq(
cache,
"org.reactivecouchbase" %% "reactivecouchbase-play" % "0.4-SNAPSHOT"
)
resolvers += "ReactiveCouchbase" at "https://raw.github.com/ReactiveCouchbase/repository/master/snapshots" | name := "couchbase-crud-scala-starter"
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.11.1"
libraryDependencies ++= Seq(
cache,
- "org.reactivecouchbase" %% "reactivecouchbase-play" % "0.3"
? ^
+ "org.reactivecouchbase" %% "reactivecouchbase-play" % "0.4-SNAPSHOT"
? ^^^^^^^^^^
)
resolvers += "ReactiveCouchbase" at "https://raw.github.com/ReactiveCouchbase/repository/master/snapshots" | 2 | 0.142857 | 1 | 1 |
66d15addc05fbaae60c02ce7971bd7bd2a0a56d3 | spec/features/logging_a_user_out_feature_spec.rb | spec/features/logging_a_user_out_feature_spec.rb | require 'rails_helper'
require 'capybara/rails'
describe "the log out process", type: :feature do
let!(:user) {create(:user)}
scenario 'logging out the current user' do
visit "/users/#{user.id}"
within ('.navbar') do
click_link '#logout'
end
expect(page).to have_content 'Login'
end
end | require 'rails_helper'
require 'capybara/rails'
require_relative '../support/session_helper.rb'
include SessionHelper
describe "the log out process", type: :feature do
let!(:user) {create(:user)}
scenario 'logging out the current user' do
login(user)
within ('nav') do
click_button 'Logout'
end
expect(page).to have_content 'Login'
end
end
| Add test for logging user out; test passes | Add test for logging user out; test passes
| Ruby | mit | kevmcgovern/EZMeals,kevmcgovern/EZMeals,kevmcgovern/EZMeals | ruby | ## Code Before:
require 'rails_helper'
require 'capybara/rails'
describe "the log out process", type: :feature do
let!(:user) {create(:user)}
scenario 'logging out the current user' do
visit "/users/#{user.id}"
within ('.navbar') do
click_link '#logout'
end
expect(page).to have_content 'Login'
end
end
## Instruction:
Add test for logging user out; test passes
## Code After:
require 'rails_helper'
require 'capybara/rails'
require_relative '../support/session_helper.rb'
include SessionHelper
describe "the log out process", type: :feature do
let!(:user) {create(:user)}
scenario 'logging out the current user' do
login(user)
within ('nav') do
click_button 'Logout'
end
expect(page).to have_content 'Login'
end
end
| require 'rails_helper'
require 'capybara/rails'
+ require_relative '../support/session_helper.rb'
+ include SessionHelper
describe "the log out process", type: :feature do
let!(:user) {create(:user)}
scenario 'logging out the current user' do
- visit "/users/#{user.id}"
+ login(user)
- within ('.navbar') do
? - ---
+ within ('nav') do
- click_link '#logout'
? ^^ - ^^
+ click_button 'Logout'
? ^^^^^ ^
end
expect(page).to have_content 'Login'
end
+
end | 9 | 0.642857 | 6 | 3 |
41f6a8d062932cd5d72b3ac708c55c0164185d64 | dev/linux/filesystem/README.md | dev/linux/filesystem/README.md |
* [Number of files per directory](http://unix.stackexchange.com/questions/3733/number-of-files-per-directory)
* [Maximum number of files/folders on Linux?](http://stackoverflow.com/questions/8238860/maximum-number-of-files-folders-on-linux)
* [Linux数据,做/var党,还是/opt党,还是/usr/local党,还是/home党呢?](https://www.zhihu.com/question/39751723?sort=created)
* [理解 Linux 的硬链接与软链接](https://www.ibm.com/developerworks/cn/linux/l-cn-hardandsymb-links/index.html)
* [第 6 堂課:基礎檔案系統管理](https://linux.vbird.org/linux_basic_train/centos8/unit06.php)
## Aliyun
* [挂载数据盘](https://help.aliyun.com/document_detail/25446.html)
* [分区格式化数据盘(Linux)](https://help.aliyun.com/document_detail/25426.htm)
* [在fstab文件中配置UUID方式自动挂载数据盘](https://help.aliyun.com/document_detail/194379.htm)
|
* [Number of files per directory](http://unix.stackexchange.com/questions/3733/number-of-files-per-directory)
* [Maximum number of files/folders on Linux?](http://stackoverflow.com/questions/8238860/maximum-number-of-files-folders-on-linux)
* [Linux数据,做/var党,还是/opt党,还是/usr/local党,还是/home党呢?](https://www.zhihu.com/question/39751723?sort=created)
* [理解 Linux 的硬链接与软链接](https://www.ibm.com/developerworks/cn/linux/l-cn-hardandsymb-links/index.html)
* [第 6 堂課:基礎檔案系統管理](https://linux.vbird.org/linux_basic_train/centos8/unit06.php)
* [command blkid don't show my partitions UUID](https://stackoverflow.com/questions/30558050/command-blkid-dont-show-my-partitions-uuid)
## Aliyun
* [挂载数据盘](https://help.aliyun.com/document_detail/25446.html)
* [分区格式化数据盘(Linux)](https://help.aliyun.com/document_detail/25426.htm)
* [在fstab文件中配置UUID方式自动挂载数据盘](https://help.aliyun.com/document_detail/194379.htm)
| Add command blkid don't show my partitions UUID | Add command blkid don't show my partitions UUID
| Markdown | mit | northbright/bookmarks,northbright/bookmarks,northbright/bookmarks | markdown | ## Code Before:
* [Number of files per directory](http://unix.stackexchange.com/questions/3733/number-of-files-per-directory)
* [Maximum number of files/folders on Linux?](http://stackoverflow.com/questions/8238860/maximum-number-of-files-folders-on-linux)
* [Linux数据,做/var党,还是/opt党,还是/usr/local党,还是/home党呢?](https://www.zhihu.com/question/39751723?sort=created)
* [理解 Linux 的硬链接与软链接](https://www.ibm.com/developerworks/cn/linux/l-cn-hardandsymb-links/index.html)
* [第 6 堂課:基礎檔案系統管理](https://linux.vbird.org/linux_basic_train/centos8/unit06.php)
## Aliyun
* [挂载数据盘](https://help.aliyun.com/document_detail/25446.html)
* [分区格式化数据盘(Linux)](https://help.aliyun.com/document_detail/25426.htm)
* [在fstab文件中配置UUID方式自动挂载数据盘](https://help.aliyun.com/document_detail/194379.htm)
## Instruction:
Add command blkid don't show my partitions UUID
## Code After:
* [Number of files per directory](http://unix.stackexchange.com/questions/3733/number-of-files-per-directory)
* [Maximum number of files/folders on Linux?](http://stackoverflow.com/questions/8238860/maximum-number-of-files-folders-on-linux)
* [Linux数据,做/var党,还是/opt党,还是/usr/local党,还是/home党呢?](https://www.zhihu.com/question/39751723?sort=created)
* [理解 Linux 的硬链接与软链接](https://www.ibm.com/developerworks/cn/linux/l-cn-hardandsymb-links/index.html)
* [第 6 堂課:基礎檔案系統管理](https://linux.vbird.org/linux_basic_train/centos8/unit06.php)
* [command blkid don't show my partitions UUID](https://stackoverflow.com/questions/30558050/command-blkid-dont-show-my-partitions-uuid)
## Aliyun
* [挂载数据盘](https://help.aliyun.com/document_detail/25446.html)
* [分区格式化数据盘(Linux)](https://help.aliyun.com/document_detail/25426.htm)
* [在fstab文件中配置UUID方式自动挂载数据盘](https://help.aliyun.com/document_detail/194379.htm)
|
* [Number of files per directory](http://unix.stackexchange.com/questions/3733/number-of-files-per-directory)
* [Maximum number of files/folders on Linux?](http://stackoverflow.com/questions/8238860/maximum-number-of-files-folders-on-linux)
* [Linux数据,做/var党,还是/opt党,还是/usr/local党,还是/home党呢?](https://www.zhihu.com/question/39751723?sort=created)
* [理解 Linux 的硬链接与软链接](https://www.ibm.com/developerworks/cn/linux/l-cn-hardandsymb-links/index.html)
* [第 6 堂課:基礎檔案系統管理](https://linux.vbird.org/linux_basic_train/centos8/unit06.php)
+ * [command blkid don't show my partitions UUID](https://stackoverflow.com/questions/30558050/command-blkid-dont-show-my-partitions-uuid)
## Aliyun
* [挂载数据盘](https://help.aliyun.com/document_detail/25446.html)
* [分区格式化数据盘(Linux)](https://help.aliyun.com/document_detail/25426.htm)
* [在fstab文件中配置UUID方式自动挂载数据盘](https://help.aliyun.com/document_detail/194379.htm) | 1 | 0.090909 | 1 | 0 |
97d5b255d44fb9712daca623f19ced95ca35f69b | README.md | README.md | Semver -- python module for semantic versioning
===============================================

Simple module for comparing versions as noted at [semver.org](http://semver.org/).
This module provides just couple of functions, main of which are:
```python
>>> import semver
>>> semver.compare("1.0.0", "2.0.0")
-1
>>> semver.compare("2.0.0", "1.0.0")
1
>>> semver.compare("2.0.0", "2.0.0")
0
>>> semver.match("2.0.0", ">=1.0.0")
True
>>> semver.match("1.0.0", ">1.0.0")
False
```
| Semver -- python module for semantic versioning
===============================================

Simple module for comparing versions as noted at [semver.org](http://semver.org/).
This module provides just couple of functions, main of which are:
```python
>>> import semver
>>> semver.compare("1.0.0", "2.0.0")
-1
>>> semver.compare("2.0.0", "1.0.0")
1
>>> semver.compare("2.0.0", "2.0.0")
0
>>> semver.match("2.0.0", ">=1.0.0")
True
>>> semver.match("1.0.0", ">1.0.0")
False
```
Installation
------------
For Python 2:
```
pip install semver
```
For Python 3:
```
pip3 install semver
```
Homepage at PyPi: https://pypi.python.org/pypi/semver
| Add info on homepage and installation | Add info on homepage and installation
| Markdown | bsd-3-clause | python-semver/python-semver,k-bx/python-semver | markdown | ## Code Before:
Semver -- python module for semantic versioning
===============================================

Simple module for comparing versions as noted at [semver.org](http://semver.org/).
This module provides just couple of functions, main of which are:
```python
>>> import semver
>>> semver.compare("1.0.0", "2.0.0")
-1
>>> semver.compare("2.0.0", "1.0.0")
1
>>> semver.compare("2.0.0", "2.0.0")
0
>>> semver.match("2.0.0", ">=1.0.0")
True
>>> semver.match("1.0.0", ">1.0.0")
False
```
## Instruction:
Add info on homepage and installation
## Code After:
Semver -- python module for semantic versioning
===============================================

Simple module for comparing versions as noted at [semver.org](http://semver.org/).
This module provides just couple of functions, main of which are:
```python
>>> import semver
>>> semver.compare("1.0.0", "2.0.0")
-1
>>> semver.compare("2.0.0", "1.0.0")
1
>>> semver.compare("2.0.0", "2.0.0")
0
>>> semver.match("2.0.0", ">=1.0.0")
True
>>> semver.match("1.0.0", ">1.0.0")
False
```
Installation
------------
For Python 2:
```
pip install semver
```
For Python 3:
```
pip3 install semver
```
Homepage at PyPi: https://pypi.python.org/pypi/semver
| Semver -- python module for semantic versioning
===============================================

Simple module for comparing versions as noted at [semver.org](http://semver.org/).
This module provides just couple of functions, main of which are:
```python
>>> import semver
>>> semver.compare("1.0.0", "2.0.0")
-1
>>> semver.compare("2.0.0", "1.0.0")
1
>>> semver.compare("2.0.0", "2.0.0")
0
>>> semver.match("2.0.0", ">=1.0.0")
True
>>> semver.match("1.0.0", ">1.0.0")
False
```
+
+ Installation
+ ------------
+
+ For Python 2:
+
+ ```
+ pip install semver
+ ```
+
+ For Python 3:
+
+ ```
+ pip3 install semver
+ ```
+
+ Homepage at PyPi: https://pypi.python.org/pypi/semver | 17 | 0.772727 | 17 | 0 |
95a6d4dfc06b9e1f024e34ff98d5182a4560678c | app/controllers/api/json/oembed_controller.rb | app/controllers/api/json/oembed_controller.rb |
class Api::Json::OembedController < Api::ApplicationController
include CartoDB
# Fetch info from the current user orgranization
def show
url = params[:url]
url += '/embed_map'
html = "<iframe width='100%' height='520' frameborder='0' src='#{url}' allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe>"
render json: {
:type => 'url',
:html => html
}.to_json
end
end
|
require 'uri'
class Api::Json::OembedController < Api::ApplicationController
include CartoDB
skip_before_filter :api_authorization_required
# Returns oembed data as required
def show
url = params[:url]
width = params[:maxwidth] || '100%'
height = params[:maxheight] || '100%'
format = request.query_parameters[:format]
uri = URI.parse(url)
if uri.host != request.host
raise ActionController::RoutingError.new('URL origin not allowed')
end
uuid = uri.path.split('/')[-1]
begin
CartoDB::Visualization::Member.new(id: uuid, type: 'derived').fetch
rescue KeyError
raise ActionController::RoutingError.new('Visualization not found: ' + uuid)
end
if public_visualizations_show_path(id: uuid) != uri.path && public_visualizations_show_path(id: uuid) + '/' != uri.path
raise ActionController::RoutingError.new('Wrong URL for visualization: ' + uuid)
end
url = File.join(url, 'embed_map')
html = "<iframe width='#{width}' height='#{height}' frameborder='0' src='#{url}' allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe>"
response_data = {
:type => 'rich',
:version => '1.0',
:width => width,
:height => height,
:html => html
}
if format == 'xml'
render xml: response_data.to_xml(root: 'oembed')
else
render json: response_data.to_json
end
end
end
| Add oEmbed 1.0 support for visualizations | Add oEmbed 1.0 support for visualizations
| Ruby | bsd-3-clause | future-analytics/cartodb,DigitalCoder/cartodb,UCL-ShippingGroup/cartodb-1,bloomberg/cartodb,nyimbi/cartodb,splashblot/dronedb,nuxcode/cartodb,dbirchak/cartodb,future-analytics/cartodb,bloomberg/cartodb,raquel-ucl/cartodb,CartoDB/cartodb,thorncp/cartodb,future-analytics/cartodb,nyimbi/cartodb,UCL-ShippingGroup/cartodb-1,nuxcode/cartodb,DigitalCoder/cartodb,CartoDB/cartodb,DigitalCoder/cartodb,dbirchak/cartodb,bloomberg/cartodb,codeandtheory/cartodb,future-analytics/cartodb,raquel-ucl/cartodb,codeandtheory/cartodb,splashblot/dronedb,dbirchak/cartodb,CartoDB/cartodb,thorncp/cartodb,raquel-ucl/cartodb,raquel-ucl/cartodb,dbirchak/cartodb,nyimbi/cartodb,DigitalCoder/cartodb,nyimbi/cartodb,UCL-ShippingGroup/cartodb-1,CartoDB/cartodb,codeandtheory/cartodb,nuxcode/cartodb,bloomberg/cartodb,bloomberg/cartodb,thorncp/cartodb,splashblot/dronedb,splashblot/dronedb,future-analytics/cartodb,DigitalCoder/cartodb,nuxcode/cartodb,nuxcode/cartodb,splashblot/dronedb,codeandtheory/cartodb,thorncp/cartodb,UCL-ShippingGroup/cartodb-1,raquel-ucl/cartodb,nyimbi/cartodb,UCL-ShippingGroup/cartodb-1,dbirchak/cartodb,codeandtheory/cartodb,CartoDB/cartodb,thorncp/cartodb | ruby | ## Code Before:
class Api::Json::OembedController < Api::ApplicationController
include CartoDB
# Fetch info from the current user orgranization
def show
url = params[:url]
url += '/embed_map'
html = "<iframe width='100%' height='520' frameborder='0' src='#{url}' allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe>"
render json: {
:type => 'url',
:html => html
}.to_json
end
end
## Instruction:
Add oEmbed 1.0 support for visualizations
## Code After:
require 'uri'
class Api::Json::OembedController < Api::ApplicationController
include CartoDB
skip_before_filter :api_authorization_required
# Returns oembed data as required
def show
url = params[:url]
width = params[:maxwidth] || '100%'
height = params[:maxheight] || '100%'
format = request.query_parameters[:format]
uri = URI.parse(url)
if uri.host != request.host
raise ActionController::RoutingError.new('URL origin not allowed')
end
uuid = uri.path.split('/')[-1]
begin
CartoDB::Visualization::Member.new(id: uuid, type: 'derived').fetch
rescue KeyError
raise ActionController::RoutingError.new('Visualization not found: ' + uuid)
end
if public_visualizations_show_path(id: uuid) != uri.path && public_visualizations_show_path(id: uuid) + '/' != uri.path
raise ActionController::RoutingError.new('Wrong URL for visualization: ' + uuid)
end
url = File.join(url, 'embed_map')
html = "<iframe width='#{width}' height='#{height}' frameborder='0' src='#{url}' allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe>"
response_data = {
:type => 'rich',
:version => '1.0',
:width => width,
:height => height,
:html => html
}
if format == 'xml'
render xml: response_data.to_xml(root: 'oembed')
else
render json: response_data.to_json
end
end
end
| +
+ require 'uri'
class Api::Json::OembedController < Api::ApplicationController
include CartoDB
- # Fetch info from the current user orgranization
+ skip_before_filter :api_authorization_required
+
+ # Returns oembed data as required
def show
url = params[:url]
- url += '/embed_map'
+ width = params[:maxwidth] || '100%'
+ height = params[:maxheight] || '100%'
+ format = request.query_parameters[:format]
+
+ uri = URI.parse(url)
+
+ if uri.host != request.host
+ raise ActionController::RoutingError.new('URL origin not allowed')
+ end
+
+ uuid = uri.path.split('/')[-1]
+ begin
+ CartoDB::Visualization::Member.new(id: uuid, type: 'derived').fetch
+ rescue KeyError
+ raise ActionController::RoutingError.new('Visualization not found: ' + uuid)
+ end
+
+ if public_visualizations_show_path(id: uuid) != uri.path && public_visualizations_show_path(id: uuid) + '/' != uri.path
+ raise ActionController::RoutingError.new('Wrong URL for visualization: ' + uuid)
+ end
+
+ url = File.join(url, 'embed_map')
- html = "<iframe width='100%' height='520' frameborder='0' src='#{url}' allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe>"
? ^^^^ ^^^
+ html = "<iframe width='#{width}' height='#{height}' frameborder='0' src='#{url}' allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe>"
? ^^^^^^^^ ^^^^^^^^^
- render json: {
+
+ response_data = {
- :type => 'url',
? - ^
+ :type => 'rich',
? ++ ^^^
+ :version => '1.0',
+ :width => width,
+ :height => height,
- :html => html
+ :html => html
? ++
- }.to_json
+ }
+
+ if format == 'xml'
+ render xml: response_data.to_xml(root: 'oembed')
+ else
+ render json: response_data.to_json
+ end
end
-
-
end | 51 | 3 | 42 | 9 |
66e40525a05c911552ff5ff9792a85044033f497 | lib/whitehall/document_filter/result_set.rb | lib/whitehall/document_filter/result_set.rb | module Whitehall::DocumentFilter
class ResultSet
def initialize(results, page, per_page)
@results = results
@docs = results.is_a?(Hash) ? results['results'] : []
@page = page
@per_page = per_page
end
def merged_results
@docs.map do |doc|
Result.new(doc)
end
end
def paginated
if @docs.empty?
Kaminari.paginate_array([]).page(@page).per(@per_page)
else
Kaminari.paginate_array(merged_results, total_count: @results['total']).page(@page).per(@per_page)
end
end
end
end | module Whitehall::DocumentFilter
class ResultSet
def initialize(results, page, per_page)
@results = results
@docs = results.respond_to?(:[]) ? results['results'] : []
@page = page
@per_page = per_page
end
def merged_results
@docs.map do |doc|
Result.new(doc)
end
end
def paginated
if @docs.empty?
Kaminari.paginate_array([]).page(@page).per(@per_page)
else
Kaminari.paginate_array(merged_results, total_count: @results['total']).page(@page).per(@per_page)
end
end
end
end | Fix broken search results after GDS API Adapters change | Fix broken search results after GDS API Adapters change
The new version of GDS API Adapters changes the type of return values
from API calls. It now returns a GdsApi::Response instead of native
types like Array or Hash. GdsApi::Response quacks like a Hash but it
isn't one.
This switch on the concrete class is a code smell, and changing to
switch on respond_to? is not much of an improvement. I think that this
switch may no longer be needed as we'll always get a hash back, but need
to investigate.
I've added a tech debt story to improve the rummager integration
tests:
https://www.pivotaltracker.com/story/show/60324804
| Ruby | mit | alphagov/whitehall,ggoral/whitehall,YOTOV-LIMITED/whitehall,YOTOV-LIMITED/whitehall,alphagov/whitehall,robinwhittleton/whitehall,askl56/whitehall,hotvulcan/whitehall,alphagov/whitehall,YOTOV-LIMITED/whitehall,hotvulcan/whitehall,robinwhittleton/whitehall,ggoral/whitehall,ggoral/whitehall,askl56/whitehall,hotvulcan/whitehall,YOTOV-LIMITED/whitehall,alphagov/whitehall,robinwhittleton/whitehall,ggoral/whitehall,hotvulcan/whitehall,robinwhittleton/whitehall,askl56/whitehall,askl56/whitehall | ruby | ## Code Before:
module Whitehall::DocumentFilter
class ResultSet
def initialize(results, page, per_page)
@results = results
@docs = results.is_a?(Hash) ? results['results'] : []
@page = page
@per_page = per_page
end
def merged_results
@docs.map do |doc|
Result.new(doc)
end
end
def paginated
if @docs.empty?
Kaminari.paginate_array([]).page(@page).per(@per_page)
else
Kaminari.paginate_array(merged_results, total_count: @results['total']).page(@page).per(@per_page)
end
end
end
end
## Instruction:
Fix broken search results after GDS API Adapters change
The new version of GDS API Adapters changes the type of return values
from API calls. It now returns a GdsApi::Response instead of native
types like Array or Hash. GdsApi::Response quacks like a Hash but it
isn't one.
This switch on the concrete class is a code smell, and changing to
switch on respond_to? is not much of an improvement. I think that this
switch may no longer be needed as we'll always get a hash back, but need
to investigate.
I've added a tech debt story to improve the rummager integration
tests:
https://www.pivotaltracker.com/story/show/60324804
## Code After:
module Whitehall::DocumentFilter
class ResultSet
def initialize(results, page, per_page)
@results = results
@docs = results.respond_to?(:[]) ? results['results'] : []
@page = page
@per_page = per_page
end
def merged_results
@docs.map do |doc|
Result.new(doc)
end
end
def paginated
if @docs.empty?
Kaminari.paginate_array([]).page(@page).per(@per_page)
else
Kaminari.paginate_array(merged_results, total_count: @results['total']).page(@page).per(@per_page)
end
end
end
end | module Whitehall::DocumentFilter
class ResultSet
def initialize(results, page, per_page)
@results = results
- @docs = results.is_a?(Hash) ? results['results'] : []
? ^ ^ ^^^^
+ @docs = results.respond_to?(:[]) ? results['results'] : []
? ^^ ++++ ^^ ^^^
@page = page
@per_page = per_page
end
def merged_results
@docs.map do |doc|
Result.new(doc)
end
end
def paginated
if @docs.empty?
Kaminari.paginate_array([]).page(@page).per(@per_page)
else
Kaminari.paginate_array(merged_results, total_count: @results['total']).page(@page).per(@per_page)
end
end
end
end | 2 | 0.083333 | 1 | 1 |
fa32b0f2dba42ad1c1acb603dd0b38180b27a817 | admin/broadleaf-open-admin-platform/src/main/resources/open_admin_style/templates/fields/asset_lookup.html | admin/broadleaf-open-admin-platform/src/main/resources/open_admin_style/templates/fields/asset_lookup.html | <div class="asset-selector-container">
<div class="field-label inline" th:text="#{${field.friendlyName}}" th:classappend="${field.required ? 'required' : ''}" />
<span class="error" th:errors="*{fields['__${field.name}__'].value}" />
<a class="show-asset-freeform-url" href="#">([[#{Freeform_URL}]])</a>
<br/>
<input type="hidden" class="mediaUrl twelve" th:field="*{fields['__${field.name}__'].value}" th:classappend="${field.required ? 'required' : ''}" />
<img class="thumbnail"
th:if="*{fields['__${field.name}__'].value != null}"
th:src="@{*{fields['__${field.name}__'].value + '?largeAdminThumbnail'}}"
th:attr="data-fullurl=@{*{fields['__${field.name}__'].value}}" />
<img class="thumbnail"
th:unless="*{fields['__${field.name}__'].value != null}" />
<button class="show-asset-selector tiny radius secondary button hover-cursor"
type="button" th:inline="text"
th:attr="data-select-url=@{${'/'+sectionKey+ '/' + entityForm.id + '/chooseAsset'}}">
<i class="icon-camera"></i> [[#{Select_Upload_Image}]]
</button>
</div>
| <div class="asset-selector-container">
<div class="field-label inline" th:text="#{${field.friendlyName}}" th:classappend="${field.required ? 'required' : ''}" />
<span class="error" th:errors="*{fields['__${field.name}__'].value}" />
<a class="show-asset-freeform-url" href="#">([[#{Freeform_URL}]])</a>
<br/>
<input type="hidden" class="mediaUrl twelve" th:field="*{fields['__${field.name}__'].value}" th:classappend="${field.required ? 'required' : ''}" />
<img class="thumbnail"
th:if="*{fields['__${field.name}__'].value != null and fields['__${field.name}__'].value != ''}"
th:src="@{*{fields['__${field.name}__'].value + '?largeAdminThumbnail'}}"
th:attr="data-fullurl=@{*{fields['__${field.name}__'].value}}" />
<img class="thumbnail"
th:unless="*{fields['__${field.name}__'].value != null and fields['__${field.name}__'].value != ''}" />
<button class="show-asset-selector tiny radius secondary button hover-cursor"
type="button" th:inline="text"
th:attr="data-select-url=@{${'/'+sectionKey+ '/' + entityForm.id + '/chooseAsset'}}">
<i class="icon-camera"></i> [[#{Select_Upload_Image}]]
</button>
</div>
| Add safety check against empty strings | Add safety check against empty strings
| HTML | apache-2.0 | cengizhanozcan/BroadleafCommerce,wenmangbo/BroadleafCommerce,ljshj/BroadleafCommerce,TouK/BroadleafCommerce,udayinfy/BroadleafCommerce,macielbombonato/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,caosg/BroadleafCommerce,alextiannus/BroadleafCommerce,lgscofield/BroadleafCommerce,shopizer/BroadleafCommerce,sitexa/BroadleafCommerce,cogitoboy/BroadleafCommerce,TouK/BroadleafCommerce,sitexa/BroadleafCommerce,udayinfy/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,sanlingdd/broadleaf,liqianggao/BroadleafCommerce,alextiannus/BroadleafCommerce,rawbenny/BroadleafCommerce,caosg/BroadleafCommerce,shopizer/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,cogitoboy/BroadleafCommerce,bijukunjummen/BroadleafCommerce,macielbombonato/BroadleafCommerce,passion1014/metaworks_framework,trombka/blc-tmp,wenmangbo/BroadleafCommerce,gengzhengtao/BroadleafCommerce,ljshj/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,gengzhengtao/BroadleafCommerce,trombka/blc-tmp,bijukunjummen/BroadleafCommerce,liqianggao/BroadleafCommerce,rawbenny/BroadleafCommerce,daniellavoie/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,passion1014/metaworks_framework,alextiannus/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,sitexa/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,cogitoboy/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,lgscofield/BroadleafCommerce,TouK/BroadleafCommerce,caosg/BroadleafCommerce,daniellavoie/BroadleafCommerce,zhaorui1/BroadleafCommerce,rawbenny/BroadleafCommerce,sanlingdd/broadleaf,zhaorui1/BroadleafCommerce,lgscofield/BroadleafCommerce,ljshj/BroadleafCommerce,bijukunjummen/BroadleafCommerce,macielbombonato/BroadleafCommerce,shopizer/BroadleafCommerce,cloudbearings/BroadleafCommerce,udayinfy/BroadleafCommerce,passion1014/metaworks_framework,liqianggao/BroadleafCommerce,zhaorui1/BroadleafCommerce,wenmangbo/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,trombka/blc-tmp,daniellavoie/BroadleafCommerce,gengzhengtao/BroadleafCommerce,cloudbearings/BroadleafCommerce,cloudbearings/BroadleafCommerce | html | ## Code Before:
<div class="asset-selector-container">
<div class="field-label inline" th:text="#{${field.friendlyName}}" th:classappend="${field.required ? 'required' : ''}" />
<span class="error" th:errors="*{fields['__${field.name}__'].value}" />
<a class="show-asset-freeform-url" href="#">([[#{Freeform_URL}]])</a>
<br/>
<input type="hidden" class="mediaUrl twelve" th:field="*{fields['__${field.name}__'].value}" th:classappend="${field.required ? 'required' : ''}" />
<img class="thumbnail"
th:if="*{fields['__${field.name}__'].value != null}"
th:src="@{*{fields['__${field.name}__'].value + '?largeAdminThumbnail'}}"
th:attr="data-fullurl=@{*{fields['__${field.name}__'].value}}" />
<img class="thumbnail"
th:unless="*{fields['__${field.name}__'].value != null}" />
<button class="show-asset-selector tiny radius secondary button hover-cursor"
type="button" th:inline="text"
th:attr="data-select-url=@{${'/'+sectionKey+ '/' + entityForm.id + '/chooseAsset'}}">
<i class="icon-camera"></i> [[#{Select_Upload_Image}]]
</button>
</div>
## Instruction:
Add safety check against empty strings
## Code After:
<div class="asset-selector-container">
<div class="field-label inline" th:text="#{${field.friendlyName}}" th:classappend="${field.required ? 'required' : ''}" />
<span class="error" th:errors="*{fields['__${field.name}__'].value}" />
<a class="show-asset-freeform-url" href="#">([[#{Freeform_URL}]])</a>
<br/>
<input type="hidden" class="mediaUrl twelve" th:field="*{fields['__${field.name}__'].value}" th:classappend="${field.required ? 'required' : ''}" />
<img class="thumbnail"
th:if="*{fields['__${field.name}__'].value != null and fields['__${field.name}__'].value != ''}"
th:src="@{*{fields['__${field.name}__'].value + '?largeAdminThumbnail'}}"
th:attr="data-fullurl=@{*{fields['__${field.name}__'].value}}" />
<img class="thumbnail"
th:unless="*{fields['__${field.name}__'].value != null and fields['__${field.name}__'].value != ''}" />
<button class="show-asset-selector tiny radius secondary button hover-cursor"
type="button" th:inline="text"
th:attr="data-select-url=@{${'/'+sectionKey+ '/' + entityForm.id + '/chooseAsset'}}">
<i class="icon-camera"></i> [[#{Select_Upload_Image}]]
</button>
</div>
| <div class="asset-selector-container">
<div class="field-label inline" th:text="#{${field.friendlyName}}" th:classappend="${field.required ? 'required' : ''}" />
<span class="error" th:errors="*{fields['__${field.name}__'].value}" />
<a class="show-asset-freeform-url" href="#">([[#{Freeform_URL}]])</a>
<br/>
<input type="hidden" class="mediaUrl twelve" th:field="*{fields['__${field.name}__'].value}" th:classappend="${field.required ? 'required' : ''}" />
<img class="thumbnail"
- th:if="*{fields['__${field.name}__'].value != null}"
+ th:if="*{fields['__${field.name}__'].value != null and fields['__${field.name}__'].value != ''}"
th:src="@{*{fields['__${field.name}__'].value + '?largeAdminThumbnail'}}"
th:attr="data-fullurl=@{*{fields['__${field.name}__'].value}}" />
<img class="thumbnail"
- th:unless="*{fields['__${field.name}__'].value != null}" />
+ th:unless="*{fields['__${field.name}__'].value != null and fields['__${field.name}__'].value != ''}" />
? ++++++++++++++++++++++++++++++++++++++++++++
<button class="show-asset-selector tiny radius secondary button hover-cursor"
type="button" th:inline="text"
th:attr="data-select-url=@{${'/'+sectionKey+ '/' + entityForm.id + '/chooseAsset'}}">
<i class="icon-camera"></i> [[#{Select_Upload_Image}]]
</button>
</div>
| 4 | 0.16 | 2 | 2 |
f9e084b619c8b511b937e1aa867ac09de264abfe | src/app/store/index.ts | src/app/store/index.ts | import * as fromRouter from '@ngrx/router-store'
import {
ActionReducerMap,
MetaReducer,
createFeatureSelector,
createSelector
} from '@ngrx/store'
import { storeFreeze } from 'ngrx-store-freeze'
import { ENV } from '../../environments/environment'
import { CustomRouterState } from '../shared/utils/custom-router-state-serializer'
export interface State {
router: fromRouter.RouterReducerState<CustomRouterState>
}
export const reducers: ActionReducerMap<State> = {
router: fromRouter.routerReducer
}
export const metaReducers: MetaReducer<{}>[] = !ENV.PROD ? [storeFreeze] : []
export const getRouterState = createFeatureSelector<
fromRouter.RouterReducerState<CustomRouterState>
>('router')
export const getRouterUrl = createSelector(getRouterState, router => {
return router && router.state && router.state.url
})
export const getRouterParams = createSelector(getRouterState, router => {
return router && router.state && router.state.params
})
| import * as fromRouter from '@ngrx/router-store'
import {
ActionReducerMap,
MetaReducer,
createFeatureSelector,
createSelector
} from '@ngrx/store'
import { storeFreeze } from 'ngrx-store-freeze'
import { ENV } from '../../environments/environment'
import { CustomRouterState } from '../shared/utils/custom-router-state-serializer'
export interface State {
router: fromRouter.RouterReducerState<CustomRouterState>
}
export const reducers: ActionReducerMap<State> = {
router: fromRouter.routerReducer
}
export const metaReducers: MetaReducer<{}>[] = !ENV.PROD ? [storeFreeze] : []
export const getRouterState = createFeatureSelector<
fromRouter.RouterReducerState<CustomRouterState>
>('router')
export const getRouterUrl = createSelector(getRouterState, router => {
return router && router.state && router.state.url
})
export const getRouterParams = createSelector(getRouterState, router => {
return router && router.state && router.state.params
})
export const getRouterParamsStudyName = createSelector(
getRouterState,
router => {
return router && router.state && router.state.params['studyName']
}
)
| Add `studyName` selector from route params | Add `studyName` selector from route params
| TypeScript | apache-2.0 | RADAR-CNS/RADAR-Dashboard,RADAR-CNS/RADAR-Dashboard,RADAR-CNS/RADAR-Dashboard,RADAR-CNS/RADAR-Dashboard | typescript | ## Code Before:
import * as fromRouter from '@ngrx/router-store'
import {
ActionReducerMap,
MetaReducer,
createFeatureSelector,
createSelector
} from '@ngrx/store'
import { storeFreeze } from 'ngrx-store-freeze'
import { ENV } from '../../environments/environment'
import { CustomRouterState } from '../shared/utils/custom-router-state-serializer'
export interface State {
router: fromRouter.RouterReducerState<CustomRouterState>
}
export const reducers: ActionReducerMap<State> = {
router: fromRouter.routerReducer
}
export const metaReducers: MetaReducer<{}>[] = !ENV.PROD ? [storeFreeze] : []
export const getRouterState = createFeatureSelector<
fromRouter.RouterReducerState<CustomRouterState>
>('router')
export const getRouterUrl = createSelector(getRouterState, router => {
return router && router.state && router.state.url
})
export const getRouterParams = createSelector(getRouterState, router => {
return router && router.state && router.state.params
})
## Instruction:
Add `studyName` selector from route params
## Code After:
import * as fromRouter from '@ngrx/router-store'
import {
ActionReducerMap,
MetaReducer,
createFeatureSelector,
createSelector
} from '@ngrx/store'
import { storeFreeze } from 'ngrx-store-freeze'
import { ENV } from '../../environments/environment'
import { CustomRouterState } from '../shared/utils/custom-router-state-serializer'
export interface State {
router: fromRouter.RouterReducerState<CustomRouterState>
}
export const reducers: ActionReducerMap<State> = {
router: fromRouter.routerReducer
}
export const metaReducers: MetaReducer<{}>[] = !ENV.PROD ? [storeFreeze] : []
export const getRouterState = createFeatureSelector<
fromRouter.RouterReducerState<CustomRouterState>
>('router')
export const getRouterUrl = createSelector(getRouterState, router => {
return router && router.state && router.state.url
})
export const getRouterParams = createSelector(getRouterState, router => {
return router && router.state && router.state.params
})
export const getRouterParamsStudyName = createSelector(
getRouterState,
router => {
return router && router.state && router.state.params['studyName']
}
)
| import * as fromRouter from '@ngrx/router-store'
import {
ActionReducerMap,
MetaReducer,
createFeatureSelector,
createSelector
} from '@ngrx/store'
import { storeFreeze } from 'ngrx-store-freeze'
import { ENV } from '../../environments/environment'
import { CustomRouterState } from '../shared/utils/custom-router-state-serializer'
export interface State {
router: fromRouter.RouterReducerState<CustomRouterState>
}
export const reducers: ActionReducerMap<State> = {
router: fromRouter.routerReducer
}
export const metaReducers: MetaReducer<{}>[] = !ENV.PROD ? [storeFreeze] : []
export const getRouterState = createFeatureSelector<
fromRouter.RouterReducerState<CustomRouterState>
>('router')
export const getRouterUrl = createSelector(getRouterState, router => {
return router && router.state && router.state.url
})
export const getRouterParams = createSelector(getRouterState, router => {
return router && router.state && router.state.params
})
+
+ export const getRouterParamsStudyName = createSelector(
+ getRouterState,
+ router => {
+ return router && router.state && router.state.params['studyName']
+ }
+ ) | 7 | 0.212121 | 7 | 0 |
38139c31786b6b4b37bfa9a64f30de5487238dcd | system-addon/content-src/components/Topics/_Topics.scss | system-addon/content-src/components/Topics/_Topics.scss | .topic {
$topic-grey: #BFC0C7;
$topic-blue: #008EA4;
font-size: 13px;
color: $topic-grey;
min-width: 780px;
line-height: 16px;
margin-top: $topic-margin-top;
ul {
display: inline;
padding-left: 12px;
}
ul li {
display: inline;
}
ul li::after {
content: '•';
padding-left: 8px;
padding-right: 8px;
}
ul li:last-child::after {
content: none;
}
.topic-link {
color: $topic-blue;
}
.topic-read-more {
float: right;
margin-right: 40px;
color: $topic-blue;
}
.topic-read-more-logo {
padding-right: 10px;
margin-left: 5px;
background-image: url('#{$image-path}topic-show-more-12.svg');
background-repeat: no-repeat;
vertical-align: middle;
}
}
| .topic {
$topic-grey: #BFC0C7;
$topic-blue: #008EA4;
font-size: 13px;
color: $topic-grey;
margin-top: $topic-margin-top;
line-height: 1.6;
@media (min-width: $break-point-large) {
line-height: 16px;
min-width: 780px;
}
ul {
margin: 0;
padding: 0;
@media (min-width: $break-point-large) {
display: inline;
padding-left: 12px;
}
}
ul li {
display: inline-block;
@media (min-width: $break-point-large) {
display: inline;
}
&::after {
content: '•';
padding-left: 8px;
padding-right: 8px;
}
&:last-child::after {
content: none;
}
}
.topic-link {
color: $topic-blue;
}
.topic-read-more {
@media (min-width: $break-point-large) {
margin-right: 40px;
float: right;
}
color: $topic-blue;
}
.topic-read-more-logo {
padding-right: 10px;
margin-left: 5px;
background-image: url('#{$image-path}topic-show-more-12.svg');
background-repeat: no-repeat;
vertical-align: middle;
}
}
| Add responsive styling for Topics | style(mc): Add responsive styling for Topics
| SCSS | mpl-2.0 | sarracini/activity-stream,mozilla/activity-stream,rlr/activity-streams,AdamHillier/activity-stream,Mardak/activity-stream,JaredKerim-Mozilla/activity-stream,mozilla/activity-streams,JaredKerim-Mozilla/activity-stream,rlr/activity-streams,JaredKerim-Mozilla/activity-stream,JaredKerim-Mozilla/activity-stream,sarracini/activity-stream,Mardak/activity-stream,rlr/activity-streams,AdamHillier/activity-stream,sarracini/activity-stream,mozilla/activity-stream,mozilla/activity-streams,Mardak/activity-stream,AdamHillier/activity-stream,mozilla/activity-stream,AdamHillier/activity-stream,Mardak/activity-stream,rlr/activity-streams,sarracini/activity-stream,mozilla/activity-stream | scss | ## Code Before:
.topic {
$topic-grey: #BFC0C7;
$topic-blue: #008EA4;
font-size: 13px;
color: $topic-grey;
min-width: 780px;
line-height: 16px;
margin-top: $topic-margin-top;
ul {
display: inline;
padding-left: 12px;
}
ul li {
display: inline;
}
ul li::after {
content: '•';
padding-left: 8px;
padding-right: 8px;
}
ul li:last-child::after {
content: none;
}
.topic-link {
color: $topic-blue;
}
.topic-read-more {
float: right;
margin-right: 40px;
color: $topic-blue;
}
.topic-read-more-logo {
padding-right: 10px;
margin-left: 5px;
background-image: url('#{$image-path}topic-show-more-12.svg');
background-repeat: no-repeat;
vertical-align: middle;
}
}
## Instruction:
style(mc): Add responsive styling for Topics
## Code After:
.topic {
$topic-grey: #BFC0C7;
$topic-blue: #008EA4;
font-size: 13px;
color: $topic-grey;
margin-top: $topic-margin-top;
line-height: 1.6;
@media (min-width: $break-point-large) {
line-height: 16px;
min-width: 780px;
}
ul {
margin: 0;
padding: 0;
@media (min-width: $break-point-large) {
display: inline;
padding-left: 12px;
}
}
ul li {
display: inline-block;
@media (min-width: $break-point-large) {
display: inline;
}
&::after {
content: '•';
padding-left: 8px;
padding-right: 8px;
}
&:last-child::after {
content: none;
}
}
.topic-link {
color: $topic-blue;
}
.topic-read-more {
@media (min-width: $break-point-large) {
margin-right: 40px;
float: right;
}
color: $topic-blue;
}
.topic-read-more-logo {
padding-right: 10px;
margin-left: 5px;
background-image: url('#{$image-path}topic-show-more-12.svg');
background-repeat: no-repeat;
vertical-align: middle;
}
}
| .topic {
$topic-grey: #BFC0C7;
$topic-blue: #008EA4;
font-size: 13px;
color: $topic-grey;
- min-width: 780px;
- line-height: 16px;
margin-top: $topic-margin-top;
+ line-height: 1.6;
+
+ @media (min-width: $break-point-large) {
+ line-height: 16px;
+ min-width: 780px;
+ }
ul {
+ margin: 0;
+ padding: 0;
+ @media (min-width: $break-point-large) {
- display: inline;
+ display: inline;
? ++
- padding-left: 12px;
+ padding-left: 12px;
? ++
+ }
}
+
ul li {
+ display: inline-block;
+ @media (min-width: $break-point-large) {
- display: inline;
+ display: inline;
? ++
- }
+ }
? ++
-
- ul li::after {
? -- ^^
+ &::after {
? ^^
- content: '•';
+ content: '•';
? ++
- padding-left: 8px;
+ padding-left: 8px;
? ++
- padding-right: 8px;
+ padding-right: 8px;
? ++
- }
+ }
? ++
-
- ul li:last-child::after {
? -- ^^
+ &:last-child::after {
? ^^
- content: none;
+ content: none;
? ++
+ }
}
.topic-link {
color: $topic-blue;
}
.topic-read-more {
- float: right;
+ @media (min-width: $break-point-large) {
- margin-right: 40px;
+ margin-right: 40px;
? ++
+ float: right;
+ }
color: $topic-blue;
}
.topic-read-more-logo {
padding-right: 10px;
margin-left: 5px;
background-image: url('#{$image-path}topic-show-more-12.svg');
background-repeat: no-repeat;
vertical-align: middle;
}
} | 46 | 0.958333 | 29 | 17 |
062d881c1827e8acd688cf10bbbc563dc3bf8d4c | src/main/kotlin/views/ImageView.kt | src/main/kotlin/views/ImageView.kt | package views
import models.Image
import models.Thumbnail
import views.BaseView.baseUrl
import views.BaseView.uriEncode
/**
* Created by allen on 3/30/17.
*/
object ImageView{
fun urlForImageFull(image: Image?): String{
if(image != null){
return "http://photog.alaska.dev/media/images/" + uriEncode(image.path)
}
return ""
}
fun urlForThumbnailMini(thumbnail: Thumbnail?): String{
if(thumbnail != null){
return "http://photog.alaska.dev/media/thumbnails/" + uriEncode(thumbnail.miniThumbnailPath)
}
return ""
}
fun urlForThumbnail(thumbnail: Thumbnail?): String{
if(thumbnail != null){
return "http://photog.alaska.dev/media/thumbnails/" + uriEncode(thumbnail.thumbnailPath)
}
return ""
}
fun urlForImage(image: Image?): String{
if(image != null){
return baseUrl() + "images/" + image.id
}
return ""
}
}
| package views
import models.Image
import models.Thumbnail
import views.BaseView.baseUrl
import views.BaseView.uriEncode
/**
* Created by allen on 3/30/17.
*/
object ImageView{
val ASSET_IMAGE_BASE_URL: String = "http://photog.alaska.dev/media/images/"
val ASSET_THUMBNAIL_BASE_URL: String = "http://photog.alaska.dev/media/thumbnails/"
fun urlForImageFull(image: Image?): String{
if(image != null){
return ASSET_IMAGE_BASE_URL + uriEncode(image.path)
}
return ""
}
fun urlForThumbnailMini(thumbnail: Thumbnail?): String{
if(thumbnail != null){
return ASSET_THUMBNAIL_BASE_URL + uriEncode(thumbnail.miniThumbnailPath)
}
return ""
}
fun urlForThumbnail(thumbnail: Thumbnail?): String{
if(thumbnail != null){
return ASSET_THUMBNAIL_BASE_URL + uriEncode(thumbnail.thumbnailPath)
}
return ""
}
fun urlForImage(image: Image?): String{
if(image != null){
return baseUrl() + "images/" + image.id
}
return ""
}
}
| Refactor thumbnail and photo asset urls to use constants | Refactor thumbnail and photo asset urls to use constants
| Kotlin | mit | allen-garvey/photog-spark,allen-garvey/photog-spark,allen-garvey/photog-spark | kotlin | ## Code Before:
package views
import models.Image
import models.Thumbnail
import views.BaseView.baseUrl
import views.BaseView.uriEncode
/**
* Created by allen on 3/30/17.
*/
object ImageView{
fun urlForImageFull(image: Image?): String{
if(image != null){
return "http://photog.alaska.dev/media/images/" + uriEncode(image.path)
}
return ""
}
fun urlForThumbnailMini(thumbnail: Thumbnail?): String{
if(thumbnail != null){
return "http://photog.alaska.dev/media/thumbnails/" + uriEncode(thumbnail.miniThumbnailPath)
}
return ""
}
fun urlForThumbnail(thumbnail: Thumbnail?): String{
if(thumbnail != null){
return "http://photog.alaska.dev/media/thumbnails/" + uriEncode(thumbnail.thumbnailPath)
}
return ""
}
fun urlForImage(image: Image?): String{
if(image != null){
return baseUrl() + "images/" + image.id
}
return ""
}
}
## Instruction:
Refactor thumbnail and photo asset urls to use constants
## Code After:
package views
import models.Image
import models.Thumbnail
import views.BaseView.baseUrl
import views.BaseView.uriEncode
/**
* Created by allen on 3/30/17.
*/
object ImageView{
val ASSET_IMAGE_BASE_URL: String = "http://photog.alaska.dev/media/images/"
val ASSET_THUMBNAIL_BASE_URL: String = "http://photog.alaska.dev/media/thumbnails/"
fun urlForImageFull(image: Image?): String{
if(image != null){
return ASSET_IMAGE_BASE_URL + uriEncode(image.path)
}
return ""
}
fun urlForThumbnailMini(thumbnail: Thumbnail?): String{
if(thumbnail != null){
return ASSET_THUMBNAIL_BASE_URL + uriEncode(thumbnail.miniThumbnailPath)
}
return ""
}
fun urlForThumbnail(thumbnail: Thumbnail?): String{
if(thumbnail != null){
return ASSET_THUMBNAIL_BASE_URL + uriEncode(thumbnail.thumbnailPath)
}
return ""
}
fun urlForImage(image: Image?): String{
if(image != null){
return baseUrl() + "images/" + image.id
}
return ""
}
}
| package views
import models.Image
import models.Thumbnail
import views.BaseView.baseUrl
import views.BaseView.uriEncode
/**
* Created by allen on 3/30/17.
*/
object ImageView{
+ val ASSET_IMAGE_BASE_URL: String = "http://photog.alaska.dev/media/images/"
+ val ASSET_THUMBNAIL_BASE_URL: String = "http://photog.alaska.dev/media/thumbnails/"
+
fun urlForImageFull(image: Image?): String{
if(image != null){
- return "http://photog.alaska.dev/media/images/" + uriEncode(image.path)
+ return ASSET_IMAGE_BASE_URL + uriEncode(image.path)
}
return ""
}
fun urlForThumbnailMini(thumbnail: Thumbnail?): String{
if(thumbnail != null){
- return "http://photog.alaska.dev/media/thumbnails/" + uriEncode(thumbnail.miniThumbnailPath)
+ return ASSET_THUMBNAIL_BASE_URL + uriEncode(thumbnail.miniThumbnailPath)
}
return ""
}
fun urlForThumbnail(thumbnail: Thumbnail?): String{
if(thumbnail != null){
- return "http://photog.alaska.dev/media/thumbnails/" + uriEncode(thumbnail.thumbnailPath)
+ return ASSET_THUMBNAIL_BASE_URL + uriEncode(thumbnail.thumbnailPath)
}
return ""
}
fun urlForImage(image: Image?): String{
if(image != null){
return baseUrl() + "images/" + image.id
}
return ""
}
} | 9 | 0.225 | 6 | 3 |
d38dfd58acfde1f7f2036934697cf1a6faf7fe48 | README.md | README.md |
```puppet
# Use defaults
# On Debian systems installs and enables service, enables
# check_disk command for root partition and check_apt command
#
include '::nrpe'
```
```puppet
class { '::nrpe':
allowed_hosts => [ '127.0.0.1', '10.0.0.6' ],
commands => {
check_disk_root => {
command => 'check_disk',
args => '-w 20% -c 10% -p /',
},
check_disk_wordpress => {
command => 'check_disk',
args => '-w 20% -c 10% -p /var/lib/wordpress/',
},
check_apt => {
command => 'check_apt',
},
},
}
``` |
```puppet
# Use defaults
# On Debian systems installs and enables service, enables
# check_disk command for root partition and check_apt command
#
include '::nrpe'
```
```puppet
# Monitor / and /var/lib/wordpress mounts, check apt updates
# and allow access from localhost and 10.0.0.6
#
class { '::nrpe':
allowed_hosts => [ '127.0.0.1', '10.0.0.6' ],
commands => {
check_disk_root => {
command => 'check_disk',
args => '-w 20% -c 10% -p /',
},
check_disk_wordpress => {
command => 'check_disk',
args => '-w 20% -c 10% -p /var/lib/wordpress/',
},
check_apt => {
command => 'check_apt',
},
},
}
``` | Add description for second example | Add description for second example
| Markdown | apache-2.0 | node13h/puppet-nrpe | markdown | ## Code Before:
```puppet
# Use defaults
# On Debian systems installs and enables service, enables
# check_disk command for root partition and check_apt command
#
include '::nrpe'
```
```puppet
class { '::nrpe':
allowed_hosts => [ '127.0.0.1', '10.0.0.6' ],
commands => {
check_disk_root => {
command => 'check_disk',
args => '-w 20% -c 10% -p /',
},
check_disk_wordpress => {
command => 'check_disk',
args => '-w 20% -c 10% -p /var/lib/wordpress/',
},
check_apt => {
command => 'check_apt',
},
},
}
```
## Instruction:
Add description for second example
## Code After:
```puppet
# Use defaults
# On Debian systems installs and enables service, enables
# check_disk command for root partition and check_apt command
#
include '::nrpe'
```
```puppet
# Monitor / and /var/lib/wordpress mounts, check apt updates
# and allow access from localhost and 10.0.0.6
#
class { '::nrpe':
allowed_hosts => [ '127.0.0.1', '10.0.0.6' ],
commands => {
check_disk_root => {
command => 'check_disk',
args => '-w 20% -c 10% -p /',
},
check_disk_wordpress => {
command => 'check_disk',
args => '-w 20% -c 10% -p /var/lib/wordpress/',
},
check_apt => {
command => 'check_apt',
},
},
}
``` |
```puppet
# Use defaults
# On Debian systems installs and enables service, enables
# check_disk command for root partition and check_apt command
#
include '::nrpe'
```
```puppet
+ # Monitor / and /var/lib/wordpress mounts, check apt updates
+ # and allow access from localhost and 10.0.0.6
+ #
class { '::nrpe':
allowed_hosts => [ '127.0.0.1', '10.0.0.6' ],
commands => {
check_disk_root => {
command => 'check_disk',
args => '-w 20% -c 10% -p /',
},
check_disk_wordpress => {
command => 'check_disk',
args => '-w 20% -c 10% -p /var/lib/wordpress/',
},
check_apt => {
command => 'check_apt',
},
},
}
``` | 3 | 0.107143 | 3 | 0 |
3c542018cb08530ad7edf51358625a4fe9b8bed8 | plugins/pj/pj.plugin.zsh | plugins/pj/pj.plugin.zsh | alias pjo="pj open"
pj () {
emulate -L zsh
setopt shwordsplit
cmd="cd"
project=$1
if [[ "open" == "$project" ]]; then
shift
project=$*
cmd=$EDITOR
else
project=$*
fi
for basedir ($PROJECT_PATHS); do
if [[ -d "$basedir/$project" ]]; then
$cmd "$basedir/$project"
return
fi
done
echo "No such project '${project}'."
}
_pj () {
emulate -L zsh
typeset -a projects
for basedir ($PROJECT_PATHS); do
projects+=(${basedir}/*(/N))
done
compadd ${projects:t}
}
compdef _pj pj
| alias pjo="pj open"
pj () {
emulate -L zsh
setopt shwordsplit
cmd="cd"
project=$1
if [[ "open" == "$project" ]]; then
shift
project=$*
cmd=$EDITOR
else
project=$*
fi
if [[ -z "$project" ]]; then
echo "You have to specify a project name."
return
fi
for basedir ($PROJECT_PATHS); do
if [[ -d "$basedir/$project" ]]; then
$cmd "$basedir/$project"
return
fi
done
echo "No such project '${project}'."
}
_pj () {
emulate -L zsh
typeset -a projects
for basedir ($PROJECT_PATHS); do
projects+=(${basedir}/*(/N))
done
compadd ${projects:t}
}
compdef _pj pj
| Fix pj() function when no project has been specified | Fix pj() function when no project has been specified
| Shell | mit | tekniklr/oh-my-zsh,tekniklr/oh-my-zsh | shell | ## Code Before:
alias pjo="pj open"
pj () {
emulate -L zsh
setopt shwordsplit
cmd="cd"
project=$1
if [[ "open" == "$project" ]]; then
shift
project=$*
cmd=$EDITOR
else
project=$*
fi
for basedir ($PROJECT_PATHS); do
if [[ -d "$basedir/$project" ]]; then
$cmd "$basedir/$project"
return
fi
done
echo "No such project '${project}'."
}
_pj () {
emulate -L zsh
typeset -a projects
for basedir ($PROJECT_PATHS); do
projects+=(${basedir}/*(/N))
done
compadd ${projects:t}
}
compdef _pj pj
## Instruction:
Fix pj() function when no project has been specified
## Code After:
alias pjo="pj open"
pj () {
emulate -L zsh
setopt shwordsplit
cmd="cd"
project=$1
if [[ "open" == "$project" ]]; then
shift
project=$*
cmd=$EDITOR
else
project=$*
fi
if [[ -z "$project" ]]; then
echo "You have to specify a project name."
return
fi
for basedir ($PROJECT_PATHS); do
if [[ -d "$basedir/$project" ]]; then
$cmd "$basedir/$project"
return
fi
done
echo "No such project '${project}'."
}
_pj () {
emulate -L zsh
typeset -a projects
for basedir ($PROJECT_PATHS); do
projects+=(${basedir}/*(/N))
done
compadd ${projects:t}
}
compdef _pj pj
| alias pjo="pj open"
pj () {
emulate -L zsh
setopt shwordsplit
cmd="cd"
project=$1
if [[ "open" == "$project" ]]; then
shift
project=$*
cmd=$EDITOR
else
project=$*
+ fi
+
+ if [[ -z "$project" ]]; then
+ echo "You have to specify a project name."
+ return
fi
for basedir ($PROJECT_PATHS); do
if [[ -d "$basedir/$project" ]]; then
$cmd "$basedir/$project"
return
fi
done
echo "No such project '${project}'."
}
_pj () {
emulate -L zsh
typeset -a projects
for basedir ($PROJECT_PATHS); do
projects+=(${basedir}/*(/N))
done
compadd ${projects:t}
}
compdef _pj pj | 5 | 0.131579 | 5 | 0 |
4ebaccef127bc830b28e73032a3323699a7a7ebe | Source/pages/repo_update.php | Source/pages/repo_update.php | <?php
# Copyright (C) 2008 John Reese
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
access_ensure_global_level( plugin_config_get( 'manage_threshold' ) );
$f_repo_id = gpc_get_int( 'repo_id' );
$f_repo_name = gpc_get_string( 'repo_name' );
$f_repo_url = gpc_get_string( 'repo_url' );
$t_repo = SourceRepo::load( $f_repo_id );
$t_type = SourceType($t_repo->type);
$t_repo->name = $f_repo_name;
$t_repo->url = $f_repo_url;
$t_repo = event_signal( 'EVENT_SOURCE_UPDATE_REPO', array( $t_repo ) );
$t_repo->save();
print_successful_redirect( plugin_page( 'repo_manage_page', true ) . '&id=' . $t_repo->id );
| <?php
# Copyright (C) 2008 John Reese
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
access_ensure_global_level( plugin_config_get( 'manage_threshold' ) );
$f_repo_id = gpc_get_int( 'repo_id' );
$f_repo_name = gpc_get_string( 'repo_name' );
$f_repo_url = gpc_get_string( 'repo_url' );
$t_repo = SourceRepo::load( $f_repo_id );
$t_type = SourceType($t_repo->type);
$t_repo->name = $f_repo_name;
$t_repo->url = $f_repo_url;
$t_updated_repo = event_signal( 'EVENT_SOURCE_UPDATE_REPO', array( $t_repo ) );
if ( !is_null( $t_updated_repo ) ) {
$t_updated_repo->save();
} else {
$t_repo->save();
}
print_successful_redirect( plugin_page( 'repo_manage_page', true ) . '&id=' . $t_repo->id );
| Fix repo update when null is returned (eg, no plugin has modified the repo). | Fix repo update when null is returned (eg, no plugin has modified the repo).
| PHP | mit | mantisbt-plugins/source-integration,dregad/source-integration,make-all/source-integration,make-all/source-integration,morgant/source-integration,bright-tools/source-integration,dregad/source-integration,mantisbt-plugins/source-integration,01-Scripts/source-integration,dregad/source-integration,bright-tools/source-integration-fixes,bright-tools/source-integration,01-Scripts/source-integration,bright-tools/source-integration,morgant/source-integration,make-all/source-integration,mantisbt-plugins/source-integration,morgant/source-integration,bright-tools/source-integration-fixes,bright-tools/source-integration,bright-tools/source-integration-fixes | php | ## Code Before:
<?php
# Copyright (C) 2008 John Reese
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
access_ensure_global_level( plugin_config_get( 'manage_threshold' ) );
$f_repo_id = gpc_get_int( 'repo_id' );
$f_repo_name = gpc_get_string( 'repo_name' );
$f_repo_url = gpc_get_string( 'repo_url' );
$t_repo = SourceRepo::load( $f_repo_id );
$t_type = SourceType($t_repo->type);
$t_repo->name = $f_repo_name;
$t_repo->url = $f_repo_url;
$t_repo = event_signal( 'EVENT_SOURCE_UPDATE_REPO', array( $t_repo ) );
$t_repo->save();
print_successful_redirect( plugin_page( 'repo_manage_page', true ) . '&id=' . $t_repo->id );
## Instruction:
Fix repo update when null is returned (eg, no plugin has modified the repo).
## Code After:
<?php
# Copyright (C) 2008 John Reese
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
access_ensure_global_level( plugin_config_get( 'manage_threshold' ) );
$f_repo_id = gpc_get_int( 'repo_id' );
$f_repo_name = gpc_get_string( 'repo_name' );
$f_repo_url = gpc_get_string( 'repo_url' );
$t_repo = SourceRepo::load( $f_repo_id );
$t_type = SourceType($t_repo->type);
$t_repo->name = $f_repo_name;
$t_repo->url = $f_repo_url;
$t_updated_repo = event_signal( 'EVENT_SOURCE_UPDATE_REPO', array( $t_repo ) );
if ( !is_null( $t_updated_repo ) ) {
$t_updated_repo->save();
} else {
$t_repo->save();
}
print_successful_redirect( plugin_page( 'repo_manage_page', true ) . '&id=' . $t_repo->id );
| <?php
# Copyright (C) 2008 John Reese
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
access_ensure_global_level( plugin_config_get( 'manage_threshold' ) );
$f_repo_id = gpc_get_int( 'repo_id' );
$f_repo_name = gpc_get_string( 'repo_name' );
$f_repo_url = gpc_get_string( 'repo_url' );
$t_repo = SourceRepo::load( $f_repo_id );
$t_type = SourceType($t_repo->type);
$t_repo->name = $f_repo_name;
$t_repo->url = $f_repo_url;
- $t_repo = event_signal( 'EVENT_SOURCE_UPDATE_REPO', array( $t_repo ) );
+ $t_updated_repo = event_signal( 'EVENT_SOURCE_UPDATE_REPO', array( $t_repo ) );
? ++++++++
+ if ( !is_null( $t_updated_repo ) ) {
+ $t_updated_repo->save();
+ } else {
- $t_repo->save();
+ $t_repo->save();
? +
+ }
print_successful_redirect( plugin_page( 'repo_manage_page', true ) . '&id=' . $t_repo->id );
| 8 | 0.258065 | 6 | 2 |
25d15dfec20a2ce70d30def098d03c74f2ae259a | examples/weather/genbindings.sh | examples/weather/genbindings.sh | PYTHONPATH=../..
export PYTHONPATH
URI='http://ws.cdyne.com/WeatherWS/Weather.asmx?wsdl'
PREFIX='weather'
WSDL="${PREFIX}.wsdl"
if [ ! -f ${WSDL} ] ; then
wget -O ${WSDL} "${URI}"
fi
rm -rf raw
mkdir -p raw
touch raw/__init__.py
../../scripts/pyxbgen \
-m "${PREFIX}" \
-W "${WSDL}" \
-r
#if [ ! -f ${PREFIX}.py ] ; then
# echo "from raw.${PREFIX} import *" > ${PREFIX}.py
#fi
| PYTHONPATH=../..
export PYTHONPATH
URI='http://ws.cdyne.com/WeatherWS/Weather.asmx?wsdl'
PREFIX='weather'
WSDL="${PREFIX}.wsdl"
if [ ! -f ${WSDL} ] ; then
wget -O ${WSDL} "${URI}"
fi
rm -rf raw weather.pyc weather.py
mkdir -p raw
touch raw/__init__.py
../../scripts/pyxbgen \
-m "${PREFIX}" \
-W "${WSDL}" \
-r
#if [ ! -f ${PREFIX}.py ] ; then
# echo "from raw.${PREFIX} import *" > ${PREFIX}.py
#fi
| Remove old versions before testing | Remove old versions before testing
| Shell | apache-2.0 | jonfoster/pyxb2,jonfoster/pyxb-upstream-mirror,jonfoster/pyxb1,CantemoInternal/pyxb,jonfoster/pyxb-upstream-mirror,balanced/PyXB,jonfoster/pyxb-upstream-mirror,balanced/PyXB,jonfoster/pyxb2,pabigot/pyxb,balanced/PyXB,CantemoInternal/pyxb,pabigot/pyxb,jonfoster/pyxb1,jonfoster/pyxb2,CantemoInternal/pyxb | shell | ## Code Before:
PYTHONPATH=../..
export PYTHONPATH
URI='http://ws.cdyne.com/WeatherWS/Weather.asmx?wsdl'
PREFIX='weather'
WSDL="${PREFIX}.wsdl"
if [ ! -f ${WSDL} ] ; then
wget -O ${WSDL} "${URI}"
fi
rm -rf raw
mkdir -p raw
touch raw/__init__.py
../../scripts/pyxbgen \
-m "${PREFIX}" \
-W "${WSDL}" \
-r
#if [ ! -f ${PREFIX}.py ] ; then
# echo "from raw.${PREFIX} import *" > ${PREFIX}.py
#fi
## Instruction:
Remove old versions before testing
## Code After:
PYTHONPATH=../..
export PYTHONPATH
URI='http://ws.cdyne.com/WeatherWS/Weather.asmx?wsdl'
PREFIX='weather'
WSDL="${PREFIX}.wsdl"
if [ ! -f ${WSDL} ] ; then
wget -O ${WSDL} "${URI}"
fi
rm -rf raw weather.pyc weather.py
mkdir -p raw
touch raw/__init__.py
../../scripts/pyxbgen \
-m "${PREFIX}" \
-W "${WSDL}" \
-r
#if [ ! -f ${PREFIX}.py ] ; then
# echo "from raw.${PREFIX} import *" > ${PREFIX}.py
#fi
| PYTHONPATH=../..
export PYTHONPATH
URI='http://ws.cdyne.com/WeatherWS/Weather.asmx?wsdl'
PREFIX='weather'
WSDL="${PREFIX}.wsdl"
if [ ! -f ${WSDL} ] ; then
wget -O ${WSDL} "${URI}"
fi
- rm -rf raw
+ rm -rf raw weather.pyc weather.py
mkdir -p raw
touch raw/__init__.py
../../scripts/pyxbgen \
-m "${PREFIX}" \
-W "${WSDL}" \
-r
#if [ ! -f ${PREFIX}.py ] ; then
# echo "from raw.${PREFIX} import *" > ${PREFIX}.py
#fi | 2 | 0.105263 | 1 | 1 |
200f37345d1a0f3f0693dad8a99bf0676cef3f68 | README.md | README.md | Real-Time Corruptor 3.x
The Real-Time Corruptor for BizHawk is a Dynamic Corruptor for emulated games. It interfaced with the Open Source BizHawk Emulator and works by corrupting data into virtual memory chips of emulated systems. RTC3 Introduces new technologies such as NetCore, the Vector Engine and Virtual Memory Domains.
Features:
- Corrupts in real-time
- Works with all of Bizhawk's emulated systems
- Multiple corruption engines with customizable algorithms
- Easy start option
- Glitch Harvester (Corruption Savestate Manager)
- Blast Editor (Corruption instruction editor)
- Stockpile Player (Corruption replayer)
- As of 3.x, can survive BizHawk crashes using Detached Mode
- The new Pipe Engine can simulate digital short circuits
- The Vector Engine is designed for 3D systems that support IEEE754 Floating Point values
- RTC Multiplayer allows you to corrupt via the internet or locally
- Comes bundled with standalone "Windows Glitch Harvester" for file corruption
Please consult the Official Wiki for software documentation. https://corrupt.wiki
Download link: http://redscientist.com/#/rtcorruptormod
| Real-Time Corruptor 3.x
The Real-Time Corruptor for BizHawk is a Dynamic Corruptor for emulated games. It interfaced with the Open Source BizHawk Emulator and works by corrupting data into virtual memory chips of emulated systems. RTC3 Introduces new technologies such as NetCore, the Vector Engine and Virtual Memory Domains.
Features:
- Corrupts in real-time
- Works with all of Bizhawk's emulated systems
- Multiple corruption engines with customizable algorithms
- Easy start option
- Glitch Harvester (Corruption Savestate Manager)
- Blast Editor (Corruption instruction editor)
- Stockpile Player (Corruption replayer)
- As of 3.x, can survive BizHawk crashes using Detached Mode
- The new Pipe Engine can simulate digital short circuits
- The Vector Engine is designed for 3D systems that support IEEE754 Floating Point values
- RTC Multiplayer allows you to corrupt via the internet or locally
- Comes bundled with standalone "Windows Glitch Harvester" for file corruption (Source available here: https://github.com/ircluzar/WGH)
Please consult the Official Wiki for software documentation. https://corrupt.wiki
Download link: http://redscientist.com/#/rtcorruptormod
| Add the link to the WGH source to the readme | Add the link to the WGH source to the readme | Markdown | mit | ircluzar/RTC3,ircluzar/RTC3,ircluzar/RTC3,ircluzar/RTC3,ircluzar/RTC3,ircluzar/RTC3,ircluzar/RTC3 | markdown | ## Code Before:
Real-Time Corruptor 3.x
The Real-Time Corruptor for BizHawk is a Dynamic Corruptor for emulated games. It interfaced with the Open Source BizHawk Emulator and works by corrupting data into virtual memory chips of emulated systems. RTC3 Introduces new technologies such as NetCore, the Vector Engine and Virtual Memory Domains.
Features:
- Corrupts in real-time
- Works with all of Bizhawk's emulated systems
- Multiple corruption engines with customizable algorithms
- Easy start option
- Glitch Harvester (Corruption Savestate Manager)
- Blast Editor (Corruption instruction editor)
- Stockpile Player (Corruption replayer)
- As of 3.x, can survive BizHawk crashes using Detached Mode
- The new Pipe Engine can simulate digital short circuits
- The Vector Engine is designed for 3D systems that support IEEE754 Floating Point values
- RTC Multiplayer allows you to corrupt via the internet or locally
- Comes bundled with standalone "Windows Glitch Harvester" for file corruption
Please consult the Official Wiki for software documentation. https://corrupt.wiki
Download link: http://redscientist.com/#/rtcorruptormod
## Instruction:
Add the link to the WGH source to the readme
## Code After:
Real-Time Corruptor 3.x
The Real-Time Corruptor for BizHawk is a Dynamic Corruptor for emulated games. It interfaced with the Open Source BizHawk Emulator and works by corrupting data into virtual memory chips of emulated systems. RTC3 Introduces new technologies such as NetCore, the Vector Engine and Virtual Memory Domains.
Features:
- Corrupts in real-time
- Works with all of Bizhawk's emulated systems
- Multiple corruption engines with customizable algorithms
- Easy start option
- Glitch Harvester (Corruption Savestate Manager)
- Blast Editor (Corruption instruction editor)
- Stockpile Player (Corruption replayer)
- As of 3.x, can survive BizHawk crashes using Detached Mode
- The new Pipe Engine can simulate digital short circuits
- The Vector Engine is designed for 3D systems that support IEEE754 Floating Point values
- RTC Multiplayer allows you to corrupt via the internet or locally
- Comes bundled with standalone "Windows Glitch Harvester" for file corruption (Source available here: https://github.com/ircluzar/WGH)
Please consult the Official Wiki for software documentation. https://corrupt.wiki
Download link: http://redscientist.com/#/rtcorruptormod
| Real-Time Corruptor 3.x
The Real-Time Corruptor for BizHawk is a Dynamic Corruptor for emulated games. It interfaced with the Open Source BizHawk Emulator and works by corrupting data into virtual memory chips of emulated systems. RTC3 Introduces new technologies such as NetCore, the Vector Engine and Virtual Memory Domains.
Features:
- Corrupts in real-time
- Works with all of Bizhawk's emulated systems
- Multiple corruption engines with customizable algorithms
- Easy start option
- Glitch Harvester (Corruption Savestate Manager)
- Blast Editor (Corruption instruction editor)
- Stockpile Player (Corruption replayer)
- As of 3.x, can survive BizHawk crashes using Detached Mode
- The new Pipe Engine can simulate digital short circuits
- The Vector Engine is designed for 3D systems that support IEEE754 Floating Point values
- RTC Multiplayer allows you to corrupt via the internet or locally
- - Comes bundled with standalone "Windows Glitch Harvester" for file corruption
+ - Comes bundled with standalone "Windows Glitch Harvester" for file corruption (Source available here: https://github.com/ircluzar/WGH)
Please consult the Official Wiki for software documentation. https://corrupt.wiki
Download link: http://redscientist.com/#/rtcorruptormod | 2 | 0.095238 | 1 | 1 |
363908da14f64a3e0588fa113b496d9696527156 | lib/committee/response_validator.rb | lib/committee/response_validator.rb | module Committee
class ResponseValidator
def initialize(link)
@link = link
# we should eventually move off of validating against parent schema too
# ... this is a Herokuism and not in the specification
schema = link.target_schema || link.parent
@validator = JsonSchema::Validator.new(schema)
end
def call(status, headers, data)
unless status == 204 # 204 No Content
check_content_type!(headers)
end
if @link.rel == "instances" && !@link.target_schema
if !data.is_a?(Array)
raise InvalidResponse, "List endpoints must return an array of objects."
end
# only consider the first object during the validation from here on
# (but only in cases where `targetSchema` is not set)
data = data[0]
end
if !@validator.validate(data)
errors = JsonSchema::SchemaError.aggregate(@validator.errors).join("\n")
raise InvalidResponse, "Invalid response.\n\n#{errors}"
end
end
private
def check_content_type!(headers)
match = [%r{application/json}, %r{application/schema\+json}].any? { |m|
headers["Content-Type"] =~ m
}
unless match
raise Committee::InvalidResponse,
%{"Content-Type" response header must be set to "application/json".}
end
end
end
end
| module Committee
class ResponseValidator
def initialize(link)
@link = link
# we should eventually move off of validating against parent schema too
# ... this is a Herokuism and not in the specification
schema = link.target_schema || link.parent
@validator = JsonSchema::Validator.new(schema)
end
def call(status, headers, data)
unless status == 204 # 204 No Content
check_content_type!(headers)
end
if @link.rel == "instances" && !@link.target_schema
if !data.is_a?(Array)
raise InvalidResponse, "List endpoints must return an array of objects."
end
# only consider the first object during the validation from here on
# (but only in cases where `targetSchema` is not set)
data = data[0]
# if the array was empty, allow it through
return if data == nil
end
if !@validator.validate(data)
errors = JsonSchema::SchemaError.aggregate(@validator.errors).join("\n")
raise InvalidResponse, "Invalid response.\n\n#{errors}"
end
end
private
def check_content_type!(headers)
match = [%r{application/json}, %r{application/schema\+json}].any? { |m|
headers["Content-Type"] =~ m
}
unless match
raise Committee::InvalidResponse,
%{"Content-Type" response header must be set to "application/json".}
end
end
end
end
| Validate successfully if a response was an empty list | Validate successfully if a response was an empty list
| Ruby | mit | incorvia/committee,swalkinshaw/committee,interagent/committee,MobileDevHQ/committee | ruby | ## Code Before:
module Committee
class ResponseValidator
def initialize(link)
@link = link
# we should eventually move off of validating against parent schema too
# ... this is a Herokuism and not in the specification
schema = link.target_schema || link.parent
@validator = JsonSchema::Validator.new(schema)
end
def call(status, headers, data)
unless status == 204 # 204 No Content
check_content_type!(headers)
end
if @link.rel == "instances" && !@link.target_schema
if !data.is_a?(Array)
raise InvalidResponse, "List endpoints must return an array of objects."
end
# only consider the first object during the validation from here on
# (but only in cases where `targetSchema` is not set)
data = data[0]
end
if !@validator.validate(data)
errors = JsonSchema::SchemaError.aggregate(@validator.errors).join("\n")
raise InvalidResponse, "Invalid response.\n\n#{errors}"
end
end
private
def check_content_type!(headers)
match = [%r{application/json}, %r{application/schema\+json}].any? { |m|
headers["Content-Type"] =~ m
}
unless match
raise Committee::InvalidResponse,
%{"Content-Type" response header must be set to "application/json".}
end
end
end
end
## Instruction:
Validate successfully if a response was an empty list
## Code After:
module Committee
class ResponseValidator
def initialize(link)
@link = link
# we should eventually move off of validating against parent schema too
# ... this is a Herokuism and not in the specification
schema = link.target_schema || link.parent
@validator = JsonSchema::Validator.new(schema)
end
def call(status, headers, data)
unless status == 204 # 204 No Content
check_content_type!(headers)
end
if @link.rel == "instances" && !@link.target_schema
if !data.is_a?(Array)
raise InvalidResponse, "List endpoints must return an array of objects."
end
# only consider the first object during the validation from here on
# (but only in cases where `targetSchema` is not set)
data = data[0]
# if the array was empty, allow it through
return if data == nil
end
if !@validator.validate(data)
errors = JsonSchema::SchemaError.aggregate(@validator.errors).join("\n")
raise InvalidResponse, "Invalid response.\n\n#{errors}"
end
end
private
def check_content_type!(headers)
match = [%r{application/json}, %r{application/schema\+json}].any? { |m|
headers["Content-Type"] =~ m
}
unless match
raise Committee::InvalidResponse,
%{"Content-Type" response header must be set to "application/json".}
end
end
end
end
| module Committee
class ResponseValidator
def initialize(link)
@link = link
# we should eventually move off of validating against parent schema too
# ... this is a Herokuism and not in the specification
schema = link.target_schema || link.parent
@validator = JsonSchema::Validator.new(schema)
end
def call(status, headers, data)
unless status == 204 # 204 No Content
check_content_type!(headers)
end
if @link.rel == "instances" && !@link.target_schema
if !data.is_a?(Array)
raise InvalidResponse, "List endpoints must return an array of objects."
end
+
# only consider the first object during the validation from here on
# (but only in cases where `targetSchema` is not set)
data = data[0]
+
+ # if the array was empty, allow it through
+ return if data == nil
end
if !@validator.validate(data)
errors = JsonSchema::SchemaError.aggregate(@validator.errors).join("\n")
raise InvalidResponse, "Invalid response.\n\n#{errors}"
end
end
private
def check_content_type!(headers)
match = [%r{application/json}, %r{application/schema\+json}].any? { |m|
headers["Content-Type"] =~ m
}
unless match
raise Committee::InvalidResponse,
%{"Content-Type" response header must be set to "application/json".}
end
end
end
end | 4 | 0.090909 | 4 | 0 |
cad01c9656ce4c02eccde90642de397ead81ce57 | Komunikator/app/src/main/java/pl/komunikator/komunikator/SearchedUsersAdapter.java | Komunikator/app/src/main/java/pl/komunikator/komunikator/SearchedUsersAdapter.java | package pl.komunikator.komunikator;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import pl.komunikator.komunikator.entity.User;
/**
* Created by adrian on 19.04.2017.
*/
public class SearchedUsersAdapter extends RecyclerView.Adapter<SearchedUsersAdapter.MyViewHolder> {
private List<User> userList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, email;
public ImageView photo;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.contactName);
email = (TextView) view.findViewById(R.id.contactEmail);
photo = (ImageView) view.findViewById(R.id.contactImageView);
}
}
public SearchedUsersAdapter(List<User> userList) {
this.userList = userList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 0;
}
}
| package pl.komunikator.komunikator;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import pl.komunikator.komunikator.entity.User;
/**
* Created by adrian on 19.04.2017.
*/
public class SearchedUsersAdapter extends RecyclerView.Adapter<SearchedUsersAdapter.MyViewHolder> {
private List<User> userList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, email;
public ImageView photo;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.contactName);
email = (TextView) view.findViewById(R.id.contactEmail);
photo = (ImageView) view.findViewById(R.id.contactImageView);
}
}
public SearchedUsersAdapter(List<User> userList) {
this.userList = userList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_searched_user, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
User user = userList.get(position);
holder.name.setText(user.getUsername());
holder.email.setText(user.getEmail());
}
@Override
public int getItemCount() {
return userList.size();
}
}
| Implement the rest of the methods | Implement the rest of the methods
| Java | mit | teneusz/aplikacja_mobilna_komunikator | java | ## Code Before:
package pl.komunikator.komunikator;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import pl.komunikator.komunikator.entity.User;
/**
* Created by adrian on 19.04.2017.
*/
public class SearchedUsersAdapter extends RecyclerView.Adapter<SearchedUsersAdapter.MyViewHolder> {
private List<User> userList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, email;
public ImageView photo;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.contactName);
email = (TextView) view.findViewById(R.id.contactEmail);
photo = (ImageView) view.findViewById(R.id.contactImageView);
}
}
public SearchedUsersAdapter(List<User> userList) {
this.userList = userList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 0;
}
}
## Instruction:
Implement the rest of the methods
## Code After:
package pl.komunikator.komunikator;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import pl.komunikator.komunikator.entity.User;
/**
* Created by adrian on 19.04.2017.
*/
public class SearchedUsersAdapter extends RecyclerView.Adapter<SearchedUsersAdapter.MyViewHolder> {
private List<User> userList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, email;
public ImageView photo;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.contactName);
email = (TextView) view.findViewById(R.id.contactEmail);
photo = (ImageView) view.findViewById(R.id.contactImageView);
}
}
public SearchedUsersAdapter(List<User> userList) {
this.userList = userList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_searched_user, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
User user = userList.get(position);
holder.name.setText(user.getUsername());
holder.email.setText(user.getEmail());
}
@Override
public int getItemCount() {
return userList.size();
}
}
| package pl.komunikator.komunikator;
import android.support.v7.widget.RecyclerView;
+ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import pl.komunikator.komunikator.entity.User;
/**
* Created by adrian on 19.04.2017.
*/
public class SearchedUsersAdapter extends RecyclerView.Adapter<SearchedUsersAdapter.MyViewHolder> {
private List<User> userList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, email;
public ImageView photo;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.contactName);
email = (TextView) view.findViewById(R.id.contactEmail);
photo = (ImageView) view.findViewById(R.id.contactImageView);
}
}
public SearchedUsersAdapter(List<User> userList) {
this.userList = userList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
- return null;
+ View itemView = LayoutInflater.from(parent.getContext())
+ .inflate(R.layout.item_searched_user, parent, false);
+
+ return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
-
+ User user = userList.get(position);
+ holder.name.setText(user.getUsername());
+ holder.email.setText(user.getEmail());
}
@Override
public int getItemCount() {
- return 0;
+ return userList.size();
}
} | 12 | 0.226415 | 9 | 3 |
62b501157ef96a51f128c44037613455801bdb7f | src/discuss/cards.cljs | src/discuss/cards.cljs | (ns discuss.cards
(:require [devcards.core :as dc :refer-macros [defcard defcard-om defcard-om-next dom-node]]
[sablono.core :as html :refer-macros [html]]
[om.next :as om :refer-macros [defui]]
[discuss.parser :as parser]
[discuss.components.search.statements :refer [SearchQuery]]
[discuss.utils.common :as lib]
[discuss.views :as views]))
(enable-console-print!)
(defcard-om discuss
views/main-view
lib/app-state)
(defonce test-data {:foo :bar
:search/results [:foo :bar :baz]})
(defonce devcard-reconciler
(om/reconciler {:state test-data
:parser (om/parser {:read parser/read :mutate parser/mutate})}))
(defcard search-query-card-no-next
(dom-node
(fn [_ node]
(om/add-root! devcard-reconciler SearchQuery node)))
{:inspect-data true})
;; -----------------------------------------------------------------------------
;; Start devcards
(defn main []
;; conditionally start the app based on whether the #main-app-area
;; node is on the page
(when-let [node (.getElementById js/document "main-app-area")]
(.render js/ReactDOM (html [:div "This is working"]) node)))
(main)
| (ns discuss.cards
(:require [devcards.core :as dc :refer-macros [defcard defcard-om defcard-om-next dom-node]]
[sablono.core :as html :refer-macros [html]]
[om.next :as om :refer-macros [defui]]
[discuss.parser :as parser]
[discuss.components.search.statements :refer [SearchQuery Results]]
[discuss.utils.common :as lib]
[discuss.views :as views]))
(enable-console-print!)
(defcard-om discuss
views/main-view
lib/app-state)
(defonce test-data {:foo :bar
:search/results [:foo :bar :baz]})
(defonce devcard-reconciler
(om/reconciler {:state test-data
:parser (om/parser {:read parser/read :mutate parser/mutate})}))
(defcard search-query
(dom-node
(fn [_ node]
(om/add-root! parser/reconciler SearchQuery node)))
{:inspect-data true})
(defcard search-results
(dom-node
(fn [_ node]
(om/add-root! parser/reconciler Results node)))
{:inspect-data true})
;; -----------------------------------------------------------------------------
;; Start devcards
(defn main []
;; conditionally start the app based on whether the #main-app-area
;; node is on the page
(when-let [node (.getElementById js/document "main-app-area")]
(.render js/ReactDOM (html [:div "This is working"]) node)))
(main)
| Add separate card for search-results | Add separate card for search-results
| Clojure | mit | hhucn/discuss,hhucn/discuss | clojure | ## Code Before:
(ns discuss.cards
(:require [devcards.core :as dc :refer-macros [defcard defcard-om defcard-om-next dom-node]]
[sablono.core :as html :refer-macros [html]]
[om.next :as om :refer-macros [defui]]
[discuss.parser :as parser]
[discuss.components.search.statements :refer [SearchQuery]]
[discuss.utils.common :as lib]
[discuss.views :as views]))
(enable-console-print!)
(defcard-om discuss
views/main-view
lib/app-state)
(defonce test-data {:foo :bar
:search/results [:foo :bar :baz]})
(defonce devcard-reconciler
(om/reconciler {:state test-data
:parser (om/parser {:read parser/read :mutate parser/mutate})}))
(defcard search-query-card-no-next
(dom-node
(fn [_ node]
(om/add-root! devcard-reconciler SearchQuery node)))
{:inspect-data true})
;; -----------------------------------------------------------------------------
;; Start devcards
(defn main []
;; conditionally start the app based on whether the #main-app-area
;; node is on the page
(when-let [node (.getElementById js/document "main-app-area")]
(.render js/ReactDOM (html [:div "This is working"]) node)))
(main)
## Instruction:
Add separate card for search-results
## Code After:
(ns discuss.cards
(:require [devcards.core :as dc :refer-macros [defcard defcard-om defcard-om-next dom-node]]
[sablono.core :as html :refer-macros [html]]
[om.next :as om :refer-macros [defui]]
[discuss.parser :as parser]
[discuss.components.search.statements :refer [SearchQuery Results]]
[discuss.utils.common :as lib]
[discuss.views :as views]))
(enable-console-print!)
(defcard-om discuss
views/main-view
lib/app-state)
(defonce test-data {:foo :bar
:search/results [:foo :bar :baz]})
(defonce devcard-reconciler
(om/reconciler {:state test-data
:parser (om/parser {:read parser/read :mutate parser/mutate})}))
(defcard search-query
(dom-node
(fn [_ node]
(om/add-root! parser/reconciler SearchQuery node)))
{:inspect-data true})
(defcard search-results
(dom-node
(fn [_ node]
(om/add-root! parser/reconciler Results node)))
{:inspect-data true})
;; -----------------------------------------------------------------------------
;; Start devcards
(defn main []
;; conditionally start the app based on whether the #main-app-area
;; node is on the page
(when-let [node (.getElementById js/document "main-app-area")]
(.render js/ReactDOM (html [:div "This is working"]) node)))
(main)
| (ns discuss.cards
(:require [devcards.core :as dc :refer-macros [defcard defcard-om defcard-om-next dom-node]]
[sablono.core :as html :refer-macros [html]]
[om.next :as om :refer-macros [defui]]
[discuss.parser :as parser]
- [discuss.components.search.statements :refer [SearchQuery]]
+ [discuss.components.search.statements :refer [SearchQuery Results]]
? ++++++++
[discuss.utils.common :as lib]
[discuss.views :as views]))
(enable-console-print!)
(defcard-om discuss
views/main-view
lib/app-state)
(defonce test-data {:foo :bar
:search/results [:foo :bar :baz]})
(defonce devcard-reconciler
(om/reconciler {:state test-data
:parser (om/parser {:read parser/read :mutate parser/mutate})}))
- (defcard search-query-card-no-next
? -------------
+ (defcard search-query
(dom-node
(fn [_ node]
- (om/add-root! devcard-reconciler SearchQuery node)))
? ^^^^ ^^
+ (om/add-root! parser/reconciler SearchQuery node)))
? ^ ^^^^
+ {:inspect-data true})
+
+ (defcard search-results
+ (dom-node
+ (fn [_ node]
+ (om/add-root! parser/reconciler Results node)))
{:inspect-data true})
;; -----------------------------------------------------------------------------
;; Start devcards
(defn main []
;; conditionally start the app based on whether the #main-app-area
;; node is on the page
(when-let [node (.getElementById js/document "main-app-area")]
(.render js/ReactDOM (html [:div "This is working"]) node)))
(main) | 12 | 0.315789 | 9 | 3 |
53163575d58e11381a01af1ffdca0f7f38e0ba97 | README.md | README.md |
**SoundVane** is a SoundCloud playlist analyzer. It recommends songs you'll love using the playlists you already love, by aggregating SoundCloud's track-based recommendations into a single, clean list of songs to listen to.
#How To Use
Go to http://soundvane.com and paste in a playlist or user url.
|
**SoundVane** is a SoundCloud playlist analyzer. It recommends songs you'll love using the playlists you already love, by aggregating SoundCloud's track-based recommendations into a single, clean list of songs to listen to.
#How To Use
Go to https://soundvane.herokuapp.com and paste in a playlist or user url.
| Change the URL to point directly to the Heroku | Change the URL to point directly to the Heroku | Markdown | apache-2.0 | aaron235/SoundVane,aaron235/SoundVane,aaron235/SoundVane | markdown | ## Code Before:
**SoundVane** is a SoundCloud playlist analyzer. It recommends songs you'll love using the playlists you already love, by aggregating SoundCloud's track-based recommendations into a single, clean list of songs to listen to.
#How To Use
Go to http://soundvane.com and paste in a playlist or user url.
## Instruction:
Change the URL to point directly to the Heroku
## Code After:
**SoundVane** is a SoundCloud playlist analyzer. It recommends songs you'll love using the playlists you already love, by aggregating SoundCloud's track-based recommendations into a single, clean list of songs to listen to.
#How To Use
Go to https://soundvane.herokuapp.com and paste in a playlist or user url.
|
**SoundVane** is a SoundCloud playlist analyzer. It recommends songs you'll love using the playlists you already love, by aggregating SoundCloud's track-based recommendations into a single, clean list of songs to listen to.
#How To Use
- Go to http://soundvane.com and paste in a playlist or user url.
+ Go to https://soundvane.herokuapp.com and paste in a playlist or user url.
? + ++++++++++
| 2 | 0.333333 | 1 | 1 |
b96c549fcdaa39ab03704fa064bd4c6852fb2249 | src/full-observation-widget.js | src/full-observation-widget.js | import createElement from 'virtual-dom/create-element'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import VText from 'virtual-dom/vnode/vtext'
import { getScheduler } from './scheduler-assignment'
export default class FullObservationWidget {
constructor (observation) {
this.type = 'Widget'
this.observation = observation
this.domNode = null
this.vnode = null
this.observationSubscription = null
}
init () {
this.trackObservation()
this.vnode = this.getObservationValue()
this.domNode = createElement(this.vnode)
return this.domNode
}
update (previous, domNode) {
this.domNode = domNode
this.trackObservation()
this.vnode = this.getObservationValue()
patch(domNode, diff(previous.vnode, this.vnode))
previous.destroy()
}
destroy () {
this.observationSubscription.dispose()
this.observationSubscription = null
this.domNode = null
this.vnode = null
}
getObservationValue () {
let value = this.observation.getValue()
if (typeof value === 'string') {
return new VText(value)
} else {
return value
}
}
trackObservation () {
this.observationSubscription = this.observation.onDidChangeValue((newVnode) => {
getScheduler().updateDocument(() => {
if (this.domNode) {
patch(this.domNode, diff(this.vnode, newVnode))
this.vnode = newVnode
}
})
})
}
}
| import createElement from 'virtual-dom/create-element'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import VText from 'virtual-dom/vnode/vtext'
import { getScheduler } from './scheduler-assignment'
export default class FullObservationWidget {
constructor (observation) {
this.type = 'Widget'
this.observation = observation
this.domNode = null
this.vnode = null
this.observationSubscription = null
}
init () {
this.trackObservation()
this.vnode = this.getObservationValue()
this.domNode = createElement(this.vnode)
return this.domNode
}
update (previous, domNode) {
this.domNode = domNode
this.trackObservation()
this.vnode = this.getObservationValue()
patch(domNode, diff(previous.vnode, this.vnode))
previous.destroy()
}
destroy () {
this.observationSubscription.dispose()
this.observationSubscription = null
this.domNode = null
this.vnode = null
}
getObservationValue () {
let value = this.observation.getValue()
if (typeof value === 'string') {
return new VText(value)
} else {
return value
}
}
trackObservation () {
this.observationSubscription = this.observation.onDidChangeValue(() => {
getScheduler().updateDocument(() => {
if (this.domNode) {
let newVnode = this.getObservationValue()
patch(this.domNode, diff(this.vnode, newVnode))
this.vnode = newVnode
}
})
})
}
}
| Convert strings to VText nodes | Convert strings to VText nodes | JavaScript | mit | lee-dohm/etch,atom/etch,nathansobo/etch,smashwilson/etch | javascript | ## Code Before:
import createElement from 'virtual-dom/create-element'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import VText from 'virtual-dom/vnode/vtext'
import { getScheduler } from './scheduler-assignment'
export default class FullObservationWidget {
constructor (observation) {
this.type = 'Widget'
this.observation = observation
this.domNode = null
this.vnode = null
this.observationSubscription = null
}
init () {
this.trackObservation()
this.vnode = this.getObservationValue()
this.domNode = createElement(this.vnode)
return this.domNode
}
update (previous, domNode) {
this.domNode = domNode
this.trackObservation()
this.vnode = this.getObservationValue()
patch(domNode, diff(previous.vnode, this.vnode))
previous.destroy()
}
destroy () {
this.observationSubscription.dispose()
this.observationSubscription = null
this.domNode = null
this.vnode = null
}
getObservationValue () {
let value = this.observation.getValue()
if (typeof value === 'string') {
return new VText(value)
} else {
return value
}
}
trackObservation () {
this.observationSubscription = this.observation.onDidChangeValue((newVnode) => {
getScheduler().updateDocument(() => {
if (this.domNode) {
patch(this.domNode, diff(this.vnode, newVnode))
this.vnode = newVnode
}
})
})
}
}
## Instruction:
Convert strings to VText nodes
## Code After:
import createElement from 'virtual-dom/create-element'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import VText from 'virtual-dom/vnode/vtext'
import { getScheduler } from './scheduler-assignment'
export default class FullObservationWidget {
constructor (observation) {
this.type = 'Widget'
this.observation = observation
this.domNode = null
this.vnode = null
this.observationSubscription = null
}
init () {
this.trackObservation()
this.vnode = this.getObservationValue()
this.domNode = createElement(this.vnode)
return this.domNode
}
update (previous, domNode) {
this.domNode = domNode
this.trackObservation()
this.vnode = this.getObservationValue()
patch(domNode, diff(previous.vnode, this.vnode))
previous.destroy()
}
destroy () {
this.observationSubscription.dispose()
this.observationSubscription = null
this.domNode = null
this.vnode = null
}
getObservationValue () {
let value = this.observation.getValue()
if (typeof value === 'string') {
return new VText(value)
} else {
return value
}
}
trackObservation () {
this.observationSubscription = this.observation.onDidChangeValue(() => {
getScheduler().updateDocument(() => {
if (this.domNode) {
let newVnode = this.getObservationValue()
patch(this.domNode, diff(this.vnode, newVnode))
this.vnode = newVnode
}
})
})
}
}
| import createElement from 'virtual-dom/create-element'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import VText from 'virtual-dom/vnode/vtext'
import { getScheduler } from './scheduler-assignment'
export default class FullObservationWidget {
constructor (observation) {
this.type = 'Widget'
this.observation = observation
this.domNode = null
this.vnode = null
this.observationSubscription = null
}
init () {
this.trackObservation()
this.vnode = this.getObservationValue()
this.domNode = createElement(this.vnode)
return this.domNode
}
update (previous, domNode) {
this.domNode = domNode
this.trackObservation()
this.vnode = this.getObservationValue()
patch(domNode, diff(previous.vnode, this.vnode))
previous.destroy()
}
destroy () {
this.observationSubscription.dispose()
this.observationSubscription = null
this.domNode = null
this.vnode = null
}
getObservationValue () {
let value = this.observation.getValue()
if (typeof value === 'string') {
return new VText(value)
} else {
return value
}
}
trackObservation () {
- this.observationSubscription = this.observation.onDidChangeValue((newVnode) => {
? --------
+ this.observationSubscription = this.observation.onDidChangeValue(() => {
getScheduler().updateDocument(() => {
if (this.domNode) {
+ let newVnode = this.getObservationValue()
patch(this.domNode, diff(this.vnode, newVnode))
this.vnode = newVnode
}
})
})
}
} | 3 | 0.052632 | 2 | 1 |
7676537b084c0af28afd8c769a3766c61600f515 | views/search.jade | views/search.jade | extends layout
block content
.container
include ./includes/searchbar.jade
#query_info
#result_head
h3 Results
#query_head
p
| Your query:
em= query
if results.length == 0
.container
p No results. Please try again!
else
each result in results
.container
.result
.excerpt
ul.default
each highlighted in result.highlight.content
li!= highlighted.replace(/(\r\n|\n|\r)/gm,"")
.source
strong= result.fields.title
br
a(href=result.fields.original_source_url) Source
#pagination_container
.pagination
ul
if currentPage > 1
li.page-prev
a(href='/search?q=' + query + '&page=' + (currentPage - 1)) Prev
li
ul
- var i = 1
while i <= pages + 1
li
if i == currentPage
a.current-page(href='/search?q=' + query + '&page=' + i)= i++
else
a(href='/search?q=' + query + '&page=' + i)= i++
if currentPage < pages
li.page-next
a(href='/search?q=' + query + '&page=' + (currentPage + 1)) Next
| extends layout
block content
.container
include ./includes/searchbar.jade
#query_info
#result_head
h3 Results
#query_head
p
| Your query:
em= query
if results.length == 0
.container
p No results. Please try again!
else
each result in results
.container
.result
.excerpt
ul.default
each highlighted in result.highlight.content
li!= highlighted.replace(/(\r\n|\n|\r)/gm,"")
.source
strong= result.fields.title
br
a(href='#') View Full Text
br
a(href=result.fields.original_source_url) Source
#pagination_container
.pagination
ul
if currentPage > 1
li.page-prev
a(href='/search?q=' + query + '&page=' + (currentPage - 1)) Prev
li
ul
- var i = 1
while i <= pages + 1
li
if i == currentPage
a.current-page(href='/search?q=' + query + '&page=' + i)= i++
else
a(href='/search?q=' + query + '&page=' + i)= i++
if currentPage < pages
li.page-next
a(href='/search?q=' + query + '&page=' + (currentPage + 1)) Next
| Add empty 'View Full Text' link. | Add empty 'View Full Text' link.
| Jade | mit | openchattanooga/chadocs,openchattanooga/chadocs | jade | ## Code Before:
extends layout
block content
.container
include ./includes/searchbar.jade
#query_info
#result_head
h3 Results
#query_head
p
| Your query:
em= query
if results.length == 0
.container
p No results. Please try again!
else
each result in results
.container
.result
.excerpt
ul.default
each highlighted in result.highlight.content
li!= highlighted.replace(/(\r\n|\n|\r)/gm,"")
.source
strong= result.fields.title
br
a(href=result.fields.original_source_url) Source
#pagination_container
.pagination
ul
if currentPage > 1
li.page-prev
a(href='/search?q=' + query + '&page=' + (currentPage - 1)) Prev
li
ul
- var i = 1
while i <= pages + 1
li
if i == currentPage
a.current-page(href='/search?q=' + query + '&page=' + i)= i++
else
a(href='/search?q=' + query + '&page=' + i)= i++
if currentPage < pages
li.page-next
a(href='/search?q=' + query + '&page=' + (currentPage + 1)) Next
## Instruction:
Add empty 'View Full Text' link.
## Code After:
extends layout
block content
.container
include ./includes/searchbar.jade
#query_info
#result_head
h3 Results
#query_head
p
| Your query:
em= query
if results.length == 0
.container
p No results. Please try again!
else
each result in results
.container
.result
.excerpt
ul.default
each highlighted in result.highlight.content
li!= highlighted.replace(/(\r\n|\n|\r)/gm,"")
.source
strong= result.fields.title
br
a(href='#') View Full Text
br
a(href=result.fields.original_source_url) Source
#pagination_container
.pagination
ul
if currentPage > 1
li.page-prev
a(href='/search?q=' + query + '&page=' + (currentPage - 1)) Prev
li
ul
- var i = 1
while i <= pages + 1
li
if i == currentPage
a.current-page(href='/search?q=' + query + '&page=' + i)= i++
else
a(href='/search?q=' + query + '&page=' + i)= i++
if currentPage < pages
li.page-next
a(href='/search?q=' + query + '&page=' + (currentPage + 1)) Next
| extends layout
block content
.container
include ./includes/searchbar.jade
#query_info
#result_head
h3 Results
#query_head
p
| Your query:
em= query
if results.length == 0
.container
p No results. Please try again!
else
each result in results
.container
.result
.excerpt
ul.default
each highlighted in result.highlight.content
li!= highlighted.replace(/(\r\n|\n|\r)/gm,"")
.source
strong= result.fields.title
br
+ a(href='#') View Full Text
+ br
a(href=result.fields.original_source_url) Source
#pagination_container
.pagination
ul
if currentPage > 1
li.page-prev
a(href='/search?q=' + query + '&page=' + (currentPage - 1)) Prev
li
ul
- var i = 1
while i <= pages + 1
li
if i == currentPage
a.current-page(href='/search?q=' + query + '&page=' + i)= i++
else
a(href='/search?q=' + query + '&page=' + i)= i++
if currentPage < pages
li.page-next
a(href='/search?q=' + query + '&page=' + (currentPage + 1)) Next
| 2 | 0.042553 | 2 | 0 |
56705fd862579d32c357e28e75c6c582804a4cf5 | wercker.yml | wercker.yml | box: wercker/nodejs@1.4.0
build:
steps:
- script:
name: "Don't actually run any tests"
code: "echo lol"
deploy:
steps:
- grampajoe/opsworks-deploy:
key-id: $AWS_ACCESS_KEY_ID
key-secret: $AWS_SECRET_ACCESS_KEY
stack-id: $AWS_OPSWORKS_STACK_ID
app-id: $AWS_OPSWORKS_APP_ID
migrate: false
wait-for-deploy: true
| box: node:7.4
build:
steps:
- script:
name: "Don't actually run any tests"
code: "echo lol"
deploy:
steps:
- grampajoe/opsworks-deploy:
key-id: $AWS_ACCESS_KEY_ID
key-secret: $AWS_SECRET_ACCESS_KEY
stack-id: $AWS_OPSWORKS_STACK_ID
app-id: $AWS_OPSWORKS_APP_ID
migrate: false
wait-for-deploy: true
| Migrate to new Wercker stack | Migrate to new Wercker stack | YAML | isc | grampajoe/opsworks-test-app | yaml | ## Code Before:
box: wercker/nodejs@1.4.0
build:
steps:
- script:
name: "Don't actually run any tests"
code: "echo lol"
deploy:
steps:
- grampajoe/opsworks-deploy:
key-id: $AWS_ACCESS_KEY_ID
key-secret: $AWS_SECRET_ACCESS_KEY
stack-id: $AWS_OPSWORKS_STACK_ID
app-id: $AWS_OPSWORKS_APP_ID
migrate: false
wait-for-deploy: true
## Instruction:
Migrate to new Wercker stack
## Code After:
box: node:7.4
build:
steps:
- script:
name: "Don't actually run any tests"
code: "echo lol"
deploy:
steps:
- grampajoe/opsworks-deploy:
key-id: $AWS_ACCESS_KEY_ID
key-secret: $AWS_SECRET_ACCESS_KEY
stack-id: $AWS_OPSWORKS_STACK_ID
app-id: $AWS_OPSWORKS_APP_ID
migrate: false
wait-for-deploy: true
| - box: wercker/nodejs@1.4.0
+ box: node:7.4
build:
steps:
- script:
name: "Don't actually run any tests"
code: "echo lol"
deploy:
steps:
- grampajoe/opsworks-deploy:
key-id: $AWS_ACCESS_KEY_ID
key-secret: $AWS_SECRET_ACCESS_KEY
stack-id: $AWS_OPSWORKS_STACK_ID
app-id: $AWS_OPSWORKS_APP_ID
migrate: false
wait-for-deploy: true | 2 | 0.133333 | 1 | 1 |
ed41dcbe7407f11655a0d20d1d44ffee509445dc | CLI/ComputeMeanShapes/CMakeLists.txt | CLI/ComputeMeanShapes/CMakeLists.txt | set(MODULE_NAME computeMean)
#-----------------------------------------------------------------------------
# SlicerExecutionModel
find_package(SlicerExecutionModel REQUIRED)
include(${SlicerExecutionModel_USE_FILE})
#Find VTK Package
find_package(VTK REQUIRED)
include(${VTK_USE_FILE})
#-----------------------------------------------------------------------------
set(MODULE_INCLUDE_DIRECTORIES
)
set(MODULE_SRCS
)
set(MODULE_TARGET_LIBRARIES
${ITK_LIBRARIES}
)
#-----------------------------------------------------------------------------
SEMMacroBuildCLI(
NAME ${MODULE_NAME}
TARGET_LIBRARIES ${MODULE_TARGET_LIBRARIES}
INCLUDE_DIRECTORIES ${MODULE_INCLUDE_DIRECTORIES}
ADDITIONAL_SRCS ${MODULE_SRCS}
) | set(MODULE_NAME computeMean)
#-----------------------------------------------------------------------------
# SlicerExecutionModel
find_package(SlicerExecutionModel REQUIRED)
include(${SlicerExecutionModel_USE_FILE})
#Find VTK Package
find_package(VTK REQUIRED)
include(${VTK_USE_FILE})
#-----------------------------------------------------------------------------
set(MODULE_INCLUDE_DIRECTORIES
include
)
set(MODULE_SRCS
)
set(MODULE_TARGET_LIBRARIES
${ITK_LIBRARIES}
)
#-----------------------------------------------------------------------------
SEMMacroBuildCLI(
NAME ${MODULE_NAME}
TARGET_LIBRARIES ${MODULE_TARGET_LIBRARIES}
INCLUDE_DIRECTORIES ${MODULE_INCLUDE_DIRECTORIES}
ADDITIONAL_SRCS ${MODULE_SRCS}
)
| Fix Windows dirent.h include issue | COMP: Fix Windows dirent.h include issue | Text | apache-2.0 | DCBIA-OrthoLab/ShapeVariationAnalyzer,pdedumast/ShapeVariationAnalyzer,DCBIA-OrthoLab/ShapeVariationAnalyzer,DCBIA-OrthoLab/ShapeVariationAnalyzer,pdedumast/ShapeVariationAnalyzer | text | ## Code Before:
set(MODULE_NAME computeMean)
#-----------------------------------------------------------------------------
# SlicerExecutionModel
find_package(SlicerExecutionModel REQUIRED)
include(${SlicerExecutionModel_USE_FILE})
#Find VTK Package
find_package(VTK REQUIRED)
include(${VTK_USE_FILE})
#-----------------------------------------------------------------------------
set(MODULE_INCLUDE_DIRECTORIES
)
set(MODULE_SRCS
)
set(MODULE_TARGET_LIBRARIES
${ITK_LIBRARIES}
)
#-----------------------------------------------------------------------------
SEMMacroBuildCLI(
NAME ${MODULE_NAME}
TARGET_LIBRARIES ${MODULE_TARGET_LIBRARIES}
INCLUDE_DIRECTORIES ${MODULE_INCLUDE_DIRECTORIES}
ADDITIONAL_SRCS ${MODULE_SRCS}
)
## Instruction:
COMP: Fix Windows dirent.h include issue
## Code After:
set(MODULE_NAME computeMean)
#-----------------------------------------------------------------------------
# SlicerExecutionModel
find_package(SlicerExecutionModel REQUIRED)
include(${SlicerExecutionModel_USE_FILE})
#Find VTK Package
find_package(VTK REQUIRED)
include(${VTK_USE_FILE})
#-----------------------------------------------------------------------------
set(MODULE_INCLUDE_DIRECTORIES
include
)
set(MODULE_SRCS
)
set(MODULE_TARGET_LIBRARIES
${ITK_LIBRARIES}
)
#-----------------------------------------------------------------------------
SEMMacroBuildCLI(
NAME ${MODULE_NAME}
TARGET_LIBRARIES ${MODULE_TARGET_LIBRARIES}
INCLUDE_DIRECTORIES ${MODULE_INCLUDE_DIRECTORIES}
ADDITIONAL_SRCS ${MODULE_SRCS}
)
| set(MODULE_NAME computeMean)
#-----------------------------------------------------------------------------
# SlicerExecutionModel
find_package(SlicerExecutionModel REQUIRED)
include(${SlicerExecutionModel_USE_FILE})
#Find VTK Package
find_package(VTK REQUIRED)
include(${VTK_USE_FILE})
#-----------------------------------------------------------------------------
set(MODULE_INCLUDE_DIRECTORIES
+ include
)
set(MODULE_SRCS
)
set(MODULE_TARGET_LIBRARIES
${ITK_LIBRARIES}
)
#-----------------------------------------------------------------------------
SEMMacroBuildCLI(
NAME ${MODULE_NAME}
TARGET_LIBRARIES ${MODULE_TARGET_LIBRARIES}
INCLUDE_DIRECTORIES ${MODULE_INCLUDE_DIRECTORIES}
ADDITIONAL_SRCS ${MODULE_SRCS}
) | 1 | 0.033333 | 1 | 0 |
e625b68f99207b26142766511c7424b996fb57a3 | README.md | README.md | Provides a custom extended PostgreSQL dialect for Hibernate 4.x
Currently it constists only of a fix for mapping the native `java.util.UUID` to the `pg-uuid` type without adding
JPA's `@Type` annotation at entity field level. This will be fixed as soon as Hibernate 5.x is released (and can
be used in your project). For further information also see [HH-9562](https://hibernate.atlassian.net/browse/HHH-9562).
[](https://travis-ci.org/xpensum/hibernate-postgresql-patch)
## Usage
Use `de.cpg.oss.hibernate.CustomPostgreSQL9Dialect` instead of standard `org.hibernate.dialect.PostgreSQL9Dialect`
in your application's hibernate configuration an you're done.
## Download
Binaries will be available on maven central with following GAV:
- groupId: `de.cpg.oss`
- artifactId: `hibernate-postgresql-patch`
- version: `1.0.0`
| Provides a custom extended PostgreSQL dialect for Hibernate 4.x
Currently it constists only of a fix for mapping the native `java.util.UUID` to the `pg-uuid` type without adding
JPA's `@Type` annotation at entity field level. This will be fixed as soon as Hibernate 5.x is released (and can
be used in your project). For further information also see [HH-9562](https://hibernate.atlassian.net/browse/HHH-9562).
[]
(https://travis-ci.org/CPGFinanceSystems/hibernate-postgresql-patch)
## Usage
Use `de.cpg.oss.hibernate.CustomPostgreSQL9Dialect` instead of standard `org.hibernate.dialect.PostgreSQL9Dialect`
in your application's hibernate configuration an you're done.
## Download
Binaries will be available on maven central with following GAV:
- groupId: `de.cpg.oss`
- artifactId: `hibernate-postgresql-patch`
- version: `1.0.0`
| Fix Travis-CI badge URL after move to another organization on GitHub | Fix Travis-CI badge URL after move to another organization on GitHub
| Markdown | mit | CPGFinanceSystems/hibernate-postgresql-patch | markdown | ## Code Before:
Provides a custom extended PostgreSQL dialect for Hibernate 4.x
Currently it constists only of a fix for mapping the native `java.util.UUID` to the `pg-uuid` type without adding
JPA's `@Type` annotation at entity field level. This will be fixed as soon as Hibernate 5.x is released (and can
be used in your project). For further information also see [HH-9562](https://hibernate.atlassian.net/browse/HHH-9562).
[](https://travis-ci.org/xpensum/hibernate-postgresql-patch)
## Usage
Use `de.cpg.oss.hibernate.CustomPostgreSQL9Dialect` instead of standard `org.hibernate.dialect.PostgreSQL9Dialect`
in your application's hibernate configuration an you're done.
## Download
Binaries will be available on maven central with following GAV:
- groupId: `de.cpg.oss`
- artifactId: `hibernate-postgresql-patch`
- version: `1.0.0`
## Instruction:
Fix Travis-CI badge URL after move to another organization on GitHub
## Code After:
Provides a custom extended PostgreSQL dialect for Hibernate 4.x
Currently it constists only of a fix for mapping the native `java.util.UUID` to the `pg-uuid` type without adding
JPA's `@Type` annotation at entity field level. This will be fixed as soon as Hibernate 5.x is released (and can
be used in your project). For further information also see [HH-9562](https://hibernate.atlassian.net/browse/HHH-9562).
[]
(https://travis-ci.org/CPGFinanceSystems/hibernate-postgresql-patch)
## Usage
Use `de.cpg.oss.hibernate.CustomPostgreSQL9Dialect` instead of standard `org.hibernate.dialect.PostgreSQL9Dialect`
in your application's hibernate configuration an you're done.
## Download
Binaries will be available on maven central with following GAV:
- groupId: `de.cpg.oss`
- artifactId: `hibernate-postgresql-patch`
- version: `1.0.0`
| Provides a custom extended PostgreSQL dialect for Hibernate 4.x
Currently it constists only of a fix for mapping the native `java.util.UUID` to the `pg-uuid` type without adding
JPA's `@Type` annotation at entity field level. This will be fixed as soon as Hibernate 5.x is released (and can
be used in your project). For further information also see [HH-9562](https://hibernate.atlassian.net/browse/HHH-9562).
- [](https://travis-ci.org/xpensum/hibernate-postgresql-patch)
+ []
+ (https://travis-ci.org/CPGFinanceSystems/hibernate-postgresql-patch)
## Usage
Use `de.cpg.oss.hibernate.CustomPostgreSQL9Dialect` instead of standard `org.hibernate.dialect.PostgreSQL9Dialect`
in your application's hibernate configuration an you're done.
## Download
Binaries will be available on maven central with following GAV:
- groupId: `de.cpg.oss`
- artifactId: `hibernate-postgresql-patch`
- version: `1.0.0` | 3 | 0.15 | 2 | 1 |
22782283e14a36635969d8b2011b484d54cbab3c | home/.emacs.d/lisp/init-flycheck.el | home/.emacs.d/lisp/init-flycheck.el | ;;; init-flycheck.el -- Flycheck setup
;;; Commentary:
;;; Load Flycheck and define custom checkers
;;; Code:
(use-package flycheck
:config
(flycheck-def-config-file-var flycheck-haml-lintrc haml-lint ".haml-lint.yml"
:safe #'stringp)
(flycheck-define-checker haml-lint
"Haml style checker using haml-lint
See URL https://github.com/brigade/haml-lint"
:command ("~/haml-lint.sh"
(config-file "--config" flycheck-haml-lintrc)
source)
:error-patterns
((warning line-start
(file-name) ":" line " [W] " (message)
line-end))
:modes (haml-mode))
(add-to-list 'flycheck-checkers 'haml-lint)
:init
(add-hook 'after-init-hook #'global-flycheck-mode)
:diminish flycheck-mode)
(provide 'init-flycheck)
;;; init-flycheck.el ends here
| ;;; init-flycheck.el -- Flycheck setup
;;; Commentary:
;;; Load Flycheck and define custom checkers
;;; Code:
(use-package flycheck
:config
(flycheck-def-config-file-var flycheck-haml-lintrc haml-lint ".haml-lint.yml" :safe #'stringp)
(flycheck-define-checker haml-lint
"Haml style checker using haml-lint
See URL https://github.com/brigade/haml-lint"
:command ("~/haml-lint.sh"
(config-file "--config" flycheck-haml-lintrc)
source)
:error-patterns
((warning line-start
(file-name) ":" line " [W] " (message)
line-end))
:modes (haml-mode))
(add-to-list 'flycheck-checkers 'haml-lint)
(bind-key "s-f" (defhydra flycheck-hydra ()
"errors"
("n" flycheck-next-error "next")
("p" flycheck-previous-error "previous")
("q" nil "quit"))
flycheck-mode-map)
:init
(add-hook 'after-init-hook #'global-flycheck-mode)
:diminish flycheck-mode)
(provide 'init-flycheck)
;;; init-flycheck.el ends here
| Add a hydra to Flycheck | Add a hydra to Flycheck
| Emacs Lisp | mit | cartolari/dotfiles,cartolari/dotfiles,cartolari/dotfiles,cartolari/dotfiles | emacs-lisp | ## Code Before:
;;; init-flycheck.el -- Flycheck setup
;;; Commentary:
;;; Load Flycheck and define custom checkers
;;; Code:
(use-package flycheck
:config
(flycheck-def-config-file-var flycheck-haml-lintrc haml-lint ".haml-lint.yml"
:safe #'stringp)
(flycheck-define-checker haml-lint
"Haml style checker using haml-lint
See URL https://github.com/brigade/haml-lint"
:command ("~/haml-lint.sh"
(config-file "--config" flycheck-haml-lintrc)
source)
:error-patterns
((warning line-start
(file-name) ":" line " [W] " (message)
line-end))
:modes (haml-mode))
(add-to-list 'flycheck-checkers 'haml-lint)
:init
(add-hook 'after-init-hook #'global-flycheck-mode)
:diminish flycheck-mode)
(provide 'init-flycheck)
;;; init-flycheck.el ends here
## Instruction:
Add a hydra to Flycheck
## Code After:
;;; init-flycheck.el -- Flycheck setup
;;; Commentary:
;;; Load Flycheck and define custom checkers
;;; Code:
(use-package flycheck
:config
(flycheck-def-config-file-var flycheck-haml-lintrc haml-lint ".haml-lint.yml" :safe #'stringp)
(flycheck-define-checker haml-lint
"Haml style checker using haml-lint
See URL https://github.com/brigade/haml-lint"
:command ("~/haml-lint.sh"
(config-file "--config" flycheck-haml-lintrc)
source)
:error-patterns
((warning line-start
(file-name) ":" line " [W] " (message)
line-end))
:modes (haml-mode))
(add-to-list 'flycheck-checkers 'haml-lint)
(bind-key "s-f" (defhydra flycheck-hydra ()
"errors"
("n" flycheck-next-error "next")
("p" flycheck-previous-error "previous")
("q" nil "quit"))
flycheck-mode-map)
:init
(add-hook 'after-init-hook #'global-flycheck-mode)
:diminish flycheck-mode)
(provide 'init-flycheck)
;;; init-flycheck.el ends here
| ;;; init-flycheck.el -- Flycheck setup
;;; Commentary:
;;; Load Flycheck and define custom checkers
;;; Code:
(use-package flycheck
:config
- (flycheck-def-config-file-var flycheck-haml-lintrc haml-lint ".haml-lint.yml"
+ (flycheck-def-config-file-var flycheck-haml-lintrc haml-lint ".haml-lint.yml" :safe #'stringp)
? +++++++++++++++++
- :safe #'stringp)
(flycheck-define-checker haml-lint
"Haml style checker using haml-lint
See URL https://github.com/brigade/haml-lint"
:command ("~/haml-lint.sh"
(config-file "--config" flycheck-haml-lintrc)
source)
:error-patterns
((warning line-start
(file-name) ":" line " [W] " (message)
line-end))
:modes (haml-mode))
(add-to-list 'flycheck-checkers 'haml-lint)
+ (bind-key "s-f" (defhydra flycheck-hydra ()
+ "errors"
+ ("n" flycheck-next-error "next")
+ ("p" flycheck-previous-error "previous")
+ ("q" nil "quit"))
+ flycheck-mode-map)
:init
(add-hook 'after-init-hook #'global-flycheck-mode)
:diminish flycheck-mode)
(provide 'init-flycheck)
;;; init-flycheck.el ends here | 9 | 0.321429 | 7 | 2 |
e6852d3444dd16fc9e6e765848f5aa72b3d60034 | .travis.yml | .travis.yml | language: ruby
rvm:
- 1.9.3
- 2.0.0
- 2.1.0
gemfile:
- ci/Gemfile-rails-3-1
- ci/Gemfile-rails-3-2
- ci/Gemfile-rails-4-0
env:
- DB=sqlite
- DB=mysql
before_script:
- "mysql -e 'create database rails_settings_test;' >/dev/null"
before_install: gem update bundler
| language: ruby
rvm:
- 1.9.3
- 2.0.0
- 2.1.1
gemfile:
- ci/Gemfile-rails-3-1
- ci/Gemfile-rails-3-2
- ci/Gemfile-rails-4-0
- ci/Gemfile-rails-4-1
env:
- DB=sqlite
- DB=mysql
before_script:
- "mysql -e 'create database rails_settings_test;' >/dev/null"
before_install: gem update bundler
| Use the added Gemfile for Rails 4.1 | Travis: Use the added Gemfile for Rails 4.1
| YAML | mit | kpost/rails-settings,DFrenkel/rails-settings,ledermann/rails-settings,ipmobiletech/rails-settings,NetsoftHoldings/rails-settings,mengqing/rails-settings,Kriechi/rails-settings,drselump14/rails-settings | yaml | ## Code Before:
language: ruby
rvm:
- 1.9.3
- 2.0.0
- 2.1.0
gemfile:
- ci/Gemfile-rails-3-1
- ci/Gemfile-rails-3-2
- ci/Gemfile-rails-4-0
env:
- DB=sqlite
- DB=mysql
before_script:
- "mysql -e 'create database rails_settings_test;' >/dev/null"
before_install: gem update bundler
## Instruction:
Travis: Use the added Gemfile for Rails 4.1
## Code After:
language: ruby
rvm:
- 1.9.3
- 2.0.0
- 2.1.1
gemfile:
- ci/Gemfile-rails-3-1
- ci/Gemfile-rails-3-2
- ci/Gemfile-rails-4-0
- ci/Gemfile-rails-4-1
env:
- DB=sqlite
- DB=mysql
before_script:
- "mysql -e 'create database rails_settings_test;' >/dev/null"
before_install: gem update bundler
| language: ruby
rvm:
- 1.9.3
- 2.0.0
- - 2.1.0
? ^
+ - 2.1.1
? ^
gemfile:
- ci/Gemfile-rails-3-1
- ci/Gemfile-rails-3-2
- ci/Gemfile-rails-4-0
+ - ci/Gemfile-rails-4-1
env:
- DB=sqlite
- DB=mysql
before_script:
- "mysql -e 'create database rails_settings_test;' >/dev/null"
before_install: gem update bundler | 3 | 0.2 | 2 | 1 |
0a7bbef10cef73756508f5d6c3bceb74392b014c | tips.json | tips.json | [
{
"title": "Overwrite pull",
"tip": "git fetch --all && git reset --hard origin/master"
},
{
"title": "List of all the files changed in a commit",
"tip": "git ls-tree --name-only -r <commit-ish>"
},
{
"title": "Git reset first commit",
"tip": "git update-ref -d HEAD"
},
{
"title": "List all the conflicted files",
"tip": "git diff --name-only --diff-filter=U"
},
{
"title": "List all branches that are already merged into master",
"tip": "git checkout master && git branch --merged"
},
{
"title": "Quickly switch to the previous branch",
"tip": "git checkout -"
},
{
"title": "Remove branches that have already been merged with master",
"tip": "git branch --merged | grep -v '\\*' | xargs -n 1 git branch -d"
},
{
"title": "List all branches and their upstreams, as well as last commit on branch",
"tip": "git branch -vv"
},
{
"title": "Track upstream branch",
"tip": "git branch -u origin/mybranch"
}
{
"title": "Delete local branch",
"tip": "git branch -d local_branchname"
}
{
"title": "Delete remote branch",
"tip": "git push origin :remote_branchname"
}
]
| [
{
"title": "Overwrite pull",
"tip": "git fetch --all && git reset --hard origin/master"
},
{
"title": "List of all the files changed in a commit",
"tip": "git ls-tree --name-only -r <commit-ish>"
},
{
"title": "Git reset first commit",
"tip": "git update-ref -d HEAD"
},
{
"title": "List all the conflicted files",
"tip": "git diff --name-only --diff-filter=U"
},
{
"title": "List all branches that are already merged into master",
"tip": "git checkout master && git branch --merged"
},
{
"title": "Quickly switch to the previous branch",
"tip": "git checkout -"
},
{
"title": "Remove branches that have already been merged with master",
"tip": "git branch --merged | grep -v '\\*' | xargs -n 1 git branch -d"
},
{
"title": "List all branches and their upstreams, as well as last commit on branch",
"tip": "git branch -vv"
},
{
"title": "Track upstream branch",
"tip": "git branch -u origin/mybranch"
}
]
| Revert "tip for deleting a local or remote branch" | Revert "tip for deleting a local or remote branch"
| JSON | mit | shekkbuilder/tips,munendrasn/tips,alexandregz/tips,samarpanda/tips,ejmr/tips,jpmens/tips,princejwesley/tips,git-tips/tips | json | ## Code Before:
[
{
"title": "Overwrite pull",
"tip": "git fetch --all && git reset --hard origin/master"
},
{
"title": "List of all the files changed in a commit",
"tip": "git ls-tree --name-only -r <commit-ish>"
},
{
"title": "Git reset first commit",
"tip": "git update-ref -d HEAD"
},
{
"title": "List all the conflicted files",
"tip": "git diff --name-only --diff-filter=U"
},
{
"title": "List all branches that are already merged into master",
"tip": "git checkout master && git branch --merged"
},
{
"title": "Quickly switch to the previous branch",
"tip": "git checkout -"
},
{
"title": "Remove branches that have already been merged with master",
"tip": "git branch --merged | grep -v '\\*' | xargs -n 1 git branch -d"
},
{
"title": "List all branches and their upstreams, as well as last commit on branch",
"tip": "git branch -vv"
},
{
"title": "Track upstream branch",
"tip": "git branch -u origin/mybranch"
}
{
"title": "Delete local branch",
"tip": "git branch -d local_branchname"
}
{
"title": "Delete remote branch",
"tip": "git push origin :remote_branchname"
}
]
## Instruction:
Revert "tip for deleting a local or remote branch"
## Code After:
[
{
"title": "Overwrite pull",
"tip": "git fetch --all && git reset --hard origin/master"
},
{
"title": "List of all the files changed in a commit",
"tip": "git ls-tree --name-only -r <commit-ish>"
},
{
"title": "Git reset first commit",
"tip": "git update-ref -d HEAD"
},
{
"title": "List all the conflicted files",
"tip": "git diff --name-only --diff-filter=U"
},
{
"title": "List all branches that are already merged into master",
"tip": "git checkout master && git branch --merged"
},
{
"title": "Quickly switch to the previous branch",
"tip": "git checkout -"
},
{
"title": "Remove branches that have already been merged with master",
"tip": "git branch --merged | grep -v '\\*' | xargs -n 1 git branch -d"
},
{
"title": "List all branches and their upstreams, as well as last commit on branch",
"tip": "git branch -vv"
},
{
"title": "Track upstream branch",
"tip": "git branch -u origin/mybranch"
}
]
| [
{
"title": "Overwrite pull",
"tip": "git fetch --all && git reset --hard origin/master"
},
{
"title": "List of all the files changed in a commit",
"tip": "git ls-tree --name-only -r <commit-ish>"
},
{
"title": "Git reset first commit",
"tip": "git update-ref -d HEAD"
},
{
"title": "List all the conflicted files",
"tip": "git diff --name-only --diff-filter=U"
},
{
"title": "List all branches that are already merged into master",
"tip": "git checkout master && git branch --merged"
},
{
"title": "Quickly switch to the previous branch",
"tip": "git checkout -"
},
{
"title": "Remove branches that have already been merged with master",
"tip": "git branch --merged | grep -v '\\*' | xargs -n 1 git branch -d"
},
{
"title": "List all branches and their upstreams, as well as last commit on branch",
"tip": "git branch -vv"
},
{
"title": "Track upstream branch",
"tip": "git branch -u origin/mybranch"
}
- {
- "title": "Delete local branch",
- "tip": "git branch -d local_branchname"
- }
- {
- "title": "Delete remote branch",
- "tip": "git push origin :remote_branchname"
- }
] | 8 | 0.173913 | 0 | 8 |
6d9f7fed56acff717d31ae12373bc76d921db7d1 | spec/regression/regression_spec.rb | spec/regression/regression_spec.rb | require "spec_helper"
describe "regression test" do
command("#{File.expand_path("../../../bin/foodcritic --tags any", __FILE__)} .", allow_error: true)
IO.readlines(File.expand_path("../cookbooks.txt", __FILE__)).each do |line|
name, ref = line.strip.split(":")
context "with cookbook #{name}" do
before do
command("git clone -q https://github.com/chef-cookbooks/#{name}.git .")
command("git checkout -q #{ref}")
end
it "should match expected output" do
expected_output = IO.readlines(File.expand_path("../expected/#{name}.txt", __FILE__))
expected_output.each do |expected_line|
expect(subject.stdout).to include expected_line
end
end
end
end
end
| require "spec_helper"
describe "regression test" do
command("#{File.expand_path("../../../bin/foodcritic", __FILE__)} --tags any .", allow_error: true)
IO.readlines(File.expand_path("../cookbooks.txt", __FILE__)).each do |line|
name, ref = line.strip.split(":")
context "with cookbook #{name}" do
before do
command("git clone -q https://github.com/chef-cookbooks/#{name}.git .")
command("git checkout -q #{ref}")
end
it "should match expected output" do
expected_output = IO.readlines(File.expand_path("../expected/#{name}.txt", __FILE__))
expected_output.each do |expected_line|
expect(subject.stdout).to include expected_line
end
end
end
end
end
| Move argument to the correct location | Move argument to the correct location
Signed-off-by: Tim Smith <764ef62106582a09ed09dfa0b6bff7c05fd7d1e4@chef.io>
| Ruby | mit | acrmp/foodcritic,Foodcritic/foodcritic | ruby | ## Code Before:
require "spec_helper"
describe "regression test" do
command("#{File.expand_path("../../../bin/foodcritic --tags any", __FILE__)} .", allow_error: true)
IO.readlines(File.expand_path("../cookbooks.txt", __FILE__)).each do |line|
name, ref = line.strip.split(":")
context "with cookbook #{name}" do
before do
command("git clone -q https://github.com/chef-cookbooks/#{name}.git .")
command("git checkout -q #{ref}")
end
it "should match expected output" do
expected_output = IO.readlines(File.expand_path("../expected/#{name}.txt", __FILE__))
expected_output.each do |expected_line|
expect(subject.stdout).to include expected_line
end
end
end
end
end
## Instruction:
Move argument to the correct location
Signed-off-by: Tim Smith <764ef62106582a09ed09dfa0b6bff7c05fd7d1e4@chef.io>
## Code After:
require "spec_helper"
describe "regression test" do
command("#{File.expand_path("../../../bin/foodcritic", __FILE__)} --tags any .", allow_error: true)
IO.readlines(File.expand_path("../cookbooks.txt", __FILE__)).each do |line|
name, ref = line.strip.split(":")
context "with cookbook #{name}" do
before do
command("git clone -q https://github.com/chef-cookbooks/#{name}.git .")
command("git checkout -q #{ref}")
end
it "should match expected output" do
expected_output = IO.readlines(File.expand_path("../expected/#{name}.txt", __FILE__))
expected_output.each do |expected_line|
expect(subject.stdout).to include expected_line
end
end
end
end
end
| require "spec_helper"
describe "regression test" do
- command("#{File.expand_path("../../../bin/foodcritic --tags any", __FILE__)} .", allow_error: true)
? -----------
+ command("#{File.expand_path("../../../bin/foodcritic", __FILE__)} --tags any .", allow_error: true)
? +++++++++++
IO.readlines(File.expand_path("../cookbooks.txt", __FILE__)).each do |line|
name, ref = line.strip.split(":")
context "with cookbook #{name}" do
before do
command("git clone -q https://github.com/chef-cookbooks/#{name}.git .")
command("git checkout -q #{ref}")
end
it "should match expected output" do
expected_output = IO.readlines(File.expand_path("../expected/#{name}.txt", __FILE__))
expected_output.each do |expected_line|
expect(subject.stdout).to include expected_line
end
end
end
end
end | 2 | 0.086957 | 1 | 1 |
b0194a1265fdd2d0179c9d90a4104257db176599 | kolibri/plugins/learn/assets/src/views/SuggestedTime.vue | kolibri/plugins/learn/assets/src/views/SuggestedTime.vue | <template>
<div class="time-context">
<div v-if="time > 0">
{{ $tr('shortTime', { time: 120 }) }}
</div>
<div v-if="time > 0">
{{ $tr('suggestedTimeLabel', { time: 120 }) }}
</div>
{{ $tr('suggestedTimeTooltip') }}
</div>
</template>
<script>
export default {
name: 'SuggestedTime',
props: {
/* Time in ms */
time: {
type: Number,
default: 0,
},
},
$trs: {
suggestedTimeTooltip: {
message: 'Suggested time to complete',
context:
'A tooltip explaning what the clock icon and time indicates about the resource they are viewing',
},
shortTime: {
message: '{time} {time, plural, one {minute} other {minutes}}',
context: 'Converts the time given into internationalized time. Nothing to translate here.',
},
suggestedTimeLabel: {
message: 'Suggested time to complete: {time} {time, plural, one {minute} other {minutes}}',
context:
"Indicates to the user the suggested time the resource should take to complete. The '# minutes' string is internationalized automatically",
},
},
};
</script>
<style scoped lang="scss"></style>
| <template>
<div class="time-context">
<span v-if="seconds > 0">
{{ $tr('suggestedTimeLabel') }}
<TimeDuration :seconds="seconds" :expand="true" />
</span>
</div>
</template>
<script>
import TimeDuration from 'kolibri.coreVue.components.TimeDuration';
export default {
name: 'SuggestedTime',
components: { TimeDuration },
props: {
/* Time in ms */
seconds: {
type: Number,
default: 8100,
},
},
$trs: {
suggestedTimeLabel: {
message: 'Suggested time to complete',
context:
'A label preceding a number of minutes that the current resource is estimated to take to complete',
},
},
};
</script>
<style scoped lang="scss"></style>
| Make sure the right string is there | Make sure the right string is there | Vue | mit | learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri | vue | ## Code Before:
<template>
<div class="time-context">
<div v-if="time > 0">
{{ $tr('shortTime', { time: 120 }) }}
</div>
<div v-if="time > 0">
{{ $tr('suggestedTimeLabel', { time: 120 }) }}
</div>
{{ $tr('suggestedTimeTooltip') }}
</div>
</template>
<script>
export default {
name: 'SuggestedTime',
props: {
/* Time in ms */
time: {
type: Number,
default: 0,
},
},
$trs: {
suggestedTimeTooltip: {
message: 'Suggested time to complete',
context:
'A tooltip explaning what the clock icon and time indicates about the resource they are viewing',
},
shortTime: {
message: '{time} {time, plural, one {minute} other {minutes}}',
context: 'Converts the time given into internationalized time. Nothing to translate here.',
},
suggestedTimeLabel: {
message: 'Suggested time to complete: {time} {time, plural, one {minute} other {minutes}}',
context:
"Indicates to the user the suggested time the resource should take to complete. The '# minutes' string is internationalized automatically",
},
},
};
</script>
<style scoped lang="scss"></style>
## Instruction:
Make sure the right string is there
## Code After:
<template>
<div class="time-context">
<span v-if="seconds > 0">
{{ $tr('suggestedTimeLabel') }}
<TimeDuration :seconds="seconds" :expand="true" />
</span>
</div>
</template>
<script>
import TimeDuration from 'kolibri.coreVue.components.TimeDuration';
export default {
name: 'SuggestedTime',
components: { TimeDuration },
props: {
/* Time in ms */
seconds: {
type: Number,
default: 8100,
},
},
$trs: {
suggestedTimeLabel: {
message: 'Suggested time to complete',
context:
'A label preceding a number of minutes that the current resource is estimated to take to complete',
},
},
};
</script>
<style scoped lang="scss"></style>
| <template>
<div class="time-context">
+ <span v-if="seconds > 0">
- <div v-if="time > 0">
- {{ $tr('shortTime', { time: 120 }) }}
- </div>
- <div v-if="time > 0">
- {{ $tr('suggestedTimeLabel', { time: 120 }) }}
- </div>
- {{ $tr('suggestedTimeTooltip') }}
? ^^^ ---
+ {{ $tr('suggestedTimeLabel') }}
? ++ ^^^^
+ <TimeDuration :seconds="seconds" :expand="true" />
+ </span>
</div>
</template>
<script>
+ import TimeDuration from 'kolibri.coreVue.components.TimeDuration';
+
export default {
name: 'SuggestedTime',
+ components: { TimeDuration },
props: {
/* Time in ms */
- time: {
+ seconds: {
type: Number,
- default: 0,
+ default: 8100,
? +++
},
},
$trs: {
- suggestedTimeTooltip: {
? ^^^ ---
+ suggestedTimeLabel: {
? ^^^^
message: 'Suggested time to complete',
context:
+ 'A label preceding a number of minutes that the current resource is estimated to take to complete',
- 'A tooltip explaning what the clock icon and time indicates about the resource they are viewing',
- },
- shortTime: {
- message: '{time} {time, plural, one {minute} other {minutes}}',
- context: 'Converts the time given into internationalized time. Nothing to translate here.',
- },
- suggestedTimeLabel: {
- message: 'Suggested time to complete: {time} {time, plural, one {minute} other {minutes}}',
- context:
- "Indicates to the user the suggested time the resource should take to complete. The '# minutes' string is internationalized automatically",
},
},
};
</script>
<style scoped lang="scss"></style> | 31 | 0.645833 | 11 | 20 |
2cfa9d62627882ec46202d6b4d9d53df155f7cd4 | drivers/ruby/tests/basictest.rb | drivers/ruby/tests/basictest.rb | require './lib/cakedb.rb'
#@conn = Cake.new("localhost", 8888)
@conn = CakeDB.new
#@conn.write("a","cheeseburger")
#@conn.write("a","chips")
#@conn.write("a","softdrink")
#@conn.write("a","nachos")
#@conn.write("a","sushi")
includedTime = 0
@conn.allSince("a", 0).each do |line|
puts line["ts"].to_s + "|" + line["data"]
end
@conn.rangeQuery("a", 0, Time.now.to_i*1000000).each do |line|
puts line["ts"].to_s + "|" + line["data"]
includedTime = line["ts"] * 10
end
@conn.lastAt("a", includedTime).each do |line|
puts line["ts"].to_s + "|" + line["data"]
end
| require './lib/cakedb.rb'
#@conn = Cake.new("localhost", 8888)
@conn = CakeDB.new
@conn.write("a","cheeseburger")
@conn.write("a","chips")
@conn.write("a","softdrink")
@conn.write("a","nachos")
@conn.write("a","sushi")
includedTime = 0
puts "Sleeping to ensure data hits the disk..."
sleep 10
@conn.allSince("a", 0).each do |line|
puts line["ts"].to_s + "|" + line["data"]
end
@conn.rangeQuery("a", 0, Time.now.to_i*1000000).each do |line|
puts line["ts"].to_s + "|" + line["data"]
includedTime = line["ts"] * 10
end
@conn.lastAt("a", includedTime).each do |line|
puts line["ts"].to_s + "|" + line["data"]
end
| Test script needs to actually write something before it can query. Added a 10 second pause to ensure the data hits the disk before the query tests start. | Test script needs to actually write something before it can query. Added a 10 second pause to ensure the data hits the disk before the query tests start.
| Ruby | bsd-3-clause | pmembrey/cakedb,pmembrey/cakedb,pmembrey/cakedb | ruby | ## Code Before:
require './lib/cakedb.rb'
#@conn = Cake.new("localhost", 8888)
@conn = CakeDB.new
#@conn.write("a","cheeseburger")
#@conn.write("a","chips")
#@conn.write("a","softdrink")
#@conn.write("a","nachos")
#@conn.write("a","sushi")
includedTime = 0
@conn.allSince("a", 0).each do |line|
puts line["ts"].to_s + "|" + line["data"]
end
@conn.rangeQuery("a", 0, Time.now.to_i*1000000).each do |line|
puts line["ts"].to_s + "|" + line["data"]
includedTime = line["ts"] * 10
end
@conn.lastAt("a", includedTime).each do |line|
puts line["ts"].to_s + "|" + line["data"]
end
## Instruction:
Test script needs to actually write something before it can query. Added a 10 second pause to ensure the data hits the disk before the query tests start.
## Code After:
require './lib/cakedb.rb'
#@conn = Cake.new("localhost", 8888)
@conn = CakeDB.new
@conn.write("a","cheeseburger")
@conn.write("a","chips")
@conn.write("a","softdrink")
@conn.write("a","nachos")
@conn.write("a","sushi")
includedTime = 0
puts "Sleeping to ensure data hits the disk..."
sleep 10
@conn.allSince("a", 0).each do |line|
puts line["ts"].to_s + "|" + line["data"]
end
@conn.rangeQuery("a", 0, Time.now.to_i*1000000).each do |line|
puts line["ts"].to_s + "|" + line["data"]
includedTime = line["ts"] * 10
end
@conn.lastAt("a", includedTime).each do |line|
puts line["ts"].to_s + "|" + line["data"]
end
| require './lib/cakedb.rb'
#@conn = Cake.new("localhost", 8888)
@conn = CakeDB.new
- #@conn.write("a","cheeseburger")
? -
+ @conn.write("a","cheeseburger")
- #@conn.write("a","chips")
? -
+ @conn.write("a","chips")
- #@conn.write("a","softdrink")
? -
+ @conn.write("a","softdrink")
- #@conn.write("a","nachos")
? -
+ @conn.write("a","nachos")
- #@conn.write("a","sushi")
? -
+ @conn.write("a","sushi")
includedTime = 0
+
+ puts "Sleeping to ensure data hits the disk..."
+ sleep 10
@conn.allSince("a", 0).each do |line|
puts line["ts"].to_s + "|" + line["data"]
end
@conn.rangeQuery("a", 0, Time.now.to_i*1000000).each do |line|
puts line["ts"].to_s + "|" + line["data"]
includedTime = line["ts"] * 10
end
@conn.lastAt("a", includedTime).each do |line|
puts line["ts"].to_s + "|" + line["data"]
end
| 13 | 0.590909 | 8 | 5 |
6a36f0cef03af2c61dbc0c5dfd4fc47496ae1f05 | moss/plots.py | moss/plots.py | import os.path as op
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
import seaborn as sns
def plot_mask_distribution(fname, ax=None, hist=False):
"""Plot the distribution of voxel coordinates in a mask file.
Parameters
----------
fname : string
path to binary mask file
Returns
-------
ax : matplotlib axis object
axis with plot on it
"""
if ax is None:
ax = plt.subplot(111)
img = nib.load(fname)
mask = img.get_data()
aff = img.get_affine()
vox = np.where(mask)
vox = np.vstack([vox, np.ones(mask.sum())])
coords = np.dot(aff, vox)[:-1]
colors = sns.get_color_list()[:3]
for axis, data, color in zip(["x", "y", "z"], coords, colors):
if hist:
sns.kdeplot(data, hist=True, label=axis, color=color, ax=ax)
else:
sns.kdeplot(data, shade=True, label=axis, color=color, ax=ax)
ax.legend()
ax.set_title(op.basename(fname))
return ax
| import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
import seaborn as sns
def plot_mask_distribution(mask_img, hist=False):
"""Plot the distribution of voxel coordinates in a mask image or file.
Parameters
----------
fname : string or nibabel image
path to binary mask file or image object with data and affine
Returns
-------
ax : matplotlib axis object
axis with plot on it
"""
if ax is None:
ax = plt.subplot(111)
if isinstance(mask_img, basestring):
img = nib.load(mask_img)
else:
img = mask_img
mask = img.get_data()
aff = img.get_affine()
vox = np.where(mask)
vox = np.vstack([vox, np.ones(mask.sum())])
coords = np.dot(aff, vox)[:-1]
colors = sns.get_color_list()[:3]
for axis, data, color in zip(["x", "y", "z"], coords, colors):
if hist:
sns.kdeplot(data, hist=True, label=axis, color=color, ax=ax)
else:
sns.kdeplot(data, shade=True, label=axis, color=color, ax=ax)
ax.legend()
return ax
| Allow plot_mask to take nibabel image | Allow plot_mask to take nibabel image
| Python | bsd-3-clause | mwaskom/moss,mwaskom/moss | python | ## Code Before:
import os.path as op
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
import seaborn as sns
def plot_mask_distribution(fname, ax=None, hist=False):
"""Plot the distribution of voxel coordinates in a mask file.
Parameters
----------
fname : string
path to binary mask file
Returns
-------
ax : matplotlib axis object
axis with plot on it
"""
if ax is None:
ax = plt.subplot(111)
img = nib.load(fname)
mask = img.get_data()
aff = img.get_affine()
vox = np.where(mask)
vox = np.vstack([vox, np.ones(mask.sum())])
coords = np.dot(aff, vox)[:-1]
colors = sns.get_color_list()[:3]
for axis, data, color in zip(["x", "y", "z"], coords, colors):
if hist:
sns.kdeplot(data, hist=True, label=axis, color=color, ax=ax)
else:
sns.kdeplot(data, shade=True, label=axis, color=color, ax=ax)
ax.legend()
ax.set_title(op.basename(fname))
return ax
## Instruction:
Allow plot_mask to take nibabel image
## Code After:
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
import seaborn as sns
def plot_mask_distribution(mask_img, hist=False):
"""Plot the distribution of voxel coordinates in a mask image or file.
Parameters
----------
fname : string or nibabel image
path to binary mask file or image object with data and affine
Returns
-------
ax : matplotlib axis object
axis with plot on it
"""
if ax is None:
ax = plt.subplot(111)
if isinstance(mask_img, basestring):
img = nib.load(mask_img)
else:
img = mask_img
mask = img.get_data()
aff = img.get_affine()
vox = np.where(mask)
vox = np.vstack([vox, np.ones(mask.sum())])
coords = np.dot(aff, vox)[:-1]
colors = sns.get_color_list()[:3]
for axis, data, color in zip(["x", "y", "z"], coords, colors):
if hist:
sns.kdeplot(data, hist=True, label=axis, color=color, ax=ax)
else:
sns.kdeplot(data, shade=True, label=axis, color=color, ax=ax)
ax.legend()
return ax
| - import os.path as op
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
import seaborn as sns
- def plot_mask_distribution(fname, ax=None, hist=False):
? ^^ ^^^^^^^^^^
+ def plot_mask_distribution(mask_img, hist=False):
? ^ ++++ ^
- """Plot the distribution of voxel coordinates in a mask file.
+ """Plot the distribution of voxel coordinates in a mask image or file.
? +++++++++
Parameters
----------
- fname : string
- path to binary mask file
+ fname : string or nibabel image
+ path to binary mask file or image object with data and affine
Returns
-------
ax : matplotlib axis object
axis with plot on it
"""
if ax is None:
ax = plt.subplot(111)
+ if isinstance(mask_img, basestring):
- img = nib.load(fname)
? ^^ ^
+ img = nib.load(mask_img)
? ++++ ^ ++++ ^
+ else:
+ img = mask_img
mask = img.get_data()
aff = img.get_affine()
vox = np.where(mask)
vox = np.vstack([vox, np.ones(mask.sum())])
coords = np.dot(aff, vox)[:-1]
colors = sns.get_color_list()[:3]
for axis, data, color in zip(["x", "y", "z"], coords, colors):
if hist:
sns.kdeplot(data, hist=True, label=axis, color=color, ax=ax)
else:
sns.kdeplot(data, shade=True, label=axis, color=color, ax=ax)
ax.legend()
- ax.set_title(op.basename(fname))
return ax | 15 | 0.405405 | 8 | 7 |
a20a809866bb2232990269a7e68a95a5563252cc | data/sdo-police-station-examples.txt | data/sdo-police-station-examples.txt | TYPES: #eg-0403 PoliceStation, areaServed
PRE-MARKUP:
Police station example (JSON-LD only).
MICRODATA:
TODO
RDFA:
TODO
JSON:
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "PoliceStation",
"name": "Youngstown Central Police Station",
"description": "Central police station",
"openingHours": "Mo-Su",
"telephone": "+13303301888",
"email": "ohio.police.example@example.com",
"image": "https://homepages.cae.wisc.edu/~ece533/images/lena.png",
"address": {
"@type": "PostalAddress",
"addressLocality": "Youngstown",
"addressRegion": "OH",
"postalCode": "44507",
"streetAddress": "270 Derek Drive"
},
"areaServed": {
"@type": "GeoCircle",
"geoMidpoint": {
"@type": "GeoCoordinates",
"latitude": 41.108237,
"longitude": -80.642982
},
"geoRadius": 1000
},
"aggregateRating": {
"@type": "AggregateRating",
"bestRating": 100,
"worstRating": 0,
"ratingValue": 88,
"reviewCount": 122
}
}
</script>
| TYPES: #eg-0403 PoliceStation, areaServed
PRE-MARKUP:
Police station example (JSON-LD only).
MICRODATA:
RDFA:
JSON:
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "PoliceStation",
"name": "Youngstown Central Police Station",
"description": "Central police station",
"openingHours": "Mo-Su",
"telephone": "+13303301888",
"email": "ohio.police.example@example.com",
"image": "https://homepages.cae.wisc.edu/~ece533/images/lena.png",
"address": {
"@type": "PostalAddress",
"addressLocality": "Youngstown",
"addressRegion": "OH",
"postalCode": "44507",
"streetAddress": "270 Derek Drive"
},
"areaServed": {
"@type": "GeoCircle",
"geoMidpoint": {
"@type": "GeoCoordinates",
"latitude": 41.108237,
"longitude": -80.642982
},
"geoRadius": 1000
},
"aggregateRating": {
"@type": "AggregateRating",
"bestRating": 100,
"worstRating": 0,
"ratingValue": 88,
"reviewCount": 122
}
}
</script>
| Update to pass CI tests | Update to pass CI tests
| Text | apache-2.0 | schemaorg/schemaorg,schemaorg/schemaorg,schemaorg/schemaorg,schemaorg/schemaorg,schemaorg/schemaorg | text | ## Code Before:
TYPES: #eg-0403 PoliceStation, areaServed
PRE-MARKUP:
Police station example (JSON-LD only).
MICRODATA:
TODO
RDFA:
TODO
JSON:
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "PoliceStation",
"name": "Youngstown Central Police Station",
"description": "Central police station",
"openingHours": "Mo-Su",
"telephone": "+13303301888",
"email": "ohio.police.example@example.com",
"image": "https://homepages.cae.wisc.edu/~ece533/images/lena.png",
"address": {
"@type": "PostalAddress",
"addressLocality": "Youngstown",
"addressRegion": "OH",
"postalCode": "44507",
"streetAddress": "270 Derek Drive"
},
"areaServed": {
"@type": "GeoCircle",
"geoMidpoint": {
"@type": "GeoCoordinates",
"latitude": 41.108237,
"longitude": -80.642982
},
"geoRadius": 1000
},
"aggregateRating": {
"@type": "AggregateRating",
"bestRating": 100,
"worstRating": 0,
"ratingValue": 88,
"reviewCount": 122
}
}
</script>
## Instruction:
Update to pass CI tests
## Code After:
TYPES: #eg-0403 PoliceStation, areaServed
PRE-MARKUP:
Police station example (JSON-LD only).
MICRODATA:
RDFA:
JSON:
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "PoliceStation",
"name": "Youngstown Central Police Station",
"description": "Central police station",
"openingHours": "Mo-Su",
"telephone": "+13303301888",
"email": "ohio.police.example@example.com",
"image": "https://homepages.cae.wisc.edu/~ece533/images/lena.png",
"address": {
"@type": "PostalAddress",
"addressLocality": "Youngstown",
"addressRegion": "OH",
"postalCode": "44507",
"streetAddress": "270 Derek Drive"
},
"areaServed": {
"@type": "GeoCircle",
"geoMidpoint": {
"@type": "GeoCoordinates",
"latitude": 41.108237,
"longitude": -80.642982
},
"geoRadius": 1000
},
"aggregateRating": {
"@type": "AggregateRating",
"bestRating": 100,
"worstRating": 0,
"ratingValue": 88,
"reviewCount": 122
}
}
</script>
| TYPES: #eg-0403 PoliceStation, areaServed
PRE-MARKUP:
Police station example (JSON-LD only).
MICRODATA:
- TODO
RDFA:
- TODO
JSON:
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "PoliceStation",
"name": "Youngstown Central Police Station",
"description": "Central police station",
"openingHours": "Mo-Su",
"telephone": "+13303301888",
"email": "ohio.police.example@example.com",
"image": "https://homepages.cae.wisc.edu/~ece533/images/lena.png",
"address": {
"@type": "PostalAddress",
"addressLocality": "Youngstown",
"addressRegion": "OH",
"postalCode": "44507",
"streetAddress": "270 Derek Drive"
},
"areaServed": {
"@type": "GeoCircle",
"geoMidpoint": {
"@type": "GeoCoordinates",
"latitude": 41.108237,
"longitude": -80.642982
},
"geoRadius": 1000
},
"aggregateRating": {
"@type": "AggregateRating",
"bestRating": 100,
"worstRating": 0,
"ratingValue": 88,
"reviewCount": 122
}
}
</script>
| 2 | 0.038462 | 0 | 2 |
c2c9d269dfff851d7ac1ff3d4d3981fa26e33aeb | README.md | README.md | In order to figure out what's DNS and how it work, I would Implement Dynamic DNS server in User-level
| In order to figure out what's DNS and how it work, I would Implement Dynamic DNS server in User-level
Standard Reference:
- [rfc1034](https://tools.ietf.org/pdf/rfc1034.pdf)
- [rfc1035](https://tools.ietf.org/pdf/rfc1035.pdf)
- [rfc2136](https://tools.ietf.org/pdf/rfc2136.pdf)
| Update the reference link for rfc standard. | Update the reference link for rfc standard.
| Markdown | bsd-2-clause | yenWu/DDNS,yenWu/DDNS | markdown | ## Code Before:
In order to figure out what's DNS and how it work, I would Implement Dynamic DNS server in User-level
## Instruction:
Update the reference link for rfc standard.
## Code After:
In order to figure out what's DNS and how it work, I would Implement Dynamic DNS server in User-level
Standard Reference:
- [rfc1034](https://tools.ietf.org/pdf/rfc1034.pdf)
- [rfc1035](https://tools.ietf.org/pdf/rfc1035.pdf)
- [rfc2136](https://tools.ietf.org/pdf/rfc2136.pdf)
| In order to figure out what's DNS and how it work, I would Implement Dynamic DNS server in User-level
+
+ Standard Reference:
+ - [rfc1034](https://tools.ietf.org/pdf/rfc1034.pdf)
+ - [rfc1035](https://tools.ietf.org/pdf/rfc1035.pdf)
+ - [rfc2136](https://tools.ietf.org/pdf/rfc2136.pdf) | 5 | 5 | 5 | 0 |
83d62bdb6c8cd152eb00f86041048ff1f714ef2b | src/Installer.php | src/Installer.php | <?php
namespace AnduFratu\CakePhpConfigInstaller;
use Composer\Package\PackageInterface;
use Composer\Installer\LibraryInstaller;
class Installer extends LibraryInstaller {
public function supports($packageType) {
return 'cakephp-config' === $packageType;
}
public function getPackageBasePath(PackageInterface $package) {
return 'Config';
}
}
| <?php
namespace AnduFratu\CakePhpConfigInstaller;
use Composer\Package\PackageInterface;
use Composer\Installer\LibraryInstaller;
class Installer extends LibraryInstaller {
public function supports($packageType) {
return 'cakephp-config' === $packageType;
}
public function getPackageBasePath(PackageInterface $package) {
return 'Config';
}
public function getInstallPath(PackageInterface $package) {
return 'Config';
}
}
| Fix the way the install path is returned | Fix the way the install path is returned
| PHP | mit | andufratu/cakephp-config-installer | php | ## Code Before:
<?php
namespace AnduFratu\CakePhpConfigInstaller;
use Composer\Package\PackageInterface;
use Composer\Installer\LibraryInstaller;
class Installer extends LibraryInstaller {
public function supports($packageType) {
return 'cakephp-config' === $packageType;
}
public function getPackageBasePath(PackageInterface $package) {
return 'Config';
}
}
## Instruction:
Fix the way the install path is returned
## Code After:
<?php
namespace AnduFratu\CakePhpConfigInstaller;
use Composer\Package\PackageInterface;
use Composer\Installer\LibraryInstaller;
class Installer extends LibraryInstaller {
public function supports($packageType) {
return 'cakephp-config' === $packageType;
}
public function getPackageBasePath(PackageInterface $package) {
return 'Config';
}
public function getInstallPath(PackageInterface $package) {
return 'Config';
}
}
| <?php
namespace AnduFratu\CakePhpConfigInstaller;
use Composer\Package\PackageInterface;
use Composer\Installer\LibraryInstaller;
class Installer extends LibraryInstaller {
public function supports($packageType) {
return 'cakephp-config' === $packageType;
}
public function getPackageBasePath(PackageInterface $package) {
return 'Config';
}
+ public function getInstallPath(PackageInterface $package) {
+ return 'Config';
+ }
+
} | 4 | 0.235294 | 4 | 0 |
c1b6a564319f2480d1c9d330f4071fad11fc27db | config/initializers/mime_types.rb | config/initializers/mime_types.rb |
Mime::Type.register "application/dxf", :dxf
Mime::Type.register "application/gml+xml", :gml
Mime::Type.register "application/msword", :doc
Mime::Type.register "application/msword", :dot
Mime::Type.register "application/rdf+xml", :rdf
Mime::Type.register "application/vnd.ms-excel", :xls
Mime::Type.register "application/vnd.ms-excel", :xlt
Mime::Type.register "application/vnd.ms-excel.sheet.macroEnabled.12", :xlsm
Mime::Type.register "application/vnd.ms-powerpoint", :ppt
Mime::Type.register "application/vnd.oasis.opendocument.spreadsheet", :ods
Mime::Type.register "application/vnd.oasis.opendocument.text", :odt
Mime::Type.register "application/vnd.openxmlformats-officedocument.presentationml.presentation", :pptx
Mime::Type.register "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", :xlsx
Mime::Type.register "application/vnd.openxmlformats-officedocument.wordprocessingml.document", :docx
Mime::Type.register "text/plain; charset=utf-8", :txt
Mime::Type.register "text/rtf", :rtf
|
Mime::Type.register "application/dxf", :dxf
Mime::Type.register "application/gml+xml", :gml
Mime::Type.register "application/msword", :doc
Mime::Type.register "application/msword", :dot
Mime::Type.register "application/rdf+xml", :rdf
Mime::Type.register "application/vnd.ms-excel", :xls
Mime::Type.register "application/vnd.ms-excel", :xlt
Mime::Type.register "application/vnd.ms-excel.sheet.macroEnabled.12", :xlsm
Mime::Type.register "application/vnd.ms-powerpoint", :ppt
Mime::Type.register "application/vnd.oasis.opendocument.spreadsheet", :ods
Mime::Type.register "application/vnd.oasis.opendocument.presentation", :odp
Mime::Type.register "application/vnd.oasis.opendocument.text", :odt
Mime::Type.register "application/vnd.openxmlformats-officedocument.presentationml.presentation", :pptx
Mime::Type.register "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", :xlsx
Mime::Type.register "application/vnd.openxmlformats-officedocument.wordprocessingml.document", :docx
Mime::Type.register "text/plain; charset=utf-8", :txt
Mime::Type.register "text/rtf", :rtf
| Add correct mime type for .odp files | Add correct mime type for .odp files
We're currently serving `application/octet-stream` instead which makes Internet Explorer think the files are zip files. | Ruby | mit | alphagov/asset-manager,alphagov/asset-manager,alphagov/asset-manager | ruby | ## Code Before:
Mime::Type.register "application/dxf", :dxf
Mime::Type.register "application/gml+xml", :gml
Mime::Type.register "application/msword", :doc
Mime::Type.register "application/msword", :dot
Mime::Type.register "application/rdf+xml", :rdf
Mime::Type.register "application/vnd.ms-excel", :xls
Mime::Type.register "application/vnd.ms-excel", :xlt
Mime::Type.register "application/vnd.ms-excel.sheet.macroEnabled.12", :xlsm
Mime::Type.register "application/vnd.ms-powerpoint", :ppt
Mime::Type.register "application/vnd.oasis.opendocument.spreadsheet", :ods
Mime::Type.register "application/vnd.oasis.opendocument.text", :odt
Mime::Type.register "application/vnd.openxmlformats-officedocument.presentationml.presentation", :pptx
Mime::Type.register "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", :xlsx
Mime::Type.register "application/vnd.openxmlformats-officedocument.wordprocessingml.document", :docx
Mime::Type.register "text/plain; charset=utf-8", :txt
Mime::Type.register "text/rtf", :rtf
## Instruction:
Add correct mime type for .odp files
We're currently serving `application/octet-stream` instead which makes Internet Explorer think the files are zip files.
## Code After:
Mime::Type.register "application/dxf", :dxf
Mime::Type.register "application/gml+xml", :gml
Mime::Type.register "application/msword", :doc
Mime::Type.register "application/msword", :dot
Mime::Type.register "application/rdf+xml", :rdf
Mime::Type.register "application/vnd.ms-excel", :xls
Mime::Type.register "application/vnd.ms-excel", :xlt
Mime::Type.register "application/vnd.ms-excel.sheet.macroEnabled.12", :xlsm
Mime::Type.register "application/vnd.ms-powerpoint", :ppt
Mime::Type.register "application/vnd.oasis.opendocument.spreadsheet", :ods
Mime::Type.register "application/vnd.oasis.opendocument.presentation", :odp
Mime::Type.register "application/vnd.oasis.opendocument.text", :odt
Mime::Type.register "application/vnd.openxmlformats-officedocument.presentationml.presentation", :pptx
Mime::Type.register "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", :xlsx
Mime::Type.register "application/vnd.openxmlformats-officedocument.wordprocessingml.document", :docx
Mime::Type.register "text/plain; charset=utf-8", :txt
Mime::Type.register "text/rtf", :rtf
|
Mime::Type.register "application/dxf", :dxf
Mime::Type.register "application/gml+xml", :gml
Mime::Type.register "application/msword", :doc
Mime::Type.register "application/msword", :dot
Mime::Type.register "application/rdf+xml", :rdf
Mime::Type.register "application/vnd.ms-excel", :xls
Mime::Type.register "application/vnd.ms-excel", :xlt
Mime::Type.register "application/vnd.ms-excel.sheet.macroEnabled.12", :xlsm
Mime::Type.register "application/vnd.ms-powerpoint", :ppt
Mime::Type.register "application/vnd.oasis.opendocument.spreadsheet", :ods
+ Mime::Type.register "application/vnd.oasis.opendocument.presentation", :odp
Mime::Type.register "application/vnd.oasis.opendocument.text", :odt
Mime::Type.register "application/vnd.openxmlformats-officedocument.presentationml.presentation", :pptx
Mime::Type.register "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", :xlsx
Mime::Type.register "application/vnd.openxmlformats-officedocument.wordprocessingml.document", :docx
Mime::Type.register "text/plain; charset=utf-8", :txt
Mime::Type.register "text/rtf", :rtf | 1 | 0.058824 | 1 | 0 |
b822ffe852112eb30250626d4e66b17166733a24 | lib/tasks/import/mappings_from_host_paths.rake | lib/tasks/import/mappings_from_host_paths.rake | require 'transition/import/mappings_from_host_paths'
namespace :import do
desc 'Create mappings from HostPaths for a site'
task :mappings_from_host_paths, [:site_abbr] => :environment do |_, args|
site = Site.find_by_abbr(args[:site_abbr])
raise "No site found for #{args[:site_abbr]}" unless site
raise 'ABORT: This site is not managed by transition' unless site.managed_by_transition?
if site.global_type
STDOUT.flush
STDOUT.puts "WARNING: This site has a global_type, so Bouncer will not use any mappings you create.\nDo you want to continue? (y/N)"
input = STDIN.gets.chomp
unless %w(y yes).include?(input)
abort("Not creating mappings for site #{args[:site_abbr]} with global_type.")
end
end
Transition::Import::MappingsFromHostPaths.refresh!(site)
puts 'You may now want to run `rake import:hits_mappings_relations` to connect hits and any new mappings.'
end
end
| require 'transition/import/mappings_from_host_paths'
namespace :import do
desc 'Create mappings from HostPaths for a site'
task :mappings_from_host_paths, [:site_abbr] => :environment do |_, args|
site = Site.find_by_abbr(args[:site_abbr])
raise "No site found for #{args[:site_abbr]}" unless site
if site.global_type
STDOUT.flush
STDOUT.puts "WARNING: This site has a global_type, so Bouncer will not use any mappings you create.\nDo you want to continue? (y/N)"
input = STDIN.gets.chomp
unless %w(y yes).include?(input)
abort("Not creating mappings for site #{args[:site_abbr]} with global_type.")
end
end
Transition::Import::MappingsFromHostPaths.refresh!(site)
puts 'You may now want to run `rake import:hits_mappings_relations` to connect hits and any new mappings.'
end
end
| Remove a reference to managed_by_transition from an import rake task | Remove a reference to managed_by_transition from an import rake task
- A transtion-postgres Errbit error
(https://errbit.preview.alphagov.co.uk/apps/53e8c4e40da115dfc200684d/problems/5425716e0da11550d7001181)
made me do a full search
everywhere. Clearly nothing has used this rake task since
https://github.com/alphagov/transition/pull/413 otherwise
Errbit would have caught the exception?
| Ruby | mit | alphagov/transition,alphagov/transition,alphagov/transition | ruby | ## Code Before:
require 'transition/import/mappings_from_host_paths'
namespace :import do
desc 'Create mappings from HostPaths for a site'
task :mappings_from_host_paths, [:site_abbr] => :environment do |_, args|
site = Site.find_by_abbr(args[:site_abbr])
raise "No site found for #{args[:site_abbr]}" unless site
raise 'ABORT: This site is not managed by transition' unless site.managed_by_transition?
if site.global_type
STDOUT.flush
STDOUT.puts "WARNING: This site has a global_type, so Bouncer will not use any mappings you create.\nDo you want to continue? (y/N)"
input = STDIN.gets.chomp
unless %w(y yes).include?(input)
abort("Not creating mappings for site #{args[:site_abbr]} with global_type.")
end
end
Transition::Import::MappingsFromHostPaths.refresh!(site)
puts 'You may now want to run `rake import:hits_mappings_relations` to connect hits and any new mappings.'
end
end
## Instruction:
Remove a reference to managed_by_transition from an import rake task
- A transtion-postgres Errbit error
(https://errbit.preview.alphagov.co.uk/apps/53e8c4e40da115dfc200684d/problems/5425716e0da11550d7001181)
made me do a full search
everywhere. Clearly nothing has used this rake task since
https://github.com/alphagov/transition/pull/413 otherwise
Errbit would have caught the exception?
## Code After:
require 'transition/import/mappings_from_host_paths'
namespace :import do
desc 'Create mappings from HostPaths for a site'
task :mappings_from_host_paths, [:site_abbr] => :environment do |_, args|
site = Site.find_by_abbr(args[:site_abbr])
raise "No site found for #{args[:site_abbr]}" unless site
if site.global_type
STDOUT.flush
STDOUT.puts "WARNING: This site has a global_type, so Bouncer will not use any mappings you create.\nDo you want to continue? (y/N)"
input = STDIN.gets.chomp
unless %w(y yes).include?(input)
abort("Not creating mappings for site #{args[:site_abbr]} with global_type.")
end
end
Transition::Import::MappingsFromHostPaths.refresh!(site)
puts 'You may now want to run `rake import:hits_mappings_relations` to connect hits and any new mappings.'
end
end
| require 'transition/import/mappings_from_host_paths'
namespace :import do
desc 'Create mappings from HostPaths for a site'
task :mappings_from_host_paths, [:site_abbr] => :environment do |_, args|
site = Site.find_by_abbr(args[:site_abbr])
raise "No site found for #{args[:site_abbr]}" unless site
- raise 'ABORT: This site is not managed by transition' unless site.managed_by_transition?
if site.global_type
STDOUT.flush
STDOUT.puts "WARNING: This site has a global_type, so Bouncer will not use any mappings you create.\nDo you want to continue? (y/N)"
input = STDIN.gets.chomp
unless %w(y yes).include?(input)
abort("Not creating mappings for site #{args[:site_abbr]} with global_type.")
end
end
Transition::Import::MappingsFromHostPaths.refresh!(site)
puts 'You may now want to run `rake import:hits_mappings_relations` to connect hits and any new mappings.'
end
end | 1 | 0.045455 | 0 | 1 |
9a2c1073f4c21d764fdcfb8f3cc46b090d26e6d3 | app/models/network/technologies/siphon.rb | app/models/network/technologies/siphon.rb | module Network
module Technologies
# Consumes excess energy from the testing ground, with the profile defining
# the maximum amount which may be consumed. If there is no excess, the
# Siphon will be turned off and will receive nothing.
class Siphon < Generic
extend Disableable
attr_accessor :output_path
def self.disabled?(options)
!options[:solar_power_to_gas]
end
def load_at(frame)
conditional_consumption_at(frame)
end
def mandatory_consumption_at(_frame)
0.0
end
def conditional_consumption_at(frame)
@profile.at(frame)
end
def excess_constrained?
true
end
def store(frame, amount)
# Energy consumed by the Siphon is converted into production on the
# assigned output path.
if output_path && amount > 0
output_path.consume(frame, -amount)
end
end
# Internal: A Siphon-only feature. Consumption will be converted to
# production on the named network.
def output_carrier
:gas
end
end # Siphon
end
end
| module Network
module Technologies
# Consumes excess energy from the testing ground, with the profile defining
# the maximum amount which may be consumed. If there is no excess, the
# Siphon will be turned off and will receive nothing.
class Siphon < Generic
extend Disableable
attr_accessor :output_path
def self.disabled?(options)
!options[:solar_power_to_gas]
end
def load_at(frame)
conditional_consumption_at(frame)
end
def mandatory_consumption_at(_frame)
0.0
end
def conditional_consumption_at(frame)
@profile.at(frame)
end
def excess_constrained?
true
end
def store(frame, amount)
# Energy consumed by the Siphon is converted into production on the
# assigned output path.
output_path.consume(frame, -amount) if output_path
end
# Internal: A Siphon-only feature. Consumption will be converted to
# production on the named network.
def output_carrier
:gas
end
end # Siphon
end
end
| Write to Siphon output path when amount is zero | Write to Siphon output path when amount is zero
This ensures that the P2G gas load array is always the correct, full
length.
Closes #1377
| Ruby | mit | quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses | ruby | ## Code Before:
module Network
module Technologies
# Consumes excess energy from the testing ground, with the profile defining
# the maximum amount which may be consumed. If there is no excess, the
# Siphon will be turned off and will receive nothing.
class Siphon < Generic
extend Disableable
attr_accessor :output_path
def self.disabled?(options)
!options[:solar_power_to_gas]
end
def load_at(frame)
conditional_consumption_at(frame)
end
def mandatory_consumption_at(_frame)
0.0
end
def conditional_consumption_at(frame)
@profile.at(frame)
end
def excess_constrained?
true
end
def store(frame, amount)
# Energy consumed by the Siphon is converted into production on the
# assigned output path.
if output_path && amount > 0
output_path.consume(frame, -amount)
end
end
# Internal: A Siphon-only feature. Consumption will be converted to
# production on the named network.
def output_carrier
:gas
end
end # Siphon
end
end
## Instruction:
Write to Siphon output path when amount is zero
This ensures that the P2G gas load array is always the correct, full
length.
Closes #1377
## Code After:
module Network
module Technologies
# Consumes excess energy from the testing ground, with the profile defining
# the maximum amount which may be consumed. If there is no excess, the
# Siphon will be turned off and will receive nothing.
class Siphon < Generic
extend Disableable
attr_accessor :output_path
def self.disabled?(options)
!options[:solar_power_to_gas]
end
def load_at(frame)
conditional_consumption_at(frame)
end
def mandatory_consumption_at(_frame)
0.0
end
def conditional_consumption_at(frame)
@profile.at(frame)
end
def excess_constrained?
true
end
def store(frame, amount)
# Energy consumed by the Siphon is converted into production on the
# assigned output path.
output_path.consume(frame, -amount) if output_path
end
# Internal: A Siphon-only feature. Consumption will be converted to
# production on the named network.
def output_carrier
:gas
end
end # Siphon
end
end
| module Network
module Technologies
# Consumes excess energy from the testing ground, with the profile defining
# the maximum amount which may be consumed. If there is no excess, the
# Siphon will be turned off and will receive nothing.
class Siphon < Generic
extend Disableable
attr_accessor :output_path
def self.disabled?(options)
!options[:solar_power_to_gas]
end
def load_at(frame)
conditional_consumption_at(frame)
end
def mandatory_consumption_at(_frame)
0.0
end
def conditional_consumption_at(frame)
@profile.at(frame)
end
def excess_constrained?
true
end
def store(frame, amount)
# Energy consumed by the Siphon is converted into production on the
# assigned output path.
- if output_path && amount > 0
- output_path.consume(frame, -amount)
? --
+ output_path.consume(frame, -amount) if output_path
? +++++++++++++++
- end
end
# Internal: A Siphon-only feature. Consumption will be converted to
# production on the named network.
def output_carrier
:gas
end
end # Siphon
end
end | 4 | 0.086957 | 1 | 3 |
78154a63e86774fb8952f42883f7788e94d0c8d2 | lib/spack/spack/operating_systems/linux_distro.py | lib/spack/spack/operating_systems/linux_distro.py | import re
from external.distro import linux_distribution
from spack.architecture import OperatingSystem
class LinuxDistro(OperatingSystem):
""" This class will represent the autodetected operating system
for a Linux System. Since there are many different flavors of
Linux, this class will attempt to encompass them all through
autodetection using the python module platform and the method
platform.dist()
"""
def __init__(self):
distname, version, _ = linux_distribution(
full_distribution_name=False)
distname, version = str(distname), str(version)
# Grabs major version from tuple on redhat; on other platforms
# grab the first legal identifier in the version field. On
# debian you get things like 'wheezy/sid'; sid means unstable.
# We just record 'wheezy' and don't get quite so detailed.
version = re.split(r'[^\w-]', version)[0]
super(LinuxDistro, self).__init__(distname, version)
| import re
from spack.architecture import OperatingSystem
class LinuxDistro(OperatingSystem):
""" This class will represent the autodetected operating system
for a Linux System. Since there are many different flavors of
Linux, this class will attempt to encompass them all through
autodetection using the python module platform and the method
platform.dist()
"""
def __init__(self):
try:
# This will throw an error if imported on a non-Linux platform.
from external.distro import linux_distribution
distname, version, _ = linux_distribution(
full_distribution_name=False)
distname, version = str(distname), str(version)
except ImportError as e:
distname, version = 'unknown', ''
# Grabs major version from tuple on redhat; on other platforms
# grab the first legal identifier in the version field. On
# debian you get things like 'wheezy/sid'; sid means unstable.
# We just record 'wheezy' and don't get quite so detailed.
version = re.split(r'[^\w-]', version)[0]
super(LinuxDistro, self).__init__(distname, version)
| Fix bug in distribution detection on unsupported platforms. | Fix bug in distribution detection on unsupported platforms.
| Python | lgpl-2.1 | EmreAtes/spack,TheTimmy/spack,mfherbst/spack,tmerrick1/spack,iulian787/spack,skosukhin/spack,matthiasdiener/spack,mfherbst/spack,lgarren/spack,EmreAtes/spack,iulian787/spack,EmreAtes/spack,matthiasdiener/spack,mfherbst/spack,LLNL/spack,TheTimmy/spack,skosukhin/spack,skosukhin/spack,LLNL/spack,krafczyk/spack,krafczyk/spack,mfherbst/spack,matthiasdiener/spack,LLNL/spack,tmerrick1/spack,krafczyk/spack,TheTimmy/spack,iulian787/spack,krafczyk/spack,TheTimmy/spack,matthiasdiener/spack,lgarren/spack,iulian787/spack,tmerrick1/spack,EmreAtes/spack,mfherbst/spack,matthiasdiener/spack,lgarren/spack,tmerrick1/spack,iulian787/spack,lgarren/spack,lgarren/spack,krafczyk/spack,skosukhin/spack,LLNL/spack,EmreAtes/spack,skosukhin/spack,TheTimmy/spack,tmerrick1/spack,LLNL/spack | python | ## Code Before:
import re
from external.distro import linux_distribution
from spack.architecture import OperatingSystem
class LinuxDistro(OperatingSystem):
""" This class will represent the autodetected operating system
for a Linux System. Since there are many different flavors of
Linux, this class will attempt to encompass them all through
autodetection using the python module platform and the method
platform.dist()
"""
def __init__(self):
distname, version, _ = linux_distribution(
full_distribution_name=False)
distname, version = str(distname), str(version)
# Grabs major version from tuple on redhat; on other platforms
# grab the first legal identifier in the version field. On
# debian you get things like 'wheezy/sid'; sid means unstable.
# We just record 'wheezy' and don't get quite so detailed.
version = re.split(r'[^\w-]', version)[0]
super(LinuxDistro, self).__init__(distname, version)
## Instruction:
Fix bug in distribution detection on unsupported platforms.
## Code After:
import re
from spack.architecture import OperatingSystem
class LinuxDistro(OperatingSystem):
""" This class will represent the autodetected operating system
for a Linux System. Since there are many different flavors of
Linux, this class will attempt to encompass them all through
autodetection using the python module platform and the method
platform.dist()
"""
def __init__(self):
try:
# This will throw an error if imported on a non-Linux platform.
from external.distro import linux_distribution
distname, version, _ = linux_distribution(
full_distribution_name=False)
distname, version = str(distname), str(version)
except ImportError as e:
distname, version = 'unknown', ''
# Grabs major version from tuple on redhat; on other platforms
# grab the first legal identifier in the version field. On
# debian you get things like 'wheezy/sid'; sid means unstable.
# We just record 'wheezy' and don't get quite so detailed.
version = re.split(r'[^\w-]', version)[0]
super(LinuxDistro, self).__init__(distname, version)
| import re
- from external.distro import linux_distribution
from spack.architecture import OperatingSystem
class LinuxDistro(OperatingSystem):
""" This class will represent the autodetected operating system
for a Linux System. Since there are many different flavors of
Linux, this class will attempt to encompass them all through
autodetection using the python module platform and the method
platform.dist()
"""
def __init__(self):
+ try:
+ # This will throw an error if imported on a non-Linux platform.
+ from external.distro import linux_distribution
- distname, version, _ = linux_distribution(
+ distname, version, _ = linux_distribution(
? ++++
- full_distribution_name=False)
+ full_distribution_name=False)
? ++++
- distname, version = str(distname), str(version)
+ distname, version = str(distname), str(version)
? ++++
+ except ImportError as e:
+ distname, version = 'unknown', ''
# Grabs major version from tuple on redhat; on other platforms
# grab the first legal identifier in the version field. On
# debian you get things like 'wheezy/sid'; sid means unstable.
# We just record 'wheezy' and don't get quite so detailed.
version = re.split(r'[^\w-]', version)[0]
super(LinuxDistro, self).__init__(distname, version) | 12 | 0.48 | 8 | 4 |
91760ce993adf9e9d45bae31719b60ec8493fd4c | README.md | README.md |
The cartodb-python project is a Python client for the [CartoDB SQL API](http://developers.cartodb.com/api/sql.html) that supports [authentication using OAuth](http://developers.cartodb.com/api/authentication.html).
# Installation #
You can install cartodb-python by cloning this repository or by using [Pip](http://pypi.python.org/pypi/pip), a Python package installer similar to easy_install.
```bash
pip install -e git+git://github.com/javisantana/cartodb-python.git#egg=cartodb
```
# Usage example #
The following example requires your CartoDB API consmer key and consumer secret. Refer to the [CartoDB Authentication documentation](http://developers.cartodb.com/api/authentication.html) for details.
```python
user = 'me@mail.com'
password = 'secret'
CONSUMER_KEY='YOUR_CARTODB_CONSUMER_KEY'
CONSUMER_SECRET='YOUR_CARTODB_CONSUMER_SECRET'
cartodb_domain = 'YOUR_CARTODB_DOMAIN'
cl = CartoDB(CONSUMER_KEY, CONSUMER_SECRET, user, password, cartodb_domain)
try:
print cl.sql('select * from mytable')
except CartoDBException as e:
print ("some error ocurred", e)
``` |
The cartodb-python project is a Python client for the [CartoDB SQL API](http://developers.cartodb.com/api/sql.html) that supports [authentication using OAuth](http://developers.cartodb.com/api/authentication.html).
# Installation #
You can install cartodb-python by cloning this repository or by using [Pip](http://pypi.python.org/pypi/pip), a Python package installer similar to easy_install.
```bash
pip install -e git+git://github.com/javisantana/cartodb-python.git#egg=cartodb
```
Note that cartodb-python depends on the python-oauth2 module:
```bash
sudo apt-get install python-oauth2
```
# Usage example #
The following example requires your CartoDB API consmer key and consumer secret. Refer to the [CartoDB Authentication documentation](http://developers.cartodb.com/api/authentication.html) for details.
```python
user = 'me@mail.com'
password = 'secret'
CONSUMER_KEY='YOUR_CARTODB_CONSUMER_KEY'
CONSUMER_SECRET='YOUR_CARTODB_CONSUMER_SECRET'
cartodb_domain = 'YOUR_CARTODB_DOMAIN'
cl = CartoDB(CONSUMER_KEY, CONSUMER_SECRET, user, password, cartodb_domain)
try:
print cl.sql('select * from mytable')
except CartoDBException as e:
print ("some error ocurred", e)
``` | Add details for the python-oauth2 dependency. | Add details for the python-oauth2 dependency. | Markdown | bsd-3-clause | CartoDB/cartodb-python,CartoDB/carto-python | markdown | ## Code Before:
The cartodb-python project is a Python client for the [CartoDB SQL API](http://developers.cartodb.com/api/sql.html) that supports [authentication using OAuth](http://developers.cartodb.com/api/authentication.html).
# Installation #
You can install cartodb-python by cloning this repository or by using [Pip](http://pypi.python.org/pypi/pip), a Python package installer similar to easy_install.
```bash
pip install -e git+git://github.com/javisantana/cartodb-python.git#egg=cartodb
```
# Usage example #
The following example requires your CartoDB API consmer key and consumer secret. Refer to the [CartoDB Authentication documentation](http://developers.cartodb.com/api/authentication.html) for details.
```python
user = 'me@mail.com'
password = 'secret'
CONSUMER_KEY='YOUR_CARTODB_CONSUMER_KEY'
CONSUMER_SECRET='YOUR_CARTODB_CONSUMER_SECRET'
cartodb_domain = 'YOUR_CARTODB_DOMAIN'
cl = CartoDB(CONSUMER_KEY, CONSUMER_SECRET, user, password, cartodb_domain)
try:
print cl.sql('select * from mytable')
except CartoDBException as e:
print ("some error ocurred", e)
```
## Instruction:
Add details for the python-oauth2 dependency.
## Code After:
The cartodb-python project is a Python client for the [CartoDB SQL API](http://developers.cartodb.com/api/sql.html) that supports [authentication using OAuth](http://developers.cartodb.com/api/authentication.html).
# Installation #
You can install cartodb-python by cloning this repository or by using [Pip](http://pypi.python.org/pypi/pip), a Python package installer similar to easy_install.
```bash
pip install -e git+git://github.com/javisantana/cartodb-python.git#egg=cartodb
```
Note that cartodb-python depends on the python-oauth2 module:
```bash
sudo apt-get install python-oauth2
```
# Usage example #
The following example requires your CartoDB API consmer key and consumer secret. Refer to the [CartoDB Authentication documentation](http://developers.cartodb.com/api/authentication.html) for details.
```python
user = 'me@mail.com'
password = 'secret'
CONSUMER_KEY='YOUR_CARTODB_CONSUMER_KEY'
CONSUMER_SECRET='YOUR_CARTODB_CONSUMER_SECRET'
cartodb_domain = 'YOUR_CARTODB_DOMAIN'
cl = CartoDB(CONSUMER_KEY, CONSUMER_SECRET, user, password, cartodb_domain)
try:
print cl.sql('select * from mytable')
except CartoDBException as e:
print ("some error ocurred", e)
``` |
The cartodb-python project is a Python client for the [CartoDB SQL API](http://developers.cartodb.com/api/sql.html) that supports [authentication using OAuth](http://developers.cartodb.com/api/authentication.html).
# Installation #
You can install cartodb-python by cloning this repository or by using [Pip](http://pypi.python.org/pypi/pip), a Python package installer similar to easy_install.
```bash
pip install -e git+git://github.com/javisantana/cartodb-python.git#egg=cartodb
```
+
+ Note that cartodb-python depends on the python-oauth2 module:
+
+ ```bash
+ sudo apt-get install python-oauth2
+ ```
+
# Usage example #
The following example requires your CartoDB API consmer key and consumer secret. Refer to the [CartoDB Authentication documentation](http://developers.cartodb.com/api/authentication.html) for details.
```python
user = 'me@mail.com'
password = 'secret'
CONSUMER_KEY='YOUR_CARTODB_CONSUMER_KEY'
CONSUMER_SECRET='YOUR_CARTODB_CONSUMER_SECRET'
cartodb_domain = 'YOUR_CARTODB_DOMAIN'
cl = CartoDB(CONSUMER_KEY, CONSUMER_SECRET, user, password, cartodb_domain)
try:
print cl.sql('select * from mytable')
except CartoDBException as e:
print ("some error ocurred", e)
``` | 7 | 0.241379 | 7 | 0 |
c5f56c44f1f757df928755f64f40679971a85dfd | .travis.yml | .travis.yml | language: objective-c
before_install:
- sudo gem install xcpretty
branches:
only:
- master
xcode_project: TextFieldCounter/TextFieldCounter.xcodeproj
xcode_scheme: TextFieldCounter
osx_image: xcode8.2
xcode_sdk: iphonesimulator9.3
script:
- xcodebuild -project TextFieldCounter/TextFieldCounter.xcodeproj -scheme 'TextFieldCounter' -sdk iphonesimulator build | xcpretty -c && exit ${PIPESTATUS[0]}
| before_install:
- sudo gem install xcpretty
branches:
only:
- master
language:
- swift
osx_image: xcode11.2
script:
- xcodebuild -scheme 'TextFieldCounter' -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 8,OS=13.2' build test | xcpretty -c
after_success:
- bash <(curl -s https://codecov.io/bash)
| Update Travis CI config file | Update Travis CI config file | YAML | mit | serralvo/TextFieldCounter,serralvo/TextFieldCounter | yaml | ## Code Before:
language: objective-c
before_install:
- sudo gem install xcpretty
branches:
only:
- master
xcode_project: TextFieldCounter/TextFieldCounter.xcodeproj
xcode_scheme: TextFieldCounter
osx_image: xcode8.2
xcode_sdk: iphonesimulator9.3
script:
- xcodebuild -project TextFieldCounter/TextFieldCounter.xcodeproj -scheme 'TextFieldCounter' -sdk iphonesimulator build | xcpretty -c && exit ${PIPESTATUS[0]}
## Instruction:
Update Travis CI config file
## Code After:
before_install:
- sudo gem install xcpretty
branches:
only:
- master
language:
- swift
osx_image: xcode11.2
script:
- xcodebuild -scheme 'TextFieldCounter' -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 8,OS=13.2' build test | xcpretty -c
after_success:
- bash <(curl -s https://codecov.io/bash)
| - language: objective-c
-
before_install:
- sudo gem install xcpretty
branches:
only:
- master
- xcode_project: TextFieldCounter/TextFieldCounter.xcodeproj
- xcode_scheme: TextFieldCounter
-
+ language:
+ - swift
+
- osx_image: xcode8.2
? ^
+ osx_image: xcode11.2
? ^^
- xcode_sdk: iphonesimulator9.3
script:
- - xcodebuild -project TextFieldCounter/TextFieldCounter.xcodeproj -scheme 'TextFieldCounter' -sdk iphonesimulator build | xcpretty -c && exit ${PIPESTATUS[0]}
+ - xcodebuild -scheme 'TextFieldCounter' -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 8,OS=13.2' build test | xcpretty -c
+
+ after_success:
+ - bash <(curl -s https://codecov.io/bash) | 16 | 0.941176 | 8 | 8 |
a5638af164a86ea9c0facaf36deb671eb98ae374 | app.rb | app.rb | require 'sinatra'
require 'net/http'
set :server, 'thin'
base_url = ''
get '/' do
Net::HTTP.post_form(URI.parse(
'https://api.justyo.co/yoall/'),
{
'api_token' => ENV['YO_KEY'],
'link' => 'http://yotext.co/show/?text=COFFEE TIME?'
}
)
end
| require 'sinatra'
require 'net/http'
set :server, 'thin'
base_url = ''
get '/' do
# do a YoAll
status = Net::HTTP.post_form(URI.parse(
'https://api.justyo.co/yoall/'),
{
'api_token' => ENV['YO_KEY'],
'link' => 'http://yotext.co/show/?text=COFFEE TIME?'
}
)
# terse status response
if status
'success'
else
'failed to YoAll'
end
end
| Hide inner workings from output, just in case | Hide inner workings from output, just in case
| Ruby | mit | sinisterstuf/yo-coffee,sinisterstuf/yo-coffee | ruby | ## Code Before:
require 'sinatra'
require 'net/http'
set :server, 'thin'
base_url = ''
get '/' do
Net::HTTP.post_form(URI.parse(
'https://api.justyo.co/yoall/'),
{
'api_token' => ENV['YO_KEY'],
'link' => 'http://yotext.co/show/?text=COFFEE TIME?'
}
)
end
## Instruction:
Hide inner workings from output, just in case
## Code After:
require 'sinatra'
require 'net/http'
set :server, 'thin'
base_url = ''
get '/' do
# do a YoAll
status = Net::HTTP.post_form(URI.parse(
'https://api.justyo.co/yoall/'),
{
'api_token' => ENV['YO_KEY'],
'link' => 'http://yotext.co/show/?text=COFFEE TIME?'
}
)
# terse status response
if status
'success'
else
'failed to YoAll'
end
end
| require 'sinatra'
require 'net/http'
set :server, 'thin'
base_url = ''
get '/' do
+
+ # do a YoAll
- Net::HTTP.post_form(URI.parse(
+ status = Net::HTTP.post_form(URI.parse(
? +++++++++
'https://api.justyo.co/yoall/'),
{
'api_token' => ENV['YO_KEY'],
'link' => 'http://yotext.co/show/?text=COFFEE TIME?'
}
)
+
+ # terse status response
+ if status
+ 'success'
+ else
+ 'failed to YoAll'
+ end
+
end | 12 | 0.75 | 11 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.