text
stringlengths 2
6.14k
|
|---|
import AbstractKeyEventSimulator from './AbstractKeyEventSimulator';
import Configuration from '../config/Configuration';
import KeyEventType from '../../const/KeyEventType';
class GlobalKeyEventSimulator extends AbstractKeyEventSimulator{
handleKeyPressSimulation(options){
this._handleEventSimulation('handleKeyPress', {eventType: KeyEventType.keypress, ...options});
}
handleKeyUpSimulation(options){
this._handleEventSimulation('handleKeyUp', {eventType: KeyEventType.keyup, ...options});
}
_handleEventSimulation(handlerName, {event, eventType, key}) {
if (this._shouldSimulate(eventType, key) && Configuration.option('simulateMissingKeyPressEvents')) {
/**
* If a key does not have a keypress event, we simulate one immediately after
* the keydown event, to keep the behaviour consistent across all keys
*/
const _event = this.cloneAndMergeEvent(event, {key, simulated: true});
this._keyEventStrategy[handlerName](_event);
}
}
}
export default GlobalKeyEventSimulator;
|
#!/usr/bin/python3
__author__ = 'ivan.shynkarenka'
import argparse
from TTWebClient.TickTraderWebClient import TickTraderWebClient
def main():
parser = argparse.ArgumentParser(description='TickTrader Web API sample')
parser.add_argument('web_api_address', help='TickTrader Web API address')
parser.add_argument('web_api_id', default=None, help='TickTrader Web API Id')
parser.add_argument('web_api_key', default=None, help='TickTrader Web API Key')
parser.add_argument('web_api_secret', default=None, help='TickTrader Web API Secret')
args = parser.parse_args()
# Create instance of the TickTrader Web API client
client = TickTraderWebClient(args.web_api_address, args.web_api_id, args.web_api_key, args.web_api_secret)
# Create, modify and cancel limit order
account = client.get_account()
# Create limit order
limit = client.create_trade(
{
'Type': 'Limit',
'Side': 'Buy',
'Symbol': 'BTCUSD',
'Amount': 0.1,
'Price': 200.0,
'Comment': 'Buy limit from Web API sample'
})
# Modify limit order
limit = client.modify_trade(
{
'Id': limit['Id'],
'Comment': 'Modified limit from Web API sample'
})
# Cancel limit order
client.cancel_trade(limit['Id'])
if __name__ == '__main__':
main()
|
/*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* cmdline.c: Kernel command line creation using ARCS argc/argv.
*
* Copyright (C) 1996 David S. Miller ([email protected])
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <asm/sgialib.h>
#include <asm/bootinfo.h>
#undef DEBUG_CMDLINE
static char *ignored[] = {
"ConsoleIn=",
"ConsoleOut=",
"SystemPartition=",
"OSLoader=",
"OSLoadPartition=",
"OSLoadFilename=",
"OSLoadOptions="
};
static char *used_arc[][2] = {
{ "OSLoadPartition=", "root=" },
{ "OSLoadOptions=", "" }
};
static char * __init move_firmware_args(char* cp)
{
char *s;
int actr, i;
actr = 1; /* Always ignore argv[0] */
while (actr < prom_argc) {
for(i = 0; i < ARRAY_SIZE(used_arc); i++) {
int len = strlen(used_arc[i][0]);
if (!strncmp(prom_argv(actr), used_arc[i][0], len)) {
/* Ok, we want it. First append the replacement... */
strcat(cp, used_arc[i][1]);
cp += strlen(used_arc[i][1]);
/* ... and now the argument */
s = strchr(prom_argv(actr), '=');
if (s) {
s++;
strcpy(cp, s);
cp += strlen(s);
}
*cp++ = ' ';
break;
}
}
actr++;
}
return cp;
}
void __init prom_init_cmdline(void)
{
char *cp;
int actr, i;
actr = 1; /* Always ignore argv[0] */
cp = arcs_cmdline;
/*
* Move ARC variables to the beginning to make sure they can be
* overridden by later arguments.
*/
cp = move_firmware_args(cp);
while (actr < prom_argc) {
for (i = 0; i < ARRAY_SIZE(ignored); i++) {
int len = strlen(ignored[i]);
if (!strncmp(prom_argv(actr), ignored[i], len))
goto pic_cont;
}
/* Ok, we want it. */
strcpy(cp, prom_argv(actr));
cp += strlen(prom_argv(actr));
*cp++ = ' ';
pic_cont:
actr++;
}
if (cp != arcs_cmdline) /* get rid of trailing space */
--cp;
*cp = '\0';
#ifdef DEBUG_CMDLINE
printk(KERN_DEBUG "prom cmdline: %s\n", arcs_cmdline);
#endif
}
|
/*
* Copyright (c) 2007-2013 Sonatype, Inc. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0,
* which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package com.sonatype.nexus.perftest.nuget;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
/**
* Performs basic HTTP operations.
*/
public class NugetHttp
{
public static final int HTTP_TIMEOUT = Integer.parseInt(System.getProperty("perftest.http.timeout", "60000"));
private DefaultHttpClient httpClient;
NugetHttp() {
httpClient = getHttpClient();
}
public HttpResponse get(String url) throws Exception {
final HttpGet get = new HttpGet(url);
return httpClient.execute(get);
}
/**
* Download content from a URL and discard it.
*/
void getAndEat(final String url) throws Exception {
final HttpResponse httpResponse = get(url);
EntityUtils.consumeQuietly(httpResponse.getEntity());
}
private DefaultHttpClient getHttpClient() {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
return new DefaultHttpClient(params);
}
}
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Selenium_EAGLE_TC3_8</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">Selenium_EAGLE_TC3_8</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>https://caintegrator-qa.nci.nih.gov/eagle/</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>username</td>
<td>tbd_value</td>
</tr>
<tr>
<td>type</td>
<td>password</td>
<td>tbd_value</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>//input[@value='Login']</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=CLICKING HERE</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Class Comparison Analysis</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>analysisName</td>
<td>TC3_8</td>
</tr>
<tr>
<td>addSelection</td>
<td>nonselectedGroups</td>
<td>label=all_case</td>
</tr>
<tr>
<td>click</td>
<td>//input[@value='Base>>']</td>
<td></td>
</tr>
<tr>
<td>addSelection</td>
<td>nonselectedGroups</td>
<td>label=stage_IB</td>
</tr>
<tr>
<td>click</td>
<td>//input[@value='>>']</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>//input[@value='Submit Analysis']</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
|
angular
.module('angular-url-format.filter', [
'angular-url-format.parseUrl'
])
.filter('url', function(parseUrl) {
var URL_PARTS = [ 'href', 'protocol', 'host', 'auth', 'hostname', 'port', 'pathname', 'search', 'path', 'query', 'hash' ];
function _parseFormat(string) {
return string.split(',').filter(function(part) {
return (URL_PARTS.indexOf(part) !== -1);
});
}
function _filterKeys(obj, fn, context) {
var res = { };
Object.keys(obj).forEach(function(key) {
if(fn.call(context, key, obj[key], obj)) {
res[key] = obj[key];
}
});
return res;
}
function _joinValues(obj, separator) {
var res = [ ];
Object.keys(obj).forEach(function(key) {
res.push(obj[key]);
});
return res.join(separator);
}
return function(value, format) {
format = _parseFormat(format);
var res = _filterKeys(parseUrl(value), function(key, value) {
return (format.indexOf(key) !== -1) && ('undefined' !== typeof value);
});
return _joinValues(res, '');
};
});
|
"""
Yahoo! Python SDK
* Yahoo! Query Language
* Yahoo! Social API
Find documentation and support on Yahoo! Developer Network: http://developer.yahoo.com
Hosted on GitHub: http://github.com/yahoo/yos-social-python/tree/master
@copyright: Copyrights for code authored by Yahoo! Inc. is licensed under the following terms:
@license: BSD Open Source License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
__author__ = 'Dustin Whittle <[email protected]>'
__version__ = '0.1'
# Yahoo! OAuth Credentials - http://developer.yahoo.com/dashboard/
CONSUMER_KEY = 'dj0yJmk9UHdCeXB0a3lDUzNhJmQ9WVdrOVdHWlJWRFJaTm0wbWNHbzlNVE01T0RBM05EQTBNdy0tJnM9Y29uc3VtZXJzZWNyZXQmeD1jYw--'
CONSUMER_SECRET = 'c629e2fce32ceaf981e11f996e6a16beaea59138'
APPLICATION_ID = 'XfQT4Y6m'
CALLBACK_URL = 'http://yapdemo.appspot.com/'
##############################################################################
# Requires: Python 2.6 + oauth + simplejson #
##############################################################################
# import required modules
import os, sys, getopt, pprint, logging, cgi, urllib
# import google app engine webapp framework
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
# update sys path to include bundled modules with priority
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'sdk/'))
import oauthlib.oauth, gmemsess
import yahoo.oauth, yahoo.yql, yahoo.application
oauthapp = yahoo.application.OAuthApplication(CONSUMER_KEY, CONSUMER_SECRET, APPLICATION_ID, CALLBACK_URL)
"""
/ -> shows login button, if needed, otherwise shows user profile, connection, and updates
/oauth -> handled login button -> oauth dance -> get request token -> redirect user -> get access token
"""
class IndexController(webapp.RequestHandler):
def get(self):
# create a memcache session for storing oauth tokens
session = gmemsess.Session(self)
# user does not have access token
if 'access_token' not in session:
# user does not have request token
if 'request_token' not in session:
# get request token
request_token = oauthapp.get_request_token(CALLBACK_URL)
# store unapproved request token in session
session['request_token'] = request_token.to_string()
session.save()
# redirect the user to authorize the request token
self.redirect(oauthapp.get_authorization_url(request_token))
else:
# retrieve approved request token from session
request_token = yahoo.oauth.RequestToken.from_string(session['request_token'])
# exchange approved request token for valid access token
access_token = oauthapp.get_access_token(request_token, self.request.get('oauth_verifier'))
# store access token in session
session['access_token'] = access_token.to_string()
session.save()
self.redirect(CALLBACK_URL)
else:
oauthapp.token = yahoo.oauth.AccessToken.from_string(session['access_token'])
profile = oauthapp.getProfile()
connections = oauthapp.getConnections()
updates = oauthapp.getUpdates()
self.response.out.write(template.render(os.path.join(os.path.dirname(__file__), 'templates/social.html'), { 'profile': profile, 'connections': connections, 'updates': updates } ))
# session.invalidate()
class OAuthController(webapp.RequestHandler):
def get(self):
session=gmemsess.Session(self)
if 'access_token' in session:
request_token = session['request_token'] if 'request_token' in session else None
if not request_token:
self.response.out.write("No un-authed token found in session")
return
token = oauth.OAuthToken.from_string(request_token)
if token.key != urllib.unquote( self.request.get('oauth_token', 'no-token') ):
self.response.out.write("Something went wrong! Tokens do not match")
return
session.save()
self.redirect('/')
else:
path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
self.response.out.write(template.render(path, {}))
application = webapp.WSGIApplication([('/', IndexController), ('/oauth', OAuthController)], debug=True)
def main():
logging.getLogger().setLevel(logging.DEBUG)
run_wsgi_app(application)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
# Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import webapp2
import handlers
class Warmup(webapp2.RequestHandler):
"""Warms up gubernator."""
def get(self):
"""Receives the warmup request."""
# TODO(fejta): warmup something useful
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Warmup successful')
app = webapp2.WSGIApplication([
('/_ah/warmup', Warmup),
(r'/webhook', handlers.GithubHandler),
(r'/events', handlers.Events),
(r'/status', handlers.Status),
(r'/timeline', handlers.Timeline),
], debug=True)
|
/*
* ArWrapperViewModel.cs
* ARToolKit5
*
* Common ViewModel for binding the ArWrapper component to UI elements.
*
* This file is part of ARToolKit.
*
* ARToolKit is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARToolKit 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ARToolKit. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules, and to
* copy and distribute the resulting executable under terms of your choice,
* provided that you also meet, for each linked independent module, the terms and
* conditions of the license of that module. An independent module is a module
* which is neither derived from nor based on this library. If you modify this
* library, you may extend this exception to your version of the library, but you
* are not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version.
*
* Copyright 2015 Daqri, LLC.
*
* Author(s): Rene Schulte.
*
*/
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.UI.Xaml;
using ARToolKitComponent;
namespace ArWinRtSamples
{
public class ArWrapperViewModel : INotifyPropertyChanged
{
private ThresholdMode _selectedThresholdMode;
private Visibility _manualThresholdVisibility;
private bool _useDebugMode;
private ARWrapper _arWrapper;
public class ThresholdMode
{
public ArThresholdMode Mode { get; private set; }
public string Name { get; private set; }
public ThresholdMode(ArThresholdMode mode)
{
Mode = mode;
Name = Enum.GetName(mode.GetType(), mode);
}
}
public ObservableCollection<ThresholdMode> ThresholdModes { get; private set; }
public ThresholdMode SelectedThresholdMode
{
get { return _selectedThresholdMode; }
set
{
if (_selectedThresholdMode != value && ArWrapper != null)
{
_selectedThresholdMode = value;
// We need to change the threshold mode in the processing thread, not here, otherwise a concurrent op can happen and UpdateAr will crash
//ArWrapper.arwSetVideoThresholdMode(value.Mode);
OnPropertyChanged();
ManualThresholdVisibility = value.Mode == ArThresholdMode.Manual ? Visibility.Visible : Visibility.Collapsed;
}
}
}
public int ManualThresholdValue
{
get { return ArWrapper == null ? -1 : ArWrapper.arwGetVideoThreshold(); }
set
{
if (ArWrapper != null)
{
if (value > 255) value = 255;
else if (value < 0) value = 0;
ArWrapper.arwSetVideoThreshold(value);
OnPropertyChanged();
}
}
}
public Visibility ManualThresholdVisibility
{
get { return _manualThresholdVisibility; }
set
{
if (_manualThresholdVisibility != value)
{
_manualThresholdVisibility = value;
OnPropertyChanged();
}
}
}
public bool UseDebugMode
{
get { return _useDebugMode; }
set
{
if (_useDebugMode != value)
{
// We need to change the debug mode in the processing thread, not here, otherwise a concurrent op can happen and UpdateAr will crash
//ArWrapper.arwSetVideoDebugMode(value);
_useDebugMode = value;
OnPropertyChanged();
}
}
}
public ARWrapper ArWrapper
{
get { return _arWrapper; }
set
{
_arWrapper = value;
if (_arWrapper != null)
{
UseDebugMode = _arWrapper.arwGetVideoDebugMode();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ArWrapperViewModel()
{
ThresholdModes = new ObservableCollection<ThresholdMode>();
foreach (ArThresholdMode mode in Enum.GetValues(typeof(ArThresholdMode)))
{
ThresholdModes.Add(new ThresholdMode(mode));
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.
*/
#ifndef __HASHMAP_H
#define __HASHMAP_H
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#if defined(__amd64__) || defined(__aarch64__)
#define ARCH64
#else
#define ARCH32
#endif
#if defined(ARCH64)
typedef int64_t hash_t;
typedef uint64_t uhash_t;
#elif defined(ARCH32)
typedef int32_t hash_t;
typedef uint32_t uhash_t;
#endif
/** A hash map. */
typedef struct Hashmap Hashmap;
/**
* Creates a new hash map. Returns NULL if memory allocation fails.
*
* @param initialCapacity number of expected entries
* @param hash function which hashes keys
* @param equals function which compares keys for equality
*/
Hashmap* hashmap_create(size_t initialCapacity,
hash_t (*hash)(void* key),
bool (*equals)(void* keyA, void* keyB));
/**
* Frees the hash map. Does not free the keys or values themselves.
*/
void hashmap_free(Hashmap* map);
/**
* Hashes the memory pointed to by key with the given size. Useful for
* implementing hash functions.
*/
hash_t hashmap_hash(void* key, size_t keySize);
/**
* Puts value for the given key in the map. Returns pre-existing value if
* any, otherwise it returns the given value.
*
* If memory allocation fails, this function returns NULL, the map's size
* does not increase, and errno is set to ENOMEM.
*/
void* hashmap_put(Hashmap* map, void* key, void* value);
/**
* Gets a value from the map. Returns NULL if no entry for the given key is
* found or if the value itself is NULL.
*/
void* hashmap_get(Hashmap* map, void* key);
/**
* Returns true if the map contains an entry for the given key.
*/
bool hashmap_contains_key(Hashmap* map, void* key);
/**
* Gets the value for a key. If a value is not found, this function gets a
* value and creates an entry using the given callback.
*
* If memory allocation fails, the callback is not called, this function
* returns NULL, and errno is set to ENOMEM.
*/
void* hashmap_memoize(Hashmap* map, void* key,
void* (*initialValue)(void* key, void* context),
void* context);
/**
* Removes an entry from the map. Returns the removed value or NULL if no
* entry was present.
*/
void* hashmap_remove(Hashmap* map, void* key);
/**
* Gets the number of entries in this map.
*/
size_t hashmap_size(Hashmap* map);
/**
* Invokes the given callback on each entry in the map. Stops iterating if
* the callback returns false.
*/
void hashmap_for_each(Hashmap* map,
bool (*callback)(void* key, void* value, void* context),
void* context);
/**
* Concurrency support.
*/
/**
* Locks the hash map so only the current thread can access it.
*/
void hashmap_lock(Hashmap* map);
/**
* Unlocks the hash map so other threads can access it.
*/
void hashmap_unlock(Hashmap* map);
/**
* Key utilities.
*/
hash_t hashmap_default_hash(void *key);
/**
* Compares two keys for equality.
*/
bool hashmap_default_equals(void* keyA, void* keyB);
/**
* Gets current capacity.
*/
size_t hashmap_current_capacity(Hashmap* map);
/**
* Counts the number of entry collisions.
*/
size_t hashmap_count_collisions(Hashmap* map);
/**
* Key utilities - use pointer as key.
*/
hash_t hashmap_ptr_hash(void *key);
/**
* Compares two pointers for equality.
*/
bool hashmap_ptr_equals(void* keyA, void* keyB);
#endif /* __HASHMAP_H */
|
import json
import os
import urllib.request
from placeholder import PlaceHolder
from projectapi import ProjectApi
class ReleaseNote(ProjectApi):
'''
Release note API.
'''
__PH_TITLE = PlaceHolder('end-title')
__PH_NOTE = PlaceHolder('note')
def __init__(self):
ProjectApi.__init__(self, '/repository/tags/{}'.format(os.environ['CI_COMMIT_TAG']))
self.message_read = False
def get_note(self):
'''
Get full release note.
:return: The note if it exists, None otherwise.
:rtype: str or None
'''
request = self.build_request()
response = urllib.request.urlopen(request)
response_data = response.read().decode()
data = json.loads(response_data)
if data['release'] is None:
return None
else:
self.message_read = True
return data['release']['description']
def get_message(self):
'''
Get release message. Message is extracted from full note.
:return: The message if it exists, empty string otherwise.
:rtype: str
'''
data = self.get_note()
if data is None:
return ''
else:
return ReleaseNote.__PH_NOTE.get_content(data)
def get_note_body(self):
'''
Get release note body (without title). Body is extracted from full note.
:return: The body.
:rtype: str
'''
data = self.get_note()
if data is None:
print('CRITICAL No release information to publish')
exit(1)
return ReleaseNote.__PH_TITLE.get_after(data, True)
def send_note(self, note):
'''
Send the full release note. The current message should have been read
unless you are sure there are none.
:param note: The full note to send.
:type note: str
'''
method = 'PUT' if self.message_read else 'POST'
send_data = {
'tag_name': os.environ['CI_COMMIT_TAG'],
'description': note
}
send_data_serialized = json.dumps(send_data).encode('utf-8')
request = self.build_request('/release', data=send_data_serialized, method=method)
request.add_header('Content-Type', 'application/json')
urllib.request.urlopen(request)
|
<style>
td{text-align:center;}
</style>
<div class="main-panel">
<div class="content">
<div class="container-fluid">
<div class="col-md-12">
<div class="col-md-6">
<?php if($status=="success"){ ?>
<div class="card">
<div class="header">
List Of Student in class
</div>
<?php
if(empty($res)){ ?>
<p class="text-center" style="margin-top:20px;">No Record Found</p> <style>#submit{display: none;}</style>
<?php }else{ ?>
<div class="fresh-datatables">
<form action="" method="post" enctype="multipart/form-data" id="take_attendance">
<input type="hidden" name="a_period" value="<?php echo $session_id; ?>">
<input type="hidden" name="abs_date" value="<?php echo $abs_date; ?>">
<table class="table table-striped">
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center">Name</th>
<th class="text-center">Present / Absent</th>
</tr>
</thead>
<tbody>
<?php $i=1;
foreach($res as $rows){
?>
<tr>
<td class="text-center"><?php echo $i; ?></td>
<input type="hidden" name="student_count" value="<?php echo count($res); ?>">
<td class="text-center"><?php echo $rows->name; ?>
<input type="hidden" name="enroll_id[]" value="<?php echo $rows->enroll_id; ?>">
<input type="hidden" name="class_id" value="<?php echo $class_id; ?>">
</td>
<td>
<select name="attendence_val[]">
<option value="P">Present</option>
<option value="A">Absent</option>
<option value="L">Leave</option>
<option value="OD">On-Duty</option>
</select>
</td>
</tr>
<?php
$i++; } }
?>
</tbody>
</table>
<button type="button" class="btn btn-warning btn-fill btn-wd pull-right" id="submit" style="margin-top:20px;" onclick="submitAttendence()">
Submit Attendance </button>
</form>
</div>
</div>
<?php } else{ ?>
<div class="card-header" data-background-color="purple">
<h4 class="title">Sorry</h4>
<p class="category"><?php echo $status; ?> </p>
</div>
<button onclick="history.go(-1);" class="btn btn-wd btn-default pull-right" style="margin-top:-10px;">Go Back</button>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#attend').addClass('collapse in');
$('#attendance').addClass('active');
$('#attend1').addClass('active');
function submitAttendence(){
swal({
title: "Are you sure?",
text: "You Want Confirm this form",
type: "success",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
$.ajax({
url: "<?php echo base_url(); ?>adminattendance/update_attendance_admin",
type:'POST',
data: $('#take_attendance').serialize(),
success: function(response) {
if(response=="success"){
// swal("Success!", "Thanks for Your Note!", "success");
$('#take_attendance')[0].reset();
swal({
title: "Attendance Done!",
text: "Thank You!",
type: "success"
}, function() {
window.location = "<?php echo base_url(); ?>adminattendance/home";
});
}else{
sweetAlert("Oops...", response, "error");
}
}
});
}else{
swal("Cancelled", "Process Cancel :)", "error");
}
});
}
</script>
|
<?php
declare(strict_types=1);
namespace Documents\Tournament;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/** @ODM\Document */
class TournamentTennis extends Tournament
{
}
|
# BSD 3-Clause License
#
# Copyright (c) 2019, Elasticsearch BV
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from elasticapm.instrumentation.packages.base import AbstractInstrumentedModule
from elasticapm.traces import capture_span
class PythonMemcachedInstrumentation(AbstractInstrumentedModule):
name = "python_memcached"
method_list = [
"add",
"append",
"cas",
"decr",
"delete",
"delete_multi",
"disconnect_all",
"flush_all",
"get",
"get_multi",
"get_slabs",
"get_stats",
"gets",
"incr",
"prepend",
"replace",
"set",
"set_multi",
"touch",
]
# Took out 'set_servers', 'reset_cas', 'debuglog', 'check_key' and
# 'forget_dead_hosts' because they involve no communication.
def get_instrument_list(self):
return [("memcache", "Client." + method) for method in self.method_list]
def call(self, module, method, wrapped, instance, args, kwargs):
name = self.get_wrapped_name(wrapped, instance, method)
address, port = None, None
if instance.servers:
address, port = instance.servers[0].address
destination = {
"address": address,
"port": port,
"service": {"name": "memcached", "resource": "memcached", "type": "cache"},
}
with capture_span(
name, span_type="cache", span_subtype="memcached", span_action="query", extra={"destination": destination}
):
return wrapped(*args, **kwargs)
|
using System;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SmokSmog
{
using Diagnostics;
using Navigation;
using Services;
using Views;
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
this.Loaded += MainPageLoaded;
this.Unloaded += MainPageUnloaded;
}
public bool IsMenuOpen
=> MenuVisualStateGroup.CurrentState == MenuOpen;
public bool IsSearchOpen { get; private set; }
private ViewModel.ViewModelLocator ViewModelLocator { get; } = new ViewModel.ViewModelLocator();
public void CloseMenu()
{
if (IsMenuOpen)
VisualStateManager.GoToState(this, nameof(MenuClose), true);
#if (WINDOWS_APP)
MenuClose.Storyboard?.Begin();
#endif
}
public void CloseSearch(object sender, object parameters)
{
SearchTextBox.SearchString = string.Empty;
IsSearchOpen = false;
var navProvider = Application.Current as INavigationProvider;
if (navProvider?.NavigationService?.CurrentSecondPageKey == nameof(SearchPage))
navProvider?.NavigationService?.NavigateTo(navProvider?.NavigationService.LastSecondPageKey);
SetSearchLayout();
}
public void OpenMenu()
{
if (!IsMenuOpen)
VisualStateManager.GoToState(this, nameof(MenuOpen), true);
#if (WINDOWS_APP)
MenuOpen.Storyboard?.Begin();
#endif
}
public void OpenSearch(object sender, object parameters)
{
var navProvider = Application.Current as INavigationProvider;
if (navProvider?.NavigationService?.CurrentSecondPageKey != nameof(SearchPage))
navProvider?.NavigationService?.NavigateTo(nameof(SearchPage));
IsSearchOpen = true;
SetSearchLayout();
SearchTextBox.Focus(FocusState.Keyboard);
}
public void ToggleMenu()
{
if (IsMenuOpen) CloseMenu(); else OpenMenu();
}
public void ToggleSearch()
{
if (IsSearchOpen)
CloseSearch(null, null);
else
OpenSearch(null, null);
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
try
{
// here is good place to setup background tasks
var tileService = ServiceLocator.Current.TilesService;
await tileService.Initialize();
await tileService.UpdatePrimaryTile();
}
catch (Exception exception)
{
Logger.Log(exception);
}
// if application run first time since last update (or first install)
// show short change log
if (ViewModelLocator.MainViewModel.IsFirstRunAfterUpdate)
{
MessageDialog md = new MessageDialog(ViewModelLocator.MainViewModel.Changelog, "Co nowego");
md.Commands.Add(new UICommand("OK", new UICommandInvokedHandler((cmd) => { })));
await md.ShowAsync();
}
base.OnNavigatedTo(e);
}
private void MainPageLoaded(object sender, RoutedEventArgs e)
{
SizeChanged += MainPageSizeChanged;
SetRootLayout();
var navProvider = Application.Current as INavigationProvider;
navProvider?.NavigationService?.NavigateTo(nameof(StationListPage));
var homeStationId = ServiceLocator.Current.SettingsService.HomeStationId;
if (homeStationId.HasValue)
navProvider?.NavigationService?.NavigateTo(nameof(StationPage), "Home");
else
navProvider?.NavigationService?.NavigateTo(nameof(InformationPage));
#if DEBUG
navProvider?.NavigationService?.NavigateTo(nameof(DebugPage));
#endif
}
private void MainPageSizeChanged(object sender, SizeChangedEventArgs e)
{
SetRootLayout();
SetSearchLayout();
}
private void MainPageUnloaded(object sender, RoutedEventArgs e)
{
SizeChanged -= MainPageSizeChanged;
}
private void SearchTextBox_OnGotFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(SearchTextBox.SearchString))
OpenSearch(null, null);
}
private void SearchTextBox_OnLostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(SearchTextBox.SearchString))
CloseSearch(null, null);
}
private void SetRootLayout()
{
// root layout
string stateName = "Default";
if (ActualWidth >= 850) stateName = "Wide";
if (ActualWidth <= 440) stateName = "Small";
VisualStateManager.GoToState(this, stateName, true);
}
private void SetSearchLayout()
{
// search layout
if (IsSearchOpen)
{
if (ActualWidth > 520)
{
VisualStateManager.GoToState(this, "WideSearchState", true);
}
else
{
VisualStateManager.GoToState(this, "NarrowSearchState", true);
}
}
else
{
VisualStateManager.GoToState(this, "ClosedSearchState", true);
}
}
}
}
|
import Server, { msg, OscType, updateNodeState, whenNodeEnd, whenNodeGo } from "@supercollider/server";
import { Command, Dryad } from "dryadic";
import _ from "lodash";
import SynthDef, { CompiledSynthDef, LoadedSynthDef } from "./SCSynthDef";
const { AddActions, nodeFree, synthNew } = msg;
interface SynthParams {
[name: string]: OscType | Dryad;
}
interface Properties {
args: SynthParams;
def: SynthDef | CompiledSynthDef | LoadedSynthDef | string;
}
interface Context {
id: string;
out?: number;
nodeID?: number;
group?: number;
scserver: Server;
}
/**
* Creates a synth on the server.
*
* Properties:
* - def
* - args
*/
export default class Synth extends Dryad<Properties> {
/**
* Make a Synth that will play the SynthDef compiled from sclang source code.
*
* source may be fully defined:
* `SynthDef("defName", { |out=0, freq=440| Out.ar(SinOsc.ar(freq)) });`
* or more simply:
* `{|freq| SinOsc.ar(freq)}`
* or even just:
* `|freq| SinOsc.ar(freq)`
*/
static fromSource(source: string, args: SynthParams = {}): Synth {
return new Synth({ def: SynthDef.fromSource(source), args });
}
/**
* Make a Synth that will play the SynthDef compiled from an *.scd source code file
*/
static fromFile(path: string, args: SynthParams = {}): Synth {
return new Synth({ def: SynthDef.fromFile(path), args });
}
/**
* If there is no SCServer in the parent context,
* then this will wrap itself in an SCServer
*/
requireParent(): string {
return "SCServer";
}
prepareForAdd(): Command {
return {
updateContext: context => ({
nodeID: context.scserver.state.nextNodeID(),
}),
};
}
// synthDefName(context:object) : string {
// // The parent SCSynthDef publishes both .synthDef (object) and .synthDefName to context
// let name = _.isString(this.properties.def) ? this.properties.def : (context.synthDef && context.synthDef.name);
// if (!name) {
// throw new Error('No synthDefName supplied to Synth', context);
// }
// return name;
// }
add(): Command {
const defName = def => (typeof def === "string" ? def : def.name);
return {
scserver: {
msg: (context: Context, properties: Properties) => {
const args = _.mapValues(properties.args, (value, key) => this._checkOscType(value, key, context.id));
// if out is not set in args and out is in synthdef
// then set it from context
// TODO: check that synthDef has an arg named out
if (_.isUndefined(args.out) && !_.isUndefined(context.out)) {
args.out = context.out;
}
const dn = this._checkOscType(defName(properties.def), "def.name", context.id);
return synthNew(dn, context.nodeID, AddActions.TAIL, context.group, args);
},
},
run: (context: Context, properties: Properties): void | Promise<number> => {
return whenNodeGo(context.scserver, context.id, context.nodeID || -1).then(nodeID => {
// TODO: call a method instead so its testable
updateNodeState(context.scserver, nodeID, {
synthDef: defName(properties.def),
});
return nodeID;
});
},
};
}
remove(): Command {
return {
scserver: {
msg: (context: Context) => nodeFree(context.nodeID || -1),
},
run: (context: Context) => whenNodeEnd(context.scserver, context.id, context.nodeID || -1),
};
}
private _checkOscType(v: any, key: string, id: string): any {
switch (typeof v) {
case "number":
case "string":
// case 'Buffer':
return v;
default:
throw new Error(`Invalid OSC type for Synth ${key}: [${typeof v}: ${v}] @ ${id}`);
}
}
}
|
#!/usr/bin/python
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import re
import sys
if len(sys.argv) != 3:
print("Usage: publish_migration.py <publish.properties> <directory to write new files>")
exit(1)
filename = sys.argv[1]
new_base_dir = sys.argv[2]
def extract_artifact(line):
splitline = line.split('%')
org = re.sub(r'^revision\.[a-z_]+\.', '', splitline[0])
name = re.sub(r'=.*', '', splitline[1].rstrip())
return (org, name)
with open(filename) as f:
content = f.readlines()
for line in content:
# For each line get the org and name, make a directory with these
# and open the publish file.
artifact = extract_artifact(line)
(org, name) = artifact
publish_dir = os.path.join(new_base_dir, org, name)
if not os.path.exists(publish_dir):
os.makedirs(publish_dir)
with open(os.path.join(publish_dir, 'publish.properties'), 'a') as output:
output.write(line)
|
// Copyright 2014 Reece Heineke<[email protected]>
#include <algorithm>
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
#include "iem/logger.hpp"
#include "iem/orderbook.hpp"
#include "iem/session.hpp"
using LoginCreds = std::pair<std::string, std::string>;
LoginCreds _read_login_credentials(char const* filename = "conf/login.json") {
// Open file in binary mode
Json::Value root;
std::ifstream config_doc(filename, std::ifstream::binary);
config_doc >> root;
// Read username and password
const auto username = root.get("username", "").asString();
const auto password = root.get("password", "").asString();
// Return as pair
return {username, password};
}
LoginCreds read_login_credentials(int argc, char* argv[]) {
return (argc == 2) ?
_read_login_credentials(argv[1]) : _read_login_credentials();
}
int _main(int argc, char* argv[]) {
using std::chrono::duration_cast;
using std::chrono::high_resolution_clock;
const auto login = read_login_credentials(argc, argv);
iem::Session session(login.first, login.second);
std::cout << "Logging in...\n";
session.authenticate();
// Print session after authentication
iem::Logger logger;
iem::snprintf_session(logger.getBuffer(), session);
logger.log();
// FedPolicyB market
const iem::Market mkt("FedPolicyB");
const auto obs = session.orderbook(mkt);
for (const auto& ob : obs) {
std::cout << ob << '\n';
}
// Send a test bid order
const iem::Contract c(mkt.name(), "FRsame1216");
// const iem::Price bid_px(0);
// const iem::PriceTimeLimit bid_ptl(bid_px, boost::posix_time::not_a_date_time);
// const iem::Single bid_o(c, iem::Side::BUY, 1, bid_ptl);
// const auto response = session.place_order(bid_o);
// std::cout << body(response) << '\n';
// Send a test ask order
// const iem::Price ask_px(1000);
// const iem::PriceTimeLimit ask_ptl(ask_px, boost::posix_time::not_a_date_time);
// const iem::Single ask_o(c, iem::Side::SELL, 1, ask_ptl);
// const auto ask_response = session.place_order(ask_o);
// For each side
std::cout << "Requesting outstanding orders\n";
const std::vector<iem::Side> sides{iem::Side::BUY, iem::Side::SELL};
for (const auto& side : sides) {
// Request side outstanding orders
const auto oos = session.outstanding_orders(c, side);
for (const auto& oo : oos) {
std::cout << oo << '\n';
}
// Cancel most recent bid order
// const auto cxl_o = oos[oos.size() - 1];
// std::cout << cxl_o << '\n';
// const auto cxl_response = session.cancel_order(cxl_o);
}
// Send a test bundle order
const iem::ContractBundle cb(mkt.name(),
iem::MonthYear(boost::gregorian::Dec, 16));
const iem::Bundle b(cb, iem::Side::BUY, 1, iem::Counterparty::EXCHANGE);
const auto bundle_response = session.place_order(b);
std::cout << body(bundle_response) << '\n';
// Request trade messages
const auto msgs = session.messages(mkt);
for (const auto& msg : msgs) {
std::cout << msg << '\n';
}
// Request holdings
const auto holdings_response = session.holdings(c);
// Request portfolio
std::cout << "Requesting portfolio messages\n";
const auto portfolio_trader_messages = session.portfolio(mkt);
for (const auto& msg : msgs) {
std::cout << msg << '\n';
}
// TODO(rheineke): Generate a heartbeat thread with a mutex around cookie
// Make simple request every n minutes and call authenticate(...) with
// forceLogin=True if request fails. Update mutexed cookie if necessary
// std::thread hb(&heartbeat, session);
// hb.detach();
// Logout
std::cout << "Logging out...\n";
session.logout();
const auto return_value = EXIT_SUCCESS;
// std::cout << "Starting trade" << '\n';
return return_value;
}
int _main2(int argc, char* argv[]) {
const auto login = read_login_credentials(argc, argv);
auto session_p = new iem::Session(login.first, login.second);
std::cout << "Logging in...\n";
// session.authenticate();
std::thread t(&iem::Session::authenticate, std::ref(session_p));
t.join(); // Race condition without join?
// Print session after authentication
iem::Logger logger;
iem::snprintf_session(logger.getBuffer(), *session_p);
logger.log();
// Find all active markets and retrieve their markets concurrently
const iem::Market mkt("FedPolicyB");
// std::thread t(&iem::Session::orderbook, session, mkt);
//
// const std::vector<iem::Market> markets = {
// iem::Market("FedPolicyB"),
// iem::Market("Congress18"),
// iem::Market("House18"),
// iem::Market("Senate18"),
// };
const auto obs = session_p->orderbook(mkt);
for (const auto& ob : obs) {
std::cout << ob << '\n';
}
// Logout after logging in
std::cout << session_p->cookie() << std::endl;
std::cout << "Logging out..." << std::endl;
const auto snd_logout_response = session_p->logout();
std::cout << status(snd_logout_response) << '\n';
std::cout << body(snd_logout_response) << '\n';
return EXIT_SUCCESS;
}
int main(int argc, char* argv[]) {
return _main2(argc, argv);
// iem::Market mkt("FedPolicyB");
// std::cout << mkt.value() << std::endl;
}
|
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: commands.py
"""Execute shell commands via os.popen() and return status, output.
Interface summary:
import commands
outtext = commands.getoutput(cmd)
(exitstatus, outtext) = commands.getstatusoutput(cmd)
outtext = commands.getstatus(file) # returns output of "ls -ld file"
A trailing newline is removed from the output string.
Encapsulates the basic operation:
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
[Note: it would be nice to add functions to interpret the exit status.]
"""
from warnings import warnpy3k
warnpy3k('the commands module has been removed in Python 3.0; use the subprocess module instead', stacklevel=2)
del warnpy3k
__all__ = [
'getstatusoutput', 'getoutput', 'getstatus']
def getstatus(file):
"""Return output of "ls -ld <file>" in a string."""
import warnings
warnings.warn('commands.getstatus() is deprecated', DeprecationWarning, 2)
return getoutput('ls -ld' + mkarg(file))
def getoutput(cmd):
"""Return output (stdout or stderr) of executing cmd in a shell."""
return getstatusoutput(cmd)[1]
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
import os
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is None:
sts = 0
if text[-1:] == '\n':
text = text[:-1]
return (
sts, text)
def mk2arg(head, x):
import os
return mkarg(os.path.join(head, x))
def mkarg(x):
if "'" not in x:
return " '" + x + "'"
s = ' "'
for c in x:
if c in '\\$"`':
s = s + '\\'
s = s + c
s = s + '"'
return s
|
"""
Copyright (C) 2016 Quinn D Granfor <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
"""
def db_music_video_list_count(self, search_value=None):
"""
Music video count
"""
if search_value is not None:
self.db_cursor.execute('select count(*)'
' from mm_metadata_music_video, mm_media'
' where mm_media_metadata_guid = mm_metadata_music_video_guid group'
' and mm_media_music_video_song %% %s', (search_value,))
else:
self.db_cursor.execute('select count(*)'
' from mm_metadata_music_video, mm_media'
' where mm_media_metadata_guid = mm_metadata_music_video_guid')
return self.db_cursor.fetchone()[0]
def db_music_video_list(self, offset=0, per_page=None, search_value=None):
"""
music video list
"""
pass
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("PokerLeagueManager.Events.WebApi")]
[assembly: AssemblyProduct("PokerLeagueManager.Events.WebApi")]
[assembly: CLSCompliant(true)]
[assembly: Guid("4906410b-06cf-4004-950a-66970c478b8c")]
|
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
// Copyright (c) 2020 Upendo Ventures, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
namespace Hotcakes.Commerce.Globalization
{
public class GlobalizationService : HccServiceBase
{
public GlobalizationService(HccRequestContext context)
: base(context)
{
Countries = Factory.CreateRepo<CountryRepository>(Context);
Regions = Factory.CreateRepo<RegionRepository>(Context);
}
public CountryRepository Countries { get; protected set; }
public RegionRepository Regions { get; protected set; }
}
}
|
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _ASM_X86_BARRIER_H
#define _ASM_X86_BARRIER_H
#include <asm/alternative.h>
#include <asm/nops.h>
/*
* Force strict CPU ordering.
* And yes, this might be required on UP too when we're talking
* to devices.
*/
#ifdef CONFIG_X86_32
#define mb() asm volatile(ALTERNATIVE("lock; addl $0,0(%%esp)", "mfence", \
X86_FEATURE_XMM2) ::: "memory", "cc")
#define rmb() asm volatile(ALTERNATIVE("lock; addl $0,0(%%esp)", "lfence", \
X86_FEATURE_XMM2) ::: "memory", "cc")
#define wmb() asm volatile(ALTERNATIVE("lock; addl $0,0(%%esp)", "sfence", \
X86_FEATURE_XMM2) ::: "memory", "cc")
#else
#define mb() asm volatile("mfence":::"memory")
#define rmb() asm volatile("lfence":::"memory")
#define wmb() asm volatile("sfence" ::: "memory")
#endif
#ifdef CONFIG_X86_PPRO_FENCE
#define dma_rmb() rmb()
#else
#define dma_rmb() barrier()
#endif
#define dma_wmb() barrier()
#define __smp_mb() mb()
#define __smp_rmb() dma_rmb()
#define __smp_wmb() barrier()
#define __smp_store_mb(var, value) do { (void)xchg(&var, value); } while (0)
#if defined(CONFIG_X86_PPRO_FENCE)
/*
* For this option x86 doesn't have a strong TSO memory
* model and we should fall back to full barriers.
*/
#define __smp_store_release(p, v) \
do { \
compiletime_assert_atomic_type(*p); \
__smp_mb(); \
WRITE_ONCE(*p, v); \
} while (0)
#define __smp_load_acquire(p) \
({ \
typeof(*p) ___p1 = READ_ONCE(*p); \
compiletime_assert_atomic_type(*p); \
__smp_mb(); \
___p1; \
})
#else /* regular x86 TSO memory ordering */
#define __smp_store_release(p, v) \
do { \
compiletime_assert_atomic_type(*p); \
barrier(); \
WRITE_ONCE(*p, v); \
} while (0)
#define __smp_load_acquire(p) \
({ \
typeof(*p) ___p1 = READ_ONCE(*p); \
compiletime_assert_atomic_type(*p); \
barrier(); \
___p1; \
})
#endif
/* Atomic operations are already serializing on x86 */
#define __smp_mb__before_atomic() barrier()
#define __smp_mb__after_atomic() barrier()
#include <asm-generic/barrier.h>
#endif /* _ASM_X86_BARRIER_H */
|
# Copyright (c) 2014 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from murano.tests.unit.dsl.foundation import object_model as om
from murano.tests.unit.dsl.foundation import test_case
class TestMultipleInheritance(test_case.DslTestCase):
def setUp(self):
super(TestMultipleInheritance, self).setUp()
self._multi_derived = om.Object(
'DerivedFrom2Classes',
rootProperty='ROOT')
model = om.Object(
'SampleClass3',
multiClassProperty=self._multi_derived
)
self._runner = self.new_runner(model)
def test_multi_class_contract(self):
self._runner.testMultiContract()
self.assertEqual(
['ParentClass1::method1', 'ParentClass2::method2'],
self.traces)
def test_root_method_resolution(self):
self._runner.on(self._multi_derived).testRootMethod()
self.assertEqual(
['CommonParent::testRootMethod', 'ROOT'],
self.traces)
def test_property_accessible_on_several_paths(self):
self.assertEqual(
'ROOT',
self._runner.testPropertyAccessibleOnSeveralPaths())
def test_specialized_mixin_override(self):
self._runner.on(self._multi_derived).testMixinOverride()
self.assertEqual(
['ParentClass2::virtualMethod', '-',
'CommonParent::virtualMethod', '-',
'CommonParent::virtualMethod', '-',
'ParentClass2::virtualMethod'],
self.traces)
|
Date: Tue, 26 Nov 1996 22:55:37 GMT
Server: NCSA/1.5
Content-type: text/html
<!DOCTYPE htmlplus PUBLIC "-//Internet/RFC xxxx//EN">
<htmplus forms=off>
<HEAD>
<LINK HREF="mailto:[email protected]" made>
<TITLE>Keele, Computer Science - Home Page</TITLE>
</HEAD>
<BODY>
<H1>
<!WA0><img src="http://www.keele.ac.uk/gallery/logos/ku.gif" alt = "Keele University">
Department of Computer Science
</H1>
<hr>
<table>
<tr>
<td>Address:</td>
<td>Department of Computer Science,</td>
</tr>
<tr>
<td></td>
<td>Keele,</td>
</tr>
<tr>
<td></td>
<td>Staffordshire UK ST5 5BG</td>
</tr>
<tr>
</tr>
<tr>
<td>Phone:</td>
<td>(01782) 583075</td>
</tr>
<tr>
</tr>
<tr>
<td>Fax:</td>
<td>(01782) 713082</td>
</tr>
</table>
<hr>
<dl>
<dt><!WA1><A HREF = "http://www.keele.ac.uk/depts/cs/General/toplevel.html"><b>General Information</b></A> -
about the Department<P>
<dt><!WA2><A HREF = "http://www.keele.ac.uk/depts/cs/Courses/toplevel.html"><b>Course Information</b></A> -
undergraduate, postgraduate and other courses<P>
<dt><!WA3><A HREF = "http://www.keele.ac.uk/depts/cs/Announcements/toplevel.html"><b>Announcements</b></A> -
conferences, short courses, seminars, demonstrating jobs.
</dl>
<hr>
<p>
<dl>
<dt><!WA4><A HREF = "http://www.keele.ac.uk/depts/cs/Staff/toplevel.html"><b>People</b></A> - home pages of
staff and research students<P>
<dt><!WA5><A HREF = "http://www.keele.ac.uk/depts/cs/Research/toplevel.html"><b>Research</b></A> - current research activities<P>
<dt><!WA6><A HREF = "http://www.keele.ac.uk/depts/cs/Publications/toplevel.html"><b>Publications</b></A> -
includes books and technical reports
</dl>
<hr>
<dl>
<dt><!WA7><A HREF="http://www.keele.ac.uk/depts/cs/Guides/guides.html"><b>Introductory Student
Guides</b></A> - labs, UNIX and applications
</dl>
<hr>
<!WA8><a href = "http://www.keele.ac.uk/cwis.html"><!WA9><img hspace = "5" alt = ""
src = "http://www.keele.ac.uk/Images/gohome.gif">Keele CWIS Home Page</a>
<hr>
<ADDRESS>
Geoff Hamilton - <!WA10><A HREF = "mailto:[email protected]">[email protected]</a>
</ADDRESS>
</BODY>
|
from pandac.PandaModules import *
from direct.directnotify import DirectNotifyGlobal
from direct.showbase import AppRunnerGlobal
import os
class BattleSounds:
notify = DirectNotifyGlobal.directNotify.newCategory('BattleSounds')
def __init__(self):
self.mgr = AudioManager.createAudioManager()
self.isValid = 0
if self.mgr != None and self.mgr.isValid():
self.isValid = 1
limit = base.config.GetInt('battle-sound-cache-size', 15)
self.mgr.setCacheLimit(limit)
base.addSfxManager(self.mgr)
self.setupSearchPath()
return
def setupSearchPath(self):
self.sfxSearchPath = DSearchPath()
self.sfxSearchPath.appendDirectory(Filename('../resources/phase_3/audio/sfx'))
self.sfxSearchPath.appendDirectory(Filename('../resources/phase_3.5/audio/sfx'))
self.sfxSearchPath.appendDirectory(Filename('../resources/phase_4/audio/sfx'))
self.sfxSearchPath.appendDirectory(Filename('../resources/phase_5/audio/sfx'))
self.sfxSearchPath.appendDirectory(Filename('/phase_3/audio/sfx'))
self.sfxSearchPath.appendDirectory(Filename('/phase_3.5/audio/sfx'))
self.sfxSearchPath.appendDirectory(Filename('/phase_4/audio/sfx'))
self.sfxSearchPath.appendDirectory(Filename('/phase_5/audio/sfx'))
def clear(self):
if self.isValid:
self.mgr.clearCache()
def getSound(self, name):
if self.isValid:
filename = Filename(name)
found = vfs.resolveFilename(filename, self.sfxSearchPath)
if not found:
self.setupSearchPath()
found = vfs.resolveFilename(filename, self.sfxSearchPath)
if not found:
self.notify.warning('%s not found on:' % name)
print self.sfxSearchPath
else:
return self.mgr.getSound(filename.getFullpath())
return self.mgr.getNullSound()
globalBattleSoundCache = BattleSounds()
|
/* GNU Objective C Runtime class related functions
Copyright (C) 1993, 1995, 1996 Free Software Foundation, Inc.
Contributed by Kresten Krab Thorup
This file is part of GNU CC.
GNU CC is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 2, or (at your option) any later version.
GNU CC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
GNU CC; see the file COPYING. If not, write to the Free Software
Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
/* As a special exception, if you link this library with files compiled with
GCC to produce an executable, this does not cause the resulting executable
to be covered by the GNU General Public License. This exception does not
however invalidate any other reasons why the executable file might be
covered by the GNU General Public License. */
#include "tconfig.h" /* include defs of bzero for target */
#include "objc.h"
#include "runtime.h" /* the kitchen sink */
#if OBJC_WITH_GC
# include <gc.h>
#endif
id __objc_object_alloc (Class);
id __objc_object_dispose (id);
id __objc_object_copy (id);
id (*_objc_object_alloc) (Class) = __objc_object_alloc; /* !T:SINGLE */
id (*_objc_object_dispose) (id) = __objc_object_dispose; /* !T:SINGLE */
id (*_objc_object_copy) (id) = __objc_object_copy; /* !T:SINGLE */
id
class_create_instance (Class class)
{
id new = nil;
#if OBJC_WITH_GC
if (CLS_ISCLASS (class))
new = (id) GC_malloc_explicitly_typed (class->instance_size,
class->gc_object_type);
#else
if (CLS_ISCLASS (class))
new = (*_objc_object_alloc) (class);
#endif
if (new != nil)
{
memset (new, 0, class->instance_size);
new->class_pointer = class;
}
return new;
}
id
object_copy (id object)
{
if ((object != nil) && CLS_ISCLASS (object->class_pointer))
return (*_objc_object_copy) (object);
else
return nil;
}
id
object_dispose (id object)
{
if ((object != nil) && CLS_ISCLASS (object->class_pointer))
{
if (_objc_object_dispose)
(*_objc_object_dispose) (object);
else
objc_free (object);
}
return nil;
}
id __objc_object_alloc (Class class)
{
return (id) objc_malloc (class->instance_size);
}
id __objc_object_dispose (id object)
{
objc_free (object);
return 0;
}
id __objc_object_copy (id object)
{
id copy = class_create_instance (object->class_pointer);
memcpy (copy, object, object->class_pointer->instance_size);
return copy;
}
|
(function() {
var EOL, gutil, path, through;
path = require('path');
gutil = require('gulp-util');
through = require('through2');
EOL = '\n';
module.exports = function(opt) {
if (opt == null) {
opt = {};
}
return through.obj(function(file, enc, next) {
var trace;
if (file.isNull()) {
return this.emit('error', new gutil.PluginError('gulp-trace', 'File can\'t be null'));
}
if (file.isStream()) {
return this.emit('error', new gutil.PluginError('gulp-trace', 'Streams not supported'));
}
if (path.extname(file.path) === '.html') {
trace = '<!-- trace:' + path.relative(process.cwd(), file.path) + ' -->' + EOL;
} else if (path.extname(file.path) === '.coffee') {
trace = '### trace:' + path.relative(process.cwd(), file.path) + ' ###' + EOL;
} else {
trace = '/* trace:' + path.relative(process.cwd(), file.path) + ' */' + EOL;
}
file.contents = new Buffer(trace + file.contents.toString());
this.push(file);
return next();
});
};
}).call(this);
|
//= require ./src/module
//= require_tree ./src/services
//= require_tree ./src/controllers
//= require_tree ./src/directives
|
"""
Command to get statistics about open ended problems.
"""
import csv
import time
from django.core.management.base import BaseCommand
from optparse import make_option
from xmodule.modulestore import Location
from xmodule.modulestore.django import modulestore
from xmodule.open_ended_grading_classes.openendedchild import OpenEndedChild
from courseware.courses import get_course
from courseware.models import StudentModule
from student.models import anonymous_id_for_user, CourseEnrollment
from instructor.utils import get_module_for_student
class Command(BaseCommand):
"""
Command to get statistics about open ended problems.
"""
help = "Usage: openended_stats <course_id> <problem_location> --task-number=<task_number>\n"
option_list = BaseCommand.option_list + (
make_option('--task-number',
type='int', default=0,
help="Task number to get statistics about."),
)
def handle(self, *args, **options):
"""Handler for command."""
task_number = options['task_number']
if len(args) == 2:
course_id = args[0]
location = args[1]
else:
print self.help
return
try:
course = get_course(course_id)
except ValueError as err:
print err
return
descriptor = modulestore().get_instance(course.id, location, depth=0)
if descriptor is None:
print "Location {0} not found in course".format(location)
return
try:
enrolled_students = CourseEnrollment.users_enrolled_in(course_id)
print "Total students enrolled in {0}: {1}".format(course_id, enrolled_students.count())
calculate_task_statistics(enrolled_students, course, location, task_number)
except KeyboardInterrupt:
print "\nOperation Cancelled"
def calculate_task_statistics(students, course, location, task_number, write_to_file=True):
"""Print stats of students."""
stats = {
OpenEndedChild.INITIAL: 0,
OpenEndedChild.ASSESSING: 0,
OpenEndedChild.POST_ASSESSMENT: 0,
OpenEndedChild.DONE: 0
}
students_with_saved_answers = []
students_with_ungraded_submissions = [] # pylint: disable=invalid-name
students_with_graded_submissions = [] # pylint: disable=invalid-name
students_with_no_state = []
student_modules = StudentModule.objects.filter(module_state_key=location, student__in=students).order_by('student')
print "Total student modules: {0}".format(student_modules.count())
for index, student_module in enumerate(student_modules):
if index % 100 == 0:
print "--- {0} students processed ---".format(index)
student = student_module.student
print "{0}:{1}".format(student.id, student.username)
module = get_module_for_student(student, course, location)
if module is None:
print " WARNING: No state found"
students_with_no_state.append(student)
continue
latest_task = module.child_module.get_task_number(task_number)
if latest_task is None:
print " No task state found"
students_with_no_state.append(student)
continue
task_state = latest_task.child_state
stats[task_state] += 1
print " State: {0}".format(task_state)
if task_state == OpenEndedChild.INITIAL:
if latest_task.stored_answer is not None:
students_with_saved_answers.append(student)
elif task_state == OpenEndedChild.ASSESSING:
students_with_ungraded_submissions.append(student)
elif task_state == OpenEndedChild.POST_ASSESSMENT or task_state == OpenEndedChild.DONE:
students_with_graded_submissions.append(student)
location = Location(location)
print "----------------------------------"
print "Time: {0}".format(time.strftime("%Y %b %d %H:%M:%S +0000", time.gmtime()))
print "Course: {0}".format(course.id)
print "Location: {0}".format(location)
print "No state: {0}".format(len(students_with_no_state))
print "Initial State: {0}".format(stats[OpenEndedChild.INITIAL] - len(students_with_saved_answers))
print "Saved answers: {0}".format(len(students_with_saved_answers))
print "Submitted answers: {0}".format(stats[OpenEndedChild.ASSESSING])
print "Received grades: {0}".format(stats[OpenEndedChild.POST_ASSESSMENT] + stats[OpenEndedChild.DONE])
print "----------------------------------"
if write_to_file:
filename = "stats.{0}.{1}".format(location.course, location.name)
time_stamp = time.strftime("%Y%m%d-%H%M%S")
with open('{0}.{1}.csv'.format(filename, time_stamp), 'wb') as csv_file:
writer = csv.writer(csv_file, delimiter=' ', quoting=csv.QUOTE_MINIMAL)
for student in students_with_ungraded_submissions:
writer.writerow(("ungraded", student.id, anonymous_id_for_user(student, ''), student.username))
for student in students_with_graded_submissions:
writer.writerow(("graded", student.id, anonymous_id_for_user(student, ''), student.username))
return stats
|
from util import file_util
class CsvFile:
def __init__(self, path):
self.path = path
self.values = dict()
if file_util.file_exists(path):
with open(path, 'r') as file:
csv = file.read()
column_names = csv[:csv.find('\n')].split(',')
lines = csv[csv.find('\n') + 1:].splitlines()
for line in lines:
if line.strip() != '':
values = line.split(',')
row = dict()
row_key = values[0]
for i in range(1, len(column_names)):
row[column_names[i]] = values[i]
self.add_row(row_key, row)
def add_row(self, row_key, values):
if row_key not in self.values.keys():
self.values[row_key] = dict()
self.values[row_key].update(values)
def save(self):
column_names = set()
for row_key in self.values.keys():
row = self.values[row_key]
for key in row.keys():
column_names.add(key)
column_names = sorted(column_names)
csv = 'method_name'
for column_name in column_names:
csv += ',' + column_name
csv += '\n'
for row_key in self.values.keys():
row = self.values[row_key]
csv_row = row_key
for column_name in column_names:
if column_name in row:
csv_row += ',' + str(row[column_name])
else:
csv_row += ','
csv += csv_row + '\n'
with open(self.path, 'w') as file:
file.write(csv)
|
"""
Support for Nest Thermostat Binary Sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.nest/
"""
from itertools import chain
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import (
BinarySensorDevice, PLATFORM_SCHEMA)
from homeassistant.components.sensor.nest import NestSensor
from homeassistant.const import (CONF_SCAN_INTERVAL, CONF_MONITORED_CONDITIONS)
from homeassistant.components.nest import (
DATA_NEST, is_thermostat, is_camera)
import homeassistant.helpers.config_validation as cv
DEPENDENCIES = ['nest']
BINARY_TYPES = ['online']
CLIMATE_BINARY_TYPES = ['fan',
'is_using_emergency_heat',
'is_locked',
'has_leaf']
CAMERA_BINARY_TYPES = [
'motion_detected',
'sound_detected',
'person_detected']
_BINARY_TYPES_DEPRECATED = [
'hvac_ac_state',
'hvac_aux_heater_state',
'hvac_heater_state',
'hvac_heat_x2_state',
'hvac_heat_x3_state',
'hvac_alt_heat_state',
'hvac_alt_heat_x2_state',
'hvac_emer_heat_state']
_VALID_BINARY_SENSOR_TYPES = BINARY_TYPES + CLIMATE_BINARY_TYPES \
+ CAMERA_BINARY_TYPES
_VALID_BINARY_SENSOR_TYPES_WITH_DEPRECATED = _VALID_BINARY_SENSOR_TYPES \
+ _BINARY_TYPES_DEPRECATED
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_SCAN_INTERVAL):
vol.All(vol.Coerce(int), vol.Range(min=1)),
vol.Required(CONF_MONITORED_CONDITIONS):
vol.All(cv.ensure_list,
[vol.In(_VALID_BINARY_SENSOR_TYPES_WITH_DEPRECATED)])
})
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup Nest binary sensors."""
if discovery_info is None:
return
nest = hass.data[DATA_NEST]
conf = config.get(CONF_MONITORED_CONDITIONS, _VALID_BINARY_SENSOR_TYPES)
for variable in conf:
if variable in _BINARY_TYPES_DEPRECATED:
wstr = (variable + " is no a longer supported "
"monitored_conditions. See "
"https://home-assistant.io/components/binary_sensor.nest/ "
"for valid options, or remove monitored_conditions "
"entirely to get a reasonable default")
_LOGGER.error(wstr)
sensors = []
device_chain = chain(nest.devices(),
nest.protect_devices(),
nest.camera_devices())
for structure, device in device_chain:
sensors += [NestBinarySensor(structure, device, variable)
for variable in conf
if variable in BINARY_TYPES]
sensors += [NestBinarySensor(structure, device, variable)
for variable in conf
if variable in CLIMATE_BINARY_TYPES
and is_thermostat(device)]
if is_camera(device):
sensors += [NestBinarySensor(structure, device, variable)
for variable in conf
if variable in CAMERA_BINARY_TYPES]
for activity_zone in device.activity_zones:
sensors += [NestActivityZoneSensor(structure,
device,
activity_zone)]
add_devices(sensors, True)
class NestBinarySensor(NestSensor, BinarySensorDevice):
"""Represents a Nest binary sensor."""
@property
def is_on(self):
"""True if the binary sensor is on."""
return self._state
def update(self):
"""Retrieve latest state."""
self._state = bool(getattr(self.device, self.variable))
class NestActivityZoneSensor(NestBinarySensor):
"""Represents a Nest binary sensor for activity in a zone."""
def __init__(self, structure, device, zone):
"""Initialize the sensor."""
super(NestActivityZoneSensor, self).__init__(structure, device, None)
self.zone = zone
@property
def name(self):
"""Return the name of the nest, if any."""
return "{} {} activity".format(self._name, self.zone.name)
def update(self):
"""Retrieve latest state."""
self._state = self.device.has_ongoing_motion_in_zone(self.zone.zone_id)
|
<?php
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('REDDIT_NAME', 'eve_link_details');
define('REDDIT_PASSWORD', '');
?>
|
from chat.tests.common import *
from chat.views import privileged
from django.http import HttpResponse, HttpRequest
class DecoratorTests(TestCase):
@privileged
def privileged_view_mock(self, request, *args, **kwargs):
"""
Mock of a view that returns an HttpResponse
with status code 200(OK).
"""
return HttpResponse(status=200)
def get_request(self, password=None):
request = HttpRequest()
request.META = {}
request.META['HTTP_AUTHORIZATION'] = password
return request
def test_request_with_correct_password(self):
"""
When the password is correct the decorator should call
the function passed.
"""
request = self.get_request(password=settings.PASS)
response = self.privileged_view_mock(request)
self.assertEqual(response.status_code, 200)
def test_request_with_wrong_password(self):
"""
When the password is wrong the decorator should respond
with a 401(Unauthorized) status code.
"""
request = self.get_request(password='wrong')
response = self.privileged_view_mock(request)
self.assertEqual(response.status_code, 401)
def test_request_with_HTTP_AUTHORIZATION_not_defined(self):
"""
When the password is not defined the decorator should
respond with a 401(Unauthorized) status code.
"""
request = self.get_request()
response = self.privileged_view_mock(request)
self.assertEqual(response.status_code, 401)
|
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
from iptest.assert_util import *
add_clr_assemblies("loadorder_2")
# namespace First {
# public class Nongeneric1 {
# public static string Flag = typeof(Nongeneric1).FullName;
# }
# }
import First
add_clr_assemblies("loadorder_2b")
# // non-generic type, which has different namespace, different name from First.Nongeneric1
# namespace Second {
# public class Nongeneric2 {
# public static string Flag = typeof(Nongeneric2).FullName;
# }
# }
import Second
AreEqual(First.Nongeneric1.Flag, "First.Nongeneric1")
AreEqual(Second.Nongeneric2.Flag, "Second.Nongeneric2")
# AttributeError for them
AssertError(AttributeError, lambda: First.Nongeneric2)
AssertError(AttributeError, lambda: Second.Nongeneric1)
from First import *
AreEqual(Nongeneric1.Flag, "First.Nongeneric1")
from Second import *
AreEqual(Nongeneric1.Flag, "First.Nongeneric1")
AreEqual(Nongeneric2.Flag, "Second.Nongeneric2")
from First import *
AreEqual(Nongeneric1.Flag, "First.Nongeneric1")
AreEqual(Nongeneric2.Flag, "Second.Nongeneric2")
|
#!/usr/bin/env python
"""
Example application views.
Note that `render_template` is wrapped with `make_response` in all application
routes. While not necessary for most Flask apps, it is required in the
App Template for static publishing.
"""
import app_config
import json
import oauth
import static
from flask import Flask, make_response, render_template
from render_utils import make_context, smarty_filter, urlencode_filter
from werkzeug.debug import DebuggedApplication
app = Flask(__name__)
app.debug = app_config.DEBUG
app.add_template_filter(smarty_filter, name='smarty')
app.add_template_filter(urlencode_filter, name='urlencode')
@app.route('/')
@oauth.oauth_required
def index():
"""
Example view demonstrating rendering a simple HTML page.
"""
context = make_context()
with open('data/featured.json') as f:
context['featured'] = json.load(f)
return make_response(render_template('index.html', **context))
app.register_blueprint(static.static)
app.register_blueprint(oauth.oauth)
# Enable Werkzeug debug pages
if app_config.DEBUG:
wsgi_app = DebuggedApplication(app, evalex=False)
else:
wsgi_app = app
# Catch attempts to run the app directly
if __name__ == '__main__':
print 'This command has been removed! Please run "fab app" instead!'
|
<?php
/*
* This file is part of the CheckToolsFramework package.
*
* Copyright (C) 2015-2016 Guillaume Kulakowski <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Llaumgui\CheckToolsFramework\CheckTool;
use Tests\Llaumgui\CheckToolsFramework\PhpUnitHelper;
use Llaumgui\CheckToolsFramework\CheckTool\YamlCheckTool;
use Symfony\Component\Finder\Finder;
class YamlheckToolTest extends PhpUnitHelper
{
/**
* Check if YAML is valide
*/
public function testDoCheck()
{
// Load CheckTool
$config = $this->yamlLoader('check_tools_framework.yml');
$yamlCheckTool = new YamlCheckTool($config['check_tools_framework']['check_tools']['yaml']);
// Get testing files
$finder = new Finder();
$finder->files()
->in(PATH_TESING_FILES)
->name('/\.yml/')
->depth(0);
$count = 0;
foreach ($finder as $file) {
$check = $yamlCheckTool->doCheck($file);
if (strpos($file->getFileName(), "yaml_ko") !== false
|| strpos($file->getFileName(), "encoding_ko") !== false) {
$this->assertFalse($check->getResult());
$count++;
} else {
$this->assertTrue($check->getResult());
$count++;
}
$this->assertInstanceOf('Llaumgui\CheckToolsFramework\CheckTool\CheckToolTest', $check);
}
$this->assertTrue($count>=2);
}
}
|
using System;
using Server;
namespace Server.Items
{
public class BoneCrusher : WarMace
{
public override int LabelNumber { get { return 1061596; } } // Bone Crusher
public override int ArtifactRarity { get { return 11; } }
public override int InitMinHits { get { return 255; } }
public override int InitMaxHits { get { return 255; } }
[Constructable]
public BoneCrusher()
{
ItemID = 0x1406;
Hue = 0x60C;
WeaponAttributes.HitLowerDefend = 50;
Attributes.BonusStr = 10;
Attributes.WeaponDamage = 75;
}
public BoneCrusher( Serial serial )
: base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
/*int version = */
reader.ReadInt();
if ( Hue == 0x604 )
{
Hue = 0x60C;
}
if ( ItemID == 0x1407 )
{
ItemID = 0x1406;
}
}
}
}
|
/**
* 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 com.huawei.streaming.window;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.huawei.streaming.event.IEvent;
import com.huawei.streaming.event.IEventType;
import com.huawei.streaming.event.TupleEvent;
import com.huawei.streaming.support.SupportConst;
import com.huawei.streaming.support.SupportEventMng;
import com.huawei.streaming.view.IDataCollection;
/**
* <WindowRelativeAccessTest>
* <功能详细描述>
*
*/
public class WindowRelativeAccessTest
{
private WindowRelativeAccess access;
private RelativeAccessByEventAndIndexService service = new RelativeAccessByEventAndIndexService();
private SupportEventMng mng = new SupportEventMng();;
private IEventType eventType = mng.getInput();
/**
* Test WindowRelativeAccess(RelativeAccessByEventAndIndexService).
*/
@Test
public void testWindowRelativeAccess()
{
try
{
access = new WindowRelativeAccess(null);
fail();
}
catch (IllegalArgumentException e)
{
Assert.assertTrue(true);
}
}
/**
* Test getEvent(IEvent, int).
*/
@Test
public void testGetEvent()
{
access = new WindowRelativeAccess(service);
Map<String, Object> values = new HashMap<String, Object>();
values.put("a", 0);
values.put("b", 0);
values.put("c", "c0");
IEvent event0 = new TupleEvent("stream", eventType, values);
values.put("a", 1);
values.put("b", 1);
values.put("c", "c1");
IEvent event1 = new TupleEvent("stream", eventType, values);
values.put("a", SupportConst.I_TWO);
values.put("b", SupportConst.I_TWO);
values.put("c", "c2");
IEvent event2 = new TupleEvent("stream", eventType, values);
values.put("a", SupportConst.I_THREE);
values.put("b", SupportConst.I_THREE);
values.put("c", "c3");
IEvent event3 = new TupleEvent("stream", eventType, values);
values.put("a", SupportConst.I_FOUR);
values.put("b", SupportConst.I_FOUR);
values.put("c", "c4");
IEvent event4 = new TupleEvent("stream", eventType, values);
values.put("a", SupportConst.I_FIVE);
values.put("b", SupportConst.I_FIVE);
values.put("c", "c5");
IEvent event5 = new TupleEvent("stream", eventType, values);
access.update(new IEvent[] {event0}, null);
assertEquals(event0, access.getEvent(event0, SupportConst.I_ZERO));
assertNull(access.getEvent(event0, SupportConst.I_ONE));
// sends the newest event last (i.e. 1 older 2 as 1 is sent first)
access.update(new IEvent[] {event1, event2}, null);
assertEquals(event1, access.getEvent(event1, SupportConst.I_ZERO));
assertNull(access.getEvent(event1, SupportConst.I_ONE));
assertEquals(event2, access.getEvent(event2, SupportConst.I_ZERO));
assertEquals(event1, access.getEvent(event2, SupportConst.I_ONE));
assertNull(access.getEvent(event2, SupportConst.I_TWO));
// sends the newest event last (i.e. 1 older 2 as 1 is sent first)
access.update(new IEvent[] {event3, event4, event5}, null);
assertEquals(event3, access.getEvent(event3, SupportConst.I_ZERO));
assertNull(access.getEvent(event3, SupportConst.I_ONE));
assertEquals(event4, access.getEvent(event4, SupportConst.I_ZERO));
assertEquals(event3, access.getEvent(event4, SupportConst.I_ONE));
assertNull(access.getEvent(event4, SupportConst.I_TWO));
assertEquals(event5, access.getEvent(event5, SupportConst.I_ZERO));
assertEquals(event4, access.getEvent(event5, SupportConst.I_ONE));
assertEquals(event3, access.getEvent(event5, SupportConst.I_TWO));
assertNull(access.getEvent(event5, SupportConst.I_THREE));
}
/**
* Test renew().
*/
@Test
public void testRenew()
{
access = new WindowRelativeAccess(service);
IDataCollection renew = access.renew();
Assert.assertEquals(true, renew instanceof WindowRelativeAccess);
}
}
|
##########################################################################
#
# Copyright (c) 2020, Don Boogert. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of Don Boogert nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import GafferUI
import GafferVDB
GafferUI.Metadata.registerNode(
GafferVDB.SphereLevelSet,
'description',
"""Creates a sphere level set.""",
plugs={
'grid' : [
'description',
"""
The name of the sphere levelset grid in the created VDB object.
"""
],
"radius" : [
"description",
"""
Sphere radius in object space units.
"""
],
"center" : [
"description",
"""
Local center of the sphere level set in object space.
"""
],
"voxelSize" : [
"description",
"""
Size of the voxels in the created sphere levelset. Smaller voxel results in more detail but higher memory usage.
"""
],
"halfWidth" : [
"description",
"""
Width of the signed distance field in voxels.
"""
],
}
)
|
#
# 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.
"""This module is deprecated. Please use `airflow.providers.google.cloud.operators.dataflow`."""
import warnings
from airflow.providers.google.cloud.operators.dataflow import (
DataflowCreateJavaJobOperator, DataflowCreatePythonJobOperator, DataflowTemplatedJobStartOperator,
)
warnings.warn(
"This module is deprecated. Please use `airflow.providers.google.cloud.operators.dataflow`.",
DeprecationWarning, stacklevel=2
)
class DataFlowJavaOperator(DataflowCreateJavaJobOperator):
"""
This class is deprecated.
Please use `airflow.providers.google.cloud.operators.dataflow.DataflowCreateJavaJobOperator`.
"""
def __init__(self, *args, **kwargs):
warnings.warn(
"""This class is deprecated.
Please use `airflow.providers.google.cloud.operators.dataflow.DataflowCreateJavaJobOperator`.""",
DeprecationWarning, stacklevel=2
)
super().__init__(*args, **kwargs)
class DataFlowPythonOperator(DataflowCreatePythonJobOperator):
"""
This class is deprecated.
Please use `airflow.providers.google.cloud.operators.dataflow.DataflowCreatePythonJobOperator`.
"""
def __init__(self, *args, **kwargs):
warnings.warn(
"""This class is deprecated.
Please use
`airflow.providers.google.cloud.operators.dataflow.DataflowCreatePythonJobOperator`.""",
DeprecationWarning, stacklevel=2
)
super().__init__(*args, **kwargs)
class DataflowTemplateOperator(DataflowTemplatedJobStartOperator):
"""
This class is deprecated.
Please use `airflow.providers.google.cloud.operators.dataflow.DataflowTemplatedJobStartOperator`.
"""
def __init__(self, *args, **kwargs):
warnings.warn(
"""This class is deprecated.
Please use
`airflow.providers.google.cloud.operators.dataflow.DataflowTemplatedJobStartOperator`.""",
DeprecationWarning, stacklevel=2
)
super().__init__(*args, **kwargs)
|
# Generated by Django 2.2.13 on 2020-08-25 11:38
import django.contrib.postgres.fields.jsonb
import django.db.models.deletion
import django.utils.timezone
import django_fsm
import model_utils.fields
from django.db import migrations, models
import waldur_core.core.fields
import waldur_core.core.models
import waldur_core.core.shims
import waldur_core.core.validators
import waldur_core.structure.models
class Migration(migrations.Migration):
dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('structure', '0012_customer_sponsor_number'),
('waldur_rancher', '0029_application'),
]
operations = [
migrations.CreateModel(
name='Ingress',
fields=[
(
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name='ID',
),
),
(
'created',
model_utils.fields.AutoCreatedField(
default=django.utils.timezone.now,
editable=False,
verbose_name='created',
),
),
(
'modified',
model_utils.fields.AutoLastModifiedField(
default=django.utils.timezone.now,
editable=False,
verbose_name='modified',
),
),
(
'description',
models.CharField(
blank=True, max_length=500, verbose_name='description'
),
),
(
'name',
models.CharField(
max_length=150,
validators=[waldur_core.core.validators.validate_name],
verbose_name='name',
),
),
('uuid', waldur_core.core.fields.UUIDField()),
('error_message', models.TextField(blank=True)),
(
'runtime_state',
models.CharField(
blank=True, max_length=150, verbose_name='runtime state'
),
),
(
'state',
django_fsm.FSMIntegerField(
choices=[
(5, 'Creation Scheduled'),
(6, 'Creating'),
(1, 'Update Scheduled'),
(2, 'Updating'),
(7, 'Deletion Scheduled'),
(8, 'Deleting'),
(3, 'OK'),
(4, 'Erred'),
],
default=5,
),
),
('backend_id', models.CharField(blank=True, max_length=255)),
(
'rules',
django.contrib.postgres.fields.jsonb.JSONField(
blank=True, default=list
),
),
(
'cluster',
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to='waldur_rancher.Cluster',
),
),
(
'namespace',
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to='waldur_rancher.Namespace',
),
),
(
'rancher_project',
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to='waldur_rancher.Project',
),
),
(
'service_project_link',
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name='+',
to='waldur_rancher.RancherServiceProjectLink',
),
),
(
'settings',
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name='+',
to='structure.ServiceSettings',
),
),
(
'tags',
waldur_core.core.shims.TaggableManager(
blank=True,
help_text='A comma-separated list of tags.',
related_name='ingress_ingress_waldur_rancher',
through='taggit.TaggedItem',
to='taggit.Tag',
verbose_name='Tags',
),
),
],
options={'abstract': False,},
bases=(
waldur_core.core.models.DescendantMixin,
waldur_core.core.models.BackendModelMixin,
waldur_core.structure.models.StructureLoggableMixin,
models.Model,
),
),
]
|
# -*- coding: utf-8 -*-
from django.forms import ModelForm
from django.core.exceptions import ValidationError
from django import forms
import datetime
from apps.registro.models import ExtensionAulicaMatricula
YEARS_CHOICES = [('', 'Seleccione...')] + [(int(n), str(n)) for n in range(1980, datetime.datetime.now().year + 1)]
class ExtensionAulicaMatriculaForm(forms.ModelForm):
anio = forms.ChoiceField(choices=YEARS_CHOICES)
class Meta:
model = ExtensionAulicaMatricula
exclude = ('extension_aulica',)
def __init__(self, *args, **kwargs):
self.extension_aulica = kwargs.pop('extension_aulica')
super(ExtensionAulicaMatriculaForm, self).__init__(*args, **kwargs)
def clean_anio(self):
anio = self.cleaned_data['anio']
try:
matricula_existente = ExtensionAulicaMatricula.objects.get(extension_aulica=self.extension_aulica, anio=anio)
except ExtensionAulicaMatricula.DoesNotExist:
matricula_existente = None
" Si ya hay una matrícula en ese año "
if matricula_existente and matricula_existente != self.instance:
msg = "La matrícula del año %s ya se ha definido." % (str(anio))
raise ValidationError(msg)
return anio
|
from django.conf.urls.defaults import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.views.generic import TemplateView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$',
view='main.views.home',
kwargs={'template': 'home.html'},
name='home'
),
url(r'^hackathon/',
TemplateView.as_view(template_name='hackathon.html'),
name='hackathon'
),
url(r'^pokemon/',
TemplateView.as_view(template_name='pokemon.html'),
name='pokemon'
),
url(r'^freshers/',
TemplateView.as_view(template_name='freshers.html'),
name='freshers'
),
(r'^library/', include('library.urls', namespace='library', app_name='library')),
(r'^events/', include('events.urls', namespace='events', app_name='events')),
url(r'^event/(?P<slug>[-\w]+)/$',
view='events.views.event',
kwargs={'template':'event.html'},
name='event_clean'
),
url(r'^library/book/(?P<id>[-\w]+)/$',
view='library.views.book',
kwargs={'template':'book.html'},
name='book_clean'
),
url(r'^library/book/(?P<id>[-\w]+)/reserve$',
view='library.views.reserve',
kwargs={'template':'library/reserve.html'},
name='reserve_clean'
),
url(r'^admin/', include(admin.site.urls))
)
# In debug mode, static files are automatically served by Django.
# Also serve user-uploaded files.
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^%s/(?P<path>.*)$' % settings.UPLOADS_DIRNAME,
'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}
),
url(r'^%(MEDIA_URL)s/(?P<path>.*)$' % {'MEDIA_URL': settings.MEDIA_URL.strip('/')},
'django.views.static.serve',
{ 'document_root': settings.MEDIA_ROOT }),
)
|
/* eslint-env mocha */
const koaRequest = require('./routes-specs').koaRequest
const models = require('./routes-specs').models
beforeEach(function syncDB () {
return models.db.sequelize.sync({force: true})
})
describe('sponsor', () => {
context('GET /sponsor', () => {
it('should return empty array if no sponsors', async () => {
await koaRequest
.get('/sponsor')
.expect(200)
.then(response => {
response.body.length.should.equal(0)
})
})
it('should return sponsors', async () => {
let sponsor1 = await models.db.sponsor.create({'name': 'Kaiser NC',
'luminate_id': '001'})
let sponsor2 = await models.db.sponsor.create({'name': 'Sutter Health',
'luminate_id': '002'})
await koaRequest
.get('/sponsor')
.expect(200)
.then(response => {
response.body[0].name.should.equal(sponsor1.name)
response.body[0].luminate_id.should.equal(sponsor1.luminate_id)
response.body[1].name.should.equal(sponsor2.name)
response.body[1].luminate_id.should.equal(sponsor2.luminate_id)
})
})
})
context('GET /sponsor/:id', () => {
it('should return 204 if no sponsor with id=id', async () => {
await koaRequest
.get('/sponsor/1')
.expect(204)
})
it('should return sponsor with id=id', async () => {
let sponsor = await models.db.sponsor.create({'name': 'Kaiser NC',
'luminate_id': '001'})
await koaRequest
.get('/sponsor/' + sponsor.id)
.expect(200)
.then(response => {
response.body.name.should.equal(sponsor.name)
response.body.luminate_id.should.equal(sponsor.luminate_id)
})
})
})
context('POST /sponsor', () => {
it('should create sponsor with name=name and luminate_id=luminate_id', async () => {
let body = {'name': 'Blue Shield', 'luminate_id': '003'}
await koaRequest
.post('/sponsor')
.send(body)
.expect(201)
.then(response => {
response.body.name.should.equal(body.name)
response.body.luminate_id.should.equal(body.luminate_id)
})
})
it('should return 400 if sponsor name conflict', async () => {
let sponsor1 = {'name': 'Kaiser NC', 'luminate_id': '001'}
let duplicateNameReq = {'name': 'Kaiser NC', 'luminate_id': '002'}
await models.db.sponsor.create(sponsor1)
await koaRequest
.post('/sponsor')
.send(duplicateNameReq)
.expect(400)
})
it('should return 400 if sponsor luminate id conflict', async () => {
let sponsor1 = {'name': 'Cigna', 'luminate_id': '004'}
let duplicateLuminateReq = {'name': 'Sutter Health', 'luminate_id': '004'}
await models.db.sponsor.create(sponsor1)
await koaRequest
.post('/sponsor')
.send(duplicateLuminateReq)
.expect(400)
})
})
context('DELETE /sponsor/:id', () => {
it('should delete sponsor with id=id', async () => {
let sponsor = await models.db.sponsor.create({'name': 'Kaiser NC',
'luminate_id': '001'})
await koaRequest
.del('/sponsor/' + sponsor.id)
.expect(204)
})
it('should return 400 if no sponsor with id=id', async () => {
await koaRequest
.del('/sponsor/' + 0)
.expect(400)
.then(response => {
response.body.should.equal(0)
})
})
})
})
|
import pytest
import copy
from src.base.bbox import Bbox
from src.base.node import Node
@pytest.fixture(scope="module")
def rappi():
return Bbox(left=8.81372, bottom=47.218788, right=8.852430, top=47.239654)
def test_instantiate():
bottom = 47.0
left = 8.0
top = 48.0
right = 9.0
bbox = Bbox(bottom=bottom, left=left, top=top, right=right)
assert bbox.bottom == bottom
assert bbox.left == left
assert bbox.top == top
assert bbox.right == right
def test_instantiate_from_string():
bottom = '47.0'
left = '8.0'
top = '48.0'
right = '9.0'
bbox = Bbox(bottom=bottom, left=left, top=top, right=right)
assert bbox.bottom == bottom
assert bbox.left == left
assert bbox.top == top
assert bbox.right == right
def test_in_bbox(rappi):
bbox = rappi
node = Node(47.22, 8.82)
assert bbox.in_bbox(node)
def test_not_in_bbox(rappi):
bbox = rappi
node = Node(48.0, 8.8)
assert not bbox.in_bbox(node)
def test_equal(rappi):
rappi2 = copy.copy(rappi)
assert rappi2 is not rappi
assert rappi2 == rappi
def test_not_equal(rappi):
bbox = Bbox()
assert bbox is not rappi
assert bbox != rappi
|
# -*- coding: utf-8 -*-
from hashlib import md5
from module.plugins.Account import Account
from module.common.json_layer import json_loads
class LinksnappyCom(Account):
__name__ = "LinksnappyCom"
__type__ = "account"
__version__ = "0.04"
__description__ = """Linksnappy.com account plugin"""
__license__ = "GPLv3"
__authors__ = [("stickell", "[email protected]")]
def loadAccountInfo(self, user, req):
data = self.getAccountData(user)
r = req.load('http://gen.linksnappy.com/lseAPI.php',
get={'act': 'USERDETAILS', 'username': user, 'password': md5(data['password']).hexdigest()})
self.logDebug("JSON data: " + r)
j = json_loads(r)
if j['error']:
return {"premium": False}
validuntil = j['return']['expire']
if validuntil == 'lifetime':
validuntil = -1
elif validuntil == 'expired':
return {"premium": False}
else:
validuntil = float(validuntil)
if 'trafficleft' not in j['return'] or isinstance(j['return']['trafficleft'], str):
trafficleft = -1
else:
trafficleft = self.parseTraffic(float(j['return']['trafficleft'] + "MB")
return {"premium": True, "validuntil": validuntil, "trafficleft": trafficleft}
def login(self, user, data, req):
r = req.load("http://gen.linksnappy.com/lseAPI.php",
get={'act' : 'USERDETAILS',
'username': user,
'password': md5(data['password']).hexdigest()},
decode=True)
if 'Invalid Account Details' in r:
self.wrongPassword()
|
<?php
if(!isset($child)){
$name = "";
$age = "";
$image = "";
$gender = "";
$child_race = "";
$medical_condition = "";
$status = "1";
$action = "action_add_child";
}
else
{
$name = $child['name'];
$age = $child['age'];
$image = $child['image'];
$gender = $child['sex'];
$child_race = $child['race'];
$medical_condition = $child['medical_condition'];
$status = $child['status'];
$action = "action_edit_child";
}
?>
<div class="row">
<div class="col s12 m12">
<div class="card-panel">
<h4 class="header2">Child Details</h4>
<div class="row">
<form class="col s12" method="POST" action="<?=$action;?>" enctype="multipart/form-data">
<div class="row">
<div class="input-field col s12">
<input id="name" type="text" name="name" value="<?=$name;?>" required>
<label for="name">Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="age" type="text" name="age" value="<?=$age;?>" required>
<label for="age">Age</label>
</div>
</div>
<div class="row">
<div class="col s12 m4 l3">
Upload Child Image
</div>
<div class="col s12 m4">
<input id="age" type="file" name="userfile">
</div>
<div class="col s12 m4">
<?php
if($image!=""){
?>
<image src="<?=base_url();?>uploads/<?=$image;?>" width="50" height="50">
<?php } ?>
</div>
</div>
<div class="row">
<div class="col s12 m4 l3">
Gender
</div>
<div class="col s12 m8 l9">
<p>
<input name="sex" type="radio" id="male" value="M" <?php echo $gender=='M'?'checked':'';?> required/>
<label for="male">Male</label>
</p>
<p>
<input name="sex" type="radio" id="female" value="F" <?php echo $gender=='F'?'checked':'';?> required/>
<label for="female">Female</label>
</p>
</div>
</div>
<div class="row">
<div class="col s12 m4 l3">
Race
</div>
<div class="col s12 m8 l9">
<select name="race" required>
<option value="">Choose your option</option>
<?php
foreach ($race as $key => $value) {
$selected = "";
if($value['id'] == $child_race)
$selected = "selected";
echo "<option value='".$value['id']."' ".$selected.">".$value['race']."</option>";
}
?>
</select>
</div>
</div>
<div class="row">
<div class="col s12 m4 l3">
Medical Condition
</div>
<div class="col s12 m8 l9">
<select name="medical_condition" required>
<option value="">Choose your option</option>
<?php
foreach ($medical as $key => $value) {
$selected="";
if($value['id'] == $medical_condition)
$selected = "selected";
echo "<option value='".$value['id']."' ".$selected.">".$value['medical_condition']."</option>";
}
?>
</select>
</div>
</div>
<div class="row">
<div class="col s12 m4 l3">
Status
</div>
<div class="col s12 m8 l9">
<p>
<input name="status" type="radio" id="1" value="1" <?php echo $status=='1'?'checked':'';?> required/>
<label for="1">Active</label>
</p>
<p>
<input name="status" type="radio" id="0" value="0" <?php echo $status=='0'?'checked':'';?> required/>
<label for="0">Deactive</label>
</p>
</div>
</div>
<input type="hidden" name="image" value="<?=$image;?>">
<input type="hidden" name="child_id" value="<?=@$this->input->get('child_id');?>">
<div class="row">
<div class="input-field col s12">
<button class="btn cyan waves-effect waves-light right" type="submit">Submit
<i class="mdi-content-send right"></i>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
|
/*******************************************************************************
* Copyright (c) 2008 Dennis Schenk, Peter Siska.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Dennis Schenk - initial implementation
* Peter Siska - initial implementation
*******************************************************************************/
package ch.unibe.iam.scg.archie.samples.i18n;
import org.eclipse.osgi.util.NLS;
/**
* <p>Message class. Used for i18n.</p>
*
* $Id: Messages.java 700 2008-12-22 09:22:22Z hephster $
*
* @author Peter Siska
* @author Dennis Schenk
* @version $Rev: 700 $
*/
public final class Messages extends NLS {
public static String CALCULATING;
public static String USER_OVERVIEW_TITLE;
public static String USER_OVERVIEW_DESCRIPTION;
public static String USER_OVERVIEW_USER;
public static String USER_OVERVIEW_ENTRIES;
public static String USER_OVERVIEW_BIRTHDAY;
public static String USER_OVERVIEW_GENDER;
public static String USER_OVERVIEW_VALID;
public static String USER_OVERVIEW_GROUPS;
public static String USER_OVERVIEW_YES;
public static String USER_OVERVIEW_NO;
public static String USER_OVERVIEW_UNDEFINED;
public static String CONSULTATION_STATS_TITLE;
public static String CONSULTATION_STATS_DESCRIPTION;
public static String CONSULTATION_STATS_AGE_GROUP;
public static String CONSULTATION_STATS_TOTAL_COSTS;
public static String CONSULTATION_STATS_NUMBER_OF_CONSULTATIONS;
public static String CONSULTATION_STATS_AVERAGE_COSTS;
public static String CONSULTATION_STATS_TOTAL_PROFITS;
public static String CONSULTATION_STATS_AVERAGE_PROFITS;
public static String CONSULTATION_STATS_REGEX_MESSAGE = "";
public static String CONSULTATION_STATS_COHORT_SIZE_EXCEPTION;
public static String CONSULTATION_TIME_STATS_TITLE;
public static String CONSULTATION_TIME_STATS_DESCRIPTION;
public static String CONSULTATION_TIME_STATS_HEADING_TIME_TOTAL;
public static String CONSULTATION_TIME_STATS_HEADING_TIME_MAX;
public static String CONSULTATION_TIME_STATS_HEADING_TIME_AVERAGE;
public static String CONSULTATION_TIME_STATS_HEADING_INCOME;
public static String CONSULTATION_TIME_STATS_HEADING_SPENDING;
public static String CONSULTATION_TIME_STATS_HEADING_PROFIT;
public static String PATIENTS_PROFITS_TITLE;
public static String PATIENTS_PROFITS_DESCRIPTION;
public static String PATIENTS_PROFITS_HEADING_PATIENT;
public static String PATIENTS_PROFITS_HEADING_COSTS;
public static String PATIENTS_PROFITS_HEADING_INCOME;
public static String PATIENTS_PROFITS_HEADING_PROFIT;
public static String PRESCRIPTIONS_OVERVIEW_TITLE;
public static String PRESCRIPTIONS_OVERVIEW_DESCRIPTION;
public static String PRESCRIPTIONS_OVERVIEW_HEADING_NAME;
public static String PRESCRIPTIONS_OVERVIEW_HEADING_COUNT;
public static String PRESCRIPTIONS_OVERVIEW_HEADING_AVG_TIME;
public static String SERVICES_TITLE;
public static String SERVICES_DESCRIPTION;
public static String SERVICES_HEADING_CODESYSTEM;
public static String SERVICES_HEADING_SERVICE;
public static String SERVICES_HEADING_AMOUNT;
public static String SERVICES_HEADING_COSTS;
public static String SERVICES_HEADING_INCOME;
public static String SERVICES_HEADING_PROFITS;
public static String DIAGNOSES_TITLE;
public static String DIAGNOSES_DESCRIPTION;
public static String DIAGNOSES_HEADING_DIAGNOSE;
public static String DIAGNOSES_HEADING_COUNT;
public static String DIAGNOSES_HEADING_AGE_MIN;
public static String DIAGNOSES_HEADING_AGE_MAX;
public static String DIAGNOSES_HEADING_AGE_AVG;
public static String DIAGNOSES_HEADING_AGE_MED;
}
|
using System;
using Activator.Base;
using Activator.Handlers;
using LeagueSharp.Common;
using EloBuddy;
using LeagueSharp.Common;
namespace Activator.Items.Consumables
{
class _2043 : CoreItem
{
internal override int Id => 2055;
internal override string Name => "Control Ward";
internal override string DisplayName => "Control Ward";
internal override int Duration => 101;
internal override int Priority => 5;
internal override float Range => 600f;
internal override MenuType[] Category => new[] { MenuType.Stealth, MenuType.ActiveCheck };
internal override MapType[] Maps => new[] { MapType.SummonersRift };
internal override int DefaultHP => 0;
internal override int DefaultMP => 0;
public override void OnTick(EventArgs args)
{
if (!Menu.Item("use" + Name).GetValue<bool>() || !IsReady())
return;
foreach (var hero in Activator.Allies())
{
if (hero.Player.Distance(Player.ServerPosition) > Range)
continue;
if (hero.HitTypes.Contains(HitType.Stealth))
{
UseItem(hero.Player.ServerPosition, Menu.Item("mode" + Name).GetValue<StringList>().SelectedIndex == 1);
}
}
}
}
}
|
<?php
/**
* Created by PhpStorm.
* User: feras
* Date: 9/27/17
* Time: 9:22 AM
*/
class Vote_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function set_vote($data) //add new vote
{
$err = $this->db->insert('votes', $data);
if ($err)
return array('error'=>$err['message']);
$data['id'] = $this->db->insert_id(); // return new vote id
return $data ;
}
}?>
|
// Copyright 2013 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.
#include "content/common/gpu/client/gpu_memory_buffer_impl_io_surface.h"
#include "base/logging.h"
#include "content/common/gpu/gpu_memory_buffer_factory_io_surface.h"
#include "ui/gfx/buffer_format_util.h"
#include "ui/gfx/mac/io_surface_manager.h"
namespace content {
namespace {
uint32_t LockFlags(gfx::BufferUsage usage) {
switch (usage) {
case gfx::BufferUsage::GPU_READ_CPU_READ_WRITE:
return kIOSurfaceLockAvoidSync;
case gfx::BufferUsage::GPU_READ:
case gfx::BufferUsage::SCANOUT:
case gfx::BufferUsage::GPU_READ_CPU_READ_WRITE_PERSISTENT:
return 0;
}
NOTREACHED();
return 0;
}
void FreeIOSurfaceForTesting(gfx::GpuMemoryBufferId id) {
gfx::IOSurfaceManager::GetInstance()->UnregisterIOSurface(id, 0);
}
} // namespace
GpuMemoryBufferImplIOSurface::GpuMemoryBufferImplIOSurface(
gfx::GpuMemoryBufferId id,
const gfx::Size& size,
gfx::BufferFormat format,
const DestructionCallback& callback,
IOSurfaceRef io_surface,
uint32_t lock_flags)
: GpuMemoryBufferImpl(id, size, format, callback),
io_surface_(io_surface),
lock_flags_(lock_flags) {}
GpuMemoryBufferImplIOSurface::~GpuMemoryBufferImplIOSurface() {
}
// static
scoped_ptr<GpuMemoryBufferImplIOSurface>
GpuMemoryBufferImplIOSurface::CreateFromHandle(
const gfx::GpuMemoryBufferHandle& handle,
const gfx::Size& size,
gfx::BufferFormat format,
gfx::BufferUsage usage,
const DestructionCallback& callback) {
base::ScopedCFTypeRef<IOSurfaceRef> io_surface(
gfx::IOSurfaceManager::GetInstance()->AcquireIOSurface(handle.id));
if (!io_surface)
return nullptr;
return make_scoped_ptr(
new GpuMemoryBufferImplIOSurface(handle.id, size, format, callback,
io_surface.release(), LockFlags(usage)));
}
// static
bool GpuMemoryBufferImplIOSurface::IsConfigurationSupported(
gfx::BufferFormat format,
gfx::BufferUsage usage) {
return GpuMemoryBufferFactoryIOSurface::
IsGpuMemoryBufferConfigurationSupported(format, usage);
}
// static
base::Closure GpuMemoryBufferImplIOSurface::AllocateForTesting(
const gfx::Size& size,
gfx::BufferFormat format,
gfx::BufferUsage usage,
gfx::GpuMemoryBufferHandle* handle) {
base::ScopedCFTypeRef<IOSurfaceRef> io_surface(
gfx::IOSurfaceManager::CreateIOSurface(size, format));
DCHECK(io_surface);
gfx::GpuMemoryBufferId kBufferId(1);
bool rv = gfx::IOSurfaceManager::GetInstance()->RegisterIOSurface(
kBufferId, 0, io_surface);
DCHECK(rv);
handle->type = gfx::IO_SURFACE_BUFFER;
handle->id = kBufferId;
return base::Bind(&FreeIOSurfaceForTesting, kBufferId);
}
bool GpuMemoryBufferImplIOSurface::Map() {
DCHECK(!mapped_);
IOReturn status = IOSurfaceLock(io_surface_, lock_flags_, NULL);
DCHECK_NE(status, kIOReturnCannotLock);
mapped_ = true;
return true;
}
void* GpuMemoryBufferImplIOSurface::memory(size_t plane) {
DCHECK(mapped_);
DCHECK_LT(plane, gfx::NumberOfPlanesForBufferFormat(format_));
return IOSurfaceGetBaseAddressOfPlane(io_surface_, plane);
}
void GpuMemoryBufferImplIOSurface::Unmap() {
DCHECK(mapped_);
IOSurfaceUnlock(io_surface_, lock_flags_, NULL);
mapped_ = false;
}
int GpuMemoryBufferImplIOSurface::stride(size_t plane) const {
DCHECK_LT(plane, gfx::NumberOfPlanesForBufferFormat(format_));
return IOSurfaceGetBytesPerRowOfPlane(io_surface_, plane);
}
gfx::GpuMemoryBufferHandle GpuMemoryBufferImplIOSurface::GetHandle() const {
gfx::GpuMemoryBufferHandle handle;
handle.type = gfx::IO_SURFACE_BUFFER;
handle.id = id_;
return handle;
}
} // namespace content
|
"""
Serializers for REST entries
"""
from cStringIO import StringIO
from django.forms import widgets
from babel.messages.pofile import read_po
from rest_framework import serializers
from po_projects.models import Project, ProjectVersion
from po_projects.generators import create_new_version, update_catalogs
class VersionSerializer(serializers.ModelSerializer):
"""
Serializer for ``ProjectVersion`` model
"""
url = serializers.HyperlinkedIdentityField(
view_name='po_projects:api-project-version-detail',
lookup_field='pk'
)
class Meta:
model = ProjectVersion
fields = ('id','version','url')
class ProjectVersionSerializer(serializers.HyperlinkedModelSerializer):
"""
Serializer for ``Project`` model for a specific version
TODO: Add tarball_url link for the given version, not for the current one
"""
url = serializers.HyperlinkedIdentityField(
view_name='po_projects:api-project-version-detail',
lookup_field='pk'
)
tarball_url = serializers.HyperlinkedIdentityField(
view_name='po_projects:api-project-archive',
lookup_field='slug'
)
class Meta:
model = Project
fields = ('url', 'id', 'slug', 'name', 'description')#, 'tarball_url' )
class ProjectCurrentSerializer(ProjectVersionSerializer):
"""
Serializer for ``Project`` model for the current version (the last one)
"""
url = serializers.HyperlinkedIdentityField(
view_name='po_projects:api-project-detail',
lookup_field='slug'
)
projectversion_set = VersionSerializer(
many=True, read_only=True,
)
pot = serializers.CharField(
widget=widgets.Textarea,
write_only=True,
required=False,
help_text='(optionnal) Content for a valid POT file to update project strings to translate in its catalogs'
)
def validate_pot(self, attrs, source):
"""
Validation for the given POT content
"""
value = attrs[source]
if value:
try:
template_file = StringIO()
template_file.write(value.encode('UTF8'))
template_file.seek(0)
# Seems the validation from read_po is too much minimalistic
# This does not really valid if the content is a real POT content
self.uploaded_pot_file = read_po(template_file, ignore_obsolete=True)
except:
raise serializers.ValidationError("Your file does not seem to be a valid POT file")
return attrs
def save(self, **kwargs):
"""
Override the save method to update template and catalog from the given POT
"""
super(ProjectCurrentSerializer, self).save(**kwargs)
if hasattr(self, 'uploaded_pot_file'):
previous_version = self.object.get_current_version()
current_version = create_new_version(self.object, previous_version.version+1, self.uploaded_pot_file)
update_catalogs(self.object, previous_version, current_version)
self.object.save()
return self.object
class Meta:
model = Project
fields = ('id', 'slug', 'name', 'description', 'url', 'tarball_url', 'pot', 'projectversion_set' )
|
// MLMVN implementation
#pragma once
#include "mvn.h"
namespace klogic {
class mlmvn;
// Separate class for calculating mlmvn output allows to parallelize, but
// is stingy about memory allocation. It uses max. two vectors to support
// computations for networks containing arbitrary number of layers
class mlmvn_forward_base {
public:
mlmvn_forward_base(const mlmvn &_net);
// Layer-by-layer calculation interface
// Start calculation X -> out
void start(const klogic::cvector &X, cvector::iterator out);
// Start calculation for X not meaning to get result
void start(const klogic::cvector &X);
// Get current layer, i.e. neurons which process incoming data and
// output results to the next layer
int current_layer() const { return layer; }
// Make calculations for current layer and step to the next one.
// Returns true if result is already available.
bool step();
// Input for current layer
cvector::const_iterator input_begin() const {
return from->begin();
}
cvector::const_iterator input_end() const {
return from->begin() + from_size;
}
protected:
// original values passed to start are saved here
cvector::iterator out;
const mlmvn &net;
bool use_out;
// Two internal vectors storing intermediate results
cvector layer1, layer2;
// `from` always points to a vector which contains input for current
// layer. At start, it points to X but then its value cycles between
// &layer1 and &layer2
const cvector *from;
// `to` points to a vector which receives output from current layer. It
// also cycles between &layer1 and &layer2 but it always "opposite" to
// `from`. If `to` points to layer1, `from` points to layer2 and vice versa.
cvector *to;
// This value corresponds to input size available in `*from`
size_t from_size;
// Current layer number. Input layer is not counted, so layer == 0
// means first hidden layer or output layer if network has no hidden
// layers
int layer;
};
//--------------------------------------------------------------
class mlmvn {
friend class mlmvn_forward;
friend class mlmvn_forward_base;
public:
typedef cvector desired_type;
// Construct an MLMVN. sizes is the following:
// Number of inputs, hidden layer 1 size, ...,
// hidden layer M size, output layer size
mlmvn(const std::vector<int> &sizes,
const std::vector<int> &k_values);
// Total layer count in network (hidden + one output)
size_t layers_count() const { return neurons.size(); }
// Input layer size
size_t input_layer_size() const { return input_size; }
// Specific layer size
size_t layer_size(size_t layer) const { return neurons[layer].size(); }
// Output (last) layer size
size_t output_layer_size() const { return output_size; }
// Correct weights
void learn(const cvector &X, const cvector &error,
double learning_rate = 1.0);
// i-th neuron in j-th layer
mvn &neuron(int i, int j) {
return neurons[j][i];
}
const mvn &neuron(int i, int j) const {
return neurons[j][i];
}
// Net output. Use with care since it allocates memory on each run
cvector output(const cvector &X) const;
void dump() const;
void dump_errors() const;
void export_neurons(cvector &all_weights, std::vector<int> &k_values) const;
void load_neurons(const cvector &all_weights, const std::vector<int> &k_values);
protected:
// Calculate errors for all neurons given
// output layer errors
void calculate_errors(const cvector &errs);
// Get overall weights and neurons counts
void get_stats(size_t &n_weights, size_t &n_neurons) const;
std::vector<std::vector<mvn> > neurons;
std::vector<std::vector<cmplx> > errors;
int s_j(int j) {
return (j <= 0) ? 1 : 1 + neurons[j-1].size();
}
int max_layer_size;
size_t input_size, output_size;
mlmvn_forward_base calculator;
};
//--------------------------------------------------------------
// Higher level version of mlmvn_forward_base
class mlmvn_forward : protected mlmvn_forward_base {
public:
mlmvn_forward(const mlmvn &net)
: mlmvn_forward_base(net) {}
// Calculate network output for input vector X and return it as a vector
cvector output(const cvector &X) {
cvector result(net.output_size);
output(X, result.begin());
return result;
}
// Calculate network output for input vector X and put it to out
void output(const cvector &X, cvector::iterator out) {
start(X, out);
while (!step())
;
}
};
//--------------------------------------------------------------
inline cvector mlmvn::output(const cvector &X) const {
return mlmvn_forward(*this).output(X);
}
};
|
<?php
use yii\db\Migration;
/**
* Handles the creation of table `weather`.
*/
class m161128_115342_create_weather_table extends Migration
{
/**
* @inheritdoc
*/
public function up()
{
$this->createTable('weather', [
'id' => $this->primaryKey(),
'created_at' => $this->integer()->notNull(),
'sost' => $this->string(32),
'temp' => $this->string(10),
'pr_r' => $this->string(32),
'pr_m' => $this->string(32),
'works' => $this->text(),
'rayon' => $this->integer()->notNull(),
]);
// add foreign key for table `user`
$this->addForeignKey(
'fk-weather-user_id',
'weather',
'rayon',
'user',
'id',
'CASCADE'
);
}
/**
* @inheritdoc
*/
public function down()
{
$this->dropTable('weather');
}
}
|
/*
Copyright (C) 2013 by Rafał Soszyński <rsoszynski121 [at] gmail [dot] com>
This file is part of The Chronicles Of Andaria Project.
The Chronicles of Andaria Project is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Chronicles of Andaria Project is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with The Chronicles Of Andaria. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Core/Containers/Equipment.h"
Equipment::Equipment()
: head_(nullptr), torso_(nullptr), leftHand_(nullptr), rightHand_(nullptr),
smallPotions_(StartingNumberOfLargePotions), largePotions_(StartingNumberOfLargePotions)
{
}
const Item * Equipment::head() const
{
return head_;
}
void Equipment::setHead(const Item *item)
{
head_ = item;
}
const Item * Equipment::torso() const
{
return torso_;
}
void Equipment::setTorso(const Item *item)
{
torso_ = item;
}
const Item * Equipment::leftHand() const
{
return leftHand_;
}
void Equipment::setLeftHand(const Item *item)
{
leftHand_ = item;
}
const Item * Equipment::rightHand() const
{
return rightHand_;
}
void Equipment::setRightHand(const Item *item)
{
rightHand_ = item;
}
quint8 Equipment::smallPotions() const
{
return smallPotions_;
}
void Equipment::setSmallPotions(quint8 cnt)
{
smallPotions_ = cnt;
}
quint8 Equipment::largePotions() const
{
return largePotions_;
}
void Equipment::setLargePotions(quint8 cnt)
{
largePotions_ = cnt;
}
const QList <const Item *> & Equipment::backpack() const
{
return backpack_;
}
const QList <const Item *> & Equipment::usedArtifacts() const
{
return usedArtifacts_;
}
void Equipment::addItem(const Item *item)
{
backpack_.append(item);
}
void Equipment::removeItem(const Item *item)
{
backpack_.removeOne(item);
}
void Equipment::addArtifact(const Item *item)
{
usedArtifacts_.append(item);
}
void Equipment::removeArtifact(const Item *item)
{
usedArtifacts_.removeOne(item);
}
|
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation;
import org.springframework.core.type.AnnotationMetadata;
/**
* @author Juergen Hoeller
* @author Phil Webb
*/
interface ImportRegistry {
AnnotationMetadata getImportingClassFor(String importedClass);
void removeImportingClassFor(String importedClass);
}
|
/*
* Copyright (c) 2015 Brandon Lyon
*
* This file is part of Emerge Game Engine (Emerge)
*
* Emerge is free software: you can redistribute it and/or modify
* it under the terms of version 3 of the GNU General Public License as
* published by the Free Software Foundation.
*
* Emerge is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Emerge. If not, see <http://www.gnu.org/licenses/>.
*/
package net.etherous.emerge.asset;
import java.awt.image.BufferedImage;
/**
* Basic interface for an asset representing an image
*/
public interface ImageAsset extends Asset
{
/**
* Produces and returns a BufferedImage instance representing the image data of this asset
*
* @return This asset's image data as a BufferedImage instance
*/
public BufferedImage getBufferedImage ();
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:1c2a26c3df33fe02e1a55fbe5ff905e8fc635aa8b50ea6cf1c7098eeff424bf5
size 35404
|
/**
* Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved.
*
* 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.
*/
#import "KGWebSocketHandlerAdapter.h"
/*
* WebSocket Native KGHandler Chain
* NativeHandler - AuthenticationHandler - HandshakeHandler - BalanceingHandler - {Nodec} - BridgeHandler
* Responsibilities:
* a). encode message to follow WebSocket standard
*/
@interface KGWebSocketNativeCodec : KGWebSocketHandlerAdapter
@end
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
'''
JSON related utilities.
This module provides a few things:
1) A handy function for getting an object down to something that can be
JSON serialized. See to_primitive().
2) Wrappers around loads() and dumps(). The dumps() wrapper will
automatically use to_primitive() for you if needed.
3) This sets up anyjson to use the loads() and dumps() wrappers if anyjson
is available.
'''
import datetime
import functools
import inspect
import itertools
import json
import xmlrpclib
import six
from stackalytics.openstack.common import timeutils
_nasty_type_tests = [inspect.ismodule, inspect.isclass, inspect.ismethod,
inspect.isfunction, inspect.isgeneratorfunction,
inspect.isgenerator, inspect.istraceback, inspect.isframe,
inspect.iscode, inspect.isbuiltin, inspect.isroutine,
inspect.isabstract]
_simple_types = (six.string_types + six.integer_types
+ (type(None), bool, float))
def to_primitive(value, convert_instances=False, convert_datetime=True,
level=0, max_depth=3):
"""Convert a complex object into primitives.
Handy for JSON serialization. We can optionally handle instances,
but since this is a recursive function, we could have cyclical
data structures.
To handle cyclical data structures we could track the actual objects
visited in a set, but not all objects are hashable. Instead we just
track the depth of the object inspections and don't go too deep.
Therefore, convert_instances=True is lossy ... be aware.
"""
# handle obvious types first - order of basic types determined by running
# full tests on nova project, resulting in the following counts:
# 572754 <type 'NoneType'>
# 460353 <type 'int'>
# 379632 <type 'unicode'>
# 274610 <type 'str'>
# 199918 <type 'dict'>
# 114200 <type 'datetime.datetime'>
# 51817 <type 'bool'>
# 26164 <type 'list'>
# 6491 <type 'float'>
# 283 <type 'tuple'>
# 19 <type 'long'>
if isinstance(value, _simple_types):
return value
if isinstance(value, datetime.datetime):
if convert_datetime:
return timeutils.strtime(value)
else:
return value
# value of itertools.count doesn't get caught by nasty_type_tests
# and results in infinite loop when list(value) is called.
if type(value) == itertools.count:
return six.text_type(value)
# FIXME(vish): Workaround for LP bug 852095. Without this workaround,
# tests that raise an exception in a mocked method that
# has a @wrap_exception with a notifier will fail. If
# we up the dependency to 0.5.4 (when it is released) we
# can remove this workaround.
if getattr(value, '__module__', None) == 'mox':
return 'mock'
if level > max_depth:
return '?'
# The try block may not be necessary after the class check above,
# but just in case ...
try:
recursive = functools.partial(to_primitive,
convert_instances=convert_instances,
convert_datetime=convert_datetime,
level=level,
max_depth=max_depth)
if isinstance(value, dict):
return dict((k, recursive(v)) for k, v in six.iteritems(value))
elif isinstance(value, (list, tuple)):
return [recursive(lv) for lv in value]
# It's not clear why xmlrpclib created their own DateTime type, but
# for our purposes, make it a datetime type which is explicitly
# handled
if isinstance(value, xmlrpclib.DateTime):
value = datetime.datetime(*tuple(value.timetuple())[:6])
if convert_datetime and isinstance(value, datetime.datetime):
return timeutils.strtime(value)
elif hasattr(value, 'iteritems'):
return recursive(dict(value.iteritems()), level=level + 1)
elif hasattr(value, '__iter__'):
return recursive(list(value))
elif convert_instances and hasattr(value, '__dict__'):
# Likely an instance of something. Watch for cycles.
# Ignore class member vars.
return recursive(value.__dict__, level=level + 1)
else:
if any(test(value) for test in _nasty_type_tests):
return six.text_type(value)
return value
except TypeError:
# Class objects are tricky since they may define something like
# __iter__ defined but it isn't callable as list().
return six.text_type(value)
def dumps(value, default=to_primitive, **kwargs):
return json.dumps(value, default=default, **kwargs)
def loads(s):
return json.loads(s)
def load(s):
return json.load(s)
try:
import anyjson
except ImportError:
pass
else:
anyjson._modules.append((__name__, 'dumps', TypeError,
'loads', ValueError, 'load'))
anyjson.force_implementation(__name__)
|
import os, sys
srcpath = os.path.abspath("../src")
sys.path.insert(0,srcpath)
import traceback, urllib2, httplib
import webbrowser
from cloudsn.providers import tweepy
CONSUMER_KEY = 'uRPdgq7wqkiKmWzs9rneJA'
CONSUMER_SECRET = 'ZwwhbUl2mwdreaiGFd8IqUhfsZignBJIYknVA867Ieg'
def main():
#Ask for permissions and set the pin
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth_url = auth.get_authorization_url()
print 'Please authorize in your browser'
webbrowser.open(auth_url)
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
ACCESS_KEY = auth.access_token.key
ACCESS_SECRET = auth.access_token.secret
print "ACCESS_KEY: " + ACCESS_KEY
print "ACCESS_SECRET: " + ACCESS_SECRET
#Access to twitter with the access keys
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
#api.update_status("Testing cloudsn with tweety")
public_tweets = api.public_timeline()
for tweet in public_tweets:
print tweet.text
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# coding: utf8
from __future__ import with_statement
from setuptools import setup, find_packages
import multiprocessing
# Figure out the version; this could be done by importing the
# module, though that requires dependencies to be already installed,
# which may not be the case when processing a pip requirements
# file, for example.
def parse_version(assignee):
import os, re
here = os.path.dirname(os.path.abspath(__file__))
version_re = re.compile(
r'%s = (\(.*?\))' % assignee)
with open(os.path.join(here, 'django_assets', '__init__.py')) as fp:
for line in fp:
match = version_re.search(line)
if match:
version = eval(match.group(1))
return ".".join(map(str, version))
else:
raise Exception("cannot find version")
version = parse_version('__version__')
webassets_version = parse_version('__webassets_version__')
setup(
name='django-assets',
version=version,
url='http://github.com/miracle2k/django-assets',
license='BSD',
author='Michael Elsdörfer',
author_email='[email protected]',
description='Asset management for Django, to compress and merge '\
'CSS and Javascript files.',
long_description=__doc__,
packages=find_packages(exclude=('tests',)),
zip_safe=False,
platforms='any',
install_requires=[
'Django>=1.7',
'webassets%s' % webassets_version
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
test_suite='nose.collector',
tests_require=[
'nose',
],
# make plugin available to pytest
entry_points = {
'pytest11': [
'django_assets = django_assets.pytest_plugin',
]
},
)
|
#region License
// Copyright © 2016 Tinkoff Bank
//
// 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.
#endregion
using System.Runtime.Serialization;
namespace Tinkoff.Acquiring.Sample.Models
{
[DataContract]
public class SaleInfo
{
[DataMember(Name = "country")]
public string Country { get; set; }
[DataMember(Name = "price")]
public decimal Price { get; set; }
}
}
|
#ifndef SDFLOADER_HPP_BUW
#define SDFLOADER_HPP_BUW
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <stddef.h>
#include <glm/glm.hpp>
#include <memory>
#include "material.hpp"
#include "color.hpp"
#include "light.hpp"
#include "shape.hpp"
#include "sphere.hpp"
#include "box.hpp"
#include "cylinder.hpp"
class sdfloader
{
private:
std::vector<Material> materials_;
std::vector<std::shared_ptr<Shape>> shapes_;
std::vector<Light> lights_;
public:
std::vector<Material> const& materials() const;
std::vector<std::shared_ptr<Shape>> const& shapes() const;
std::vector<Light> const& lights() const;
void load();
};
#endif
|
// Copyright (c) Augurk. All Rights Reserved.
// Licensed under the Apache License, Version 2.0.
using Augurk.Api.Managers;
using Augurk.Entities.Analysis;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace Augurk.Api.Controllers.V2
{
/// <summary>
/// ApiController for publishing analysis results.
/// </summary>
[ApiVersion("2.0")]
[Route("api/v{apiVersion:apiVersion}/products/{productName}/versions/{productVersion}/analysis")]
public class AnalysisController : Controller
{
private readonly IAnalysisReportManager _analysisReportManager;
private readonly Analyzer _analyzer;
/// <summary>
/// Initializes a new instance of the <see cref="AnalysisController"/>.
/// </summary>
public AnalysisController(IAnalysisReportManager analysisReportManager, IFeatureManager featureManager)
{
_analysisReportManager = analysisReportManager ?? throw new ArgumentNullException(nameof(analysisReportManager));
_analyzer = new Analyzer(featureManager, _analysisReportManager);
}
/// <summary>
/// Persists an analysis report for further analysis.
/// </summary>
/// <param name="analysisReport">The report as producted by one of the Augurk automation analyzers.</param>
/// <param name="productName">Name of the product that the feature belongs to.</param>
/// <param name="groupName">Name of the group that the feature belongs to.</param>
[Route("reports")]
[HttpPost]
[ProducesResponseType(202)]
public async Task<ActionResult> PostAnalysisReport([FromBody] AnalysisReport analysisReport, string productName, string version)
{
analysisReport.Version = version;
await _analysisReportManager.InsertOrUpdateAnalysisReportAsync(productName, version, analysisReport);
// Run the analysis
await _analyzer.AnalyzeAndPersistResultsAsync(productName, version);
return Accepted();
}
}
}
|
//////////////////////////////////////////////////////////////////////////
#pragma once
#include "Graphics.hpp"
#include "CPF/Graphics/iImage.hpp"
#include "CPF/Graphics/ImageDesc.hpp"
#include "DescriptorManager.hpp"
namespace CPF
{
namespace Graphics
{
struct ClearValue;
}
namespace Adapter
{
namespace D3D12
{
class Image : public tRefCounted<Graphics::iImage>
{
public:
Image(ID3D12Resource* resource);
Image(Device*, Graphics::HeapType heap, const Graphics::ClearValue* clearValue, const Graphics::ImageDesc* desc);
virtual ~Image();
GOM::Result CPF_STDCALL QueryInterface(uint64_t id, void** outIface) override;
bool Map(void**, const Graphics::Range* = nullptr) override;
void Unmap(const Graphics::Range* range) override;
GOM::Result GetDesc(Graphics::ImageDesc* desc) const override;
ID3D12Resource* GetResource();
const D3D12_SHADER_RESOURCE_VIEW_DESC* GetResourceViewDesc() const { return &mResourceView; }
const Descriptor& GetDescriptor() const { return mDescriptor; }
private:
IntrusivePtr<ID3D12Resource> mpResource;
Graphics::ImageDesc mDesc;
Descriptor mDescriptor;
D3D12_SHADER_RESOURCE_VIEW_DESC mResourceView;
};
}
}
}
|
//// [FunctionDeclaration12_es6.ts]
var v = function * yield() { }
//// [FunctionDeclaration12_es6.js]
var v = function* () { }, yield = () => { };
|
#include <cstdio>
#include <vector>
#include <cstring>
#define N 1100
int vis[N], g[N][N], deg[N], n, m;
int dfs(int u)
{
int res = 0;
vis[u] = 1;
++res;
for (int i = 1; i <= n; ++i) {
if (g[u][i] == 1 && vis[i] == 0) {
res += dfs(i);
}
}
return res;
}
int main(void)
{
scanf("%d", &n);
while (n != 0) {
scanf("%d", &m);
memset(g, 0, sizeof(g));
memset(deg, 0, sizeof(deg));
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= m; ++i) {
int u, v;
scanf("%d%d", &u, &v);
g[u][v] = 1;
g[v][u] = 1;
deg[u]++;
deg[v]++;
}
int flag = 0;
for (int i = 1; i <= n; ++i) {
if (deg[i] % 2 == 1) {
flag = -1;
break;
}
}
if (flag == 0) {
if (dfs(1) == n) {
printf("1\n");
} else {
printf("0\n");
}
} else {
printf("0\n");
}
scanf("%d", &n);
}
return 0;
}
|
import React from 'react'
import ReactDOM from 'react-dom'
export default class Topbar extends React.Component {
constructor(props) {
super(props);
this.handleSearchChange = this.handleSearchChange.bind(this);
this.sortByTitle = this.sortByTitle.bind(this);
this.sortByYear = this.sortByYear.bind(this);
this.sortByRating = this.sortByRating.bind(this);
this.showMovies = this.showMovies.bind(this);
this.showSeries = this.showSeries.bind(this);
this.show = "movie"
}
handleSearchChange(e) {
this.props.onSearchChange(e.target.value);
}
sortByTitle(e) {
let sortby = this.props.sortBy;
if (sortby[0] == 'title')
sortby[1] *= -1;
sortby[0] = 'title';
this.props.onSortChange(sortby);
}
sortByYear(e) {
let sortby = this.props.sortBy;
if (sortby[0] == 'year')
sortby[1] *= -1;
sortby[0] = 'year';
this.props.onSortChange(sortby);
}
sortByRating(e) {
let sortby = this.props.sortBy;
if (sortby[0] == 'imdbrating')
sortby[1] *= -1;
sortby[0] = 'imdbrating';
this.props.onSortChange(sortby);
}
showMovies() {
this.show = "movie";
this.props.onTypeChange("movie");
}
showSeries() {
this.show = "series";
this.props.onTypeChange("series");
}
render() {
let sortClass = "";
if (this.props.sortBy[0] == 'imdbrating')
sortClass += "rating "
else
sortClass += this.props.sortBy[0] + " "
sortClass += (this.props.sortBy[1] > 0) ? "asc" : "desc";
return (
<div id="topbar" className={this.props.className}>
<div id="types">
<div className={"type " + ((this.show == "movie") ? 'selected' : '')} onClick={this.showMovies}>Movies</div>
<div className={"type " + ((this.show == "series") ? 'selected' : '')} onClick={this.showSeries}>Series</div>
</div>
<input id="searchbar" value={this.props.searchQuery} onChange={this.handleSearchChange} placeholder="Search by title, actors, directors, plot etc.." />
<div id="sort" className={sortClass}>
<div className="sort-option sortby-title" onClick={this.sortByTitle}>Title</div>
<div className="sort-option sortby-year" onClick={this.sortByYear}>Year</div>
<div className="sort-option sortby-rating" onClick={this.sortByRating}>Rating</div>
</div>
</div>
);
}
}
|
<?php
/* @var $this DefaultController */
/* @var $data array */
?>
<div class="view">
<b>
<?php echo CHtml::encode('Format'); ?>:
</b>
<?php echo CHtml::encode($data['format']); ?>
<br />
<b>
<?php echo CHtml::encode('Sequence'); ?>:
</b>
<?php
echo CHtml::textArea('result', $data['sequence'], array(
'readonly'=>'readonly',
)); ?>
<br />
</div>
|
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
var PATH_REGEXP = new RegExp([
// Match already escaped characters that would otherwise incorrectly appear
// in future matches. This allows the user to escape special characters that
// shouldn't be transformed.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?"]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined]
'([\\/.])?(?:\\:(\\w+)(?:\\(((?:\\\\.|[^)])*)\\))?|\\(((?:\\\\.|[^)])*)\\))([+*?])?',
// Match regexp special characters that should always be escaped.
'([.+*?=^!:${}()[\\]|\\/])'
].join('|'), 'g');
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {String} group
* @return {String}
*/
function escapeGroup(group) {
return group.replace(/([=!:$\/()])/g, '\\$1');
}
/**
* Attach the keys as a property of the regexp.
*
* @param {RegExp} re
* @param {Array} keys
* @return {RegExp}
*/
var attachKeys = function (re, keys) {
re.keys = keys;
return re;
};
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array should be passed in, which will contain the placeholder key
* names. For example `/user/:id` will then contain `["id"]`.
*
* @param {(String|RegExp|Array)} path
* @param {Array} keys
* @param {Object} options
* @return {RegExp}
*/
export function pathToRegexp(path, keys?, options?) {
if (keys && !Array.isArray(keys)) {
options = keys;
keys = null;
}
keys = keys || [];
options = options || {};
var strict = options.strict;
var end = options.end !== false;
var flags = options.sensitive ? '' : 'i';
var index = 0;
if (path instanceof RegExp) {
// Match all capturing groups of a regexp.
var groups = path.source.match(/\((?!\?)/g) || [];
// Map all the matches to their numeric keys and push into the keys.
keys.push.apply(keys, groups.map(function (match, index) {
return {
name: index,
delimiter: null,
optional: false,
repeat: false
};
}));
// Return the source back to the user.
return attachKeys(path, keys);
}
if (Array.isArray(path)) {
// Map array parts into regexps and return their source. We also pass
// the same keys and options instance into every generation to get
// consistent matching groups before we join the sources together.
path = path.map(function (value) {
return pathToRegexp(value, keys, options).source;
});
// Generate a new regexp instance by joining all the parts together.
return attachKeys(new RegExp('(?:' + path.join('|') + ')', flags), keys);
}
// Alter the path string into a usable regexp.
path = path.replace(PATH_REGEXP, function (match, escaped, prefix, key, capture, group, suffix, escape) {
// Avoiding re-escaping escaped characters.
if (escaped) {
return escaped;
}
// Escape regexp special characters.
if (escape) {
return '\\' + escape;
}
var repeat = suffix === '+' || suffix === '*';
var optional = suffix === '?' || suffix === '*';
keys.push({
name: key || index++,
delimiter: prefix || '/',
optional: optional,
repeat: repeat
});
// Escape the prefix character.
prefix = prefix ? '\\' + prefix : '';
// Match using the custom capturing group, or fallback to capturing
// everything up to the next slash (or next period if the param was
// prefixed with a period).
capture = escapeGroup(capture || group || '[^' + (prefix || '\\/') + ']+?');
// Allow parameters to be repeated more than once.
if (repeat) {
capture = capture + '(?:' + prefix + capture + ')*';
}
// Allow a parameter to be optional.
if (optional) {
return '(?:' + prefix + '(' + capture + '))?';
}
// Basic parameter support.
return prefix + '(' + capture + ')';
});
// Check whether the path ends in a slash as it alters some match behaviour.
var endsWithSlash = path[path.length - 1] === '/';
// In non-strict mode we allow an optional trailing slash in the match. If
// the path to match already ended with a slash, we need to remove it for
// consistency. The slash is only valid at the very end of a path match, not
// anywhere in the middle. This is important for non-ending mode, otherwise
// "/test/" will match "/test//route".
if (!strict) {
path = (endsWithSlash ? path.slice(0, -2) : path) + '(?:\\/(?=$))?';
}
// In non-ending mode, we need prompt the capturing groups to match as much
// as possible by using a positive lookahead for the end or next path segment.
if (!end) {
path += strict && endsWithSlash ? '' : '(?=\\/|$)';
}
return attachKeys(new RegExp('^' + path + (end ? '$' : ''), flags), keys);
};
|
import time
import logging
log = logging.getLogger(__name__)
class NeedRegenerationException(Exception):
"""An exception that when raised in the 'with' block,
forces the 'has_value' flag to False and incurs a
regeneration of the value.
"""
NOT_REGENERATED = object()
class Lock(object):
"""Dogpile lock class.
Provides an interface around an arbitrary mutex
that allows one thread/process to be elected as
the creator of a new value, while other threads/processes
continue to return the previous version
of that value.
.. versionadded:: 0.4.0
The :class:`.Lock` class was added as a single-use object
representing the dogpile API without dependence on
any shared state between multiple instances.
:param mutex: A mutex object that provides ``acquire()``
and ``release()`` methods.
:param creator: Callable which returns a tuple of the form
(new_value, creation_time). "new_value" should be a newly
generated value representing completed state. "creation_time"
should be a floating point time value which is relative
to Python's ``time.time()`` call, representing the time
at which the value was created. This time value should
be associated with the created value.
:param value_and_created_fn: Callable which returns
a tuple of the form (existing_value, creation_time). This
basically should return what the last local call to the ``creator()``
callable has returned, i.e. the value and the creation time,
which would be assumed here to be from a cache. If the
value is not available, the :class:`.NeedRegenerationException`
exception should be thrown.
:param expiretime: Expiration time in seconds. Set to
``None`` for never expires. This timestamp is compared
to the creation_time result and ``time.time()`` to determine if
the value returned by value_and_created_fn is "expired".
:param async_creator: A callable. If specified, this callable will be
passed the mutex as an argument and is responsible for releasing the mutex
after it finishes some asynchronous value creation. The intent is for
this to be used to defer invocation of the creator callable until some
later time.
.. versionadded:: 0.4.1 added the async_creator argument.
"""
def __init__(self,
mutex,
creator,
value_and_created_fn,
expiretime,
async_creator=None,
):
self.mutex = mutex
self.creator = creator
self.value_and_created_fn = value_and_created_fn
self.expiretime = expiretime
self.async_creator = async_creator
def _is_expired(self, createdtime):
"""Return true if the expiration time is reached, or no
value is available."""
return not self._has_value(createdtime) or \
(
self.expiretime is not None and
time.time() - createdtime > self.expiretime
)
def _has_value(self, createdtime):
"""Return true if the creation function has proceeded
at least once."""
return createdtime > 0
def _enter(self):
value_fn = self.value_and_created_fn
try:
value = value_fn()
value, createdtime = value
except NeedRegenerationException:
log.debug("NeedRegenerationException")
value = NOT_REGENERATED
createdtime = -1
generated = self._enter_create(createdtime)
if generated is not NOT_REGENERATED:
generated, createdtime = generated
return generated
elif value is NOT_REGENERATED:
try:
value, createdtime = value_fn()
return value
except NeedRegenerationException:
raise Exception("Generation function should "
"have just been called by a concurrent "
"thread.")
else:
return value
def _enter_create(self, createdtime):
if not self._is_expired(createdtime):
return NOT_REGENERATED
async = False
if self._has_value(createdtime):
if not self.mutex.acquire(False):
log.debug("creation function in progress "
"elsewhere, returning")
return NOT_REGENERATED
else:
log.debug("no value, waiting for create lock")
self.mutex.acquire()
try:
log.debug("value creation lock %r acquired" % self.mutex)
# see if someone created the value already
try:
value, createdtime = self.value_and_created_fn()
except NeedRegenerationException:
pass
else:
if not self._is_expired(createdtime):
log.debug("value already present")
return value, createdtime
elif self.async_creator:
log.debug("Passing creation lock to async runner")
self.async_creator(self.mutex)
async = True
return value, createdtime
log.debug("Calling creation function")
created = self.creator()
return created
finally:
if not async:
self.mutex.release()
log.debug("Released creation lock")
def __enter__(self):
return self._enter()
def __exit__(self, type, value, traceback):
pass
|
import mechanicalsoup
import resolve
import time
@when(u'you get {url}')
def step_impl(context, url):
url = resolve.url(context, url)
context.log.info('getting url {}'.format(url))
context.browser = mechanicalsoup.StatefulBrowser()
attempt = 0
while True:
attempt += 1
resp = context.browser.open(url)
if resp.status_code < 500:
context.log.info('GET {} [{}]'.format(url, resp.status_code))
resp.status_code.should.equal(200)
break
context.log.info('failed to get {} [{}]'.format(url, resp.status_code))
if attempt > 5:
raise Exception('Unable to get page {} [{}]'.format(url, resp.status_code))
time.sleep(1)
@when(u'you post "{data}" to {url}')
def step_impl(context, data, url):
url = resolve.url(context, url)
fields = data.split('=')
assert len(fields) == 2, 'Invalid data format: {}'.format(data)
payload = { fields[0]: fields[1] }
context.log.info('posting url {} {}'.format(url, payload))
context.browser = mechanicalsoup.StatefulBrowser()
resp = context.browser.post(url, data=payload)
context.log.info('POST {} [{}]'.format(url, resp.status_code))
@when(u'you login with "{username}"/"{password}"')
def step_impl(context, username, password):
context.browser.select_form('form[action="/login.do"]')
context.browser['username'] = username
context.browser['password'] = password
context.browser.submit_selected()
@then(u'you should be at {url}')
def step_impl(context, url):
context.browser.get_url().should.match(r'{}(\?.*)?'.format(resolve.url(context, url)))
@then(u'you should see "{text}"')
def step_impl(context, text):
context.browser.get_current_page().get_text().should.match(r'.*{}.*'.format(text))
|
import {ReactNode} from "react";
import {CSSProp, useTheme} from "@focus4/styling";
import {layoutCss, LayoutCss} from "./layout";
export function Content(props: {children?: ReactNode; theme?: CSSProp<LayoutCss>}) {
const theme = useTheme("layout", layoutCss, props.theme);
return <div className={theme.content()}>{props.children}</div>;
}
|
import os
SOURCE_EXT_LIST = ['.cpp', '.cc', '.c', '.cxx']
HEADER_EXT_LIST = ['.h', '.inc', '.hpp', '.inl']
def update_src_lists(var_name, out_file_path, source_folder=None, append=False,
root_folder=None, source_ext_list=SOURCE_EXT_LIST,
header_ext_list=HEADER_EXT_LIST):
if source_folder is None:
source_folder = os.path.dirname(out_file_path)
if root_folder is None:
root_folder = os.path.commonprefix(
[os.path.dirname(out_file_path), source_folder])
header_list = ""
source_list = ""
for dirpath, dirnames, files in os.walk(source_folder):
for file_name in files:
ext = os.path.splitext(file_name)[1]
if ext in source_ext_list:
source_list += ("\n\t" + os.path.relpath(
os.path.join(dirpath, file_name), root_folder))
elif ext in header_ext_list:
header_list += ("\n\t" + os.path.relpath(
os.path.join(dirpath, file_name), root_folder))
out_text = ""
if header_list:
out_text += 'set({}_HEADERS{}\n)\n\n'.format(
var_name, header_list.replace("\\", "/"))
if source_list:
out_text += 'set({}_SOURCES{}\n)\n\n'.format(
var_name, source_list.replace("\\", "/"))
if os.path.isfile(out_file_path) and open(out_file_path).read() == out_text:
return
with open(out_file_path, "a" if append else "w") as file:
file.write(out_text)
|
# -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2013 Michal Čihař <[email protected]>
#
# This file is part of Weblate <http://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Tests for user handling.
"""
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User, Group
from django.core import mail
from django.core.management import call_command
class RegistrationTest(TestCase):
def test_register(self):
response = self.client.post(
reverse('weblate_register'),
{
'username': 'username',
'email': '[email protected]',
'password1': 'password',
'password2': 'password',
'first_name': 'First',
'last_name': 'Last',
}
)
# Check we did succeed
self.assertRedirects(response, reverse('registration_complete'))
# Check registration mail
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
'Your registration on Weblate'
)
# Get confirmation URL from mail
line = ''
for line in mail.outbox[0].body.splitlines():
if line.startswith('http://example.com'):
break
# Confirm account
response = self.client.get(line[18:])
self.assertRedirects(
response,
reverse('registration_activation_complete')
)
user = User.objects.get(username='username')
# Verify user is active
self.assertTrue(user.is_active)
# Verify stored first/last name
self.assertEqual(user.first_name, 'First')
self.assertEqual(user.last_name, 'Last')
class CommandTest(TestCase):
'''
Tests for management commands.
'''
def test_createadmin(self):
call_command('createadmin')
user = User.objects.get(username='admin')
self.assertEqual(user.first_name, 'Weblate')
self.assertEqual(user.last_name, 'Admin')
def test_setupgroups(self):
call_command('setupgroups')
group = Group.objects.get(name='Users')
self.assertTrue(
group.permissions.filter(
codename='save_translation'
).exists()
)
|
/*
This file is part of Zen Beat.
Zen Beat is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Zen Beat is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Zen Beat. If not, see <http://www.gnu.org/licenses/>.
*/
package com.game.zen.beat;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.SoundPool;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class HowToActivity extends ActionBarActivity {
public static final String PREFS_NAME = "ZenBeatPrefs";
MediaPlayer mp;
protected float level;
protected int sound1, sound2, sound3, sound4, sound5, sound6, sound7, sound8;
protected SoundPool sp;
protected static final int vol = 1;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.try_notes_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_to_game:
Intent intent = new Intent(getApplicationContext(), GameActivity.class);
startActivity(intent);
break;
case R.id.action_settings:
Intent intent1 = new Intent(getBaseContext(), SettingsActivity.class);
startActivity(intent1);
return true;
default: break;
}
return true;
}
private OnClickListener Ocl1 = new OnClickListener() {
public void onClick(View v) {
sp.play(sound1, vol, vol, 1, 0, 1f);
}
};
private OnClickListener Ocl2 = new OnClickListener() {
public void onClick(View v) {
sp.play(sound2, vol, vol, 1, 0, 1f);
}
};
private OnClickListener Ocl3 = new OnClickListener() {
public void onClick(View v) {
if ( level >= 2) {
sp.play(sound3, vol, vol, 1, 0, 1f);
}
}
};
private OnClickListener Ocl4 = new OnClickListener() {
public void onClick(View v) {
if ( level >= 2) {
sp.play(sound4, vol, vol, 1, 0, 1f);
}
}
};
private OnClickListener Ocl5 = new OnClickListener() {
public void onClick(View v) {
if ( level >= 7) {
sp.play(sound5, vol, vol, 1, 0, 1f);
}
}
};
private OnClickListener Ocl6 = new OnClickListener() {
public void onClick(View v) {
if ( level >= 7) {
sp.play(sound6, vol, vol, 1, 0, 1f);
}
}
};
private OnClickListener Ocl7 = new OnClickListener() {
public void onClick(View v) {
if ( level >= 11) {
sp.play(sound7, vol, vol, 1, 0, 1f);
}
}
};
private OnClickListener Ocl8 = new OnClickListener() {
public void onClick(View v) {
if ( level >= 11) {
sp.play(sound8, vol, vol, 1, 0, 1f);
}
}
};
private OnClickListener Oclreplay = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), GameActivity.class);
startActivity(intent);
}
};
private OnCompletionListener Ocl = new OnCompletionListener() {
public void onCompletion(MediaPlayer media) {
mp.release();
dismissDialog(0);
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_ht);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
level = settings.getFloat("level", 0f);
sp = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
ImageView b1 = (ImageView)findViewById(R.id.b1);
b1.setOnClickListener(Ocl1);
ImageView b2 = (ImageView)findViewById(R.id.b2);
b2.setOnClickListener(Ocl2);
ImageView b3 = (ImageView)findViewById(R.id.b3);
b3.setOnClickListener(Ocl3);
ImageView b4 = (ImageView)findViewById(R.id.b4);
b4.setOnClickListener(Ocl4);
ImageView b5 = (ImageView)findViewById(R.id.b5);
b5.setOnClickListener(Ocl5);
ImageView b6 = (ImageView)findViewById(R.id.b6);
b6.setOnClickListener(Ocl6);
ImageView b7 = (ImageView)findViewById(R.id.b7);
b7.setOnClickListener(Ocl7);
ImageView b8 = (ImageView)findViewById(R.id.b8);
b8.setOnClickListener(Ocl8);
if (level < 11) {
b7.setVisibility(View.GONE);//8 = GONE
b7.setImageResource(R.drawable.trans);
b8.setVisibility(View.GONE);//8 = GONE
b8.setImageResource(R.drawable.trans);
}
if (level < 7) {
b5.setVisibility(View.GONE);//8 = GONE
b5.setImageResource(R.drawable.trans);
b6.setVisibility(View.GONE);//8 = GONE
b6.setImageResource(R.drawable.trans);
}
if (level < 2) {
b3.setVisibility(View.GONE);//8 = GONE
b3.setImageResource(R.drawable.trans);
b4.setVisibility(View.GONE);//8 = GONE
b4.setImageResource(R.drawable.trans);
}
sound2= sp.load(this, R.raw.s1, 1);
sound1= sp.load(this, R.raw.s2, 1);
sound4= sp.load(this, R.raw.s3, 1);
sound3= sp.load(this, R.raw.s4, 1);
sound6= sp.load(this, R.raw.s5, 1);
sound5= sp.load(this, R.raw.s6, 1);
sound8= sp.load(this, R.raw.s7, 1);
sound7= sp.load(this, R.raw.s8, 1);
}
}
|
End of preview. Expand
in Data Studio
Reactive AI / Beta Pre-Train Corpus
Pre-training corpus for RxT-Beta models, created from public & open datasets. Includes high-quality english and polish web crawl data, mathematic and scientific subsets, and code in different programming languages
Subsets & original datasets
- FineWeb-Edu
fineweb-edu-s100(51.3M examples) - 50% of 'sample-100BT' subsetfineweb-edu-2025-26(14M examples) - CC-MAIN-2025-26 subset - latest crawl
- FineWiki
finewiki-en(6.6M examples) - english wikipedia subsetfinewiki-pl(1.5M examples) - polish wikipedia subset
- FineWeb2-HQ
fineweb2-hq-pl(13.3M examples) - high-quality filtered polish web crawl
- FineMath
finemath-4plus(6.7M examples)infiwebmath-4plus(6.3M examples)
- ProofPile-2
pp2-arxiv(4M examples) - arXiv research papers
- Notebooks:
kaggle(0.58M examples) - from HuggingFaceTB/issues-kaggle-notebooksgithub-jupyter(0.05M examples) - from codeparrot/github-jupyter-code-to-text
- Downloads last month
- 145