text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use StandardCharsets instead of string value
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.commons.imaging.formats.psd;
import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ImageResourceBlockTest{
@Test
public void testCreatesImageResourceBlockAndCallsGetName() throws UnsupportedEncodingException {
final byte[] byteArray = new byte[3];
final ImageResourceBlock imageResourceBlock = new ImageResourceBlock(0, byteArray, byteArray);
assertEquals( new String(byteArray, StandardCharsets.ISO_8859_1), imageResourceBlock.getName());
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.commons.imaging.formats.psd;
import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ImageResourceBlockTest{
@Test
public void testCreatesImageResourceBlockAndCallsGetName() throws UnsupportedEncodingException {
final byte[] byteArray = new byte[3];
final ImageResourceBlock imageResourceBlock = new ImageResourceBlock(0, byteArray, byteArray);
assertEquals( new String(byteArray, "ISO-8859-1"), imageResourceBlock.getName());
}
}
|
Fix scraper skipping an entry at start.
|
from Database import Database
from Nyaa import Nyaa, NyaaEntry
import getopt
import os
import sys
script_dir = os.path.dirname(os.path.realpath(__file__))
nt = Nyaa()
db = Database(script_dir)
arguments = sys.argv[1:]
optlist, args = getopt.getopt(arguments, '', ['start='])
if len(optlist) > 0:
for opt, arg in optlist:
if opt == '--start':
start_entry = int(arg)
if 'start_entry' not in globals():
start_entry = db.last_entry + 1
for i in range(start_entry, nt.last_entry + 1):
entry = NyaaEntry('http://www.nyaa.se/?page=view&tid={}'.format(i))
if entry.exists == True:
if entry.category in db.categories and entry.sub_category in db.sub_categories:
if entry.magnet == 0:
continue
print('Entry: {}, Name: {}'.format(i, entry.name))
db.write_torrent((i, entry.name, entry.magnet, db.categories[entry.category],
db.sub_categories[entry.sub_category], db.status[entry.status], entry.date, entry.time))
db.c.close()
|
from Database import Database
from Nyaa import Nyaa, NyaaEntry
import getopt
import os
import sys
script_dir = os.path.dirname(os.path.realpath(__file__))
nt = Nyaa()
db = Database(script_dir)
arguments = sys.argv[1:]
optlist, args = getopt.getopt(arguments, '', ['start='])
if len(optlist) > 0:
for opt, arg in optlist:
if opt == '--start':
start_entry = int(arg)
if 'start_entry' not in globals():
start_entry = db.last_entry + 1
for i in range(start_entry + 1, nt.last_entry + 1):
entry = NyaaEntry('http://www.nyaa.se/?page=view&tid={}'.format(i))
if entry.exists == True:
if entry.category in db.categories and entry.sub_category in db.sub_categories:
if entry.magnet == 0:
continue
print('Entry: {}, Name: {}'.format(i, entry.name))
db.write_torrent((i, entry.name, entry.magnet, db.categories[entry.category],
db.sub_categories[entry.sub_category], db.status[entry.status], entry.date, entry.time))
db.c.close()
|
Fix api starting with auth set
|
import importlib
import pecan
from joulupukki.api.controllers.v3.users import UsersController
from joulupukki.api.controllers.v3.projects import ProjectsController
from joulupukki.api.controllers.v3.stats import StatsController
from joulupukki.api.controllers.v3.auth import AuthController
class V3Controller(object):
"""Version 3 API controller root."""
users = UsersController()
projects = ProjectsController()
stats = StatsController()
auth = AuthController()
# Handle github and gitlab auth
if pecan.conf.auth is not None:
try:
externalservice = importlib.import_module('joulupukki.api.controllers.v3.' + pecan.conf.auth).ExternalServiceController()
except Exception as exp:
#TODO
print(exp)
pass
|
import importlib
import pecan
from joulupukki.api.controllers.v3.users import UsersController
from joulupukki.api.controllers.v3.projects import ProjectsController
from joulupukki.api.controllers.v3.stats import StatsController
from joulupukki.api.controllers.v3.auth import AuthController
authcontroller = importlib.import_module('joulupukki.api.controllers.v3.' + pecan.conf.auth)
class V3Controller(object):
"""Version 3 API controller root."""
users = UsersController()
projects = ProjectsController()
stats = StatsController()
auth = AuthController()
# Handle github and gitlab auth
if pecan.conf.auth is not None:
try:
externalservice = importlib.import_module('joulupukki.api.controllers.v3.' + pecan.conf.auth).ExternalServiceController()
except Exception as exp:
#TODO
print(exp)
pass
|
Fix int float setting issue.
|
import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Create command cache for environment where os.listdir is not working'
def handle(self, *args, **options):
try:
os.remove("local/total_settings.py")
except:
pass
with open("local/total_settings.py", "w") as f:
for key, value in dump_attrs(settings):
if value is None:
continue
if type(value) in (list, tuple, dict, bool, int, float):
print >>f, key, "=", value
elif type(value) in (str, ):
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
else:
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
|
import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Create command cache for environment where os.listdir is not working'
def handle(self, *args, **options):
try:
os.remove("local/total_settings.py")
except:
pass
with open("local/total_settings.py", "w") as f:
for key, value in dump_attrs(settings):
if value is None:
continue
if type(value) in (list, tuple, dict, bool):
print >>f, key, "=", value
elif type(value) in (str, ):
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
else:
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
|
Update login form clean method to return full cleaned data.
|
#! coding: utf-8
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import authenticate
class LoginForm(forms.Form):
username = forms.CharField(label=_('Naudotojo vardas'), max_length=100,
help_text=_('VU MIF uosis.mif.vu.lt serverio.'))
password = forms.CharField(label=_(u'Slaptažodis'), max_length=128,
widget=forms.PasswordInput(render_value=False))
def clean(self):
cleaned_data = super(LoginForm, self).clean()
if self.errors:
return cleaned_data
user = authenticate(**cleaned_data)
if not user:
raise forms.ValidationError(_(u'Naudotojo vardas arba slaptažodis '
'yra neteisingi'))
cleaned_data['user'] = user
return cleaned_data
|
#! coding: utf-8
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import authenticate
class LoginForm(forms.Form):
username = forms.CharField(label=_('Naudotojo vardas'), max_length=100,
help_text=_('VU MIF uosis.mif.vu.lt serverio.'))
password = forms.CharField(label=_(u'Slaptažodis'), max_length=128,
widget=forms.PasswordInput(render_value=False))
def clean(self):
cleaned_data = super(LoginForm, self).clean()
if self.errors:
return cleaned_data
user = authenticate(**cleaned_data)
if not user:
raise forms.ValidationError(_(u'Naudotojo vardas arba slaptažodis '
'yra neteisingi'))
return {'user': user}
|
fix(AnnotationBuilder): Remove objective flag from the defaut set of field of an annotation
|
import { generateUUID } from '../UUID';
import SelectionBuilder from '../SelectionBuilder';
// ----------------------------------------------------------------------------
// Internal helpers
// ----------------------------------------------------------------------------
let generation = 0;
function setInitialGenerationNumber(genNum) {
generation = genNum;
}
// ----------------------------------------------------------------------------
// Public builder method
// ----------------------------------------------------------------------------
function annotation(selection, score, weight = 1, rationale = '', name = '') {
generation++;
return {
id: generateUUID(),
generation,
selection,
score,
weight,
rationale,
name,
};
}
// ----------------------------------------------------------------------------
function update(annotationObject, changeSet) {
const updatedAnnotation = Object.assign({}, annotationObject, changeSet);
let changeDetected = false;
Object.keys(updatedAnnotation).forEach(key => {
if (updatedAnnotation[key] !== annotationObject[key]) {
changeDetected = true;
}
});
if (changeDetected) {
generation++;
updatedAnnotation.generation = generation;
}
return updatedAnnotation;
}
// ----------------------------------------------------------------------------
function fork(annotationObj) {
const id = generateUUID();
generation++;
return Object.assign({}, annotationObj, { generation, id });
}
// ----------------------------------------------------------------------------
function markModified(annotationObject) {
generation++;
return Object.assign({}, annotationObject, { generation });
}
// ----------------------------------------------------------------------------
// Exposed object
// ----------------------------------------------------------------------------
const EMPTY_ANNOTATION = annotation(SelectionBuilder.EMPTY_SELECTION, 0);
export default {
annotation,
update,
markModified,
fork,
setInitialGenerationNumber,
EMPTY_ANNOTATION,
};
|
import { generateUUID } from '../UUID';
import SelectionBuilder from '../SelectionBuilder';
// ----------------------------------------------------------------------------
// Internal helpers
// ----------------------------------------------------------------------------
let generation = 0;
function setInitialGenerationNumber(genNum) {
generation = genNum;
}
// ----------------------------------------------------------------------------
// Public builder method
// ----------------------------------------------------------------------------
function annotation(selection, score, weight = 1, rationale = '', name = '') {
generation++;
return {
id: generateUUID(),
generation,
selection,
score,
weight,
rationale,
name,
objective: false,
};
}
// ----------------------------------------------------------------------------
function update(annotationObject, changeSet) {
const updatedAnnotation = Object.assign({}, annotationObject, changeSet);
let changeDetected = false;
Object.keys(updatedAnnotation).forEach(key => {
if (updatedAnnotation[key] !== annotationObject[key]) {
changeDetected = true;
}
});
if (changeDetected) {
generation++;
updatedAnnotation.generation = generation;
}
return updatedAnnotation;
}
// ----------------------------------------------------------------------------
function fork(annotationObj) {
const id = generateUUID();
generation++;
return Object.assign({}, annotationObj, { generation, id });
}
// ----------------------------------------------------------------------------
function markModified(annotationObject) {
generation++;
return Object.assign({}, annotationObject, { generation });
}
// ----------------------------------------------------------------------------
// Exposed object
// ----------------------------------------------------------------------------
const EMPTY_ANNOTATION = annotation(SelectionBuilder.EMPTY_SELECTION, 0);
export default {
annotation,
update,
markModified,
fork,
setInitialGenerationNumber,
EMPTY_ANNOTATION,
};
|
Raise NotImplementedError if pandas is not installed
|
""" Tablib - DataFrame Support.
"""
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
try:
from pandas import DataFrame
except ImportError:
DataFrame = None
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
if DataFrame is None:
return False
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
if DataFrame is None:
raise NotImplementedError(
'DataFrame Format requires `pandas` to be installed.'
' Try `pip install tablib[pandas]`.')
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
|
""" Tablib - DataFrame Support.
"""
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
from pandas import DataFrame
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
|
Update script to use new way of calling class.
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys, os
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to collection")
parser.add_argument('--pynuxrc', default='~/.pynuxrc-prod', help="rcfile for use with pynux utils")
if argv is None:
argv = parser.parse_args()
dh = DeepHarvestNuxeo(argv.path, '', pynuxrc=argv.pynuxrc)
print "about to fetch objects for path {}".format(dh.path)
objects = dh.fetch_objects()
object_count = len(objects)
print "finished fetching objects. {} found".format(object_count)
print "about to iterate through objects and get components"
component_count = 0
for obj in objects:
components = dh.fetch_components(obj)
component_count = component_count + len(components)
print "finished fetching components. {} found".format(component_count)
print "Grand Total: {}".format(object_count + component_count)
if __name__ == "__main__":
sys.exit(main())
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys, os
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to collection")
parser.add_argument('--pynuxrc', default='~/.pynuxrc-prod', help="rcfile for use with pynux utils")
if argv is None:
argv = parser.parse_args()
dh = DeepHarvestNuxeo(argv.path, 'barbarahui_test_bucket', argv.pynuxrc)
print "about to fetch objects for path {}".format(dh.path)
objects = dh.fetch_objects()
object_count = len(objects)
print "finished fetching objects. {} found".format(object_count)
print "about to iterate through objects and get components"
component_count = 0
for obj in objects:
components = dh.fetch_components(obj)
component_count = component_count + len(components)
print "finished fetching components. {} found".format(component_count)
print "Grand Total: {}".format(object_count + component_count)
if __name__ == "__main__":
sys.exit(main())
|
Use const instead of var
|
const data = require("sdk/self").data;
const tabs = require("sdk/tabs");
const { ToggleButton } = require("sdk/ui/button/toggle");
var btn_config = {};
var btn;
function tabToggle(tab) {
if (btn.state('window').checked) {
tab.attach({
contentScriptFile: data.url('embed.js')
});
} else {
tab.attach({
contentScript: [
'var s = document.createElement("script");',
's.setAttribute("src", "' + data.url('destroy.js') + '");',
'document.body.appendChild(s);'
]
});
}
}
btn_config = {
id: "hypothesis",
label: "Annotate",
icon: {
"18": './images/sleeping_18.png',
"32": './images/sleeping_32.png',
"36": './images/sleeping_36.png',
"64": './images/sleeping_64.png'
},
onClick: function(state) {
tabToggle(tabs.activeTab)
}
};
if (undefined === ToggleButton) {
btn = require("sdk/widget").Widget(btn_config);
} else {
btn = ToggleButton(btn_config);
}
tabs.on('open', function(tab) {
tab.on('activate', tabToggle);
tab.on('pageshow', tabToggle);
});
|
var data = require("sdk/self").data;
var tabs = require("sdk/tabs");
var { ToggleButton } = require("sdk/ui/button/toggle");
var btn_config = {};
var btn;
function tabToggle(tab) {
if (btn.state('window').checked) {
tab.attach({
contentScriptFile: data.url('embed.js')
});
} else {
tab.attach({
contentScript: [
'var s = document.createElement("script");',
's.setAttribute("src", "' + data.url('destroy.js') + '");',
'document.body.appendChild(s);'
]
});
}
}
btn_config = {
id: "hypothesis",
label: "Annotate",
icon: {
"18": './images/sleeping_18.png',
"32": './images/sleeping_32.png',
"36": './images/sleeping_36.png',
"64": './images/sleeping_64.png'
},
onClick: function(state) {
tabToggle(tabs.activeTab)
}
};
if (undefined === ToggleButton) {
btn = require("sdk/widget").Widget(btn_config);
} else {
btn = ToggleButton(btn_config);
}
tabs.on('open', function(tab) {
tab.on('activate', tabToggle);
tab.on('pageshow', tabToggle);
});
|
Fix promise implementation in connection tests. Assert on result length as well.
|
import dbConfig from '../src/databaseConfig';
import MssqlSnapshot from '../src/MssqlSnapshot';
import {killConnections, createConnection} from './testUtilities';
describe('when retrieving active connections to a db', function() {
let target = null;
beforeEach(() => {
target = new MssqlSnapshot(dbConfig());
return Promise.all([killConnections, createConnection]);
});
it('it returns an accurate list that includes the current connection', (done) => {
target.connections().then(
(result) => {
result.length.should.eql(1);
result[0].should.have.property('BlockedBy');
result[0].should.have.property('CPUTime');
result[0].should.have.property('DatabaseName');
result[0].should.have.property('DiskIO');
result[0].should.have.property('LastBatch');
result[0].should.have.property('Login');
result[0].should.have.property('ProgramName');
result[0].should.have.property('HostName');
result[0].should.have.property('SPID');
result[0].should.have.property('Status');
done();
},
(err) => {
done(err);
});
});
});
|
import dbConfig from '../src/databaseConfig';
import MssqlSnapshot from '../src/MssqlSnapshot';
import * as utility from './testUtilities';
describe('when retrieving active connections to a db', function() {
let target = null;
beforeEach(() => {
return utility.killConnections()
.then(utility.createConnection)
.then(() => target = new MssqlSnapshot(dbConfig()));
});
it('it returns an accurate list that includes the current connection', (done) => {
target.connections().then(
(result) => {
result[0].should.have.property('BlockedBy');
result[0].should.have.property('CPUTime');
result[0].should.have.property('DatabaseName');
result[0].should.have.property('DiskIO');
result[0].should.have.property('LastBatch');
result[0].should.have.property('Login');
result[0].should.have.property('ProgramName');
result[0].should.have.property('HostName');
result[0].should.have.property('SPID');
result[0].should.have.property('Status');
done();
},
(err) => {
done(err);
});
});
});
|
Demo: Put radio buttons within <label> element
|
'use strict'
class HelloMessage2 extends Cape.Component {
constructor(name) {
super()
this.names = [ 'alice', 'bob', 'charlie' ]
this.name = name
}
render(m) {
m.h1('Greeting')
m.p('Who are you?')
m.div(m => {
this.names.forEach(name => {
m.label(m => {
m.checked(name === this.name)
.onclick(e => { this.name = e.target.value; this.refresh() })
.radioButton('name', name)
m.sp()
m.text(name)
})
})
})
m.class('message').p(m => {
m.text('Hello, ')
m.em(this.name + '!')
m.sp()
m.text('My name is Cape.JS.')
})
}
}
if (typeof module !== 'undefined' && module.exports) module.exports = HelloMessage2
|
'use strict'
class HelloMessage2 extends Cape.Component {
constructor(name) {
super()
this.names = [ 'alice', 'bob', 'charlie' ]
this.name = name
}
render(m) {
m.h1('Greeting')
m.p('Who are you?')
m.div(m => {
this.names.forEach(name => {
m.checked(name === this.name)
.onclick(e => { this.name = e.target.value; this.refresh() })
.radioButton('name', name)
m.sp()
m.text(name)
})
})
m.class('message').p(m => {
m.text('Hello, ')
m.em(this.name + '!')
m.sp()
m.text('My name is Cape.JS.')
})
}
}
if (typeof module !== 'undefined' && module.exports) module.exports = HelloMessage2
|
Add results to environment parameters RESULT_M, RESULT_B
|
#/usr/bin/python
""" Baseline example that needs to be beaten """
import os
import numpy as np
import matplotlib.pyplot as plt
x, y, yerr = np.loadtxt("data/data.txt", unpack=True)
A = np.vstack((np.ones_like(x), x)).T
C = np.diag(yerr * yerr)
cov = np.linalg.inv(np.dot(A.T, np.linalg.solve(C, A)))
b_ls, m_ls = np.dot(cov, np.dot(A.T, np.linalg.solve(C, y)))
fig, ax = plt.subplots()
ax.errorbar(x, y, yerr=yerr, c="k", fmt="o")
x_range = np.array([min(x), max(x)])
ax.plot(x_range, m_ls * x_range + b_ls, c="#666666", lw=2, zorder=-100)
ax.set_xlabel("x")
ax.set_ylabel("y")
fig.savefig("assets/result.png")
print("Results of m, b: ({0:.4f} {1:.4f})".format(m_ls, b_ls))
# Let's store result parameters in environment variables, and we will deal
# with more complex values (e.g., uncertainties, etc) later
os.environ["RESULT_M"] = "{0:.5f}".format(m_ls)
os.environ["RESULT_B"] = "{0:.5f}".format(b_ls)
|
#/usr/bin/python
""" Baseline example that needs to be beaten """
import numpy as np
import matplotlib.pyplot as plt
x, y, yerr = np.loadtxt("data/data.txt", unpack=True)
A = np.vstack((np.ones_like(x), x)).T
C = np.diag(yerr * yerr)
cov = np.linalg.inv(np.dot(A.T, np.linalg.solve(C, A)))
b_ls, m_ls = np.dot(cov, np.dot(A.T, np.linalg.solve(C, y)))
fig, ax = plt.subplots()
ax.errorbar(x, y, yerr=yerr, c="k", fmt="o")
x_range = np.array([min(x), max(x)])
ax.plot(x_range, m_ls * x_range + b_ls, c="#666666", lw=2, zorder=-100)
ax.set_xlabel("x")
ax.set_ylabel("y")
fig.savefig("assets/result.png")
print m_ls, b_ls
|
Add support for reading snapshots for program audit reader
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "AuditImplied"
description = """
A user with the ProgramReader role for a private program will also have this
role in the audit context for any audit created for that program.
"""
permissions = {
"read": [
"Snapshot",
"Request",
"Comment",
"Assessment",
"Issue",
"Audit",
"AuditObject",
"Meeting",
"ObjectDocument",
"ObjectPerson",
"Relationship",
"Document",
"Meeting",
"UserRole",
"Context",
],
"create": [],
"view_object_page": [
"__GGRC_ALL__"
],
"update": [],
"delete": []
}
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "AuditImplied"
description = """
A user with the ProgramReader role for a private program will also have this
role in the audit context for any audit created for that program.
"""
permissions = {
"read": [
"Request",
"Comment",
"Assessment",
"Issue",
"Audit",
"AuditObject",
"Meeting",
"ObjectDocument",
"ObjectPerson",
"Relationship",
"Document",
"Meeting",
"UserRole",
"Context",
],
"create": [],
"view_object_page": [
"__GGRC_ALL__"
],
"update": [],
"delete": []
}
|
Test now fails properly without feature.
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from rollyourown.seo.admin import register_seo_admin, get_inline
from django.contrib import admin
from userapp.seo import Coverage, WithSites
register_seo_admin(admin.site, Coverage)
register_seo_admin(admin.site, WithSites)
from userapp.models import Product, Page, Category, Tag, NoPath
class WithMetadataAdmin(admin.ModelAdmin):
inlines = [get_inline(Coverage), get_inline(WithSites)]
admin.site.register(Product, admin.ModelAdmin)
admin.site.register(Page, admin.ModelAdmin)
admin.site.register(Tag, WithMetadataAdmin)
admin.site.register(NoPath, WithMetadataAdmin)
alternative_site = admin.AdminSite()
#from rollyourown.seo.admin import auto_register_inlines
alternative_site.register(Tag)
#auto_register_inlines(Coverage, alternative_site)
alternative_site.register(Page)
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from rollyourown.seo.admin import register_seo_admin, get_inline
from django.contrib import admin
from userapp.seo import Coverage, WithSites
register_seo_admin(admin.site, Coverage)
register_seo_admin(admin.site, WithSites)
from userapp.models import Product, Page, Category, Tag, NoPath
class WithMetadataAdmin(admin.ModelAdmin):
inlines = [get_inline(Coverage), get_inline(WithSites)]
admin.site.register(Product, admin.ModelAdmin)
admin.site.register(Page, admin.ModelAdmin)
admin.site.register(Tag, WithMetadataAdmin)
admin.site.register(NoPath, WithMetadataAdmin)
alternative_site = admin.AdminSite()
#from rollyourown.seo.admin import auto_register_inlines
#alternative_site.register(Tag)
#auto_register_inlines(Coverage, alternative_site)
#alternative_site.register(Page)
|
Fix returned value from ternary operation
|
<?php
namespace Fulfillment\Postage\Api;
use Fulfillment\Postage\Models\Request\Contracts\Postage as PostageContract;
use Fulfillment\Postage\Exceptions\ValidationFailureException;
use Fulfillment\Postage\Models\Response\Postage as ResponsePostage;
use Fulfillment\Postage\Models\Request\Postage as RequestPostage;
class PostageApi extends ApiRequestBase
{
/**
* @param PostageContract|array $postage
* @param bool|true $validateRequest
*
* @return RequestPostage|array
* @throws ValidationFailureException
* @throws \JsonMapper_Exception
*/
public function createPostage($postage, $validateRequest = true)
{
$this->tryValidation($postage, $validateRequest);
$json = $this->apiClient->post('postage', $postage);
return ($this->jsonOnly ? $json : $this->jsonMapper->map($json, new ResponsePostage()));
}
}
|
<?php
namespace Fulfillment\Postage\Api;
use Fulfillment\Postage\Models\Request\Contracts\Postage as PostageContract;
use Fulfillment\Postage\Exceptions\ValidationFailureException;
use Fulfillment\Postage\Models\Request\Postage;
class PostageApi extends ApiRequestBase
{
/**
* @param PostageContract|array $postage
* @param bool|true $validateRequest
*
* @return Postage|array
* @throws ValidationFailureException
* @throws \JsonMapper_Exception
*/
public function createPostage($postage, $validateRequest = true)
{
$this->tryValidation($postage, $validateRequest);
$json = $this->apiClient->post('postage/', $postage);
return $this->jsonOnly ? $json : $this->jsonMapper->map($json, new Postage());
}
}
|
Add a symlink to downloaded manifest.
|
#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
names = f.namelist()
if len(names) != 1:
raise Exception("too many entries: %s", names)
f.extractall(path=os.path.dirname(sys.argv[2]))
os.symlink(names[0], sys.argv[2])
|
#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
f.extractall()
|
Make code compatible with no user agent
|
import copy
from django import template
from django.conf import settings
from games import models
register = template.Library()
def get_links(user_agent):
systems = ['ubuntu', 'fedora', 'linux']
downloads = copy.copy(settings.DOWNLOADS)
main_download = None
for system in systems:
if system in user_agent:
main_download = {system: settings.DOWNLOADS[system]}
downloads.pop(system)
if not main_download:
main_download = {'linux': downloads.pop('linux')}
return (main_download, downloads)
@register.inclusion_tag('includes/download_links.html', takes_context=True)
def download_links(context):
request = context['request']
user_agent = request.META.get('HTTP_USER_AGENT', '').lower()
context['main_download'], context['downloads'] = get_links(user_agent)
return context
@register.inclusion_tag('includes/featured_slider.html', takes_context=True)
def featured_slider(context):
context['featured_contents'] = models.Featured.objects.all()
return context
@register.inclusion_tag('includes/latest_games.html', takes_context=True)
def latest_games(context):
games = models.Game.objects.published().order_by('-created')[:5]
context['latest_games'] = games
return context
|
import copy
from django import template
from django.conf import settings
from games import models
register = template.Library()
def get_links(user_agent):
systems = ['ubuntu', 'fedora', 'linux']
downloads = copy.copy(settings.DOWNLOADS)
main_download = None
for system in systems:
if system in user_agent:
main_download = {system: settings.DOWNLOADS[system]}
downloads.pop(system)
if not main_download:
main_download = {'linux': downloads.pop('linux')}
return (main_download, downloads)
@register.inclusion_tag('includes/download_links.html', takes_context=True)
def download_links(context):
request = context['request']
user_agent = request.META['HTTP_USER_AGENT'].lower()
context['main_download'], context['downloads'] = get_links(user_agent)
return context
@register.inclusion_tag('includes/featured_slider.html', takes_context=True)
def featured_slider(context):
context['featured_contents'] = models.Featured.objects.all()
return context
@register.inclusion_tag('includes/latest_games.html', takes_context=True)
def latest_games(context):
games = models.Game.objects.published().order_by('-created')[:5]
context['latest_games'] = games
return context
|
Set logging level higher so we don't spam tests with debug messages
|
"""
Tests of neo.rawio.examplerawio
Note for dev:
if you write a new RawIO class your need to put some file
to be tested at g-node portal, Ask neuralensemble list for that.
The file need to be small.
Then you have to copy/paste/renamed the TestExampleRawIO
class and a full test will be done to test if the new coded IO
is compliant with the RawIO API.
If you have problems, do not hesitate to ask help github (prefered)
of neuralensemble list.
Note that same mechanism is used a neo.io API so files are tested
several time with neo.rawio (numpy buffer) and neo.io (neo object tree).
See neo.test.iotest.*
Author: Samuel Garcia
"""
import logging
import unittest
from neo.rawio.alphaomegarawio import AlphaOmegaRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
logging.getLogger().setLevel(logging.INFO)
class TestAlphaOmegaRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = AlphaOmegaRawIO
entities_to_download = [
"alphaomega",
]
entities_to_test = [
"alphaomega/",
]
if __name__ == "__main__":
unittest.main()
|
"""
Tests of neo.rawio.examplerawio
Note for dev:
if you write a new RawIO class your need to put some file
to be tested at g-node portal, Ask neuralensemble list for that.
The file need to be small.
Then you have to copy/paste/renamed the TestExampleRawIO
class and a full test will be done to test if the new coded IO
is compliant with the RawIO API.
If you have problems, do not hesitate to ask help github (prefered)
of neuralensemble list.
Note that same mechanism is used a neo.io API so files are tested
several time with neo.rawio (numpy buffer) and neo.io (neo object tree).
See neo.test.iotest.*
Author: Samuel Garcia
"""
import unittest
from neo.rawio.alphaomegarawio import AlphaOmegaRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
class TestAlphaOmegaRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = AlphaOmegaRawIO
entities_to_download = [
"alphaomega",
]
entities_to_test = [
"alphaomega/",
]
if __name__ == "__main__":
unittest.main()
|
Make assertion message use same var as test
Ensure that the assertion message correctly shows the value used by
the assertion test.
|
from collections import OrderedDict
from itertools import chain
from ..utils.orderedtype import OrderedType
from .structures import NonNull
class Argument(OrderedType):
def __init__(self, type, default_value=None, description=None, name=None, required=False, _creation_counter=None):
super(Argument, self).__init__(_creation_counter=_creation_counter)
if required:
type = NonNull(type)
self.name = name
self.type = type
self.default_value = default_value
self.description = description
def to_arguments(args, extra_args):
from .unmountedtype import UnmountedType
extra_args = sorted(extra_args.items(), key=lambda f: f[1])
iter_arguments = chain(args.items(), extra_args)
arguments = OrderedDict()
for default_name, arg in iter_arguments:
if isinstance(arg, UnmountedType):
arg = arg.Argument()
if not isinstance(arg, Argument):
raise ValueError('Unknown argument "{}".'.format(default_name))
arg_name = default_name or arg.name
assert arg_name not in arguments, 'More than one Argument have same name "{}".'.format(arg_name)
arguments[arg_name] = arg
return arguments
|
from collections import OrderedDict
from itertools import chain
from ..utils.orderedtype import OrderedType
from .structures import NonNull
class Argument(OrderedType):
def __init__(self, type, default_value=None, description=None, name=None, required=False, _creation_counter=None):
super(Argument, self).__init__(_creation_counter=_creation_counter)
if required:
type = NonNull(type)
self.name = name
self.type = type
self.default_value = default_value
self.description = description
def to_arguments(args, extra_args):
from .unmountedtype import UnmountedType
extra_args = sorted(extra_args.items(), key=lambda f: f[1])
iter_arguments = chain(args.items(), extra_args)
arguments = OrderedDict()
for default_name, arg in iter_arguments:
if isinstance(arg, UnmountedType):
arg = arg.Argument()
if not isinstance(arg, Argument):
raise ValueError('Unknown argument "{}".'.format(default_name))
arg_name = default_name or arg.name
assert arg_name not in arguments, 'More than one Argument have same name "{}".'.format(arg.name)
arguments[arg_name] = arg
return arguments
|
Add renderer for Composite_Cc getTemplateVars
fixes Cc html component (which needs renderer)
|
<?php
class Kwc_Abstract_Composite_Cc_Component extends Kwc_Chained_Cc_Component
{
public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
{
$ret = parent::getTemplateVars($renderer);
foreach ($this->getData()->getChildComponents(array('generator' => 'child')) as $c) {
if ($ret[$c->id]) $ret[$c->id] = $c; // Bei TextImage kann zB. Bild ausgeblendet werden und soll dann in Übersetzung auch nicht angezeigt werden
}
return $ret;
}
public function hasContent()
{
foreach ($this->getData()->getChildComponents(array('generator' => 'child')) as $c) {
if ($c->hasContent()) return true;
}
return false;
}
}
|
<?php
class Kwc_Abstract_Composite_Cc_Component extends Kwc_Chained_Cc_Component
{
public function getTemplateVars()
{
$ret = parent::getTemplateVars();
foreach ($this->getData()->getChildComponents(array('generator' => 'child')) as $c) {
if ($ret[$c->id]) $ret[$c->id] = $c; // Bei TextImage kann zB. Bild ausgeblendet werden und soll dann in Übersetzung auch nicht angezeigt werden
}
return $ret;
}
public function hasContent()
{
foreach ($this->getData()->getChildComponents(array('generator' => 'child')) as $c) {
if ($c->hasContent()) return true;
}
return false;
}
}
|
Fix modifications of Composer\Util\RemoteFilesystem (constructor)
|
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Naderman\Composer\AWS;
use Composer\Composer;
use Composer\Config;
use Composer\IO\IOInterface;
use Composer\Util\RemoteFilesystem;
/**
* Composer Plugin for AWS functionality
*
* @author Nils Adermann <naderman@naderman.de>
*/
class S3RemoteFilesystem extends RemoteFilesystem
{
protected $awsClient;
/**
* {@inheritDoc}
*/
public function __construct(IOInterface $io, Config $config = null, array $options = array(), AwsClient $awsClient)
{
parent::__construct($io, $config, $options);
$this->awsClient = $awsClient;
}
/**
* {@inheritDoc}
*/
public function getContents($originUrl, $fileUrl, $progress = true, $options = array())
{
return $this->awsClient->download($fileUrl, $progress);
}
/**
* {@inheritDoc}
*/
public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array())
{
$this->awsClient->download($fileUrl, $progress, $fileName);
}
}
|
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Naderman\Composer\AWS;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Util\RemoteFilesystem;
/**
* Composer Plugin for AWS functionality
*
* @author Nils Adermann <naderman@naderman.de>
*/
class S3RemoteFilesystem extends RemoteFilesystem
{
protected $awsClient;
/**
* {@inheritDoc}
*/
public function __construct(IOInterface $io, $options, AwsClient $awsClient)
{
parent::__construct($io, $options);
$this->awsClient = $awsClient;
}
/**
* {@inheritDoc}
*/
public function getContents($originUrl, $fileUrl, $progress = true, $options = array())
{
return $this->awsClient->download($fileUrl, $progress);
}
/**
* {@inheritDoc}
*/
public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array())
{
$this->awsClient->download($fileUrl, $progress, $fileName);
}
}
|
Remove mildly useful but highly dangerous debug feature.
|
<?php
class Config {
public function __construct() {
$raw_config = file_get_contents(__DIR__ . '/../config.json');
if (!$raw_config) {
throw new FileNotFoundException('Unable to load config.');
}
$vars = json_decode($raw_config, true /* as array */);
$this->vars = [];
foreach ($vars as $k => $v) {
$f = function($match) { return mb_strtoupper($match{1}); };
$key = preg_replace_callback('/\\.([a-z])/', $f, $k);
$this->vars[$k] = $v;
}
if (!$this->vars) {
throw new UnexpectedValueException('Unable to parse config.');
}
}
public function __call($name, $arguments) {
if (isset($this->vars[$name])) {
return $this->vars[$name];
}
if (isset($arguments[0])) {
return $arguments[0];
}
return null;
}
}
|
<?php
class Config {
public function __construct() {
$raw_config = file_get_contents(__DIR__ . '/../config.json');
if (!$raw_config) {
throw new FileNotFoundException('Unable to load config.');
}
$vars = json_decode($raw_config, true /* as array */);
$this->vars = [];
foreach ($vars as $k => $v) {
$f = function($match) { return mb_strtoupper($match{1}); };
$key = preg_replace_callback('/\\.([a-z])/', $f, $k);
$this->vars[$k] = $v;
}
if (!$this->vars) {
throw new UnexpectedValueException('Unable to parse config.');
}
}
public function __call($name, $arguments) {
if (isset($_GET[$name])) {
return $_GET[$name];
}
if (isset($this->vars[$name])) {
return $this->vars[$name];
}
if (isset($arguments[0])) {
return $arguments[0];
}
return null;
}
}
|
Mark this test as xfail
|
# TestREPLThrowReturn.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
"""Test that the REPL correctly handles the case that a called function throws."""
import os, time
import unittest2
import lldb
from lldbsuite.test.lldbrepl import REPLTest, load_tests
import lldbsuite.test.decorators as decorators
class REPLThrowReturnTestCase (REPLTest):
mydir = REPLTest.compute_mydir(__file__)
@decorators.swiftTest
@decorators.skipUnlessDarwin
@decorators.no_debug_info_test
@decorators.expectedFailureAll(oslist=["macosx"], bugnumber="rdar://27648290")
def testREPL(self):
REPLTest.testREPL(self)
def doTest(self):
self.sendline('import Foundation; Data()')
self.sendline('enum VagueProblem: Error { case SomethingWentWrong }; func foo() throws -> Int { throw VagueProblem.SomethingWentWrong }')
self.promptSync()
self.command('foo()', patterns=['\\$E0', 'SomethingWentWrong'])
|
# TestREPLThrowReturn.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
"""Test that the REPL correctly handles the case that a called function throws."""
import os, time
import unittest2
import lldb
from lldbsuite.test.lldbrepl import REPLTest, load_tests
import lldbsuite.test.decorators as decorators
class REPLThrowReturnTestCase (REPLTest):
mydir = REPLTest.compute_mydir(__file__)
@decorators.swiftTest
@decorators.skipUnlessDarwin
@decorators.no_debug_info_test
@decorators.expectedFlakeyDarwin
def testREPL(self):
REPLTest.testREPL(self)
def doTest(self):
self.sendline('import Foundation; Data()')
self.sendline('enum VagueProblem: Error { case SomethingWentWrong }; func foo() throws -> Int { throw VagueProblem.SomethingWentWrong }')
self.promptSync()
self.command('foo()', patterns=['\\$E0', 'SomethingWentWrong'])
|
Add page keywords for new 5.6.1 page
Former-commit-id: 4b8c1dd1a20b6d0fb8229ef8a29adf8ba92807f4
|
<?
defined('C5_EXECUTE') or die("Access Denied.");
class ConcreteUpgradeVersion561Helper {
public $dbRefreshTables = array(
'Blocks',
'CollectionVersionBlocksOutputCache',
'PermissionAccessList'
);
public function run() {
$sp = Page::getByPath('/dashboard/system/seo/excluded');
if (!is_object($sp) || $sp->isError()) {
$sp = SinglePage::add('/dashboard/system/seo/excluded');
$sp->update(array('cName'=>t('Excluded URL Word List')));
$sp->setAttribute('meta_keywords', t('pretty, slug'));
}
$bt = BlockType::getByHandle('next_previous');
if (is_object($bt)) {
$bt->refresh();
}
$db = Loader::db();
$columns = $db->MetaColumns('Pages');
if (isset($columns['PTID'])) {
$db->Execute('alter table Pages drop column ptID');
}
if (isset($columns['CTID'])) {
$db->Execute('alter table Pages drop column ctID');
}
$bt = BlockType::getByHandle('search');
if (is_object($bt)) {
$bt->refresh();
}
}
}
|
<?
defined('C5_EXECUTE') or die("Access Denied.");
class ConcreteUpgradeVersion561Helper {
public $dbRefreshTables = array(
'Blocks',
'CollectionVersionBlocksOutputCache',
'PermissionAccessList'
);
public function run() {
$sp = Page::getByPath('/dashboard/system/seo/excluded');
if (!is_object($sp) || $sp->isError()) {
$sp = SinglePage::add('/dashboard/system/seo/excluded');
$sp->update(array('cName'=>t('Excluded URL Word List')));
}
$bt = BlockType::getByHandle('next_previous');
if (is_object($bt)) {
$bt->refresh();
}
$db = Loader::db();
$columns = $db->MetaColumns('Pages');
if (isset($columns['PTID'])) {
$db->Execute('alter table Pages drop column ptID');
}
if (isset($columns['CTID'])) {
$db->Execute('alter table Pages drop column ctID');
}
$bt = BlockType::getByHandle('search');
if (is_object($bt)) {
$bt->refresh();
}
}
}
|
Use pyramid.paster instad of paste.deploy
--HG--
extra : convert_revision : g.bagnoli%40asidev.com-20110509152058-7sd3ek2lvqrdksuw
|
import os
import logging
import pyramid.paster
from paste.script.util.logging_config import fileConfig
log = logging.getLogger(__name__)
def get_pylons_app(global_conf):
pyramid_config = os.path.realpath(global_conf['__file__'])
dir_, conf = os.path.split(pyramid_config)
config_file = os.path.join(dir_, "pylons-%s" % (conf))
logging.debug("Pyramid config from :%s, pylons config: %s",
pyramid_config, config_file)
fileConfig(config_file)
log.info("Loading application from %s", config_file)
app = pyramid.paster.get_app(config_file, 'main')
if not hasattr(app, "__name__"):
app.__name__ = "Wrapped Pylons app"
return app
|
import os
import logging
from paste.deploy import loadapp
from paste.script.util.logging_config import fileConfig
log = logging.getLogger(__name__)
def get_pylons_app(global_conf):
pyramid_config = os.path.realpath(global_conf['__file__'])
dir_, conf = os.path.split(pyramid_config)
config_file = os.path.join(dir_, "pylons-%s" % (conf))
logging.debug("Pyramid config from :%s, pylons config: %s",
pyramid_config, config_file)
fileConfig(config_file)
log.info("Loading application from %s", config_file)
app = loadapp("config:%s" % (config_file))
if not hasattr(app, "__name__"):
app.__name__ = "Wrapped Pylons app"
return app
|
Fix the tile entity type (just push out null. We don't need this here)
|
package info.u_team.u_team_core.util.registry;
import java.util.function.Supplier;
import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;
public class TileEntityTypeDeferredRegister {
public static TileEntityTypeDeferredRegister create(String modid) {
return new TileEntityTypeDeferredRegister(modid);
}
private final CommonDeferredRegister<TileEntityType<?>> register;
protected TileEntityTypeDeferredRegister(String modid) {
register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
}
public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
return register.register(name, () -> supplier.get().build(null));
}
public void register(IEventBus bus) {
register.register(bus);
}
public CommonDeferredRegister<TileEntityType<?>> getRegister() {
return register;
}
}
|
package info.u_team.u_team_core.util.registry;
import java.util.function.Supplier;
import com.mojang.datafixers.DataFixUtils;
import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraft.util.SharedConstants;
import net.minecraft.util.datafix.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;
public class TileEntityTypeDeferredRegister {
public static TileEntityTypeDeferredRegister create(String modid) {
return new TileEntityTypeDeferredRegister(modid);
}
private final CommonDeferredRegister<TileEntityType<?>> register;
protected TileEntityTypeDeferredRegister(String modid) {
register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
}
public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
return register.register(name, () -> supplier.get().build(DataFixesManager.getDataFixer().getSchema(DataFixUtils.makeKey(SharedConstants.getVersion().getWorldVersion())).getChoiceType(TypeReferences.BLOCK_ENTITY, register.getModid() + ":" + name)));
}
public void register(IEventBus bus) {
register.register(bus);
}
public CommonDeferredRegister<TileEntityType<?>> getRegister() {
return register;
}
}
|
fix(analysis): Set date to YYYY-MM-DD format
fix #873
|
import React from 'react'
import DateTime from 'react-datetime'
let datePickerCount = 0
export default function DatePicker(p) {
// Run once on mount and cleanup on unmount
React.useEffect(() => {
datePickerCount++
return () => datePickerCount--
}, [])
function onChange(date) {
// If the date hasjust been cleared, don't save it
if (!date || !date.toISOString) return
// grab just the date portion of the ISO
// ISO is in UTC, see comment below
p.onChange(date.toISOString().split('T')[0])
}
return (
<DateTime
dateFormat='YYYY-MM-DD'
type='date'
closeOnSelect
value={new Date(p.value)}
timeFormat={false}
inputProps={{
disabled: p.disabled,
id: `date-picker-${datePickerCount}`
}}
utc // because new Date('2016-12-12') yields a date at midnight UTC
onChange={onChange}
/>
)
}
|
import React from 'react'
import DateTime from 'react-datetime'
let datePickerCount = 0
export default function DatePicker(p) {
// Run once on mount and cleanup on unmount
React.useEffect(() => {
datePickerCount++
return () => datePickerCount--
}, [])
function onChange(date) {
// If the date hasjust been cleared, don't save it
if (!date || !date.toISOString) return
// grab just the date portion of the ISO
// ISO is in UTC, see comment below
p.onChange(date.toISOString().split('T')[0])
}
return (
<DateTime
type='date'
closeOnSelect
value={new Date(p.value)}
timeFormat={false}
inputProps={{
disabled: p.disabled,
id: `date-picker-${datePickerCount}`
}}
utc // because new Date('2016-12-12') yields a date at midnight UTC
onChange={onChange}
/>
)
}
|
Revert "Revert "[HOTFIX] Remove replaces line on 0001_squashed""
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Channel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=20)),
],
),
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('text', models.TextField(max_length=2000)),
('datetime', models.DateTimeField()),
('channel', models.ForeignKey(to='chat.Channel')),
('username', models.CharField(max_length=20)),
],
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
replaces = [(b'chat', '0001_squashed_0008_auto_20150702_1437'), (b'chat', '0002_auto_20150707_1647')]
dependencies = [
]
operations = [
migrations.CreateModel(
name='Channel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=20)),
],
),
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('text', models.TextField(max_length=2000)),
('datetime', models.DateTimeField()),
('channel', models.ForeignKey(to='chat.Channel')),
('username', models.CharField(max_length=20)),
],
),
]
|
Add default BUFFER_SIZE for feeds
|
# -*- coding: utf-8 -*-
from collections import deque
from logbook import Logger
log = Logger('pyFxTrader')
class Strategy(object):
TIMEFRAMES = [] # e.g. ['M30', 'H2']
BUFFER_SIZE = 500
feeds = {}
def __init__(self, instrument):
self.instrument = instrument
if not self.TIMEFRAMES:
raise ValueError('Please define TIMEFRAMES variable.')
for tf in self.TIMEFRAMES:
self.feeds[tf] = deque(maxlen=self.BUFFER_SIZE)
log.info('Initialized %s feed for %s' % (tf, self.instrument))
def start(self):
"""Called on strategy start."""
raise NotImplementedError()
def new_bar(self, instrument, cur_index):
"""Called on every bar of every instrument that client is subscribed on."""
raise NotImplementedError()
def execute(self, engine, instruments, cur_index):
"""Called on after all indicators have been updated for this bar's index"""
raise NotImplementedError()
def end(self, engine):
"""Called on strategy stop."""
raise NotImplementedError()
|
# -*- coding: utf-8 -*-
class Strategy(object):
TIMEFRAMES = [] # e.g. ['M30', 'H2']
def __init__(self, instrument):
self.instrument = instrument
if not self.TIMEFRAMES:
raise ValueError('Please define TIMEFRAMES variable.')
def start(self):
"""Called on strategy start."""
raise NotImplementedError()
def new_bar(self, instrument, cur_index):
"""Called on every bar of every instrument that client is subscribed on."""
raise NotImplementedError()
def execute(self, engine, instruments, cur_index):
"""Called on after all indicators have been updated for this bar's index"""
raise NotImplementedError()
def end(self, engine):
"""Called on strategy stop."""
raise NotImplementedError()
|
Add callback to url_callbacks so url module doesn't query it
|
from willie import web
from willie import module
import time
import json
import re
regex = re.compile('(play.spotify.com\/track\/)([\w-]+)')
def setup(bot):
if not bot.memory.contains('url_callbacks'):
bot.memory['url_callbacks'] = tools.WillieMemory()
bot.memory['url_callbacks'][regex] = spotify
def shutdown(bot):
del bot.memory['url_callbacks'][regex]
@module.rule('.*(play.spotify.com\/track\/)([\w-]+).*')
def spotify(bot, trigger, found_match=None):
match = found_match or trigger
resp = web.get('https://api.spotify.com/v1/tracks/%s' % match.group(2))
result = json.loads(resp)
try:
artist = result['artists'][0]['name']
title = result['name']
album = result['album']['name']
duration = result['duration_ms']
duration_hms = time.strftime('%H:%M:%S', time.gmtime(duration / 1000))
bot.say('{0} - {1} [{2}] | {3}'.format(artist, title, album, duration_hms))
except KeyError:
bot.say('Track not found.')
|
from willie import web
from willie import module
import time
import json
import urllib
@module.rule('.*(play.spotify.com\/track\/)([\w-]+).*')
def spotify(bot, trigger, found_match=None):
match = found_match or trigger
resp = web.get('https://api.spotify.com/v1/tracks/%s' % match.group(2))
result = json.loads(resp)
try:
artist = result['artists'][0]['name']
title = result['name']
album = result['album']['name']
duration = result['duration_ms']
duration_hms = time.strftime('%H:%M:%S', time.gmtime(duration / 1000))
bot.say('{0} - {1} [{2}] | {3}'.format(artist, title, album, duration_hms))
except KeyError:
bot.say('Track not found.')
|
Make local site debug easier
|
<?php
require_once __DIR__ . '/vendor/autoload.php';
if (is_dir("/home/gettauru")) {
$level = \PWE\Core\PWELogger::WARNING;
$tempdir = "/home/gettauru/tmp";
$logfile = "/home/gettauru/logs/pwe.".date('Ym');
} else { // our real website settings
// local debugging settings
$level = \PWE\Core\PWELogger::DEBUG;
$tempdir = sys_get_temp_dir();
$logfile = "/tmp/taurus-pwe.log";
}
\PWE\Core\PWELogger::setStdErr($logfile);
\PWE\Core\PWELogger::setStdOut($logfile);
\PWE\Core\PWELogger::setLevel($level);
/** @var $PWECore PWE\Core\PWECore */
$PWECore->setRootDirectory(__DIR__);
$PWECore->setXMLDirectory($PWECore->getDataDirectory());
$PWECore->setTempDirectory($tempdir);
if (!is_dir("/home/gettauru")) {
$fname=$tempdir.'/taurus.xml';
if (!is_file($fname)) {
file_put_contents($fname, "<registry/>");
}
$PWECore->getModulesManager()->setRegistryFile($fname);
}
require_once __DIR__."/updates.php";
|
<?php
require_once __DIR__ . '/vendor/autoload.php';
if ($_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
// local debugging settings
$level = \PWE\Core\PWELogger::DEBUG;
$tempdir = sys_get_temp_dir();
$logfile = "/tmp/taurus-pwe.log";
} else { // our real website settings
$level = \PWE\Core\PWELogger::WARNING;
$tempdir = "/home/gettauru/tmp";
$logfile = "/home/gettauru/logs/pwe.".date('Ym');
}
\PWE\Core\PWELogger::setStdErr($logfile);
\PWE\Core\PWELogger::setStdOut($logfile);
\PWE\Core\PWELogger::setLevel($level);
/** @var $PWECore PWE\Core\PWECore */
$PWECore->setRootDirectory(__DIR__);
$PWECore->setXMLDirectory($PWECore->getDataDirectory());
$PWECore->setTempDirectory($tempdir);
if ($_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
$PWECore->getModulesManager()->setRegistryFile($tempdir.'/taurus.xml');
}
require_once __DIR__."/updates.php";
|
Update the resource controller instance. The class has changed.
Signed-off-by: Clement Escoffier <6397137e57d1f87002962a37058f2a1c76fca9db@gmail.com>
|
package site;
import org.apache.felix.ipojo.configuration.Configuration;
import org.apache.felix.ipojo.configuration.Instance;
/**
* Declares an instance of the asset controller to server $basedir/documentation.
* The goal is to have the external documentation (reference, mojo and javadoc) structured as follows:
* <p/>
* {@literal documentation/reference/0.4}
* {@literal documentation/reference/0.5-SNAPSHOT}
* {@literal documentation/wisdom-maven-plugin/0.4}
* {@literal documentation/wisdom-maven-plugin/0.5-SNAPSHOT}
* {@literal documentation/apidocs/0.4}
* {@literal documentation/apidocs/0.5-SNAPSHOT}
* ...
*/
@Configuration
public class DocConfiguration {
/**
* Declares the instance of resource controller serving resources from 'basedir/documentation'.
*/
public static Instance declareTheDocumentationController() {
return Instance.instance().of("org.wisdom.resources.AssetController")
.named("Documentation-Resources")
.with("path").setto("documentation");
}
}
|
package site;
import org.apache.felix.ipojo.configuration.Configuration;
import org.apache.felix.ipojo.configuration.Instance;
/**
* Declares an instance of the asset controller to server $basedir/documentation.
* The goal is to have the external documentation (reference, mojo and javadoc) structured as follows:
*
* {@literal documentation/reference/0.4}
* {@literal documentation/reference/0.5-SNAPSHOT}
* {@literal documentation/wisdom-maven-plugin/0.4}
* {@literal documentation/wisdom-maven-plugin/0.5-SNAPSHOT}
* {@literal documentation/apidocs/0.4}
* {@literal documentation/apidocs/0.5-SNAPSHOT}
* ...
*/
@Configuration
public class DocConfiguration {
/**
* Declares the instance of resource controller serving resources from 'basedir/documentation'.
*/
Instance instance = Instance.instance().of("org.wisdom.resources.ResourceController")
.named("Documentation-Resources")
.with("path").setto("documentation");
}
|
Add functionality in order to reload in-place
|
<?php
namespace atk4\ui;
/**
* This class generates action, that will be able to loop-back to the callback method.
*/
class jsReload implements jsExpressionable
{
public $view = null;
public $cb = null;
public function __construct($view)
{
$this->view = $view;
$this->cb = $this->view->add(new Callback('reload'));
$this->cb->set(function () {
echo $this->view->render();
$this->view->app->run_called = true; // prevent shutdown function from triggering.
exit;
});
}
public function jsRender()
{
$addSpinner = (new jQuery($this->view))->text('')->append("<div class='ui active loader inline'></div>");
$getRequest = (new jQuery())->get($this->cb->getURL(), '', new jsFunction(['data'], [
(new jQuery($this->view))->replaceWith(new jsExpression("data"))
]));
$final = new jsChain();
$final->_constructorArgs = [$addSpinner, $getRequest];
return $final->jsRender();
}
}
|
<?php
namespace atk4\ui;
/**
* This class generates action, that will be able to loop-back to the callback method.
*/
class jsReload implements jsExpressionable
{
public $view = null;
public $cb = null;
public function __construct($view)
{
$this->view = $view;
$this->cb = $this->view->add(new Callback('reload'));
$this->cb->set(function () {
echo $this->view->render();
$this->view->app->run_called = true; // prevent shutdown function from triggering.
exit;
});
}
public function jsRender()
{
// Temporarily here
//$r = new jsExpression('document.location=[]', [$this->cb->getURL()]);
// Works but not ideal! Proof of concept!
$r = (new jQuery($this->view))->load($this->cb->getURL());
return $r->jsRender();
}
}
|
Add Serializable interface for PrepareStatementParameterHeader.
|
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* 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.
* </p>
*/
package io.shardingsphere.proxy.transport.mysql.packet.command.statement.execute;
import io.shardingsphere.proxy.transport.mysql.constant.ColumnType;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.io.Serializable;
/**
* Prepared statement parameter header.
*
* @author zhangyonglun
*/
@AllArgsConstructor
@Getter
public class PreparedStatementParameterHeader implements Serializable {
private static final long serialVersionUID = -672589695838350689L;
private final ColumnType columnType;
private final int unsignedFlag;
}
|
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* 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.
* </p>
*/
package io.shardingsphere.proxy.transport.mysql.packet.command.statement.execute;
import io.shardingsphere.proxy.transport.mysql.constant.ColumnType;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Prepared statement parameter header.
*
* @author zhangyonglun
*/
@AllArgsConstructor
@Getter
public class PreparedStatementParameterHeader {
private final ColumnType columnType;
private final int unsignedFlag;
}
|
Fix Select2 width to 100%
|
import React from 'react';
import { FormGroup, ControlLabel, Col } from 'react-bootstrap';
import Select2 from 'react-select2-wrapper';
import { cloneObject } from '../../utils';
import 'react-select2-wrapper/css/select2.css';
class SelectGroup extends React.Component {
render() {
let selectProps = cloneObject(this.props);
delete selectProps.preComponent;
delete selectProps.label;
return (
<div>
{this.props.preComponent}
<FormGroup controlId={this.props.id}>
{this.props.label &&
<Col componentClass={ControlLabel} md={4}>{this.props.label}</Col>
}
<Col md={6}>
<Select2 {...selectProps} style={{ width: '100%' }} />
</Col>
</FormGroup>
</div>
);
}
}
export default SelectGroup;
|
import React from 'react';
import { FormGroup, ControlLabel, Col } from 'react-bootstrap';
import Select2 from 'react-select2-wrapper';
import { cloneObject } from '../../utils';
import 'react-select2-wrapper/css/select2.css';
class SelectGroup extends React.Component {
render() {
let selectProps = cloneObject(this.props);
delete selectProps.preComponent;
delete selectProps.label;
return (
<div>
{this.props.preComponent}
<FormGroup controlId={this.props.id}>
{this.props.label &&
<Col componentClass={ControlLabel} md={4}>{this.props.label}</Col>
}
<Col md={6}>
<Select2 {...selectProps} />
</Col>
</FormGroup>
</div>
);
}
}
export default SelectGroup;
|
Add input data to assignment's name.
|
<?php
require_once(__DIR__ . '/Assignment.class.php');
/**
* Grader for JFlap programs.
*
* @author Marco Aurélio Graciotto Silva
*/
class CmdlineInputOutputAssignment extends Assignment
{
private $input;
private $output;
public function setInput($input) {
$this->input = $input;
}
public function getInput() {
return $this->input;
}
public function setOutput($output) {
$this->output = $output;
}
public function getOutput() {
return $this->output;
}
public function loadData($data) {
$this->setInput($data['input']);
$this->setOutput($data['output']);
$this->setName($this->getName() . '- ' . $this->getInput());
}
public function getSupportedFeatures() {
$features = array();
$features[] = 'SoftwareTesting_Driver_CommandLineInputOutput';
return $features;
}
}
?>
|
<?php
require_once(__DIR__ . '/Assignment.class.php');
/**
* Grader for JFlap programs.
*
* @author Marco Aurélio Graciotto Silva
*/
class CmdlineInputOutputAssignment extends Assignment
{
private $input;
private $output;
public function setInput($input) {
$this->input = $input;
}
public function getInput() {
return $this->input;
}
public function setOutput($output) {
$this->output = $output;
}
public function getOutput() {
return $this->output;
}
public function loadData($data) {
$this->setInput($data['input']);
$this->setOutput($data['output']);
}
public function getSupportedFeatures() {
$features = array();
$features[] = 'SoftwareTesting_Driver_CommandLineInputOutput';
return $features;
}
}
?>
|
Remove invalid arg in influxdb test.
Copy paste bug from graphite. Namespace doesn't apply to InfuxDb.
|
'use strict';
const DataGenerator = require('../lib/plugins/influxdb/data-generator'),
expect = require('chai').expect;
describe('influxdb', function() {
describe('dataGenerator', function() {
it('should generate data for gpsi.pageSummary', function() {
const message = {
"type": "gpsi.pageSummary",
"timestamp": "2016-01-08T12:59:06+01:00",
"source": "gpsi",
"data": {
"median": "13",
"mean": "14.42",
"min": "13",
"p10": "13",
"p70": "16",
"p80": "16",
"p90": "16",
"p99": "16",
"max": "16"
},
'url': 'http://sub.domain.com/foo/bar'
};
let generator = new DataGenerator();
var data = generator.dataFromMessage(message);
expect(data).to.not.be.empty;
const firstName = data[0].seriesName;
expect(firstName).to.match(/pageSummary.sub_domain_com/);
expect(firstName).to.match(/foo_bar.gpsi.median/);
});
});
});
|
'use strict';
const DataGenerator = require('../lib/plugins/influxdb/data-generator'),
expect = require('chai').expect;
describe('influxdb', function() {
describe('dataGenerator', function() {
it('should generate data for gpsi.pageSummary', function() {
const message = {
"type": "gpsi.pageSummary",
"timestamp": "2016-01-08T12:59:06+01:00",
"source": "gpsi",
"data": {
"median": "13",
"mean": "14.42",
"min": "13",
"p10": "13",
"p70": "16",
"p80": "16",
"p90": "16",
"p99": "16",
"max": "16"
},
'url': 'http://sub.domain.com/foo/bar'
};
let generator = new DataGenerator('ns');
var data = generator.dataFromMessage(message);
expect(data).to.not.be.empty;
const firstName = data[0].seriesName;
expect(firstName).to.match(/pageSummary.sub_domain_com/);
expect(firstName).to.match(/foo_bar.gpsi.median/);
});
});
});
|
Send XpayMessageEntity to process() method
|
<?php
namespace Hicoria\Xpay;
use Nette\Object;
class XpaySmsDispatcher extends Object {
/**
* @var IMessageProcessor[]
*/
private $processors;
public function register($regex, IMessageProcessor $processor) {
$this->processors[$regex] = $processor;
}
public function process(XpayMessageEntity $paymentEntity) {
foreach($this->getProcessors() as $regexp => $processor) {
$success = preg_match_all("~" . preg_replace("/~/", "\\~", $regexp) . "~", $paymentEntity->getModified(), $matches);
// drop first element - we want matches in parentheses
array_shift($matches);
// continue for both, error and no match
if(!$success)
return $success;
$processor->process($paymentEntity, $matches);
break;
}
return true;
}
/**
* @return \Hicoria\Xpay\IMessageProcessor[]
*/
public function getProcessors()
{
return $this->processors;
}
}
|
<?php
namespace Hicoria\Xpay;
use Nette\Object;
class XpaySmsDispatcher extends Object {
/**
* @var IMessageProcessor[]
*/
private $processors;
public function register($regex, IMessageProcessor $processor) {
$this->processors[$regex] = $processor;
}
public function process(XpayMessageEntity $paymentEntity) {
foreach($this->getProcessors() as $regexp => $processor) {
$success = preg_match_all("~" . preg_replace("/~/", "\\~", $regexp) . "~", $paymentEntity->getModified(), $matches);
// drop first element - we want matches in parentheses
array_shift($matches);
// continue for both, error and no match
if(!$success)
return $success;
$processor->process($matches);
break;
}
return true;
}
/**
* @return \Hicoria\Xpay\IMessageProcessor[]
*/
public function getProcessors()
{
return $this->processors;
}
}
|
Increase limit for display of affiliations.
|
/* eslint-disable prefer-arrow-callback */
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { Affiliations } from '../affiliations.js';
Meteor.publish('affiliations.byParent', function affiliationsbyEvent(id) {
check(id, String);
return Affiliations.find({ parentId: id }, {
fields: Affiliations.publicFields,
limit: 100,
});
});
Meteor.publish('affiliations.byProfile', function affiliationsbyProfile(id) {
check(id, String);
return Affiliations.find({ 'profile._id': id }, {
fields: Affiliations.publicFields,
limit: 100,
});
});
Meteor.publish('affiliations.anyById', function affiliationsbyProfile(id) {
check(id, String);
return Affiliations.find(
{
$or: [
{ 'profile._id': id },
{ parentId: id },
],
}, {
fields: Affiliations.publicFields,
limit: 100,
}
);
});
|
/* eslint-disable prefer-arrow-callback */
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { Affiliations } from '../affiliations.js';
Meteor.publish('affiliations.byParent', function affiliationsbyEvent(id) {
check(id, String);
return Affiliations.find({ parentId: id }, {
fields: Affiliations.publicFields,
limit: 25,
});
});
Meteor.publish('affiliations.byProfile', function affiliationsbyProfile(id) {
check(id, String);
return Affiliations.find({ 'profile._id': id }, {
fields: Affiliations.publicFields,
limit: 25,
});
});
Meteor.publish('affiliations.anyById', function affiliationsbyProfile(id) {
check(id, String);
return Affiliations.find(
{
$or: [
{ 'profile._id': id },
{ parentId: id },
],
}, {
fields: Affiliations.publicFields,
limit: 25,
}
);
});
|
Update for plug-in : GitHub
|
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'GitHub',
version:'0.3',
prepareImgLinks:function (callback) {
var res = [];
$('a > img[data-canonical-src]').each(function () {
var img = $(this);
img.data('hoverZoomSrc', [img.attr('data-canonical-src')]);
img.data('hoverZoomCaption', [img.attr('alt')]);
res.push(img);
});
hoverZoom.urlReplace(res,
'a[href*="/blob/"]',
/\/github.com\/(.*)\/blob\/(.*\.(jpg|png|gif))/,
'/raw.githubusercontent.com/$1/$2'
);
hoverZoom.urlReplace(res,
'img[src]',
/(.*)\?(.*)/,
'$1'
);
callback($(res), this.name);
}
});
|
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'GitHub',
prepareImgLinks:function (callback) {
var res = [];
$('a > img[data-canonical-src]').each(function () {
var img = $(this);
img.data('hoverZoomSrc', [img.attr('data-canonical-src')]);
img.data('hoverZoomCaption', [img.attr('alt')]);
res.push(img);
});
hoverZoom.urlReplace(res,
'a[href*="/blob/"]',
/\/github.com\/(.*)\/blob\/(.*\.(jpg|png|gif))/,
'/raw.githubusercontent.com/$1/$2'
);
callback($(res));
}
});
|
Make sender address name field optional
|
"""
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from typing import Optional
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: Optional[str]
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
return formataddr((self.name, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
|
"""
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: str
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
realname = self.name if self.name else False
return formataddr((realname, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
|
FIX forgot debug dump (!)
|
<?php
class Default_Model_MovieMapper extends Default_Model_AbstractMapper
{
public function find($id)
{
$result = $this->getDbTable()->find($id);
return $result->current();
}
public function fetchAll()
{
$resultSet = $this->getDbTable()->fetchAll();
return $resultSet;
}
public function getFilteredQuery($idUser, $status)
{
$select = $this->getDbTable()->select()
->from('movie')
->joinLeft('status', 'movie.id = status.idMovie' , array())
->where('status.idUser = ?', $idUser);
if ($status >= 0 && $status <= 5)
{
$select->where('status.rating = ?', $status);
}
else
{
$select->where('status.rating <> ?', 0);
}
if ($status == 0)
{
$select->orWhere('status.idUser IS NULL');
$select->orWhere('status.rating IS NULL');
}
return $select;
}
}
?>
|
<?php
class Default_Model_MovieMapper extends Default_Model_AbstractMapper
{
public function find($id)
{
$result = $this->getDbTable()->find($id);
return $result->current();
}
public function fetchAll()
{
$resultSet = $this->getDbTable()->fetchAll();
return $resultSet;
}
public function getFilteredQuery($idUser, $status)
{
$select = $this->getDbTable()->select()
->from('movie')
->joinLeft('status', 'movie.id = status.idMovie' , array())
->where('status.idUser = ?', $idUser);
if ($status >= 0 && $status <= 5)
{
$select->where('status.rating = ?', $status);
}
else
{
$select->where('status.rating <> ?', 0);
}
if ($status == 0)
{
$select->orWhere('status.idUser IS NULL');
$select->orWhere('status.rating IS NULL');
}
echo $select;
return $select;
}
}
?>
|
Comment so it can compile for testing
|
package info.u_team.u_team_test.data.provider;
import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;
public class TestItemModelsProvider extends CommonItemModelsProvider {
public TestItemModelsProvider(GenerationData data) {
super(data);
}
@Override
protected void registerModels() {
// Items
simpleGenerated(TestItems.BASIC.get());
simpleGenerated(TestItems.BASIC_FOOD.get());
simpleGenerated(TestItems.BETTER_ENDERPEARL.get());
// iterateItems(TestItems.BASIC_ARMOR, this::simpleGenerated); // TODO
// iterateItems(TestItems.BASIC_TOOL, this::simpleHandheld); // TODO
// Blocks
simpleBlock(TestBlocks.BASIC.get());
simpleBlock(TestBlocks.BASIC_TILEENTITY.get());
simpleBlock(TestBlocks.BASIC_ENERGY_CREATOR.get());
simpleBlock(TestBlocks.BASIC_FLUID_INVENTORY.get());
}
}
|
package info.u_team.u_team_test.data.provider;
import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;
public class TestItemModelsProvider extends CommonItemModelsProvider {
public TestItemModelsProvider(GenerationData data) {
super(data);
}
@Override
protected void registerModels() {
// Items
simpleGenerated(TestItems.BASIC.get());
simpleGenerated(TestItems.BASIC_FOOD.get());
simpleGenerated(TestItems.BETTER_ENDERPEARL.get());
iterateItems(TestItems.BASIC_ARMOR, this::simpleGenerated);
iterateItems(TestItems.BASIC_TOOL, this::simpleHandheld);
// Blocks
simpleBlock(TestBlocks.BASIC.get());
simpleBlock(TestBlocks.BASIC_TILEENTITY.get());
simpleBlock(TestBlocks.BASIC_ENERGY_CREATOR.get());
simpleBlock(TestBlocks.BASIC_FLUID_INVENTORY.get());
}
}
|
Add an option to enable/disable JSON parsing
|
import xhr from 'xhr'
function isString (obj) { return (typeof (obj) === 'string') }
function isSuccess (code) { return (code >= 200 && code <= 399) }
async function get (url, deserialize = true) {
return request(url, 'GET', deserialize)
}
async function post (url, payload) {
return request(url, 'POST', true, payload)
}
async function request (url, method, deserialize = true, payload = undefined) {
return new Promise(
function (resolve, reject) {
const headers = {}
if (payload) {
headers['Content-Type'] = 'application/json'
}
const options = {
body: isString(payload) ? payload : JSON.stringify(payload),
headers: headers,
uri: url,
method: method
}
const callback = function (err, resp, body) {
if (!err && isSuccess(resp.statusCode)) {
if (deserialize) {
resolve(JSON.parse(body))
} else {
resolve(body)
}
} else {
reject(resp.statusCode)
}
}
xhr(options, callback)
}
)
}
export { get, post }
|
import xhr from 'xhr'
function isString (obj) { return (typeof (obj) === 'string') }
function isSuccess (code) { return (code >= 200 && code <= 399) }
async function get (url) {
return request(url, 'GET')
}
async function post (url, payload) {
return request(url, 'POST', payload)
}
async function request (url, method, payload = undefined) {
return new Promise(
function (resolve, reject) {
const headers = {}
if (payload) {
headers['Content-Type'] = 'application/json'
}
const options = {
body: isString(payload) ? payload : JSON.stringify(payload),
headers: headers,
uri: url,
method: method
}
const callback = function (err, resp, body) {
if (!err && isSuccess(resp.statusCode)) {
resolve(JSON.parse(body))
} else {
reject(resp.statusCode)
}
}
xhr(options, callback)
}
)
}
export { get, post }
|
Use "Aptible Legacy Infrastructure" everywhere
|
import Ember from 'ember';
import ajax from 'diesel/utils/ajax';
import config from 'diesel/config/environment';
function errorToMessage(e) {
switch(e.status) {
case 0:
return "Metrics server is unavailable; please try again later";
case 400:
return "Metrics server declined to serve the request";
case 404:
return "No data available. If you just launched your containers, please try again later. Otherwise, please contact support (metrics are partially unavailable on Aptible legacy infrastructure)";
case 500:
return "Metrics server is unavailable; please try again later";
default:
return "An unknown error occured";
}
}
export default Ember.Service.extend({
session: Ember.inject.service(),
fetchMetrics(containers, horizon, metric) {
let accessToken = this.get("session.token.accessToken");
let containerIds = containers.map((container) => container.get("id"));
return ajax(`${config.metricsBaseUri}/proxy/${containerIds.join(":")}?horizon=${horizon}&metric=${metric}`, {
headers: {
"Authorization": `Bearer ${accessToken}`
}
})
.catch((e) => {
throw new Error(errorToMessage(e));
});
}
});
|
import Ember from 'ember';
import ajax from 'diesel/utils/ajax';
import config from 'diesel/config/environment';
function errorToMessage(e) {
switch(e.status) {
case 0:
return "Metrics server is unavailable; please try again later";
case 400:
return "Metrics server declined to serve the request";
case 404:
return "No data available. If you just launched your containers, please try again later. Otherwise, please contact support (metrics are not available on some Aptible legacy stacks)";
case 500:
return "Metrics server is unavailable; please try again later";
default:
return "An unknown error occured";
}
}
export default Ember.Service.extend({
session: Ember.inject.service(),
fetchMetrics(containers, horizon, metric) {
let accessToken = this.get("session.token.accessToken");
let containerIds = containers.map((container) => container.get("id"));
return ajax(`${config.metricsBaseUri}/proxy/${containerIds.join(":")}?horizon=${horizon}&metric=${metric}`, {
headers: {
"Authorization": `Bearer ${accessToken}`
}
})
.catch((e) => {
throw new Error(errorToMessage(e));
});
}
});
|
Update ioc storage path for the raw tiffs.
|
from ophyd.controls.area_detector import (AreaDetectorFileStoreHDF5,
AreaDetectorFileStoreTIFF,
AreaDetectorFileStoreTIFFSquashing)
# from shutter import sh1
shctl1 = EpicsSignal('XF:28IDC-ES:1{Det:PE1}cam1:ShutterMode', name='shctl1')
pe1 = AreaDetectorFileStoreTIFFSquashing(
'XF:28IDC-ES:1{Det:PE1}',
name='pe1',
stats=[],
ioc_file_path = 'H:/pe1_data',
file_path = '/home/xf28id1/pe1_data',
shutter=shctl1,
shutter_val=(1, 0)
)
# Dan and Sanjit commented this out in June.
#shctl2 = EpicsSignal('XF:28IDC-ES:1{Det:PE2}cam1:ShutterMode', name='shctl2')
#pe2 = AreaDetectorFileStoreTIFFSquashing(
# 'XF:28IDC-ES:1{Det:PE2}',
# name='pe2',
# stats=[],
# ioc_file_path = 'G:/pe2_data',
# file_path = '/home/xf28id1/pe2_data',
# shutter=shctl2,
# shutter_val=(1,0))
|
from ophyd.controls.area_detector import (AreaDetectorFileStoreHDF5,
AreaDetectorFileStoreTIFF,
AreaDetectorFileStoreTIFFSquashing)
# from shutter import sh1
shctl1 = EpicsSignal('XF:28IDC-ES:1{Det:PE1}cam1:ShutterMode', name='shctl1')
pe1 = AreaDetectorFileStoreTIFFSquashing(
'XF:28IDC-ES:1{Det:PE1}',
name='pe1',
stats=[],
ioc_file_path = 'G:/pe1_data',
file_path = '/home/xf28id1/pe1_data',
shutter=shctl1,
shutter_val=(1, 0)
)
# Dan and Sanjit commented this out in June.
#shctl2 = EpicsSignal('XF:28IDC-ES:1{Det:PE2}cam1:ShutterMode', name='shctl2')
#pe2 = AreaDetectorFileStoreTIFFSquashing(
# 'XF:28IDC-ES:1{Det:PE2}',
# name='pe2',
# stats=[],
# ioc_file_path = 'G:/pe2_data',
# file_path = '/home/xf28id1/pe2_data',
# shutter=shctl2,
# shutter_val=(1,0))
|
Convert url param values to unicode before encoding.
|
import hashlib
import hmac
import urllib, urllib2
API_OPERATING_STATUSES = (
(1, 'Normal'),
(2, 'Degraded Service'),
(3, 'Service Disruption'),
(4, 'Undergoing Maintenance')
)
API_STATUSES = (
(1, 'Active'),
(2, 'Deprecated'),
(3, 'Disabled')
)
KEY_STATUSES = (
('U', 'Unactivated'),
('A', 'Active'),
('S', 'Suspended')
)
UNPUBLISHED, PUBLISHED, NEEDS_UPDATE = range(3)
PUB_STATUSES = (
(UNPUBLISHED, 'Unpublished'),
(PUBLISHED, 'Published'),
(NEEDS_UPDATE, 'Needs Update'),
)
def get_signature(params, signkey):
# sorted k,v pairs of everything but signature
data = sorted([(k,unicode(v).encode('utf-8'))
for k,v in params.iteritems()
if k != 'signature'])
qs = urllib.urlencode(data)
return hmac.new(str(signkey), qs, hashlib.sha1).hexdigest()
def apicall(url, signkey, **params):
params['signature'] = get_signature(params, signkey)
data = sorted([(k,v) for k,v in params.iteritems()])
body = urllib.urlencode(data)
urllib2.urlopen(url, body)
|
import hashlib
import hmac
import urllib, urllib2
API_OPERATING_STATUSES = (
(1, 'Normal'),
(2, 'Degraded Service'),
(3, 'Service Disruption'),
(4, 'Undergoing Maintenance')
)
API_STATUSES = (
(1, 'Active'),
(2, 'Deprecated'),
(3, 'Disabled')
)
KEY_STATUSES = (
('U', 'Unactivated'),
('A', 'Active'),
('S', 'Suspended')
)
UNPUBLISHED, PUBLISHED, NEEDS_UPDATE = range(3)
PUB_STATUSES = (
(UNPUBLISHED, 'Unpublished'),
(PUBLISHED, 'Published'),
(NEEDS_UPDATE, 'Needs Update'),
)
def get_signature(params, signkey):
# sorted k,v pairs of everything but signature
data = sorted([(k,v.encode('utf-8')) for k,v in params.iteritems() if k != 'signature'])
qs = urllib.urlencode(data)
return hmac.new(str(signkey), qs, hashlib.sha1).hexdigest()
def apicall(url, signkey, **params):
params['signature'] = get_signature(params, signkey)
data = sorted([(k,v) for k,v in params.iteritems()])
body = urllib.urlencode(data)
urllib2.urlopen(url, body)
|
Fix NO TESTS FOUND IN TESTCASE error
Ref:
http://nickhayden.com/blog/laravel-5-no-tests-found-in-testcase-error/
|
<?php
abstract class TestCase extends Illuminate\Foundation\Testing\TestCase
{
protected $baseUrl = 'http://localhost:8000';
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
return $app;
}
public function prepareForTests()
{
// Mail::pretend(true);
}
public function setupDatabase()
{
// Artisan::call('migrate:reset');
// Artisan::call('db:seed', array('--class'=>'TestingDatabaseSeeder'));
}
public function setUp()
{
parent::setUp();
$this->prepareForTests();
}
public function tearDown()
{
parent::tearDown();
Mockery::close();
}
}
|
<?php
class TestCase extends Illuminate\Foundation\Testing\TestCase
{
protected $baseUrl = 'http://localhost:8000';
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
return $app;
}
public function prepareForTests()
{
// Mail::pretend(true);
}
public function setupDatabase()
{
// Artisan::call('migrate:reset');
// Artisan::call('db:seed', array('--class'=>'TestingDatabaseSeeder'));
}
public function setUp()
{
parent::setUp();
$this->prepareForTests();
}
public function tearDown()
{
parent::tearDown();
Mockery::close();
}
}
|
Add option to print debug statements at regular intervals
Useful to track the progress of the load. This was a change copied from the
production server.
|
import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representation of the timeline")
parser.add_argument("user_email",
help="specify the user email to load the data as")
parser.add_argument("-n", "--make_new", action="store_true",
help="specify whether the entries should overwrite existing ones (default) or create new ones")
parser.add_argument("-v", "--verbose",
help="after how many lines we should print a status message.")
args = parser.parse_args()
fn = args.timeline_filename
print fn
print "Loading file " + fn
tsdb = edb.get_timeseries_db()
user = ecwu.User.register(args.user_email)
override_uuid = user.uuid
print("After registration, %s -> %s" % (args.user_email, override_uuid))
entries = json.load(open(fn), object_hook = bju.object_hook)
for i, entry in enumerate(entries):
entry["user_id"] = override_uuid
if args.make_new:
del entry["_id"]
if args.verbose is not None and i % args.verbose == 0:
print "About to save %s" % entry
tsdb.save(entry)
|
import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representation of the timeline")
parser.add_argument("user_email",
help="specify the user email to load the data as")
parser.add_argument("-n", "--make_new", action="store_true",
help="specify whether the entries should overwrite existing ones (default) or create new ones")
args = parser.parse_args()
fn = args.timeline_filename
print fn
print "Loading file " + fn
tsdb = edb.get_timeseries_db()
user = ecwu.User.register(args.user_email)
override_uuid = user.uuid
print("After registration, %s -> %s" % (args.user_email, override_uuid))
entries = json.load(open(fn), object_hook = bju.object_hook)
for entry in entries:
entry["user_id"] = override_uuid
if args.make_new:
del entry["_id"]
tsdb.save(entry)
|
Fix NPE with nullable expressions in custom syntax
|
package com.btk5h.skriptmirror.skript.custom;
import org.bukkit.event.Event;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
public class CustomSyntaxExpression extends SimpleExpression<Object> {
private Expression<?> source;
private Event realEvent;
public CustomSyntaxExpression(Expression<?> source, Event realEvent) {
this.source = source;
this.realEvent = realEvent;
}
public static CustomSyntaxExpression wrap(Expression<?> source, Event realEvent) {
if (source instanceof CustomSyntaxExpression) {
return (CustomSyntaxExpression) source;
}
return new CustomSyntaxExpression(source, realEvent);
}
@Override
protected Object[] get(Event e) {
return source == null ? new Object[0] : source.getAll(realEvent);
}
@Override
public boolean isSingle() {
return source == null || source.isSingle();
}
@Override
public Class<?> getReturnType() {
return source == null ? Object.class : source.getReturnType();
}
@Override
public String toString(Event e, boolean debug) {
return source == null ? "" : source.toString(realEvent, debug);
}
@Override
public Expression<?> getSource() {
return source;
}
@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parseResult) {
throw new UnsupportedOperationException();
}
}
|
package com.btk5h.skriptmirror.skript.custom;
import org.bukkit.event.Event;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
public class CustomSyntaxExpression extends SimpleExpression<Object> {
private Expression<?> source;
private Event realEvent;
public CustomSyntaxExpression(Expression<?> source, Event realEvent) {
this.source = source;
this.realEvent = realEvent;
}
public static CustomSyntaxExpression wrap(Expression<?> source, Event realEvent) {
if (source instanceof CustomSyntaxExpression) {
return (CustomSyntaxExpression) source;
}
return new CustomSyntaxExpression(source, realEvent);
}
@Override
protected Object[] get(Event e) {
return source.getAll(realEvent);
}
@Override
public boolean isSingle() {
return source.isSingle();
}
@Override
public Class<?> getReturnType() {
return source.getReturnType();
}
@Override
public String toString(Event e, boolean debug) {
return source.toString(realEvent, debug);
}
@Override
public Expression<?> getSource() {
return source;
}
@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parseResult) {
throw new UnsupportedOperationException();
}
}
|
Set Sentry log level to warning
To prevent every damn thing from being logged...
|
#
# Centralized logging setup
#
import os
import logging
from .utils import getLogger
l = getLogger('backend')
logging.basicConfig(
level=logging.DEBUG,
format='[%(asctime)s][%(levelname)s] %(name)s '
'%(filename)s:%(funcName)s:%(lineno)d | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
sentry_dsn = os.environ.get('AT_SENTRY_DSN')
if sentry_dsn:
from raven import Client
from raven.handlers.logging import SentryHandler
from raven.conf import setup_logging
client = Client(sentry_dsn)
handler = SentryHandler(client, level='WARNING')
setup_logging(handler)
l.info("Set up Sentry client")
|
#
# Centralized logging setup
#
import os
import logging
from .utils import getLogger
l = getLogger('backend')
logging.basicConfig(
level=logging.DEBUG,
format='[%(asctime)s][%(levelname)s] %(name)s '
'%(filename)s:%(funcName)s:%(lineno)d | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
sentry_dsn = os.environ.get('AT_SENTRY_DSN')
if sentry_dsn:
from raven import Client
from raven.handlers.logging import SentryHandler
from raven.conf import setup_logging
client = Client(sentry_dsn)
handler = SentryHandler(client)
setup_logging(handler)
l.info("Set up Sentry client")
|
FIX augmentSQL func to be compatible with 3.2 method signature
|
<?php
class ForumSpamPostExtension extends DataExtension {
public function augmentSQL(SQLQuery &$query) {
if (Config::inst()->forClass('Post')->allow_reading_spam) return;
$member = Member::currentUser();
$forum = $this->owner->Forum();
// Do Status filtering
if($member && is_numeric($forum->ID) && $member->ID == $forum->Moderator()->ID) {
$filter = "\"Post\".\"Status\" IN ('Moderated', 'Awaiting')";
} else {
$filter = "\"Post\".\"Status\" = 'Moderated'";
}
$query->addWhere($filter);
// Filter out posts where the author is in some sort of banned / suspended status
$query->addInnerJoin("Member", "\"AuthorStatusCheck\".\"ID\" = \"Post\".\"AuthorID\"", "AuthorStatusCheck");
$authorStatusFilter = array(
array('"AuthorStatusCheck"."ForumStatus"' => 'Normal')
);
if ($member && $member->ForumStatus === 'Ghost') {
$authorStatusFilter[] = array('"Post"."AuthorID" = ?', $member->ID);
}
$query->addWhereAny($authorStatusFilter);
$query->setDistinct(false);
}
}
|
<?php
class ForumSpamPostExtension extends DataExtension {
public function augmentSQL(SQLSelect $query) {
if (Config::inst()->forClass('Post')->allow_reading_spam) return;
$member = Member::currentUser();
$forum = $this->owner->Forum();
// Do Status filtering
if($member && is_numeric($forum->ID) && $member->ID == $forum->Moderator()->ID) {
$filter = "\"Post\".\"Status\" IN ('Moderated', 'Awaiting')";
} else {
$filter = "\"Post\".\"Status\" = 'Moderated'";
}
$query->addWhere($filter);
// Filter out posts where the author is in some sort of banned / suspended status
$query->addInnerJoin("Member", "\"AuthorStatusCheck\".\"ID\" = \"Post\".\"AuthorID\"", "AuthorStatusCheck");
$authorStatusFilter = array(
array('"AuthorStatusCheck"."ForumStatus"' => 'Normal')
);
if ($member && $member->ForumStatus === 'Ghost') {
$authorStatusFilter[] = array('"Post"."AuthorID" = ?', $member->ID);
}
$query->addWhereAny($authorStatusFilter);
$query->setDistinct(false);
}
}
|
Move redirect setting to correct location.
|
<?php
/**
* Application Settings
* @author John Kloor <kloor@bgsu.edu>
* @copyright 2017 Bowling Green State University Libraries
* @license MIT
*/
use Symfony\Component\Yaml\Yaml;
// Setup the default settings for the application.
$settings = [
// Application settings.
'app' => [
// Whether to enable debug information.
'debug' => false,
// Path to log file, if any.
'log' => false,
// URI index requests are redirected to.
'redirect' => false
],
// Template settings.
'template' => [
// Path to search for templates before this package's templates.
'path' => false,
// Filename of template that defines a page. Default: page.html.twig
'page' => false
],
// SMTP settings.
'smtp' => [
// Server hostname.
'host' => false,
// Server port number. Default: 25
'port' => 25
],
// Actions handled by the application.
'actions' => []
];
// Check if a config.yaml file exists.
$file = dirname(__DIR__) . '/config.yaml';
if (file_exists($file)) {
// If so, load the settings from that file.
$settings = array_replace_recursive(
$settings,
Yaml::parse(file_get_contents($file))
);
}
// Return the complete settings array.
return $settings;
|
<?php
/**
* Application Settings
* @author John Kloor <kloor@bgsu.edu>
* @copyright 2017 Bowling Green State University Libraries
* @license MIT
*/
use Symfony\Component\Yaml\Yaml;
// Setup the default settings for the application.
$settings = [
// Application settings.
'app' => [
// Whether to enable debug information.
'debug' => false,
// Path to log file, if any.
'log' => false
],
// Template settings.
'template' => [
// Path to search for templates before this package's templates.
'path' => false,
// Filename of template that defines a page. Default: page.html.twig
'page' => false
],
// SMTP settings.
'smtp' => [
// Server hostname.
'host' => false,
// Server port number. Default: 25
'port' => 25
],
// URI index requests are redirected to.
'redirect' => false,
// Actions handled by the application.
'actions' => []
];
// Check if a config.yaml file exists.
$file = dirname(__DIR__) . '/config.yaml';
if (file_exists($file)) {
// If so, load the settings from that file.
$settings = array_replace_recursive(
$settings,
Yaml::parse(file_get_contents($file))
);
}
// Return the complete settings array.
return $settings;
|
Comment out tests that fail intentionally (for testing purposes).
|
package water.cookbook;
import org.junit.*;
import water.*;
import water.fvec.*;
import water.util.Log;
import water.util.RemoveAllKeysTask;
public class Cookbook extends TestUtil {
@Before
public void removeAllKeys() {
Log.info("Removing all keys...");
RemoveAllKeysTask collector = new RemoveAllKeysTask();
collector.invokeOnAllNodes();
Log.info("Removed all keys.");
}
// @Test
// public void testWillFail() {
// throw new RuntimeException("first test fails");
// }
// ---
// Test flow-coding a filter & group-by computing e.g. mean
@Test
public void testBasic() {
Key k = Key.make("cars.hex");
Frame fr = parseFrame(k, "smalldata/cars.csv");
//Frame fr = parseFrame(k, "../datasets/UCI/UCI-large/covtype/covtype.data");
// Call into another class so we do not need to weave anything in this class
// when run as a JUnit
Cookbook2.basicStatic(k, fr);
}
// @Test
// public void testWillFail2() {
// throw new RuntimeException("3 test fails");
// }
}
|
package water.cookbook;
import org.junit.*;
import water.*;
import water.fvec.*;
import water.util.Log;
import water.util.RemoveAllKeysTask;
public class Cookbook extends TestUtil {
@Before
public void removeAllKeys() {
Log.info("Removing all keys...");
RemoveAllKeysTask collector = new RemoveAllKeysTask();
collector.invokeOnAllNodes();
Log.info("Removed all keys.");
}
@Test
public void testWillFail() {
throw new RuntimeException("first test fails");
}
// ---
// Test flow-coding a filter & group-by computing e.g. mean
@Test
public void testBasic() {
Key k = Key.make("cars.hex");
Frame fr = parseFrame(k, "smalldata/cars.csv");
//Frame fr = parseFrame(k, "../datasets/UCI/UCI-large/covtype/covtype.data");
// Call into another class so we do not need to weave anything in this class
// when run as a JUnit
Cookbook2.basicStatic(k, fr);
}
@Test
public void testWillFail2() {
throw new RuntimeException("3 test fails");
}
}
|
Fix for PHP 7 exceptions (throwables)
|
<?php namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends \Neonbug\Common\Exceptions\Handler {
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Throwable $e
* @return void
*/
public function report($e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $e
* @return \Illuminate\Http\Response
*/
public function render($request, $e)
{
return parent::render($request, $e);
}
}
|
<?php namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler {
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
}
|
db: Use stdout and stderr, not console
|
#!/usr/bin/env node
var Neo4j = require("node-neo4j");
var utils = require("./utils");
var stdin = process.openStdin();
var stdout = process.stdout;
var stderr = process.stderr;
utils.validateEnvironment("node db-admin.js");
stderr.write("=> Connecting to " + process.env.DATABASE_URL + "\n");
(function runAdminInterface() {
var connectionString = utils.createConnectionString();
var db = new Neo4j(connectionString);
stdin.addListener("data", function handleStdinData(d) {
stderr.write("=> Running: " + d.toString().trim() + "\n");
db.cypherQuery(d.toString().trim(), function handleQueryRes(err, result) {
if (err) {
stderr.write(String(err) + "\n");
return;
}
stdout.write(JSON.stringify(result.data, null, 2) + "\n");
stdout.write(JSON.stringify(result.columns, null, 2) + "\n");
});
});
}());
|
#!/usr/bin/env node
var Neo4j = require("node-neo4j");
var utils = require("./utils");
var stdin = process.openStdin();
utils.validateEnvironment("node db-admin.js");
console.log("=> Connecting to " + process.env.DATABASE_URL);
(function runAdminInterface() {
var connectionString = utils.createConnectionString();
var db = new Neo4j(connectionString);
stdin.addListener("data", function (d) {
console.log("=> Running: " + d.toString().trim());
db.cypherQuery(d.toString().trim(), function (err, result) {
if (err) {
console.log(err);
return;
}
console.log(result.data);
console.log(result.columns);
});
});
}());
|
Set download_url to pypi directory.
git-svn-id: c8188841f5432f3fe42d04dee4f87e556eb5cf84@23 99efc558-b41a-11dd-8714-116ca565c52f
|
#!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
import os
from setuptools import setup, find_packages
here = os.path.dirname(__file__)
version_file = os.path.join(here, 'src/iptools/__init__.py')
d = {}
execfile(version_file, d)
version = d['__version__']
setup(
name = 'iptools',
version = version,
description = 'Python utilites for manipulating IP addresses',
long_description = "Utilities for manipulating IP addresses including a class that can be used to include CIDR network blocks in Django's INTERNAL_IPS setting.",
url = 'http://python-iptools.googlecode.com',
download_url = 'http://pypi.python.org/packages/source/i/iptools/',
author = 'Bryan Davis',
author_email = 'casadebender+iptools@gmail.com',
license = 'BSD',
platforms = ['any',],
package_dir = {'': 'src'},
packages = find_packages('src'),
include_package_data = True,
test_suite='iptools.test_iptools',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Utilities',
'Topic :: Internet',
],
zip_safe=False,
)
|
#!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
import os
from setuptools import setup, find_packages
here = os.path.dirname(__file__)
version_file = os.path.join(here, 'src/iptools/__init__.py')
d = {}
execfile(version_file, d)
version = d['__version__']
setup(
name = 'iptools',
version = version,
description = 'Python utilites for manipulating IP addresses',
long_description = "Utilities for manipulating IP addresses including a class that can be used to include CIDR network blocks in Django's INTERNAL_IPS setting.",
url = 'http://python-iptools.googlecode.com',
author = 'Bryan Davis',
author_email = 'casadebender+iptools@gmail.com',
license = 'BSD',
platforms = ['any',],
package_dir = {'': 'src'},
packages = find_packages('src'),
include_package_data = True,
test_suite='iptools.test_iptools',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Utilities',
'Topic :: Internet',
],
zip_safe=False,
)
|
Update to comply with last release of jsgraph
|
'use strict';
var wavelengthToColor = require('./wavelengthToColor');
function getAnnotation(pixel, color, height) {
return {
"fillColor": color,
"type": "rect",
"position": [{
"y": "0px",
"x": pixel+2
},{
"y": height+"px",
"x": pixel-1
}]
};
}
module.exports=function(spectrum) {
if (! spectrum) return;
var annotations=[];
annotations.push(getAnnotation(spectrum.nMRed,"red",15));
annotations.push(getAnnotation(spectrum.nMBlue,"blue",15));
annotations.push(getAnnotation(spectrum.nMGreen,"green",15));
var x=spectrum.x;
for (var i=0; i<x.length; i++) {
var color=wavelengthToColor(x[i]).color;
annotations.push(getAnnotation(x[i],color,10));
}
return annotations;
}
|
'use strict';
var wavelengthToColor = require('./wavelengthToColor');
function getAnnotation(pixel, color, height) {
return {
"pos2": {
"y": height+"px",
"x": pixel-1
},
"fillColor": color,
"type": "rect",
"pos": {
"y": "0px",
"x": pixel+2
}
};
}
module.exports=function(spectrum) {
if (! spectrum) return;
var annotations=[];
annotations.push(getAnnotation(spectrum.nMRed,"red",15));
annotations.push(getAnnotation(spectrum.nMBlue,"blue",15));
annotations.push(getAnnotation(spectrum.nMGreen,"green",15));
var x=spectrum.x;
for (var i=0; i<x.length; i++) {
var color=wavelengthToColor(x[i]).color;
annotations.push(getAnnotation(x[i],color,10));
}
return annotations;
}
|
Fix adding pattern to actually use the pattern text.
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addPattern } from '../actions'
import TextField from 'material-ui/TextField'
import RaisedButton from 'material-ui/RaisedButton'
import Subheader from 'material-ui/Subheader'
import Paper from 'material-ui/Paper'
import * as styles from './styles'
const mapStateToProps = function(state) {
return {
patternList: state.patternList
}
}
class AddPattern extends Component {
render() {
return (
<div>
<Subheader style={styles.headingStyle}>Add Pattern</Subheader>
<Paper style={styles.paperStyle} zDepth={2} rounded={true}>
<TextField ref="name" style={styles.inputStyle} hintText="Name" />
<TextField ref="pattern" style={styles.inputStyle} hintText="Pattern" fullWidth={true} />
<RaisedButton label="Add Pattern" primary={true} style={styles.buttonStyle} onClick={ () => this.props.addPattern(this.refs.name.input.value, this.refs.pattern.input.value) } />
</Paper>
</div>
)
}
}
export default connect(mapStateToProps,
(dispatch) => {
return {
addPattern: (name, pattern) => {
dispatch(addPattern(name, pattern))
}
}
})(AddPattern)
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addPattern } from '../actions'
import TextField from 'material-ui/TextField'
import RaisedButton from 'material-ui/RaisedButton'
import Subheader from 'material-ui/Subheader'
import Paper from 'material-ui/Paper'
import * as styles from './styles'
const mapStateToProps = function(state) {
return {
patternList: state.patternList
}
}
class AddPattern extends Component {
render() {
return (
<div>
<Subheader style={styles.headingStyle}>Add Pattern</Subheader>
<Paper style={styles.paperStyle} zDepth={2} rounded={true}>
<TextField ref="name" style={styles.inputStyle} hintText="Name" />
<TextField ref="pattern" style={styles.inputStyle} hintText="Pattern" fullWidth={true} />
<RaisedButton label="Add Pattern" primary={true} style={styles.buttonStyle} onClick={ () => this.props.addPattern(this.refs.name.input.value, this.refs.pattern.state.searchText) } />
</Paper>
</div>
)
}
}
export default connect(mapStateToProps,
(dispatch) => {
return {
addPattern: (name, pattern) => {
dispatch(addPattern(name, pattern))
}
}
})(AddPattern)
|
Fix table name error in sale_stock column renames
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, a suite of business apps
# This module Copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.openupgrade import openupgrade
column_renames = {
'sale_order_line': [('procurement_id', None)]}
@openupgrade.migrate()
def migrate(cr, version):
openupgrade.rename_columns(cr, column_renames)
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, a suite of business apps
# This module Copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.openupgrade import openupgrade
column_renames = {
'sale.order.line': [('procurement_id', None)]}
@openupgrade.migrate()
def migrate(cr, version):
openupgrade.rename_columns(cr, column_renames)
|
Add redirectTo - user -> user/profile
|
<?php
use Rudolf\Component\Routing\Route;
$collection->add('user/login', new Route(
'user/login(/redirect-to/<page>)?',
'Rudolf\Modules\Users\Login\Controller::login',
['page' => '.*$'],
['page' => 'dashboard']
));
$collection->add('user', new Route(
'user([\/])?',
'Rudolf\Modules\Users\Profile\Controller::redirectTo',
[],
['target' => DIR.'/user/profile']
));
$collection->add('user/logout', new Route(
'user/logout',
'Rudolf\Modules\Users\Login\Controller::logout'
));
$collection->add('user/profile', new Route(
'user/profile',
'Rudolf\Modules\Users\Profile\Controller::profile'
));
|
<?php
use Rudolf\Component\Routing;
use Rudolf\Component\Modules;
$module = new Modules\Module('dashboard');
$config = $module->getConfig();
$collection->add('user/login', new Routing\Route(
'user/login(/redirect-to/<page>)?',
'Rudolf\Modules\Users\Login\Controller::login',
array( // wyrazenia regularne dla parametrow
'page' => '.*$',
),
array( // wartosci domyslne
'page' => 'dashboard',
)
));
$collection->add('user/logout', new Routing\Route(
'user/logout',
'Rudolf\Modules\Users\Login\Controller::logout'
));
$collection->add('user/profile', new Routing\Route(
'user/profile',
'Rudolf\Modules\Users\Profile\Controller::profile'
));
|
[LIB-387] Change param name in APNS device model
|
import stampit from 'stampit';
import {Meta, Model} from './base';
const APNSDeviceMeta = Meta({
name: 'apnsdevice',
pluralName: 'apnsdevices',
endpoints: {
'detail': {
'methods': ['delete', 'patch', 'put', 'get'],
'path': '/v1/instances/{instanceName}/push_notifications/apns/devices/{registration_id}/'
},
'list': {
'methods': ['post', 'get'],
'path': '/v1/instances/{instanceName}/push_notifications/apns/devices/'
}
}
});
const APNSDeviceConstraints = {
instanceName: {
presence: true,
length: {
minimum: 5
}
},
user_id: {
presence: true
},
registration_id: {
presence: true
},
device_id: {
presence: true
}
};
const APNSDevice = stampit()
.compose(Model)
.setMeta(APNSDeviceMeta)
.setConstraints(APNSDeviceConstraints);
export default APNSDevice;
|
import stampit from 'stampit';
import {Meta, Model} from './base';
const APNSDeviceMeta = Meta({
name: 'apnsdevice',
pluralName: 'apnsdevices',
endpoints: {
'detail': {
'methods': ['delete', 'patch', 'put', 'get'],
'path': '/v1/instances/{instanceName}/push_notifications/apns/devices/{id}'
},
'list': {
'methods': ['post', 'get'],
'path': '/v1/instances/{instanceName}/push_notifications/apns/devices/'
}
}
});
const APNSDeviceConstraints = {
instanceName: {
presence: true,
length: {
minimum: 5
}
},
user_id: {
presence: true
},
registration_id: {
presence: true
},
device_id: {
presence: true
}
};
const APNSDevice = stampit()
.compose(Model)
.setMeta(APNSDeviceMeta)
.setConstraints(APNSDeviceConstraints);
export default APNSDevice;
|
Add serializer for png assets
|
import jpegThumbnail from './jpeg-thumbnail';
import storage from '../storage';
const costumePayload = costume => {
// TODO is it ok to base64 encode SVGs? What about unicode text inside them?
const assetDataUrl = storage.get(costume.assetId).encodeDataURI();
const assetDataFormat = costume.dataFormat;
const payload = {
type: 'costume',
name: costume.name,
// Params to be filled in below
mime: '',
body: '',
thumbnail: ''
};
switch (assetDataFormat) {
case 'svg':
payload.mime = 'image/svg+xml';
payload.body = assetDataUrl.replace('data:image/svg+xml;base64,', '');
break;
case 'png':
payload.mime = 'image/png';
payload.body = assetDataUrl.replace('data:image/png;base64,', '');
break;
default:
alert(`Cannot serialize for format: ${assetDataFormat}`); // eslint-disable-line
}
// TODO we may be able to optimize by not actually generating thumbnails...
return jpegThumbnail(assetDataUrl).then(thumbnail => {
payload.thumbnail = thumbnail.replace('data:image/jpeg;base64,', '');
return payload;
});
};
export default costumePayload;
|
import jpegThumbnail from './jpeg-thumbnail';
import storage from '../storage';
const costumePayload = costume => {
// TODO is it ok to base64 encode SVGs? What about unicode text inside them?
const assetDataUrl = storage.get(costume.assetId).encodeDataURI();
const assetDataFormat = costume.dataFormat;
const payload = {
type: 'costume',
name: costume.name,
// Params to be filled in below
mime: '',
body: '',
thumbnail: ''
};
switch (assetDataFormat) {
case 'svg':
payload.mime = 'image/svg+xml';
payload.body = assetDataUrl.replace('data:image/svg+xml;base64,', '');
break;
default:
alert(`Cannot serialize for format: ${assetDataFormat}`); // eslint-disable-line
}
// TODO we may be able to optimize by not actually generating thumbnails...
return jpegThumbnail(assetDataUrl).then(thumbnail => {
payload.thumbnail = thumbnail.replace('data:image/jpeg;base64,', '');
return payload;
});
};
export default costumePayload;
|
Update with reference to global nav partial
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-borders/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-borders/tachyons-borders.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_borders.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/borders/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/themes/borders/index.html', html)
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-borders/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-borders/tachyons-borders.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_borders.css', 'utf8')
var template = fs.readFileSync('./templates/docs/borders/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS
})
fs.writeFileSync('./docs/themes/borders/index.html', html)
|
Fix GNOME keymap missing shortcuts.
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.
*/
/*
* @author max
*/
package com.intellij.openapi.keymap.impl;
import java.util.Arrays;
import java.util.List;
public class DefaultBundledKeymaps implements BundledKeymapProvider {
public List<String> getKeymapFileNames() {
return Arrays.asList(
"Keymap_Default.xml",
"Keymap_Mac.xml",
"Keymap_MacClassic.xml",
"Keymap_Emacs.xml",
"Keymap_VisualStudio.xml",
"Keymap_XWin.xml",
"Keymap_GNOME.xml",
"Keymap_KDE.xml",
"Keymap_Eclipse.xml",
"Keymap_Netbeans.xml"
);
}
}
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.
*/
/*
* @author max
*/
package com.intellij.openapi.keymap.impl;
import java.util.Arrays;
import java.util.List;
public class DefaultBundledKeymaps implements BundledKeymapProvider {
public List<String> getKeymapFileNames() {
return Arrays.asList(
"Keymap_Default.xml",
"Keymap_Mac.xml",
"Keymap_MacClassic.xml",
"Keymap_Emacs.xml",
"Keymap_VisualStudio.xml",
"Keymap_GNOME.xml",
"Keymap_XWin.xml",
"Keymap_KDE.xml",
"Keymap_Eclipse.xml",
"Keymap_Netbeans.xml"
);
}
}
|
Drop max-concurrency for update in refresh pipeline (invalid arg)
|
from setuptools import find_packages, setup
setup(
name="redshift-etl",
version="0.27.1",
author="Harry's Data Engineering and Contributors",
description="ETL code to ferry data from PostgreSQL databases (or S3 files) to Redshift cluster",
license="MIT",
keywords="redshift postgresql etl extract transform load",
url="https://github.com/harrystech/harrys-redshift-etl",
package_dir={"": "python"},
packages=find_packages("python"),
package_data={
"etl": [
"assets/*",
"config/*"
]
},
scripts=[
"python/scripts/submit_arthur.sh",
"python/scripts/re_run_partial_pipeline.py"
],
entry_points={
"console_scripts": [
# NB The script must end in ".py" so that spark submit accepts it as a Python script.
"arthur.py = etl.commands:run_arg_as_command",
"run_tests.py = etl.selftest:run_tests"
]
}
)
|
from setuptools import find_packages, setup
setup(
name="redshift-etl",
version="0.27.0",
author="Harry's Data Engineering and Contributors",
description="ETL code to ferry data from PostgreSQL databases (or S3 files) to Redshift cluster",
license="MIT",
keywords="redshift postgresql etl extract transform load",
url="https://github.com/harrystech/harrys-redshift-etl",
package_dir={"": "python"},
packages=find_packages("python"),
package_data={
"etl": [
"assets/*",
"config/*"
]
},
scripts=[
"python/scripts/submit_arthur.sh",
"python/scripts/re_run_partial_pipeline.py"
],
entry_points={
"console_scripts": [
# NB The script must end in ".py" so that spark submit accepts it as a Python script.
"arthur.py = etl.commands:run_arg_as_command",
"run_tests.py = etl.selftest:run_tests"
]
}
)
|
Disable nsinit tests in travis.
Signed-off-by: Eric Myhre <2346ad27d7568ba9896f1b7da6b5991251debdf2@exultant.us>
|
package nsinit
import (
"os"
"testing"
. "github.com/smartystreets/goconvey/convey"
"polydawn.net/repeatr/executor/tests"
"polydawn.net/repeatr/testutil"
)
func Test(t *testing.T) {
Convey("Spec Compliance: nsinit Executor", t,
testutil.Requires(
testutil.RequiresRoot,
testutil.RequiresNamespaces,
testutil.WithTmpdir(func() {
execEng := &Executor{}
execEng.Configure("nsinit_workspace")
So(os.Mkdir(execEng.workspacePath, 0755), ShouldBeNil)
//tests.CheckBasicExecution(execEng) // correct error reporting sections fail spec compliance
tests.CheckFilesystemContainment(execEng)
//tests.CheckPwdBehavior(execEng) // correct error reporting sections fail spec compliance
tests.CheckEnvBehavior(execEng)
}),
),
)
}
|
package nsinit
import (
"os"
"testing"
. "github.com/smartystreets/goconvey/convey"
"polydawn.net/repeatr/executor/tests"
"polydawn.net/repeatr/testutil"
)
func Test(t *testing.T) {
Convey("Spec Compliance: nsinit Executor", t,
testutil.Requires(
testutil.RequiresRoot,
testutil.WithTmpdir(func() {
execEng := &Executor{}
execEng.Configure("nsinit_workspace")
So(os.Mkdir(execEng.workspacePath, 0755), ShouldBeNil)
//tests.CheckBasicExecution(execEng) // correct error reporting sections fail spec compliance
tests.CheckFilesystemContainment(execEng)
//tests.CheckPwdBehavior(execEng) // correct error reporting sections fail spec compliance
tests.CheckEnvBehavior(execEng)
}),
),
)
}
|
Fix a bug in bug reporting when not joined to a game.
|
<?
$steps = $_REQUEST['steps'];
$subject = $_REQUEST['subject'];
$error_msg = $_REQUEST['error_msg'];
$description = $_REQUEST['description'];
$new_sub = '[Bug] '.$subject;
$message = 'Login: '.$account->login.EOL.EOL.'-----------'.EOL.EOL.
'Account ID: '.$account->account_id.EOL.EOL.'-----------'.EOL.EOL.
'Description: '.$description.EOL.EOL.'-----------'.EOL.EOL.
'Steps to repeat: '.$steps.EOL.EOL.'-----------'.EOL.EOL.
'Error Message: '.$error_msg;
//mail('bugs@smrealms.de',
// $new_sub,
// $message,
// 'From: '.$account->email);
if(is_object($player))
$player->sendMessageToBox(BOX_BUGS_REPORTED, nl2br($message));
else
$account->sendMessageToBox(BOX_BUGS_REPORTED, nl2br($message));
$container = array();
$container['url'] = 'skeleton.php';
if (SmrSession::$game_id > 0) {
if ($player->isLandedOnPlanet())
$container['body'] = 'planet_main.php';
else
$container['body'] = 'current_sector.php';
} else
$container['body'] = 'game_play.php';
forward($container);
?>
|
<?
$steps = $_REQUEST['steps'];
$subject = $_REQUEST['subject'];
$error_msg = $_REQUEST['error_msg'];
$description = $_REQUEST['description'];
$new_sub = '[Bug] '.$subject;
$message = 'Login: '.$account->login.EOL.EOL.'-----------'.EOL.EOL.
'Account ID: '.$account->account_id.EOL.EOL.'-----------'.EOL.EOL.
'Description: '.$description.EOL.EOL.'-----------'.EOL.EOL.
'Steps to repeat: '.$steps.EOL.EOL.'-----------'.EOL.EOL.
'Error Message: '.$error_msg;
//mail('bugs@smrealms.de',
// $new_sub,
// $message,
// 'From: '.$account->email);
$player->sendMessageToBox(BOX_BUGS_REPORTED, nl2br($message));
$container = array();
$container['url'] = 'skeleton.php';
if (SmrSession::$game_id > 0) {
if ($player->isLandedOnPlanet())
$container['body'] = 'planet_main.php';
else
$container['body'] = 'current_sector.php';
} else
$container['body'] = 'game_play.php';
forward($container);
?>
|
Add breadcrumb components to entry script
|
export { Badge, BadgeColors } from './components/badge';
export { Button, Link, ButtonSizes, ButtonColors } from './components/button';
export { ButtonGroup, ButtonGroupSizes, ButtonGroupColors } from './components/button-group';
export { Breadcrumbs, BreadcrumbItem } from './components/breadcrumbs';
export { Callout, CalloutColors, CalloutSizes } from './components/callout';
export { CloseButton } from './components/close-button';
export { FlexVideo } from './components/flex-video';
export { Row, Column } from './components/grid';
export { Icon } from './components/icon';
export { Label, LabelColors } from './components/label';
export { Menu, MenuItem, MenuText, MenuAlignments } from './components/menu';
export { Pagination, PaginationItem, PaginationPrevious, PaginationNext, PaginationEllipsis } from './components/pagination';
export { Progress, ProgressMeter, ProgressMeterWithText, ProgressMeterText, NativeProgress } from './components/progress-bar';
export { ResponsiveNavigation, TitleBar, MenuIcon, TitleBarTitle } from './components/responsive';
export { Switch, SwitchInput, SwitchPaddle, SwitchActive, SwitchInactive, SwitchTypes, SwitchSizes } from './components/switch';
export { TopBar, TopBarTitle, TopBarLeft, TopBarRight } from './components/top-bar';
|
export { Badge, BadgeColors } from './components/badge';
export { Button, Link, ButtonSizes, ButtonColors } from './components/button';
export { ButtonGroup, ButtonGroupSizes, ButtonGroupColors } from './components/button-group';
export { Callout, CalloutColors, CalloutSizes } from './components/callout';
export { CloseButton } from './components/close-button';
export { FlexVideo } from './components/flex-video';
export { Row, Column } from './components/grid';
export { Icon } from './components/icon';
export { Label, LabelColors } from './components/label';
export { Menu, MenuItem, MenuText, MenuAlignments } from './components/menu';
export { Pagination, PaginationItem, PaginationPrevious, PaginationNext, PaginationEllipsis } from './components/pagination';
export { Progress, ProgressMeter, ProgressMeterWithText, ProgressMeterText, NativeProgress } from './components/progress-bar';
export { ResponsiveNavigation, TitleBar, MenuIcon, TitleBarTitle } from './components/responsive';
export { Switch, SwitchInput, SwitchPaddle, SwitchActive, SwitchInactive, SwitchTypes, SwitchSizes } from './components/switch';
export { TopBar, TopBarTitle, TopBarLeft, TopBarRight } from './components/top-bar';
|
Update to handle modal window submits.
|
/* ajax_windows.js. Support for modal popup windows in Umlaut items. */
jQuery(document).ready(function($) {
var populate_modal = function(data, textStatus, jqXHR) {
data = $(data);
var heading = data.find("h1, h2, h3, h4, h5, h6").eq(0).remove();
if (heading) $("#modal .modal-header h3").text(heading.text());
var submit = data.find("form input[type=submit]").eq(0).remove();
$("#modal .modal-body").html(data.html());
$("#modal .modal-footer input[type=submit]").remove();
if (submit) $("#modal .modal-footer").prepend(submit);
$("#modal").modal("show");
}
var display_modal = function(event) {
event.preventDefault();
$.get(this.href, "", populate_modal, "html");
return false;
}
var ajax_form_catch = function(event) {
event.preventDefault();
var form = $("#modal form");
$.post(form.attr("action"), form.serialize(), populate_modal, "html");
return false;
};
$("a.ajax_window").live("click", display_modal);
$("#modal .modal-footer input[type=submit]").live("click", ajax_form_catch);
$("#modal form").live("submit", ajax_form_catch);
});
|
/* ajax_windows.js. Support for modal popup windows in Umlaut items. */
jQuery(document).ready(function($) {
var populate_modal = function(data, textStatus, jqXHR) {
data = $(data);
var heading = data.find("h1, h2, h3, h4, h5, h6").eq(0).remove();
$("#modal .modal-header h3").text(heading.text());
var submit = data.find("form input[type=submit]").eq(0).remove();
$("#modal .modal-body").html(data.html());
footer = $("#modal .modal-footer")
var old_submit = footer.find("#modal .modal-footer input[type=submit]").eq(0).remove();
if (submit) {
footer.prepend(submit);
}
$("#modal").modal("show");
}
var display_modal = function(event) {
event.preventDefault();
$.get(this.href, "", populate_modal, "html");
return false;
}
var ajax_form_catch = function(event) {
event.preventDefault();
var form = $("#modal form");
$.post(form.attr("action"), form.serialize(), populate_modal, "html");
return false;
};
$("a.ajax_window").live("click", display_modal);
$("#modal .modal-footer input[type=submit]").live("click", ajax_form_catch);
$("#modal form").live("submit", ajax_form_catch);
});
|
Fix uncaught exception if minecraft server is offline when the bot starts
|
'use strict';
module.exports = function(config, ircbot) {
const Rcon = require('rcon');
const client = new Rcon(config.rcon.host, config.rcon.port, config.rcon.password);
client.on('auth', function() {
console.log('RCON authentication successful');
}).on('response', function(str) {
console.log('RCON got response: ' + str);
}).on('end', function() {
console.log('RCON socket closed');
}).on('error', function(e) {
console.log('RCON socket connection failed: ' + e.message);
});
client.connect();
ircbot.addListener('action', function(from, to, text) {
if (to !== config.channel) {
return;
}
client.send('say * ' + from + ' ' + text);
});
ircbot.addListener('message' + config.channel, function(from, text) {
client.send('say <' + from + '> ' + text);
});
};
|
'use strict';
module.exports = function(config, ircbot) {
const Rcon = require('rcon');
const client = new Rcon(config.rcon.host, config.rcon.port, config.rcon.password);
client.on('auth', function() {
console.log('RCON authentication successful');
}).on('response', function(str) {
console.log('RCON got response: ' + str);
}).on('end', function() {
console.log('RCON socket closed');
});
client.connect();
ircbot.addListener('action', function(from, to, text) {
if (to !== config.channel) {
return;
}
client.send('say * ' + from + ' ' + text);
});
ircbot.addListener('message' + config.channel, function(from, text) {
client.send('say <' + from + '> ' + text);
});
};
|
Make helper class final and non-instantiable
|
package fr.tvbarthel.apps.devredpe2014.ui;
import android.app.ActionBar;
import android.content.Context;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.TypefaceSpan;
import fr.tvbarthel.apps.devredpe2014.R;
public final class ActionBarHelper {
public static void setDevredTitle(Context context, ActionBar actionBar) {
if (actionBar != null) {
SpannableString title = new SpannableString(context.getString(R.string.app_name).toUpperCase());
TypefaceSpan typefaceSpanLight = new TypefaceSpan("sans-serif-light");
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(context.getResources().getColor(android.R.color.holo_red_dark));
title.setSpan(typefaceSpanLight, 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
title.setSpan(foregroundColorSpan, title.length() - 4, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
actionBar.setTitle(title);
}
}
// Non instantiable class.
private ActionBarHelper() {
}
}
|
package fr.tvbarthel.apps.devredpe2014.ui;
import android.app.ActionBar;
import android.content.Context;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.TypefaceSpan;
import fr.tvbarthel.apps.devredpe2014.R;
public class ActionBarHelper {
public static void setDevredTitle(Context context, ActionBar actionBar) {
if (actionBar != null) {
SpannableString title = new SpannableString(context.getString(R.string.app_name).toUpperCase());
TypefaceSpan typefaceSpanLight = new TypefaceSpan("sans-serif-light");
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(context.getResources().getColor(android.R.color.holo_red_dark));
title.setSpan(typefaceSpanLight, 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
title.setSpan(foregroundColorSpan, title.length() - 4, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
actionBar.setTitle(title);
}
}
}
|
Add exception when mysql is not support for fulltext index
|
<?php namespace Octommerce\Octommerce\Updates;
use DB;
use Schema;
use Exception;
use October\Rain\Database\Updates\Migration;
class AddFulltextIndexToProductsTable extends Migration
{
public function up()
{
try {
DB::statement('ALTER TABLE octommerce_octommerce_products ADD FULLTEXT (name)');
DB::statement('ALTER TABLE octommerce_octommerce_products ADD FULLTEXT (description)');
DB::statement('ALTER TABLE octommerce_octommerce_products ADD FULLTEXT (sku)');
DB::statement('ALTER TABLE octommerce_octommerce_products ADD FULLTEXT (keywords)');
} catch (Exception $e) {
// MySQL is not supported. Please update to the newer version
}
}
public function down()
{
try {
Schema::table('octommerce_octommerce_products', function($table) {
$table->dropIndex(['name', 'description', 'sku', 'keywords']);
});
} catch (Exception $e) {
// MySQL is not supported. Please update to the newer version
}
}
}
|
<?php namespace Octommerce\Octommerce\Updates;
use DB;
use Schema;
use October\Rain\Database\Updates\Migration;
class AddFulltextIndexToProductsTable extends Migration
{
public function up()
{
DB::statement('ALTER TABLE octommerce_octommerce_products ADD FULLTEXT (name)');
DB::statement('ALTER TABLE octommerce_octommerce_products ADD FULLTEXT (description)');
DB::statement('ALTER TABLE octommerce_octommerce_products ADD FULLTEXT (sku)');
DB::statement('ALTER TABLE octommerce_octommerce_products ADD FULLTEXT (keywords)');
}
public function down()
{
Schema::table('octommerce_octommerce_products', function($table) {
$table->dropIndex(['name', 'description', 'sku', 'keywords']);
});
}
}
|
Change tilt series type to float in manual background sub.
|
def transform_scalars(dataset):
from tomviz import utils
import numpy as np
#----USER SPECIFIED VARIABLES-----#
###XRANGE###
###YRANGE###
###ZRANGE###
#---------------------------------#
data_bs = utils.get_array(dataset) #get data as numpy array
data_bs = data_bs.astype(np.float32) #change tilt series type to float
if data_bs is None: #Check if data exists
raise RuntimeError("No data array found!")
for i in range(ZRANGE[0],ZRANGE[1]):
a = data_bs[:,:,i] - np.average(data_bs[XRANGE[0]:XRANGE[1],YRANGE[0]:YRANGE[1],i])
data_bs[:,:,i] = a
utils.set_array(dataset, data_bs)
|
def transform_scalars(dataset):
from tomviz import utils
import numpy as np
#----USER SPECIFIED VARIABLES-----#
###XRANGE###
###YRANGE###
###ZRANGE###
#---------------------------------#
data_bs = utils.get_array(dataset) #get data as numpy array
if data_bs is None: #Check if data exists
raise RuntimeError("No data array found!")
for i in range(ZRANGE[0],ZRANGE[1]):
a = data_bs[:,:,i] - np.average(data_bs[XRANGE[0]:XRANGE[1],YRANGE[0]:YRANGE[1],i])
data_bs[:,:,i] = a
utils.set_array(dataset, data_bs)
|
Correct a workaround for PyPy
|
from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not issubclass(array, Collection): # PyPy <= 7.3.9
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
|
from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not isinstance(array, Collection): # PyPy issue 3820
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
|
Add slash to initiative submit url
|
from django.conf.urls import url
from bluebottle.initiatives.views import (
InitiativeList, InitiativeDetail, InitiativeImage,
InitiativeReviewTransitionList
)
urlpatterns = [
url(
r'^/transitions$',
InitiativeReviewTransitionList.as_view(),
name='initiative-review-transition-list'
),
url(r'^$', InitiativeList.as_view(), name='initiative-list'),
url(r'^/(?P<pk>\d+)$', InitiativeDetail.as_view(), name='initiative-detail'),
url(
r'^/(?P<pk>\d+)/image/(?P<size>\d+x\d+)$',
InitiativeImage.as_view(),
name='initiative-image'
)
]
|
from django.conf.urls import url
from bluebottle.initiatives.views import (
InitiativeList, InitiativeDetail, InitiativeImage,
InitiativeReviewTransitionList
)
urlpatterns = [
url(
r'^transitions$',
InitiativeReviewTransitionList.as_view(),
name='initiative-review-transition-list'
),
url(r'^$', InitiativeList.as_view(), name='initiative-list'),
url(r'^/(?P<pk>\d+)$', InitiativeDetail.as_view(), name='initiative-detail'),
url(
r'^/(?P<pk>\d+)/image/(?P<size>\d+x\d+)$',
InitiativeImage.as_view(),
name='initiative-image'
)
]
|
Check for permission only in external calls
|
const auth = require('@feathersjs/authentication');
const globalHooks = require('../../../hooks');
const { ScopeService } = require('./ScopeService');
const { lookupScope, checkScopePermissions } = require('./hooks');
/**
* Implements retrieving a list of all users who are associated with a scope.
* @class ScopeMembersService
* @extends {ScopeService}
*/
class ScopeMembersService extends ScopeService {
/**
* Custom set of hooks.
* @static
* @returns Object<FeathersHooksCollection>
* @override ScopeService#hooks
* @memberof ScopeMembersService
*/
static hooks() {
return {
before: {
all: [
globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')),
lookupScope,
globalHooks.ifNotLocal(checkScopePermissions(['SCOPE_PERMISSIONS_VIEW'])),
],
},
};
}
/**
* Implements the route
* @param {Object} params Feathers request params
* @returns {Array<ObjectId>} a list of userIds
* @memberof ScopeMembersService
*/
async find(params) {
const members = await this.handler.apply(this, [params]) || [];
return members;
}
}
module.exports = {
ScopeMembersService,
};
|
const auth = require('@feathersjs/authentication');
const globalHooks = require('../../../hooks');
const { ScopeService } = require('./ScopeService');
const { lookupScope, checkScopePermissions } = require('./hooks');
/**
* Implements retrieving a list of all users who are associated with a scope.
* @class ScopeMembersService
* @extends {ScopeService}
*/
class ScopeMembersService extends ScopeService {
/**
* Custom set of hooks.
* @static
* @returns Object<FeathersHooksCollection>
* @override ScopeService#hooks
* @memberof ScopeMembersService
*/
static hooks() {
return {
before: {
all: [
globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')),
lookupScope,
checkScopePermissions(['SCOPE_PERMISSIONS_VIEW']),
],
},
};
}
/**
* Implements the route
* @param {Object} params Feathers request params
* @returns {Array<ObjectId>} a list of userIds
* @memberof ScopeMembersService
*/
async find(params) {
const members = await this.handler.apply(this, [params]) || [];
return members;
}
}
module.exports = {
ScopeMembersService,
};
|
Fix title for desktop notification
|
# coding: utf-8
import platform
if platform.system() == 'Darwin':
from Foundation import NSUserNotificationDefaultSoundName
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
def desktop_notify(text, title=None, sound=False):
title = title or 'Modder'
notification = NSUserNotification.alloc().init()
notification.setTitle_(title.decode('utf-8'))
notification.setInformativeText_(text.decode('utf-8'))
if sound:
notification.setSoundName_(NSUserNotificationDefaultSoundName)
center = NSUserNotificationCenter.defaultUserNotificationCenter()
center.deliverNotification_(notification)
elif platform.system() == 'Windows':
def desktop_notify(text, title=None, sound=False):
title = title or 'Modder'
pass
elif platform.system() == 'Linux':
def desktop_notify(text, title=None, sound=False):
title = title or 'Modder'
pass
|
# coding: utf-8
import platform
if platform.system() == 'Darwin':
from Foundation import NSUserNotificationDefaultSoundName
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
def desktop_notify(text, title='Modder', sound=False):
notification = NSUserNotification.alloc().init()
notification.setTitle_(title.decode('utf-8'))
notification.setInformativeText_(text.decode('utf-8'))
if sound:
notification.setSoundName_(NSUserNotificationDefaultSoundName)
center = NSUserNotificationCenter.defaultUserNotificationCenter()
center.deliverNotification_(notification)
elif platform.system() == 'Windows':
def desktop_notify(text, title='Modder', sound=False):
pass
elif platform.system() == 'Linux':
def desktop_notify(text, title='Modder', sound=False):
pass
|
Fix typo causing fatal error.
|
<?php
use Cake\Core\Plugin;
use Cake\Routing\Router;
Router::scope('/', function($routes) {
/**
* Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/View/Pages/home.ctp)...
*/
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
/**
* Connect a route for the index action of any controller.
* And a more general catch all route for any action.
*
* You can remove these routes once you've connected the
* routes you want in your application.
*/
$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'InflectedRoute']);
$routes->connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']);
});
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
|
<?php
use Cake\Core\Plugin;
use Cake\Routing\Router;
Router::scope('/', function($routes) {
/**
* Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/View/Pages/home.ctp)...
*/
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
$routes->connect('/pages/*', ['controller', => 'pages', 'action' => 'display']);
/**
* Connect a route for the index action of any controller.
* And a more general catch all route for any action.
*
* You can remove these routes once you've connected the
* routes you want in your application.
*/
$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'InflectedRoute']);
$routes->connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']);
});
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
|
Add students app url configuration
|
"""halaqat URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from back_office import urls as back_office_url
from students import urls as students_url
urlpatterns = [
url(r'^back_office/', include(back_office_url)),
url(r'^students/', include(students_url)),
url(r'^admin/', include(admin.site.urls)),
]
|
"""halaqat URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from back_office import urls as back_office_url
urlpatterns = [
url(r'^back_office/', include(back_office_url)),
url(r'^admin/', include(admin.site.urls)),
]
|
Fix public fields from Event
|
from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
|
from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
|
Fix user collection pass by ref.
|
package models
import (
"github.com/UserStack/ustackd/backends"
)
type UserCollection struct {
}
func (this *UserCollection) All() []User {
return []User{
User{&backends.User{Uid: 1, Email: "foo"}},
User{&backends.User{Uid: 2, Email: "admin"}},
User{&backends.User{Uid: 3, Email: "abc"}},
User{&backends.User{Uid: 4, Email: "def"}},
User{&backends.User{Uid: 5, Email: "hij"}},
User{&backends.User{Uid: 6, Email: "glk"}},
User{&backends.User{Uid: 7, Email: "uvw"}},
User{&backends.User{Uid: 8, Email: "xyz"}}}
}
func (this *UserCollection) Find(uid int64) *User {
for _, user := range this.All() {
if user.Uid == uid {
return &user
}
}
return &User{}
}
func Users() *UserCollection {
return &UserCollection{}
}
|
package models
import (
"github.com/UserStack/ustackd/backends"
)
type UserCollection struct {
}
func (this UserCollection) All() []User {
return []User{
User{&backends.User{Uid: 1, Email: "foo"}},
User{&backends.User{Uid: 2, Email: "admin"}},
User{&backends.User{Uid: 3, Email: "abc"}},
User{&backends.User{Uid: 4, Email: "def"}},
User{&backends.User{Uid: 5, Email: "hij"}},
User{&backends.User{Uid: 6, Email: "glk"}},
User{&backends.User{Uid: 7, Email: "uvw"}},
User{&backends.User{Uid: 8, Email: "xyz"}}}
}
func (this UserCollection) Find(uid int64) *User {
for _, user := range this.All() {
if user.Uid == uid {
return &user
}
}
return &User{}
}
func Users() UserCollection {
return UserCollection{}
}
|
Add call to make login default
|
#!/usr/bin/env node
'use strict'
var program = require('commander')
var winston = require('winston')
var exec = require('./lib/exec')
program
.version(require('./package.json').version)
.description('Ensure default login keychain exists')
.parse(process.argv)
exec('security list-keychains -d user').then(function (process) {
if (/keychain/.test(process.stdout)) {
winston.info('Keychain exists')
} else {
return exec('security create-keychain -p "" login.keychain').then(function (process) {
winston.info('Created keychain')
}).catch(function (err) {
if (err === 48) {
winston.info('Restored keychain')
} else {
throw err
}
}).then(function () {
return exec('security default-keychain -s login.keychain');
})
}
})
.catch(function (err) {
winston.error('Tried to create keychain', err)
process.exit(1)
})
|
#!/usr/bin/env node
'use strict'
var program = require('commander')
var winston = require('winston')
var exec = require('./lib/exec')
program
.version(require('./package.json').version)
.description('Ensure default login keychain exists')
.parse(process.argv)
exec('security list-keychains -d user').then(function (process) {
if (/keychain/.test(process.stdout)) {
winston.info('Keychain exists')
} else {
return exec('security create-keychain -p "" login.keychain').then(function (process) {
winston.info('Created keychain')
}).catch(function (err) {
if (err === 48) {
winston.info('Restored keychain')
} else {
throw err
}
})
}
})
.catch(function (err) {
winston.error('Tried to create keychain', err)
process.exit(1)
})
|
Remove default route for serving static files from URL map.
|
# -*- coding: utf-8 -*-
"""
Gewebehaken
~~~~~~~~~~~
The WSGI application
:Copyright: 2015 `Jochen Kupperschmidt <http://homework.nwsnet.de/>`_
:License: MIT, see LICENSE for details.
"""
import logging
from logging import FileHandler, Formatter
from flask import Flask
from .hooks.twitter import blueprint as twitter_blueprint
def create_app(log_filename=None):
"""Create the actual application."""
app = Flask(__name__, static_folder=None)
if log_filename:
configure_logging(app, log_filename)
app.register_blueprint(twitter_blueprint)
return app
def configure_logging(app, filename):
"""Configure app to log to that file."""
handler = FileHandler(filename, encoding='utf-8')
handler.setFormatter(Formatter('%(asctime)s %(funcName)s %(message)s'))
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
# -*- coding: utf-8 -*-
"""
Gewebehaken
~~~~~~~~~~~
The WSGI application
:Copyright: 2015 `Jochen Kupperschmidt <http://homework.nwsnet.de/>`_
:License: MIT, see LICENSE for details.
"""
import logging
from logging import FileHandler, Formatter
from flask import Flask
from .hooks.twitter import blueprint as twitter_blueprint
def create_app(log_filename=None):
"""Create the actual application."""
app = Flask(__name__)
if log_filename:
configure_logging(app, log_filename)
app.register_blueprint(twitter_blueprint)
return app
def configure_logging(app, filename):
"""Configure app to log to that file."""
handler = FileHandler(filename, encoding='utf-8')
handler.setFormatter(Formatter('%(asctime)s %(funcName)s %(message)s'))
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
Update for cards package refactoring
|
package jcrib;
import java.util.ArrayList;
import java.util.List;
import jcrib.cards.Card;
import jcrib.cards.Hand;
public class Player {
private String name;
private int points;
private Hand hand;
private Card cut;
private List<List<Score>> scores = new ArrayList<>();
public Player(String name) {
this.name = name;
this.hand = new Hand();
}
public void addScores(List<Score> scores) {
this.scores.add(scores);
}
public String getName() {
return name;
}
public Hand getHand() {
return hand;
}
public Card getCutCard() {
return cut;
}
public void setCutCard(Card cut) {
this.cut = cut;
}
public int getPoints() {
return points;
}
@Override
public String toString() {
return name + ": " + getPoints() + " pts; " + hand.toString();
}
}
|
package jcrib;
import java.util.ArrayList;
import java.util.List;
public class Player {
private String name;
private int points;
private Hand hand;
private Card cut;
private List<List<Score>> scores = new ArrayList<>();
public Player(String name) {
this.name = name;
this.hand = new Hand();
}
public void addScores(List<Score> scores) {
this.scores.add(scores);
}
public String getName() {
return name;
}
public Hand getHand() {
return hand;
}
public Card getCutCard() {
return cut;
}
public void setCutCard(Card cut) {
this.cut = cut;
}
public int getPoints() {
return points;
}
@Override
public String toString() {
return name + ": " + points + " pts; " + hand.toString();
}
}
|
Fix tab spacing from 2 to 4 spaces
|
#!/usr/local/bin/python3.6
# read nginx access log
# parse and get the ip addresses and times
# match ip addresses to geoip
# possibly ignore bots
import re
def get_log_lines(path):
"""Return a list of regex matched log lines from the passed nginx access log path"""
lines = []
with open(path) as f:
r = re.compile("""(?P<remote>[^ ]*) (?P<host>[^ ]*) (?P<user>[^ ]*) \[(?P<time>[^\]]*)\] "(?P<method>\S+)(?: +(?P<path>[^\"]*) +\S*)?" (?P<code>[^ ]*) (?P<size>[^ ]*)(?: "(?P<referer>[^\"]*)" "(?P<agent>[^\"]*)")""")
for line in f:
m = r.match(line)
if m is not None:
md = m.groupdict()
lines.append(md)
return lines
def get_ip_address_city(ip_address):
pass
def is_bot(useragent):
pass
def summarize(data):
pass
if __name__ == "__main__":
access_file_path = "/var/log/nginx/imadm.ca.access.log"
access_log = get_log_lines(access_file_path)
|
#!/usr/local/bin/python3.6
# read nginx access log
# parse and get the ip addresses and times
# match ip addresses to geoip
# possibly ignore bots
import re
def get_log_lines(path):
"""Return a list of regex matched log lines from the passed nginx access log path"""
lines = []
with open(path) as f:
r = re.compile("""(?P<remote>[^ ]*) (?P<host>[^ ]*) (?P<user>[^ ]*) \[(?P<time>[^\]]*)\] "(?P<method>\S+)(?: +(?P<path>[^\"]*) +\S*)?" (?P<code>[^ ]*) (?P<size>[^ ]*)(?: "(?P<referer>[^\"]*)" "(?P<agent>[^\"]*)")""")
for line in f:
m = r.match(line)
if m is not None:
md = m.groupdict()
lines.append(md)
return lines
def get_ip_address_city(ip_address):
pass
def is_bot(useragent):
pass
def summarize(data):
pass
if __name__ == "__main__":
access_file_path = "/var/log/nginx/imadm.ca.access.log"
access_log = get_log_lines(access_file_path)
|
Fix issue of count down latch example2 didn't shutdown
|
package com.hzh.corejava.concurrent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by huangzehai on 2017/2/20.
*/
class CountDownLatchExample2 { // ...
private static final int N = 3;
public static void main(String[] args) throws InterruptedException {
CountDownLatch doneSignal = new CountDownLatch(N);
ExecutorService e = Executors.newFixedThreadPool(3);
for (int i = 0; i < N; ++i) // create and start threads
e.execute(new WorkerRunnable(doneSignal, i));
doneSignal.await(); // wait for all to finish
e.shutdown();
System.out.println("Done all jobs");
}
}
class WorkerRunnable implements Runnable {
private final CountDownLatch doneSignal;
private final int i;
WorkerRunnable(CountDownLatch doneSignal, int i) {
this.doneSignal = doneSignal;
this.i = i;
}
public void run() {
doWork(i);
doneSignal.countDown();
}
void doWork(int i) {
System.out.println("Do job for part " + i);
}
}
|
package com.hzh.corejava.concurrent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* Created by huangzehai on 2017/2/20.
*/
class CountDownLatchExample2 { // ...
private static final int N = 3;
public static void main(String[] args) throws InterruptedException {
CountDownLatch doneSignal = new CountDownLatch(N);
Executor e = Executors.newFixedThreadPool(3);
for (int i = 0; i < N; ++i) // create and start threads
e.execute(new WorkerRunnable(doneSignal, i));
doneSignal.await(); // wait for all to finish
System.out.println("Done all jobs");
}
}
class WorkerRunnable implements Runnable {
private final CountDownLatch doneSignal;
private final int i;
WorkerRunnable(CountDownLatch doneSignal, int i) {
this.doneSignal = doneSignal;
this.i = i;
}
public void run() {
doWork(i);
doneSignal.countDown();
}
void doWork(int i) {
System.out.println("Do job for part " + i);
}
}
|
Include the eslint react defaults so it behaves as expected for React JSX files
|
module.exports = {
'parser': 'babel-eslint',
'env': {
'browser': true,
'es6': true,
'node': true,
},
'extends': [
'eslint:recommended',
'plugin:react/recommended',
],
'installedESLint': true,
'parserOptions': {
'ecmaFeatures': {
'experimentalObjectRestSpread': true,
'jsx': true,
},
'sourceType': 'module',
},
'plugins': [
'react',
'jsx',
],
'rules': {
'indent': [
'error',
2,
],
'linebreak-style': [
'error',
'unix',
],
'quotes': [
'error',
'single',
],
'semi': [
'error',
'never',
],
}
}
|
module.exports = {
'parser': 'babel-eslint',
'env': {
'browser': true,
'es6': true,
'node': true,
},
'extends': 'eslint:recommended',
'installedESLint': true,
'parserOptions': {
'ecmaFeatures': {
'experimentalObjectRestSpread': true,
'jsx': true,
},
'sourceType': 'module',
},
'plugins': [
'react',
'jsx',
],
'rules': {
'indent': [
'error',
2,
],
'linebreak-style': [
'error',
'unix',
],
'quotes': [
'error',
'single',
],
'semi': [
'error',
'never',
],
}
}
|
Rework shared options to share values
|
module.exports = function shareOptionValues(commands) {
let providedOptionsById = {}
commands.forEach(({ options }) => {
if (options && options.length) {
options.forEach((option) => {
if (option.config) {
providedOptionsById[option.config.id] = option
}
})
}
})
return commands.map((command) => {
let { config, options } = command
if (!config || !config.options || !config.options.length) {
return command
}
let providedCommandOptions = config.options
.filter(({ id }) => providedOptionsById[id])
.map(({ id }) => providedOptionsById[id])
command = Object.assign({}, command)
command.options = (options || [])
.filter(({ id }) => !providedOptionsById[id])
.concat(providedCommandOptions)
return command
})
}
|
module.exports = function shareOptionValues(commands) {
let providedOptionsById = {}
commands.forEach(({ options }) => {
if (options) {
options.forEach((option) => {
if (option.config) {
providedOptionsById[option.config.id] = option
}
})
}
})
return commands.map((command) => {
if (!command.config || !command.config.options) {
return command
}
command = Object.assign({}, command)
command.config.options.forEach(({ id }) => {
let providedOption = providedOptionsById[id]
if (providedOption) {
let option = command.options && command.options.find((o) => {
return o.config && o.config.id === id
})
if (!option) {
command.options.push(providedOption)
}
}
})
return command
})
}
|
Change DSLR description - so it doesn't look like a duplicate
|
package org.drools.workbench.screens.guided.rule.type;
import javax.enterprise.context.ApplicationScoped;
import org.uberfire.backend.vfs.Path;
import org.uberfire.workbench.type.ResourceTypeDefinition;
@ApplicationScoped
public class GuidedRuleDSLRResourceTypeDefinition
implements ResourceTypeDefinition {
@Override
public String getShortName() {
return "guided rule (with DSL)";
}
@Override
public String getDescription() {
return "Guided Rule (with DSL)";
}
@Override
public String getPrefix() {
return "";
}
@Override
public String getSuffix() {
return "gre.dslr";
}
@Override
public int getPriority() {
return 102;
}
@Override
public String getSimpleWildcardPattern() {
return "*." + getSuffix();
}
@Override
public boolean accept( final Path path ) {
return path.getFileName().endsWith( "." + getSuffix() );
}
}
|
package org.drools.workbench.screens.guided.rule.type;
import javax.enterprise.context.ApplicationScoped;
import org.uberfire.backend.vfs.Path;
import org.uberfire.workbench.type.ResourceTypeDefinition;
@ApplicationScoped
public class GuidedRuleDSLRResourceTypeDefinition
implements ResourceTypeDefinition {
@Override
public String getShortName() {
return "guided rule (with DSL)";
}
@Override
public String getDescription() {
return "Guided Rule";
}
@Override
public String getPrefix() {
return "";
}
@Override
public String getSuffix() {
return "gre.dslr";
}
@Override
public int getPriority() {
return 102;
}
@Override
public String getSimpleWildcardPattern() {
return "*." + getSuffix();
}
@Override
public boolean accept( final Path path ) {
return path.getFileName().endsWith( "." + getSuffix() );
}
}
|
FIX Ensure only those with perms to datachanges can view published state
|
<?php
/**
* Add to Pages you want changes recorded for
*
* @author stephen@silverstripe.com.au
* @license BSD License http://silverstripe.org/bsd-license/
*/
class SiteTreeChangeRecordable extends ChangeRecordable {
public function onAfterPublish(&$original) {
$this->dataChangeTrackService->track($this->owner, 'Publish');
}
public function onAfterUnpublish() {
$this->dataChangeTrackService->track($this->owner, 'Unpublish');
}
public function updateCMSFields(FieldList $fields) {
if (Permission::check('CMS_ACCESS_DataChangeAdmin')) {
//Get all data changes relating to this page filter them by publish/unpublish
$dataChanges = DataChangeRecord::get()->filter('ClassID', $this->owner->ID)->exclude('ChangeType', 'Change');
//create a gridfield out of them
$gridFieldConfig = GridFieldConfig_RecordViewer::create();
$publishedGrid = new GridField('PublishStates', 'Published States', $dataChanges, $gridFieldConfig);
$dataColumns = $publishedGrid->getConfig()->getComponentByType('GridFieldDataColumns');
$dataColumns->setDisplayFields(array('ChangeType' => 'Change Type',
'ObjectTitle' => 'Page Title',
'ChangedBy.Title' => 'User',
'Created' => 'Modification Date',
));
//linking through to the datachanges modeladmin
$fields->addFieldsToTab('Root.PublishedState', $publishedGrid);
return $fields;
}
}
}
|
<?php
/**
* Add to Pages you want changes recorded for
*
* @author stephen@silverstripe.com.au
* @license BSD License http://silverstripe.org/bsd-license/
*/
class SiteTreeChangeRecordable extends ChangeRecordable {
public function onAfterPublish(&$original) {
$this->dataChangeTrackService->track($this->owner, 'Publish');
}
public function onAfterUnpublish() {
$this->dataChangeTrackService->track($this->owner, 'Unpublish');
}
public function updateCMSFields(FieldList $fields) {
//Get all data changes relating to this page filter them by publish/unpublish
$dataChanges = DataChangeRecord::get()->filter('ClassID', $this->owner->ID)->exclude('ChangeType', 'Change');
//create a gridfield out of them
$gridFieldConfig = GridFieldConfig_RecordViewer::create();
$publishedGrid = new GridField('PublishStates', 'Published States', $dataChanges, $gridFieldConfig);
$dataColumns = $publishedGrid->getConfig()->getComponentByType('GridFieldDataColumns');
$dataColumns->setDisplayFields(array('ChangeType' => 'Change Type',
'ObjectTitle' => 'Page Title',
'ChangedBy.Title' => 'User',
'Created' => 'Modification Date',
));
//linking through to the datachanges modeladmin
$fields->addFieldsToTab('Root.PublishedState', $publishedGrid);
return $fields;
}
}
|
Add speech prefixes - still required in 2012, so should be left in due to reader issues
|
"use strict";
/**
* Properties to prefix.
*/
var postcss = require("postcss"),
props = [
// text
"hyphens",
"line-break",
"text-align-last",
"text-emphasis",
"text-emphasis-color",
"text-emphasis-style",
"word-break",
// writing modes
"writing-mode",
"text-orientation",
"text-combine-upright",
// text to speech
"cue",
"cue-before",
"cue-after",
"pause",
"rest",
"speak",
"speak-as",
"voice-family"
];
/**
* PostCSS plugin to prefix ePub3 properties.
* @param {Object} style
*/
function plugin(style) {
style.eachDecl(function(decl) {
if (decl.value) {
if (props.indexOf(decl.prop) >= 0) {
decl.parent.insertBefore(decl, decl.clone({prop: "-epub-" + decl.prop}));
}
}
});
}
/*
* ...and export for use...
*/
module.exports = {
postcss: plugin,
process: function(css, opts) {
return postcss(plugin).process(css, opts).css;
}
};
|
"use strict";
/**
* Properties to prefix.
*/
var postcss = require("postcss"),
props = [
"hyphens",
"line-break",
"text-align-last",
"text-emphasis",
"text-emphasis-color",
"text-emphasis-style",
"word-break",
// writing modes
"writing-mode",
"text-orientation",
"text-combine-upright"
];
/**
* PostCSS plugin to prefix ePub3 properties.
* @param {Object} style
*/
function plugin(style) {
style.eachDecl(function(decl) {
if (decl.value) {
if (props.indexOf(decl.prop) >= 0) {
decl.parent.insertBefore(decl, decl.clone({prop: "-epub-" + decl.prop}));
}
}
});
}
/*
* ...and export for use...
*/
module.exports = {
postcss: plugin,
process: function(css, opts) {
return postcss(plugin).process(css, opts).css;
}
};
|
Update gunicorn timeout after gunicorn issue was answered.
|
# This file contains gunicorn configuration setttings, as described at
# http://docs.gunicorn.org/en/latest/settings.html
# The file is loaded via the -c ichnaea.gunicorn_config command line option
# Be explicit about the worker class
worker_class = "sync"
# Set timeout to the same value as the default one from Amazon ELB (60 secs).
timeout = 60
# Recycle worker processes after 100k requests to prevent memory leaks
# from effecting us
max_requests = 100000
# Avoid too much output on the console
loglevel = "warning"
def post_worker_init(worker):
from random import randint
# Use 10% jitter, to prevent all workers from restarting at once,
# as they get an almost equal number of requests
jitter = randint(0, max_requests // 10)
worker.max_requests += jitter
# Actually initialize the application
worker.wsgi(None, None)
|
# This file contains gunicorn configuration setttings, as described at
# http://docs.gunicorn.org/en/latest/settings.html
# The file is loaded via the -c ichnaea.gunicorn_config command line option
# Be explicit about the worker class
worker_class = "sync"
# Set timeout to the same value as the default one from Amazon ELB (60 secs).
# It should be 60 seconds, but gunicorn halves the configured value,
# see https://github.com/benoitc/gunicorn/issues/829
timeout = 120
# Recycle worker processes after 100k requests to prevent memory leaks
# from effecting us
max_requests = 100000
# Avoid too much output on the console
loglevel = "warning"
def post_worker_init(worker):
from random import randint
# Use 10% jitter, to prevent all workers from restarting at once,
# as they get an almost equal number of requests
jitter = randint(0, max_requests // 10)
worker.max_requests += jitter
# Actually initialize the application
worker.wsgi(None, None)
|
Print Preview: Hook up the cancel button.
BUG=57895
TEST=manual
Review URL: http://codereview.chromium.org/5151009
git-svn-id: http://src.chromium.org/svn/trunk/src@66822 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: b25a2a4aa82aa8107b7f95d2e4a61633652024d7
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
$('cancel-button').addEventListener('click', function(e) {
window.close();
});
chrome.send('getPrinters');
};
/**
* Fill the printer list drop down.
*/
function setPrinters(printers) {
if (printers.length > 0) {
for (var i = 0; i < printers.length; ++i) {
var option = document.createElement('option');
option.textContent = printers[i];
$('printer-list').add(option);
}
} else {
var option = document.createElement('option');
option.textContent = localStrings.getString('no-printer');
$('printer-list').add(option);
$('printer-list').disabled = true;
$('print-button').disabled = true;
}
}
window.addEventListener('DOMContentLoaded', load);
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
chrome.send('getPrinters');
};
/**
* Fill the printer list drop down.
*/
function setPrinters(printers) {
if (printers.length > 0) {
for (var i = 0; i < printers.length; ++i) {
var option = document.createElement('option');
option.textContent = printers[i];
$('printer-list').add(option);
}
} else {
var option = document.createElement('option');
option.textContent = localStrings.getString('no-printer');
$('printer-list').add(option);
$('printer-list').disabled = true;
$('print-button').disabled = true;
}
}
window.addEventListener('DOMContentLoaded', load);
|
Revert "Fix headless unit test running"
This reverts commit d2652f66c5cd09730a789373fe1cc0f51d357b7d.
That commit just made us not run the unit tests from Gulp any more.
|
/*
Copyright 2014 Spotify AB
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.
*/
/* global require */
var gulp = require('gulp');
var qunit = require('gulp-qunit');
var jshint = require('gulp-jshint');
var htmlhint = require("gulp-htmlhint");
var csslint = require("gulp-csslint");
gulp.task('test', function() {
return gulp.src('./test.html').pipe(qunit());
});
gulp.task('jslint', function() {
return gulp.src('*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'));
});
gulp.task('htmllint', function() {
return gulp.src(["*.html", "!test.html"])
.pipe(htmlhint())
.pipe(htmlhint.reporter())
.pipe(htmlhint.failReporter());
});
gulp.task('csslint', function() {
gulp.src('*.css')
.pipe(csslint())
.pipe(csslint.reporter())
.pipe(csslint.failReporter());
});
|
/*
Copyright 2014 Spotify AB
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.
*/
/* global require */
var gulp = require('gulp');
var qunit = require('gulp-qunit');
var jshint = require('gulp-jshint');
var htmlhint = require("gulp-htmlhint");
var csslint = require("gulp-csslint");
gulp.task('test', function() {
return gulp.src('file://test.html').pipe(qunit());
});
gulp.task('jslint', function() {
return gulp.src('*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'));
});
gulp.task('htmllint', function() {
return gulp.src(["*.html", "!test.html"])
.pipe(htmlhint())
.pipe(htmlhint.reporter())
.pipe(htmlhint.failReporter());
});
gulp.task('csslint', function() {
gulp.src('*.css')
.pipe(csslint())
.pipe(csslint.reporter())
.pipe(csslint.failReporter());
});
|
Rename distributable name to avoid conflicts with releases from the
parent project
Since this is a fork we need to diferentiate between our project and
parent project releases. If we rely only on the version we won't be able
to avoid conflicts with oficial releases on pypi.
|
from setuptools import setup, find_packages
setup(
name='django-robots-pbs',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://github.com/jezdez/django-robots/',
packages=find_packages(),
zip_safe=False,
package_data = {
'robots': [
'locale/*/LC_MESSAGES/*',
'templates/robots/*.html',
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
setup_requires = ['s3sourceuploader',],
)
|
from setuptools import setup, find_packages
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://github.com/jezdez/django-robots/',
packages=find_packages(),
zip_safe=False,
package_data = {
'robots': [
'locale/*/LC_MESSAGES/*',
'templates/robots/*.html',
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
setup_requires = ['s3sourceuploader',],
)
|
Update: Debug log task dependencies to allow them to be silenced
|
'use strict';
var log = require('gulplog');
var chalk = require('chalk');
var prettyTime = require('pretty-hrtime');
var formatError = require('../formatError');
// Wire up logging events
function logEvents(gulpInst) {
var loggedErrors = [];
gulpInst.on('start', function(evt) {
// TODO: batch these
// so when 5 tasks start at once it only logs one time with all 5
var level = evt.branch ? 'debug' : 'info';
log[level]('Starting', '\'' + chalk.cyan(evt.name) + '\'...');
});
gulpInst.on('stop', function(evt) {
var time = prettyTime(evt.duration);
var level = evt.branch ? 'debug' : 'info';
log[level](
'Finished', '\'' + chalk.cyan(evt.name) + '\'',
'after', chalk.magenta(time)
);
});
gulpInst.on('error', function(evt) {
var msg = formatError(evt);
var time = prettyTime(evt.duration);
var level = evt.branch ? 'debug' : 'error';
log[level](
'\'' + chalk.cyan(evt.name) + '\'',
chalk.red('errored after'),
chalk.magenta(time)
);
// If we haven't logged this before, log it and add to list
if (loggedErrors.indexOf(evt.error) === -1) {
log.error(msg);
loggedErrors.push(evt.error);
}
});
}
module.exports = logEvents;
|
'use strict';
var log = require('gulplog');
var chalk = require('chalk');
var prettyTime = require('pretty-hrtime');
var formatError = require('../formatError');
// Wire up logging events
function logEvents(gulpInst) {
var loggedErrors = [];
gulpInst.on('start', function(evt) {
// TODO: batch these
// so when 5 tasks start at once it only logs one time with all 5
log.info('Starting', '\'' + chalk.cyan(evt.name) + '\'...');
});
gulpInst.on('stop', function(evt) {
var time = prettyTime(evt.duration);
log.info(
'Finished', '\'' + chalk.cyan(evt.name) + '\'',
'after', chalk.magenta(time)
);
});
gulpInst.on('error', function(evt) {
var msg = formatError(evt);
var time = prettyTime(evt.duration);
log.error(
'\'' + chalk.cyan(evt.name) + '\'',
chalk.red('errored after'),
chalk.magenta(time)
);
// If we haven't logged this before, log it and add to list
if (loggedErrors.indexOf(evt.error) === -1) {
log.error(msg);
loggedErrors.push(evt.error);
}
});
}
module.exports = logEvents;
|
Fix bug : index out of bound on making cover img
|
const fs = require('fs');
const mm = require('musicmetadata');
// var iconv = require('iconv-lite');
class Music {
constructor(path = '', coverPath = ''){
let read_stream = fs.createReadStream(path);
let parser = mm(read_stream,{duration : true}, (err, data) => {
if(err){
this.valid = false;
throw err;
}
this.path = path;
this.valid = true;
this.title = data.title;
this.artist = data.artist;//array
this.album = data.album;
this.album_artist = data.albumartist;//array
this.year = data.year;
this.track_num = data.track.no;
this.disk_num = data.disk.no;
this.gerne = data.gerne;//array
this.duration = data.duration;
if(data.picture.length){
this.art_format = data.picture[0].format;//picture is an array
this.coverPath = coverPath+this.title +'.'+ this.art_format;
this.cover = this.title +'.'+ this.art_format;
fs.writeFileSync( this.coverPath, data.picture[0].data);
}
read_stream.close();
});
}
}
module.exports = Music;
|
const fs = require('fs');
const mm = require('musicmetadata');
// var iconv = require('iconv-lite');
class Music {
constructor(path = '', coverPath = ''){
let read_stream = fs.createReadStream(path);
let parser = mm(read_stream,{duration : true}, (err, data) => {
if(err){
this.valid = false;
throw err;
}
this.path = path;
this.valid = true;
this.title = data.title;
this.artist = data.artist;//array
this.album = data.album;
this.album_artist = data.albumartist;//array
this.year = data.year;
this.track_num = data.track.no;
this.disk_num = data.disk.no;
this.gerne = data.gerne;//array
this.art_format = data.picture[0].format;//picture is an array
this.duration = data.duration;
this.coverPath = coverPath+this.title +'.'+ this.art_format;
this.cover = this.title +'.'+ this.art_format;
fs.writeFileSync( this.coverPath, data.picture[0].data);
read_stream.close();
});
}
}
module.exports = Music;
|
Change log message and only calculate max age once
|
const logger = require('../config/logger')
const STS_MAX_AGE = 180 * 24 * 60 * 60
module.exports = function headers(req, res, next) {
if (
req.url.indexOf('/css') === -1 &&
req.url.indexOf('/javascripts') === -1 &&
req.url.indexOf('/images') === -1
) {
logger.debug('Headers middleware -> Adding response headers')
res.set('Cache-Control', 'no-cache, no-store, must-revalidate, private')
res.set('Pragma', 'no-cache')
res.set('X-Frame-Options', 'DENY')
res.set('X-Content-Type-Options', 'nosniff')
res.set('X-XSS-Protection', '1; mode=block')
res.set('Strict-Transport-Security', `max-age=${STS_MAX_AGE}`)
}
next()
}
|
const logger = require('../config/logger')
module.exports = function headers(req, res, next) {
if (
req.url.indexOf('/css') === -1 &&
req.url.indexOf('/javascripts') === -1 &&
req.url.indexOf('/images') === -1
) {
logger.debug('adding headers')
const STS_MAX_AGE = 180 * 24 * 60 * 60
res.set('Cache-Control', 'no-cache, no-store, must-revalidate, private')
res.set('Pragma', 'no-cache')
res.set('X-Frame-Options', 'DENY')
res.set('X-Content-Type-Options', 'nosniff')
res.set('X-XSS-Protection', '1; mode=block')
res.set('Strict-Transport-Security', `max-age=${STS_MAX_AGE}`)
}
next()
}
|
Fix some grammatical gender constants
Summary: Ref T5267. I missed these in the variable types conversion.
Test Plan: `arc unit --everything`
Reviewers: chad
Reviewed By: chad
Maniphest Tasks: T5267
Differential Revision: https://secure.phabricator.com/D16824
|
<?php
final class PhabricatorPronounSetting
extends PhabricatorSelectSetting {
const SETTINGKEY = 'pronoun';
public function getSettingName() {
return pht('Pronoun');
}
public function getSettingPanelKey() {
return PhabricatorAccountSettingsPanel::PANELKEY;
}
protected function getSettingOrder() {
return 200;
}
protected function getControlInstructions() {
return pht('Choose the pronoun you prefer.');
}
public function getSettingDefaultValue() {
return PhutilPerson::GENDER_UNKNOWN;
}
protected function getSelectOptions() {
// TODO: When editing another user's settings as an administrator, this
// is not the best username: the user's username would be better.
$viewer = $this->getViewer();
$username = $viewer->getUsername();
$label_unknown = pht('%s updated their profile', $username);
$label_her = pht('%s updated her profile', $username);
$label_his = pht('%s updated his profile', $username);
return array(
PhutilPerson::GENDER_UNKNOWN => $label_unknown,
PhutilPerson::GENDER_MASCULINE => $label_his,
PhutilPerson::GENDER_FEMININE => $label_her,
);
}
}
|
<?php
final class PhabricatorPronounSetting
extends PhabricatorSelectSetting {
const SETTINGKEY = 'pronoun';
public function getSettingName() {
return pht('Pronoun');
}
public function getSettingPanelKey() {
return PhabricatorAccountSettingsPanel::PANELKEY;
}
protected function getSettingOrder() {
return 200;
}
protected function getControlInstructions() {
return pht('Choose the pronoun you prefer.');
}
public function getSettingDefaultValue() {
return PhutilPerson::SEX_UNKNOWN;
}
protected function getSelectOptions() {
// TODO: When editing another user's settings as an administrator, this
// is not the best username: the user's username would be better.
$viewer = $this->getViewer();
$username = $viewer->getUsername();
$label_unknown = pht('%s updated their profile', $username);
$label_her = pht('%s updated her profile', $username);
$label_his = pht('%s updated his profile', $username);
return array(
PhutilPerson::SEX_UNKNOWN => $label_unknown,
PhutilPerson::SEX_MALE => $label_his,
PhutilPerson::SEX_FEMALE => $label_her,
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.