text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Correct routing on home page | @extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>
<div class="panel-body">
<ul>
<li class="h3" style="list-style: none;"><a href="{{ route('domain.create') }}">Create New Site</a></li>
<li class="h3" style="list-style: none;"><a href="{{ route('domain.index') }}">View Existing Sites</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
@endsection
| @extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>
<div class="panel-body">
<ul>
<li class="h3"><a href="{{ url('domain.create') }}">Create New Site</a></li>
<li class="h3"><a href="{{ url('domain.index') }}">View Existing Sites</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
@endsection
|
Handle last chunk when less than size. | package cryptanalysis
import ()
func Chunk(data []byte, size int) [][]byte {
count := len(data) - size
var chunks [][]byte
for i:=0; i<count; i=i+size {
chunks = append(chunks, data[i:i+size])
}
chunks = append(chunks, data[count*size:])
return chunks
}
func Transpose(data [][]byte) [][]byte {
var transpose [][]byte
for i, _ := range data[0] {
var temp []byte
for j, _ := range data {
temp = append(temp, data[j][i])
}
transpose = append(transpose, temp)
}
return transpose
}
func PadPkcs7(data []byte, size int) []byte {
if len(data) < size {
pad := size - len(data)
for i:=0; i<pad; i++ {
data = append(data, byte(pad))
}
}
return data
}
| package cryptanalysis
import ()
func Chunk(data []byte, size int) [][]byte {
var chunks [][]byte
for i:=0; i<len(data); i=i+size {
chunks = append(chunks, data[i:i+size])
}
return chunks
}
func Transpose(data [][]byte) [][]byte {
var transpose [][]byte
for i, _ := range data[0] {
var temp []byte
for j, _ := range data {
temp = append(temp, data[j][i])
}
transpose = append(transpose, temp)
}
return transpose
}
func PadPkcs7(data []byte, size int) []byte {
if len(data) < size {
pad := size - len(data)
for i:=0; i<pad; i++ {
data = append(data, byte(pad))
}
}
return data
}
|
Decrease concurrency of Selenium tests | define({
suites: false,
proxyPort: 9090,
proxyUrl: "http://localhost:9090/",
capabilities: {
"selenium-version": "2.45.0"
},
tunnel: "SauceLabsTunnel",
tunnelOptions: {
port: 4444
},
environments: [
{ browserName: "Firefox" },
{ browserName: "Internet Explorer", platform: "Windows 8.1", version: "11" },
{ browserName: "Chrome" }
],
maxConcurrency: 1,
functionalSuites: [
"tests/functional/mainpage",
"tests/functional/admin/auth/signin",
"tests/functional/admin/dashboard/dashboard",
"tests/functional/admin/dashboard/comics/create",
],
excludeInstrumentation: /tests|node_modules/
}); | define({
suites: false,
proxyPort: 9090,
proxyUrl: "http://localhost:9090/",
capabilities: {
"selenium-version": "2.45.0"
},
tunnel: "SauceLabsTunnel",
tunnelOptions: {
port: 4444
},
environments: [
{ browserName: "Firefox" },
{ browserName: "Internet Explorer", platform: "Windows 8.1", version: "11" },
{ browserName: "Chrome" }
],
maxConcurrency: 3,
functionalSuites: [
"tests/functional/mainpage",
"tests/functional/admin/auth/signin",
"tests/functional/admin/dashboard/dashboard",
"tests/functional/admin/dashboard/comics/create",
],
excludeInstrumentation: /tests|node_modules/
}); |
Add Korean translation "today, meridiem" | /**
* Korean translation for bootstrap-datetimepicker
* Gu Youn <http://github.com/guyoun>
* Baekjoon Choi <http://github.com/Baekjoon>
*/
;(function($){
$.fn.datetimepicker.dates['kr'] = {
days: ["์ผ์์ผ", "์์์ผ", "ํ์์ผ", "์์์ผ", "๋ชฉ์์ผ", "๊ธ์์ผ", "ํ ์์ผ", "์ผ์์ผ"],
daysShort: ["์ผ", "์", "ํ", "์", "๋ชฉ", "๊ธ", "ํ ", "์ผ"],
daysMin: ["์ผ", "์", "ํ", "์", "๋ชฉ", "๊ธ", "ํ ", "์ผ"],
months: ["1์", "2์", "3์", "4์", "5์", "6์", "7์", "8์", "9์", "10์", "11์", "12์"],
monthsShort: ["1์", "2์", "3์", "4์", "5์", "6์", "7์", "8์", "9์", "10์", "11์", "12์"],
suffix: [],
meridiem: ["์ค์ ", "์คํ"],
today: "์ค๋",
};
}(jQuery));
| /**
* Korean translation for bootstrap-datetimepicker
* Gu Youn <http://github.com/guyoun>
*/
;(function($){
$.fn.datetimepicker.dates['kr'] = {
days: ["์ผ์์ผ", "์์์ผ", "ํ์์ผ", "์์์ผ", "๋ชฉ์์ผ", "๊ธ์์ผ", "ํ ์์ผ", "์ผ์์ผ"],
daysShort: ["์ผ", "์", "ํ", "์", "๋ชฉ", "๊ธ", "ํ ", "์ผ"],
daysMin: ["์ผ", "์", "ํ", "์", "๋ชฉ", "๊ธ", "ํ ", "์ผ"],
months: ["1์", "2์", "3์", "4์", "5์", "6์", "7์", "8์", "9์", "10์", "11์", "12์"],
monthsShort: ["1์", "2์", "3์", "4์", "5์", "6์", "7์", "8์", "9์", "10์", "11์", "12์"],
suffix: [],
meridiem: []
};
}(jQuery));
|
Add derived eves to Eves array | import settings from './helpers/settings'
import {findDistance, limitPositions, chooseOne, randomInt, getAvgPostion} from './helpers/general'
import {applyLimbForces, updateBodyPartPositions} from './helpers/movement'
import {createEveData, deriveEveData} from './helpers/eveCreation'
import {killEve, collectStats, saveStateToDB} from './helpers/lifeCycle'
//Create initial data:
var Eves = [];
for(var i = 0; i < settings.eveCount; i ++) {
Eves.push(createEveData());
}
//Animate:
setInterval(() => {
applyLimbForces(Eves);
updateBodyPartPositions(Eves);
}, settings.stepTime)
//Selective Pressure:
setInterval(() => {
killEve(Eves);
var eve = chooseOne(Eves);
Eves.push(deriveEveData(eve));
}, settings.killTime)
// //Check progress
// setInterval(() => {
// console.log('Eve 1, limb1:', Eves[0].limbs[0])
// }, 1000)
// setTimeout(animate, 1000);
// setInterval(collectStats, 10000);
// setInterval(function() {
// killEves();
// Eves.push(deriveEveData(chooseOne(Eves)));
// generateEves();
// }, 10000);
//setInterval(saveStateToDB, 10000)
| import settings from './helpers/settings'
import {findDistance, limitPositions, chooseOne, randomInt, getAvgPostion} from './helpers/general'
import {applyLimbForces, updateBodyPartPositions} from './helpers/movement'
import {createEveData, deriveEveData} from './helpers/eveCreation'
import {killEve, collectStats, saveStateToDB} from './helpers/lifeCycle'
//Create initial data:
var Eves = [];
for(var i = 0; i < settings.eveCount; i ++) {
Eves.push(createEveData());
}
//Animate:
setInterval(() => {
applyLimbForces(Eves);
updateBodyPartPositions(Eves);
// console.log('YO!',chooseOne.valueOf())
}, settings.stepTime)
//Selective Pressure:
setInterval(() => {
killEve(Eves);
var eve = chooseOne(Eves);
deriveEveData(eve);
}, settings.killTime)
// //Check progress
// setInterval(() => {
// console.log('Eve 1, limb1:', Eves[0].limbs[0])
// }, 1000)
// setTimeout(animate, 1000);
// setInterval(collectStats, 10000);
// setInterval(function() {
// killEves();
// Eves.push(deriveEveData(chooseOne(Eves)));
// generateEves();
// }, 10000);
//setInterval(saveStateToDB, 10000)
|
Remove test that crashes ArtNet receiver | import collections, copy, queue
from . import control
from .. util import artnet_message, log, server_cache, udp
QUEUE_TIMEOUT = 0.1
class ArtNet(control.ExtractedControl):
def __init__(self, *args, ip_address, port=artnet_message.UDP_PORT, **kwds):
super().__init__(*args, **kwds)
self.address = ip_address, port
def _convert(self, msg):
msg = artnet_message.bytes_to_message(msg)
msg = collections.OrderedDict((
('type', 'dmx'),
('net', msg.net),
('subUni', msg.subUni),
('data', msg.data)))
return super()._convert(msg)
def _make_thread(self):
return udp.Receiver(self.address, receive=self.receive)
| import collections, copy, queue
from . import control
from .. util import artnet_message, log, server_cache, udp
QUEUE_TIMEOUT = 0.1
class ArtNet(control.ExtractedControl):
def __init__(self, *args, ip_address, port=artnet_message.UDP_PORT, **kwds):
super().__init__(*args, **kwds)
self.address = ip_address, port
def _convert(self, msg):
msg = artnet_message.bytes_to_message(msg)
assert any(i for i in msg.data)
msg = collections.OrderedDict((
('type', 'dmx'),
('net', msg.net),
('subUni', msg.subUni),
('data', msg.data)))
return super()._convert(msg)
def _make_thread(self):
return udp.Receiver(self.address, receive=self.receive)
|
Make it so we don't rely on weird rounding in python to assign card to the correct index | import random
class Blackjack:
def __init__(self):
self.deck = range(1, 53)
self.shuffle()
self.deal()
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
self.player = [None, None]
self.dealer = [None, None]
for i in xrange(4):
if i % 2:
self.player[i/2] = self.deck.pop()
else:
self.dealer[(i-1)/2] = self.deck.pop()
if __name__ == "__main__":
"""
This is testing only, this module is intended
to be imported.
"""
bj = Blackjack()
print bj.player
print bj.dealer
| import random
class Blackjack:
def __init__(self):
self.deck = range(1, 53)
self.shuffle()
self.deal()
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
self.player = [None, None]
self.dealer = [None, None]
for i in xrange(4):
if i % 2:
self.player[i/2] = self.deck.pop()
else:
self.dealer[i/2] = self.deck.pop()
if __name__ == "__main__":
"""
This is testing only, this module is intended
to be imported.
"""
bj = Blackjack()
print bj.player
print bj.dealer
|
Switch to Python 3.4 wording. | #!/usr/bin/env python
#
# **THIS SCRIPT IS WRITTEN FOR PYTHON 3.4.**
#
"""
Usage: python3.4 parse.py ELECTION_NAME PRECINCTS.csv WINEDS.txt OUTPUT.tsv
Parses the given files and writes a new output file to stdout.
The new output file is tab-delimited (.tsv). Tabs are used since some
fields contain commas (e.g. "US Representative, District 12").
Arguments:
ELECTION_NAME: the name of the election for display purposes.
This appears in the first line of the output file.
An example value is "San Francisco June 3, 2014 Election".
PRECINCTS.csv: path to a CSV file mapping precincts to their
different districts and neighborhoods.
WINEDS.txt: path to a TXT export file from the WinEDS Reporting Tool.
The report contains vote totals for each precinct in each contest,
along with "registered voters" and "ballots cast" totals.
OUTPUT.tsv: desired output path.
In the above, relative paths will be interpreted as relative to the
current working directory.
"""
import sys
from pywineds.parser import main
if __name__ == "__main__":
main(__doc__, sys.argv)
| #!/usr/bin/env python
#
# **THIS SCRIPT IS WRITTEN FOR PYTHON 3.**
#
"""
Usage: python3.4 parse.py ELECTION_NAME PRECINCTS.csv WINEDS.txt OUTPUT.tsv
Parses the given files and writes a new output file to stdout.
The new output file is tab-delimited (.tsv). Tabs are used since some
fields contain commas (e.g. "US Representative, District 12").
Arguments:
ELECTION_NAME: the name of the election for display purposes.
This appears in the first line of the output file.
An example value is "San Francisco June 3, 2014 Election".
PRECINCTS.csv: path to a CSV file mapping precincts to their
different districts and neighborhoods.
WINEDS.txt: path to a TXT export file from the WinEDS Reporting Tool.
The report contains vote totals for each precinct in each contest,
along with "registered voters" and "ballots cast" totals.
OUTPUT.tsv: desired output path.
In the above, relative paths will be interpreted as relative to the
current working directory.
"""
import sys
from pywineds.parser import main
if __name__ == "__main__":
main(__doc__, sys.argv)
|
Disable convertion to divs, preserve paragraphs. | /**
* Wysiwyg related javascript
*/
// =require ./lib/redactor.js
(function($){
$(document).ready( function() {
/**
* Minimal wysiwyg support
*/
$('.wysiwyg-minimal').redactor({
airButtons: ['bold', 'italic', 'deleted', '|', 'link'],
air: true
});
/**
* Basic wysiwyg support
*/
$('.wysiwyg').redactor();
/**
* Assets-aware wysiwyg support
*/
$('.wysiwyg-full').redactor({
fixed: true,
wym: true,
convertDivs: false,
imageUpload: '/images',
imageGetJson: '/images',
imageUploadErrorCallback: function( o, json ) { alert( json.error ); },
fileUpload: '/uploads',
fileUploadErrorCallback: function( o, json ) { alert( json.error ); },
uploadFields: {
authenticity_token: $('meta[name="csrf-token"]').attr('content'),
assetable_type: $('.assetable_type').val(),
assetable_id: $('.assetable_id').val()
}
});
});
}(jQuery))
| /**
* Wysiwyg related javascript
*/
// =require ./lib/redactor.js
(function($){
$(document).ready( function() {
/**
* Minimal wysiwyg support
*/
$('.wysiwyg-minimal').redactor({
airButtons: ['bold', 'italic', 'deleted', '|', 'link'],
air: true
});
/**
* Basic wysiwyg support
*/
$('.wysiwyg').redactor();
/**
* Assets-aware wysiwyg support
*/
$('.wysiwyg-full').redactor({
fixed: true,
wym: true,
imageUpload: '/images',
imageGetJson: '/images',
imageUploadErrorCallback: function( o, json ) { alert( json.error ); },
fileUpload: '/uploads',
fileUploadErrorCallback: function( o, json ) { alert( json.error ); },
uploadFields: {
authenticity_token: $('meta[name="csrf-token"]').attr('content'),
assetable_type: $('.assetable_type').val(),
assetable_id: $('.assetable_id').val()
}
});
});
}(jQuery))
|
Revert "switched to using npipe instead of socket"
This reverts commit d115fc9c0f2c97e46c216179aea4f4252e7a08bb. | package main
import (
"encoding/json"
"fmt"
"github.com/gwwfps/lolconf-probe/display"
"log"
"net/http"
)
type handler func(http.ResponseWriter, *http.Request)
type inner func() (interface{}, error)
func wrapHandler(h inner) handler {
return func(w http.ResponseWriter, r *http.Request) {
result, handlerError := h()
if handlerError != nil {
writeError(w, handlerError)
return
}
serialized, marshalError := json.Marshal(result)
if marshalError != nil {
writeError(w, marshalError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprint(w, string(serialized))
}
}
func writeError(w http.ResponseWriter, e error) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, e.Error())
}
func main() {
http.HandleFunc("/resolutions", wrapHandler(display.ListAvailableResolutions))
e := http.ListenAndServe("127.0.0.1:5532", nil)
if e != nil {
log.Fatal("ListenAndServe: ", e)
}
}
| package main
import (
"encoding/json"
"fmt"
"github.com/gwwfps/lolconf-probe/display"
"github.com/natefinch/npipe"
"log"
"net/http"
)
type handler func(http.ResponseWriter, *http.Request)
type inner func() (interface{}, error)
func wrapHandler(h inner) handler {
return func(w http.ResponseWriter, r *http.Request) {
result, handlerError := h()
if handlerError != nil {
writeError(w, handlerError)
return
}
serialized, marshalError := json.Marshal(result)
if marshalError != nil {
writeError(w, marshalError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprint(w, string(serialized))
}
}
func writeError(w http.ResponseWriter, e error) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, e.Error())
}
func main() {
http.HandleFunc("/resolutions", wrapHandler(display.ListAvailableResolutions))
l, e := npipe.Listen(`\\.\pipe\lolconf`)
if e != nil {
log.Fatal("Error listening on pipe: ", e)
}
serveError := http.Serve(l, nil)
if serveError != nil {
log.Fatal("Http serve error: ", serveError)
}
}
|
Make the get_status script quieter | #!/usr/bin/env python
# This script uses the built-in Python module to check whether a given
# pipeline is passing, failing, or blocked. To check for a blocked
# pipeline, it looks through all upstream pipelines for any that are
# failing or paused.
from __future__ import print_function
import json
import gocd_parser.stream_status
from gocd_parser.retriever import server
from gocd_parser import gocd_argparse, gocd_logger
# uncomment to set a default "INFO" logger
#logger = gocd_logger.get()
arg_parser = gocd_argparse.get()
arg_parser.add_argument(
'-n', '--pipeline_name',
required=True,
help='The name of the pipeline to check',
)
args = arg_parser.parse_args()
go_server = server.Server(args.go_url, args.go_user, args.go_password)
# Retrieve the graph of the value stream
status = gocd_parser.stream_status.StreamStatus(go_server, args.pipeline_name)
# Send its blocker info to stdout
print( json.dumps( status.dump(), sort_keys=True, indent=2))
| #!/usr/bin/env python
# This script uses the built-in Python module to check whether a given
# pipeline is passing, failing, or blocked. To check for a blocked
# pipeline, it looks through all upstream pipelines for any that are
# failing or paused.
from __future__ import print_function
import json
import gocd_parser.stream_status
from gocd_parser.retriever import server
from gocd_parser import gocd_argparse, gocd_logger
logger = gocd_logger.get()
arg_parser = gocd_argparse.get()
arg_parser.add_argument(
'-n', '--pipeline_name',
required=True,
help='The name of the pipeline to check',
)
args = arg_parser.parse_args()
go_server = server.Server(args.go_url, args.go_user, args.go_password)
# Retrieve the graph of the value stream
status = gocd_parser.stream_status.StreamStatus(go_server, args.pipeline_name)
# Send its blocker info to stdout
print( json.dumps( status.dump(), sort_keys=True, indent=2))
|
Fix bug in ticket revoke controller. | angular.module('billett.admin').controller('AdminTicketRevokeController', function ($http, $modalInstance, order, ticket) {
var ctrl = this;
ctrl.order = order;
ctrl.ticket = ticket;
ctrl.revoke = function () {
ctrl.sending = true;
$http.post('api/ticket/' + ctrl.ticket.id + '/revoke', {
'paymentgroup_id': ctrl.paymentgroup.id
}).then(function () {
$modalInstance.close();
}, function () {
alert("Ukjent feil oppsto");
delete ctrl.sending;
});
};
ctrl.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
| angular.module('billett.admin').controller('AdminTicketRevokeController', function ($http, $modalInstance, order, ticket) {
var ctrl = this;
ctrl.order = order;
ctrl.ticket = ticket;
ctrl.revoke = function () {
ctrl.sending = true;
$http.post('api/ticket/' + ticket.id + '/revoke', {
'paymentgroup_id': ctrl.active_paymentgroup.id
}).then(function () {
$modalInstance.close();
}, function () {
alert("Ukjent feil oppsto");
delete ctrl.sending;
});
};
ctrl.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
|
Add setCheckedPositions() for multi-select case. | package com.nex3z.togglebuttongroup;
import android.content.Context;
import android.util.AttributeSet;
import java.util.Set;
public class MultiSelectToggleGroup extends ToggleButtonGroup {
private static final String LOG_TAG = MultiSelectToggleGroup.class.getSimpleName();
public MultiSelectToggleGroup(Context context) {
this(context, null);
}
public MultiSelectToggleGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onToggleButtonClicked(int position) {
ToggleButton button = mButtons.get(position);
boolean isChecked = button.isChecked();
isChecked = !isChecked;
button.setChecked(isChecked, isAnimationEnabled());
if (mListener != null) {
mListener.onCheckedStateChange(position, isChecked);
}
}
/**
* Check buttons at the positions from the given set.
*
* @param checkedPositions positions to be checked
*/
public void setCheckedPositions(Set<Integer> checkedPositions) {
uncheckAll();
for (int position : checkedPositions) {
setCheckedAt(position, true);
}
}
}
| package com.nex3z.togglebuttongroup;
import android.content.Context;
import android.util.AttributeSet;
public class MultiSelectToggleGroup extends ToggleButtonGroup {
private static final String LOG_TAG = MultiSelectToggleGroup.class.getSimpleName();
public MultiSelectToggleGroup(Context context) {
this(context, null);
}
public MultiSelectToggleGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onToggleButtonClicked(int position) {
ToggleButton button = mButtons.get(position);
boolean isChecked = button.isChecked();
isChecked = !isChecked;
button.setChecked(isChecked, isAnimationEnabled());
if (mListener != null) {
mListener.onCheckedStateChange(position, isChecked);
}
}
}
|
Add CSRF middleware to main app stack. | <?php namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Routing\Stack\Builder as Stack;
use Illuminate\Foundation\Support\Providers\AppServiceProvider as ServiceProvider;
class AppServiceProvider extends ServiceProvider {
/**
* All of the application's route middleware keys.
*
* @var array
*/
protected $middleware = [
'auth' => 'App\Http\Middleware\AuthMiddleware',
'auth.basic' => 'App\Http\Middleware\BasicAuthMiddleware',
'csrf' => 'App\Http\Middleware\CsrfMiddleware',
'guest' => 'App\Http\Middleware\GuestMiddleware',
];
/**
* The application's middleware stack.
*
* @var array
*/
protected $stack = [
'App\Http\Middleware\MaintenanceMiddleware',
'Illuminate\Cookie\Middleware\Guard',
'Illuminate\Cookie\Middleware\Queue',
'Illuminate\Session\Middleware\Reader',
'Illuminate\Session\Middleware\Writer',
'Illuminate\View\Middleware\ErrorBinder',
'App\Http\Middleware\CsrfMiddleware',
];
/**
* Build the application stack based on the provider properties.
*
* @return void
*/
public function stack()
{
$this->app->stack(function(Stack $stack, Router $router)
{
return $stack
->middleware($this->stack)->then(function($request) use ($router)
{
return $router->dispatch($request);
});
});
}
}
| <?php namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Routing\Stack\Builder as Stack;
use Illuminate\Foundation\Support\Providers\AppServiceProvider as ServiceProvider;
class AppServiceProvider extends ServiceProvider {
/**
* All of the application's route middleware keys.
*
* @var array
*/
protected $middleware = [
'auth' => 'App\Http\Middleware\AuthMiddleware',
'auth.basic' => 'App\Http\Middleware\BasicAuthMiddleware',
'csrf' => 'App\Http\Middleware\CsrfMiddleware',
'guest' => 'App\Http\Middleware\GuestMiddleware',
];
/**
* The application's middleware stack.
*
* @var array
*/
protected $stack = [
'App\Http\Middleware\MaintenanceMiddleware',
'Illuminate\Cookie\Middleware\Guard',
'Illuminate\Cookie\Middleware\Queue',
'Illuminate\Session\Middleware\Reader',
'Illuminate\Session\Middleware\Writer',
'Illuminate\View\Middleware\ErrorBinder',
];
/**
* Build the application stack based on the provider properties.
*
* @return void
*/
public function stack()
{
$this->app->stack(function(Stack $stack, Router $router)
{
return $stack
->middleware($this->stack)->then(function($request) use ($router)
{
return $router->dispatch($request);
});
});
}
}
|
Simplify the parsing, since we're now passing in objects instead of arrays | 'use strict';
var Backbone = require('backbone');
var $ = require('jquery');
Backbone.$ = $;
var uniqueID = {};
var _ = require('../../bower_components/underscore');
var BusinessModel = require('../models/business-model');
module.exports = Backbone.Collection.extend({
model: BusinessModel,
url: function() {
var URLstring = 'api/0_0_1/' +
JSON.stringify(this.location) +
'/' +
JSON.stringify(this.params);
return URLstring;
},
initialize: function(location, params) {
this.location = location; // No longer necessary, b/c overwritten on search
this.params = params; // Eventually necessary?
},
parse: function(response) {
var allBusinesses = [];
var businesses = JSON.parse(response).businesses;
businesses.forEach(function(business) {
if (uniqueID[business.id]) { return; }
uniqueID[business.id] = true;
allBusinesses.push(business);
});
return allBusinesses;
},
search: function(latLong) {
this.location = latLong;
this.fetch();
}
}); | 'use strict';
var Backbone = require('backbone');
var $ = require('jquery');
Backbone.$ = $;
var _ = require('../../bower_components/underscore');
var BusinessModel = require('../models/business-model');
module.exports = Backbone.Collection.extend({
model: BusinessModel,
url: function() {
var URLstring = 'api/0_0_1/' +
JSON.stringify(this.location) +
'/' +
JSON.stringify(this.params);
return URLstring;
},
initialize: function(location, params) {
this.location = location; // No longer necessary, b/c overwritten on search
this.params = params; // Eventually necessary?
},
parse: function(response) {
/* The data comes in as an array of objects (one for each lat/long point),
each of which has a "businesses" attribute that holds an array of businesses.
We parse the businesses out of each object and return a master businesses array.
*/
var allBusinesses = [];
for (var i = 0; i < response.length; i++) {
var innerArray = JSON.parse(response[i]).businesses;
for (var j = 0; j < innerArray.length; j++) {
allBusinesses.push(innerArray[j]);
}
}
// Filter out duplicate businesses with Underscore
allBusinesses = _.uniq(allBusinesses, function(business) {
return business.id;
});
return allBusinesses;
},
search: function(latLongArray) {
this.location = latLongArray;
this.fetch();
}
}); |
Add parameter 'validate' to TLS handler | from __future__ import print_function
from pygelf.tcp import GelfTcpHandler
import ssl
import socket
import sys
class GelfTlsHandler(GelfTcpHandler):
def __init__(self, validate=False, ca_certs=None, **kwargs):
super(GelfTlsHandler, self).__init__(**kwargs)
if validate and ca_certs is None:
raise ValueError('CA bundle file path must be specified')
self.ca_certs = ca_certs
self.reqs = ssl.CERT_REQUIRED if validate else ssl.CERT_NONE
def makeSocket(self, timeout=1):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if hasattr(s, 'settimeout'):
s.settimeout(timeout)
try:
wrapped_socket = ssl.wrap_socket(s, ca_certs=self.ca_certs, cert_reqs=self.reqs)
wrapped_socket.connect((self.host, self.port))
return wrapped_socket
except Exception as e:
print('SSL socket exception:', e, file=sys.stderr)
| from __future__ import print_function
from pygelf.tcp import GelfTcpHandler
import ssl
import socket
import sys
class GelfTlsHandler(GelfTcpHandler):
def __init__(self, cert=None, **kwargs):
super(GelfTlsHandler, self).__init__(**kwargs)
self.cert = cert
def makeSocket(self, timeout=1):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if hasattr(s, 'settimeout'):
s.settimeout(timeout)
try:
if self.cert is None:
wrapped_socket = ssl.wrap_socket(s)
else:
wrapped_socket = ssl.wrap_socket(s, ca_certs=self.cert, cert_reqs=ssl.CERT_REQUIRED)
wrapped_socket.connect((self.host, self.port))
return wrapped_socket
except Exception as e:
print('SSL socket exception:', e, file=sys.stderr)
|
Add test for implicit ip addresses | 'use strict'
/* global describe, it */
var ipLocation = require('../')
var assert = require('assert')
function randomInt () {
return Math.round(Math.random() * 255)
}
function randomIp () {
return randomInt() + '.' +
randomInt() + '.' +
randomInt() + '.' +
randomInt()
}
describe('additional providers', function () {
var ip = randomIp()
describe('no additional providers', function () {
it('ip address: ' + ip, function (done) {
ipLocation(ip, [], function (err, res) {
assert(!err)
assert(typeof res === 'object')
assert(res.ip)
setTimeout(done, 1000)
})
})
})
})
describe('too many arguments', function () {
var ip = randomIp()
it('ip address: ' + ip, function () {
try {
ipLocation(ip, [], [], function () {})
} catch (ex) {
assert(ex)
}
})
})
describe('implicit (no) ip address', function () {
it('return data about requesting client', function (done) {
ipLocation(function (err, res) {
assert(!err)
assert(typeof res === 'object')
assert(res.ip)
setTimeout(done, 1000)
})
})
})
| 'use strict'
/* global describe, it */
var ipLocation = require('../')
var assert = require('assert')
function randomInt () {
return Math.round(Math.random() * 255)
}
function randomIp () {
return randomInt() + '.' +
randomInt() + '.' +
randomInt() + '.' +
randomInt()
}
describe('additional providers', function () {
var ip = randomIp()
describe('no additional providers', function () {
it('ip address: ' + ip, function (done) {
ipLocation(ip, [], function (err, res) {
assert(!err)
assert(typeof res === 'object')
assert(res.ip)
setTimeout(done, 1000)
})
})
})
})
describe('too many arguments', function () {
var ip = randomIp()
it('ip address: ' + ip, function () {
try {
ipLocation(ip, [], [], function () {})
} catch (ex) {
assert(ex)
}
})
})
|
Fix bug in download links | import copy
from django import template
from django.conf import settings
from games import models
register = template.Library()
def get_links(user_agent):
systems = ['ubuntu', 'fedora', 'linux']
downloads = copy.copy(settings.DOWNLOADS)
main_download = None
for system in systems:
if system in user_agent:
main_download = {system: downloads[system]}
downloads.pop(system)
if not main_download:
main_download = {'linux': downloads.pop('linux')}
return (main_download, downloads)
@register.inclusion_tag('includes/download_links.html', takes_context=True)
def download_links(context):
request = context['request']
user_agent = request.META.get('HTTP_USER_AGENT', '').lower()
context['main_download'], context['downloads'] = get_links(user_agent)
return context
@register.inclusion_tag('includes/featured_slider.html', takes_context=True)
def featured_slider(context):
context['featured_contents'] = models.Featured.objects.all()
return context
@register.inclusion_tag('includes/latest_games.html', takes_context=True)
def latest_games(context):
games = models.Game.objects.published().order_by('-created')[:5]
context['latest_games'] = games
return context
| import copy
from django import template
from django.conf import settings
from games import models
register = template.Library()
def get_links(user_agent):
systems = ['ubuntu', 'fedora', 'linux']
downloads = copy.copy(settings.DOWNLOADS)
main_download = None
for system in systems:
if system in user_agent:
main_download = {system: settings.DOWNLOADS[system]}
downloads.pop(system)
if not main_download:
main_download = {'linux': downloads.pop('linux')}
return (main_download, downloads)
@register.inclusion_tag('includes/download_links.html', takes_context=True)
def download_links(context):
request = context['request']
user_agent = request.META.get('HTTP_USER_AGENT', '').lower()
context['main_download'], context['downloads'] = get_links(user_agent)
return context
@register.inclusion_tag('includes/featured_slider.html', takes_context=True)
def featured_slider(context):
context['featured_contents'] = models.Featured.objects.all()
return context
@register.inclusion_tag('includes/latest_games.html', takes_context=True)
def latest_games(context):
games = models.Game.objects.published().order_by('-created')[:5]
context['latest_games'] = games
return context
|
Handle null parentNode from SVGInjector
Credit to @apires for the idea in #13. See issues #12 and iconic/SVGInjector#32. | import React, { PureComponent, PropTypes } from 'react'
import SVGInjector from 'svg-injector'
export default class ReactSVG extends PureComponent {
static defaultProps = {
callback: () => {},
className: '',
evalScripts: 'once'
}
static propTypes = {
callback: PropTypes.func,
className: PropTypes.string,
evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]),
path: PropTypes.string.isRequired
}
injectSVG() {
const {
evalScripts,
callback: each
} = this.props
if (this._img) {
SVGInjector(this._img, {
evalScripts,
each
})
}
}
componentDidMount() {
this.injectSVG()
}
componentDidUpdate() {
this.injectSVG()
}
render() {
const {
className,
path
} = this.props
return (
<div>
<img
ref={img => this._img = img}
className={className}
data-src={path}
/>
</div>
)
}
}
| import React, { PureComponent, PropTypes } from 'react'
import SVGInjector from 'svg-injector'
export default class ReactSVG extends PureComponent {
static defaultProps = {
callback: () => {},
className: '',
evalScripts: 'once'
}
static propTypes = {
callback: PropTypes.func,
className: PropTypes.string,
evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]),
path: PropTypes.string.isRequired
}
injectSVG() {
const {
evalScripts,
callback: each
} = this.props
if (this._img) {
SVGInjector(this._img, {
evalScripts,
each
})
}
}
componentDidMount() {
this.injectSVG()
}
componentDidUpdate() {
this.injectSVG()
}
render() {
const {
className,
path
} = this.props
return (
<img
ref={img => this._img = img}
className={className}
data-src={path}
/>
)
}
}
|
Add proper success/error logging to Sass task. | var fs = require('fs');
var path = require('path');
var sass = require('node-sass');
module.exports = function(grunt) {
grunt.registerTask('sass', function() {
var done = this.async();
grunt.log.writeln(sass.info());
var inFile = path.resolve('scss/app.scss');
var outFile = path.resolve('dist/app.min.css');
sass.render({
file: inFile,
outFile: outFile,
outputStyle: 'compressed',
sourceMap: false,
success: function(result) {
if(grunt.file.exists(outFile)) {
grunt.file.delete(outFile);
}
grunt.file.write(outFile, result.css);
grunt.log.ok('Wrote "' + outFile + '".')
done();
},
error: function(error) {
grunt.log.error('Error: ' + error.message);
grunt.log.error('File: ' + error.file);
grunt.log.error('Line: ' + error.line);
done();
}
});
});
};
| var fs = require('fs');
var path = require('path');
var sass = require('node-sass');
module.exports = function(grunt) {
function writeFile(path, contents) {
if(grunt.file.exists(path)) {
grunt.file.delete(path);
}
grunt.file.write(path, contents);
}
grunt.registerTask('sass', function() {
grunt.log.writeln(sass.info());
var inFile = path.resolve('scss/app.scss');
var outFile = path.resolve('dist/app.min.css');
var result = sass.renderSync({
file: inFile,
outFile: outFile,
outputStyle: 'compressed',
sourceMap: false
});
writeFile(outFile, result.css);
});
};
|
Make `lmieulet:meteor-coverage` a weak dependency | Package.describe({
name: 'meteortesting:mocha',
summary: 'Run Meteor package or app tests with Mocha',
git: 'https://github.com/meteortesting/meteor-mocha.git',
documentation: '../README.md',
version: '1.1.5',
testOnly: true,
});
Package.onUse(function onUse(api) {
api.use([
'meteortesting:mocha-core@7.0.0',
'ecmascript@0.3.0',
]);
api.use(['meteortesting:browser-tests@1.3.2', 'http@1.0.0'], 'server');
api.use('browser-policy@1.0.0', 'server', { weak: true });
api.use('lmieulet:meteor-coverage@1.1.4 || 2.0.1 || 3.0.0', 'client', { weak: true });
api.mainModule('client.js', 'client');
api.mainModule('server.js', 'server');
});
| Package.describe({
name: 'meteortesting:mocha',
summary: 'Run Meteor package or app tests with Mocha',
git: 'https://github.com/meteortesting/meteor-mocha.git',
documentation: '../README.md',
version: '1.1.5',
testOnly: true,
});
Package.onUse(function onUse(api) {
api.use([
'meteortesting:mocha-core@7.0.0',
'ecmascript@0.3.0',
'lmieulet:meteor-coverage@1.1.4 || 2.0.1 || 3.0.0',
]);
api.use(['meteortesting:browser-tests@1.3.2', 'http@1.0.0'], 'server');
api.use('browser-policy@1.0.0', 'server', { weak: true });
api.mainModule('client.js', 'client');
api.mainModule('server.js', 'server');
});
|
Update the example with latest interface
Update the example with the latest interface of the function "convert" | import torch
import torch.nn as nn
import torch.nn.functional as F
from onnx_coreml import convert
# Step 0 - (a) Define ML Model
class small_model(nn.Module):
def __init__(self):
super(small_model, self).__init__()
self.fc1 = nn.Linear(768, 256)
self.fc2 = nn.Linear(256, 10)
def forward(self, x):
y = F.relu(self.fc1(x))
y = F.softmax(self.fc2(y))
return y
# Step 0 - (b) Create model or Load from dist
model = small_model()
dummy_input = torch.randn(768)
# Step 1 - PyTorch to ONNX model
torch.onnx.export(model, dummy_input, './small_model.onnx')
# Step 2 - ONNX to CoreML model
mlmodel = convert(model='./small_model.onnx', minimum_ios_deployment_target='13')
# Save converted CoreML model
mlmodel.save('small_model.mlmodel')
| import torch
import torch.nn as nn
import torch.nn.functional as F
from onnx_coreml import convert
# Step 0 - (a) Define ML Model
class small_model(nn.Module):
def __init__(self):
super(small_model, self).__init__()
self.fc1 = nn.Linear(768, 256)
self.fc2 = nn.Linear(256, 10)
def forward(self, x):
y = F.relu(self.fc1(x))
y = F.softmax(self.fc2(y))
return y
# Step 0 - (b) Create model or Load from dist
model = small_model()
dummy_input = torch.randn(768)
# Step 1 - PyTorch to ONNX model
torch.onnx.export(model, dummy_input, './small_model.onnx')
# Step 2 - ONNX to CoreML model
mlmodel = convert(model='./small_model.onnx', target_ios='13')
# Save converted CoreML model
mlmodel.save('small_model.mlmodel')
|
Use os.system() instead of pexpect.run().
Also do not generate too dense mesh by default, so that it's faster. | #!/usr/bin/env python
import os, sys
import geom
from sfepy.fem.mesh import Mesh
try:
from site_cfg import tetgen_path
except ImportError:
tetgen_path = '/usr/bin/tetgen'
def mesh():
if len( sys.argv ) == 3:
geomFileName = sys.argv[1]
vtkFileName = sys.argv[2]
if len( sys.argv ) == 2:
geomFileName = sys.argv[1]
vtkFileName = "tmp/t.1.vtk"
else:
geomFileName = "database/box.geo"
vtkFileName = "tmp/t.1.vtk"
os.system( "gmsh -0 %s -o tmp/x.geo" % geomFileName )
g=geom.read_gmsh("tmp/x.geo")
g.printinfo()
geom.write_tetgen(g,"tmp/t.poly")
geom.runtetgen("tmp/t.poly",a=0.03,Q=1.0,quadratic=False,
tetgenpath = tetgen_path)
m = Mesh.fromFile("tmp/t.1.node")
m.write( vtkFileName, io = "auto" )
try:
os.makedirs( "tmp" )
except OSError, e:
if e.errno != 17: # [Errno 17] File exists
raise
mesh()
| #!/usr/bin/env python
import os, sys
import pexpect
import geom
from sfepy.fem.mesh import Mesh
try:
from site_cfg import tetgen_path
except ImportError:
tetgen_path = '/usr/bin/tetgen'
def mesh():
if len( sys.argv ) == 3:
geomFileName = sys.argv[1]
vtkFileName = sys.argv[2]
if len( sys.argv ) == 2:
geomFileName = sys.argv[1]
vtkFileName = "tmp/t.1.vtk"
else:
geomFileName = "database/box.geo"
vtkFileName = "tmp/t.1.vtk"
pexpect.run( "gmsh -0 %s -o tmp/x.geo" % geomFileName )
g=geom.read_gmsh("tmp/x.geo")
g.printinfo()
geom.write_tetgen(g,"tmp/t.poly")
geom.runtetgen("tmp/t.poly",a=0.0003,Q=1.0,quadratic=False,
tetgenpath = tetgen_path)
m = Mesh.fromFile("tmp/t.1.node")
m.write( vtkFileName, io = "auto" )
try:
os.makedirs( "tmp" )
except OSError, e:
if e.errno != 17: # [Errno 17] File exists
raise
mesh()
|
Set the default location type to 'hash' | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'webapp',
environment: environment,
baseURL: '/',
locationType: 'hash',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'auto';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'webapp',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'auto';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
Configure BookInstance list view and add an inline listing | from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
class AuthorsInstanceInline(admin.TabularInline):
model = Book
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
inlines = [AuthorsInstanceInline]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
list_display = ('book', 'status', 'due_back', 'id')
| from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
|
Fix spaces inserted by scrobble proxy | <?php
/* Libre.fm -- a free network service for sharing your music listening habits
Copyright (C) 2009 Libre.fm Project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
require_once('config.php');
$session = curl_init($submissions_url);
$post_vars = '';
foreach($_POST as $key => $element) {
if (is_array($element)) {
$i = 0;
foreach($element as $e) {
$post_vars .= $key . "[" . $i . "]=" . $e . "&";
$i++;
}
} else {
$post_vars .= $key.'='.$element.'&';
}
}
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $post_vars);
$response = curl_exec($session);
echo $response;
curl_close($session);
?>
| <?php
/* Libre.fm -- a free network service for sharing your music listening habits
Copyright (C) 2009 Libre.fm Project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
require_once('config.php');
$session = curl_init($submissions_url);
$post_vars = '';
foreach($_POST as $key => $element) {
if (is_array($element)) {
$i = 0;
foreach($element as $e) {
$post_vars .= $key . "[" . $i . "] = " . $e . "&";
$i++;
}
} else {
$post_vars .= $key.'='.$element.'&';
}
}
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $post_vars);
$response = curl_exec($session);
echo $response;
curl_close($session);
?>
|
Change linechart test to find components by class instead of tag to prevent confusion with voronoi tag | 'use strict';
var expect = require('chai').expect;
describe('LineChart', function() {
it('renders linechart', function() {
var React = require('react/addons');
var LineChart = require('../src/linechart').LineChart;
var generate = require('../utils/datagen').generateArrayOfPoints;
var TestUtils = React.addons.TestUtils;
// Render a linechart using array data
var data = {
series1: generate(5),
series2: generate(5)
};
var linechart = TestUtils.renderIntoDocument(
<LineChart data={data} width={400} height={200} />
);
// Verify that it has the same number of bars as the array's length
var paths = TestUtils.scryRenderedDOMComponentsWithClass(
linechart, 'rd3-linechart-path');
expect(paths).to.have.length(2);
});
});
| 'use strict';
var expect = require('chai').expect;
describe('LineChart', function() {
it('renders linechart', function() {
var React = require('react/addons');
var LineChart = require('../src/linechart').LineChart;
var generate = require('../utils/datagen').generateArrayOfPoints;
var TestUtils = React.addons.TestUtils;
// Render a linechart using array data
var data = {
series1: generate(5),
series2: generate(5)
};
var linechart = TestUtils.renderIntoDocument(
<LineChart data={data} width={400} height={200} />
);
// Verify that it has the same number of bars as the array's length
var paths = TestUtils.scryRenderedDOMComponentsWithTag(
linechart, 'path');
expect(paths).to.have.length(2);
});
});
|
Make ring use the default isClosed | /*
* Copyright (c) 2016-2019 Chronicle Software Ltd
*/
package net.openhft.chronicle.queue.backed.map;
// TODO add queue names and only read the ones for it.
public interface QueueEvents<K, V> {
/**
* @param key to put
* @param value to put
* @param timestamp last batch timestamp
*/
void $put(String name, K key, V value, long timestamp);
/**
* @param key to remove
* @param timestamp last batch timestamp
*/
void $remove(String name, K key, long timestamp);
/**
* Remove all entries
*
* @param timestamp last batch timestamp
*/
void $clear(String name, long timestamp);
/**
* @param hostId which caused the checkpoint
*/
void $checkPoint(String name, int hostId);
}
| /*
* Copyright (c) 2016-2019 Chronicle Software Ltd
*/
package net.openhft.chronicle.queue.backed.map;
import net.openhft.chronicle.wire.DocumentContext;
import net.openhft.chronicle.wire.MethodWriterWithContext;
import net.openhft.chronicle.wire.UnrecoverableTimeoutException;
// TODO add queue names and only read the ones for it.
public interface QueueEvents<K, V> {
/**
* @param key to put
* @param value to put
* @param timestamp last batch timestamp
*/
void $put(String name, K key, V value, long timestamp);
/**
* @param key to remove
* @param timestamp last batch timestamp
*/
void $remove(String name, K key, long timestamp);
/**
* Remove all entries
*
* @param timestamp last batch timestamp
*/
void $clear(String name, long timestamp);
/**
* @param hostId which caused the checkpoint
*/
void $checkPoint(String name, int hostId);
}
|
Put buttons in a container. | <!-- HEAD INSERT -->
<?php require_once("library/head-utils.php");?>
<body class="sfooter">
<div class="sfooter-content">
<!-- NO HEADER ON THIS PAGE -->
<div class="container container-fluid">
<div class="row">
<div class="col-sx-12">
<div class="align-right">
<button class="btn btn-up" type="button">SIGN UP</button>
<button class="btn btn-in" type="button">SIGN IN</button>
</div>
<div class="fullscreen-bg">
<video loop muted autoplay poster="img/BarkParkzTransparent.png" class="fullscreen-bg__video">
</video>
</div>
<div class="video-background">
<div class="video-foreground">
<iframe src="https://www.youtube.com/embed/_uTuRIxAgZ4?controls=0&showinfo=0&rel=0&autoplay=1&loop=1&playlist=_uTuRIxAgZ4" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div><!-- /.container -->
<!-- FOOTER INSERT -->
<?php require_once("library/footer.php");?>
</div>
</body> | <!-- HEAD INSERT -->
<?php require_once("library/head-utils.php");?>
<body class="sfooter">
<div class="sfooter-content">
<!-- NO HEADER ON THIS PAGE -->
<div class="row">
<div class="col-sx-12">
<div class="align-right">
<button class="btn btn-up" type="button">SIGN UP</button>
<button class="btn btn-in" type="button">SIGN IN</button>
</div>
<div class="fullscreen-bg">
<video loop muted autoplay poster="img/BarkParkzTransparent.png" class="fullscreen-bg__video">
</video>
</div>
<div class="video-background">
<div class="video-foreground">
<iframe src="https://www.youtube.com/embed/_uTuRIxAgZ4?controls=0&showinfo=0&rel=0&autoplay=1&loop=1&playlist=_uTuRIxAgZ4" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<!-- FOOTER INSERT -->
<?php require_once("library/footer.php");?>
</div>
</div>
</div>
</body> |
Clear cache when user changes info. | from django.core.cache.utils import make_template_fragment_key
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.cache import cache
from .models import Problem, Contest, Submission, Organization, Profile
from .caching import update_submission
@receiver(post_save, sender=Problem)
def problem_update(sender, instance, **kwargs):
cache.delete(make_template_fragment_key('problem_html', (instance.id,)))
cache.delete(make_template_fragment_key('submission_problem', (instance.id,)))
cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,)))
@receiver(post_save, sender=Profile)
def problem_update(sender, instance, **kwargs):
cache.delete(make_template_fragment_key('user_on_rank', (instance.id,)))
cache.delete(make_template_fragment_key('submission_user', (instance.id,)))
@receiver(post_save, sender=Contest)
def contest_update(sender, instance, **kwargs):
cache.delete(make_template_fragment_key('contest_html', (instance.id,)))
@receiver(post_save, sender=Submission)
def submission_update(sender, instance, **kwargs):
update_submission(instance.id)
@receiver(post_save, sender=Organization)
def organization_update(sender, instance, **kwargs):
cache.delete(make_template_fragment_key('organization_html', (instance.id,)))
| from django.core.cache.utils import make_template_fragment_key
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.cache import cache
from .models import Problem, Contest, Submission, Organization
from .caching import update_submission
@receiver(post_save, sender=Problem)
def problem_update(sender, instance, **kwargs):
cache.delete(make_template_fragment_key('problem_html', (instance.id,)))
cache.delete(make_template_fragment_key('submission_problem', (instance.id,)))
cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,)))
@receiver(post_save, sender=Contest)
def contest_update(sender, instance, **kwargs):
cache.delete(make_template_fragment_key('contest_html', (instance.id,)))
@receiver(post_save, sender=Submission)
def submission_update(sender, instance, **kwargs):
update_submission(instance.id)
@receiver(post_save, sender=Organization)
def organization_update(sender, instance, **kwargs):
cache.delete(make_template_fragment_key('organization_html', (instance.id,)))
|
Format police. getItemId() fails silently. setData conforms to Android standard. | package com.activeandroid.widget;
import java.util.Collection;
import java.util.List;
import android.content.Context;
import android.widget.ArrayAdapter;
import com.activeandroid.Model;
public class ModelAdapter<T extends Model> extends ArrayAdapter<T> {
public ModelAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public ModelAdapter(Context context, int resource, int textViewResourceId) {
super(context, resource, textViewResourceId);
}
public ModelAdapter(Context context, int textViewResourceId, List<T> objects) {
super(context, textViewResourceId, objects);
}
public ModelAdapter(Context context, int resource, int textViewResourceId, List<T> objects) {
super(context, resource, textViewResourceId, objects);
}
/**
* Clears the adapter and, if data != null, fills if with new Items.
*
* @param collection A Collection<? extends T> which members get added to the adapter.
*/
public void setData(Collection<? extends T> collection) {
clear();
if (collection != null) {
for (T item : collection) {
add(item);
}
}
}
/**
* @return The Id of the record at position.
*/
@Override
public long getItemId(int position) {
T item = getItem(position);
if (item != null) {
return item.getId();
}
else {
return -1;
}
}
} | package com.activeandroid.widget;
import java.util.List;
import android.content.Context;
import android.widget.ArrayAdapter;
import com.activeandroid.Model;
public class ModelAdapter<T extends Model> extends ArrayAdapter<T> {
public ModelAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public ModelAdapter(Context context, int resource,
int textViewResourceId) {
super(context, resource, textViewResourceId);
}
public ModelAdapter(Context context, int textViewResourceId,
List<T> objects) {
super(context, textViewResourceId, objects);
}
public ModelAdapter(Context context, int resource,
int textViewResourceId, List<T> objects) {
super(context, resource, textViewResourceId, objects);
}
/**
* Clears the adapter and, if data != null, fills if with new Items.
*
* @param data A List<T> which members get added to the adapter.
*/
public void setData(List<T> data) {
clear();
if (data != null) {
for (T t : data) {
add(t);
}
}
}
/**
* @throws RuntimeException If no record is found.
* @return The Id of the record at position.
*/
@Override
public long getItemId(int position) {
T t = this.getItem(position);
if (t!=null)
return t.getId();
else
throw new RuntimeException("ItemNotfound");
}
}
|
Include API internal endpoint in notification email to super admins. | <?php
/* @var $addedByUser \Sil\DevPortal\models\User */
/* @var $api \Sil\DevPortal\models\Api */
?>
<p>A new API has been added to the API Developer Portal. </p>
<p><?= sprintf(
'%s%s added an API named "%s" (%s). <a href="%s">Click here</a> for more '
. 'information.',
CHtml::encode($addedByUser ? $addedByUser->display_name : 'Someone'),
CHtml::encode($addedByUser ? ' (' . $addedByUser->email . ')' : ''),
CHtml::encode($api->display_name),
CHtml::encode($api->getInternalApiEndpoint()),
\Yii::app()->createAbsoluteUrl('/api/details/', array(
'code' => $api->code,
))
); ?></p>
<p>
API Added <?php echo date(Yii::app()->params['friendlyDateFormat']); ?>
</p>
| <?php
/* @var $addedByUser \Sil\DevPortal\models\User */
/* @var $api \Sil\DevPortal\models\Api */
?>
<p>A new API has been added to the API Developer Portal. </p>
<p><?php echo sprintf(
'%s%s added an API named "%s". <a href="%s">Click here</a> for more '
. 'information.',
CHtml::encode($addedByUser ? $addedByUser->display_name : 'Someone'),
($addedByUser ? ' (' . $addedByUser->email . ')' : ''),
CHtml::encode($api->display_name),
\Yii::app()->createAbsoluteUrl('/api/details/', array(
'code' => $api->code,
))
); ?>
</p>
<p>
API Added <?php echo date(Yii::app()->params['friendlyDateFormat']); ?>
</p>
|
Fix teh fixed fix of fscked fix. | # -*- coding: utf-8 -*-
"""El Marj box in Lebanon"""
from .idb import * # noqa
IDEASCUBE_NAME = u"El Marj Lebanon" # Fixme
COUNTRIES_FIRST = ['LB', 'SY', 'JO', 'PS']
TIME_ZONE = 'Asia/Beirut'
LANGUAGE_CODE = 'ar'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'library',
},
{
'id': 'mediacenter',
},
{
'id': 'khanacademy',
},
{
'id': 'wikipedia',
'languages': ['ar']
},
{
'id': 'wiktionary',
'languages': ['ar']
},
{
'id': 'wikiversity',
'languages': ['ar']
},
{
'id': 'wikibooks',
'languages': ['ar']
},
{
'id': 'wikisource',
'languages': ['ar']
},
{
'id': 'wikiquote',
'languages': ['ar']
},
{
'id': 'bil-tunisia',
'languages': ['ar']
},
]
| # -*- coding: utf-8 -*-
"""El-Marj box in Lebanon"""
from .idb import * # noqa
IDEASCUBE_NAME = u"El-Marj Lebanon" # Fixme
COUNTRIES_FIRST = ['LB', 'SY', 'JO', 'PS']
TIME_ZONE = 'Asia/Beirut'
LANGUAGE_CODE = 'ar'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'library',
},
{
'id': 'mediacenter',
},
{
'id': 'khanacademy',
},
{
'id': 'wikipedia',
'languages': ['ar']
},
{
'id': 'wiktionary',
'languages': ['ar']
},
{
'id': 'wikiversity',
'languages': ['ar']
},
{
'id': 'wikibooks',
'languages': ['ar']
},
{
'id': 'wikisource',
'languages': ['ar']
},
{
'id': 'wikiquote',
'languages': ['ar']
},
{
'id': 'bil-tunisia',
'languages': ['ar']
},
]
|
Update to use new module pinyin-api | 'use strict'
require("babel-core/register")
require("babel-polyfill")
const pinyin = require('pinyin-api')
const execute = () => {
const text = document.querySelector('#input').value
if (text) {
const re = /^[a-zรผฤรกวร ฤรฉฤรจลรณวรฒลซรบวรนฤซรญวรฌ]+$/i
if (re.test(text)) {
pinyin.split(text).then((data) => {
document.querySelector('#output').innerHTML = data.join(' ')
}, console.log)
} else {
pinyin.convert(text, {keepSpaces: true}).then((data) => {
document.querySelector('#output').innerHTML = data
}, console.log)
}
}
}
document.querySelector('#convert').addEventListener('click', execute)
document.querySelector('#input').addEventListener('keyup', (event) => {
if (event.keyCode == 13) {
event.preventDefault()
execute()
}
})
| 'use strict'
require("babel-core/register")
require("babel-polyfill")
const convert = require('pinyin-convert')
const split = require('pinyin-split')
const execute = () => {
const text = document.querySelector('#input').value
if (text) {
const re = /^[a-zรผฤรกวร ฤรฉฤรจลรณวรฒลซรบวรนฤซรญวรฌ]+$/i
if (re.test(text)) {
split(text).then((data) => {
document.querySelector('#output').innerHTML = data.join(' ')
}, console.log)
} else {
convert(text, {keepSpaces: true}).then((data) => {
document.querySelector('#output').innerHTML = data
}, console.log)
}
}
}
document.querySelector('#convert').addEventListener('click', execute)
document.querySelector('#input').addEventListener('keyup', (event) => {
if (event.keyCode == 13) {
event.preventDefault()
execute()
}
}) |
Add more HTTP headers to GhettoOauth
The official iPhone Twitter client uses
HTTP_X_VERIFY_CREDENTIALS_AUTHORIZATION when it's
connecting to image upload services. | from django.contrib.auth.models import User
import re
class GhettoOAuthMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
user_id = self._get_token_from_header(request, 'HTTP_AUTHORIZATION')
if not user_id:
user_id = self._get_token_from_header(request, 'HTTP_X_VERIFY_CREDENTIALS_AUTHORIZATION')
if 'oauth_token' in request.GET:
user_id = request.GET['oauth_token']
if user_id:
request.user = User.objects.get(pk=user_id)
return view_func(request, *view_args, **view_kwargs)
def _get_token_from_header(self, request, header):
if header in request.META and request.META[header].startswith('OAuth'):
m = re.search(r'oauth_token="(\d+)"', request.META[header])
if m:
return m.group(1)
| from django.contrib.auth.models import User
import re
class GhettoOAuthMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
user_id = None
if 'HTTP_AUTHORIZATION' in request.META and request.META['HTTP_AUTHORIZATION'].startswith('OAuth'):
m = re.search(r'oauth_token="(\d+)"',
request.META['HTTP_AUTHORIZATION'])
if m:
user_id = m.group(1)
if 'oauth_token' in request.GET:
user_id = request.GET['oauth_token']
if user_id:
request.user = User.objects.get(pk=user_id)
return view_func(request, *view_args, **view_kwargs)
|
Remove unnecessary duplication in track test
Differentiate between the test name and the failure message. | package config
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestTrackIgnoreString(t *testing.T) {
track := &Track{
IgnorePatterns: []string{
"con[.]txt",
"pro.f",
},
}
testCases := map[string]bool{
"falcon.txt": false,
"beacon|txt": true,
"beacon.ext": true,
"proof": false,
}
for name, ok := range testCases {
t.Run(name, func(t *testing.T) {
acceptable, err := track.AcceptFilename(name)
assert.NoError(t, err, name)
assert.Equal(t, ok, acceptable, fmt.Sprintf("%s is %s", name, acceptability(ok)))
})
}
}
func acceptability(ok bool) string {
if ok {
return "fine"
}
return "not acceptable"
}
| package config
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestTrackIgnoreString(t *testing.T) {
track := &Track{
IgnorePatterns: []string{
"con[.]txt",
"pro.f",
},
}
testCases := map[string]bool{
"falcon.txt": false,
"beacon|txt": true,
"beacon.ext": true,
"proof": false,
}
for name, ok := range testCases {
testName := fmt.Sprintf("%s is %s", name, acceptability(ok))
t.Run(testName, func(t *testing.T) {
acceptable, err := track.AcceptFilename(name)
assert.NoError(t, err, name)
assert.Equal(t, ok, acceptable, testName)
})
}
}
func acceptability(ok bool) string {
if ok {
return "fine"
}
return "not acceptable"
}
|
Update description in blueprints generator | import { Base } from 'yeoman-generator';
import generatorArguments from './arguments';
import generatorOptions from './options';
import generatorSteps from './steps';
export default class BlueprintsGenerator extends Base {
constructor(...args) {
super(...args);
Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key]));
Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key]));
this.description = 'Scaffolds the optimized blueprints for REST API';
}
get configuring() {
return generatorSteps.configuring;
}
get conflicts() {
return generatorSteps.conflicts;
}
get default() {
return generatorSteps.default;
}
get end() {
return generatorSteps.end;
}
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
return generatorSteps.writing;
}
}
| import { Base } from 'yeoman-generator';
import generatorArguments from './arguments';
import generatorOptions from './options';
import generatorSteps from './steps';
export default class BlueprintsGenerator extends Base {
constructor(...args) {
super(...args);
Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key]));
Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key]));
}
get configuring() {
return generatorSteps.configuring;
}
get conflicts() {
return generatorSteps.conflicts;
}
get default() {
return generatorSteps.default;
}
get end() {
return generatorSteps.end;
}
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
return generatorSteps.writing;
}
}
|
Switch default toelrance to zero | /**
* These are all the device types defined in Johnny-Five. These
* extend our Input objects (not elements)
*
* min - Minimum value for the device type
* max - Maximum value for the device type
* _methods - A list of deviceMethods names that apply to the device type
*/
var deviceTypes = {
Led: {
min: 0,
max: 255,
_methods: ['on', 'off'] //, 'toggle', 'brightness', 'pulse', 'fade', 'fadeIn', 'fadeOut', 'strobe', 'stop']
},
Servo: {
min: 0,
max: 180,
tolerance: 0,
_lastUpdate: 0,
_methods: ['move'] //, 'center', 'sweep'
}
}
| /**
* These are all the device types defined in Johnny-Five. These
* extend our Input objects (not elements)
*
* min - Minimum value for the device type
* max - Maximum value for the device type
* _methods - A list of deviceMethods names that apply to the device type
*/
var deviceTypes = {
Led: {
min: 0,
max: 255,
_methods: ['on', 'off'] //, 'toggle', 'brightness', 'pulse', 'fade', 'fadeIn', 'fadeOut', 'strobe', 'stop']
},
Servo: {
min: 0,
max: 180,
tolerance: 1,
_lastUpdate: 0,
_methods: ['move'] //, 'center', 'sweep'
}
}
|
Add the extra step to the 1.18 test. | // Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package upgrades_test
import (
gc "launchpad.net/gocheck"
"launchpad.net/juju-core/testing/testbase"
"launchpad.net/juju-core/upgrades"
)
type steps118Suite struct {
testbase.LoggingSuite
}
var _ = gc.Suite(&steps118Suite{})
var expectedSteps = []string{
"make $DATADIR/locks owned by ubuntu:ubuntu",
"generate system ssh key",
"update rsyslog port",
"install rsyslog-gnutls",
"remove deprecated environment config settings",
"migrate local provider agent config",
"make /home/ubuntu/.profile source .juju-proxy file",
}
func (s *steps118Suite) TestUpgradeOperationsContent(c *gc.C) {
upgradeSteps := upgrades.StepsFor118()
c.Assert(upgradeSteps, gc.HasLen, len(expectedSteps))
assertExpectedSteps(c, upgradeSteps, expectedSteps)
}
| // Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package upgrades_test
import (
gc "launchpad.net/gocheck"
"launchpad.net/juju-core/testing/testbase"
"launchpad.net/juju-core/upgrades"
)
type steps118Suite struct {
testbase.LoggingSuite
}
var _ = gc.Suite(&steps118Suite{})
var expectedSteps = []string{
"make $DATADIR/locks owned by ubuntu:ubuntu",
"generate system ssh key",
"update rsyslog port",
"install rsyslog-gnutls",
"remove deprecated environment config settings",
"migrate local provider agent config",
}
func (s *steps118Suite) TestUpgradeOperationsContent(c *gc.C) {
upgradeSteps := upgrades.StepsFor118()
c.Assert(upgradeSteps, gc.HasLen, len(expectedSteps))
assertExpectedSteps(c, upgradeSteps, expectedSteps)
}
|
Address review comment: Remove another root check. | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Functional tests for the ``flocker-changestate`` command line tool.
"""
from subprocess import check_output
from unittest import skipUnless
from twisted.python.procutils import which
from twisted.trial.unittest import TestCase
from ... import __version__
_require_installed = skipUnless(which("flocker-changestate"),
"flocker-changestate not installed")
class FlockerChangeStateTests(TestCase):
"""Tests for ``flocker-changestate``."""
@_require_installed
def test_version(self):
"""
``flocker-changestate`` is a command available on the system path
"""
result = check_output([b"flocker-changestate"] + [b"--version"])
self.assertEqual(result, b"%s\n" % (__version__,))
class FlockerReportStateTests(TestCase):
"""Tests for ``flocker-reportstate``."""
@_require_installed
def test_version(self):
"""
``flocker-reportstate`` is a command available on the system path
"""
result = check_output([b"flocker-reportstate"] + [b"--version"])
self.assertEqual(result, b"%s\n" % (__version__,))
| # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Functional tests for the ``flocker-changestate`` command line tool.
"""
from os import getuid
from subprocess import check_output
from unittest import skipUnless
from twisted.python.procutils import which
from twisted.trial.unittest import TestCase
from ... import __version__
_require_installed = skipUnless(which("flocker-changestate"),
"flocker-changestate not installed")
_require_root = skipUnless(getuid() == 0,
"Root required to run these tests.")
class FlockerChangeStateTests(TestCase):
"""Tests for ``flocker-changestate``."""
@_require_installed
def test_version(self):
"""
``flocker-changestate`` is a command available on the system path
"""
result = check_output([b"flocker-changestate"] + [b"--version"])
self.assertEqual(result, b"%s\n" % (__version__,))
class FlockerReportStateTests(TestCase):
"""Tests for ``flocker-reportstate``."""
@_require_installed
def test_version(self):
"""
``flocker-reportstate`` is a command available on the system path
"""
result = check_output([b"flocker-reportstate"] + [b"--version"])
self.assertEqual(result, b"%s\n" % (__version__,))
|
Test the HttpRequestHelper by loading a google search URL instead of Yahoo. Yahoo recently changed something that broke this. | package edu.pdx.cs410J.web;
import org.junit.Test;
import java.io.IOException;
import java.net.HttpURLConnection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for the <code>HttpRequestHelper</code> class
*/
public class HttpRequestHelperTest {
private HttpRequestHelper helper = new HttpRequestHelper();
@Test
public void testGet() throws IOException {
HttpRequestHelper.Response response = helper.get("http://www.google.com");
assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
assertTrue(response.getContent().contains("Google"));
}
@Test
public void testGetWithParameters() throws IOException {
HttpRequestHelper.Response response = helper.get("https://www.google.com/search", "p", "Java");
assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
assertTrue(response.getContent().contains("Java"));
}
}
| package edu.pdx.cs410J.web;
import org.junit.Test;
import java.io.IOException;
import java.net.HttpURLConnection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for the <code>HttpRequestHelper</code> class
*/
public class HttpRequestHelperTest {
private HttpRequestHelper helper = new HttpRequestHelper();
@Test
public void testGet() throws IOException {
HttpRequestHelper.Response response = helper.get("http://www.google.com");
assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
assertTrue(response.getContent().contains("Google"));
}
@Test
public void testGetWithParameters() throws IOException {
HttpRequestHelper.Response response = helper.get("http://search.yahoo.com/search", "p", "Java");
assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
assertTrue(response.getContent().contains("Java"));
}
}
|
Send receiving user with api/users/:id/messages | const models = require('../../../database/schemas.js');
module.exports = {
getAllForUser: (req, res) => {
models.User.findOne({
where: {
id: req.params.id,
},
})
.then((user) => {
user.getMessages({
include: [
{ model: models.User },
{ model: models.User, as: 'sender' },
{ model: models.Post },
],
})
.then((messages) => {
res.json(messages);
});
});
},
createMessage: (req, res) => {
res.send(200);
},
};
| const models = require('../../../database/schemas.js');
module.exports = {
getAllForUser: (req, res) => {
models.User.findOne({
where: {
id: req.params.id,
},
})
.then((user) => {
user.getMessages({
include: [
{ model: models.User, as: 'sender' },
{ model: models.Post },
],
})
.then((messages) => {
res.json(messages);
});
});
},
createMessage: (req, res) => {
res.send(200);
},
};
|
Set a nice, generous timeout on requests. | /*
* Initialize the Restify server.
*/
var restify = require('restify');
var config = require('./config');
var routes = require('./routes');
var log = require('./logging').getLogger();
exports.create = function () {
var server = restify.createServer();
server.server.setTimeout(600000);
server.pre(restify.pre.sanitizePath());
server.name = config.info.name;
server.use(function (req, res, next) {
log.verbose(req.method + ' ' + req.url);
next();
});
server.use(restify.fullResponse());
server.on('uncaughtException', function (req, res, route, err) {
log.error({
statusCode: err.statusCode || 500,
requestURL: req.url,
stack: err.stack,
error: err.message,
message: 'Uncaught exception'
});
res.send(err);
});
routes.loadRoutes(server);
return server;
};
| /*
* Initialize the Restify server.
*/
var restify = require('restify');
var config = require('./config');
var routes = require('./routes');
var log = require('./logging').getLogger();
exports.create = function () {
var server = restify.createServer();
server.pre(restify.pre.sanitizePath());
server.name = config.info.name;
server.use(function (req, res, next) {
log.verbose(req.method + ' ' + req.url);
next();
});
server.use(restify.fullResponse());
server.on('uncaughtException', function (req, res, route, err) {
log.error({
statusCode: err.statusCode || 500,
requestURL: req.url,
stack: err.stack,
error: err.message,
message: 'Uncaught exception'
});
res.send(err);
});
routes.loadRoutes(server);
return server;
};
|
Fix deploy CLI arg parsing | #! /usr/bin/python
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from list_builds import list_every_build
from get_build import ensure_build_file
from deploy_build import deploy_build
def main():
args = parse_argsets([chromium_src_arg], parser)
build = list_every_build(args.chromium_src)[-1]
build_file = ensure_build_file(build)
deploy_build(build_file)
print('Deployed build:', build)
if __name__ == '__main__':
main()
| #! /usr/bin/python
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from list_builds import list_builds
from get_build import ensure_build_file
from deploy_build import deploy_build
def main():
build = list_builds('every')[-1]
build_file = ensure_build_file(build)
deploy_build(build_file)
print('Deployed build:', build)
if __name__ == '__main__':
main()
|
Allow Form::checkboxes() to customize output separator.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\Html;
use Illuminate\Html\FormBuilder as BaseFormBuilder;
class FormBuilder extends BaseFormBuilder
{
/**
* Create a checkboxes input field.
*
* @param string $name
* @param array $list
* @param bool $checked
* @param array $options
* @param string $separator
* @return string
*/
public function checkboxes($name, $list = [], $checked = null, $options = [], $separator = '<br>')
{
$group = [];
foreach ($list as $id => $label) {
$name = str_replace('[]', '', $name);
$identifier = sprintf('%s_%s', $name, $id);
$options['id'] = $identifier;
$control = $this->checkbox(
sprintf('%s[]', $name),
$id,
in_array($id, (array) $checked),
$options
);
$label = $this->label($identifier, $label);
$group[] = implode(' ', [$control, $label]);
}
return implode($separator, $group);
}
}
| <?php namespace Orchestra\Html;
class FormBuilder extends \Illuminate\Html\FormBuilder
{
/**
* Create a checkboxes input field.
*
* @param string $name
* @param array $list
* @param bool $checked
* @param array $options
* @return string
*/
public function checkboxes($name, $list = array(), $checked = null, $options = array())
{
$group = [];
foreach ($list as $id => $label) {
$name = str_replace('[]', '', $name);
$identifier = sprintf('%s_%s', $name, $id);
$options['id'] = $identifier;
$control = $this->checkbox(
sprintf('%s[]', $name),
$id,
in_array($id, (array) $checked),
$options
);
$label = $this->label($identifier, $label);
$group[] = implode(' ', [$control, $label]);
}
return implode('<br>', $group);
}
}
|
Add readTemplateSync() to open a mustache template
We'll be opening a template for the summary email stuff too, so we'll
want to reuse this use of fs.readFileSync(). | var _ = require('underscore'),
fs = require('fs'),
path = require('path'),
Mustache = require('mustache'),
moment = require('moment'),
appConfig = require('../config');
function readTemplateSync (templateName) {
return fs.readFileSync(
path.resolve(__dirname, './templates/' + templateName)
).toString('utf8');
}
function Messages(options) {
var defaults = {
dateFormat : 'DD MMMM YYYY'
};
this.config = _.extend({}, defaults, options);
this.templates = {
reminder: readTemplateSync('reminder.mus'),
reminderSubject: 'NOTIFICATION: "{{dataSet.name}}" is OUT OF DATE.'
};
}
Messages.prototype.dataSetReminder = function (dataSet, dashboards, options) {
var config = _.extend({}, this.config, options),
lastUpdatedRaw = moment(dataSet['last-updated']).utc();
return Mustache.render(this.templates.reminder, {
dataSet: dataSet,
dashboards: dashboards,
lastUpdated: lastUpdatedRaw.format(config.dateFormat),
outOfDate: lastUpdatedRaw.add(dataSet['max-age-expected'], 's').fromNow(true),
adminAppUrl: appConfig.adminAppUrl,
notificationsEmail: appConfig.notificationsEmail
});
};
Messages.prototype.dataSetReminderSubject = function (dataSet) {
return Mustache.render(this.templates.reminderSubject, {
dataSet: dataSet
});
};
module.exports = Messages;
| var _ = require('underscore'),
fs = require('fs'),
path = require('path'),
Mustache = require('mustache'),
moment = require('moment'),
appConfig = require('../config');
function Messages(options) {
var defaults = {
dateFormat : 'DD MMMM YYYY'
};
this.config = _.extend({}, defaults, options);
this.templates = {
reminder: fs.readFileSync(
path.resolve(__dirname, './templates/reminder.mus')
).toString('utf8'),
reminderSubject: 'NOTIFICATION: "{{dataSet.name}}" is OUT OF DATE.'
};
}
Messages.prototype.dataSetReminder = function (dataSet, dashboards, options) {
var config = _.extend({}, this.config, options),
lastUpdatedRaw = moment(dataSet['last-updated']).utc();
return Mustache.render(this.templates.reminder, {
dataSet: dataSet,
dashboards: dashboards,
lastUpdated: lastUpdatedRaw.format(config.dateFormat),
outOfDate: lastUpdatedRaw.add(dataSet['max-age-expected'], 's').fromNow(true),
adminAppUrl: appConfig.adminAppUrl,
notificationsEmail: appConfig.notificationsEmail
});
};
Messages.prototype.dataSetReminderSubject = function (dataSet) {
return Mustache.render(this.templates.reminderSubject, {
dataSet: dataSet
});
};
module.exports = Messages;
|
Fix ACL check and redirect in RightDeleteAction
Refs #7742 | <?php
/*
* This file is part of the Access to Memory (AtoM) software.
*
* Access to Memory (AtoM) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Access to Memory (AtoM) 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.
*
* You should have received a copy of the GNU General Public License
* along with Access to Memory (AtoM). If not, see <http://www.gnu.org/licenses/>.
*/
class RightDeleteAction extends sfAction
{
public function execute($request)
{
$this->right = $this->getRoute()->resource;
$relatedObject = $this->right->relationsRelatedByobjectId[0]->subject;
// Check user authorization against the related object
if (!QubitAcl::check($relatedObject, 'delete'))
{
QubitAcl::forwardUnauthorized();
}
$this->right->delete();
return $this->redirect(array($relatedObject));
}
}
| <?php
/*
* This file is part of the Access to Memory (AtoM) software.
*
* Access to Memory (AtoM) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Access to Memory (AtoM) 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.
*
* You should have received a copy of the GNU General Public License
* along with Access to Memory (AtoM). If not, see <http://www.gnu.org/licenses/>.
*/
class RightDeleteAction extends sfAction
{
public function execute($request)
{
$this->right = $this->getRoute()->resource;
// Check user authorization
if (!QubitAcl::check($this->resource, 'delete'))
{
QubitAcl::forwardUnauthorized();
}
$this->right->delete();
return $this->redirect(array($this->resource, 'module' => 'informationobject'));
}
}
|
Fix scrolling to the end of the current phrase | /*
-- utils.js
This file contains generic functions for other javascript files to use.
Like returnTime(), capitalize() etc.
*/
/**
* Get unix time
* @returns {number}
*/
export function returnTime() {
let d = new Date();
return d.getTime();
}
/**
* Updates the current phrase's scroll amount
* called after a new word pushed to current phrase
*/
export function updateCurrentPhraseScroll() {
setTimeout(() => {
let element = document.getElementById('cPhrase');
element.scrollLeft = element.scrollWidth;
}, 1);
}
/**
* capitalize first letter
* @param {string} str
* @returns {string}
*/
export function capitalize(str) {
return str.charAt(0)
.toLocaleUpperCase() + str.slice(1);
}
/**
* Find the device the types
*
* @param {number} w Width
* @param {number} h Height
* @returns {string} the device types which can be 'phone' or 'tablet'
*/
export function deviceType(w, h) {
let type;
let total;
if (w && h) {
total = w + h;
} else {
total = window.innerWidth + window.innerHeight;
}
if (total < 1500) {
type = 'phone';
} else {
type = 'tablet';
}
return type;
}
| /*
-- utils.js
This file contains generic functions for other javascript files to use.
Like returnTime(), capitalize() etc.
*/
/**
* Get unix time
* @returns {number}
*/
export function returnTime() {
let d = new Date();
return d.getTime();
}
/**
* Updates the current phrase's scroll amount
* called after a new word pushed to current phrase
*/
export function updateCurrentPhraseScroll() {
return setTimeout(function () {
let element = document.getElementById('cPhrase');
if (element) {
element.scrollLeft = element.scrollWidth - window.innerWidth;
}
}, 1);
}
/**
* capitalize first letter
* @param {string} str
* @returns {string}
*/
export function capitalize(str) {
return str.charAt(0)
.toLocaleUpperCase() + str.slice(1);
}
/**
* Find the device the types
*
* @param {number} w Width
* @param {number} h Height
* @returns {string} the device types which can be 'phone' or 'tablet'
*/
export function deviceType(w, h) {
let type;
let total;
if (w && h) {
total = w + h;
} else {
total = window.innerWidth + window.innerHeight;
}
if (total < 1500) {
type = 'phone';
} else {
type = 'tablet';
}
return type;
}
|
Set Heartbeat interval to 5 mins | package net.vexelon.currencybg.srv;
import javax.ws.rs.core.MediaType;
/**
* Global constants
*
*/
public final class Defs {
/*
* Database parameters
*/
public static final String DB_DRIVER = "com.mysql.jdbc.Driver";
public static final String DB_NAME = "currencybg";
public static final String DB_HOST = System.getenv("OPENSHIFT_MYSQL_DB_HOST");
public static final String DB_PORT = System.getenv("OPENSHIFT_MYSQL_DB_PORT");
public static final String DB_CONNECTION = String.format("jdbc:mysql://%s:%s/%s", DB_HOST, DB_PORT, DB_NAME);
public static final String DB_USER = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
public static final String DB_PASSWORD = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
public static final String DATEFORMAT_ISO_8601 = "yyyy-MM-dd'T'HH:mmZ";
/*
* Currency update parameters
*/
public static final long UPDATE_FIRST_INTERVAL = 10; // 10 seconds
public static final long UPDATES_PERIODIC_INTERVAL = 5 * 60; // 5 minutes
/*
* HTTP API specific
*/
public static final String HEADER_APIKEY = "APIKey";
public static final String API_JSON_CONTENT_TYPE = MediaType.APPLICATION_JSON_TYPE + ";charset=utf-8";
public static final String DATETIME_FORMAT = "yyyy-MM-dd";
} | package net.vexelon.currencybg.srv;
import javax.ws.rs.core.MediaType;
/**
* Global constants
*
*/
public final class Defs {
/*
* Database parameters
*/
public static final String DB_DRIVER = "com.mysql.jdbc.Driver";
public static final String DB_NAME = "currencybg";
public static final String DB_HOST = System.getenv("OPENSHIFT_MYSQL_DB_HOST");
public static final String DB_PORT = System.getenv("OPENSHIFT_MYSQL_DB_PORT");
public static final String DB_CONNECTION = String.format("jdbc:mysql://%s:%s/%s", DB_HOST, DB_PORT, DB_NAME);
public static final String DB_USER = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
public static final String DB_PASSWORD = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
public static final String DATEFORMAT_ISO_8601 = "yyyy-MM-dd'T'HH:mmZ";
/*
* Currency update parameters
*/
public static final long UPDATE_FIRST_INTERVAL = 10; // 10 seconds
public static final long UPDATES_PERIODIC_INTERVAL = 6 * 60 * 60; // 6 hours
/*
* HTTP API specific
*/
public static final String HEADER_APIKEY = "APIKey";
public static final String API_JSON_CONTENT_TYPE = MediaType.APPLICATION_JSON_TYPE + ";charset=utf-8";
public static final String DATETIME_FORMAT = "yyyy-MM-dd";
} |
Add missing curly brackets in CM Tabris templates | (function() {
var templates = {
"name": "javascript",
"context": "javascript",
"templates": [{
"name": "properties",
"description": "With LayoutData containing `left`, `top` and `right` arguments.",
"template": "{layoutData: {left: 0, top: 0, right: 0}}"
}, {
"name": "properties",
"description": "With Text, Font and LayoutData containing `left`, `top` and `right` arguments.",
"template": "{text: ${text}, font: \"14px\", layoutData: {left: 0, top: 0, right: 0}}"
}, {
"name": "animationProperties",
"description": "With the `opacity` property set for a fade out effect.",
"template": "{opacity: 0}"
}, {
"name": "animationProperties",
"description": "With the `translation` property set for a horizontal translation animation.",
"template": "{transform: {translationX: 20}}"
}]
};
CodeMirror.templatesHint.addTemplates(templates);
})();
| (function() {
var templates = {
"name": "javascript",
"context": "javascript",
"templates": [{
"name": "properties",
"description": "With LayoutData containing `left`, `top` and `right` arguments.",
"template": "{layoutData: {left: 0, top: 0, right: 0}"
}, {
"name": "properties",
"description": "With Text, Font and LayoutData containing `left`, `top` and `right` arguments.",
"template": "{text: ${text}, font: \"14px\", layoutData: {left: 0, top: 0, right: 0}"
}, {
"name": "animationProperties",
"description": "With the `opacity` property set for a fade out effect.",
"template": "{opacity: 0}"
}, {
"name": "animationProperties",
"description": "With the `translation` property set for a horizontal translation animation.",
"template": "{transform: {translationX: 20}}"
}]
};
CodeMirror.templatesHint.addTemplates(templates);
})(); |
Add a broader set of events for inline event handler rewrite function |
opera.isReady(function() {
// Rewrite in-line event handlers (eg. <input ... onclick=""> for a sub-set of common standard events)
document.addEventListener('DOMContentLoaded', function(e) {
var selectors = ['load', 'beforeunload', 'unload', 'click', 'dblclick', 'mouseover', 'mousemove',
'mousedown', 'mouseup', 'mouseout', 'keydown', 'keypress', 'keyup', 'blur', 'focus'];
for(var i = 0, l = selectors.length; i < l; i++) {
var els = document.querySelectorAll('[on' + selectors[i] + ']');
for(var j = 0, k = els.length; j < k; j++) {
var fn = new Function('e', els[j].getAttribute('on' + selectors[i]));
var target = els[j];
if(selectors[i].indexOf('load') > -1 && els[j] === document.body) {
target = window;
}
els[j].removeAttribute('on' + selectors[i]);
target.addEventListener(selectors[i], fn, true);
}
}
}, false);
});
|
// Rewrite in-line event handlers (eg. <input ... onclick=""> for a sub-set of common standard events)
document.addEventListener('DOMContentLoaded', function(e) {
var selectors = ['load', 'click', 'mouseover', 'mouseout', 'keydown', 'keypress', 'keyup', 'blur', 'focus'];
for(var i = 0, l = selectors.length; i < l; i++) {
var els = document.querySelectorAll('[on' + selectors[i] + ']');
for(var j = 0, k = els.length; j < k; j++) {
var fn = new Function('e', els[j].getAttribute('on' + selectors[i]));
var target = els[j];
if(selectors[i] === 'load' && els[j] === document.body) {
target = window;
}
els[j].removeAttribute('on' + selectors[i]);
target.addEventListener(selectors[i], fn, true);
}
}
}, false);
|
Fix bug where non-existing function was being called | var duplicate = false;
jQuery( document ).ready( function()
{
checkValueIsExist( "name", "validateProgramStage.action", {id:getFieldValue('programId'), programStageId:getFieldValue('id')});
jQuery("#availableList").dhisAjaxSelect({
source: "../dhis-web-commons-ajax-json/getDataElements.action?domain=patient",
iterator: "dataElements",
connectedTo: 'selectedDataElementsValidator',
handler: function(item) {
var option = jQuery("<option />");
option.text( item.name );
option.attr( "value", item.id );
if( item.optionSet == "true"){
option.attr( "valuetype", "optionset" );
}
else{
option.attr( "valuetype", item.valueType );
}
var flag = false;
jQuery("#selectedList").find("tr").each( function( k, selectedItem ){
if(selectedItem.id == item.id )
{
flag = true;
return;
}
});
if(!flag) return option;
}
});
});
| var duplicate = false;
jQuery( document ).ready( function()
{
showHideUserGroup();
checkValueIsExist( "name", "validateProgramStage.action", {id:getFieldValue('programId'), programStageId:getFieldValue('id')});
jQuery("#availableList").dhisAjaxSelect({
source: "../dhis-web-commons-ajax-json/getDataElements.action?domain=patient",
iterator: "dataElements",
connectedTo: 'selectedDataElementsValidator',
handler: function(item) {
var option = jQuery("<option />");
option.text( item.name );
option.attr( "value", item.id );
if( item.optionSet == "true"){
option.attr( "valuetype", "optionset" );
}
else{
option.attr( "valuetype", item.valueType );
}
var flag = false;
jQuery("#selectedList").find("tr").each( function( k, selectedItem ){
if(selectedItem.id == item.id )
{
flag = true;
return;
}
});
if(!flag) return option;
}
});
});
|
Allow Report Issue to label to be customized (changed to Service Request) | <?php
$post_id = get_the_ID();
$type = get_post_meta( $post_id, 'issue_category_type', true );
?>
<article <?php post_class(); ?>>
<header>
<h1 class="entry-title"><?php the_title( sprintf( _x( 'Report Issue: ', 'post prefix', 'wp-issue' )) ); ?></h1>
</header>
<div class="entry-content row" id="entry-content">
<div class="col-md-9">
<?php the_content(); ?>
<?php if ($type == 'iframe'): ?>
<iframe src="<?php echo get_post_meta( $post_id, 'iframe', true ); ?>" style="border:none;height:1500px;width:100%"></iframe>
<?php elseif($type == 'form'): ?>
<?php gravity_form( get_post_meta( $post_id, 'form', true ), false, false ); ?>
<?php else: ?>
<script type="text/javascript">
jQuery('#entry-content').html('<div class="text-center"><i class="fa fa-spinner fa-pulse fa-4x"></i></div>');
window.location = '<?php echo get_post_meta( $post_id, 'url', true ) ?>';
</script>
<?php endif ?>
</div>
</div>
</article> | <?php
$post_id = get_the_ID();
$type = get_post_meta( $post_id, 'issue_category_type', true );
?>
<article <?php post_class(); ?>>
<header>
<h1 class="entry-title"><?php the_title( sprintf( 'Report Issue: ') ); ?></h1>
</header>
<div class="entry-content row" id="entry-content">
<div class="col-md-9">
<?php the_content(); ?>
<?php if ($type == 'iframe'): ?>
<iframe src="<?php echo get_post_meta( $post_id, 'iframe', true ); ?>" style="border:none;height:1500px;width:100%"></iframe>
<?php elseif($type == 'form'): ?>
<?php gravity_form( get_post_meta( $post_id, 'form', true ), false, false ); ?>
<?php else: ?>
<script type="text/javascript">
jQuery('#entry-content').html('<div class="text-center"><i class="fa fa-spinner fa-pulse fa-4x"></i></div>');
window.location = '<?php echo get_post_meta( $post_id, 'url', true ) ?>';
</script>
<?php endif ?>
</div>
</div>
</article> |
Fix property declaration from constructor, to constructor: | /**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
/**
* This shim allows elements written in, or compiled to, ES5 to work on native
* implementations of Custom Elements v1. It sets new.target to the value of
* this.constructor so that the native HTMLElement constructor can access the
* current under-construction element's definition.
*
* Because `new.target` is a syntax error in VMs that don't support it, this
* shim must only be loaded in browsers that do.
*/
(() => {
let origHTMLElement = HTMLElement;
// TODO(justinfagnani): Tests!!
window.HTMLElement = function() {
// prefer new.target for elements that call super() constructors or
// Reflect.construct directly
let newTarget = new.target || this.constructor;
return Reflect.construct(origHTMLElement, [], newTarget);
}
HTMLElement.prototype = Object.create(origHTMLElement.prototype, {
constructor: {value: HTMLElement, configurable: true, writable: true},
});
// TODO(justinfagnani): patch all native subclasses of HTMLElement
})();
| /**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
/**
* This shim allows elements written in, or compiled to, ES5 to work on native
* implementations of Custom Elements v1. It sets new.target to the value of
* this.constructor so that the native HTMLElement constructor can access the
* current under-construction element's definition.
*
* Because `new.target` is a syntax error in VMs that don't support it, this
* shim must only be loaded in browsers that do.
*/
(() => {
let origHTMLElement = HTMLElement;
// TODO(justinfagnani): Tests!!
window.HTMLElement = function() {
// prefer new.target for elements that call super() constructors or
// Reflect.construct directly
let newTarget = new.target || this.constructor;
return Reflect.construct(origHTMLElement, [], newTarget);
}
HTMLElement.prototype = Object.create(origHTMLElement.prototype, {
constructor, {value: HTMLElement, configurable: true, writable: true},
});
// TODO(justinfagnani): patch all native subclasses of HTMLElement
})();
|
Clean up profiling completion code | 'use strict';
const Fidelity = require('../lib/index.js');
const Genet = require('genet');
const someWork = (resolve) => {
setImmediate(() => resolve(Math.floor(Math.random() * (10 - 0))));
};
function runBenchmarks () {
const profile = new Genet({
profileName: 'fidelity',
// filter out everything but fidelity core code
filter: /^(?!.*bench.*)(?=.*fidelity).*/,
duration: 50000,
showAppOnly: true,
verbose: true,
flamegraph: true
});
exports.compare = {
'new Fidelity Promise': function (done) {
new Fidelity(someWork).then(done);
},
'Fidelity.resolve()': function (done) {
Fidelity.resolve(Math.floor(Math.random() * (10 - 0))).then(done);
}
};
exports.done = function (data) {
profile.stop().then(() => {
console.log('Profiling stopped');
bench.show(data);
});
};
exports.time = 5000;
exports.countPerLap = 6;
exports.compareCount = 8;
profile.start();
const bench = require('bench');
bench.runMain();
}
runBenchmarks();
| 'use strict';
const Fidelity = require('../lib/index.js');
const Genet = require('genet');
const someWork = (resolve) => {
setImmediate(() => resolve(Math.floor(Math.random() * (10 - 0))));
};
function runBenchmarks () {
const profile = new Genet({
profileName: 'fidelity',
// filter out everything but fidelity core code
filter: /^(?!.*bench.*)(?=.*fidelity).*/,
duration: 50000,
showAppOnly: true,
verbose: true,
flamegraph: true
});
exports.compare = {
'new Fidelity Promise': function (done) {
new Fidelity(someWork).then(done);
},
'Fidelity.resolve()': function (done) {
Fidelity.resolve(Math.floor(Math.random() * (10 - 0))).then(done);
}
};
let num = 1;
exports.done = function (data) {
profile.stop().then(() => console.log('Profiling stopped'));
bench.show(data);
console.error('done', num);
num = num + 1;
};
exports.time = 5000;
exports.countPerLap = 6;
exports.compareCount = 8;
profile.start();
const bench = require('bench');
bench.runMain();
}
runBenchmarks();
|
Convert Resource to support dropwizard service. | package com.topsy.jmxproxy;
import com.topsy.jmxproxy.core.Host;
import com.topsy.jmxproxy.jmx.ConnectionManager;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.WebApplicationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("/{host}:{port:\\d+}")
@Produces(MediaType.APPLICATION_JSON)
public class JMXProxyResource {
private static final Logger LOG = LoggerFactory.getLogger(JMXProxyResource.class);
private final ConnectionManager manager;
public JMXProxyResource(ConnectionManager manager) {
this.manager = manager;
}
@GET
public Host getJMXHostData(@PathParam("host") String host, @PathParam("port") int port) {
LOG.debug("fetching jmx data for " + host + ":" + port);
try {
return manager.getHost(host + ":" + port);
} catch (Exception e) {
LOG.debug("failed parameters: " + host + ":" + port, e);
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
}
| package com.topsy.jmxproxy.resource;
import com.topsy.jmxproxy.service.JMXConnectionManager;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.sun.jersey.api.core.InjectParam;
@Service
@Path("/")
public class JMXProxyResource {
private static Logger LOG = Logger.getLogger(JMXProxyResource.class);
@InjectParam
private static JMXConnectionManager manager;
@GET
@Path("/{host}:{port:\\d+}")
@Produces(MediaType.APPLICATION_JSON)
public Response getJMXDataJSON(@PathParam("host") String host, @PathParam("port") int port) {
LOG.debug("request jmx domains as json for " + host + ":" + port);
try {
return Response.ok(manager.getHost(host + ":" + port)).build();
} catch (Exception e) {
LOG.debug("failed parameters: " + host + ":" + port, e);
return Response.status(Response.Status.NOT_FOUND).build();
}
}
}
|
Move Cumbria to the North West | """
Import administrative areas from the NPTG.
Usage:
import_areas < AdminAreas.csv
"""
from ..import_from_csv import ImportFromCSVCommand
from ...models import AdminArea
class Command(ImportFromCSVCommand):
def handle_row(self, row):
AdminArea.objects.update_or_create(
id=row['AdministrativeAreaCode'],
defaults={
'atco_code': row['AtcoAreaCode'],
'name': row['AreaName'],
'short_name': row['ShortName'],
'country': row['Country'],
'region_id': row['RegionCode'],
}
)
def handle(self, *args, **options):
super(Command, self).handle(*args, **options)
# Move Cumbria to the North West.
# There is the legacy of the confusing 'North East and Cumbria' Traveline region,
#ย but actually Cumbrian bus services are in the North West now
AdminArea.objects.filter(name='Cumbria').update(region_id='NW')
| """
Import administrative areas from the NPTG.
Usage:
import_areas < AdminAreas.csv
"""
from ..import_from_csv import ImportFromCSVCommand
from ...models import AdminArea
class Command(ImportFromCSVCommand):
def handle_row(self, row):
AdminArea.objects.update_or_create(
id=row['AdministrativeAreaCode'],
defaults={
'atco_code': row['AtcoAreaCode'],
'name': row['AreaName'],
'short_name': row['ShortName'],
'country': row['Country'],
'region_id': row['RegionCode'],
}
)
|
Remove node version debug line | const exec = require('shell-utils').exec;
const _ = require('lodash');
const fix = _.includes(process.argv, '--fix') ? '--fix' : '';
const dirs = [
'lib/src',
'integration',
'e2e',
'scripts',
'playground/src'
];
run();
function run() {
const paths = _.chain(dirs).map((d) => `'${d}/**/*.[tj]s*'`).join(' ').value();
exec.execSync(`tslint ${paths} ${fix} --format verbose`);
assertAllTsFilesInSrc();
exec.execSync(`jest --coverage`);
}
function assertAllTsFilesInSrc() {
const allFiles = exec.execSyncRead('find ./lib/src -type f');
const lines = _.split(allFiles, '\n');
const offenders = _.filter(lines, (f) => !f.endsWith('.ts') && !f.endsWith('.tsx'));
if (offenders.length) {
throw new Error(`\n\nOnly ts/tsx files are allowed:\n${offenders.join('\n')}\n\n\n`);
}
}
| const exec = require('shell-utils').exec;
const _ = require('lodash');
const fix = _.includes(process.argv, '--fix') ? '--fix' : '';
const dirs = [
'lib/src',
'integration',
'e2e',
'scripts',
'playground/src'
];
run();
function run() {
exec.execSync('node -v');
const paths = _.chain(dirs).map((d) => `'${d}/**/*.[tj]s*'`).join(' ').value();
exec.execSync(`tslint ${paths} ${fix} --format verbose`);
assertAllTsFilesInSrc();
exec.execSync(`jest --coverage`);
}
function assertAllTsFilesInSrc() {
const allFiles = exec.execSyncRead('find ./lib/src -type f');
const lines = _.split(allFiles, '\n');
const offenders = _.filter(lines, (f) => !f.endsWith('.ts') && !f.endsWith('.tsx'));
if (offenders.length) {
throw new Error(`\n\nOnly ts/tsx files are allowed:\n${offenders.join('\n')}\n\n\n`);
}
}
|
Fix headers and compression issues | 'use strict';
var config = require('meanio').loadConfig(),
apiUri = config.api.uri,
request = require('request');
module.exports = function(General, app, auth, database) {
app.get('/api/:entity/:id/:issue', function(req, res) {
var objReq = {
uri: apiUri + '/api/' + req.params.entity + '/' + req.params.id + '/' + req.params.issue,
method: 'GET',
headers: req.headers,
gzip: true
};
request(objReq, function(error, response, body) {
if (!error && response.statusCode === 200 && response.body.length)
return res.json(JSON.parse(response.body));
if(response)
return res.status(response.statusCode).send(response.body);
});
});
app.post('/api/:entity/:id/:issue', function (req, res) {
var objReq = {
uri: apiUri + '/api/' + req.params.entity + '/' + req.params.id + '/' + req.params.issue,
method: 'POST',
headers: req.headers,
gzip: true
};
request(objReq, function (error, response, body) {
if (!error && response.statusCode === 200 && response.body.length)
return res.json(JSON.parse(response.body));
if (response)
return res.status(response.statusCode).send(response.body);
});
});
};
| 'use strict';
var config = require('meanio').loadConfig(),
apiUri = config.api.uri,
request = require('request');
module.exports = function(General, app, auth, database) {
app.get('/api/:entity/:id/:issue', function(req, res) {
var objReq = {
uri: apiUri + '/api/' + req.params.entity + '/' + req.params.id + '/' + req.params.issue,
method: 'GET',
headers: res.headers
};
request(objReq, function(error, response, body) {
if (!error && response.statusCode === 200 && response.body.length)
return res.json(JSON.parse(response.body));
if(response)
return res.status(response.statusCode).send(response.body);
});
});
app.post('/api/:entity/:id/:issue', function (req, res) {
var objReq = {
uri: apiUri + '/api/' + req.params.entity + '/' + req.params.id + '/' + req.params.issue,
method: 'POST',
headers: res.headers
};
request(objReq, function (error, response, body) {
if (!error && response.statusCode === 200 && response.body.length)
return res.json(JSON.parse(response.body));
if (response)
return res.status(response.statusCode).send(response.body);
});
});
};
|
Kill off another hardcoded path | #!/usr/bin/python
import os, sys
import pwd
if os.geteuid():
print >> sys.stderr, "Script must be run as root to manipulate permissions"
sys.exit(1)
from conary import dbstore
from mint import config
apacheGid = pwd.getpwnam('apache')[3]
isogenUid = pwd.getpwnam('isogen')[2]
cfg = config.MintConfig()
cfg.read(config.RBUILDER_CONFIG)
db = dbstore.connect(cfg.dbPath, cfg.dbDriver)
cu = db.cursor()
cu.execute('SELECT filename FROM ImageFiles')
imageFiles = [x[0] for x in cu.fetchall()]
for baseDir, dirs, files in os.walk(cfg.imagesPath):
if len(baseDir.split(os.path.sep)) == 6:
os.chown(baseDir, isogenUid, apacheGid)
os.chmod(baseDir, os.stat(baseDir)[0] & 0777 | 0020)
for file in files:
path = os.path.join(baseDir, file)
if file not in imageFiles:
os.unlink(path)
else:
os.chown(path, isogenUid, apacheGid)
| #!/usr/bin/python
import os, sys
import pwd
if os.geteuid():
print >> sys.stderr, "Script must be run as root to manipulate permissions"
sys.exit(1)
from conary import dbstore
from mint import config
apacheGid = pwd.getpwnam('apache')[3]
isogenUid = pwd.getpwnam('isogen')[2]
cfg = config.MintConfig()
cfg.read('/srv/rbuilder/rbuilder.conf')
db = dbstore.connect(cfg.dbPath, cfg.dbDriver)
cu = db.cursor()
cu.execute('SELECT filename FROM ImageFiles')
imageFiles = [x[0] for x in cu.fetchall()]
for baseDir, dirs, files in os.walk('/srv/rbuilder/finished-images'):
if len(baseDir.split(os.path.sep)) == 6:
os.chown(baseDir, isogenUid, apacheGid)
os.chmod(baseDir, os.stat(baseDir)[0] & 0777 | 0020)
for file in files:
path = os.path.join(baseDir, file)
if file not in imageFiles:
os.unlink(path)
else:
os.chown(path, isogenUid, apacheGid)
|
Add unauthorized exception to CreateAccount api method | package io.github.trevornelson;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiMethod.HttpMethod;
import com.google.api.server.spi.response.UnauthorizedException;
import com.google.appengine.api.users.User;
import io.github.trevornelson.Account;
@Api(
name = "dashboards",
version = "v1",
scopes = {Constants.EMAIL_SCOPE},
clientIds = {Constants.WEB_CLIENT_ID, Constants.API_EXPLORER_CLIENT_ID }
)
public class Dashboards {
private String extractUsername(String emailAddress) {
return emailAddress.split("@")[0];
}
@ApiMethod(name = "dashboards.createAccount", httpMethod = HttpMethod.POST)
public Account CreateAccount(final User user) throws UnauthorizedException {
if (user == null) {
throw new UnauthorizedException("Authentication is required");
}
String email = user.getEmail();
String username = extractUsername(email);
String userId = user.getUserId();
Account account = new Account(userId, username, email);
return account;
}
}
| package io.github.trevornelson;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiMethod.HttpMethod;
import com.google.api.server.spi.response.UnauthorizedException;
import com.google.appengine.api.users.User;
import io.github.trevornelson.Account;
@Api(
name = "dashboards",
version = "v1",
scopes = {Constants.EMAIL_SCOPE},
clientIds = {Constants.WEB_CLIENT_ID, Constants.ANDROID_CLIENT_ID, Constants.IOS_CLIENT_ID},
audiences = {Constants.ANDROID_AUDIENCE}
)
public class Dashboards {
private String extractUsername(String emailAddress) {
return emailAddress.split("@")[0];
}
@ApiMethod(name = "dashboards.createAccount", httpMethod = HttpMethod.POST)
public Account CreateAccount(final User user, String accountUsername) throws UnauthorizedException {
if (user == null) {
throw new UnauthorizedException("Authentication is required");
}
String email = user.getEmail();
String username = extractUsername(email);
String userId = user.getUserId();
Account account = new Account(userId, username, email);
return account;
}
}
|
Add console.log et remove verify for bot framework | var restify = require('restify');
var builder = require('botbuilder');
// Get secrets from server environment
var botConnectorOptions = {
appId: process.env.MICROSOFT_APP_ID,
appSecret: process.env.MICROSOFT_APP_PASSWORD
};
// Create bot
var bot = new builder.BotConnectorBot(botConnectorOptions);
bot.add('/', function (session) {
//respond with user's message
console.log('message received')
session.send("You said " + session.message.text);
});
// Setup Restify Server
var server = restify.createServer();
// Handle Bot Framework messages
server.post('/api/messages', bot.listen());
// Serve a static web page
server.get(/.*/, restify.serveStatic({
'directory': '.',
'default': 'index.html'
}));
server.listen(process.env.port || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
| var restify = require('restify');
var builder = require('botbuilder');
// Get secrets from server environment
var botConnectorOptions = {
appId: process.env.MICROSOFT_APP_ID,
appSecret: process.env.MICROSOFT_APP_PASSWORD
};
// Create bot
var bot = new builder.BotConnectorBot(botConnectorOptions);
bot.add('/', function (session) {
//respond with user's message
session.send("You said " + session.message.text);
});
// Setup Restify Server
var server = restify.createServer();
// Handle Bot Framework messages
server.post('/api/messages', bot.verifyBotFramework(), bot.listen());
// Serve a static web page
server.get(/.*/, restify.serveStatic({
'directory': '.',
'default': 'index.html'
}));
server.listen(process.env.port || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
|
Set event subscriber priority for failure events | <?php
declare(strict_types=1);
namespace Codeception\Subscriber;
use Codeception\Event\TestEvent;
use Codeception\Events;
use Codeception\ResultAggregator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class FailFast implements EventSubscriberInterface
{
use Shared\StaticEventsTrait;
/**
* @var array<string, array<string, int>>
*/
protected static array $events = [
Events::TEST_FAIL => ['stopOnFail', 128],
Events::TEST_ERROR => ['stopOnFail', 128],
];
private int $failureCount = 0;
public function __construct(private int $stopFailureCount, private ResultAggregator $resultAggregator)
{
}
public function stopOnFail(TestEvent $e): void
{
$this->failureCount++;
if ($this->failureCount >= $this->stopFailureCount) {
$this->resultAggregator->stop();
}
}
}
| <?php
declare(strict_types=1);
namespace Codeception\Subscriber;
use Codeception\Event\TestEvent;
use Codeception\Events;
use Codeception\ResultAggregator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class FailFast implements EventSubscriberInterface
{
use Shared\StaticEventsTrait;
/**
* @var array<string, string>
*/
protected static array $events = [
Events::TEST_FAIL => 'stopOnFail',
Events::TEST_ERROR => 'stopOnFail',
];
private int $failureCount = 0;
public function __construct(private int $stopFailureCount, private ResultAggregator $resultAggregator)
{
}
public function stopOnFail(TestEvent $e): void
{
$this->failureCount++;
if ($this->failureCount >= $this->stopFailureCount) {
$this->resultAggregator->stop();
}
}
}
|
Save .travis.yml into build properties | from buildbot.process import buildstep
from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION
from buildbot.process.properties import Properties
from twisted.internet import defer
from ..travisyml import TravisYml
class ConfigurableStep(buildstep.LoggingBuildStep):
"""
Base class for a step which can be tuned by changing settings in .travis.yml
"""
@defer.inlineCallbacks
def getStepConfig(self):
config = TravisYml()
struct = self.build.getProperty(".travis.yml", None)
if struct:
config.parse(struct)
defer.returnValue(config)
log = self.addLog(".travis.yml")
cmd = self.cmd = buildstep.RemoteShellCommand(workdir="build", command=["cat", ".travis.yml"])
cmd.useLog(log, False, "stdio")
yield self.runCommand(cmd)
self.cmd = None
if cmd.rc != 0:
raise buildstep.BuildStepFailed()
config = TravisYml()
config.parse(log.getText())
self.build.setProperty(".travis.yml", config.config, ".VCS")
defer.returnValue(config)
| from buildbot.process import buildstep
from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION
from buildbot.process.properties import Properties
from twisted.internet import defer
from ..travisyml import TravisYml
class ConfigurableStep(buildstep.LoggingBuildStep):
"""
Base class for a step which can be tuned by changing settings in .travis.yml
"""
@defer.inlineCallbacks
def getStepConfig(self):
log = self.addLog(".travis.yml")
cmd = self.cmd = buildstep.RemoteShellCommand(workdir="build", command=["cat", ".travis.yml"])
cmd.useLog(log, False, "stdio")
yield self.runCommand(cmd)
self.cmd = None
if cmd.rc != 0:
raise buildstep.BuildStepFailed()
config = TravisYml()
config.parse(log.getText())
defer.returnValue(config)
|
Add the iWantTwo and iWantZero functions ? | package es.softwareprocess.fillercreep;
public class AIMaximum implements AI {
public FundamentalStuff evaluate(int playernumber, FillerCreep fillerCreep) {
FundamentalStuff[] stuff = FillerCreep.getStuffArray();
int maxscore = -1;
int maxstuff = -1;
for (int i = 0; i < stuff.length; i++) {
int score = fillerCreep.testPlayerPlay(playernumber, stuff[i]);
if (score > maxscore) {
maxscore = score;
maxstuff = i;
}
}
return stuff[maxstuff];
}
@Override
public void MasterAI() {
// TODO Auto-generated method stub
}
public int iWantTwo() {
return 2;
}
public int iWantZero() {
return 0;
}
}
| package es.softwareprocess.fillercreep;
public class AIMaximum implements AI {
public FundamentalStuff evaluate(int playernumber, FillerCreep fillerCreep) {
FundamentalStuff[] stuff = FillerCreep.getStuffArray();
int maxscore = -1;
int maxstuff = -1;
for (int i = 0; i < stuff.length; i++) {
int score = fillerCreep.testPlayerPlay(playernumber, stuff[i]);
if (score > maxscore) {
maxscore = score;
maxstuff = i;
}
}
return stuff[maxstuff];
}
@Override
public void MasterAI() {
// TODO Auto-generated method stub
}
}
|
Improve formatting of resend action description | from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = (
"Send code by SMS (personnel code only)")
admin.site.register(Record, RecordAdmin)
| from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = "Send code by SMS (personnel "\
"code only)"
admin.site.register(Record, RecordAdmin)
|
View: Remove array_key_exists from flash partial | @foreach (session('flash_notification', collect())->toArray() as $message)
@if ($loop->first)
<div class="container">
@endif
@if ($message['overlay'])
@include('partials.flashModal', [
'modalClass' => 'flash-modal',
'title' => $message['title'],
'body' => $message['message']
])
@else
<div class="alert alert-{{ $message['level'] }}" data-closable>
{!! $message['message'] !!}
<button class="close" aria-label="Dismiss alert" data-dismiss="alert" type="button" data-close>
<span aria-hidden="true">×</span>
</button>
</div>
@endif
@if ($loop->last)
</div>
@endif
@endforeach
{{ session()->forget('flash_notification') }}
| @foreach (session('flash_notification', collect())->toArray() as $message)
@if ($loop->first)
<div class="container">
@endif
@if ($message['overlay'])
@include('partials.flashModal', [
'modalClass' => 'flash-modal',
'title' => $message['title'],
'body' => $message['message']
])
@else
<div class="alert alert-{{ array_key_exists('level', $message) ? $message['level'] : '' }}" data-closable>
{!! $message['message'] !!}
<button class="close" aria-label="Dismiss alert" data-dismiss="alert" type="button" data-close>
<span aria-hidden="true">×</span>
</button>
</div>
@endif
@if ($loop->last)
</div>
@endif
@endforeach
{{ session()->forget('flash_notification') }}
|
Remove unnecessary console logging since the open browser is all the feedback required. | <?php
namespace App\Actions;
use App\Shell\Shell;
use Facades\App\Environment;
class OpenInBrowser
{
use LamboAction;
protected $shell;
public function __construct(Shell $shell)
{
$this->shell = $shell;
}
public function __invoke()
{
$this->logStep('Opening in Browser');
if (Environment::isMac() && $this->browser()) {
$this->shell->execInProject(sprintf(
'open -a "%s" "%s"',
$this->browser(),
config('lambo.store.project_url')
));
} else {
$this->shell->execInProject("valet open");
}
}
public function browser()
{
return config('lambo.store.browser');
}
}
| <?php
namespace App\Actions;
use App\Shell\Shell;
use Facades\App\Environment;
class OpenInBrowser
{
use LamboAction;
protected $shell;
public function __construct(Shell $shell)
{
$this->shell = $shell;
}
public function __invoke()
{
$this->logStep('Opening in Browser');
if (Environment::isMac() && $this->browser()) {
$this->shell->execInProject(sprintf(
'open -a "%s" "%s"',
$this->browser(),
config('lambo.store.project_url')
));
$this->info('[ lambo ] Opened your new site. in ' . $this->browser() . ' Happy coding!');
} else {
$this->shell->execInProject("valet open");
}
}
public function browser()
{
return config('lambo.store.browser');
}
}
|
Enhancement: Use small header layout in User module | <?php
return [
'module_layouts' => [
'User' => 'layout/layout-small-header.phtml',
'ZfcUser' => 'layout/layout-small-header.phtml',
'ZfModule' => 'layout/layout-small-header.phtml',
],
'asset_manager' => [
'caching' => [
'default' => [
'cache' => 'FilePath', // Apc, FilePath, FileSystem etc.
'options' => [
'dir' => 'public',
],
],
],
],
'service_manager' => [
'factories' => [
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
],
'invokables' => [
'Zend\Session\SessionManager' => 'Zend\Session\SessionManager',
],
],
'db' => [
'driver' => 'pdo',
'dsn' => 'mysql:dbname=modules;host=localhost',
'username' => 'modules',
'password' => 'modules',
],
];
| <?php
return [
'module_layouts' => [
'ZfcUser' => 'layout/layout-small-header.phtml',
'ZfModule' => 'layout/layout-small-header.phtml',
],
'asset_manager' => [
'caching' => [
'default' => [
'cache' => 'FilePath', // Apc, FilePath, FileSystem etc.
'options' => [
'dir' => 'public',
],
],
],
],
'service_manager' => [
'factories' => [
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
],
'invokables' => [
'Zend\Session\SessionManager' => 'Zend\Session\SessionManager',
],
],
'db' => [
'driver' => 'pdo',
'dsn' => 'mysql:dbname=modules;host=localhost',
'username' => 'modules',
'password' => 'modules',
],
];
|
Add support for multiple schemas | "use strict";
var requestHelper = require('./request-helper');
var jsonSchema = require('jsonschema');
/**
* Returns an express middleware function that validates the request body
* or the request's field if provided against the given JSON schema.
*
* schemas is either an array of object or a single object
*/
var validateJson = function(schemas, field) {
return function(req, res, next) {
if (!field) {
field = 'body';
}
if (field === 'body' && !requestHelper.isContentType(req, 'application/json')) {
res.sendInvalidRequest("Invalid content type: " + req.get('Content-Type'));
return;
}
if (!Array.isArray(schemas)) {
schemas = [schemas];
}
var errors = [];
schemas.forEach(function (schema) {
var result = jsonSchema.validate(req[field], schema);
if (result.errors.length > 0) {
errors.push(result.toString());
}
});
if (errors.length === schemas.length && errors.length > 0) {
var errorMessage = '';
errors.forEach(function(err) {
errorMessage += err;
});
return res.sendInvalidRequest(errorMessage);
}
next();
};
};
module.exports = validateJson;
| "use strict";
var requestHelper = require('./request-helper');
var jsonSchema = require('jsonschema');
/**
* Returns an express middleware function that validates the request body
* or the request's field if provided against the given JSON schema.
*/
var validateJson = function(schema, field) {
return function(req, res, next) {
if (!field) {
field = 'body';
}
if (field === 'body' && !requestHelper.isContentType(req, 'application/json')) {
res.sendInvalidRequest("Invalid content type: " + req.get('Content-Type'));
return;
}
var result = jsonSchema.validate(req[field], schema);
if (result.errors.length > 0) {
res.sendInvalidRequest(result.toString());
return;
}
next();
};
};
module.exports = validateJson;
|
Update test to latest number of 27 nub sources | package org.gbif.checklistbank.nub.source;
import org.gbif.api.vocabulary.Rank;
import org.gbif.checklistbank.nub.model.SrcUsage;
import java.util.List;
import java.util.UUID;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ClasspathUsageSourceTest {
/**
* integration test with prod registry
* @throws Exception
*/
@Test
public void testListSources() throws Exception {
ClasspathUsageSource src = ClasspathUsageSource.allSources();
List<NubSource> sources = src.listSources();
assertEquals(27, sources.size());
assertEquals(1, sources.get(0).priority);
assertEquals(Rank.FAMILY, sources.get(0).ignoreRanksAbove);
}
@Test
public void testIterateSource() throws Exception {
ClasspathUsageSource src = ClasspathUsageSource.emptySource();
NubSource fungi = new NubSource();
fungi.name = "squirrels";
fungi.key = UUID.fromString("d7dddbf4-2cf0-4f39-9b2a-99b0e2c3aa01");
fungi.ignoreRanksAbove = Rank.SPECIES;
int counter = 0;
for (SrcUsage u : src.iterateSource(fungi)) {
counter++;
System.out.print(u.key + " ");
System.out.println(u.scientificName);
}
assertEquals(9, counter);
}
} | package org.gbif.checklistbank.nub.source;
import org.gbif.api.vocabulary.Rank;
import org.gbif.checklistbank.nub.model.SrcUsage;
import java.util.List;
import java.util.UUID;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ClasspathUsageSourceTest {
/**
* integration test with prod registry
* @throws Exception
*/
@Test
public void testListSources() throws Exception {
ClasspathUsageSource src = ClasspathUsageSource.allSources();
List<NubSource> sources = src.listSources();
assertEquals(26, sources.size());
assertEquals(1, sources.get(0).priority);
assertEquals(Rank.FAMILY, sources.get(0).ignoreRanksAbove);
}
@Test
public void testIterateSource() throws Exception {
ClasspathUsageSource src = ClasspathUsageSource.emptySource();
NubSource fungi = new NubSource();
fungi.name = "squirrels";
fungi.key = UUID.fromString("d7dddbf4-2cf0-4f39-9b2a-99b0e2c3aa01");
fungi.ignoreRanksAbove = Rank.SPECIES;
int counter = 0;
for (SrcUsage u : src.iterateSource(fungi)) {
counter++;
System.out.print(u.key + " ");
System.out.println(u.scientificName);
}
assertEquals(9, counter);
}
} |
Correct syntax for Python3 compatibility | #!/usr/bin/env python2
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import unittest
import os.path
if __name__ == '__main__':
print("Running")
suite = unittest.TestLoader().discover(
start_dir = os.path.dirname(os.path.abspath(__file__)),
pattern = "test_*.py",
top_level_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
unittest.TextTestRunner().run(suite)
| #!/usr/bin/env python2
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import unittest
import os.path
if __name__ == '__main__':
print "Running"
suite = unittest.TestLoader().discover(
start_dir = os.path.dirname(os.path.abspath(__file__)),
pattern = "test_*.py",
top_level_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
unittest.TextTestRunner().run(suite)
|
Clarify that submission ID != task ID
Calling this out in the helptext will hopefully help avoid people
conflating these two quite as easily. (An imperfect solution for an
imperfect world.) | import click
from globus_cli.parsing import common_options
from globus_cli.safeio import FORMAT_TEXT_RAW, formatted_print
from globus_cli.services.transfer import get_client
@click.command(
"generate-submission-id",
short_help="Get a submission ID",
help=(
"""\
Generate a new task submission ID for use in `globus transfer` and `gloubs delete`.
Submission IDs allow you to safely retry submission of a task in the presence of
network errors. No matter how many times you submit a task with a given ID, it will
only be accepted and executed once. The response status may change between
submissions.
\b
Important Note: Submission IDs are not the same as Task IDs.
"""
),
)
@common_options
def generate_submission_id():
"""
Executor for `globus task generate-submission-id`
"""
client = get_client()
res = client.get_submission_id()
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="value")
| import click
from globus_cli.parsing import common_options
from globus_cli.safeio import FORMAT_TEXT_RAW, formatted_print
from globus_cli.services.transfer import get_client
@click.command(
"generate-submission-id",
short_help="Get a submission ID",
help=(
"Generate a new task submission ID for use in "
"`globus transfer` and `gloubs delete`. Submission IDs "
"allow you to safely retry submission of a task in the "
"presence of network errors. No matter how many times "
"you submit a task with a given ID, it will only be "
"accepted and executed once. The response status may "
"change between submissions."
),
)
@common_options
def generate_submission_id():
"""
Executor for `globus task generate-submission-id`
"""
client = get_client()
res = client.get_submission_id()
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="value")
|
Add fallback for old name ordinalParse | import { makeGetSet } from '../moment/get-set';
import { addFormatToken } from '../format/format';
import { addUnitAlias } from './aliases';
import { addUnitPriority } from './priorities';
import { addRegexToken, match1to2, match2 } from '../parse/regex';
import { addParseToken } from '../parse/token';
import { DATE } from './constants';
import toInt from '../utils/to-int';
// FORMATTING
addFormatToken('D', ['DD', 2], 'Do', 'date');
// ALIASES
addUnitAlias('date', 'D');
// PRIOROITY
addUnitPriority('date', 9);
// PARSING
addRegexToken('D', match1to2);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
// TODO: Remove "ordinalParse" fallback in next major release.
return isStrict ?
(locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
locale._dayOfMonthOrdinalParseLenient;
});
addParseToken(['D', 'DD'], DATE);
addParseToken('Do', function (input, array) {
array[DATE] = toInt(input.match(match1to2)[0], 10);
});
// MOMENTS
export var getSetDayOfMonth = makeGetSet('Date', true);
| import { makeGetSet } from '../moment/get-set';
import { addFormatToken } from '../format/format';
import { addUnitAlias } from './aliases';
import { addUnitPriority } from './priorities';
import { addRegexToken, match1to2, match2 } from '../parse/regex';
import { addParseToken } from '../parse/token';
import { DATE } from './constants';
import toInt from '../utils/to-int';
// FORMATTING
addFormatToken('D', ['DD', 2], 'Do', 'date');
// ALIASES
addUnitAlias('date', 'D');
// PRIOROITY
addUnitPriority('date', 9);
// PARSING
addRegexToken('D', match1to2);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
return isStrict ? locale._dayOfMonthOrdinalParse : locale._dayOfMonthOrdinalParseLenient;
});
addParseToken(['D', 'DD'], DATE);
addParseToken('Do', function (input, array) {
array[DATE] = toInt(input.match(match1to2)[0], 10);
});
// MOMENTS
export var getSetDayOfMonth = makeGetSet('Date', true);
|
Move flask-restful api defs before init_app, since it doesn't work
otherwise with new version of flask-restful | from flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
| from flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
|
Remove accidentally added .only in tests | import { init } from '../htmlnano';
describe('collapseAttributeWhitespace', () => {
const options = {collapseAttributeWhitespace: {}};
it('it should collapse whitespaces inside list-like attributes', () => {
return init(
'<a class=" foo bar baz ">click</a>',
'<a class="foo bar baz">click</a>',
options
);
});
it('should not collapse whitespaces inside non-list-like attributes', () => {
return init(
'<a id=" foo bar " href=" baz bar ">click</a>',
'<a id=" foo bar " href=" baz bar ">click</a>',
options
);
});
});
| import { init } from '../htmlnano';
describe.only('collapseAttributeWhitespace', () => {
const options = {collapseAttributeWhitespace: {}};
it('it should collapse whitespaces inside list-like attributes', () => {
return init(
'<a class=" foo bar baz ">click</a>',
'<a class="foo bar baz">click</a>',
options
);
});
it('should not collapse whitespaces inside non-list-like attributes', () => {
return init(
'<a id=" foo bar " href=" baz bar ">click</a>',
'<a id=" foo bar " href=" baz bar ">click</a>',
options
);
});
});
|
Format exceptions to JSON in JSON layer | <?php
namespace Aztech\Layers\Elements;
use Aztech\Layers\Responses\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class JsonRenderingLayer
{
private $callable;
public function __construct(callable $callable)
{
$this->callable = $callable;
}
public function __invoke(Request $request = null)
{
if (! $request) {
$request = Request::createFromGlobals();
}
$callable = $this->callable;
try {
$response = $callable($request);
}
catch (HttpException $exception) {
$response = new JsonResponse($exception->getMessage(), $exception->getStatusCode());
}
if ($response instanceof Response) {
return (new JsonResponse($response->getContent(), $response->getStatusCode()))->getResponse();
}
if (! $response) {
$response = [];
}
return (new JsonResponse($response, 200))->getResponse();
}
}
| <?php
namespace Aztech\Layers\Elements;
use Aztech\Layers\Responses\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class JsonRenderingLayer
{
private $callable;
public function __construct(callable $callable)
{
$this->callable = $callable;
}
public function __invoke(Request $request = null)
{
if (! $request) {
$request = Request::createFromGlobals();
}
$callable = $this->callable;
$response = $callable($request);
if ($response instanceof Response) {
return (new JsonResponse($response->getContent(), $response->getStatusCode()))->getResponse();
}
if (! $response) {
$response = [];
}
return (new JsonResponse($response, 200))->getResponse();
}
}
|
Remove leftover text key from our own payload creation | # encoding: utf-8
"""A payload based version of page."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from IPython.core.getipython import get_ipython
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
def page(strng, start=0, screen_lines=0, pager_cmd=None):
"""Print a string, piping through a pager.
This version ignores the screen_lines and pager_cmd arguments and uses
IPython's payload system instead.
Parameters
----------
strng : str or mime-dict
Text to page, or a mime-type keyed dict of already formatted data.
start : int
Starting line at which to place the display.
"""
# Some routines may auto-compute start offsets incorrectly and pass a
# negative value. Offset to 0 for robustness.
start = max(0, start)
shell = get_ipython()
if isinstance(strng, dict):
data = strng
else:
data = {'text/plain' : strng}
payload = dict(
source='page',
data=data,
start=start,
screen_lines=screen_lines,
)
shell.payload_manager.write_payload(payload)
def install_payload_page():
"""Install this version of page as IPython.core.page.page."""
from IPython.core import page as corepage
corepage.page = page
| # encoding: utf-8
"""A payload based version of page."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from IPython.core.getipython import get_ipython
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
def page(strng, start=0, screen_lines=0, pager_cmd=None):
"""Print a string, piping through a pager.
This version ignores the screen_lines and pager_cmd arguments and uses
IPython's payload system instead.
Parameters
----------
strng : str or mime-dict
Text to page, or a mime-type keyed dict of already formatted data.
start : int
Starting line at which to place the display.
"""
# Some routines may auto-compute start offsets incorrectly and pass a
# negative value. Offset to 0 for robustness.
start = max(0, start)
shell = get_ipython()
if isinstance(strng, dict):
data = strng
else:
data = {'text/plain' : strng}
payload = dict(
source='page',
data=data,
text=strng,
start=start,
screen_lines=screen_lines,
)
shell.payload_manager.write_payload(payload)
def install_payload_page():
"""Install this version of page as IPython.core.page.page."""
from IPython.core import page as corepage
corepage.page = page
|
Fix bad message from TimeoutError
Before:
Error creating IAM Role my-role: timeout while waiting for state
to become 'success'. last error: %!s(<nil>) | package resource
import (
"fmt"
"strings"
)
type NotFoundError struct {
LastError error
LastRequest interface{}
LastResponse interface{}
Message string
Retries int
}
func (e *NotFoundError) Error() string {
if e.Message != "" {
return e.Message
}
return "couldn't find resource"
}
// UnexpectedStateError is returned when Refresh returns a state that's neither in Target nor Pending
type UnexpectedStateError struct {
LastError error
State string
ExpectedState []string
}
func (e *UnexpectedStateError) Error() string {
return fmt.Sprintf(
"unexpected state '%s', wanted target '%s'. last error: %s",
e.State,
strings.Join(e.ExpectedState, ", "),
e.LastError,
)
}
// TimeoutError is returned when WaitForState times out
type TimeoutError struct {
LastError error
ExpectedState []string
}
func (e *TimeoutError) Error() string {
msg := fmt.Sprintf("timeout while waiting for state to become '%s'",
strings.Join(e.ExpectedState, ", "))
if e.LastError != nil {
msg += fmt.Sprintf(". last error: %s", e.LastError)
}
return msg
}
| package resource
import (
"fmt"
"strings"
)
type NotFoundError struct {
LastError error
LastRequest interface{}
LastResponse interface{}
Message string
Retries int
}
func (e *NotFoundError) Error() string {
if e.Message != "" {
return e.Message
}
return "couldn't find resource"
}
// UnexpectedStateError is returned when Refresh returns a state that's neither in Target nor Pending
type UnexpectedStateError struct {
LastError error
State string
ExpectedState []string
}
func (e *UnexpectedStateError) Error() string {
return fmt.Sprintf(
"unexpected state '%s', wanted target '%s'. last error: %s",
e.State,
strings.Join(e.ExpectedState, ", "),
e.LastError,
)
}
// TimeoutError is returned when WaitForState times out
type TimeoutError struct {
LastError error
ExpectedState []string
}
func (e *TimeoutError) Error() string {
return fmt.Sprintf(
"timeout while waiting for state to become '%s'. last error: %s",
strings.Join(e.ExpectedState, ", "),
e.LastError,
)
}
|
Move webpack output into correct place | #!/usr/bin/env node
const chalk = require("chalk");
const cli = require("../cli/cli");
console.log(``);
console.log(`${chalk.black(chalk.bgYellow(" ~~~~~~~~~~ "))}`);
console.log(`${chalk.black(chalk.bgYellow(" ๐ซ kaba "))}`);
console.log(`${chalk.black(chalk.bgYellow(" ~~~~~~~~~~ "))}`);
console.log(``);
if (cli.showHelp())
{
// @todo implement
console.log("show help");
process.exit(0);
}
else if (cli.showVersion())
{
// @todo implement
console.log("show version");
process.exit(0);
}
// set environment
process.env.NODE_ENV = cli.isDebug() ? '"development"' : '"production"';
// strip all other arguments
process.argv = process.argv.slice(0,2);
try
{
console.log(chalk`Running {cyan webpack} ...`);
console.log();
require('webpack/bin/webpack');
}
catch (e)
{
console.log(chalk`{red Webpack Error: ${e.message}}`);
if (cli.isVerbose())
{
throw e;
}
}
| #!/usr/bin/env node
const chalk = require("chalk");
const cli = require("../cli/cli");
console.log(``);
console.log(`${chalk.black(chalk.bgYellow(" ~~~~~~~~~~ "))}`);
console.log(`${chalk.black(chalk.bgYellow(" ๐ซ kaba "))}`);
console.log(`${chalk.black(chalk.bgYellow(" ~~~~~~~~~~ "))}`);
console.log(``);
console.log('Running webpack ...');
console.log();
if (cli.showHelp())
{
// @todo implement
console.log("show help");
process.exit(0);
}
else if (cli.showVersion())
{
// @todo implement
console.log("show version");
process.exit(0);
}
// set environment
process.env.NODE_ENV = cli.isDebug() ? '"development"' : '"production"';
// strip all other arguments
process.argv = process.argv.slice(0,2);
try
{
require('webpack/bin/webpack');
}
catch (e)
{
console.log(chalk`{red Webpack Error: ${e.message}}`);
if (cli.isVerbose())
{
throw e;
}
}
|
Update dsub version to 0.3.10
PiperOrigin-RevId: 324884094 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.10'
| # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.10.dev0'
|
Use Symbol instead of closure | 'use strict'
var tgTypes = {};
var _rowWidth = Symbol('rowWidth');
tgTypes.InlineKeyboardMarkup = function (rowWidth) {
this['inline_keyboard'] = [[]];
this[_rowWidth] = (rowWidth > 8 ? 8 : rowWidth) || 8; //Currently maximum supported in one row
};
tgTypes.InlineKeyboardMarkup.prototype.add = function (text, field, fieldValue) {
if (this._isRowFull()) {
this.newRow();
};
this['inline_keyboard'][this._lastRow()].push(
{
'text': text,
[field]: fieldValue
}
);
return this;
};
tgTypes.InlineKeyboardMarkup.prototype.newRow = function () {
this['inline_keyboard'].push([]);
return this;
};
tgTypes.InlineKeyboardMarkup.prototype._isRowFull = function () {
if (this['inline_keyboard'][this._lastRow()].length === this[_rowWidth]) {
return true;
};
};
tgTypes.InlineKeyboardMarkup.prototype._lastRow = function () {
return this['inline_keyboard'].length-1;
};
module.exports = tgTypes;
| 'use strict'
var tgTypes = {};
tgTypes.InlineKeyboardMarkup = function (rowWidth) {
this['inline_keyboard'] = [[]];
var rowWidth = (rowWidth > 8 ? 8 : rowWidth) || 8; //Currently maximum supported in one row
//Closure to make this property private
this._rowWidth = function () {
return rowWidth;
};
};
tgTypes.InlineKeyboardMarkup.prototype.add = function (text, field, fieldValue) {
this['inline_keyboard'][this._lastRow()].push(
{
'text': text,
[field]: fieldValue
}
);
if (this._isRowFull()) {
this.newRow();
};
return this;
};
tgTypes.InlineKeyboardMarkup.prototype.newRow = function () {
this['inline_keyboard'].push([]);
return this;
};
tgTypes.InlineKeyboardMarkup.prototype._isRowFull = function () {
if (this['inline_keyboard'][this._lastRow()].length === this._rowWidth()) {
return true;
};
};
tgTypes.InlineKeyboardMarkup.prototype._lastRow = function () {
return this['inline_keyboard'].length-1;
};
module.exports = tgTypes;
|
Fix REST function comments for POST | # restfns - REST functions for azurerm
import requests
# do_get(endpoint, access_token)
# do an HTTP GET request and return JSON
def do_get(endpoint, access_token):
headers = {"Authorization": 'Bearer ' + access_token}
return requests.get(endpoint, headers=headers).json()
# do_delete(endpoint, access_token)
# do an HTTP GET request and return JSON
def do_delete(endpoint, access_token):
headers = {"Authorization": 'Bearer ' + access_token}
return requests.delete(endpoint, headers=headers)
# do_put(endpoint, body, access_token)
# do an HTTP PUT request and return JSON
def do_put(endpoint, body, access_token):
headers = {"content-type": "application/json", "Authorization": 'Bearer ' + access_token}
return requests.put(endpoint, data=body, headers=headers)
# do_post(endpoint, body, access_token)
# do an HTTP POST request and return JSON
def do_post(endpoint, body, access_token):
headers = {"content-type": "application/json", "Authorization": 'Bearer ' + access_token}
return requests.post(endpoint, data=body, headers=headers) | # restfns - REST functions for azurerm
import requests
# do_get(endpoint, access_token)
# do an HTTP GET request and return JSON
def do_get(endpoint, access_token):
headers = {"Authorization": 'Bearer ' + access_token}
return requests.get(endpoint, headers=headers).json()
# do_delete(endpoint, access_token)
# do an HTTP GET request and return JSON
def do_delete(endpoint, access_token):
headers = {"Authorization": 'Bearer ' + access_token}
return requests.delete(endpoint, headers=headers)
# do_put(endpoint, body, access_token)
# do an HTTP PUT request and return JSON
def do_put(endpoint, body, access_token):
headers = {"content-type": "application/json", "Authorization": 'Bearer ' + access_token}
return requests.put(endpoint, data=body, headers=headers)
# do_put(endpoint, body, access_token)
# do an HTTP PUT request and return JSON
def do_post(endpoint, body, access_token):
headers = {"content-type": "application/json", "Authorization": 'Bearer ' + access_token}
return requests.post(endpoint, data=body, headers=headers) |
Add test on check file if exist | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import pytest
from .test_bot import TestBot
class TestBotSupport(TestBot):
@pytest.mark.parametrize('url,result', [
('https://google.com', ['https://google.com']),
('google.com', ['google.com']),
('google.com/search?q=instabot', ['google.com/search?q=instabot']),
('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']),
('ะผะฒะด.ัั', ['ะผะฒะด.ัั']),
('https://ะผะฒะด.ัั', ['https://ะผะฒะด.ัั']),
('http://ะผะฒะด.ัั/news/', ['http://ะผะฒะด.ัั/news/']),
('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']),
])
def test_extract_urls(self, url, result):
assert self.BOT.extract_urls(url) == result
def test_check_if_file_exist(self):
test_file = open('test', 'w')
assert self.BOT.check_if_file_exists('test')
test_file.close()
os.remove('test')
def test_check_if_file_exist_fail(self):
assert not self.BOT.check_if_file_exists('test')
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from .test_bot import TestBot
class TestBotSupport(TestBot):
@pytest.mark.parametrize('url,result', [
('https://google.com', ['https://google.com']),
('google.com', ['google.com']),
('google.com/search?q=instabot', ['google.com/search?q=instabot']),
('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']),
('ะผะฒะด.ัั', ['ะผะฒะด.ัั']),
('https://ะผะฒะด.ัั', ['https://ะผะฒะด.ัั']),
('http://ะผะฒะด.ัั/news/', ['http://ะผะฒะด.ัั/news/']),
('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']),
])
def test_extract_urls(self, url, result):
assert self.BOT.extract_urls(url) == result
|
Update Lambda Helper docblock. It was a lie. | <?php
/*
* This file is part of Mustache.php.
*
* (c) 2012 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Mustache Lambda Helper.
*
* Passed as the second argument to section lambdas (higher order sections),
* giving them access to a `render` method for rendering a string with the
* current context.
*/
class Mustache_LambdaHelper
{
private $mustache;
private $context;
/**
* Mustache Lambda Helper constructor.
*
* @param Mustache_Engine $mustache Mustache engine instance.
* @param Mustache_Context $context Rendering context.
*/
public function __construct(Mustache_Engine $mustache, Mustache_Context $context)
{
$this->mustache = $mustache;
$this->context = $context;
}
/**
* Render a string as a Mustache template with the current rendering context.
*
* @param string $string
*
* @return Rendered template.
*/
public function render($string)
{
return $this->mustache
->loadLambda((string) $string)
->renderInternal($this->context);
}
}
| <?php
/*
* This file is part of Mustache.php.
*
* (c) 2012 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Mustache Lambda Helper.
*
* Passed to section and interpolation lambdas, giving them access to a `render`
* method for rendering a string with the current context.
*/
class Mustache_LambdaHelper
{
private $mustache;
private $context;
/**
* Mustache Lambda Helper constructor.
*
* @param Mustache_Engine $mustache Mustache engine instance.
* @param Mustache_Context $context Rendering context.
*/
public function __construct(Mustache_Engine $mustache, Mustache_Context $context)
{
$this->mustache = $mustache;
$this->context = $context;
}
/**
* Render a string as a Mustache template with the current rendering context.
*
* @param string $string
*
* @return Rendered template.
*/
public function render($string)
{
return $this->mustache
->loadLambda((string) $string)
->renderInternal($this->context);
}
}
|
Update login controller for register | package com.huixinpn.dionysus.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.huixinpn.dionysus.domain.User;
import com.huixinpn.dionysus.service.UserService;
@Controller
public class LoginController {
private UserService userService;
@Autowired
public LoginController(UserService service) {
this.userService = service;
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public void login(@RequestBody User user) {
userService.sign(user.getUsername(),
user.getPassword());
}
@RequestMapping(value = "/login/failure", method = RequestMethod.GET)
public String loginFailure() {
String message = "Login Failure!";
return "redirect:/login?message="+message;
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout() {
String message = "Logout Success!";
return "redirect:/login?message="+message;
}
@RequestMapping(value = "/validate/users", method = RequestMethod.POST)
public boolean validate(@RequestBody User user) {
return userService.userValidation(
user.getUsername(),
user.getPassword());
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public User register(@RequestBody User user) {
return userService.register(user);
}
}
| package com.huixinpn.dionysus.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.huixinpn.dionysus.domain.User;
import com.huixinpn.dionysus.service.UserService;
@Controller
public class LoginController {
private UserService userService;
@Autowired
public LoginController(UserService service) {
this.userService = service;
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public void login(@RequestBody User user) {
userService.sign(user.getUsername(),
user.getPassword());
}
@RequestMapping(value = "/login/failure", method = RequestMethod.GET)
public String loginFailure() {
String message = "Login Failure!";
return "redirect:/login?message="+message;
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout() {
String message = "Logout Success!";
return "redirect:/login?message="+message;
}
@RequestMapping(value = "/validate/users", method = RequestMethod.POST)
public boolean validate(@RequestBody User user) {
return userService.userValidation(
user.getUsername(),
user.getPassword());
}
}
|
Add more necessary methods to Transcoder interface | package transcode
import (
"errors"
"github.com/mdlayher/wavepipe/data"
)
var (
// ErrInvalidCodec is returned when an invalid transcoder codec is selected
ErrInvalidCodec = errors.New("transcode: no such transcoder codec")
// ErrInvalidQuality is returned when an invalid quality is selected for a given codec
ErrInvalidQuality = errors.New("transcode: invalid quality for transcoder codec")
)
// Enabled determines whether transcoding is available and enabled for wavepipe
var Enabled bool
// FFmpegPath is the path to the ffmpeg binary detected by the transcode manager
var FFmpegPath string
// Transcoder represents a transcoding operation, and the methods which must be defined
// for a transcoder
type Transcoder interface {
Codec() string
FFmpeg() *FFmpeg
MIMEType() string
SetSong(*data.Song)
Quality() string
}
// Factory generates a new Transcoder depending on the input parameters
func Factory(codec string, quality string) (Transcoder, error) {
// Check for a valid codec
switch codec {
// MP3
case "mp3", "MP3":
return NewMP3Transcoder(quality)
// Invalid choice
default:
return nil, ErrInvalidCodec
}
}
| package transcode
import (
"errors"
)
var (
// ErrInvalidCodec is returned when an invalid transcoder codec is selected
ErrInvalidCodec = errors.New("transcode: no such transcoder codec")
// ErrInvalidQuality is returned when an invalid quality is selected for a given codec
ErrInvalidQuality = errors.New("transcode: invalid quality for transcoder codec")
)
// Enabled determines whether transcoding is available and enabled for wavepipe
var Enabled bool
// FFmpegPath is the path to the ffmpeg binary detected by the transcode manager
var FFmpegPath string
// Transcoder represents a transcoding operation, and the methods which must be defined
// for a transcoder
type Transcoder interface {
Codec() string
Quality() string
}
// Factory generates a new Transcoder depending on the input parameters
func Factory(codec string, quality string) (Transcoder, error) {
// Check for a valid codec
switch codec {
// MP3
case "mp3", "MP3":
return NewMP3Transcoder(quality)
// Invalid choice
default:
return nil, ErrInvalidCodec
}
}
|
Set the module as auto_install
So it installs when both sale_payment_method and sale_automatic_workflow are installed.
This module acts as the glue between them | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Sale Payment Method - Automatic Reconcile',
'version': '1.0',
'author': ['Camptocamp', 'Akretion'],
'license': 'AGPL-3',
'category': 'Generic Modules/Others',
'depends': ['sale_payment_method',
'sale_automatic_workflow'],
'website': 'http://www.camptocamp.com',
'data': [],
'test': [],
'installable': True,
'auto_install': True,
}
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Sale Payment Method - Automatic Reconcile',
'version': '1.0',
'author': ['Camptocamp', 'Akretion'],
'license': 'AGPL-3',
'category': 'Generic Modules/Others',
'depends': ['sale_payment_method',
'sale_automatic_workflow'],
'website': 'http://www.camptocamp.com',
'data': [],
'test': [],
'installable': True,
'auto_install': False,
}
|
Add note about needing to create the infopage | from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, \
SAOrganisationDetailView, SAPersonDetail, SANewsletterPage
from pombola.core.urls import organisation_patterns, person_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
# Override the person url so we can add some extra data
for index, pattern in enumerate(person_patterns):
if pattern.name == 'person':
person_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAPersonDetail.as_view(), name='person')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
# Catch the newsletter info page to change the template used so that the signup form is injected.
# NOTE - you still need to create an InfoPage with the slug 'newsletter' for this not to 404.
url(r'^info/newsletter', SANewsletterPage.as_view(), {'slug': 'newsletter'}, name='info_page_newsletter'),
)
| from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, \
SAOrganisationDetailView, SAPersonDetail, SANewsletterPage
from pombola.core.urls import organisation_patterns, person_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
# Override the person url so we can add some extra data
for index, pattern in enumerate(person_patterns):
if pattern.name == 'person':
person_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAPersonDetail.as_view(), name='person')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
url(r'^info/newsletter', SANewsletterPage.as_view(), {'slug': 'newsletter'}, name='info_page_newsletter'),
)
|
Add debug to fileID stuff
Show the xattr added after archive completes. | package agent
import (
"github.intel.com/hpdd/logging/debug"
"github.intel.com/hpdd/lustre"
"github.intel.com/hpdd/lustre/fs"
"github.intel.com/hpdd/lustre/pkg/xattr"
)
const xattrFileID = "trusted.hsm_file_id"
func updateFileID(mnt fs.RootDir, fid *lustre.Fid, fileID []byte) error {
p := fs.FidPath(mnt, fid)
debug.Printf("setting %s=%s on %s", xattrFileID, fileID, p)
return xattr.Lsetxattr(p, xattrFileID, fileID, 0)
}
func getFileID(mnt fs.RootDir, fid *lustre.Fid) ([]byte, error) {
buf := make([]byte, 256)
p := fs.FidPath(mnt, fid)
sz, err := xattr.Lgetxattr(p, xattrFileID, buf)
if err != nil {
return nil, err
}
return buf[0:sz], nil
}
| package agent
import (
"github.intel.com/hpdd/lustre"
"github.intel.com/hpdd/lustre/fs"
"github.intel.com/hpdd/lustre/pkg/xattr"
)
const xattrFileID = "trusted.hsm_file_id"
func updateFileID(mnt fs.RootDir, fid *lustre.Fid, fileID []byte) error {
p := fs.FidPath(mnt, fid)
err := xattr.Lsetxattr(p, xattrFileID, fileID, 0)
if err != nil {
return err
}
return nil
}
func getFileID(mnt fs.RootDir, fid *lustre.Fid) ([]byte, error) {
buf := make([]byte, 256)
p := fs.FidPath(mnt, fid)
sz, err := xattr.Lgetxattr(p, xattrFileID, buf)
if err != nil {
return nil, err
}
return buf[0:sz], nil
}
|
Use Ember namespace for jquery use | import Em from 'ember';
import { task, timeout } from 'ember-concurrency';
const { computed } = Em;
var applicationController = Em.Controller.extend({
activeNote: null,
hideSidePanel: false,
init: function() {
Em.run.scheduleOnce('afterRender', () => {
Em.$('body div').first().addClass('app-container');
});
},
// data
sortedNotes: computed('model.[]', 'model.@each.updatedAt', function() {
return this.get('model').sortBy('updatedAt', 'createdAt').reverseObjects();
}),
deleteNote: task(function *(note) {
yield timeout(150);
this.get('model').removeObject(note);
if (Em.isEmpty(this.get('model'))) {
this.send('createNote');
} else {
this.send('showNote', this.get('sortedNotes.firstObject'));
}
yield note.destroyRecord();
}).drop(),
actions: {
createNote() {
this.transitionToRoute('new');
},
deleteNote(note) {
this.get('deleteNote').perform(note);
},
signOut() {
this.get('session').close().then(()=> {
this.transitionToRoute('signin');
});
},
toggleSidePanelHidden() {
this.toggleProperty('hideSidePanel');
}
}
});
export default applicationController;
| import Em from 'ember';
import { task, timeout } from 'ember-concurrency';
const { computed } = Em;
var applicationController = Em.Controller.extend({
activeNote: null,
hideSidePanel: false,
init: function() {
Em.run.scheduleOnce('afterRender', () => {
$('body div').first().addClass('app-container');
});
},
// data
sortedNotes: computed('model.[]', 'model.@each.updatedAt', function() {
return this.get('model').sortBy('updatedAt', 'createdAt').reverseObjects();
}),
deleteNote: task(function *(note) {
yield timeout(150);
this.get('model').removeObject(note);
if (Em.isEmpty(this.get('model'))) {
this.send('createNote');
} else {
this.send('showNote', this.get('sortedNotes.firstObject'));
}
yield note.destroyRecord();
}).drop(),
actions: {
createNote() {
this.transitionToRoute('new');
},
deleteNote(note) {
this.get('deleteNote').perform(note);
},
signOut() {
this.get('session').close().then(()=> {
this.transitionToRoute('signin');
});
},
toggleSidePanelHidden() {
this.toggleProperty('hideSidePanel');
}
}
});
export default applicationController;
|
Delete files after they have been processed. | <?php
define('JAVA_PATH', '/usr/bin/java');
define('TMP_DIR', '/tmp');
define('FFF_PATH', dirname(dirname(__FILE__)));
define('CLASSPATH', FFF_PATH . '/itext.jar:' . FFF_PATH . '/json-org.jar:' . FFF_PATH . '/');
$template_tmp = isset($_FILES['template']['tmp_name']) ? $_FILES['template']['tmp_name'] : '';
$config_tmp = isset($_FILES['config']['tmp_name']) ? $_FILES['config']['tmp_name'] : '';
$template = tempnam(TMP_DIR, 'FFF');
$config = tempnam(TMP_DIR, 'FFF');
$output = tempnam(TMP_DIR, 'FFF');
// Move uploaded files, otherwise they may be deleted before we call FFF
move_uploaded_file($template_tmp, $template);
move_uploaded_file($config_tmp, $config);
$execstr = JAVA_PATH . ' -classpath ' . CLASSPATH . " FormFillFlatten $config $template $output";
exec($execstr);
echo file_get_contents($output);
// Remove the temporary files
unlink($template);
unlink($config);
unlink($output);
?>
| <?php
define('JAVA_PATH', '/usr/bin/java');
define('TMP_DIR', '/tmp');
define('FFF_PATH', dirname(dirname(__FILE__)));
define('CLASSPATH', FFF_PATH . '/itext.jar:' . FFF_PATH . '/json-org.jar:' . FFF_PATH . '/');
$template_tmp = isset($_FILES['template']['tmp_name']) ? $_FILES['template']['tmp_name'] : '';
$config_tmp = isset($_FILES['config']['tmp_name']) ? $_FILES['config']['tmp_name'] : '';
$template = tempnam(TMP_DIR, 'FFF');
$config = tempnam(TMP_DIR, 'FFF');
$output = tempnam(TMP_DIR, 'FFF');
// Move uploaded files, otherwise they may be deleted before we call FFF
move_uploaded_file($template_tmp, $template);
move_uploaded_file($config_tmp, $config);
$execstr = JAVA_PATH . ' -classpath ' . CLASSPATH . " FormFillFlatten $config $template $output";
exec($execstr);
echo file_get_contents($output);
?>
|
Remove now useless TearDown method. | # Basic test of dynamic code generation
import unittest
import os, glob
import stdio
from ctypes import POINTER, c_int
class DynModTest(unittest.TestCase):
def test_fopen(self):
self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE))
self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING])
def test_constants(self):
self.failUnlessEqual(stdio.O_RDONLY, 0)
self.failUnlessEqual(stdio.O_WRONLY, 1)
self.failUnlessEqual(stdio.O_RDWR, 2)
def test_compiler_errors(self):
from ctypeslib.codegen.cparser import CompilerError
from ctypeslib.dynamic_module import include
self.failUnlessRaises(CompilerError, lambda: include("#error"))
if __name__ == "__main__":
unittest.main()
| # Basic test of dynamic code generation
import unittest
import os, glob
import stdio
from ctypes import POINTER, c_int
class DynModTest(unittest.TestCase):
def tearDown(self):
for fnm in glob.glob(stdio._gen_basename + ".*"):
try:
os.remove(fnm)
except IOError:
pass
def test_fopen(self):
self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE))
self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING])
def test_constants(self):
self.failUnlessEqual(stdio.O_RDONLY, 0)
self.failUnlessEqual(stdio.O_WRONLY, 1)
self.failUnlessEqual(stdio.O_RDWR, 2)
def test_compiler_errors(self):
from ctypeslib.codegen.cparser import CompilerError
from ctypeslib.dynamic_module import include
self.failUnlessRaises(CompilerError, lambda: include("#error"))
if __name__ == "__main__":
unittest.main()
|
Remove generation of unnecessary generated.rst file | #!/usr/bin/env python
from os.path import join, dirname, abspath
from IPython.terminal.ipapp import TerminalIPythonApp
from ipykernel.kernelapp import IPKernelApp
here = abspath(dirname(__file__))
options = join(here, 'source', 'config', 'options')
def write_doc(name, title, app, preamble=None):
filename = '%s.rst' % name
with open(join(options, filename), 'w') as f:
f.write(title + '\n')
f.write(('=' * len(title)) + '\n')
f.write('\n')
if preamble is not None:
f.write(preamble + '\n\n')
f.write(app.document_config_options())
if __name__ == '__main__':
write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp())
write_doc('kernel', 'IPython kernel options', IPKernelApp(),
preamble=("These options can be used in :file:`ipython_kernel_config.py`. "
"The kernel also respects any options in `ipython_config.py`"),
)
| #!/usr/bin/env python
from os.path import join, dirname, abspath
from IPython.terminal.ipapp import TerminalIPythonApp
from ipykernel.kernelapp import IPKernelApp
here = abspath(dirname(__file__))
options = join(here, 'source', 'config', 'options')
generated = join(options, 'generated.rst')
def write_doc(name, title, app, preamble=None):
filename = '%s.rst' % name
with open(join(options, filename), 'w') as f:
f.write(title + '\n')
f.write(('=' * len(title)) + '\n')
f.write('\n')
if preamble is not None:
f.write(preamble + '\n\n')
f.write(app.document_config_options())
with open(generated, 'a') as f:
f.write(filename + '\n')
if __name__ == '__main__':
# create empty file
with open(generated, 'w'):
pass
write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp())
write_doc('kernel', 'IPython kernel options', IPKernelApp(),
preamble=("These options can be used in :file:`ipython_kernel_config.py`. "
"The kernel also respects any options in `ipython_config.py`"),
)
|
TextImage: Improve data-type of flow attribute in content-api | <?php
class Kwc_TextImage_ApiContent implements Kwf_Component_ApiContent_Interface
{
public function getContent(Kwf_Component_Data $data)
{
$ret = array();
$row = $data->getComponent()->getRow();
if ($row->image) {
if ($row->position) {
$ret['position'] = $row->position;
}
if ($row->image_width) {
$ret['imageWidth'] = $row->image_width;
}
if ($row->flow) {
$ret['flow'] = !!$row->flow;
}
$ret['image'] = $data->getChildComponent('-image');
}
$ret['text'] = $data->getChildComponent('-text');
return $ret;
}
}
| <?php
class Kwc_TextImage_ApiContent implements Kwf_Component_ApiContent_Interface
{
public function getContent(Kwf_Component_Data $data)
{
$ret = array();
$row = $data->getComponent()->getRow();
if ($row->image) {
if ($row->position) {
$ret['position'] = $row->position;
}
if ($row->image_width) {
$ret['imageWidth'] = $row->image_width;
}
if ($row->flow) {
$ret['flow'] = $row->flow;
}
$ret['image'] = $data->getChildComponent('-image');
}
$ret['text'] = $data->getChildComponent('-text');
return $ret;
}
}
|
Use gpx.name as index to gpx data_frame | __author__ = 'max'
import gpxpy
import pandas as pd
def parse_gpx(gpx_file_name):
return gpxpy.parse(gpx_file_name)
def data_frame_for_track_segment(segment):
seg_dict = {}
for point in segment.points:
seg_dict[point.time] = [point.latitude, point.longitude,
point.elevation, point.speed]
seg_frame = pd.DataFrame(data=seg_dict)
# Switch columns and rows s.t. timestamps are rows and gps data columns.
seg_frame = seg_frame.T
seg_frame.columns = ['latitude', 'longitude', 'altitude', 'speed']
return seg_frame
def track_segment_mapping(track):
segments = (data_frame_for_track_segment(segment)
for segment in track.segments)
return segments
def pandas_data_frame_for_gpx(gpx):
tracks_frames = (track_segment_mapping(track) for track in gpx.tracks)
# Create a hierarchical DataFrame by unstacking.
tracks_frame = pd.DataFrame(tracks_frames)
assert gpx.name
return pd.DataFrame({gpx.name:tracks_frame.unstack()}) | __author__ = 'max'
import gpxpy
import pandas as pd
def parse_gpx(gpx_file_name):
return gpxpy.parse(gpx_file_name)
def data_frame_for_track_segment(segment):
seg_dict = {}
for point in segment.points:
seg_dict[point.time] = [point.latitude, point.longitude,
point.elevation, point.speed]
seg_frame = pd.DataFrame(data=seg_dict)
# Switch columns and rows s.t. timestamps are rows and gps data columns.
seg_frame = seg_frame.T
seg_frame.columns = ['latitude', 'longitude', 'altitude', 'speed']
return seg_frame
def track_segment_mapping(track):
segments = (data_frame_for_track_segment(segment)
for segment in track.segments)
return segments
def pandas_data_frame_for_gpx(gpx):
tracks_frames = (track_segment_mapping(track) for track in gpx.tracks)
# Create a hierarchical DataFrame by unstacking.
tracks_frame = pd.DataFrame(tracks_frames)
return tracks_frame.unstack() |
Add test for CommandNotFoundError exception being thrown by Executor. | <?php
class ExecutorTest extends PHPUnit_Framework_TestCase
{
/**
* @var \MeadSteve\Console\Executor
*/
protected $testedExecutor;
protected function setUp()
{
$this->testedExecutor = new MeadSteve\Console\Executor();
}
function testExecute_ThrowsExceptionOnInvalidCommand()
{
$this->setExpectedException(
'MeadSteve\Console\Exceptions\ExecutionError',
"git: 'foobar' is not a git command. See 'git --help'."
);
$this->testedExecutor->execute("git foobar");
}
function testExecute_ThrowsCommandNotFoundErrorWhenNotFond()
{
$this->setExpectedException(
'MeadSteve\Console\Exceptions\CommandNotFoundError'
);
$this->testedExecutor->execute("gitDSFGscvb foobar");
}
function testExecute_ReturnsArrayOnValidCommand()
{
$output = $this->testedExecutor->execute("git status");
$this->assertInternalType('array', $output);
}
}
| <?php
class ExecutorTest extends PHPUnit_Framework_TestCase
{
/**
* @var \MeadSteve\Console\Executor
*/
protected $testedExecutor;
protected function setUp()
{
$this->testedExecutor = new MeadSteve\Console\Executor();
}
function testExecute_ThrowsExceptionOnInvalidCommand()
{
$this->setExpectedException(
'MeadSteve\Console\Exceptions\ExecutionError',
"git: 'foobar' is not a git command. See 'git --help'."
);
$this->testedExecutor->execute("git foobar");
}
function testExecute_ReturnsArrayOnValidCommand()
{
$output = $this->testedExecutor->execute("git status");
$this->assertInternalType('array', $output);
}
}
|
Fix misspeling in function name | <?php
namespace ExpressiveLogger\Factory;
use ExpressiveLogger\Exception\InvalidConfigurationException;
use Interop\Container\ContainerInterface;
use Monolog\Handler\RedisHandler;
use Monolog\Logger;
use Predis\Client;
final class RedisHandlerFactory
{
public function __invoke(ContainerInterface $container) : RedisHandler
{
$config = $container->get('config');
if (!isset($config['expressiveLogger']['handlers']['redis'])) {
throw new InvalidConfigurationException('Redis config is not set');
}
$redisConfig = $config['expressiveLogger']['handlers']['redis'];
$redisClient = $container->get($redisConfig['client']);
if (!$redisClient) {
throw new InvalidConfigurationException('Redis client not found in container');
}
if ($redisClient instanceof Client) {
throw new InvalidConfigurationException('Redis client have to be instance of Predis\Client');
}
$key = $redisConfig['key'] ?? 'default';
$level = $redisConfig['key'] ?? Logger::DEBUG;
return new RedisHandler($redisClient, $key, $level);
}
} | <?php
namespace ExpressiveLogger\Factory;
use ExpressiveLogger\Exception\InvalidConfigurationException;
use Interop\Container\ContainerInterface;
use Monolog\Handler\RedisHandler;
use Monolog\Logger;
use Predis\Client;
final class RedisHandlerFactory
{
public function __invokable(ContainerInterface $container) : RedisHandler
{
$config = $container->get('config');
if (!isset($config['expressiveLogger']['handlers']['redis'])) {
throw new InvalidConfigurationException('Redis config is not set');
}
$redisConfig = $config['expressiveLogger']['handlers']['redis'];
$redisClient = $container->get($redisConfig['client']);
if (!$redisClient) {
throw new InvalidConfigurationException('Redis client not found in container');
}
if ($redisClient instanceof Client) {
throw new InvalidConfigurationException('Redis client have to be instance of Predis\Client');
}
$key = $redisConfig['key'] ?? 'default';
$level = $redisConfig['key'] ?? Logger::DEBUG;
return new RedisHandler($redisClient, $key, $level);
}
} |
Move broadcast test to use oauth | const { expect } = require('chai')
const nockHelper = require('./helpers/nock_helper')
const Hubspot = require('..')
describe('broadcasts', function() {
describe('get', function() {
before(nockHelper.mockOauthEndpoint('/broadcast/v1/broadcasts', []))
after(nockHelper.resetNock)
it('Should return details on a set of broadcast messages', function() {
const hubspot = new Hubspot({
accessToken: process.env.ACCESS_TOKEN || 'fake-token',
})
return hubspot.broadcasts
.get()
.then(data => expect(data).to.be.a('array'))
})
})
describe('get with a callback', function() {
before(nockHelper.mockOauthEndpoint('/broadcast/v1/broadcasts', []))
after(nockHelper.resetNock)
it('Should invoke the callback with the broadcasts', function() {
const hubspot = new Hubspot({
accessToken: process.env.ACCESS_TOKEN || 'fake-token',
})
let result
const fakeCallback = (_error, receivedValue) => (result = receivedValue)
return hubspot.broadcasts
.get(fakeCallback)
.then(() => expect(result).to.be.a('array'))
})
})
})
| const { expect } = require('chai')
const nockHelper = require('./helpers/nock_helper')
const Hubspot = require('..')
describe('broadcasts', function() {
describe('get', function() {
before(nockHelper.mockEndpoint('/broadcast/v1/broadcasts', []))
after(nockHelper.resetNock)
it('Should return details on a set of broadcast messages', function() {
const hubspot = new Hubspot({ apiKey: 'demo' })
return hubspot.broadcasts
.get()
.then(data => expect(data).to.be.a('array'))
})
})
describe('get with a callback', function() {
before(nockHelper.mockEndpoint('/broadcast/v1/broadcasts', []))
after(nockHelper.resetNock)
it('Should invoke the callback with the broadcasts', function() {
const hubspot = new Hubspot({ apiKey: 'demo' })
let result
const fakeCallback = (_error, receivedValue) => (result = receivedValue)
return hubspot.broadcasts
.get(fakeCallback)
.then(() => expect(result).to.be.a('array'))
})
})
})
|
Use cache factory to save questionnaire and return url on add new question | 'use strict';
angular.module('ngQuestionnaires.questionnaireNewController', [
'ng'
])
.controller('questionnaireNewController', [
'$scope',
'$cacheFactory',
'$location',
function ($scope, $cacheFactory, $location) {
$scope.action = 'New';
var questionnaire = $cacheFactory.get('data').get('questionnaire');
if (questionnaire !== undefined) {
$scope.questionnaire = questionnaire;
$cacheFactory.get('data').remove('questionnaire');
}
$scope.questions = $cacheFactory.get('data').get('questions');
$scope.addQuestion = function () {
$cacheFactory.get('data').put('questionnaire', $scope.questionnaire);
$cacheFactory.get('data').put('returnTo', $location.url());
$location.url('/questions/new');
};
}]); | 'use strict';
angular.module('ngQuestionnaires.questionnaireNewController', [
'ng'
])
.controller('questionnaireNewController', [
'$scope',
'$cacheFactory',
function ($scope, $cacheFactory) {
$scope.action = 'New';
$scope.questions = $cacheFactory.get('data').get('questions');
$scope.addQuestion = function () {
// store questionnaire inputs in cache service
// store return to new questionnaire in cache service
// navigate to new question form
// on save new question,
// persist state and check for return to value in cache service,
// then navigate there
// on cancel new question,
// check for return to value in cache service,
// then navigate there
// on returning to new questionnaire form,
// check cache service for questionnaire inputs and display them,
// then remove from cache service
};
}]); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.