text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Add function can now have the ' character | package seedu.scheduler.model.entry;
import seedu.scheduler.commons.exceptions.IllegalValueException;
/**
* Represents an Entry's name in the scheduler.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class Name {
public static final String MESSAGE_NAME_CONSTRAINTS = "Entry names should be spaces or alphanumeric characters";
//@@author A0126090N
public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum}\' ]+";
//@@author
public final String fullName;
/**
* Validates given name.
*
* @throws IllegalValueException if given name string is invalid.
*/
public Name(String name) throws IllegalValueException {
assert name != null;
name = name.trim();
if (!isValidName(name)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = name;
}
/**
* Returns true if a given string is a valid entry name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Name // instanceof handles nulls
&& this.fullName.equals(((Name) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
}
| package seedu.scheduler.model.entry;
import seedu.scheduler.commons.exceptions.IllegalValueException;
/**
* Represents an Entry's name in the scheduler.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class Name {
public static final String MESSAGE_NAME_CONSTRAINTS = "Entry names should be spaces or alphanumeric characters";
public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";
public final String fullName;
/**
* Validates given name.
*
* @throws IllegalValueException if given name string is invalid.
*/
public Name(String name) throws IllegalValueException {
assert name != null;
name = name.trim();
if (!isValidName(name)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = name;
}
/**
* Returns true if a given string is a valid entry name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Name // instanceof handles nulls
&& this.fullName.equals(((Name) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
}
|
GREEN: Test now uses correct value. | package de.itemis.mosig.racecar.tirepressure;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.junit.Assert.assertEquals;
public class AlarmTest {
private static final double PRESSURE_INTERVAL_LOWER_BOUND = 17d;
private Sensor mockedSensor;
private Alarm underTest;
@Before
public void setUp() {
mockedSensor = Mockito.mock(Sensor.class);
Mockito.when(mockedSensor.popNextPressurePsiValue()).thenCallRealMethod();
underTest = createUnderTest(mockedSensor);
}
@Test
public void alarmShouldBeOffAfterConstruction() {
assertEquals(false, underTest.isAlarmOn());
}
@Test
public void alarmShouldGoOffIfPressureIsBelowInterval() {
setupNextPressureValue(PRESSURE_INTERVAL_LOWER_BOUND - 1);
underTest.check();
assertEquals(true, underTest.isAlarmOn());
}
@Test
public void alarmShouldGoOffIfPressureIsAboveInterval() {
setupNextPressureValue(21 + 1);
underTest.check();
assertEquals(true, underTest.isAlarmOn());
}
/*
* #### start of private helper code ####
*/
private Alarm createUnderTest(Sensor sensor) {
return new Alarm(sensor);
}
private void setupNextPressureValue(double nextValue) {
Mockito.when(mockedSensor.popNextPressurePsiValue()).thenReturn(nextValue);
}
}
| package de.itemis.mosig.racecar.tirepressure;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.junit.Assert.assertEquals;
public class AlarmTest {
private static final double PRESSURE_INTERVAL_LOWER_BOUND = 17d;
private Sensor mockedSensor;
private Alarm underTest;
@Before
public void setUp() {
mockedSensor = Mockito.mock(Sensor.class);
Mockito.when(mockedSensor.popNextPressurePsiValue()).thenCallRealMethod();
underTest = createUnderTest(mockedSensor);
}
@Test
public void alarmShouldBeOffAfterConstruction() {
assertEquals(false, underTest.isAlarmOn());
}
@Test
public void alarmShouldGoOffIfPressureIsBelowInterval() {
setupNextPressureValue(PRESSURE_INTERVAL_LOWER_BOUND - 1);
underTest.check();
assertEquals(true, underTest.isAlarmOn());
}
@Test
public void alarmShouldGoOffIfPressureIsAboveInterval() {
setupNextPressureValue(21);
underTest.check();
assertEquals(true, underTest.isAlarmOn());
}
/*
* #### start of private helper code ####
*/
private Alarm createUnderTest(Sensor sensor) {
return new Alarm(sensor);
}
private void setupNextPressureValue(double nextValue) {
Mockito.when(mockedSensor.popNextPressurePsiValue()).thenReturn(nextValue);
}
}
|
Modify data source to HDFS | package com.parquet;
import com.richstonedt.nokia_api.peopleflow.Record;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.function.MapPartitionsFunction;
import org.apache.spark.sql.Encoder;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.SaveMode;
import org.apache.spark.sql.SparkSession;
import java.util.Iterator;
/**
* Created by yangpy on 2017/8/7.
*/
public class Test {
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.appName("Java Spark SQL basic example")
.config("spark.some.config.option", "some-value")
.master("local[4]")
.getOrCreate();
Encoder<Record> recordEncoder = Encoders.bean(Record.class);
spark.read().textFile("/highway/demodata/parquet/data.json")
.mapPartitions(new MapPartitionsFunction<String, Record>() {
@Override
public Iterator<Record> call(Iterator<String> iterator) throws Exception {
return null;
}
}, recordEncoder)
.write()
.mode(SaveMode.Overwrite)
.parquet("abc.parquet");
}
}
| package com.parquet;
import com.richstonedt.nokia_api.peopleflow.Record;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.function.MapPartitionsFunction;
import org.apache.spark.sql.Encoder;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.SaveMode;
import org.apache.spark.sql.SparkSession;
import java.util.Iterator;
/**
* Created by yangpy on 2017/8/7.
*/
public class Test {
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.appName("Java Spark SQL basic example")
.config("spark.some.config.option", "some-value")
.master("local[4]")
.getOrCreate();
Encoder<Record> recordEncoder = Encoders.bean(Record.class);
spark.read().textFile("D:\\data.json")
.mapPartitions(new MapPartitionsFunction<String, Record>() {
@Override
public Iterator<Record> call(Iterator<String> iterator) throws Exception {
return null;
}
}, recordEncoder)
.write()
.mode(SaveMode.Overwrite)
.parquet("abc.parquet");
}
}
|
Save taxon root at end | <?php
namespace Tests\SitemapPlugin\Controller;
use Lakion\ApiTestCase\XmlApiTestCase;
use Sylius\Component\Core\Model\Product;
use Sylius\Component\Core\Model\Taxon;
/**
* @author Stefan Doorn <[email protected]>
*/
class SitemapTaxonControllerApiTest extends XmlApiTestCase
{
/**
* @before
*/
public function setUpDatabase()
{
parent::setUpDatabase();
$root = new Taxon();
$root->setCurrentLocale('en_US');
$root->setName('Root');
$root->setCode('root');
$root->setSlug('root');
$taxon = new Taxon();
$taxon->setCurrentLocale('en_US');
$taxon->setName('Test');
$taxon->setCode('test-code');
$taxon->setSlug('test');
$taxon->setParent($root);
$this->getEntityManager()->persist($taxon);
$taxon = new Taxon();
$taxon->setCurrentLocale('en_US');
$taxon->setName('Mock');
$taxon->setCode('mock-code');
$taxon->setSlug('mock');
$taxon->setParent($root);
$this->getEntityManager()->persist($taxon);
$this->getEntityManager()->persist($root);
$this->getEntityManager()->flush();
}
public function testShowActionResponse()
{
$this->client->request('GET', '/sitemap/taxons.xml');
$response = $this->client->getResponse();
$this->assertResponse($response, 'show_sitemap_taxons');
}
}
| <?php
namespace Tests\SitemapPlugin\Controller;
use Lakion\ApiTestCase\XmlApiTestCase;
use Sylius\Component\Core\Model\Product;
use Sylius\Component\Core\Model\Taxon;
/**
* @author Stefan Doorn <[email protected]>
*/
class SitemapTaxonControllerApiTest extends XmlApiTestCase
{
/**
* @before
*/
public function setUpDatabase()
{
parent::setUpDatabase();
$root = new Taxon();
$root->setCurrentLocale('en_US');
$root->setName('Root');
$root->setCode('root');
$root->setSlug('root');
$this->getEntityManager()->persist($root);
$taxon = new Taxon();
$taxon->setCurrentLocale('en_US');
$taxon->setName('Test');
$taxon->setCode('test-code');
$taxon->setSlug('test');
$taxon->setParent($root);
$this->getEntityManager()->persist($taxon);
$taxon = new Taxon();
$taxon->setCurrentLocale('en_US');
$taxon->setName('Mock');
$taxon->setCode('mock-code');
$taxon->setSlug('mock');
$taxon->setParent($root);
$this->getEntityManager()->persist($taxon);
$this->getEntityManager()->flush();
}
public function testShowActionResponse()
{
$this->client->request('GET', '/sitemap/taxons.xml');
$response = $this->client->getResponse();
$this->assertResponse($response, 'show_sitemap_taxons');
}
}
|
Fix the token request and log level | <?php
namespace APIBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use APIBundle\Entity\Exercise;
use APIBundle\Form\Type\EventType;
use APIBundle\Entity\Event;
class InjectTypeController extends Controller
{
public static $INJECT_TYPE_MANUAL = 'openex_manual';
/**
* @ApiDoc(
* description="List inject types"
* )
* @Rest\Get("/inject_types")
*/
public function getInjectTypesAction(Request $request)
{
$logger = $this->get('logger');
$contracts = array();
try {
$url = $this->getParameter('worker_url') . '/cxf/contracts';
$contracts = json_decode(file_get_contents($url), true);
} catch (\Exception $e) {
$logger->error('Contracts can not be retrieved from worker: ' . $e->getMessage());
}
$other = array();
$other['type'] = self::$INJECT_TYPE_MANUAL;
$other['fields'] = array();
$other['fields'][] = array(
'name' => 'content',
'type' => 'textarea',
'cardinality' => '1',
'mandatory' => true,
);
$contracts[] = $other;
$output = json_encode($contracts);
return new Response($output);
}
} | <?php
namespace APIBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use APIBundle\Entity\Exercise;
use APIBundle\Form\Type\EventType;
use APIBundle\Entity\Event;
class InjectTypeController extends Controller
{
public static $INJECT_TYPE_MANUAL = 'openex_manual';
/**
* @ApiDoc(
* description="List inject types"
* )
* @Rest\Get("/inject_types")
*/
public function getInjectTypesAction(Request $request)
{
$logger = $this->get('logger');
$contracts = array();
try {
$url = $this->getParameter('worker_url') . '/cxf/contracts';
$contracts = json_decode(file_get_contents($url), true);
} catch (\Exception $e) {
$logger->error('Contracts can not be retrieved from worker');
}
$other = array();
$other['type'] = self::$INJECT_TYPE_MANUAL;
$other['fields'] = array();
$other['fields'][] = array(
'name' => 'content',
'type' => 'textarea',
'cardinality' => '1',
'mandatory' => true,
);
$contracts[] = $other;
$output = json_encode($contracts);
return new Response($output);
}
} |
:no_entry: Stop page repositioning after using my location | (function (global) {
'use strict';
var $ = global.jQuery;
var $geoLocate = $('.geo-locate');
var $geoLocateDenied = $('.geo-locate--denied');
var $geoLocateError = $('.geo-locate--error');
var $geoLocateLocate = $('.geo-locate--locate');
var $geoLocateSearching = $('.geo-locate--searching');
var window = global;
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
if (latitude && longitude) {
var locationDescription = 'your location';
var location = './results?location=' + encodeURIComponent(locationDescription) + '&latitude=' + latitude + '&longitude=' + longitude;
// load the results page
window.location = location;
} else {
error();
}
}
function error(e) {
switch(e.code) {
case e.PERMISSION_DENIED:
$geoLocate.hide();
$geoLocateDenied.show();
break;
case e.POSITION_UNAVAILABLE:
$geoLocateError.show();
break;
case e.TIMEOUT:
$geoLocateError.show();
break;
}
$geoLocateSearching.hide();
}
if (navigator.geolocation) {
$geoLocate.show();
$geoLocateLocate.on('click', function(e) {
$geoLocateError.hide();
navigator.geolocation.getCurrentPosition(success, error);
$geoLocateSearching.show();
e.preventDefault();
});
}
})(window);
| (function (global) {
'use strict';
var $ = global.jQuery;
var $geoLocate = $('.geo-locate');
var $geoLocateDenied = $('.geo-locate--denied');
var $geoLocateError = $('.geo-locate--error');
var $geoLocateLocate = $('.geo-locate--locate');
var $geoLocateSearching = $('.geo-locate--searching');
var window = global;
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
if (latitude && longitude) {
var locationDescription = 'your location';
var location = './results?location=' + encodeURIComponent(locationDescription) + '&latitude=' + latitude + '&longitude=' + longitude;
// load the results page
window.location = location;
} else {
error();
}
}
function error(e) {
switch(e.code) {
case e.PERMISSION_DENIED:
$geoLocate.hide();
$geoLocateDenied.show();
break;
case e.POSITION_UNAVAILABLE:
$geoLocateError.show();
break;
case e.TIMEOUT:
$geoLocateError.show();
break;
}
$geoLocateSearching.hide();
}
if (navigator.geolocation) {
$geoLocate.show();
$geoLocateLocate.on('click', function() {
$geoLocateError.hide();
navigator.geolocation.getCurrentPosition(success, error);
$geoLocateSearching.show();
});
}
})(window);
|
Copy entrypoint config to new app/config/ | <?php
/**
* @package jelix
* @subpackage jsoap module
* @author Laurent Jouanneau
* @contributor
* @copyright 2009-2015 Laurent Jouanneau
* @link http://www.jelix.org
* @licence GNU Lesser General Public Licence see LICENCE file or http://www.gnu.org/licenses/lgpl.html
*/
class jsoapModuleInstaller extends jInstallerModule {
function install() {
// configure the entry point
$entrypoint = $this->getParameter('entrypoint');
if (!$entrypoint) {
$entrypoint = 'soap';
}
if (!file_exists(jApp::wwwPath($entrypoint.'.php'))) {
$this->copyFile('files/soap.php', jApp::wwwPath($entrypoint.'.php'));
}
// setup the configuration
if (!file_exists(jApp::appConfigPath($entrypoint.'/config.ini.php'))) {
$this->copyFile('files/config.ini.php', jApp::appConfigPath($entrypoint.'/config.ini.php'));
}
if ($this->entryPoint->getMainConfigIni()->getValue('soap', 'responses') === null) {
$this->entryPoint->getMainConfigIni()->setValue('soap', "jsoap~jResponseSoap", "responses");
}
$this->declareNewEntryPoint($entrypoint, 'soap', $entrypoint.'/config.ini.php');
}
} | <?php
/**
* @package jelix
* @subpackage jsoap module
* @author Laurent Jouanneau
* @contributor
* @copyright 2009-2015 Laurent Jouanneau
* @link http://www.jelix.org
* @licence GNU Lesser General Public Licence see LICENCE file or http://www.gnu.org/licenses/lgpl.html
*/
class jsoapModuleInstaller extends jInstallerModule {
function install() {
// configure the entry point
$entrypoint = $this->getParameter('entrypoint');
if (!$entrypoint) {
$entrypoint = 'soap';
}
if (!file_exists(jApp::wwwPath($entrypoint.'.php'))) {
$this->copyFile('files/soap.php', jApp::wwwPath($entrypoint.'.php'));
}
// setup the configuration
if (!file_exists(jApp::configPath($entrypoint.'/config.ini.php'))) {
$this->copyFile('files/config.ini.php', jApp::configPath($entrypoint.'/config.ini.php'));
}
if ($this->entryPoint->getMainConfigIni()->getValue('soap', 'responses') === null) {
$this->entryPoint->getMainConfigIni()->setValue('soap', "jsoap~jResponseSoap", "responses");
}
$this->declareNewEntryPoint($entrypoint, 'soap', $entrypoint.'/config.ini.php');
}
} |
Delete button issue now fixed | import React from "react";
import { Button, Popup, Input, Header, Divider } from 'semantic-ui-react';
export default class DayEditBox extends React.Component {
render(){
var myId = "dayedit-" + this.props.id + "-text";
var content = (
<div>
<Input focus placeholder={this.props.fillerText} id={myId}/>
<Divider/>
<Popup
trigger={<Button negative>Delete</Button>}
content={
<div>
<Header as="h1">Hey there!</Header>
<p>Deleting the day will also delete any cells in the day.</p>
<Button negative onClick={this.props.onDelete}>I understand. Delete it!</Button>
</div>
}
on="click"
/>
<Button
positive
onClick={
(event, data) => {
this.props.onClick(event, data, myId);
}
}
>
Save
</Button>
</div>
);
return(
<Popup
trigger={this.props.trigger}
content={content}
on="click"
header="Edit Day"
/>
);
}
} | import React from "react";
import { Button, Popup, Input, Heading, Divider } from 'semantic-ui-react';
export default class DayEditBox extends React.Component {
render(){
var myId = "dayedit-" + this.props.id + "-text";
var content = (
<div>
<Input focus placeholder={this.props.fillerText} id={myId}/>
<Divider/>
<Popup
trigger={<Button negative>Delete</Button>}
content={
<div>
<Heading as="h1">Hey there!</Heading>
<p>Deleting the day will also delete any cells in the day.</p>
<Button negative onClick={this.props.onDelete}>I understand. Delete it!</Button>
</div>
}
on="click"
/>
<Button
positive
onClick={
(event, data) => {
this.props.onClick(event, data, myId);
}
}
>
Save
</Button>
</div>
);
return(
<Popup
trigger={this.props.trigger}
content={content}
on="click"
header="Edit Day"
/>
);
}
} |
Return 404 not found if user or research entity doesn't exist when getting the profile image | /**
* TagLabelController
*
* @description :: Server-side logic for managing Journals
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
const path = require('path');
const fs = require('fs');
module.exports = {
getProfileImage: async function (req, res, next) {
const username = req.params.username;
const user = await User.findOne({username});
if (!user || (user && !_.has(user, 'researchEntity'))) {
return res.notFound({
message: 'User not found!'
});
}
const data = await UserData.findOne({researchEntity: user.researchEntity});
if (!_.has(data, 'profile')) {
return res.notFound({
message: 'Profile not found!'
});
}
const profile = data.profile;
if (_.has(profile, 'hidden.value') && profile.hidden.value) {
return res.forbidden({
message: 'This profile is not public!'
});
}
if (_.has(profile, 'image.privacy') && profile.image.privacy !== 'public') {
return res.forbidden({
message: 'This image is not public!'
});
}
const image = await UserData.getProfileImage(user, profile);
if (image) {
const imagePath = path.join(sails.config.appPath, image);
const stream = fs.createReadStream(imagePath);
stream.pipe(res)
} else {
return res.notFound({
message: 'Image not found!'
});
}
}
}; | /**
* TagLabelController
*
* @description :: Server-side logic for managing Journals
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
const path = require('path');
const fs = require('fs');
module.exports = {
getProfileImage: async function (req, res, next) {
const username = req.params.username;
const user = await User.findOne({username});
const data = await UserData.findOne({researchEntity: user.researchEntity});
if (!_.has(data, 'profile')) {
return res.notFound({
message: 'Profile not found!'
});
}
const profile = data.profile;
if (_.has(profile, 'hidden.value') && profile.hidden.value) {
return res.forbidden({
message: 'This profile is not public!'
});
}
if (_.has(profile, 'image.privacy') && profile.image.privacy !== 'public') {
return res.forbidden({
message: 'This image is not public!'
});
}
const image = await UserData.getProfileImage(user, profile);
if (image) {
const imagePath = path.join(sails.config.appPath, image);
const stream = fs.createReadStream(imagePath);
stream.pipe(res)
} else {
return res.notFound({
message: 'Image not found!'
});
}
}
}; |
Add a bit more JavaDoc | package org.dstadler.commoncrawl;
/**
* Which extensions we are interested in.
*
* If you want to change which files are downloaded, just can
* set a different list of file-extensions here, e.g.
*
* <pre>
".pdf"
</pre>
*
* would find and download PDF documents.
*/
public class Extensions {
private static final String[] EXTENSIONS = new String[] {
// Excel
".xls",
".xlsx",
".xlsm",
".xltx",
".xlsb",
// Word
".doc",
".docx",
".dotx",
".docm",
".ooxml",
// Powerpoint
".ppt",
".pot",
".pptx",
".pptm",
".ppsm",
".ppsx",
".thmx",
".potx",
// Outlook
".msg",
// Publisher
".pub",
// Visio - binary
".vsd",
".vss",
".vst",
".vsw",
// Visio - ooxml (currently unsupported)
".vsdm",
".vsdx",
".vssm",
".vssx",
".vstm",
".vstx",
// POIFS
".ole2",
// Microsoft Admin Template?
".adm",
// Microsoft TNEF
// ".dat", new HMEFFileHandler());
};
public static boolean matches(String url) {
for(String ext : EXTENSIONS) {
if(url.endsWith(ext)) {
return true;
}
}
return false;
}
}
| package org.dstadler.commoncrawl;
/**
* Which extensions we are interested in.
*
* @author dominik.stadler
*/
public class Extensions {
private static final String[] EXTENSIONS = new String[] {
// Excel
".xls",
".xlsx",
".xlsm",
".xltx",
".xlsb",
// Word
".doc",
".docx",
".dotx",
".docm",
".ooxml",
// Powerpoint
".ppt",
".pot",
".pptx",
".pptm",
".ppsm",
".ppsx",
".thmx",
".potx",
// Outlook
".msg",
// Publisher
".pub",
// Visio - binary
".vsd",
".vss",
".vst",
".vsw",
// Visio - ooxml (currently unsupported)
".vsdm",
".vsdx",
".vssm",
".vssx",
".vstm",
".vstx",
// POIFS
".ole2",
// Microsoft Admin Template?
".adm",
// Microsoft TNEF
// ".dat", new HMEFFileHandler());
};
public static boolean matches(String url) {
for(String ext : EXTENSIONS) {
if(url.endsWith(ext)) {
return true;
}
}
return false;
}
}
|
Install ember-sinon as an addon. | /* globals module */
var EOL = require('os').EOL;
module.exports = {
description: 'Register test helpers',
afterInstall: function( options ) {
// Import statement
var firstFile = 'tests/helpers/start-app.js';
var firstText = "import slRegisterTestHelpers from './sl/register-test-helpers';";
var firstLocationText = "import Ember from 'ember';" + EOL;
// Execution of registration function
var secondFile = 'tests/helpers/start-app.js';
var secondText = " slRegisterTestHelpers();";
var secondLocationText = "application.setupForTesting();" + EOL;
// .jshintrc file
var thirdFile = 'tests/.jshintrc';
var thirdText = ' "contains",' + EOL + ' "requires",';
var thirdLocationText = '"predef": [' + EOL;
return this.insertIntoFile( firstFile, firstText, { after: firstLocationText } )
// Execution of registration function
.then( () => {
return this.insertIntoFile( secondFile, secondText, { after: secondLocationText } );
})
.then( () => {
return this.insertIntoFile( thirdFile, thirdText, { after: thirdLocationText } );
})
.then( () => {
return this.addAddonToProject( 'ember-sinon' );
});
},
normalizeEntityName: function() {}
};
| /* globals module */
var EOL = require('os').EOL;
module.exports = {
description: 'Register test helpers',
afterInstall: function( options ) {
// Import statement
var firstFile = 'tests/helpers/start-app.js';
var firstText = "import slRegisterTestHelpers from './sl/register-test-helpers';";
var firstLocationText = "import Ember from 'ember';" + EOL;
// Execution of registration function
var secondFile = 'tests/helpers/start-app.js';
var secondText = " slRegisterTestHelpers();";
var secondLocationText = "application.setupForTesting();" + EOL;
// .jshintrc file
var thirdFile = 'tests/.jshintrc';
var thirdText = ' "contains",' + EOL + ' "requires",';
var thirdLocationText = '"predef": [' + EOL;
// Import statement
return this.insertIntoFile( firstFile, firstText, { after: firstLocationText } )
// Execution of registration function
.then( function() {
return this.insertIntoFile( secondFile, secondText, { after: secondLocationText } );
}.bind(this))
// .jshintrc file
.then( function() {
return this.insertIntoFile( thirdFile, thirdText, { after: thirdLocationText } );
}.bind(this));
},
normalizeEntityName: function() {}
};
|
Fix: Use headless Chrome for Angular tests again. | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('karma-mocha-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['kjhtml', 'mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false,
customLaunchers: {
ChromeHeadlessForDocker: {
base: 'ChromeHeadless',
flags: [
'--disable-web-security',
'--disable-gpu',
'--no-sandbox'
],
displayName: 'Chrome Headless for docker'
}
},
browsers: ['ChromeHeadlessForDocker']
});
};
| // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('karma-mocha-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['kjhtml', 'mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false,
customLaunchers: {
ChromeHeadlessForDocker: {
base: 'ChromeHeadless',
flags: [
'--disable-web-security',
'--disable-gpu',
'--no-sandbox'
],
displayName: 'Chrome Headless for docker'
}
},
browsers: ['Chrome']
});
};
|
Convert Hamburger component to stateless function | import React from 'react';
import styled from 'styled-components';
import theme from 'theme';
const StyledHamburger = styled.div`
position: relative;
width: 15px;
height: 13px;
`;
export const Bar = styled.div`
position: absolute;
height: 3px;
background: ${theme.black};
overflow: hidden;
&::after {
content: '';
display: block;
width: 100%;
height: 100%;
background: ${theme.gray};
position: absolute;
top: 0;
left: 100%;
z-index: 1;
transition: all .3s ease-in-out;
}
&:nth-child(1) {
top: 0;
width: 9px;
&::after {
transition-delay: .1s;
}
}
&:nth-child(2) {
top: 5px;
width: 15px;
&::after {
transition-delay: .2s;
}
}
&:nth-child(3) {
top: 10px;
width: 12px;
&::after {
transition-delay: .3s;
}
}
`;
const Hamburger = () => (
<StyledHamburger>
<Bar />
<Bar />
<Bar />
</StyledHamburger>
);
export default Hamburger;
| import React from 'react';
import styled from 'styled-components';
import theme from 'theme';
const StyledHamburger = styled.div`
position: relative;
width: 15px;
height: 13px;
`;
export const Bar = styled.div`
position: absolute;
height: 3px;
background: ${theme.black};
overflow: hidden;
&::after {
content: '';
display: block;
width: 100%;
height: 100%;
background: ${theme.gray};
position: absolute;
top: 0;
left: 100%;
z-index: 1;
transition: all .3s ease-in-out;
}
&:nth-child(1) {
top: 0;
width: 9px;
&::after {
transition-delay: .1s;
}
}
&:nth-child(2) {
top: 5px;
width: 15px;
&::after {
transition-delay: .2s;
}
}
&:nth-child(3) {
top: 10px;
width: 12px;
&::after {
transition-delay: .3s;
}
}
`;
class Hamburger extends React.PureComponent {
render() {
return (
<StyledHamburger>
<Bar />
<Bar />
<Bar />
</StyledHamburger>
);
}
}
export default Hamburger;
|
Add predicate to check CSRF token | from pyramid.view import (
view_config,
view_defaults,
)
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import (
remember,
forget,
)
@view_defaults(accept='application/json', renderer='json', context='..traversal.User')
class User(object):
def __init__(self, context, request):
self.request = request
self.context = context
@view_config()
def info(self):
if self.request.authenticated_userid is None:
ret = {
'authenticated': False,
}
else:
ret = {
'authenticated': True,
'user': {
'username': '[email protected]',
}
}
return ret
@view_config(name='login', check_csrf=True, request_method='POST')
def login(self):
if self.request.body:
print(self.request.json_body)
headers = remember(self.request, "[email protected]")
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
return {}
@view_config(name='logout', check_csrf=True, request_method='POST')
def logout(self):
headers = forget(self.request)
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
| from pyramid.view import (
view_config,
view_defaults,
)
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import (
remember,
forget,
)
@view_defaults(accept='application/json', renderer='json', context='..traversal.User')
class User(object):
def __init__(self, context, request):
self.request = request
self.context = context
@view_config()
def info(self):
if self.request.authenticated_userid is None:
ret = {
'authenticated': False,
}
else:
ret = {
'authenticated': True,
'user': {
'username': '[email protected]',
}
}
return ret
@view_config(name='login')
def login(self):
if self.request.body:
print(self.request.json_body)
headers = remember(self.request, "[email protected]")
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
return {}
@view_config(name='logout')
def logout(self):
headers = forget(self.request)
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
|
Check when session is null | /* global SolidAuthClient, SolidUtils, $rdf */
TweeFiUtils = {
TweetUri: class {
constructor(value) {
// Regex-pattern to check URLs against:
// https://twitter.com/<twitteruser>/status/<long number>
var urlRegex = /^https:\/\/twitter.com\/([a-zA-Z _.,!"'/$]+)\/status\/([0-9]*$)/;
this.match = urlRegex.exec(value);
this.value = value;
}
isValid() {
return this.match !== null;
}
getUser() {
return this.match[1];
}
getStatus() {
return this.match[2];
}
toString() {
return this.value;
}
},
updateLoginInfo() {
SolidAuthClient.currentSession().then(function (session) {
if (session) {
var user = $rdf.sym(session.webId);
SolidUtils.rdfFetch(session.webId).then(function (response) {
var name = response.graph.any(user, SolidUtils.vocab.foaf('name'));
$("#loginInfo").html("Logged in as:");
$("#loginName").html("<a class='nav-link' href='" + session.webId + "'>" + name + "</a>");
});
} else {
$("#loginInfo").html("Not logged in");
}
});
}
} | /* global SolidAuthClient, SolidUtils, $rdf */
TweeFiUtils = {
TweetUri: class {
constructor(value) {
// Regex-pattern to check URLs against:
// https://twitter.com/<twitteruser>/status/<long number>
var urlRegex = /^https:\/\/twitter.com\/([a-zA-Z _.,!"'/$]+)\/status\/([0-9]*$)/;
this.match = urlRegex.exec(value);
this.value = value;
}
isValid() {
return this.match !== null;
}
getUser() {
return this.match[1];
}
getStatus() {
return this.match[2];
}
toString() {
return this.value;
}
},
updateLoginInfo() {
SolidAuthClient.currentSession().then(function (session) {
var user = $rdf.sym(session.webId);
SolidUtils.rdfFetch(session.webId).then(function (response) {
var name = response.graph.any(user, SolidUtils.vocab.foaf('name'));
$("#loginInfo").html("Logged in as:");
$("#loginName").html("<a class='nav-link' href='" + session.webId + "'>" + name + "</a>");
});
});
}
} |
Fix filter bug on empty value | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Filter\ORM;
use Symfony\Component\Form\FormFactory;
use Doctrine\ORM\QueryBuilder;
class ChoiceFilter extends Filter
{
public function filter($queryBuilder, $alias, $field, $value)
{
if ($this->getField()->getAttribute('multiple')) {
if (!is_array($value) || count($value) == 0) {
return;
}
if (in_array('all', $value)) {
return;
}
$queryBuilder->andWhere($queryBuilder->expr()->in(sprintf('%s.%s',
$alias,
$field
), $value));
} else {
if (empty($value) || $value == 'all') {
return;
}
$queryBuilder->andWhere(sprintf('%s.%s = :%s',
$alias,
$field,
$this->getName()
));
$queryBuilder->setParameter($this->getName(), $value);
}
}
public function defineFieldBuilder(FormFactory $formFactory, $value = null)
{
$options = $this->getFieldDescription()->getOption('filter_field_options', array('required' => false));
$this->field = $formFactory->createNamedBuilder('choice', $this->getName(), $value, $options)->getForm();
}
} | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Filter\ORM;
use Symfony\Component\Form\FormFactory;
use Doctrine\ORM\QueryBuilder;
class ChoiceFilter extends Filter
{
public function filter($queryBuilder, $alias, $field, $value)
{
if ($this->getField()->getAttribute('multiple')) {
if (!is_array($value) || count($value) == 0) {
return;
}
if (in_array('all', $value)) {
return;
}
$queryBuilder->andWhere($queryBuilder->expr()->in(sprintf('%s.%s',
$alias,
$field
), $value));
} else {
if ($value === null || $value == 'all') {
return;
}
$queryBuilder->andWhere(sprintf('%s.%s = :%s',
$alias,
$field,
$this->getName()
));
$queryBuilder->setParameter($this->getName(), $value);
}
}
public function defineFieldBuilder(FormFactory $formFactory, $value = null)
{
$options = $this->getFieldDescription()->getOption('filter_field_options', array('required' => false));
$this->field = $formFactory->createNamedBuilder('choice', $this->getName(), $value, $options)->getForm();
}
} |
[Guice] Remove use of deprecated constants | package io.cucumber.guice;
import com.google.inject.Guice;
import com.google.inject.Stage;
import java.util.Map;
import static java.text.MessageFormat.format;
final class InjectorSourceFactory {
static final String GUICE_INJECTOR_SOURCE_KEY = "guice.injector-source";
private final Map<String, String> properties;
InjectorSourceFactory(Map<String, String> properties) {
this.properties = properties;
}
InjectorSource create() {
String injectorSourceClassName = properties.get(GUICE_INJECTOR_SOURCE_KEY);
if (injectorSourceClassName == null) {
return createDefaultScenarioModuleInjectorSource();
} else {
return instantiateUserSpecifiedInjectorSource(injectorSourceClassName);
}
}
private InjectorSource createDefaultScenarioModuleInjectorSource() {
return () -> Guice.createInjector(Stage.PRODUCTION, CucumberModules.createScenarioModule());
}
private InjectorSource instantiateUserSpecifiedInjectorSource(String injectorSourceClassName) {
try {
return (InjectorSource) Class.forName(injectorSourceClassName, true, Thread.currentThread().getContextClassLoader()).newInstance();
} catch (Exception e) {
String message = format("Instantiation of ''{0}'' failed. Check the caused by exception and ensure your" +
"InjectorSource implementation is accessible and has a public zero args constructor.",
injectorSourceClassName);
throw new InjectorSourceInstantiationFailed(message, e);
}
}
} | package io.cucumber.guice;
import com.google.inject.Guice;
import com.google.inject.Stage;
import java.util.Map;
import static java.text.MessageFormat.format;
final class InjectorSourceFactory {
static final String GUICE_INJECTOR_SOURCE_KEY = "guice.injector-source";
private final Map<String, String> properties;
InjectorSourceFactory(Map<String, String> properties) {
this.properties = properties;
}
InjectorSource create() {
String injectorSourceClassName = properties.get(GUICE_INJECTOR_SOURCE_KEY);
if (injectorSourceClassName == null) {
return createDefaultScenarioModuleInjectorSource();
} else {
return instantiateUserSpecifiedInjectorSource(injectorSourceClassName);
}
}
private InjectorSource createDefaultScenarioModuleInjectorSource() {
return () -> Guice.createInjector(Stage.PRODUCTION, CucumberModules.SCENARIO);
}
private InjectorSource instantiateUserSpecifiedInjectorSource(String injectorSourceClassName) {
try {
return (InjectorSource) Class.forName(injectorSourceClassName, true, Thread.currentThread().getContextClassLoader()).newInstance();
} catch (Exception e) {
String message = format("Instantiation of ''{0}'' failed. Check the caused by exception and ensure your" +
"InjectorSource implementation is accessible and has a public zero args constructor.",
injectorSourceClassName);
throw new InjectorSourceInstantiationFailed(message, e);
}
}
} |
FIX moved bio script to misc.bio_utils | from setuptools import setup
console_scripts = [
'extract-metagene-profiles=riboutils.extract_metagene_profiles:main',
'estimate-metagene-profile-bayes-factors=riboutils.estimate_metagene_profile_bayes_factors:main',
'select-periodic-offsets=riboutils.select_periodic_offsets:main'
]
def readme():
with open('README.md') as f:
return f.read()
setup(name='riboutils',
version='0.1',
description="This package contains utilities for other ribosome profiling projects.",
long_description=readme(),
keywords="ribosome profiling utilities translation",
url="",
author="Brandon Malone",
author_email="[email protected]",
license='MIT',
packages=['riboutils'],
install_requires = [
'numpy',
'pandas',
'scipy',
'tqdm',
'appdirs',
'statsmodels',
'misc[bio]'
],
extras_require = {
},
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose'],
entry_points = {
'console_scripts': console_scripts
},
zip_safe=False
)
| from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(name='riboutils',
version='0.1',
description="This package contains utilities for other ribosome profiling projects.",
long_description=readme(),
keywords="ribosome profiling utilities translation",
url="",
author="Brandon Malone",
author_email="[email protected]",
license='MIT',
packages=['riboutils'],
install_requires = [
'numpy',
'pandas',
'scipy',
'tqdm',
'appdirs',
'statsmodels',
'misc[bio]'
],
extras_require = {
},
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose'],
entry_points = {
'console_scripts': [
'extract-metagene-profiles=riboutils.extract_metagene_profiles:main',
'estimate-metagene-profile-bayes-factors=riboutils.estimate_metagene_profile_bayes_factors:main',
'select-periodic-offsets=riboutils.select_periodic_offsets:main'
]
},
zip_safe=False
)
|
Add "use strict" + code cleanup | "use strict";
var argv = require("optimist")
.boolean(['fetchtags'])
.default('url', 'http://downloads.vagrantup.com')
.default('file', 'checksums.json')
.default('tag', 'v1.3.3')
.default('tagpath', '/tags/')
.argv;
var request = require("request")
, cheerio = require("cheerio")
, crypto = require("crypto")
, fs = require("fs");
// This will pull all the available tags from the
// vagrantup downloads site
function get_tags(url) {
request(url, function(err, resp, body) {
var t = [];
if (err)
throw err;
var $ = cheerio.load(body);
//console.log(body);
$('a.tag').each(function(tag) {
//console.log(tag);
get_package_info(url + '/tags/', $(this).text());
t.push($(this).text());
//console.log(tags);
});
console.log(t);
});
};
function get_package_info(url, tag){
request(url + tag, function(err, resp, body) {
var $ = cheerio.load(body);
$('a.file').each( function(file) {
console.log($(this).attr('href'));
});
});
};
if (argv.fetchtags) {
get_tags(argv.url);
} else {
get_package_info(argv.url + argv.tagpath , argv.tag);
}
| var argv = require("optimist")
.boolean(['fetchtags'])
.default('url', 'http://downloads.vagrantup.com')
.default('file', 'checksums.json')
.default('tag', 'v1.3.3')
.default('tagpath', '/tags/')
.argv;
var request = require("request")
, cheerio = require("cheerio")
, crypto = require("crypto")
, fs = require("fs");
// This will pull all the available tags from the
// vagrantup downloads site
function get_tags(url) {
request(url, function(err, resp, body) {
var t = [];
if (err)
throw err;
$ = cheerio.load(body);
//console.log(body);
$('a.tag').each(function(tag) {
//console.log(tag);
get_package_info(url + '/tags/', $(this).text());
t.push($(this).text());
//console.log(tags);
});
console.log(t);
});
};
function get_package_info(url, tag){
u = url + tag;
console.log(u);
request(url + tag, function(err, resp, body) {
$ = cheerio.load(body);
$('a.file').each( function(file) {
console.log($(this).attr('href'));
});
});
};
if (argv.fetchtags) {
get_tags(argv.url);
} else
{
get_package_info(argv.url + argv.tagpath , argv.tag);
}
|
Fix logic for validating viewBox prop | const meetOrSliceTypes = {
meet: 0,
slice: 1,
none: 2,
};
const alignEnum = [
"xMinYMin",
"xMidYMin",
"xMaxYMin",
"xMinYMid",
"xMidYMid",
"xMaxYMid",
"xMinYMax",
"xMidYMax",
"xMaxYMax",
"none",
].reduce((prev, name) => {
prev[name] = name;
return prev;
}, {});
const spacesRegExp = /\s+/;
export default function(props) {
const { viewBox, preserveAspectRatio } = props;
if (!viewBox) {
return null;
}
const params = viewBox.trim().split(spacesRegExp);
if (params.length === 4 && params.some(param => isNaN(+param))) {
console.warn("Invalid `viewBox` prop:" + viewBox);
return null;
}
const modes = preserveAspectRatio
? preserveAspectRatio.trim().split(spacesRegExp)
: [];
const meetOrSlice = meetOrSliceTypes[modes[1]] || 0;
const align = alignEnum[modes[0]] || "xMidYMid";
return {
minX: +params[0],
minY: +params[1],
vbWidth: +params[2],
vbHeight: +params[3],
align,
meetOrSlice,
};
}
export { meetOrSliceTypes, alignEnum };
| const meetOrSliceTypes = {
meet: 0,
slice: 1,
none: 2,
};
const alignEnum = [
"xMinYMin",
"xMidYMin",
"xMaxYMin",
"xMinYMid",
"xMidYMid",
"xMaxYMid",
"xMinYMax",
"xMidYMax",
"xMaxYMax",
"none",
].reduce((prev, name) => {
prev[name] = name;
return prev;
}, {});
const spacesRegExp = /\s+/;
export default function(props) {
const { viewBox, preserveAspectRatio } = props;
if (!viewBox) {
return null;
}
const params = viewBox.trim().split(spacesRegExp);
if (params.length === 4 && params.every(param => !isNaN(+param))) {
console.warn("Invalid `viewBox` prop:" + viewBox);
return null;
}
const modes = preserveAspectRatio
? preserveAspectRatio.trim().split(spacesRegExp)
: [];
const meetOrSlice = meetOrSliceTypes[modes[1]] || 0;
const align = alignEnum[modes[0]] || "xMidYMid";
return {
minX: +params[0],
minY: +params[1],
vbWidth: +params[2],
vbHeight: +params[3],
align,
meetOrSlice,
};
}
export { meetOrSliceTypes, alignEnum };
|
Add a reset button into the search section.
:) | <?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\CttStaticdataLanguagesSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="ctt-staticdata-languages-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
'layout' => 'horizontal',
'fieldConfig' => [
'template' => "{label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
'horizontalCssClasses' => [
'offset' => '',
'label' => 'col-md-3',
'wrapper' => 'col-md-5',
'error' => '',
'hint' => '',
],
]
]); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'short_name') ?>
<div class="form-group">
<div class="col-md-offset-3 col-md-9">
<?= Html::submitButton(Yii::t('app/frontend', 'Search'), ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app/fronted', 'Reset'),
Url::to(['index']),
['class' => 'btn btn-danger']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
| <?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\CttStaticdataLanguagesSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="ctt-staticdata-languages-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
'layout' => 'horizontal',
'fieldConfig' => [
'template' => "{label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
'horizontalCssClasses' => [
'offset' => '',
'label' => 'col-md-3',
'wrapper' => 'col-md-5',
'error' => '',
'hint' => '',
],
]
]); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'short_name') ?>
<div class="form-group">
<div class="col-md-offset-3 col-md-9">
<?= Html::submitButton(Yii::t('app/frontend', 'Search'), ['class' => 'btn btn-primary']) ?>
<?php // echo Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
|
[base] Remove faulty keypress condition in input text component
See https://github.com/driebit/ginger/commit/d4f55200359e4534c528b967c2d85188196778da#commitcomment-23920421 | $.widget("ui.search_cmp_input_text", {
_create: function() {
var me = this,
widgetElement = $(me.element);
me.widgetElement = widgetElement;
me.type = 'qs';
me.widgetElement.keypress(function(event) {
if (event.keyCode === 13) {
event.preventDefault();
$(document).trigger('search:inputChanged');
}
});
if (widgetElement.data('instant')) {
var timer = null;
me.widgetElement.on('keyup', function() {
if (timer) clearTimeout(timer);
timer = setTimeout(
function() {
$(document).trigger('search:inputChanged')
},
300
);
});
}
},
getValues: function() {
var me = this,
value = ($.url().param('qs') != '' && !window.location.hash) ? value = $.url().param('qs') : me.widgetElement.val();
return [{
'type': me.type,
'values': value
}]
},
setValues: function(values) {
var me = this,
widgetValues;
try {
widgetValues = values[me.type];
} catch(e) {}
me.widgetElement.val('');
if (widgetValues) {
me.widgetElement.val(widgetValues);
}
}
});
| $.widget("ui.search_cmp_input_text", {
_create: function() {
var me = this,
widgetElement = $(me.element);
me.widgetElement = widgetElement;
me.type = 'qs';
me.widgetElement.keypress(function(event) {
if (event.keyCode == 13) {
var onSeachPage = ($('.do_search_ui') < 0);
if (onSeachPage) {
event.preventDefault();
$(document).trigger('search:inputChanged');
}
}
});
if (widgetElement.data('instant')) {
var timer = null;
me.widgetElement.on('keyup', function() {
if (timer) clearTimeout(timer);
timer = setTimeout(
function() {
$(document).trigger('search:inputChanged')
},
300
);
});
}
},
getValues: function() {
var me = this,
value = ($.url().param('qs') != '' && !window.location.hash) ? value = $.url().param('qs') : me.widgetElement.val();
return [{
'type': me.type,
'values': value
}]
},
setValues: function(values) {
var me = this,
widgetValues;
try {
widgetValues = values[me.type];
} catch(e) {}
me.widgetElement.val('');
if (widgetValues) {
me.widgetElement.val(widgetValues);
}
}
});
|
Add /firefox/nightly/all/ to download link tests | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from bs4 import BeautifulSoup
import pytest
import requests
def pytest_generate_tests(metafunc):
if 'not headless' in metafunc.config.option.markexpr:
return # test deslected by mark expression
base_url = metafunc.config.option.base_url
if not base_url:
pytest.skip(
'This test requires a base URL to be specified on the command '
'line or in a configuration file.')
paths = (
'/firefox/all/',
'/firefox/beta/all/',
'/firefox/developer/all/',
'/firefox/nightly/all/',
'/firefox/organizations/all/',
'/firefox/android/all/',
'/firefox/android/beta/all/')
argvalues = []
for path in paths:
r = requests.get(base_url + path)
soup = BeautifulSoup(r.content, 'html.parser')
table = soup.find('table', class_='build-table')
urls = [a['href'] for a in table.find_all('a')]
assert len(urls) > 0
argvalues.extend(urls)
metafunc.parametrize('url', argvalues)
@pytest.mark.headless
@pytest.mark.nondestructive
def test_localized_download_links(url):
r = requests.head(url, allow_redirects=True)
assert requests.codes.ok == r.status_code
| # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from bs4 import BeautifulSoup
import pytest
import requests
def pytest_generate_tests(metafunc):
if 'not headless' in metafunc.config.option.markexpr:
return # test deslected by mark expression
base_url = metafunc.config.option.base_url
if not base_url:
pytest.skip(
'This test requires a base URL to be specified on the command '
'line or in a configuration file.')
paths = (
'/firefox/all/',
'/firefox/beta/all/',
'/firefox/developer/all/',
'/firefox/organizations/all/',
'/firefox/android/all/',
'/firefox/android/beta/all/')
argvalues = []
for path in paths:
r = requests.get(base_url + path)
soup = BeautifulSoup(r.content, 'html.parser')
table = soup.find('table', class_='build-table')
urls = [a['href'] for a in table.find_all('a')]
assert len(urls) > 0
argvalues.extend(urls)
metafunc.parametrize('url', argvalues)
@pytest.mark.headless
@pytest.mark.nondestructive
def test_localized_download_links(url):
r = requests.head(url, allow_redirects=True)
assert requests.codes.ok == r.status_code
|
Change project name to cljsbook. | import paver
from paver.easy import *
import paver.setuputils
paver.setuputils.install_distutils_tasks()
import os, sys
from sphinxcontrib import paverutils
sys.path.append(os.getcwd())
updateProgressTables = True
try:
from runestone.server.chapternames import populateChapterInfob
except ImportError:
updateProgressTables = False
home_dir = os.getcwd()
master_url = 'http://127.0.0.1:8000'
master_app = 'runestone'
serving_dir = "./build/cljsbook"
dest = "../../static"
options(
sphinx = Bunch(docroot=".",),
build = Bunch(
builddir="./build/cljsbook",
sourcedir="_sources",
outdir="./build/cljsbook",
confdir=".",
project_name = "cljsbook",
template_args={'course_id': 'cljsbook',
'login_required':'false',
'appname':master_app,
'loglevel': 0,
'course_url':master_url,
'use_services': 'true',
'python3': 'true',
'dburl': '',
'basecourse': 'cljsbook'
}
)
)
from runestone import build # build is called implicitly by the paver driver.
| import paver
from paver.easy import *
import paver.setuputils
paver.setuputils.install_distutils_tasks()
import os, sys
from sphinxcontrib import paverutils
sys.path.append(os.getcwd())
updateProgressTables = True
try:
from runestone.server.chapternames import populateChapterInfob
except ImportError:
updateProgressTables = False
home_dir = os.getcwd()
master_url = 'http://127.0.0.1:8000'
master_app = 'runestone'
serving_dir = "./build/interactiveclojurescript"
dest = "../../static"
options(
sphinx = Bunch(docroot=".",),
build = Bunch(
builddir="./build/interactiveclojurescript",
sourcedir="_sources",
outdir="./build/interactiveclojurescript",
confdir=".",
project_name = "interactiveclojurescript",
template_args={'course_id': 'interactiveclojurescript',
'login_required':'false',
'appname':master_app,
'loglevel': 0,
'course_url':master_url,
'use_services': 'true',
'python3': 'true',
'dburl': '',
'basecourse': 'interactiveclojurescript'
}
)
)
from runestone import build # build is called implicitly by the paver driver.
|
Remove debugging graph from JsonUl test | /*global describe, it*/
var expect = require('../unexpected-with-plugins'),
AssetGraph = require('../../lib');
describe('relations/JsonUrl', function () {
it('should get the href correctly', function (done) {
new AssetGraph({root: __dirname + '/../../testdata/relations/JsonUrl/'})
.loadAssets('app.webmanifest')
.populate()
.queue(function (assetGraph) {
expect(assetGraph, 'to contain relations', 'HtmlApplicationManifest', 1);
expect(assetGraph, 'to contain relations', 'JsonUrl', 1);
expect(assetGraph.findRelations({ type: 'JsonUrl' }), 'to satisfy', [
{
href: 'index.html',
hrefType: 'relative'
}
]);
})
.run(done);
});
it('should set the href correctly', function (done) {
new AssetGraph({root: __dirname + '/../../testdata/relations/JsonUrl/'})
.loadAssets('app.webmanifest')
.populate()
.queue(function (assetGraph) {
assetGraph.findAssets({ type: 'Html'})[0].fileName = 'foo.html';
expect(assetGraph.findRelations({ type: 'JsonUrl' }), 'to satisfy', [
{
href: 'foo.html',
hrefType: 'relative'
}
]);
})
.run(done);
});
});
| /*global describe, it*/
var expect = require('../unexpected-with-plugins'),
AssetGraph = require('../../lib');
describe('relations/JsonUrl', function () {
it('should get the href correctly', function (done) {
new AssetGraph({root: __dirname + '/../../testdata/relations/JsonUrl/'})
.loadAssets('app.webmanifest')
.populate()
.queue(function (assetGraph) {
expect(assetGraph, 'to contain relations', 'HtmlApplicationManifest', 1);
expect(assetGraph, 'to contain relations', 'JsonUrl', 1);
expect(assetGraph.findRelations({ type: 'JsonUrl' }), 'to satisfy', [
{
href: 'index.html',
hrefType: 'relative'
}
]);
})
.run(done);
});
it('should set the href correctly', function (done) {
new AssetGraph({root: __dirname + '/../../testdata/relations/JsonUrl/'})
.loadAssets('app.webmanifest')
.populate()
.queue(function (assetGraph) {
assetGraph.findAssets({ type: 'Html'})[0].fileName = 'foo.html';
expect(assetGraph.findRelations({ type: 'JsonUrl' }), 'to satisfy', [
{
href: 'foo.html',
hrefType: 'relative'
}
]);
})
.drawGraph('debug.svg')
.run(done);
});
});
|
Fix tooltip message for titles | const React = require('react');
const classNames = require('classnames');
const { BLOCKS } = require('markup-it');
const TAGS = {
[BLOCKS.HEADING_1]: 'h1',
[BLOCKS.HEADING_2]: 'h2',
[BLOCKS.HEADING_3]: 'h3',
[BLOCKS.HEADING_4]: 'h4',
[BLOCKS.HEADING_5]: 'h5',
[BLOCKS.HEADING_6]: 'h6'
};
/**
* Render an heading that has been modified.
* @type {React}
*/
const HeadingNode = React.createClass({
propTypes: {
original: React.PropTypes.object,
attributes: React.PropTypes.object.isRequired,
node: React.PropTypes.object.isRequired,
children: React.PropTypes.node.isRequired
},
render() {
const { children, attributes, node, original } = this.props;
const originalTag = original ? TAGS[original.type] : null;
const modifiedTag = TAGS[node.type];
const originalID = original ? original.data.get('id', '<none>') : null;
const modifiedID = node.data.get('id', '<none>');
let title = '';
if (original && originalTag != modifiedTag) {
title = `Tag: ${originalTag} -> ${modifiedTag}`;
}
if (original && originalID != modifiedID) {
title = `${title ? title + ', ' : ''}ID: ${originalID} -> ${modifiedID}`;
}
return React.createElement(modifiedTag, {
...attributes,
className: classNames(attributes.className, {
'tooltipped': title
}),
'aria-label': title
}, children);
}
});
module.exports = HeadingNode;
| const React = require('react');
const classNames = require('classnames');
const { BLOCKS } = require('markup-it');
const TAGS = {
[BLOCKS.HEADING_1]: 'h1',
[BLOCKS.HEADING_2]: 'h2',
[BLOCKS.HEADING_3]: 'h3',
[BLOCKS.HEADING_4]: 'h4',
[BLOCKS.HEADING_5]: 'h5',
[BLOCKS.HEADING_6]: 'h6'
};
/**
* Render an heading that has been modified.
* @type {React}
*/
const HeadingNode = React.createClass({
propTypes: {
original: React.PropTypes.object,
attributes: React.PropTypes.object.isRequired,
node: React.PropTypes.object.isRequired,
children: React.PropTypes.node.isRequired
},
render() {
const { children, attributes, node, original } = this.props;
const originalTag = original ? TAGS[original.type] : null;
const modifiedTag = TAGS[node.type];
let title = '';
if (originalTag != modifiedTag) {
title = `Tag: ${originalTag} -> ${modifiedTag}`;
}
return React.createElement(modifiedTag, {
...attributes,
className: classNames(attributes.className, {
'tooltipped': title
}),
'aria-label': title
}, children);
}
});
module.exports = HeadingNode;
|
Add character encoding meta tag
Signed-off-by: Eddie Ringle <[email protected]> | <!DOCTYPE html>
<html>
<head>
<title>Layout Test</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/style.css" />
<?php
wp_head();
comments_popup_script(400, 400);
?>
</head>
<body>
<div id="wrapper">
<div id="header-wrap">
<div id="header">
<div id="logo">
<h1><a href="/">A</a></h1>
</div>
<div id="sideline">
<p>Bla blah blah bleh blee!</p>
</div>
</div>
</div>
<div id="body-wrap">
<div id="body">
<div id="navigation">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
</ul>
</div>
<div id="page"> | <!DOCTYPE html>
<html>
<head>
<title>Layout Test</title>
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/style.css" />
<?php
wp_head();
comments_popup_script(400, 400);
?>
</head>
<body>
<div id="wrapper">
<div id="header-wrap">
<div id="header">
<div id="logo">
<h1><a href="/">A</a></h1>
</div>
<div id="sideline">
<p>Bla blah blah bleh blee!</p>
</div>
</div>
</div>
<div id="body-wrap">
<div id="body">
<div id="navigation">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
</ul>
</div>
<div id="page"> |
Make curl work in py3 again | import logging
import os
from twisted.web import server, guard, resource
from twisted.cred import portal
from lbrynet import conf
from .auth import PasswordChecker, HttpPasswordRealm
from .util import initialize_api_key_file
log = logging.getLogger(__name__)
class AuthJSONRPCResource(resource.Resource):
def __init__(self, protocol):
resource.Resource.__init__(self)
self.putChild(b"", protocol)
self.putChild(conf.settings['API_ADDRESS'].encode(), protocol)
def getChild(self, name, request):
request.setHeader('cache-control', 'no-cache, no-store, must-revalidate')
request.setHeader('expires', '0')
return self if name == '' else resource.Resource.getChild(self, name, request)
def getServerFactory(self):
if conf.settings['use_auth_http']:
log.info("Using authenticated API")
pw_path = os.path.join(conf.settings['data_dir'], ".api_keys")
initialize_api_key_file(pw_path)
checker = PasswordChecker.load_file(pw_path)
realm = HttpPasswordRealm(self)
portal_to_realm = portal.Portal(realm, [checker, ])
factory = guard.BasicCredentialFactory('Login to lbrynet api')
root = guard.HTTPAuthSessionWrapper(portal_to_realm, [factory, ])
else:
log.info("Using non-authenticated API")
root = self
return server.Site(root)
| import logging
import os
from twisted.web import server, guard, resource
from twisted.cred import portal
from lbrynet import conf
from .auth import PasswordChecker, HttpPasswordRealm
from .util import initialize_api_key_file
log = logging.getLogger(__name__)
class AuthJSONRPCResource(resource.Resource):
def __init__(self, protocol):
resource.Resource.__init__(self)
self.putChild("", protocol)
self.putChild(conf.settings['API_ADDRESS'], protocol)
def getChild(self, name, request):
request.setHeader('cache-control', 'no-cache, no-store, must-revalidate')
request.setHeader('expires', '0')
return self if name == '' else resource.Resource.getChild(self, name, request)
def getServerFactory(self):
if conf.settings['use_auth_http']:
log.info("Using authenticated API")
pw_path = os.path.join(conf.settings['data_dir'], ".api_keys")
initialize_api_key_file(pw_path)
checker = PasswordChecker.load_file(pw_path)
realm = HttpPasswordRealm(self)
portal_to_realm = portal.Portal(realm, [checker, ])
factory = guard.BasicCredentialFactory('Login to lbrynet api')
root = guard.HTTPAuthSessionWrapper(portal_to_realm, [factory, ])
else:
log.info("Using non-authenticated API")
root = self
return server.Site(root)
|
Fix crash when Arg "Enter Number" field is left empty. | package eu.f3rog.blade.sample.arg;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
import blade.Blade;
import blade.F;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import eu.f3rog.blade.sample.R;
@Blade
public class TestArgActivity extends AppCompatActivity {
@BindView(R.id.edt_num)
EditText mEditNumber;
@BindView(R.id.edt_text)
EditText mEditText;
@OnClick(R.id.btn_show_fragment)
public void showFragment() {
if (mEditNumber.getText().length() == 0) {
Toast.makeText(this, "Input a number!", Toast.LENGTH_SHORT).show();
mEditNumber.requestFocus();
return;
}
int number = Integer.parseInt(mEditNumber.getText().toString());
String text = mEditText.getText().toString();
Data data = new Data(number, text);
double randomDouble = new Random().nextDouble();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frag, F.newDataFragment(randomDouble, data))
.commit();
}
@OnClick(R.id.btn_show_dialog)
public void b2() {
F.newSampleDialogFragment("Hello mate :)").show(getSupportFragmentManager(), "some-tag");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_arg);
ButterKnife.bind(this);
}
}
| package eu.f3rog.blade.sample.arg;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import java.util.Random;
import blade.Blade;
import blade.F;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import eu.f3rog.blade.sample.R;
@Blade
public class TestArgActivity extends AppCompatActivity {
@BindView(R.id.edt_num)
EditText mEditNumber;
@BindView(R.id.edt_text)
EditText mEditText;
@OnClick(R.id.btn_show_fragment)
public void showFragment() {
int number = Integer.parseInt(mEditNumber.getText().toString());
String text = mEditText.getText().toString();
Data data = new Data(number, text);
double randomDouble = new Random().nextDouble();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frag, F.newDataFragment(randomDouble, data))
.commit();
}
@OnClick(R.id.btn_show_dialog)
public void b2() {
F.newSampleDialogFragment("Hello mate :)").show(getSupportFragmentManager(), "some-tag");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_arg);
ButterKnife.bind(this);
}
}
|
Replace baseURL with data provider.
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@8663 b4e469a2-07ce-4b26-9273-4d7d95a670c7 | package org.helioviewer.jhv.timelines.data;
import java.util.HashMap;
public class BandType {
private String label;
private String name;
private String unitLabel;
private final HashMap<String, Double> warnLevels = new HashMap<>();
private double min;
private double max;
private boolean isLog = false;
private DataProvider dataprovider;
@Override
public String toString() {
return label;
}
public String getLabel() {
return label;
}
public void setLabel(String _label) {
label = _label;
}
public String getUnitLabel() {
return unitLabel;
}
public void setUnitLabel(String _unitLabel) {
unitLabel = _unitLabel;
}
public HashMap<String, Double> getWarnLevels() {
return warnLevels;
}
public double getMin() {
return min;
}
public void setMin(double _min) {
min = _min;
}
public double getMax() {
return max;
}
public void setMax(double _max) {
max = _max;
}
public void setName(String _name) {
name = _name;
}
public String getName() {
return name;
}
public void setScale(String scale) {
isLog = scale.equals("logarithmic");
}
public boolean isLogScale() {
return isLog;
}
public DataProvider getDataprovider() {
return dataprovider;
}
public void setDataprovider(DataProvider dataprovider) {
this.dataprovider = dataprovider;
}
}
| package org.helioviewer.jhv.timelines.data;
import java.util.HashMap;
public class BandType {
private String baseURL;
private String label;
private String name;
private String unitLabel;
private final HashMap<String, Double> warnLevels = new HashMap<>();
private double min;
private double max;
private boolean isLog = false;
@Override
public String toString() {
return label;
}
public String getBaseURL() {
return baseURL;
}
public void setBaseURL(String _baseURL) {
baseURL = _baseURL;
}
public String getLabel() {
return label;
}
public void setLabel(String _label) {
label = _label;
}
public String getUnitLabel() {
return unitLabel;
}
public void setUnitLabel(String _unitLabel) {
unitLabel = _unitLabel;
}
public HashMap<String, Double> getWarnLevels() {
return warnLevels;
}
public double getMin() {
return min;
}
public void setMin(double _min) {
min = _min;
}
public double getMax() {
return max;
}
public void setMax(double _max) {
max = _max;
}
public void setName(String _name) {
name = _name;
}
public String getName() {
return name;
}
public void setScale(String scale) {
isLog = scale.equals("logarithmic");
}
public boolean isLogScale() {
return isLog;
}
}
|
Reduce the number of assets cached in the service worker | const webpack = require("webpack");
const merge = require("webpack-merge");
const workboxPlugin = require("workbox-webpack-plugin");
const GitRevisionPlugin = require("git-revision-webpack-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const common = require("./webpack.common.js");
const gitRevisionPlugin = new GitRevisionPlugin();
const config = merge(common, {
devtool: "source-map",
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
},
SENTRY_DSN: JSON.stringify(
"https://[email protected]/146021"
),
COMMITHASH: JSON.stringify(gitRevisionPlugin.commithash())
}),
new UglifyJsPlugin({
// TODO: Is this needed with the devtool setting above?
sourceMap: true,
parallel: true,
uglifyOptions: {
compress: {
// Workaround: https://github.com/mishoo/UglifyJS2/issues/2842
inline: false
}
}
}),
new workboxPlugin.GenerateSW({
swDest: "service-worker.js",
// importWorkboxFrom: "local",
clientsClaim: true,
skipWaiting: true,
// Safari (mobile and desktop) seems to have CORs issues when loading
// .mp3s from service workers.
exclude: [/\.mp3/, /\.wsz/]
})
]
});
config.entry.webamp.unshift("./js/googleAnalytics.min.js");
module.exports = config;
| const webpack = require("webpack");
const merge = require("webpack-merge");
const workboxPlugin = require("workbox-webpack-plugin");
const GitRevisionPlugin = require("git-revision-webpack-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const common = require("./webpack.common.js");
const gitRevisionPlugin = new GitRevisionPlugin();
const config = merge(common, {
devtool: "source-map",
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
},
SENTRY_DSN: JSON.stringify(
"https://[email protected]/146021"
),
COMMITHASH: JSON.stringify(gitRevisionPlugin.commithash())
}),
new UglifyJsPlugin({
// TODO: Is this needed with the devtool setting above?
sourceMap: true,
parallel: true,
uglifyOptions: {
compress: {
// Workaround: https://github.com/mishoo/UglifyJS2/issues/2842
inline: false
}
}
}),
new workboxPlugin.GenerateSW({
swDest: "service-worker.js",
clientsClaim: true,
skipWaiting: true
})
]
});
config.entry.webamp.unshift("./js/googleAnalytics.min.js");
module.exports = config;
|
Fix get non-object on product detail | <?php namespace Octommerce\Octommerce\Components;
use Cms\Classes\ComponentBase;
use Octommerce\Octommerce\Models\Product as ProductModel;
class ProductDetail extends ComponentBase
{
public function componentDetails()
{
return [
'name' => 'ProductDetail Component',
'description' => 'No description provided yet...'
];
}
public function defineProperties()
{
return [
'slug' => [
'title' => 'octommerce.octommerce::lang.component.product_detail.param.id_param_title',
'description' => 'octommerce.octommerce::lang.component.product_detail.param.id_param_desc',
'default' => '{{ :slug }}',
'type' => 'string'
],
];
}
public function onRun()
{
$product = $this->loadProduct();
if (!$product) {
$this->setStatusCode(404);
return $this->controller->run('404');
}
$this->product = $this->page['product'] = $product;
$this->page->title = $product->name;
$this->page->description = $product->description;
}
public function onChangeVariation()
{
}
protected function loadProduct()
{
$slug = $this->property('slug');
$product = ProductModel::whereSlug($slug)
->whereIsPublished(1)
->with('categories')
->with('lists')
->with('reviews')
->first();
// if ($product->type == 'variable') {
//
// }
return $product;
}
}
| <?php namespace Octommerce\Octommerce\Components;
use Cms\Classes\ComponentBase;
use Octommerce\Octommerce\Models\Product as ProductModel;
class ProductDetail extends ComponentBase
{
public function componentDetails()
{
return [
'name' => 'ProductDetail Component',
'description' => 'No description provided yet...'
];
}
public function defineProperties()
{
return [
'slug' => [
'title' => 'octommerce.octommerce::lang.component.product_detail.param.id_param_title',
'description' => 'octommerce.octommerce::lang.component.product_detail.param.id_param_desc',
'default' => '{{ :slug }}',
'type' => 'string'
],
];
}
public function onRun()
{
$product = $this->loadProduct();
if (!$product) {
$this->setStatusCode(404);
return $this->controller->run('404');
}
$this->product = $this->page['product'] = $product;
$this->page->title = $product->name;
$this->page->description = $product->description;
}
public function onChangeVariation()
{
}
protected function loadProduct()
{
$slug = $this->property('slug');
$product = ProductModel::whereSlug($slug)
->whereIsPublished(1)
->with('categories')
->with('lists')
->with('reviews')
->first();
if ($product->type == 'variable') {
}
return $product;
}
} |
BUGFIX: Fix deprecated e modifier in preg_replace
With PHP 7, Faker issued the following warning:
preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead | <?php
namespace KDambekalns\Faker;
/* *
* This script belongs to the Flow package "Faker". *
* */
/**
* Faker class for the Faker package
*
* The Faker package is based on http://faker.rubyforge.org/
*/
class Faker
{
/**
* Replace all # characters in $string with a random digit.
*
* @param string $string
* @return string
*/
public static function numerify($string)
{
return preg_replace_callback('/#/', function() { return rand(0,9); }, $string);
}
/**
* Replace all ? characters in $string with a random char (a-z).
*
* @param string $string
* @return string
*/
public static function letterify($string)
{
return preg_replace_callback('/\?/', function() { return chr(rand(97,122)); }, $string);
}
/**
* Return the combined result of letterify() and numerify().
*
* @param string $string
* @return string
*/
public static function bothify($string)
{
return static::letterify(static::numerify($string));
}
}
| <?php
namespace KDambekalns\Faker;
/* *
* This script belongs to the Flow package "Faker". *
* */
/**
* Faker class for the Faker package
*
* The Faker package is based on http://faker.rubyforge.org/
*/
class Faker
{
/**
* Replace all # characters in $string with a random digit.
*
* @param string $string
* @return string
*/
public static function numerify($string)
{
return preg_replace('/#/e', 'rand(0,9)', $string);
}
/**
* Replace all ? characters in $string with a random char (a-z).
*
* @param string $string
* @return string
*/
public static function letterify($string)
{
return preg_replace('/\?/e', 'chr(rand(97,122))', $string);
}
/**
* Return the combined result of letterify() and numerify().
*
* @param string $string
* @return string
*/
public static function bothify($string)
{
return static::letterify(static::numerify($string));
}
}
|
Switch api service to prod | import axios from 'axios';
class WldApi {
constructor() {
if(!WldApi.instance) {
this.baseURL = 'http://wld-backend.herokuapp.com';
//this.baseURL = 'http://localhost:3001';
this.token = localStorage.getItem('token');
WldApi.instance = this;
}
return WldApi.instance;
}
setToken(token) {
localStorage.setItem('token', token);
this.token = token;
}
destroyToken() {
localStorage.removeItem('token');
this.token = null;
}
configs(opts = {}) {
return Object.assign({}, {
'headers': {
'Authorization': this.token
}
}, opts);
}
get(path, opts = {}) {
return axios.get(
this.baseURL + path,
this.configs(opts)
);
}
put(path, data = {}, opts = {}) {
return axios.put(
this.baseURL + path,
data,
this.configs(opts)
);
}
post(path, data = {}, opts = {}) {
return axios.post(
this.baseURL + path,
data,
this.configs(opts)
);
}
delete(path, opts = {}) {
return axios.delete(
this.baseURL + path,
this.configs(opts)
);
}
}
const instance = new WldApi();
export default instance;
| import axios from 'axios';
class WldApi {
constructor() {
if(!WldApi.instance) {
// this.baseURL = 'http://wld-backend.herokuapp.com';
this.baseURL = 'http://localhost:3001';
this.token = localStorage.getItem('token');
WldApi.instance = this;
}
return WldApi.instance;
}
setToken(token) {
localStorage.setItem('token', token);
this.token = token;
}
destroyToken() {
localStorage.removeItem('token');
this.token = null;
}
configs(opts = {}) {
return Object.assign({}, {
'headers': {
'Authorization': this.token
}
}, opts);
}
get(path, opts = {}) {
return axios.get(
this.baseURL + path,
this.configs(opts)
);
}
put(path, data = {}, opts = {}) {
return axios.put(
this.baseURL + path,
data,
this.configs(opts)
);
}
post(path, data = {}, opts = {}) {
return axios.post(
this.baseURL + path,
data,
this.configs(opts)
);
}
delete(path, opts = {}) {
return axios.delete(
this.baseURL + path,
this.configs(opts)
);
}
}
const instance = new WldApi();
export default instance;
|
BAP-687: Delete confirmation message is not useful
- added "Cancel" button on delete modal | $(function() {
$('#btn-apigen').on('click', function(e) {
var el = $(this);
$.get(el.attr('href'), function (data) {
el.prev().text(data);
})
return false;
});
$('#btn-remove-profile').on('click', function(e) {
var el = $(this),
message = el.attr('data-message'),
doAction = function() {
$.ajax({
url: Routing.generate('oro_api_delete_profile', { id: el.attr('data-id') }),
type: 'DELETE',
success: function (data) {
window.location.href = Routing.generate('oro_user_index');
}
});
};
if (!_.isUndefined(Oro.BootstrapModal)) {
var confirm = new Oro.BootstrapModal({
title: 'Delete Confirmation',
content: message,
okText: 'Yes, Delete',
cancelText: 'Cancel'
});
confirm.on('ok', doAction);
confirm.open();
} else if (window.confirm(message)) {
doAction();
}
return false;
});
$('#roles-list input')
.on('click', function() {
var inputs = $(this).closest('.controls');
inputs.find(':checkbox').attr('required', inputs.find(':checked').length > 0 ? null : 'required');
})
.triggerHandler('click');
$('#btn-enable input').on('change', function(e) {
// if ($(this).is(':checked')) {
//
// }
$('.status-enabled').toggleClass('hide');
$('.status-disabled').toggleClass('hide');
});
});
| $(function() {
$('#btn-apigen').on('click', function(e) {
var el = $(this);
$.get(el.attr('href'), function (data) {
el.prev().text(data);
})
return false;
});
$('#btn-remove-profile').on('click', function(e) {
var el = $(this),
message = el.attr('data-message'),
doAction = function() {
$.ajax({
url: Routing.generate('oro_api_delete_profile', { id: el.attr('data-id') }),
type: 'DELETE',
success: function (data) {
window.location.href = Routing.generate('oro_user_index');
}
});
};
if (!_.isUndefined(Oro.BootstrapModal)) {
confirm = new Oro.BootstrapModal({
title: 'Delete Confirmation',
content: message,
okText: 'Yes, Delete'
});
confirm.on('ok', doAction);
confirm.open();
} else if (window.confirm(message)) {
doAction();
}
return false;
});
$('#roles-list input')
.on('click', function() {
var inputs = $(this).closest('.controls');
inputs.find(':checkbox').attr('required', inputs.find(':checked').length > 0 ? null : 'required');
})
.triggerHandler('click');
$('#btn-enable input').on('change', function(e) {
// if ($(this).is(':checked')) {
//
// }
$('.status-enabled').toggleClass('hide');
$('.status-disabled').toggleClass('hide');
});
}); |
Fix round trip for testing JdkInflate / JdkDeflate
The Inflater and Deflater calls need to be aligned on whether or not
the compressed output includes the ZLIB header and checksum fields. | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.compress.thirdparty;
import io.airlift.compress.Decompressor;
import io.airlift.compress.MalformedInputException;
import java.nio.ByteBuffer;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
public class JdkInflateDecompressor
implements Decompressor
{
@Override
public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength)
throws MalformedInputException
{
try {
Inflater inflater = new Inflater(true);
inflater.setInput(input, inputOffset, inputLength);
int resultLength = inflater.inflate(output, outputOffset, maxOutputLength);
inflater.end();
return resultLength;
}
catch (DataFormatException e) {
throw new RuntimeException(e);
}
}
@Override
public void decompress(ByteBuffer input, ByteBuffer output)
throws MalformedInputException
{
throw new UnsupportedOperationException("not yet implemented");
}
}
| /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.compress.thirdparty;
import io.airlift.compress.Decompressor;
import io.airlift.compress.MalformedInputException;
import java.nio.ByteBuffer;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
public class JdkInflateDecompressor
implements Decompressor
{
@Override
public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength)
throws MalformedInputException
{
try {
Inflater inflater = new Inflater();
inflater.setInput(input, inputOffset, inputLength);
int resultLength = inflater.inflate(output, outputOffset, maxOutputLength);
inflater.end();
return resultLength;
}
catch (DataFormatException e) {
throw new RuntimeException(e);
}
}
@Override
public void decompress(ByteBuffer input, ByteBuffer output)
throws MalformedInputException
{
throw new UnsupportedOperationException("not yet implemented");
}
}
|
Set up MonkeyTestJS and make all tests pass | (function(global) {
global.monkeytestjs = {
"facebookId": "000000000000000",
"local": {
"env": ["DEV URL OR PART OF"]
},
"stage": {
"env": ["STAGE URL OR PART OF"],
"facebookId": "222222222222222"
},
"beta": {
"env": ["BETA URL OR PART OF"],
"facebookId": "33333333333333333"
},
"production": {
"env": ["PRODUCTION URL OR PART OF"],
"facebookId": "4444444444444444444"
},
"testsDir": "mytests",
"globalTests": [
"global/not_server_error.js",
"global/is_html_w3c_valid.js", // The first task is done by this global test, so I just ignore it. I have implemented the following two tests below
"global/has_utf8_metatag.js"
// Comment the following test, because I don't add a valid GA id. This is not required in the test
/*"global/has_google_analytics.js"*/
],
"pages": [
{
"url": "/",
"tests": [ "enquiry/require_fields_test.js","enquiry/product_complaint_test.js" ]
}
],
"proxyUrl": "core/proxy.php?mode=native&url=<%= url %>",
"loadSources": true
};
})(this);
| (function(global) {
global.monkeytestjs = {
"facebookId": "000000000000000",
"local": {
"env": ["DEV URL OR PART OF"]
},
"stage": {
"env": ["STAGE URL OR PART OF"],
"facebookId": "222222222222222"
},
"beta": {
"env": ["BETA URL OR PART OF"],
"facebookId": "33333333333333333"
},
"production": {
"env": ["PRODUCTION URL OR PART OF"],
"facebookId": "4444444444444444444"
},
"testsDir": "mytests",
"globalTests": [
"global/not_server_error.js",
"global/is_html_w3c_valid.js",
"global/has_utf8_metatag.js",
"global/has_google_analytics.js"
],
"pages": [
{
"url": "/",
"tests": [ "page/demo_page_test.js","page/has_facebook_appid.js" ]
}
],
"proxyUrl": "core/proxy.php?mode=native&url=<%= url %>",
"loadSources": true
};
})(this);
|
Use config for API url | define([
'Class', 'uri', 'bluebird',
'map/services/DataService'
], function(Class, UriTemplate, Promise, ds) {
'use strict';
var GET_REQUEST_ID = 'GeostoreService:get',
SAVE_REQUEST_ID = 'GeostoreService:save';
var URL = window.gfw.config.GFW_API_HOST + '/api/geostore/{id}';
var GeostoreService = Class.extend({
get: function(id) {
return new Promise(function(resolve, reject) {
var url = new UriTemplate(URL).fillFromObject({id: id});
ds.define(GET_REQUEST_ID, {
cache: {type: 'persist', duration: 1, unit: 'days'},
url: url,
type: 'GET'
});
var requestConfig = {
resourceId: GET_REQUEST_ID,
success: function(response) {
resolve(response.data);
},
};
ds.request(requestConfig);
});
},
save: function(geojson) {
return new Promise(function(resolve, reject) {
var url = new UriTemplate(URL).fillFromObject({});
ds.define(SAVE_REQUEST_ID, {
url: url,
type: 'POST',
contentType: 'application/json'
});
var requestConfig = {
resourceId: SAVE_REQUEST_ID,
data: JSON.stringify(geojson),
success: function(response) {
resolve(response.data.id);
},
error: reject
};
ds.request(requestConfig);
});
}
});
return new GeostoreService();
});
| define([
'Class', 'uri', 'bluebird',
'map/services/DataService'
], function(Class, UriTemplate, Promise, ds) {
'use strict';
var GET_REQUEST_ID = 'GeostoreService:get',
SAVE_REQUEST_ID = 'GeostoreService:save';
var URL = window.gfw.config.GFW_API_HOST + '/geostore/{id}';
var GeostoreService = Class.extend({
get: function(id) {
return new Promise(function(resolve, reject) {
var url = new UriTemplate(URL).fillFromObject({id: id});
ds.define(GET_REQUEST_ID, {
cache: {type: 'persist', duration: 1, unit: 'days'},
url: url,
type: 'GET'
});
var requestConfig = {
resourceId: GET_REQUEST_ID,
success: function(response) {
resolve(response.data);
},
};
ds.request(requestConfig);
});
},
save: function(geojson) {
return new Promise(function(resolve, reject) {
var url = new UriTemplate(URL).fillFromObject({});
ds.define(SAVE_REQUEST_ID, {
url: url,
type: 'POST',
contentType: 'application/json'
});
var requestConfig = {
resourceId: SAVE_REQUEST_ID,
data: JSON.stringify(geojson),
success: function(response) {
resolve(response.data.id);
},
error: reject
};
ds.request(requestConfig);
});
}
});
return new GeostoreService();
});
|
Return false for undefined functions, not null | <?php
namespace ZfcTwig\Service;
use RuntimeException;
use Twig_Environment;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZfcTwig\Twig\Func\ViewHelper;
class TwigEnvironmentFactory implements FactoryInterface
{
/**
* Create service
*
* @param ServiceLocatorInterface $serviceLocator
* @return mixed
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Configuration');
$config = $config['zfctwig'];
$env = new Twig_Environment(null, (array) $config['environment_options']);
if ($config['enable_fallback_functions']) {
$helperPluginManager = $serviceLocator->get('ViewHelperManager');
$env->registerUndefinedFunctionCallback(function($name) use ($helperPluginManager) {
if ($helperPluginManager->has($name)) {
return new ViewHelper($name);
}
return false;
});
}
if (!$serviceLocator->has($config['environment_loader'])) {
throw new RuntimeException(sprintf(
'Loader with alias "%s" could not be found!',
$config['loader']
));
}
$env->setLoader($serviceLocator->get($config['environment_loader']));
// Extensions are loaded later to avoid circular dependencies (for example, if an extension needs Renderer).
return $env;
}
}
| <?php
namespace ZfcTwig\Service;
use RuntimeException;
use Twig_Environment;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZfcTwig\Twig\Func\ViewHelper;
class TwigEnvironmentFactory implements FactoryInterface
{
/**
* Create service
*
* @param ServiceLocatorInterface $serviceLocator
* @return mixed
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Configuration');
$config = $config['zfctwig'];
$env = new Twig_Environment(null, (array) $config['environment_options']);
if ($config['enable_fallback_functions']) {
$helperPluginManager = $serviceLocator->get('ViewHelperManager');
$env->registerUndefinedFunctionCallback(function($name) use ($helperPluginManager) {
if ($helperPluginManager->has($name)) {
return new ViewHelper($name);
}
return null;
});
}
if (!$serviceLocator->has($config['environment_loader'])) {
throw new RuntimeException(sprintf(
'Loader with alias "%s" could not be found!',
$config['loader']
));
}
$env->setLoader($serviceLocator->get($config['environment_loader']));
// Extensions are loaded later to avoid circular dependencies (for example, if an extension needs Renderer).
return $env;
}
} |
Use asyncCoroutine instead of manual rethrow + new Coroutine | #!/usr/bin/env php
<?php
require __DIR__ . '/../../vendor/autoload.php';
use Amp\Delayed;
use Amp\Emitter;
use Amp\Loop;
use function Amp\asyncCoroutine;
Loop::run(function () {
try {
$emitter = new Emitter;
$iterator = $emitter->iterate();
$generator = function (Emitter $emitter) {
yield $emitter->emit(new Delayed(500, 1));
yield $emitter->emit(new Delayed(1500, 2));
yield $emitter->emit(new Delayed(1000, 3));
yield $emitter->emit(new Delayed(2000, 4));
yield $emitter->emit(5);
yield $emitter->emit(6);
yield $emitter->emit(7);
yield $emitter->emit(new Delayed(2000, 8));
yield $emitter->emit(9);
yield $emitter->emit(10);
$emitter->complete();
};
asyncCoroutine($generator)($emitter);
while (yield $iterator->advance()) {
printf("Emitter emitted %d\n", $iterator->getCurrent());
yield new Delayed(500); // Listener consumption takes 500 ms.
}
} catch (\Exception $exception) {
printf("Exception: %s\n", $exception);
}
});
| #!/usr/bin/env php
<?php
require __DIR__ . '/../../vendor/autoload.php';
use Amp\Coroutine;
use Amp\Delayed;
use Amp\Emitter;
use Amp\Loop;
use Amp\Promise;
Loop::run(function () {
try {
$emitter = new Emitter;
$iterator = $emitter->iterate();
$generator = function (Emitter $emitter) {
yield $emitter->emit(new Delayed(500, 1));
yield $emitter->emit(new Delayed(1500, 2));
yield $emitter->emit(new Delayed(1000, 3));
yield $emitter->emit(new Delayed(2000, 4));
yield $emitter->emit(5);
yield $emitter->emit(6);
yield $emitter->emit(7);
yield $emitter->emit(new Delayed(2000, 8));
yield $emitter->emit(9);
yield $emitter->emit(10);
$emitter->complete();
};
Promise\rethrow(new Coroutine($generator($emitter)));
while (yield $iterator->advance()) {
printf("Emitter emitted %d\n", $iterator->getCurrent());
yield new Delayed(500); // Listener consumption takes 500 ms.
}
} catch (\Exception $exception) {
printf("Exception: %s\n", $exception);
}
});
|
Add missing semicolon to ExperimentManager | 'use strict';
// Trial Data service used to persist data for individual trials
angular.module('core').factory('ExperimentManager', ['TrialData', '$q', '$http', '$state',
function (TrialData, $q, $http, $state) {
var experimentManager = {
advanceSlide: function () {
TrialData.data.state.currentSlideIndex++;
$state.go(TrialData.data.schema[TrialData.data.state.currentSlideIndex].name);
},
masterReset: function () {
var deferred = $q.defer();
// Reset TrialData
TrialData.reset();
// Generate new session identifier and store it in TrialData
/* global UUID */
var sessionID = UUID.generate();
TrialData.data.metadata.session_number = sessionID;
// Get a new experiment setup from the backend
$http.get('/api/experiment-schemas/random')
.success(function (data) {
// Assign the media property from the ExperimentSchema we received as the media property on the TrialData
TrialData.data.media = data.media;
TrialData.data.schema = data.structure;
deferred.resolve();
})
.error(function () {
deferred.reject('An experiment schema could not be fetched from the server');
});
return deferred.promise;
}
};
return experimentManager;
}
]); | 'use strict';
// Trial Data service used to persist data for individual trials
angular.module('core').factory('ExperimentManager', ['TrialData', '$q', '$http', '$state',
function (TrialData, $q, $http, $state) {
var experimentManager = {
advanceSlide: function () {
TrialData.data.state.currentSlideIndex++;
$state.go(TrialData.data.schema[TrialData.data.state.currentSlideIndex].name)
},
masterReset: function () {
var deferred = $q.defer();
// Reset TrialData
TrialData.reset();
// Generate new session identifier and store it in TrialData
/* global UUID */
var sessionID = UUID.generate();
TrialData.data.metadata.session_number = sessionID;
// Get a new experiment setup from the backend
$http.get('/api/experiment-schemas/random')
.success(function (data) {
// Assign the media property from the ExperimentSchema we received as the media property on the TrialData
TrialData.data.media = data.media;
TrialData.data.schema = data.structure;
deferred.resolve();
})
.error(function () {
deferred.reject('An experiment schema could not be fetched from the server');
});
return deferred.promise;
}
};
return experimentManager;
}
]); |
Correct the Mistral lexer entry point | import setuptools
setuptools.setup(
name="discode-server",
version="0.0.1",
url="https://github.com/d0ugal/discode-server",
license="BSD",
description="Quick code review",
long_description="TODO",
author="Dougal Matthews",
author_email="[email protected]",
keywords='code review codereview discussion',
packages=setuptools.find_packages(),
include_package_date=True,
zip_safe=False,
install_requires=[
# Rwmove the following on the next Sanic release (and add Sanic).
'httptools>=0.0.9',
'uvloop>=0.5.3',
'ujson>=1.35',
'aiofiles>=0.3.0',
],
entry_points={
'console_scripts': [
'discode-server = discode_server.__main__:cli',
],
'pygments.lexers': [
'mistral = discode_server.lexers.mistral:MistralLexer',
]
},
classifier=[
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Topic :: Internet',
'Topic :: Utilities'
],
)
| import setuptools
setuptools.setup(
name="discode-server",
version="0.0.1",
url="https://github.com/d0ugal/discode-server",
license="BSD",
description="Quick code review",
long_description="TODO",
author="Dougal Matthews",
author_email="[email protected]",
keywords='code review codereview discussion',
packages=setuptools.find_packages(),
include_package_date=True,
zip_safe=False,
install_requires=[
# Rwmove the following on the next Sanic release (and add Sanic).
'httptools>=0.0.9',
'uvloop>=0.5.3',
'ujson>=1.35',
'aiofiles>=0.3.0',
],
entry_points={
'console_scripts': [
'discode-server = discode_server.__main__:cli',
],
'pygments.lexers': [
'mistral = discode_server.lexers.mistral.MistralLexer',
]
},
classifier=[
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Topic :: Internet',
'Topic :: Utilities'
],
)
|
Fix path issues and this scoping issues. | const tmp = require('tmp');
const fs = require('fs');
function isReactComponent(source = '') {
return source.indexOf('(_react.Component)') > -1;
}
function WebpackAccessibilityPlugin(options) {
this.createElement = options.createElement;
this.renderMarkup = options.renderMarkup;
}
WebpackAccessibilityPlugin.prototype.apply = (compiler) => {
compiler.plugin('emit', (compilation, callback) => {
// Explore each chunk (build output):
compilation.chunks.forEach((chunk) => {
// Start with application specific modules
chunk.modules
.filter(module => module.resource && module.resource.indexOf('node_modules') === -1 && module.resource.match(/\.(js|jsx)$/))
.map(module => module._source._value) // eslint-disable-line no-underscore-dangle
.filter(isReactComponent)
.forEach((source) => {
// Write to temporary file
tmp.file({ postfix: '.js', dir: `${__dirname}/tmp` }, (tmpErr, path, fd, cleanupCallback) => {
if (tmpErr) throw tmpErr;
fs.writeFile(path, source, (err) => {
if (err) throw err;
const component = require(path).default; // eslint-disable-line
const element = this.createElement(component);
const markup = this.renderMarkup(element);
// Run a11y report on markup!
console.log(markup); // eslint-disable-line
cleanupCallback();
});
});
}, this);
}, this);
callback();
});
};
module.exports = WebpackAccessibilityPlugin;
| const tmp = require('tmp');
const fs = require('fs');
function isReactComponent(source = '') {
return source.indexOf('(_react.Component)') > -1;
}
function WebpackAccessibilityPlugin(options) {
this.createElement = options.createElement;
this.renderMarkup = options.renderMarkup;
}
WebpackAccessibilityPlugin.prototype.apply = (compiler) => {
compiler.plugin('emit', (compilation, callback) => {
// Explore each chunk (build output):
compilation.chunks.forEach((chunk) => {
// Start with application specific modules
chunk.modules
.filter(module => module.resource && module.resource.indexOf('node_modules') === -1 && module.resource.match(/\.(js|jsx)$/))
.map(module => module._source._value)
.filter(isReactComponent)
.forEach((source) => {
// Write to temporary file
tmp.file({ postfix: '.js', dir: './tmp' }, (tmpErr, path, fd, cleanupCallback) => {
if (tmpErr) throw tmpErr;
const self = this;
fs.writeFile(path, source, (err) => {
if (err) throw err;
const component = require(path).default;
const element = self.createElement(component);
const markup = self.renderMarkup(element);
// Run a11y report on markup!
console.log(markup);
cleanupCallback();
});
});
}, this);
}, this);
callback();
});
};
module.exports = WebpackAccessibilityPlugin;
|
Fix strings route on test. | <?php
namespace Nobox\LazyStrings\Tests;
use Illuminate\Support\Facades\Config;
use Nobox\LazyStrings\LazyStrings;
use Orchestra\Testbench\TestCase;
class LazyStringsServiceProviderTest extends TestCase
{
public function setUp()
{
parent::setUp();
}
protected function getPackageProviders($app)
{
return ['Nobox\LazyStrings\LazyStringsServiceProvider'];
}
/**
* Define environment setup.
*
* @param \Illuminate\Foundation\Application $app
*
* @return void
*/
protected function getEnvironmentSetUp($app)
{
$app['config']->set('lazy-strings.csv-url', 'http://docs.google.com/spreadsheets/d/1V_cHt5Fe4x9XwVepvlXB39sqKXD3xs_QbM-NppkrE4A/export?format=csv');
$app['config']->set('lazy-strings.sheets', array('en' => 0));
$app['config']->set('lazy-strings.target-folder', 'lazy-strings');
$app['config']->set('lazy-strings.nested', true);
$app['config']->set('lazy-strings.strings-route', 'build-copy');
}
/**
* @test
*/
public function it_shows_strings_generation_view()
{
$this->call('GET', '/lazy/build-copy');
$this->assertResponseOk();
$this->assertViewHas('refreshedBy');
$this->assertViewHas('refreshedOn');
}
}
| <?php
namespace Nobox\LazyStrings\Tests;
use Illuminate\Support\Facades\Config;
use Nobox\LazyStrings\LazyStrings;
use Orchestra\Testbench\TestCase;
class LazyStringsServiceProviderTest extends TestCase
{
public function setUp()
{
parent::setUp();
}
protected function getPackageProviders($app)
{
return ['Nobox\LazyStrings\LazyStringsServiceProvider'];
}
/**
* Define environment setup.
*
* @param \Illuminate\Foundation\Application $app
*
* @return void
*/
protected function getEnvironmentSetUp($app)
{
$app['config']->set('lazy-strings.csv-url', 'http://docs.google.com/spreadsheets/d/1V_cHt5Fe4x9XwVepvlXB39sqKXD3xs_QbM-NppkrE4A/export?format=csv');
$app['config']->set('lazy-strings.sheets', array('en' => 0));
$app['config']->set('lazy-strings.target-folder', 'lazy-strings');
$app['config']->set('lazy-strings.nested', true);
$app['config']->set('lazy-strings.strings-route', 'lazy/build-copy');
}
/**
* @test
*/
public function it_shows_strings_generation_view()
{
$this->call('GET', '/lazy/build-copy');
$this->assertResponseOk();
$this->assertViewHas('refreshedBy');
$this->assertViewHas('refreshedOn');
}
}
|
Add handling for failed setup | class TestResult(object):
def __init__(self):
self.runCount = 0
self.errorCount = 0
self.setUpErrorCount = 0
def summary(self):
return "{} run, {} failed, {} setups failed".format(self.runCount,
self.errorCount,
self.setUpErrorCount)
def testStarted(self):
self.runCount += 1
def testFailed(self):
self.errorCount += 1
def setUpFailed(self):
self.setUpErrorCount += 1
class TestSuite(object):
def __init__(self):
self.tests = []
def add(self, test):
self.tests.append(test)
def run(self, result):
for test in self.tests:
test.run(result)
class TestCase(object):
def __init__(self, name):
self.name = name
def run(self, result):
result.testStarted()
try:
self.setUp()
except Exception as e:
result.setUpFailed()
try:
method = getattr(self, self.name)
method()
except:
result.testFailed()
self.tearDown()
return result
def setUp(self):
pass
def tearDown(self):
pass
class WasRun(TestCase):
def __init__(self, name):
self.log = ""
TestCase.__init__(self, name)
def setUp(self):
self.log += "setUp "
def tearDown(self):
self.log += "tearDown "
def testMethod(self):
self.log += "testMethod "
def testBrokenMethod(self):
raise Exception | class TestResult(object):
def __init__(self):
self.runCount = 0
self.errorCount = 0
def summary(self):
return "{} run, {} failed".format(self.runCount, self.errorCount)
def testStarted(self):
self.runCount += 1
def testFailed(self):
self.errorCount += 1
class TestSuite(object):
def __init__(self):
self.tests = []
def add(self, test):
self.tests.append(test)
def run(self, result):
for test in self.tests:
test.run(result)
class TestCase(object):
def __init__(self, name):
self.name = name
def run(self, result):
result.testStarted()
self.setUp()
try:
method = getattr(self, self.name)
method()
except:
result.testFailed()
self.tearDown()
return result
def setUp(self):
pass
def tearDown(self):
pass
class WasRun(TestCase):
def __init__(self, name):
self.log = ""
TestCase.__init__(self, name)
def setUp(self):
self.log += "setUp "
def tearDown(self):
self.log += "tearDown "
def testMethod(self):
self.log += "testMethod "
def testBrokenMethod(self):
raise Exception |
Fix php5.5 bug with unsuported boolean or in argument default | <?php
namespace Sandhje\Spanner\Filesystem;
/**
* Filesystem wrapper
*
* @author Sandhje
*
*/
class Filesystem
{
/**
* Equals PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME
*
* @var int
*/
const PATHINFO_ALL = 15;
/**
* is_file wrapper
*
* @param string $filename
*/
public function is_file($filename)
{
return is_file($filename);
}
/**
* is_dir wrapper
*
* @param string $dir
*/
public function is_dir($directory)
{
return is_dir($directory);
}
/**
* is_readable wrapper
*
* @param string $filename
* @return boolean
*/
public function is_readable($filename)
{
return is_readable($filename);
}
/**
* pathinfo wrapper
*
* @param string $path
* @param int $options
* @return mixed
*/
public function pathinfo($path, $options = self::PATHINFO_ALL)
{
return pathinfo($path, $options);
}
/**
* Load file from filesystem
*
* @param string $filename
* @return string
*/
public function load($filename)
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if($ext === "php") {
return (include $filename);
} else {
return file_get_contents($filename);
}
}
}
?> | <?php
namespace Sandhje\Spanner\Filesystem;
/**
* Filesystem wrapper
*
* @author Sandhje
*
*/
class Filesystem
{
/**
* is_file wrapper
*
* @param string $filename
*/
public function is_file($filename)
{
return is_file($filename);
}
/**
* is_dir wrapper
*
* @param string $dir
*/
public function is_dir($directory)
{
return is_dir($directory);
}
/**
* is_readable wrapper
*
* @param string $filename
* @return boolean
*/
public function is_readable($filename)
{
return is_readable($filename);
}
/**
* pathinfo wrapper
*
* @param string $path
* @param int $options
* @return mixed
*/
public function pathinfo($path, $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME)
{
return pathinfo($path, $options);
}
/**
* Load file from filesystem
*
* @param string $filename
* @return string
*/
public function load($filename)
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if($ext === "php") {
return (include $filename);
} else {
return file_get_contents($filename);
}
}
}
?> |
Break infix coordination only if there is one | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The infix coordination class
class InfixCoordination:
# Constructor for the infix coordination
def __init__(self):
self.has_infix_coordination = False
self.slice_point = -1
self.subtree_list = []
# Break the tree
def break_tree(self, tree):
self.has_infix_coordination = False
self.slice_point = -1
self.subtree_list = []
self.parse_tree(tree)
print "Infix Coordination: " + str(self.has_infix_coordination)
print self.slice_point
print self.subtree_list
if self.has_infix_coordination:
result_string = ' '.join(self.subtree_list[:self.slice_point-1]) +\
'. ' + ' '.join(self.subtree_list[self.slice_point:])
else:
result_string = ' '.join(tree.leaves())
print result_string
return result_string
# Parse the tree
def parse_tree(self, tree):
if type(tree) == Tree:
sentence_root = tree[0]
if type(sentence_root) == Tree:
if sentence_root.label() == "S":
print "Valid Tree"
counter = 0
for node in sentence_root:
counter += 1
self.subtree_list.append(' '.join(node.leaves()))
if type(node) == Tree:
if node.label() == "CC":
self.has_infix_coordination |= True
self.slice_point = counter
| __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The infix coordination class
class InfixCoordination:
# Constructor for the infix coordination
def __init__(self):
self.has_infix_coordination = False
self.slice_point = -1
self.subtree_list = []
# Break the tree
def break_tree(self, tree):
self.has_infix_coordination = False
self.slice_point = -1
self.subtree_list = []
self.parse_tree(tree)
print "Infix Coordination: " + str(self.has_infix_coordination)
print self.slice_point
print self.subtree_list
result_string = ' '.join(self.subtree_list[:self.slice_point-1]) +\
'. ' + ' '.join(self.subtree_list[self.slice_point:])
print result_string
return result_string
# Parse the tree
def parse_tree(self, tree):
if type(tree) == Tree:
sentence_root = tree[0]
if type(sentence_root) == Tree:
if sentence_root.label() == "S":
print "Valid Tree"
counter = 0
for node in sentence_root:
counter += 1
self.subtree_list.append(' '.join(node.leaves()))
if type(node) == Tree:
if node.label() == "CC":
self.has_infix_coordination |= True
self.slice_point = counter
|
Correct set policy on bag.
Had been missing create constraint. | """
Establish the data structures representing the bags and recipes needed
by this plugin.
"""
store_contents = {}
store_structure = {}
store_contents['_default_errors'] = [
'src/_errors/index.recipe',
]
store_structure['recipes'] = {}
store_structure['bags'] = {}
store_structure['recipes']['_errors'] = {
'desc': 'Pretty Errors Error Tiddlers',
'recipe': [
('_default_errors', ''),
('_errors', ''),
],
'policy': {
'read': [],
'write': ['R:ADMIN'],
'manage': ['R:ADMIN'],
'delete': ['R:ADMIN'],
'owner': 'administractor',
'create': ['R:ADMIN'],
},
}
store_structure['bags']['_default_errors'] = {
'desc': 'Default error tiddlers for Pretty Errors',
'policy': {
'read': [],
'write': ['NONE'],
'create': ['NONE'],
'delete': ['NONE'],
'manage': ['NONE'],
'accept': ['NONE'],
'owner': 'administrator',
},
}
store_structure['bags']['_errors'] = {
'desc': 'Override error tiddlers for Pretty Errors',
'policy': {
'read': [],
'write': ['R:ADMIN'],
'create': ['R:ADMIN'],
'delete': ['R:ADMIN'],
'manage': ['R:ADMIN'],
'accept': ['NONE'],
'owner': 'administrator',
},
}
instance_config = {
'system_plugins': ['tiddlywebplugins.prettyerror'],
}
|
store_contents = {}
store_structure = {}
store_contents['_default_errors'] = [
'src/_errors/index.recipe',
]
store_structure['recipes'] = {}
store_structure['bags'] = {}
store_structure['recipes']['_errors'] = {
'desc': 'Pretty Errors Error Tiddlers',
'recipe': [
('_default_errors', ''),
('_errors', ''),
],
'policy': {
'read': [],
'write': ['R:ADMIN'],
'manage': ['R:ADMIN'],
'delete': ['R:ADMIN'],
'owner': 'administractor',
'write': ['R:ADMIN'],
},
}
store_structure['bags']['_default_errors'] = {
'desc': 'Default error tiddlers for Pretty Errors',
'policy': {
'read': [],
'write': ['NONE'],
'create': ['NONE'],
'delete': ['NONE'],
'manage': ['NONE'],
'accept': ['NONE'],
'owner': 'administrator',
},
}
store_structure['bags']['_errors'] = {
'desc': 'Override error tiddlers for Pretty Errors',
'policy': {
'read': [],
'write': ['R:ADMIN'],
'create': ['R:ADMIN'],
'delete': ['R:ADMIN'],
'manage': ['R:ADMIN'],
'accept': ['NONE'],
'owner': 'administrator',
},
}
instance_config = {
'system_plugins': ['tiddlywebplugins.prettyerror'],
}
|
Add github token to model | from bson.objectid import ObjectId
from humbledb import Mongo, Document
class ClassProperty (property):
"""Subclass property to make classmethod properties possible"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
class User(Document):
username = ''
password = ''
email = ''
github_access_token = ''
config_database = 'mirrit'
config_collection = 'users'
@property
def id(self):
return unicode(self._id)
@property
def user_id(self):
return unicode(self._id)
@staticmethod
def get_by_login(cls, username, password):
with Mongo:
return cls.find({'username': username,
'password': password})
def persist(self):
with Mongo:
if self._id:
super(User, self).__self_class__.update(
{'_id': self._id}, self, w=1)
else:
super(User, self).__self_class__.insert(self, w=1)
class Wrapper(object):
def get(self, id):
with Mongo:
return User.find({'_id': ObjectId(id)})
wrapper = Wrapper()
User.query = wrapper
| from bson.objectid import ObjectId
from humbledb import Mongo, Document
class ClassProperty (property):
"""Subclass property to make classmethod properties possible"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
class User(Document):
username = ''
password = ''
email = ''
config_database = 'mirrit'
config_collection = 'users'
@property
def id(self):
return unicode(self._id)
@property
def user_id(self):
return unicode(self._id)
@staticmethod
def get_by_login(cls, username, password):
with Mongo:
return cls.find({'username': username,
'password': password})
def persist(self):
with Mongo:
if self._id:
super(User, self).__self_class__.update(
{'_id': self._id}, self, w=1)
else:
super(User, self).__self_class__.insert(self, w=1)
class Wrapper(object):
def get(self, id):
with Mongo:
return User.find({'_id': ObjectId(id)})
wrapper = Wrapper()
User.query = wrapper
|
Change read_chrom_sizes to read from a FAIDX index if available | import os
from wrappers import bowtie2, picard, samtools
def create_reference_indices(ref_fn):
'''
For a given reference FASTA file, generate several indices.
'''
bowtie2.build(ref_fn)
samtools.faidx_index(ref_fn)
picard.create_sequence_dictionary(ref_fn)
def read_chrom_sizes(reference_assembly_fn):
'''
Iterate through a FASTA file to find the length of each chromosome. If a
FAIDX index is available, it will read the lengths from there.
'''
chrom_sizes = dict()
if os.path.exists(reference_assembly_fn + '.fai'):
with open(reference_assembly_fn + '.fai') as f:
for line in f:
chromosome, size = line.strip().split('\t')[:2]
chrom_sizes[chromosome] = int(size)
else:
last_chromosome = None
with open(reference_assembly_fn) as f:
for line in f:
if line.startswith('>'):
last_chromosome = line.split('>')[1].strip()
chrom_sizes[last_chromosome] = 0
else:
chrom_sizes[last_chromosome] += len(line.strip())
return chrom_sizes
def read_chrom_sizes_from_file(chrom_sizes_fn):
'''
Read chromosome sizes from a UCSC chrom_sizes file.
'''
chrom_sizes = dict()
with open(chrom_sizes_fn) as f:
for line in f:
chromosome, size = line.strip().split()
chrom_sizes[chromosome] = int(size)
return chrom_sizes
| from wrappers import bowtie2, picard, samtools
def create_reference_indices(ref_fn):
'''
For a given reference FASTA file, generate several indices.
'''
bowtie2.build(ref_fn)
samtools.faidx_index(ref_fn)
picard.create_sequence_dictionary(ref_fn)
def read_chrom_sizes(reference_assembly_fn):
'''
Iterate through a FASTA file to find the length of each chromosome.
'''
chrom_sizes = dict()
last_chromosome = None
with open(reference_assembly_fn) as f:
for line in f:
if line.startswith('>'):
last_chromosome = line.split('>')[1].strip()
chrom_sizes[last_chromosome] = 0
else:
chrom_sizes[last_chromosome] += len(line.strip())
return chrom_sizes
def read_chrom_sizes_from_file(chrom_sizes_fn):
'''
Read chromosome sizes from a UCSC chrom_sizes file.
'''
chrom_sizes = dict()
with open(chrom_sizes_fn) as f:
for line in f:
chromosome, size = line.strip().split()
chrom_sizes[chromosome] = int(size)
return chrom_sizes
|
Use the local createQueryBuilder with alias | <?php
namespace NS\SentinelBundle\Repository;
use NS\SecurityBundle\Doctrine\SecuredEntityRepository;
use NS\UtilBundle\Service\AjaxAutocompleteRepositoryInterface;
/**
* Description of Common
*
* @author gnat
*/
class Common extends SecuredEntityRepository implements AjaxAutocompleteRepositoryInterface
{
public function getAllSecuredQueryBuilder($alias = 'o')
{
return $this->secure($this->createQueryBuilder($alias)->orderBy("$alias.name","ASC"));
}
public function getForAutoComplete($fields, array $value, $limit)
{
$alias = 'd';
$qb = $this->createQueryBuilder($alias)->setMaxResults($limit);
if(!empty($value) && $value['value'][0]=='*')
return $qb->getQuery();
if(!empty($value))
{
if(is_array($fields))
{
foreach ($fields as $f)
{
$field = "$alias.$f";
$qb->addOrderBy($field)
->orWhere("$field LIKE :param")->setParameter('param',$value['value'].'%');
}
}
else
{
$field = "$alias.$fields";
$qb->orderBy($field)->andWhere("$field LIKE :param")->setParameter('param',$value['value'].'%');
}
}
return $qb->getQuery();
}
}
| <?php
namespace NS\SentinelBundle\Repository;
use NS\SecurityBundle\Doctrine\SecuredEntityRepository;
use NS\UtilBundle\Service\AjaxAutocompleteRepositoryInterface;
/**
* Description of Common
*
* @author gnat
*/
class Common extends SecuredEntityRepository implements AjaxAutocompleteRepositoryInterface
{
public function getAllSecuredQueryBuilder($alias = 'o')
{
return $this->secure($this->createQueryBuilder($alias)->orderBy("$alias.name","ASC"));
}
public function getForAutoComplete($fields, array $value, $limit)
{
$alias = 'd';
$qb = $this->_em->createQueryBuilder()
->select($alias)
->from($this->getClassName(), $alias)
->setMaxResults($limit);
if(!empty($value) && $value['value'][0]=='*')
return $qb->getQuery();
if(!empty($value))
{
if(is_array($fields))
{
foreach ($fields as $f)
{
$field = "$alias.$f";
$qb->addOrderBy($field)
->orWhere("$field LIKE :param")->setParameter('param',$value['value'].'%');
}
}
else
{
$field = "$alias.$fields";
$qb->orderBy($field)->andWhere("$field LIKE :param")->setParameter('param',$value['value'].'%');
}
}
return $qb->getQuery();
}
}
|
Use double quotes on help string | from flask import request
from flask_restful import Resource, Api, abort, reqparse
from .models import db, Comment, Lecture
api = Api()
class CommentListResource(Resource):
def get(self, lecture_id):
db_lecture = Lecture.query.filter(Lecture.id == lecture_id).first()
if not db_lecture:
abort(404, message="Lecture {} does not exist".format(lecture_id))
db_comments = Comment.query.filter(Comment.lecture_id == lecture_id)
comments = [
{'id': c.id, 'content': c.content}
for c in db_comments
]
return {
'comments': comments
}
def post(self, lecture_id):
lecture = Lecture.query.filter(Lecture.id == lecture_id).first()
if not lecture:
abort(404, message="Lecture {} does not exist".format(lecture_id))
parser = reqparse.RequestParser()
parser.add_argument('data', help="Text content of comment")
args = parser.parse_args()
if not args.data:
abort(400, message="Comment has no data parameter")
content = args.data
comment = Comment(content, lecture)
db.session.add(comment)
db.session.commit()
return {
'id': comment.id
}
api.add_resource(CommentListResource, '/api/0/lectures/<lecture_id>/comments')
| from flask import request
from flask_restful import Resource, Api, abort, reqparse
from .models import db, Comment, Lecture
api = Api()
class CommentListResource(Resource):
def get(self, lecture_id):
db_lecture = Lecture.query.filter(Lecture.id == lecture_id).first()
if not db_lecture:
abort(404, message="Lecture {} does not exist".format(lecture_id))
db_comments = Comment.query.filter(Comment.lecture_id == lecture_id)
comments = [
{'id': c.id, 'content': c.content}
for c in db_comments
]
return {
'comments': comments
}
def post(self, lecture_id):
lecture = Lecture.query.filter(Lecture.id == lecture_id).first()
if not lecture:
abort(404, message="Lecture {} does not exist".format(lecture_id))
parser = reqparse.RequestParser()
parser.add_argument('data', help='Text content of comment')
args = parser.parse_args()
if not args.data:
abort(400, message="Comment has no data parameter")
content = args.data
comment = Comment(content, lecture)
db.session.add(comment)
db.session.commit()
return {
'id': comment.id
}
api.add_resource(CommentListResource, '/api/0/lectures/<lecture_id>/comments')
|
Add response object to the reject, too. | var Promise = require('bluebird'),
request = require('request');
function rp(options) {
var statusCodes = {
'GET' : [200],
'HEAD' : [200],
'PUT' : [200, 201],
'POST' : [200, 201],
'DELETE' : [200, 201]
}, c = {simple: true}, i;
if (typeof options === 'string') {
c.uri = options;
c.method = 'GET';
}
if (typeof options === 'object') {
for (i in options) {
if (options.hasOwnProperty(i)) {
c[i] = options[i];
}
}
}
c.method = c.method || 'GET';
return new Promise(function (resolve, reject) {
request(c, function (error, response, body) {
if (error) {
reject({
error: error,
options: c,
response: response
});
} else if (c.simple && (statusCodes[c.method].indexOf(response.statusCode) === -1)) {
reject({
error: body,
options: c,
response: response,
statusCode: response.statusCode
});
} else {
if (c.transform && typeof c.transform === 'function') {
resolve(c.transform(body));
} else {
resolve(body);
}
}
});
});
}
module.exports = function (a) {
if (a) return rp(a);
};
| var Promise = require('bluebird'),
request = require('request');
function rp(options) {
var statusCodes = {
'GET' : [200],
'HEAD' : [200],
'PUT' : [200, 201],
'POST' : [200, 201],
'DELETE' : [200, 201]
}, c = {simple: true}, i;
if (typeof options === 'string') {
c.uri = options;
c.method = 'GET';
}
if (typeof options === 'object') {
for (i in options) {
if (options.hasOwnProperty(i)) {
c[i] = options[i];
}
}
}
c.method = c.method || 'GET';
return new Promise(function (resolve, reject) {
request(c, function (error, response, body) {
if (error) {
reject({
error: error,
options: c
});
} else if (c.simple && (statusCodes[c.method].indexOf(response.statusCode) === -1)) {
reject({
error: body,
options: c,
statusCode: response.statusCode
});
} else {
if (c.transform && typeof c.transform === 'function') {
resolve(c.transform(body));
} else {
resolve(body);
}
}
});
});
}
module.exports = function (a) {
if (a) return rp(a);
};
|
Use `html.escape` instead of the deprecated `cgi.escape`. | # -*- coding: utf-8 -*-
"""
byceps.blueprints.board.formatting
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from html import escape
import bbcode
try:
from .smileys import get_smileys
except ImportError:
get_smileys = lambda: []
try:
from .smileys import replace_smileys
except ImportError:
replace_smileys = lambda x: x
def create_parser():
"""Create a customized BBcode parser."""
parser = bbcode.Parser(replace_cosmetic=False)
# Replace image tags.
def render_image(name, value, options, parent, context):
return '<img src="{}"/>'.format(value)
parser.add_formatter('img', render_image, replace_links=False)
# Render quotes with optional author.
def render_quote(name, value, options, parent, context):
intro = ''
if 'author' in options:
author = escape(options['author'])
intro = '<p class="quote-intro"><cite>{}</cite> schrieb:</p>\n' \
.format(author)
return '{}<blockquote>{}</blockquote>'.format(intro, value)
parser.add_formatter('quote', render_quote, strip=True)
return parser
PARSER = create_parser()
def render_html(value):
"""Render text as HTML, interpreting BBcode."""
html = PARSER.format(value)
html = replace_smileys(html)
return html
| # -*- coding: utf-8 -*-
"""
byceps.blueprints.board.formatting
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from cgi import escape
import bbcode
try:
from .smileys import get_smileys
except ImportError:
get_smileys = lambda: []
try:
from .smileys import replace_smileys
except ImportError:
replace_smileys = lambda x: x
def create_parser():
"""Create a customized BBcode parser."""
parser = bbcode.Parser(replace_cosmetic=False)
# Replace image tags.
def render_image(name, value, options, parent, context):
return '<img src="{}"/>'.format(value)
parser.add_formatter('img', render_image, replace_links=False)
# Render quotes with optional author.
def render_quote(name, value, options, parent, context):
intro = ''
if 'author' in options:
author = escape(options['author'])
intro = '<p class="quote-intro"><cite>{}</cite> schrieb:</p>\n' \
.format(author)
return '{}<blockquote>{}</blockquote>'.format(intro, value)
parser.add_formatter('quote', render_quote, strip=True)
return parser
PARSER = create_parser()
def render_html(value):
"""Render text as HTML, interpreting BBcode."""
html = PARSER.format(value)
html = replace_smileys(html)
return html
|
Use ColorSchemeunit new run with package API
Re: https://github.com/gerardroche/sublime-color-scheme-unit/issues/18
The new API allows to run with package name so Unittesting doesn't need
to open any files before running the tests.
I also added an async parameter which allows to run the tests in non
async mode and get the result of the tests, True for pass and False for
fail. This allows UnitTesting to handle printing the OK, FAILED and DONE
messsages. | import sublime
from sublime_plugin import ApplicationCommand
from .mixin import UnitTestingMixin
from .const import DONE_MESSAGE
try:
from ColorSchemeUnit.lib.runner import ColorSchemeUnit
except Exception:
print('ColorSchemeUnit runner could not be imported')
class UnitTestingColorSchemeCommand(ApplicationCommand, UnitTestingMixin):
def run(self, package=None, **kargs):
if not package:
return
window = sublime.active_window()
settings = self.load_unittesting_settings(package, **kargs)
stream = self.load_stream(package, settings["output"])
tests = sublime.find_resources("color_scheme_test*")
tests = [t for t in tests if t.startswith("Packages/%s/" % package)]
if not tests:
stream.write("ERROR: No syntax_test files are found in %s!" % package)
stream.write("\n")
stream.write(DONE_MESSAGE)
stream.close()
return
# trigger "Start reading output"
stream.write("Running ColorSchemeUnit\n")
stream.flush()
result = ColorSchemeUnit(window).run(output=stream, package=package, async=False)
if result:
stream.write('\n')
stream.write("OK.\n")
else:
stream.write('\n')
stream.write("FAILED.\n")
stream.write("\n")
stream.write(DONE_MESSAGE)
stream.close()
| import sublime
from sublime_plugin import ApplicationCommand
from .mixin import UnitTestingMixin
from .const import DONE_MESSAGE
try:
from ColorSchemeUnit.lib.runner import ColorSchemeUnit
except Exception:
print('ColorSchemeUnit runner could not be imported')
class UnitTestingColorSchemeCommand(ApplicationCommand, UnitTestingMixin):
def run(self, package=None, **kargs):
if not package:
return
window = sublime.active_window()
settings = self.load_unittesting_settings(package, **kargs)
stream = self.load_stream(package, settings["output"])
# Make sure at least one file from the
# package opened for ColorSchemeUnit.
tests = sublime.find_resources("color_scheme_test*")
tests = [t for t in tests if t.startswith("Packages/%s/" % package)]
if not tests:
stream.write("ERROR: No syntax_test files are found in %s!" % package)
stream.write("\n")
stream.write(DONE_MESSAGE)
stream.close()
return
# trigger "Start reading output"
stream.write("Running ColorSchemeUnit\n")
stream.flush()
view = window.open_file(sublime.packages_path().rstrip('Packages') + tests[0])
view.set_scratch(True)
ColorSchemeUnit(window).run(output=stream)
|
Include url message when fail to run urlparser | from modules import *
import re
import urllib2
import traceback
try:
import simplejson as json
except ImportError:
import json
from unidecode import unidecode
from twitter import Twitter
from bitly import Bitly
from youtube import Youtube
class Urlparser(Module):
"""Checks incoming messages for possible urls. If a url is found then
route the url to a corresponding module to handle.
"""
def __init__(self, *args, **kwargs):
"""Constructor."""
Module.__init__(self, kwargs=kwargs)
self.url_patterns = [
Twitter,
Youtube,
Bitly,
]
self.url_pattern = re.compile("http://(.*?)")
def _register_events(self):
self.add_event('pubmsg', 'parse_message')
def parse_message(self, event):
nick = event['nick']
# make sure the message contains a url before checking
# the other handlers patterns
try:
for handler in self.url_patterns:
m = handler.pattern.search(event['message'])
if m:
handler_instance = handler()
msg = handler_instance.handle(event=event, match=m)
if msg:
self.server.privmsg(event['target'], msg.encode('ascii', 'ignore'))
break
except:
print "<<Error>> in Urlparser (%s)" % (event['message'])
print traceback.print_exc()
| from modules import *
import re
import urllib2
import traceback
try:
import simplejson as json
except ImportError:
import json
from unidecode import unidecode
from twitter import Twitter
from bitly import Bitly
from youtube import Youtube
class Urlparser(Module):
"""Checks incoming messages for possible urls. If a url is found then
route the url to a corresponding module to handle.
"""
def __init__(self, *args, **kwargs):
"""Constructor."""
Module.__init__(self, kwargs=kwargs)
self.url_patterns = [
Twitter,
Youtube,
Bitly,
]
self.url_pattern = re.compile("http://(.*?)")
def _register_events(self):
self.add_event('pubmsg', 'parse_message')
def parse_message(self, event):
nick = event['nick']
# make sure the message contains a url before checking
# the other handlers patterns
try:
for handler in self.url_patterns:
m = handler.pattern.search(event['message'])
if m:
handler_instance = handler()
msg = handler_instance.handle(event=event, match=m)
if msg:
self.server.privmsg(event['target'], msg.encode('ascii', 'ignore'))
break
except:
print "<<Error>> in Urlparser"
print traceback.print_exc()
|
Print stack trace when initialization fails | package org.galibier.messaging.benchmark.zookeeper;
import com.netflix.curator.framework.CuratorFramework;
import com.netflix.curator.framework.CuratorFrameworkFactory;
import com.netflix.curator.retry.RetryOneTime;
import org.apache.zookeeper.KeeperException;
import org.galibier.messaging.benchmark.Message;
import org.galibier.messaging.benchmark.Operation;
public abstract class ZKOperation implements Operation {
protected final CuratorFramework client;
protected final String path;
public ZKOperation(String host, String path) {
this.client = CuratorFrameworkFactory.newClient(host, new RetryOneTime(100));
this.path = path;
}
@Override
public void initialize() {
client.start();
try {
client.create().forPath(path, Message.getDefault());
} catch (KeeperException.NodeExistsException e) {
// ignore
} catch (Exception e) {
e.printStackTrace(System.err);
System.out.println("Initialization failed");
System.exit(1);
}
}
@Override
public void terminate() {
try {
client.delete().forPath(path);
} catch (KeeperException.NoNodeException e) {
// ignore
} catch (Exception e) {
// ignore
} finally {
client.close();
}
}
}
| package org.galibier.messaging.benchmark.zookeeper;
import com.netflix.curator.framework.CuratorFramework;
import com.netflix.curator.framework.CuratorFrameworkFactory;
import com.netflix.curator.retry.RetryOneTime;
import org.apache.zookeeper.KeeperException;
import org.galibier.messaging.benchmark.Message;
import org.galibier.messaging.benchmark.Operation;
public abstract class ZKOperation implements Operation {
protected final CuratorFramework client;
protected final String path;
public ZKOperation(String host, String path) {
this.client = CuratorFrameworkFactory.newClient(host, new RetryOneTime(100));
this.path = path;
}
@Override
public void initialize() {
client.start();
try {
client.create().forPath(path, Message.getDefault());
} catch (KeeperException.NodeExistsException e) {
// ignore
} catch (Exception e) {
System.out.println("Initialization failed");
System.exit(1);
}
}
@Override
public void terminate() {
try {
client.delete().forPath(path);
} catch (KeeperException.NoNodeException e) {
// ignore
} catch (Exception e) {
// ignore
} finally {
client.close();
}
}
}
|
Fix java generatino of DAOSink. | /**
* @license
* Copyright 2016 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.
*/
foam.CLASS({
package: 'foam.dao',
name: 'DAOProperty',
extends: 'FObjectProperty',
documentation: 'Property for storing a reference to a DAO.',
requires: [ 'foam.dao.ProxyDAO' ],
properties: [
{
name: 'view',
value: {class: 'foam.comics.InlineBrowserView'},
},
['of', 'foam.dao.DAO']
],
methods: [
function installInProto(proto) {
this.SUPER(proto);
var name = this.name;
var prop = this;
Object.defineProperty(proto, name + '$proxy', {
get: function daoProxyGetter() {
var proxy = prop.ProxyDAO.create({delegate: this[name]});
this[name + '$proxy'] = proxy;
this.sub('propertyChange', name, function(_, __, ___, s) {
proxy.delegate = s.get();
});
return proxy;
},
configurable: true
});
}
]
});
| /**
* @license
* Copyright 2016 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.
*/
foam.CLASS({
package: 'foam.dao',
name: 'DAOProperty',
extends: 'Property',
documentation: 'Property for storing a reference to a DAO.',
requires: [ 'foam.dao.ProxyDAO' ],
properties: [
{
name: 'view',
value: {class: 'foam.comics.InlineBrowserView'},
}
],
methods: [
function installInProto(proto) {
this.SUPER(proto);
var name = this.name;
var prop = this;
Object.defineProperty(proto, name + '$proxy', {
get: function daoProxyGetter() {
var proxy = prop.ProxyDAO.create({delegate: this[name]});
this[name + '$proxy'] = proxy;
this.sub('propertyChange', name, function(_, __, ___, s) {
proxy.delegate = s.get();
});
return proxy;
},
configurable: true
});
}
]
});
|
Remove debug kit from unit tests | <?php
namespace App\Test\TestCase;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\TestSuite\TestCase;
class AppTest extends TestCase
{
/**
* @dataProvider pluginProvider
*/
public function testLoadedPlugins($plugin, $config)
{
if (empty($config)) {
$this->assertTrue(Plugin::loaded($plugin), "Plugin $plugin is not loaded");
} else {
$enabled = false;
switch (gettype($config)) {
case 'string':
$enabled = Configure::read($config);
break;
case 'array':
foreach ($config as $conf) {
if (!Configure::read($conf)) {
$enabled = false;
break;
}
$enabled = true;
}
break;
}
$message = "Plugin $plugin is not loaded but [" . implode(' or ', (array)$config) . "] is true";
$this->assertEquals($enabled, Plugin::loaded($plugin), $message);
}
}
public function pluginProvider()
{
return [
['ADmad/JwtAuth', 'API.auth'],
['AdminLTE', null],
['Alt3/Swagger', ['API.auth', 'Swagger.crawl']],
['AuditStash', null],
['Burzum/FileStorage', null],
['CakeDC/Users', null],
['Crud', null],
['CsvMigrations', null],
['DatabaseLog', null],
['Groups', null],
['Menu', null],
['Migrations', null],
['Qobo/Utils', null],
['RolesCapabilities', null],
['Search', null],
['Translations', null],
];
}
}
| <?php
namespace App\Test\TestCase;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\TestSuite\TestCase;
class AppTest extends TestCase
{
/**
* @dataProvider pluginProvider
*/
public function testLoadedPlugins($plugin, $config)
{
if (empty($config)) {
$this->assertTrue(Plugin::loaded($plugin), "Plugin $plugin is not loaded");
} else {
$enabled = false;
switch (gettype($config)) {
case 'string':
$enabled = Configure::read($config);
break;
case 'array':
foreach ($config as $conf) {
if (!Configure::read($conf)) {
$enabled = false;
break;
}
$enabled = true;
}
break;
}
$message = "Plugin $plugin is not loaded but [" . implode(' or ', (array)$config) . "] is true";
$this->assertEquals($enabled, Plugin::loaded($plugin), $message);
}
}
public function pluginProvider()
{
return [
['ADmad/JwtAuth', 'API.auth'],
['AdminLTE', null],
['Alt3/Swagger', ['API.auth', 'Swagger.crawl']],
['AuditStash', null],
['Burzum/FileStorage', null],
['CakeDC/Users', null],
['Crud', null],
['CsvMigrations', null],
['DatabaseLog', null],
['DebugKit', 'debug'],
['Groups', null],
['Menu', null],
['Migrations', null],
['Qobo/Utils', null],
['RolesCapabilities', null],
['Search', null],
['Translations', null],
];
}
}
|
Fix problem with ws host:port mismatch on heroku | var Reflux = require('reflux');
var config = require('./../../../config');
var ApiActions = require('./../actions/ApiActions');
var buffer = [];
var ws;
var ApiStore = Reflux.createStore({
init: function () {
ws = new WebSocket('ws://' + window.document.location.host);
ws.onmessage = function (event) {
console.log(JSON.parse(event.data));
ApiStore.trigger(JSON.parse(event.data));
};
ws.onopen = function () {
buffer.forEach(function (request) {
ws.send(JSON.stringify(request));
});
};
this.listenTo(ApiActions.get, this.get);
},
get: function (id, params) {
if (ws.readyState !== WebSocket.OPEN) {
buffer.push({
id: id,
params: params || {}
});
return;
}
ws.send(JSON.stringify({
id: id,
params: params || {}
}));
}
});
module.exports = ApiStore; | var Reflux = require('reflux');
var config = require('./../../../config');
var ApiActions = require('./../actions/ApiActions');
var buffer = [];
var ws;
var ApiStore = Reflux.createStore({
init: function () {
ws = new WebSocket('ws://' + config.host + ':' + config.port);
ws.onmessage = function (event) {
console.log(JSON.parse(event.data));
ApiStore.trigger(JSON.parse(event.data));
};
ws.onopen = function () {
buffer.forEach(function (request) {
ws.send(JSON.stringify(request));
});
};
this.listenTo(ApiActions.get, this.get);
},
get: function (id, params) {
if (ws.readyState !== WebSocket.OPEN) {
buffer.push({
id: id,
params: params || {}
});
return;
}
ws.send(JSON.stringify({
id: id,
params: params || {}
}));
}
});
module.exports = ApiStore; |
Stop inserting semicolons during concat | module.exports = function(grunt) {
grunt.initConfig({
concat: {
dist: {
src: ['lib/osteo.js', 'lib/*.js'],
dest: 'osteo.js'
}
},
jshint: {
options: {
jshintrc: true
},
beforeconcat: ['lib/*.js'],
afterconcat: ['osteo.js']
},
uglify: {
options: {
report: 'min'
},
dist: {
src: 'osteo.js',
dest: 'osteo.min.js'
}
},
mocha: {
src: ['test/test.html'],
options: {
bail: true,
log: true,
run: true,
mocha: {
ignoreLeaks: true
}
}
},
watch: {
files: ['lib/*.js', 'test/*.js'],
tasks: ['concat', 'jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-mocha');
grunt.registerTask('test', ['concat', 'mocha']);
grunt.registerTask('default', ['test']);
grunt.registerTask('release', ['concat', 'mocha', 'uglify']);
};
| module.exports = function(grunt) {
grunt.initConfig({
concat: {
options: {
separator: ';',
},
dist: {
src: ['lib/osteo.js', 'lib/*.js'],
dest: 'osteo.js'
}
},
jshint: {
options: {
jshintrc: true
},
beforeconcat: ['lib/*.js'],
afterconcat: ['osteo.js']
},
uglify: {
options: {
report: 'min'
},
dist: {
src: 'osteo.js',
dest: 'osteo.min.js'
}
},
mocha: {
src: ['test/test.html'],
options: {
bail: true,
log: true,
run: true,
mocha: {
ignoreLeaks: true
}
}
},
watch: {
files: ['lib/*.js', 'test/*.js'],
tasks: ['concat', 'jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-mocha');
grunt.registerTask('test', ['concat', 'mocha']);
grunt.registerTask('default', ['test']);
grunt.registerTask('release', ['concat', 'mocha', 'uglify']);
};
|
psqcppconan: Allow the use of .exe | # /ciscripts/check/psqcppconan/check.py
#
# Run tests and static analysis checks on a polysquare conan c++ project.
#
# See /LICENCE.md for Copyright information
"""Run tests and static analysis checks on a polysquare conan c++ project."""
import argparse
import os
def run(cont, util, shell, argv=None):
"""Run checks on this conan project."""
parser = argparse.ArgumentParser(description="""Run conan checks""")
parser.add_argument("--run-test-binaries",
nargs="*",
type=str,
help="""Files relative to the build dir to run""")
result, remainder = parser.parse_known_args(argv or list())
conan_check_script = "check/conan/check.py"
conan_check = cont.fetch_and_import(conan_check_script)
def _during_test(cont, executor, util, build):
"""Run the specified test binaries with the --tap switch.
We then pipe the output into tap-mocha-reporter.
"""
del build
for binary in result.run_test_binaries or list():
if not os.path.exists(binary) and os.path.exists(binary + ".exe"):
binary = binary + ".exe"
executor(cont,
util.running_output,
os.path.join(os.getcwd(), binary))
util.print_message(binary)
kwargs = {
"kind": "polysquare conan c++",
"during_test": _during_test
}
return conan_check.run(cont,
util,
shell,
argv=remainder,
override_kwargs=kwargs)
| # /ciscripts/check/psqcppconan/check.py
#
# Run tests and static analysis checks on a polysquare conan c++ project.
#
# See /LICENCE.md for Copyright information
"""Run tests and static analysis checks on a polysquare conan c++ project."""
import argparse
import os
def run(cont, util, shell, argv=None):
"""Run checks on this conan project."""
parser = argparse.ArgumentParser(description="""Run conan checks""")
parser.add_argument("--run-test-binaries",
nargs="*",
type=str,
help="""Files relative to the build dir to run""")
result, remainder = parser.parse_known_args(argv or list())
conan_check_script = "check/conan/check.py"
conan_check = cont.fetch_and_import(conan_check_script)
def _during_test(cont, executor, util, build):
"""Run the specified test binaries with the --tap switch.
We then pipe the output into tap-mocha-reporter.
"""
del build
for binary in result.run_test_binaries or list():
executor(cont,
util.running_output,
os.path.join(os.getcwd(), binary))
util.print_message(binary)
kwargs = {
"kind": "polysquare conan c++",
"during_test": _during_test
}
return conan_check.run(cont,
util,
shell,
argv=remainder,
override_kwargs=kwargs)
|
Revert "return json of message being sent to debug mail issue" | from django.shortcuts import redirect
from django.http import JsonResponse
from django.core.mail import EmailMessage
from django.middleware import csrf
from rest_framework.decorators import api_view
@api_view(['POST', 'GET'])
def send_contact_message(request):
if request.method == 'POST':
to_address = request.POST.get("to_address", "").split(',')
from_name = request.POST.get("from_name", "")
from_address = request.POST.get("from_address", "")
from_string = '{} <{}>'.format(from_name, from_address)
subject = request.POST.get("subject", "")
message_body = request.POST.get("message_body", "")
email = EmailMessage(subject,
message_body,
'[email protected]',
to_address,
reply_to=[from_string])
email.send()
return redirect('/contact-thank-you')
# if this is not posting a message, let's send the csfr token back
else:
csrf_token = csrf.get_token(request)
data = {'csrf_token': csrf_token}
return JsonResponse(data)
| from django.shortcuts import redirect
from django.http import JsonResponse
from django.core.mail import EmailMessage
from django.middleware import csrf
from rest_framework.decorators import api_view
@api_view(['POST', 'GET'])
def send_contact_message(request):
if request.method == 'POST':
to_address = request.POST.get("to_address", "").split(',')
from_name = request.POST.get("from_name", "")
from_address = request.POST.get("from_address", "")
from_string = '{} <{}>'.format(from_name, from_address)
subject = request.POST.get("subject", "")
message_body = request.POST.get("message_body", "")
csrf_token = request.POST.get("csrfmiddlewaretoken", "")
email = EmailMessage(subject,
message_body,
'[email protected]',
to_address,
reply_to=[from_string])
email.send(fail_silently=False)
#return redirect('/contact-thank-you')
data = {'subject': subject,
'message_body': message_body,
'to_address': to_address,
'reply_to': [from_string],
'from_address': '[email protected]',
'csrf_token': csrf_token,
}
return JsonResponse(data)
# if this is not posting a message, let's send the csfr token back
else:
csrf_token = csrf.get_token(request)
data = {'csrf_token': csrf_token}
return JsonResponse(data)
|
Move table name literal out of query | var mysql = require('mysql');
var connectionParams = require('../../config/connectionParams');
function getConnection() {
var connection = mysql.createConnection(connectionParams);
return connection;
}
function Calibration(databaseRow) {
for(var propertyName in databaseRow) {
this[propertyName] = databaseRow[propertyName];
}
}
function Calibrations() {
function query(queryString, queryParams, callback) {
var connection = getConnection();
connection.connect();
connection.query(queryString, queryParams, callback);
connection.end()
}
var TABLE_NAME = 'View_Calibrations';
this.findById = function(calibration_id, callback) {
// callback is (calibration, err)
// query the calibrations by id
var queryString = 'SELECT * FROM ' + TABLE_NAME + ' WHERE CalibrationID = ?';
query(queryString, [calibration_id], function(err, results) {
if(err) {
callback(null,err);
} else {
var calibrationResult = new Calibration(results[0]);
callback(calibrationResult);
}
});
};
this.findByFilter = function(params, callback) {
var queryString = 'SELECT * FROM ' + TABLE_NAME + ' WHERE minAge > ? AND maxAge < ?';
query(queryString, [params.min, params.max], function(err, results) {
if(err) {
callback(null,err);
} else {
var calibrationResults = results.map(function(result) { return new Calibration(result)});
callback(calibrationResults);
}
});
};
}
module.exports = new Calibrations(); | var mysql = require('mysql');
var connectionParams = require('../../config/connectionParams');
function getConnection() {
var connection = mysql.createConnection(connectionParams);
return connection;
}
function Calibration(databaseRow) {
for(var propertyName in databaseRow) {
this[propertyName] = databaseRow[propertyName];
}
}
function Calibrations() {
function query(queryString, queryParams, callback) {
var connection = getConnection();
connection.connect();
connection.query(queryString, queryParams, callback);
connection.end()
}
this.findById = function(calibration_id, callback) {
// callback is (calibration, err)
// query the calibrations by id
var queryString = 'SELECT * FROM calibrations WHERE CalibrationID = ?';
query(queryString, [calibration_id], function(err, results) {
if(err) {
callback(null,err);
} else {
var calibrationResult = new Calibration(results[0]);
callback(calibrationResult);
}
});
};
this.findByFilter = function(params, callback) {
var queryString = 'SELECT * FROM calibrations WHERE minAge > ? AND maxAge < ?';
query(queryString, [params.min, params.max], function(err, results) {
if(err) {
callback(null,err);
} else {
var calibrationResults = results.map(function(result) { return new Calibration(result)});
callback(calibrationResults);
}
});
};
}
module.exports = new Calibrations(); |
Make sure pull requests are sorted in descending order (earliest first) | const Repository = require("../models/repository").model;
module.exports = {
createRepository: function (repo, issues, pullRequests) {
return Repository.create({
_id: `${repo.owner}:${repo.name}`,
name: repo.name,
owner: repo.owner,
url: repo.url,
issues: issues,
pullRequests: pullRequests
});
},
getRepositories: function () {
return Repository.find({}).select('name owner url -_id');
},
getRepository: function (id) {
return Repository.findOne({
"_id": id
}).select('name owner url');
},
updateRepository: function (repo) {
return repo.save();
},
getPullRequests: function (id) {
return Repository.findOne({
"_id": id
}).select("pullRequests -_id").sort({
"pullRequests.mergedAt": "desc"
});
},
getIssues: function (id) {
return Repository.findOne({
"_id": id
}).select("issues -_id");
}
}; | const Repository = require("../models/repository").model;
module.exports = {
createRepository: function (repo, issues, pullRequests) {
return Repository.create({
_id: `${repo.owner}:${repo.name}`,
name: repo.name,
owner: repo.owner,
url: repo.url,
issues: issues,
pullRequests: pullRequests
});
},
getRepositories: function () {
return Repository.find({}).select('name owner url -_id');
},
getRepository: function (id) {
return Repository.findOne({
"_id": id
}).select('name owner url');
},
updateRepository: function (repo) {
return repo.save();
},
getPullRequests: function (id) {
return Repository.findOne({
"_id": id
}).select("pullRequests -_id").sort({
"pullRequests.mergedAt": -1
});
},
getIssues: function (id) {
return Repository.findOne({
"_id": id
}).select("issues -_id");
}
}; |
Fix bad return `return { state }` > `return state` | import { CONNECT, GET_CURRENT_USER_SUCCESS } from './actionTypes'
import { combineReducers } from 'redux'
let isNewLoginValue = false
export const nuxeoReducer = combineReducers({
connect: (state = { isConnected: false }, action = {}) => {
switch (action.type) {
case CONNECT:
return {
...state,
isConnected: true,
client: action.client,
}
default:
return state
}
},
computeLogin: (
state = {
isFetching: false,
response: {
get: () => {
return ''
},
},
success: false,
},
action = {}
) => {
switch (action.type) {
case GET_CURRENT_USER_SUCCESS: {
const newLoginValue = isNewLoginValue
isNewLoginValue = false
return {
...state,
response: action.user,
isFetching: false,
success: true,
isConnected: !action.isAnonymous,
isNewLogin: newLoginValue,
}
}
default:
return { ...state, isFetching: false }
}
},
})
| import { CONNECT, GET_CURRENT_USER_SUCCESS } from './actionTypes'
import { combineReducers } from 'redux'
let isNewLoginValue = false
export const nuxeoReducer = combineReducers({
connect: (state = { isConnected: false }, action = {}) => {
switch (action.type) {
case CONNECT:
return {
...state,
isConnected: true,
client: action.client,
}
default: // NOTE: do nothing
}
return { state } // NOTE: should this be `return state`?
},
computeLogin: (
state = {
isFetching: false,
response: {
get: () => {
return ''
},
},
success: false,
},
action = {}
) => {
switch (action.type) {
case GET_CURRENT_USER_SUCCESS: {
const newLoginValue = isNewLoginValue
isNewLoginValue = false
return {
...state,
response: action.user,
isFetching: false,
success: true,
isConnected: !action.isAnonymous,
isNewLogin: newLoginValue,
}
}
default:
return { ...state, isFetching: false }
}
},
})
|
Add on click listener in on submit function | package br.com.bloder.blormlib;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;
/**
* Created by bloder on 05/06/16.
*/
public class Blorm {
public static class Builder {
private List<Validate> validations;
private View field;
public Builder() {
validations = new ArrayList<>();
}
public Builder field(View field) {
this.field = field;
return this;
}
public Builder is(Validate validation) {
this.validations.add(validation);
return this;
}
public Builder is(Validation validation) {
validation.field = this.field;
this.validations.add(validation.validate());
return this;
}
public Builder is(String errorMessgae, Validation validation) {
validation.field = this.field;
validation.errorMessage = errorMessgae;
this.validations.add(validation.validate());
return this;
}
public void onSubmit(View submittedItem) {
submittedItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Blorm(validations).onSubmitted();
}
});
}
}
private List<Validate> validations;
public Blorm(List<Validate> validations) {
this.validations = validations;
}
private void onSubmitted() {
for(Validate validate : validations) {
if(!validate.validate()) {
validate.onError();
}
}
}
}
| package br.com.bloder.blormlib;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;
/**
* Created by bloder on 05/06/16.
*/
public class Blorm {
public static class Builder {
private List<Validate> validations;
private View field;
public Builder() {
validations = new ArrayList<>();
}
public Builder field(View field) {
this.field = field;
return this;
}
public Builder is(Validate validation) {
this.validations.add(validation);
return this;
}
public Builder is(Validation validation) {
validation.field = this.field;
this.validations.add(validation.validate());
return this;
}
public Builder is(String errorMessgae, Validation validation) {
validation.field = this.field;
validation.errorMessage = errorMessgae;
this.validations.add(validation.validate());
return this;
}
public void onSubmit(View submittedItem) {
new Blorm(this.validations).onSubmitted();
}
}
private List<Validate> validations;
public Blorm(List<Validate> validations) {
this.validations = validations;
}
private void onSubmitted() {
for(Validate validate : validations) {
if(!validate.validate()) {
validate.onError();
}
}
}
}
|
Fix the wildcards in watch task | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
react: {
files: ['components/**/*.jsx', 'dashboards/**/*.jsx'],
tasks: ['browserify']
}
},
browserify: {
options: {
transform: [ require('grunt-react').browserify ]
},
dashboards: {
files: [
{
expand: true,
cwd: 'dashboards/',
src: ['*.jsx'],
dest: 'src/main/resources/static/scripts/dashboards/',
ext: '.built.js',
extDot: 'first'
}
]
}
},
cssmin: {
dashboards: {
files: {
'src/main/resources/static/styles/dashboard.built.css': ['node_modules/normalize.css/normalize.css']
}
}
},
copy: {
fonts: {
files: [
{
expand: true,
cwd: 'node_modules/font-awesome/fonts/',
src: ['*'],
dest: 'src/main/resources/static/fonts/',
filter: 'isFile'
}
]
}
}
});
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('build', ['browserify', 'cssmin', 'copy']);
grunt.registerTask('default', ['build', 'watch']);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
react: {
files: ['components/*.jsx', 'dashboards/*.jsx'],
tasks: ['browserify']
}
},
browserify: {
options: {
transform: [ require('grunt-react').browserify ]
},
dashboards: {
files: [
{
expand: true,
cwd: 'dashboards/',
src: ['*.jsx'],
dest: 'src/main/resources/static/scripts/dashboards/',
ext: '.built.js',
extDot: 'first'
}
]
}
},
cssmin: {
dashboards: {
files: {
'src/main/resources/static/styles/dashboard.built.css': ['node_modules/normalize.css/normalize.css']
}
}
},
copy: {
fonts: {
files: [
{
expand: true,
cwd: 'node_modules/font-awesome/fonts/',
src: ['*'],
dest: 'src/main/resources/static/fonts/',
filter: 'isFile'
}
]
}
}
});
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('build', ['browserify', 'cssmin', 'copy']);
grunt.registerTask('default', ['build', 'watch']);
};
|
Use PHP 8 constructor property promotion | <?php
declare(strict_types = 1);
/**
* /src/EventSubscriber/DoctrineExtensionSubscriber.php
*
* @author TLe, Tarmo Leppänen <[email protected]>
*/
namespace App\EventSubscriber;
use App\Security\UserTypeIdentification;
use Doctrine\ORM\NonUniqueResultException;
use Gedmo\Blameable\BlameableListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
/**
* Class DoctrineExtensionSubscriber
*
* @package App\EventSubscriber
* @author TLe, Tarmo Leppänen <[email protected]>
*/
class DoctrineExtensionSubscriber implements EventSubscriberInterface
{
public function __construct(
private BlameableListener $blameableListener,
private UserTypeIdentification $userTypeIdentification,
) {
}
/**
* {@inheritdoc}
*
* @return array<string, string>
*/
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => 'onKernelRequest',
];
}
/**
* @throws NonUniqueResultException
*/
public function onKernelRequest(): void
{
$user = $this->userTypeIdentification->getUser();
if ($user !== null) {
$this->blameableListener->setUserValue($user);
}
}
}
| <?php
declare(strict_types = 1);
/**
* /src/EventSubscriber/DoctrineExtensionSubscriber.php
*
* @author TLe, Tarmo Leppänen <[email protected]>
*/
namespace App\EventSubscriber;
use App\Security\UserTypeIdentification;
use Doctrine\ORM\NonUniqueResultException;
use Gedmo\Blameable\BlameableListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
/**
* Class DoctrineExtensionSubscriber
*
* @package App\EventSubscriber
* @author TLe, Tarmo Leppänen <[email protected]>
*/
class DoctrineExtensionSubscriber implements EventSubscriberInterface
{
private BlameableListener $blameableListener;
private UserTypeIdentification $userTypeIdentification;
public function __construct(BlameableListener $blameableListener, UserTypeIdentification $userTypeIdentification)
{
$this->blameableListener = $blameableListener;
$this->userTypeIdentification = $userTypeIdentification;
}
/**
* {@inheritdoc}
*
* @return array<string, string>
*/
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => 'onKernelRequest',
];
}
/**
* @throws NonUniqueResultException
*/
public function onKernelRequest(): void
{
$user = $this->userTypeIdentification->getUser();
if ($user !== null) {
$this->blameableListener->setUserValue($user);
}
}
}
|
BAP-10771: Migrate data audit command to be executed in new message queue
- fix tests | <?php
namespace Oro\Bundle\DataAuditBundle\Service;
use Doctrine\Common\Util\ClassUtils;
use Metadata\ClassMetadata;
use Metadata\PropertyMetadata;
use Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider;
class GetEntityAuditMetadataService
{
/**
* @var ConfigProvider
*/
private $auditConfigProvider;
/**
* @param ConfigProvider $auditConfigProvider
*/
public function __construct(ConfigProvider $auditConfigProvider)
{
$this->auditConfigProvider = $auditConfigProvider;
}
/**
* @param string $entityClass
*
* @return ClassMetadata|null
*/
public function getMetadata($entityClass)
{
$entityClass = ClassUtils::getRealClass($entityClass);
if (false == $this->auditConfigProvider->hasConfig($entityClass)) {
return null;
}
if (false == $this->auditConfigProvider->getConfig($entityClass)->is('auditable')) {
return null;
}
$classMetadata = new ClassMetadata($entityClass);
foreach ($classMetadata->reflection->getProperties() as $rp) {
$fieldName = $rp->getName();
if (false == $this->auditConfigProvider->hasConfig($entityClass, $fieldName)) {
continue;
}
$fieldConfig = $this->auditConfigProvider->getConfig($entityClass, $fieldName);
if (false == $fieldConfig->is('auditable')) {
continue;
}
$propertyMetadata = new PropertyMetadata($entityClass, $rp->getName());
$classMetadata->addPropertyMetadata($propertyMetadata);
}
return $classMetadata;
}
}
| <?php
namespace Oro\Bundle\DataAuditBundle\Service;
use Doctrine\Common\Util\ClassUtils;
use Metadata\ClassMetadata;
use Metadata\PropertyMetadata;
use Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider;
class GetEntityAuditMetadataService
{
/**
* @var ConfigProvider
*/
private $auditConfigProvider;
/**
* @param ConfigProvider $auditConfigProvider
*/
public function __construct(ConfigProvider $auditConfigProvider)
{
$this->auditConfigProvider = $auditConfigProvider;
}
/**
* @param string $entityClass
*
* @return ClassMetadata|null
*/
public function getMetadata($entityClass)
{
if (false == $this->auditConfigProvider->hasConfig($entityClass)) {
return null;
}
if (false == $this->auditConfigProvider->getConfig($entityClass)->is('auditable')) {
return null;
}
$classMetadata = new ClassMetadata(ClassUtils::getRealClass($entityClass));
foreach ($classMetadata->reflection->getProperties() as $rp) {
$fieldName = $rp->getName();
if (false == $this->auditConfigProvider->hasConfig($entityClass, $fieldName)) {
continue;
}
$fieldConfig = $this->auditConfigProvider->getConfig($entityClass, $fieldName);
if (false == $fieldConfig->is('auditable')) {
continue;
}
$propertyMetadata = new PropertyMetadata($entityClass, $rp->getName());
$classMetadata->addPropertyMetadata($propertyMetadata);
}
return $classMetadata;
}
}
|
Use user instead of username | <?php
/*
* This file is part of Slim HTTP Basic Authentication middleware
*
* Copyright (c) 2013-2014 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/slim-basic-auth
*
*/
namespace Slim\Middleware\HttpBasicAuthentication;
class PdoAuthenticator implements AuthenticatorInterface
{
private $options;
public function __construct(array $options = array())
{
/* Default options. */
$this->options = array(
"table" => "users",
"user" => "user",
"hash" => "hash"
);
if ($options) {
$this->options = array_merge($this->options, $options);
}
}
public function authenticate($user, $pass)
{
$statement = $this->options["pdo"]->prepare(
"SELECT *
FROM {$this->options['table']}
WHERE {$this->options['user']} = ?
LIMIT 1"
);
$statement->execute(array($user));
if ($user = $statement->fetch(\PDO::FETCH_ASSOC)) {
return password_verify($pass, $user[$this->options["hash"]]);
}
return false;
}
}
| <?php
/*
* This file is part of Slim HTTP Basic Authentication middleware
*
* Copyright (c) 2013-2014 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/slim-basic-auth
*
*/
namespace Slim\Middleware\HttpBasicAuthentication;
class PdoAuthenticator implements AuthenticatorInterface
{
private $options;
public function __construct(array $options = array())
{
/* Default options. */
$this->options = array(
"table" => "users",
"user" => "user",
"hash" => "hash"
);
if ($options) {
$this->options = array_merge($this->options, $options);
}
}
public function authenticate($username, $pass)
{
$statement = $this->options["pdo"]->prepare(
"SELECT *
FROM {$this->options['table']}
WHERE {$this->options['user']} = ?
LIMIT 1"
);
$statement->execute(array($username));
if ($user = $statement->fetch(\PDO::FETCH_ASSOC)) {
return password_verify($pass, $user[$this->options["hash"]]);
}
return false;
}
}
|
Disable scroll on number fields | (function(){
'use strict';
angular.module('cla.controllers')
.controller('LayoutCtrl',
['$rootScope', '$scope', '$window', 'History', 'user', 'hotkeys', 'localStorageService',
function($rootScope, $scope, $window, History, user, hotkeys, localStorageService){
var offStateChange = $rootScope.$on('$stateChangeSuccess', function(event, to, toParams, from, fromParams){
if (from.name === 'case_list') {
History.caseListStateParams = fromParams;
}
$window.scrollTo(0,0);
});
var numberFields = angular.element('body');
numberFields.on('mousewheel', ':input[type=number]',function () {
angular.element(this).blur();
});
$scope.$on('$destroy', function () {
offStateChange();
numberFields.off('mousewheel');
});
$rootScope.user = user;
hotkeys.add({
combo: 's c',
description: 'Search cases',
callback: function(e) {
e.preventDefault();
angular.element('#search [name="q"]').focus();
}
});
hotkeys.add({
combo: '$',
description: 'Show call scripts',
callback: function(e) {
e.preventDefault();
$rootScope.showCallScript = !$rootScope.showCallScript;
localStorageService.set('showCallScript', $rootScope.showCallScript);
}
});
}
]
);
})();
| (function(){
'use strict';
angular.module('cla.controllers')
.controller('LayoutCtrl',
['$rootScope', '$scope', '$window', 'History', 'user', 'hotkeys', 'localStorageService',
function($rootScope, $scope, $window, History, user, hotkeys, localStorageService){
var offStateChange = $rootScope.$on('$stateChangeSuccess', function(event, to, toParams, from, fromParams){
if (from.name === 'case_list') {
History.caseListStateParams = fromParams;
}
$window.scrollTo(0,0);
});
$scope.$on('$destroy', function () {
offStateChange();
});
$rootScope.user = user;
hotkeys.add({
combo: 's c',
description: 'Search cases',
callback: function(e) {
e.preventDefault();
angular.element('#search [name="q"]').focus();
}
});
hotkeys.add({
combo: '$',
description: 'Show call scripts',
callback: function(e) {
e.preventDefault();
$rootScope.showCallScript = !$rootScope.showCallScript;
localStorageService.set('showCallScript', $rootScope.showCallScript);
}
});
}
]
);
})();
|
QS-1015: Fix show statistics in question list (own profile) | import React, { PropTypes, Component } from 'react';
import Question from './Question';
export default class QuestionList extends Component {
static propTypes = {
questions : PropTypes.object.isRequired,
ownPicture : PropTypes.string.isRequired,
defaultPicture: PropTypes.string.isRequired,
userId : PropTypes.number.isRequired
};
constructor(props) {
super(props);
this.onClickHandler = this.onClickHandler.bind(this);
this.state = {
graphDisplayQuestionId: null
};
}
onClickHandler(questionId) {
this.setState({
graphDisplayQuestionId: questionId
});
}
render() {
const {questions, userId, ownPicture, defaultPicture} = this.props;
return (
<div className="question-list">
{Object.keys(questions).map((questionId, index) =>
<Question userId={userId}
userAnswer={questions[questionId].userAnswer}
ownPicture={ownPicture}
defaultPicture={defaultPicture}
key={index}
accessibleKey={index}
question={questions[questionId]}
last={index == questions.length}
onClickHandler={this.onClickHandler}
graphActive={this.state.graphDisplayQuestionId == questionId}
/>
)}
</div>
);
}
}
| import React, { PropTypes, Component } from 'react';
import Question from './Question';
export default class QuestionList extends Component {
static propTypes = {
questions : PropTypes.object.isRequired,
ownPicture : PropTypes.string.isRequired,
defaultPicture: PropTypes.string.isRequired,
userId : PropTypes.number.isRequired
};
constructor(props) {
super(props);
this.onClickHandler = this.onClickHandler.bind(this);
this.state = {
graphDisplayQuestionId: null
};
}
onClickHandler(questionId) {
this.setState({
graphDisplayQuestionId: questionId
});
}
render() {
const {questions, userId, ownPicture, defaultPicture} = this.props;
return (
<div className="question-list">
{Object.keys(questions).map((questionId, index) =>
<Question userId={userId}
userAnswer={questions[questionId].userAnswer}
ownPicture={ownPicture}
defaultPicture={defaultPicture}
key={index}
accessibleKey={index}
question={questions[questionId]}
last={index == questions.length}
onClickHandler={this.onClickHandler}
graphActive={this.state.graphDisplayQuestionId === questionId}
/>
)}
</div>
);
}
}
|
Handle baseDir option to resolve include paths before rendering; | "use strict";
var sass = require("node-sass");
var through = require("through");
var path = require("path");
var extend = require('util')._extend;
module.exports = function (fileName, globalOptions) {
if (!/(\.scss|\.css)$/i.test(fileName)) {
return through();
}
var inputString = "";
return through(
function (chunk) {
inputString += chunk;
},
function () {
var options, css, moduleBody;
// new copy of globalOptions for each file
options = extend({}, globalOptions || {});
options.includePaths = extend([], (globalOptions ? globalOptions.includePaths : {}) || []);
// Resolve include paths to baseDir
if(options.baseDir) {
options.includePaths = options.includePaths.map(function (p) { return path.dirname(path.resolve(options.baseDir, p)); });
}
options.data = inputString;
options.includePaths.unshift(path.dirname(fileName));
try {
css = sass.renderSync(options);
} catch (err) {
this.emit('error', err);
return;
}
var escapedCSS = JSON.stringify(css)
moduleBody = "var css = " + escapedCSS + ";" +
"(require('sassify'))(css); module.exports = css;";
this.queue(moduleBody);
this.queue(null);
}
);
};
| "use strict";
var sass = require("node-sass");
var through = require("through");
var path = require("path");
var extend = require('util')._extend;
module.exports = function (fileName, globalOptions) {
if (!/(\.scss|\.css)$/i.test(fileName)) {
return through();
}
var inputString = "";
return through(
function (chunk) {
inputString += chunk;
},
function () {
var options, css, moduleBody;
// new copy of globalOptions for each file
options = extend({}, globalOptions || {});
options.includePaths = extend([], (globalOptions ? globalOptions.includePaths : {}) || []);
options.data = inputString;
options.includePaths.unshift(path.dirname(fileName));
try {
css = sass.renderSync(options);
} catch (err) {
this.emit('error', err);
return;
}
var escapedCSS = JSON.stringify(css)
moduleBody = "var css = " + escapedCSS + ";" +
"(require('sassify'))(css); module.exports = css;";
this.queue(moduleBody);
this.queue(null);
}
);
};
|
CRM-3997: Make all mailboxes available under System organization
- fix jscs | define(function(require) {
'use strict';
var $ = require('jquery');
var _ = require('underscore');
var BaseComponent = require('oroui/js/app/components/base/component');
var CheckConnectionView = require('../views/check-connection-view');
var CheckConnectionModel = require('../models/check-connection-model');
var CheckConnectionComponent;
CheckConnectionComponent = BaseComponent.extend({
/**
* Initialize component
*
* @param {Object} options
* @param {string} options.elementNamePrototype
*/
initialize: function(options) {
if (options.elementNamePrototype) {
var viewOptions = _.extend({
'model': new CheckConnectionModel({}),
'el': $(options._sourceElement).closest(options.parentElementSelector),
'entity': options.forEntity || 'user',
'entityId': options.id,
'organization': options.organization || ''
}, options.viewOptions || {});
if (/^.+\[\w+]$/i.test(options.elementNamePrototype)) {
viewOptions.formPrefix = options.elementNamePrototype.match(/(.+)\[\w+]$/i)[1];
}
this.view = new CheckConnectionView(viewOptions);
} else {
// unable to initialize
$(options._sourceElement).remove();
}
}
});
return CheckConnectionComponent;
});
| define(function(require) {
'use strict';
var $ = require('jquery');
var BaseComponent = require('oroui/js/app/components/base/component');
var CheckConnectionView = require('../views/check-connection-view');
var CheckConnectionModel = require('../models/check-connection-model');
var CheckConnectionComponent;
CheckConnectionComponent = BaseComponent.extend({
/**
* Initialize component
*
* @param {Object} options
* @param {string} options.elementNamePrototype
*/
initialize: function(options) {
if (options.elementNamePrototype) {
var viewOptions = _.extend({
'model': new CheckConnectionModel({}),
'el': $(options._sourceElement).closest(options.parentElementSelector),
'entity': options.forEntity || 'user',
'entityId': options.id,
'organization': options.organization || ''
}, options.viewOptions || {});
if (/^.+\[\w+]$/i.test(options.elementNamePrototype)) {
viewOptions.formPrefix = options.elementNamePrototype.match(/(.+)\[\w+]$/i)[1];
}
this.view = new CheckConnectionView(viewOptions);
} else {
// unable to initialize
$(options._sourceElement).remove();
}
}
});
return CheckConnectionComponent;
});
|
Fix order of migration in operations | # -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
def fix_fee_product_index(apps, schema_editor):
try:
schema_editor.execute(
'DROP INDEX IF EXISTS idx_16977_product_id;'
)
except (ProgrammingError, OperationalError):
pass
try:
schema_editor.execute(
'ALTER TABLE IF EXISTS cfpb.ratechecker_fee '
'DROP CONSTRAINT IF EXISTS idx_16977_product_id;'
)
except (ProgrammingError, OperationalError):
pass
try:
schema_editor.execute(
'ALTER TABLE IF EXISTS cfpb.ratechecker_fee '
'ADD CONSTRAINT idx_16977_product_id '
'UNIQUE (product_id, state_id, lender, single_family, condo, coop);'
)
except (ProgrammingError, OperationalError):
pass
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.RunPython(fix_fee_product_index),
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.DeleteModel(
name='Fee',
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
def fix_fee_product_index(apps, schema_editor):
try:
schema_editor.execute(
'DROP INDEX IF EXISTS idx_16977_product_id;'
)
except (ProgrammingError, OperationalError):
pass
try:
schema_editor.execute(
'ALTER TABLE IF EXISTS cfpb.ratechecker_fee '
'DROP CONSTRAINT IF EXISTS idx_16977_product_id;'
)
except (ProgrammingError, OperationalError):
pass
try:
schema_editor.execute(
'ALTER TABLE IF EXISTS cfpb.ratechecker_fee '
'ADD CONSTRAINT idx_16977_product_id '
'UNIQUE (product_id, state_id, lender, single_family, condo, coop);'
)
except (ProgrammingError, OperationalError):
pass
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='fee',
unique_together=set([]),
),
migrations.RemoveField(
model_name='fee',
name='plan',
),
migrations.RunPython(fix_fee_product_index),
migrations.DeleteModel(
name='Fee',
),
]
|
Remove newline at end of hostname | <?php
class Kwf_Assets_WebpackConfig
{
public static function getDevServerPort()
{
if (!Kwf_Config::getValue('debug.webpackDevServer')) {
return null;
}
if ($port = Kwf_Config::getValue('debug.webpackDevServerPort')) {
return $port;
}
$port = null;
if (file_exists('cache/webpack-dev-server-port')) {
$port = file_get_contents('cache/webpack-dev-server-port');
} else {
while (true) {
if ($port) {
$r = @socket_create_listen($port);
if ($r) {
socket_close($r);
break;
}
}
$port = rand(1024, 65535);
}
file_put_contents('cache/webpack-dev-server-port', $port);
}
return $port;
}
public static function getDevServerPublic()
{
if ($ret = Kwf_Config::getValue('debug.webpackDevServerPublic')) {
return $ret;
} else {
return trim(`hostname`).':'.self::getDevServerPort();
}
}
public static function getDevServerUrl()
{
if ($url = Kwf_Config::getValue('debug.webpackDevServerUrl')) {
return $url;
} else {
return 'http://'.self::getDevServerPublic();
}
}
}
| <?php
class Kwf_Assets_WebpackConfig
{
public static function getDevServerPort()
{
if (!Kwf_Config::getValue('debug.webpackDevServer')) {
return null;
}
if ($port = Kwf_Config::getValue('debug.webpackDevServerPort')) {
return $port;
}
$port = null;
if (file_exists('cache/webpack-dev-server-port')) {
$port = file_get_contents('cache/webpack-dev-server-port');
} else {
while (true) {
if ($port) {
$r = @socket_create_listen($port);
if ($r) {
socket_close($r);
break;
}
}
$port = rand(1024, 65535);
}
file_put_contents('cache/webpack-dev-server-port', $port);
}
return $port;
}
public static function getDevServerPublic()
{
if ($ret = Kwf_Config::getValue('debug.webpackDevServerPublic')) {
return $ret;
} else {
return `hostname`.':'.self::getDevServerPort();
}
}
public static function getDevServerUrl()
{
if ($url = Kwf_Config::getValue('debug.webpackDevServerUrl')) {
return $url;
} else {
return 'http://'.self::getDevServerPublic();
}
}
}
|
Print message for pull success. | import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done", p.sync_msg
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
| import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done"
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
|
Add warning when subscribe is not difined | import { Meteor } from 'meteor/meteor';
import { subscribe } from 'graphql';
import forAwaitEach from '../common/forAwaitEach';
import {
DEFAULT_PUBLICATION,
} from '../common/defaults';
export function createGraphQLPublication({
schema,
publication = DEFAULT_PUBLICATION,
} = {}) {
if (!subscribe) {
console.warn('DDP-Apollo: You need [email protected] or higher for subscription support');
return;
}
Meteor.publish(publication, function publishGraphQL({
query,
variables,
operationName,
} = {}) {
const {
userId,
_subscriptionId: subId,
_session: session,
} = this;
if (!query) {
this.stop();
return;
}
const context = { userId };
const subscribeToQuery = async () => {
const iterator = await subscribe(
schema,
query,
{},
context,
variables,
operationName,
);
return forAwaitEach(iterator, (graphqlData) => {
// If this subscription has ended we should stop listening to the iterator
const { _deactivated: done } = this;
if (done) {
return false;
}
session.socket.send(JSON.stringify({
msg: 'pong',
subId,
graphqlData,
}));
return true;
});
};
this.ready();
subscribeToQuery();
});
}
| import { Meteor } from 'meteor/meteor';
import { subscribe } from 'graphql';
import forAwaitEach from '../common/forAwaitEach';
import {
DEFAULT_PUBLICATION,
} from '../common/defaults';
export function createGraphQLPublication({
schema,
publication = DEFAULT_PUBLICATION,
} = {}) {
Meteor.publish(publication, function publishGraphQL({
query,
variables,
operationName,
} = {}) {
const {
userId,
_subscriptionId: subId,
_session: session,
} = this;
if (!query) {
this.stop();
return;
}
const context = { userId };
const subscribeToQuery = async () => {
const iterator = await subscribe(
schema,
query,
{},
context,
variables,
operationName,
);
return forAwaitEach(iterator, (graphqlData) => {
// If this subscription has ended we should stop listening to the iterator
const { _deactivated: done } = this;
if (done) {
return false;
}
session.socket.send(JSON.stringify({
msg: 'pong',
subId,
graphqlData,
}));
return true;
});
};
this.ready();
subscribeToQuery();
});
}
|
Use the declared first and second variables | (function ($) {
$.fn.dragster = function (options) {
var settings = $.extend({
enter: function () { },
leave: function () { }
}, options);
return this.each(function () {
var first = false,
second = false;
$(this).on('dragenter', function () {
if (first) {
return second = true;
} else {
first = true;
$(this).trigger('dragster:enter');
}
});
$(this).on('dragleave', function () {
if (second) {
second = false;
} else if (first) {
first = false;
}
if (!first && !second) {
$(this).trigger('dragster:leave');
}
});
$(this).on('dragster:enter', settings.enter);
$(this).on('dragster:leave', settings.leave);
});
};
}(jQuery));
| (function ($) {
$.fn.dragster = function (options) {
var settings = $.extend({
enter: function () { },
leave: function () { }
}, options);
return this.each(function () {
var first = false,
second = false;
$(this).on('dragenter', function () {
if (this.first) {
return this.second = true;
} else {
this.first = true;
$(this).trigger('dragster:enter');
}
});
$(this).on('dragleave', function () {
if (this.second) {
this.second = false;
} else if (this.first) {
this.first = false;
}
if (!this.first && !this.second) {
$(this).trigger('dragster:leave');
}
});
$(this).on('dragster:enter', settings.enter);
$(this).on('dragster:leave', settings.leave);
});
};
}(jQuery)); |
Make the automatic object to array transformer generate deep arrays | <?php
namespace FOQ\ElasticaBundle\Transformer;
use RuntimeException;
use Traversable;
use ArrayAccess;
/**
* AutomaticObjectToArrayTransformer
* Tries to convert objects by generating getters
* based on the required keys
*/
class ObjectToArrayAutomaticTransformer implements ObjectToArrayTransformerInterface
{
/**
* Transforms an object into an array having the required keys
*
* @param object $object the object to convert
* @param array $requiredKeys the keys we want to have in the returned array
* @return array
**/
public function transform($object, array $requiredKeys)
{
$class = get_class($object);
$array = array();
foreach ($requiredKeys as $key) {
$getter = 'get'.ucfirst($key);
if (!method_exists($class, $getter)) {
throw new RuntimeException(sprintf('The getter %s::%s does not exist', $class, $getter));
}
$array[$key] = $this->normalizeValue($object->$getter());
}
return array_filter($array);
}
public function normalizeValue($value)
{
if (is_array($value) || $value instanceof Traversable || $value instanceof ArrayAccess) {
$value = array_map(function($v) {
return (string) $v;
}, is_array($value) ? $value : iterator_to_array($value));
} else {
$value = (string) $value;
}
return $value;
}
}
| <?php
namespace FOQ\ElasticaBundle\Transformer;
use RuntimeException;
use Traversable;
use ArrayAccess;
/**
* AutomaticObjectToArrayTransformer
* Tries to convert objects by generating getters
* based on the required keys
*/
class ObjectToArrayAutomaticTransformer implements ObjectToArrayTransformerInterface
{
/**
* Transforms an object into an array having the required keys
*
* @param object $object the object to convert
* @param array $requiredKeys the keys we want to have in the returned array
* @return array
**/
public function transform($object, array $requiredKeys)
{
$class = get_class($object);
$array = array();
foreach ($requiredKeys as $key) {
$getter = 'get'.ucfirst($key);
if (!method_exists($class, $getter)) {
throw new RuntimeException(sprintf('The getter %s::%s does not exist', $class, $getter));
}
$array[$key] = $this->normalizeValue($object->$getter());
}
return array_filter($array);
}
public function normalizeValue($value)
{
if (is_array($value) || $value instanceof Traversable || $value instanceof ArrayAccess) {
$values = array();
foreach ($value as $v) {
$values[] = (string) $v;
}
$value = implode(', ', $values);
}
return (string) $value;
}
}
|
Raise minimum requirement to force minimum TG version | from setuptools import setup, find_packages
import os
version = '0.5.4'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin',
version=version,
description="Admin Controller add-on for basic TG identity model.",
long_description=README + "\n" +
CHANGES,
# Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin',
author='Christopher Perkins',
author_email='[email protected]',
url='https://github.com/TurboGears/tgext.admin',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['tgext'],
include_package_data=True,
zip_safe=True,
install_requires=[
'setuptools',
'tgext.crud>=0.6.5',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
| from setuptools import setup, find_packages
import os
version = '0.5.4'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin',
version=version,
description="Admin Controller add-on for basic TG identity model.",
long_description=README + "\n" +
CHANGES,
# Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin',
author='Christopher Perkins',
author_email='[email protected]',
url='https://github.com/TurboGears/tgext.admin',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['tgext'],
include_package_data=True,
zip_safe=True,
install_requires=[
'setuptools',
'tgext.crud>=0.5.2',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
Use benchmark directory to load skeleton | import os
from contextlib import contextmanager
from collections import OrderedDict
from time import process_time
import numpy as np
from skan import csr
rundir = os.path.dirname(__file__)
@contextmanager
def timer():
time = []
t0 = process_time()
yield time
t1 = process_time()
time.append(t1 - t0)
def bench_suite():
times = OrderedDict()
skeleton = np.load(os.path.join(rundir, 'infected3.npz'))['skeleton']
with timer() as t_build_graph:
g, indices, degrees = csr.skeleton_to_csgraph(skeleton,
spacing=2.24826)
times['build graph'] = t_build_graph[0]
with timer() as t_stats:
stats = csr.branch_statistics(g, indices, degrees)
times['compute statistics'] = t_stats[0]
with timer() as t_summary:
summary = csr.summarise(skeleton)
times['compute per-skeleton statistics'] = t_summary[0]
return times
def print_bench_results(times=None, memory=None):
if times is not None:
print('Timing results:')
for key in times:
print('--- ', key, '%.3f s' % times[key])
if memory is not None:
print('Memory results:')
for key in memory:
print('--- ', key, '%.3f MB' % (memory[key] / 1e6))
if __name__ == '__main__':
times = bench_suite()
print_bench_results(times)
| import os
from contextlib import contextmanager
from collections import OrderedDict
from time import process_time
import numpy as np
from skan import csr
rundir = os.path.dirname(__file__)
@contextmanager
def timer():
time = []
t0 = process_time()
yield time
t1 = process_time()
time.append(t1 - t0)
def bench_suite():
times = OrderedDict()
skeleton = np.load('infected3.npz')['skeleton']
with timer() as t_build_graph:
g, indices, degrees = csr.skeleton_to_csgraph(skeleton,
spacing=2.24826)
times['build graph'] = t_build_graph[0]
with timer() as t_stats:
stats = csr.branch_statistics(g, indices, degrees)
times['compute statistics'] = t_stats[0]
with timer() as t_summary:
summary = csr.summarise(skeleton)
times['compute per-skeleton statistics'] = t_summary[0]
return times
def print_bench_results(times=None, memory=None):
if times is not None:
print('Timing results:')
for key in times:
print('--- ', key, '%.3f s' % times[key])
if memory is not None:
print('Memory results:')
for key in memory:
print('--- ', key, '%.3f MB' % (memory[key] / 1e6))
if __name__ == '__main__':
times = bench_suite()
print_bench_results(times)
|
Put eval in setTimeout as an attempt to ensure that the page is really rendered | /**
* @fileoverview Run the bootstrap service
*/
var port = 3020,
system = require('system'),
page = require('webpage').create(),
serverObj = require('./server').create(port),
util = require('./util'),
module = system.args[1],
config = system.args[2];
if (!module) {
console.error('missing module');
serverObj.close();
phantom.exit(1);
}
if (!config) {
console.error('missing config');
serverObj.close();
phantom.exit(1);
}
config = decodeURIComponent(config);
var url = 'http://localhost:' + port + '/' + module + '.html?config=' + config;
console.log('<!-- html generated by Livefyre -->');
page.open(url, function(status) {
if (status !== 'success') {
console.error('Page could not be opened');
serverObj.close();
phantom.exit(1);
}
// TODO(rrp): Generalize this bit
// Wait for fyre-comment-stream el? (need to ensure 100% loaded somehow)
util.waitFor(function() {
return page.evaluate(function() {
return document.getElementsByClassName('fyre-comment-stream').length > 0;
});
}, function() {
setTimeout(function() {
var html = page.evaluate(function() {
return document.getElementById('bs').innerHTML;
});
console.log(html);
serverObj.close();
phantom.exit();
}, 500);
}, 30000);
});
| /**
* @fileoverview Run the bootstrap service
*/
var port = 3020,
system = require('system'),
page = require('webpage').create(),
serverObj = require('./server').create(port),
util = require('./util'),
module = system.args[1],
config = system.args[2];
if (!module) {
console.error('missing module');
serverObj.close();
phantom.exit(1);
}
if (!config) {
console.error('missing config');
serverObj.close();
phantom.exit(1);
}
config = decodeURIComponent(config);
var url = 'http://localhost:' + port + '/' + module + '.html?config=' + config;
console.log('<!-- html generated by Livefyre -->');
page.open(url, function(status) {
if (status !== 'success') {
console.error('Page could not be opened');
serverObj.close();
phantom.exit(1);
}
// TODO(rrp): Generalize this bit
// Wait for fyre-comment-stream el? (need to ensure 100% loaded somehow)
util.waitFor(function() {
return page.evaluate(function() {
return document.getElementsByClassName('fyre-comment-stream').length > 0;
});
}, function() {
var html = page.evaluate(function() {
return document.getElementById('bs').innerHTML;
});
console.log(html);
serverObj.close();
phantom.exit();
}, 30000);
});
|
Fix to avoid infinite loop when ob_end_clean() failed. | <?php
namespace Ouzo;
class Error
{
static public function exceptionHandler(\Exception $exception)
{
self::_handleError($exception->getMessage(), $exception->getTraceAsString());
}
static public function errorHandler($errno, $errstr, $errfile, $errline)
{
self::_handleError("$errstr ERRNO($errno)", "$errfile:$errline");
}
private static function _clearOutputBuffers()
{
while (ob_get_level()) {
if (!ob_end_clean()){
break;
}
}
}
private static function _handleError($errorMessage, $errorTrace)
{
try {
Logger::getPanelLogger()->addError($errorMessage, array($errorTrace));
/** @noinspection PhpIncludeInspection */
self::_clearOutputBuffers();
header("HTTP/1.1 500 Internal Server Error");
require_once(ViewPathResolver::resolveViewPath('exception'));
} catch (\Exception $e) {
echo "Framework critical error. Exception thrown in exception handler.<br>\n";
echo "<hr>\n";
echo "Message: " . $e->getMessage() . "<br>\n";
echo "Trace: " . $e->getTraceAsString() . "<br>\n";
}
}
static public function shutdownHandler()
{
$error = error_get_last();
if ($error && $error['type'] & (E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_RECOVERABLE_ERROR)) {
self::errorHandler($error['type'], $error['message'], $error['file'], $error['line']);
}
}
} | <?php
namespace Ouzo;
class Error
{
static public function exceptionHandler(\Exception $exception)
{
self::_handleError($exception->getMessage(), $exception->getTraceAsString());
}
static public function errorHandler($errno, $errstr, $errfile, $errline)
{
self::_handleError("$errstr ERRNO($errno)", "$errfile:$errline");
}
private static function _clearOutputBuffers()
{
while (ob_get_level()) {
ob_end_clean();
}
}
private static function _handleError($errorMessage, $errorTrace)
{
try {
Logger::getPanelLogger()->addError($errorMessage, array($errorTrace));
/** @noinspection PhpIncludeInspection */
self::_clearOutputBuffers();
header("HTTP/1.1 500 Internal Server Error");
require_once(ViewPathResolver::resolveViewPath('exception'));
} catch (\Exception $e) {
echo "Framework critical error. Exception thrown in exception handler.<br>\n";
echo "<hr>\n";
echo "Message: " . $e->getMessage() . "<br>\n";
echo "Trace: " . $e->getTraceAsString() . "<br>\n";
}
}
static public function shutdownHandler()
{
$error = error_get_last();
if ($error && $error['type'] & (E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_RECOVERABLE_ERROR)) {
self::errorHandler($error['type'], $error['message'], $error['file'], $error['line']);
}
}
} |
Fix issue with post with no tag | import needle from 'needle';
import { SiteConf, getDate } from 'base';
export const postsApiHandler = (req, res) => {
needle('get', SiteConf.PostsApi)
.then(resp => {
const data = resp.body;
const filter = req.params.filter;
const pagination = data.meta.pagination;
const posts = PostList(data.posts, filter);
const result = { posts, pagination };
res.json(result);
})
.catch(err => {
console.log(333, err);
res.status(500).json(err);
});
};
export const PostList = (posts, filter) => {
return posts.filter((post) => {
const reg = new RegExp(`^(.+?)${ SiteConf.postOpeningSplitChar }`);
const result = reg.exec(post.html);
if (result) post.opening = result[1];
else {
let i = 0;
let max = SiteConf.postOpeningChars;
const words = post.html.split(' ');
post.opening = '';
for (i; i <= max ; i++) {
post.opening += `${words[i]} `;
}
post.opening += '...</p>';
}
post.html = null;
post.markdown = null;
post.published_at = getDate(post.published_at);
if (filter && post.tags[0]) {
if (post.tags[0].slug === filter.split(':')[1]) return post;
else return false;
}
else return post;
}
);
};
| import needle from 'needle';
import { SiteConf, getDate } from 'base';
export const postsApiHandler = (req, res) => {
needle('get', SiteConf.PostsApi)
.then(resp => {
const data = resp.body;
const filter = req.params.filter;
const pagination = data.meta.pagination;
const posts = PostList(data.posts, filter);
const result = { posts, pagination };
res.json(result);
})
.catch(err => {
res.status(500).json(err);
});
};
export const PostList = (posts, filter) => {
return posts.filter((post) => {
const reg = new RegExp(`^(.+?)${ SiteConf.postOpeningSplitChar }`);
const result = reg.exec(post.html);
if (result) post.opening = result[1];
else {
let i = 0;
let max = SiteConf.postOpeningChars;
const words = post.html.split(' ');
post.opening = '';
for (i; i <= max ; i++) {
post.opening += `${words[i]} `;
}
post.opening += '...</p>';
}
post.html = null;
post.markdown = null;
post.published_at = getDate(post.published_at);
if (filter) {
if (post.tags[0].slug === filter.split(':')[1]) return post;//data.push(post);
else return false;
}
else return post;
}
);
};
|
Stop installing the 'forum' demo project (but still ship it in the release tarball). | import os
from setuptools import setup, find_packages
overview = file('docs/overview.txt')
data = overview.read()
overview.close()
setup(
name='dinette',
description='Dinette is a forum application in the spirit of PunBB.',
keywords='django, forum',
packages=find_packages(exclude=["forum", "forum.*"]),
include_package_data=True,
zip_safe=False,
version="1.2",
author="Agiliq Solutions",
author_email="[email protected]",
long_description= data,
classifiers = ['Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Internet :: WWW/HTTP :: WSGI',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
],
url="http://www.agiliq.com/",
license="GPL",
platforms=["all"],
)
| import os
from setuptools import setup, find_packages
overview = file('docs/overview.txt')
data = overview.read()
overview.close()
setup(
name='dinette',
description='Dinette is a forum application in the spirit of PunBB.',
keywords='django, forum',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
version="1.2",
author="Agiliq Solutions",
author_email="[email protected]",
long_description= data,
classifiers = ['Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Internet :: WWW/HTTP :: WSGI',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
],
url="http://www.agiliq.com/",
license="GPL",
platforms=["all"],
)
|
Update model with new mycosti value. | /**
* Class Sliders
*/
Humble( function () {
var Sliders = function (node, model) {
this.model = model;
this.node = node;
this.sliders = {};
this.render();
}
Sliders.prototype = {
render : function () {
var items = this.model.getItems(),
node = this.node;
_.each(items, function (item, key) {
var slider = this._renderSlider(item);
node.append(slider);
slider.data('key', key);
sliders[key] = slider;
}, this);
this.bind();
},
_renderSlider : function (item) {
var slider = $('<div class="slider"></div>'),
widget = $('<div></div>'),
total = this.model.getTotalTaxes(),
value = item['mycosti'],
title = item['dimensionName'],
config;
slider.append('<div class="value mycosti">$'+value+'</div>');
slider.append('<div class="title">'+title+'</div>');
slider.append(widget);
config = {
max : total,
value : value
};
widget.slider(config);
return slider;
},
bind : function () {
this.node.delegate('.slider', 'slide', {this : this}, this._onSlide);
},
_onSlide : function (e, ui) {
var key = $(this).data('key'),
sliders = e.data.this;
$(this).find('.mycosti').html('$'+ui.value);
sliders.model.set(key, 'mycosti', ui.value);
}
}
Humble.Sliders = Sliders;
});
| /**
* Class Sliders
*/
Humble( function () {
var Sliders = function (node, model) {
this.model = model;
this.node = node;
this.sliders = {};
this.render();
}
Sliders.prototype = {
render : function () {
var items = this.model.getItems(),
node = this.node;
_.each(items, function (item, key) {
var slider = this._renderSlider(item);
node.append(slider);
slider.data('key', key);
sliders[key] = slider;
}, this);
this.bind();
},
_renderSlider : function (item) {
var slider = $('<div class="slider"></div>'),
widget = $('<div></div>'),
total = this.model.getTotalTaxes(),
value = item['mycosti'],
title = item['dimensionName'],
config;
slider.append('<div class="value mycosti">$'+value+'</div>');
slider.append('<div class="title">'+title+'</div>');
slider.append(widget);
config = {
max : total,
value : value
};
widget.slider(config);
return slider;
},
bind : function () {
this.node.delegate('.slider', 'slide', {this : this}, this._onSlide);
},
_onSlide : function (e, ui) {
$(this).find('.mycosti').html('$'+ui.value);
}
}
Humble.Sliders = Sliders;
});
|
chore: Refactor classnames usage a little bit | import React, { PropTypes } from 'react'
import { Link } from 'react-router'
import classnames from 'classnames'
import Date from '../../components/Date'
import Tag from '../../components/Tag'
import styles from './PostItem.scss'
const PostItem = ({__url, date, title, draft, tags, description}) => {
const articleClass = classnames(styles.article, {
[styles.draft]: draft
})
const linkClass = classnames(styles.title, {
[styles.titleDraft]: draft
})
return (
<article
key={__url}
className={articleClass}
>
<Link
to={__url}
className={linkClass}
>
{title}
</Link>
<p>
{
tags &&
Array.isArray(tags) &&
tags.map((tag) =>
<Tag key={tag} name={tag} />
)
}
<Date date={date} className={styles.date} />
</p>
{
description &&
<p className={styles.description}>{description}</p>
}
</article>
)
}
PostItem.propTypes = {
__url: PropTypes.string.isRequired,
date: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
description: PropTypes.string,
draft: PropTypes.boolean,
tags: PropTypes.array
}
export default PostItem
| import React, { PropTypes } from 'react'
import { Link } from 'react-router'
import classnames from 'classnames'
import Date from '../../components/Date'
import Tag from '../../components/Tag'
import styles from './PostItem.scss'
const PostItem = ({__url, date, title, draft, tags, description}) => {
const articleClass = classnames({
[styles.article]: true,
[styles.draft]: draft
})
const linkClass = classnames({
[styles.title]: true,
[styles.titleDraft]: draft
})
return (
<article
key={__url}
className={articleClass}
>
<Link
to={__url}
className={linkClass}
>
{title}
</Link>
<p>
{
tags &&
Array.isArray(tags) &&
tags.map((tag) =>
<Tag key={tag} name={tag} />
)
}
<Date date={date} className={styles.date} />
</p>
{
description &&
<p className={styles.description}>{description}</p>
}
</article>
)
}
PostItem.propTypes = {
__url: PropTypes.string.isRequired,
date: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
description: PropTypes.string,
draft: PropTypes.boolean,
tags: PropTypes.array
}
export default PostItem
|
Add some info and outfile to prepare function | #!/usr/bin/env python
# encoding: utf-8
import sys
import re
import argparse
from argparse import RawDescriptionHelpFormatter
from patterns import pre_patterns
def prepare(infile, outfile=sys.stdout):
"""
Apply pre_patterns from patterns to infile
:infile: input file
"""
try:
for line in infile:
result = line
for pattern in pre_patterns:
result = re.sub(pattern[0], pattern[1], result, re.VERBOSE)
outfile.write(result)
except (KeyboardInterrupt):
pass
except:
raise
def main():
parser = argparse.ArgumentParser(description=\
"""
Parse file[s]\n\n
examlpe: cat error_log | tail -n 1000 | ./direlog.py
""", formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('file', nargs='*', default=[],
help='file[s] to do some work')
parser.add_argument('-s', '--stat', action='store_const', const=True,
help='get statistics')
args = parser.parse_args()
if not args.file:
prepare(sys.stdin)
else:
for filename in args.file:
with open(filename, 'r') as f:
prepare(f)
pass
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# encoding: utf-8
import sys
import re
import argparse
from patterns import pre_patterns
def prepare(infile):
"""
Apply pre_patterns from patterns to infile
:infile: input file
"""
try:
for line in infile:
result = line
for pattern in pre_patterns:
result = re.sub(pattern[0], pattern[1], result)
sys.stdout.write(result)
except (KeyboardInterrupt):
pass
def main():
parser = argparse.ArgumentParser(description='Parse file[s]')
parser.add_argument('file', nargs='*', default=[],
help='file[s] to do some work')
parser.add_argument('-s', '--stat', action='store_const', const=True,
help='get statistics')
args = parser.parse_args()
if not args.file:
prepare(sys.stdin)
else:
for filename in args.file:
with open(filename, 'r') as f:
prepare(f)
# if outfilename:
# outfile = open(outfilename, 'w')
# else:
# outfile = sys.stdout
pass
if __name__ == '__main__':
main()
|
Add paragraph tag in hello template. | "use strict";
(function (app) {
app.HttpService = ng.core
.Class({
constructor: function () {},
http: function () {
return new ng.http.Http(
new ng.http.XHRBackend(
new ng.http.BrowserXhr()),
new ng.http.RequestOptions());
}
});
}(window.app || (window.app = {})));
(function (app) {
app.HelloComponent = ng.core
.Component({
selector: "hello",
bindings: [app.HttpService]
})
.View({
template: "<p>{{ greeting }} world! {{ greetingFromJSON }}</p>"
})
.Class({
constructor: [app.HttpService, function Hello(httpService) {
var vm = this;
vm.greeting = "Hello";
vm.greetingFromJSON = "n.a";
activate();
function activate() {
var rx = httpService.http()
.get("/src/client/app/greetings.json").share();
rx.subscribe(function (res) {
var greetings = res.json();
vm.greetingFromJSON = greetings.hello;
});
}
}]
});
}(window.app || (window.app = {})));
| "use strict";
(function (app) {
app.HttpService = ng.core
.Class({
constructor: function () {},
http: function () {
return new ng.http.Http(
new ng.http.XHRBackend(
new ng.http.BrowserXhr()),
new ng.http.RequestOptions());
}
});
}(window.app || (window.app = {})));
(function (app) {
app.HelloComponent = ng.core
.Component({
selector: "hello",
bindings: [app.HttpService]
})
.View({
template: "{{ greeting }} world! {{ greetingFromJSON }}"
// templateUrl: "hello.html"
})
.Class({
constructor: [app.HttpService, function Hello(httpService) {
var vm = this;
vm.greeting = "Hello";
vm.greetingFromJSON = "n.a";
activate();
function activate() {
var rx = httpService.http()
.get("/src/client/app/greetings.json").share();
rx.subscribe(function (res) {
var greetings = res.json();
vm.greetingFromJSON = greetings.hello;
});
}
}]
});
}(window.app || (window.app = {})));
|
Fix for "No module named decorator" on fresh environment installs.
Fixes regression from 4b26b5837ced0c2f76495b05b87e63e05f81c2af. | #! /usr/bin/env python
from distutils.core import setup
setup(
name = 'qless-py',
version = '0.10.0',
description = 'Redis-based Queue Management',
long_description = '''
Redis-based queue management, with heartbeating, job tracking,
stats, notifications, and a whole lot more.''',
url = 'http://github.com/seomoz/qless-py',
author = 'Dan Lecocq',
author_email = '[email protected]',
license = "MIT License",
keywords = 'redis, qless, job',
packages = ['qless', 'qless.workers'],
package_dir = {
'qless': 'qless',
'qless.workers': 'qless/workers'},
package_data = {'qless': ['qless-core/*.lua']},
include_package_data = True,
scripts = ['bin/qless-py-worker'],
extras_require = {
'ps': ['setproctitle']
},
install_requires = [
'argparse', 'decorator', 'hiredis', 'redis', 'psutil', 'simplejson'],
classifiers = [
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Intended Audience :: Developers',
'Operating System :: OS Independent'
]
)
| #! /usr/bin/env python
from distutils.core import setup
setup(
name = 'qless-py',
version = '0.10.0',
description = 'Redis-based Queue Management',
long_description = '''
Redis-based queue management, with heartbeating, job tracking,
stats, notifications, and a whole lot more.''',
url = 'http://github.com/seomoz/qless-py',
author = 'Dan Lecocq',
author_email = '[email protected]',
license = "MIT License",
keywords = 'redis, qless, job',
packages = ['qless', 'qless.workers'],
package_dir = {
'qless': 'qless',
'qless.workers': 'qless/workers'},
package_data = {'qless': ['qless-core/*.lua']},
include_package_data = True,
scripts = ['bin/qless-py-worker'],
extras_require = {
'ps': ['setproctitle']
},
install_requires = [
'argparse', 'hiredis', 'redis', 'psutil', 'simplejson'],
classifiers = [
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Intended Audience :: Developers',
'Operating System :: OS Independent'
]
)
|
Correct URL used for refunding application fees
Fixes #208.
See also stripe/stripe-ruby#351. | <?php
namespace Stripe;
class ApplicationFee extends ApiResource
{
/**
* This is a special case because the application fee endpoint has an
* underscore in it. The parent `className` function strips underscores.
*
* @return string The name of the class.
*/
public static function className()
{
return 'application_fee';
}
/**
* @param string $id The ID of the application fee to retrieve.
* @param array|string|null $opts
*
* @return ApplicationFee
*/
public static function retrieve($id, $opts = null)
{
return self::_retrieve($id, $opts);
}
/**
* @param array|null $params
* @param array|string|null $opts
*
* @return Collection of ApplicationFees
*/
public static function all($params = null, $opts = null)
{
return self::_all($params, $opts);
}
/**
* @param array|null $params
* @param array|string|null $opts
*
* @return ApplicationFee The refunded application fee.
*/
public function refund($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/refunds';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
}
| <?php
namespace Stripe;
class ApplicationFee extends ApiResource
{
/**
* This is a special case because the application fee endpoint has an
* underscore in it. The parent `className` function strips underscores.
*
* @return string The name of the class.
*/
public static function className()
{
return 'application_fee';
}
/**
* @param string $id The ID of the application fee to retrieve.
* @param array|string|null $opts
*
* @return ApplicationFee
*/
public static function retrieve($id, $opts = null)
{
return self::_retrieve($id, $opts);
}
/**
* @param array|null $params
* @param array|string|null $opts
*
* @return Collection of ApplicationFees
*/
public static function all($params = null, $opts = null)
{
return self::_all($params, $opts);
}
/**
* @param array|null $params
* @param array|string|null $opts
*
* @return ApplicationFee The refunded application fee.
*/
public function refund($params = null, $opts = null)
{
$url = $this->instanceUrl() . '/refund';
list($response, $opts) = $this->_request('post', $url, $params, $opts);
$this->refreshFrom($response, $opts);
return $this;
}
}
|
Remove " " from log name | # -*- coding: utf-8 -*-
import datetime
import logging
import os
import hashlib
from utils.settings_handler import settings
def set_up_logging():
"""
Logger for tenhou communication and AI output
"""
logs_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'logs')
if not os.path.exists(logs_directory):
os.mkdir(logs_directory)
# we shouldn't be afraid about collision
# also, we need it to distinguish different bots logs (if they were run in the same time)
name_hash = hashlib.sha1(settings.USER_ID.encode('utf-8')).hexdigest()[:5]
logger = logging.getLogger('tenhou')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
file_name = '{}_{}.log'.format(name_hash, datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S'))
fh = logging.FileHandler(os.path.join(logs_directory, file_name))
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(fh)
logger = logging.getLogger('ai')
logger.setLevel(logging.DEBUG)
logger.addHandler(ch)
logger.addHandler(fh)
| # -*- coding: utf-8 -*-
import datetime
import logging
import os
import hashlib
from utils.settings_handler import settings
def set_up_logging():
"""
Logger for tenhou communication and AI output
"""
logs_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'logs')
if not os.path.exists(logs_directory):
os.mkdir(logs_directory)
# we shouldn't be afraid about collision
# also, we need it to distinguish different bots logs (if they were run in the same time)
name_hash = hashlib.sha1(settings.USER_ID.encode('utf-8')).hexdigest()[:5]
logger = logging.getLogger('tenhou')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
file_name = '{}_{}.log'.format(name_hash, datetime.datetime.now().strftime('%Y-%m-%d %H_%M_%S'))
fh = logging.FileHandler(os.path.join(logs_directory, file_name))
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(fh)
logger = logging.getLogger('ai')
logger.setLevel(logging.DEBUG)
logger.addHandler(ch)
logger.addHandler(fh)
|
Use local json-rpc.php file for mysql demo | <?php
require('json-rpc.php');
if (function_exists('xdebug_disable')) {
xdebug_disable();
}
$link = new mysqli('localhost', 'user', 'password', 'db_name');
class MysqlDemo {
public function query($query) {
global $link;
if (preg_match("/create|drop/", $query)) {
throw new Exception("Sorry you are not allowed to execute '" .
$query . "'");
}
if (!preg_match("/(select.*from *test|insert *into *test.*|delete *from *test|update *test)/", $query)) {
throw new Exception("Sorry you can't execute '" . $query .
"' you are only allowed to select, insert, delete " .
"or update 'test' table");
}
if ($res = $link->query($query)) {
if ($res === true) {
return true;
}
if ($res->num_rows > 0) {
while ($row = $res->fetch_array(MYSQLI_NUM)) {
$result[] = $row;
}
return $result;
} else {
return array();
}
} else {
throw new Exception("MySQL Error: " . mysql_error());
}
}
}
handle_json_rpc(new MysqlDemo());
?>
| <?php
require('json-rpc/json-rpc.php');
if (function_exists('xdebug_disable')) {
xdebug_disable();
}
$link = new mysqli('localhost', 'user', 'password', 'db_name');
class MysqlDemo {
public function query($query) {
global $link;
if (preg_match("/create|drop/", $query)) {
throw new Exception("Sorry you are not allowed to execute '" .
$query . "'");
}
if (!preg_match("/(select.*from *test|insert *into *test.*|delete *from *test|update *test)/", $query)) {
throw new Exception("Sorry you can't execute '" . $query .
"' you are only allowed to select, insert, delete " .
"or update 'test' table");
}
if ($res = $link->query($query)) {
if ($res === true) {
return true;
}
if ($res->num_rows > 0) {
while ($row = $res->fetch_array(MYSQLI_NUM)) {
$result[] = $row;
}
return $result;
} else {
return array();
}
} else {
throw new Exception("MySQL Error: " . mysql_error());
}
}
}
handle_json_rpc(new MysqlDemo());
?>
|
Add better handling of temp file | import time
import os
import tempfile
from sys import platform as _platform
from gtts import gTTS
from pygame import mixer
from .playsound import playsound
from ..components import _BaseComponent
class TextToSpeech(_BaseComponent):
def __init__(self, queues):
super().__init__(queues)
self.queue_tts = None
def setup(self):
self.queue_tts = self._queues['QueueTextToSpeech']
def run(self):
while self._is_init:
sentence = self.queue_tts.get()
if sentence is None:
break
print('To say out loud : {}'.format(sentence))
tts = gTTS(text=sentence, lang='en')
if _platform == "darwin":
with tempfile.NamedTemporaryFile() as audio_file:
tts.write_to_fp(audio_file)
audio_file.seek(0)
playsound(audio_file.name)
else:
filename = tempfile.gettempdir() + '/' + str(time.time()).split('.')[0] + ".mp3"
tts.save(filename)
if _platform == "linux" or _platform == "linux2":
mixer.init()
mixer.music.load(filename)
mixer.music.play()
else:
playsound(filename)
os.remove(filename)
self.queue_tts.task_done()
def stop(self):
print('Stopping {0}...'.format(self.__class__.__name__))
self._is_init = False
self.queue_tts.put(None)
| import time
import os
from tempfile import NamedTemporaryFile
from sys import platform as _platform
from gtts import gTTS
from pygame import mixer
from .playsound import playsound
from ..components import _BaseComponent
class TextToSpeech(_BaseComponent):
def __init__(self, queues):
super().__init__(queues)
self.queue_tts = None
def setup(self):
self.queue_tts = self._queues['QueueTextToSpeech']
def run(self):
while self._is_init:
sentence = self.queue_tts.get()
if sentence is None:
break
print('To say out loud : {}'.format(sentence))
tts = gTTS(text=sentence, lang='en')
if _platform == "darwin":
with NamedTemporaryFile() as audio_file:
tts.write_to_fp(audio_file)
audio_file.seek(0)
playsound(audio_file.name)
else:
filename = os.environ['TMP'] + str(
time.time()).split('.')[0] + ".mp3"
tts.save(filename)
if _platform == "linux" or _platform == "linux2":
mixer.init()
mixer.music.load(filename)
mixer.music.play()
else:
playsound(filename)
os.remove(filename)
self.queue_tts.task_done()
def stop(self):
print('Stopping {0}...'.format(self.__class__.__name__))
self._is_init = False
self.queue_tts.put(None)
|
Change timeout requirement to use semver comparator | import os
from setuptools import find_packages, setup
from asgiref import __version__
# We use the README as the long_description
readme_path = os.path.join(os.path.dirname(__file__), "README.rst")
setup(
name='asgiref',
version=__version__,
url='http://github.com/django/asgiref/',
author='Django Software Foundation',
author_email='[email protected]',
description='ASGI specs, helper code, and adapters',
long_description=open(readme_path).read(),
license='BSD',
zip_safe=False,
packages=find_packages(exclude=['tests']),
include_package_data=True,
extras_require={
"tests": [
"pytest~=3.3",
"pytest-asyncio~=0.8",
],
},
install_requires=[
'async_timeout~=3.0',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
],
)
| import os
from setuptools import find_packages, setup
from asgiref import __version__
# We use the README as the long_description
readme_path = os.path.join(os.path.dirname(__file__), "README.rst")
setup(
name='asgiref',
version=__version__,
url='http://github.com/django/asgiref/',
author='Django Software Foundation',
author_email='[email protected]',
description='ASGI specs, helper code, and adapters',
long_description=open(readme_path).read(),
license='BSD',
zip_safe=False,
packages=find_packages(exclude=['tests']),
include_package_data=True,
extras_require={
"tests": [
"pytest~=3.3",
"pytest-asyncio~=0.8",
],
},
install_requires=[
'async_timeout>=3.0,<4.0',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
],
)
|
GH-35: Update for rename of default branch to main | /*
A handlebars helper to allow us to safely output object content from within a template. See the docs for details:
https://github.com/fluid-project/fluid-handlebars/blob/main/docs/jsonifyHelper.md
*/
/* eslint-env node */
"use strict";
var fluid = fluid || require("infusion");
fluid.registerNamespace("fluid.handlebars.helper.jsonify");
fluid.handlebars.helper.jsonify.getJsonifyFunction = function (that) {
return function (contentToStringify, options) {
if (contentToStringify) {
var combinedOptions = fluid.copy(that.options);
if (options && options.hash) {
fluid.each(options.hash, function (value, key) {
combinedOptions[key] = value;
});
}
if (typeof contentToStringify !== "string" || combinedOptions.stringifyStrings) {
try {
return JSON.stringify(contentToStringify, combinedOptions.replacer, combinedOptions.space);
}
catch (e) {
fluid.fail("Can't convert JSON object to string: " + e);
}
}
}
return contentToStringify;
};
};
fluid.defaults("fluid.handlebars.helper.jsonify", {
gradeNames: ["fluid.handlebars.helper"],
helperName: "jsonify",
replacer: null,
stringifyStrings: false,
space: 2,
invokers: {
"getHelper": {
"funcName": "fluid.handlebars.helper.jsonify.getJsonifyFunction",
"args": ["{that}"]
}
}
});
| /*
A handlebars helper to allow us to safely output object content from within a template. See the docs for details:
https://github.com/fluid-project/fluid-handlebars/blob/master/docs/jsonifyHelper.md
*/
/* eslint-env node */
"use strict";
var fluid = fluid || require("infusion");
fluid.registerNamespace("fluid.handlebars.helper.jsonify");
fluid.handlebars.helper.jsonify.getJsonifyFunction = function (that) {
return function (contentToStringify, options) {
if (contentToStringify) {
var combinedOptions = fluid.copy(that.options);
if (options && options.hash) {
fluid.each(options.hash, function (value, key) {
combinedOptions[key] = value;
});
}
if (typeof contentToStringify !== "string" || combinedOptions.stringifyStrings) {
try {
return JSON.stringify(contentToStringify, combinedOptions.replacer, combinedOptions.space);
}
catch (e) {
fluid.fail("Can't convert JSON object to string: " + e);
}
}
}
return contentToStringify;
};
};
fluid.defaults("fluid.handlebars.helper.jsonify", {
gradeNames: ["fluid.handlebars.helper"],
helperName: "jsonify",
replacer: null,
stringifyStrings: false,
space: 2,
invokers: {
"getHelper": {
"funcName": "fluid.handlebars.helper.jsonify.getJsonifyFunction",
"args": ["{that}"]
}
}
});
|
Add identifier property to mixin. | # -*- coding: utf-8 -*-
from .models import Translation
from .utils.i18n import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def identifier(self):
return self._linguist.identifier
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
| # -*- coding: utf-8 -*-
from .models import Translation
from .utils import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
|
Fix chunkhash not allowed in development | // Used to run webpack dev server to test the demo in local
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = (env, options) => ({
mode: options.mode,
devtool: 'source-map',
entry: path.resolve(__dirname, 'demo/js/demo.js'),
output: {
path: path.resolve(__dirname, 'pages'),
filename:
options.mode === 'production'
? '[name][chunkhash].js'
: '[name].js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/],
use: [
{
loader: 'babel-loader',
},
],
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader'],
},
],
},
plugins: [
options.mode === 'development'
? new webpack.HotModuleReplacementPlugin()
: () => {},
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'demo/index.html'),
}),
],
devServer: {
contentBase: './demo',
},
});
| // Used to run webpack dev server to test the demo in local
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = (env, options) => ({
mode: options.mode,
devtool: 'source-map',
entry: path.resolve(__dirname, 'demo/js/demo.js'),
output: {
path: path.resolve(__dirname, 'pages'),
filename: '[name][chunkhash].js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/],
use: [
{
loader: 'babel-loader',
},
],
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader'],
},
],
},
plugins: [
options.mode === 'development'
? new webpack.HotModuleReplacementPlugin()
: () => {},
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'demo/index.html'),
}),
],
devServer: {
contentBase: './demo',
},
});
|
Subsets and Splits