text stringlengths 1 1.05M |
|---|
<gh_stars>0
package org.springaop.chapter.three;
import org.springaop.chapter.three.domain.Command;
import org.springaop.chapter.three.domain.PersonUser;
import org.springaop.chapter.three.domain.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ProxyFactoryBeanTest {
public static void main(String[] args) {
String[] paths = { "org/springaop/chapter/three/applicationContext.xml" };
ApplicationContext ctx = new ClassPathXmlApplicationContext(paths);
User user = (User) ctx.getBean("user");
user.getName();
Command command = (Command) ctx.getBean("command");
command.execute();
PersonUser person = (PersonUser) ctx.getBean("personUser");
person.getName();
}
}
|
<filename>pub-ediff/hico-dropreceiver.js
import { HTMLBindable } from "./hico-htmlbindable.js";
export class DropReceiver extends HTMLBindable {
constructor(html_element) {
if(!html_element instanceof EventTarget)
throw new TypeError("Argument of DropReceiver must be a HTMLElement + EventTarget");
super(html_element);
this.on_dragenter = null;
this.on_dragleave = null;
this.on_received = null;
this._entered_level = null;
const me = this;
this._on_dragenter = (ev)=>{
ev.preventDefault();
if(me._entered_level === null) {
if(me.on_dragenter !== null)
me.on_dragenter(ev, me);
me._entered_level = [];
}
me._entered_level.push(ev.target);
};
this._on_dragleave = (ev)=>{
ev.preventDefault();
if(me._entered_level === null) {
me.on_dragleave(ev, me);
return;
}
if(me._entered_level.length == 1) {
me._entered_level = null;
if(me.on_dragleave !== null)
me.on_dragleave(ev, me);
}
else
me._entered_level.pop();
};
this._on_dragover = (ev)=>{
ev.preventDefault();
};
this._on_drop = (ev)=>{
ev.preventDefault();
me._entered_level = null;
if(me.on_received !== null)
me.on_received(ev, me);
};
this._on_dragend = (ev)=>{
ev.preventDefault();
if(me.on_dragenter !== null)
me.on_dragleave(ev, me);
me._entered_level = null;
};
html_element.addEventListener("dragenter", this._on_dragenter);
html_element.addEventListener("dragleave", this._on_dragleave);
html_element.addEventListener("dragover", this._on_dragover);
html_element.addEventListener("drop", this._on_drop);
html_element.addEventListener("dragend", this._on_dragend);
}
unbind() {
const html_element = this.raw_html_element;
this.on_dragenter = null;
this.on_dragleave = null;
this.on_received = null;
html_element.removeEventListener("dragenter", this._on_dragenter);
html_element.removeEventListener("dragleave", this._on_dragleave);
html_element.removeEventListener("dragover", this._on_dragover);
html_element.removeEventListener("drop", this._on_drop);
html_element.removeEventListener("dragend", this._on_dragend);
super.unbind();
}
} |
'''
This simple WebSocket server responds to text messages by reversing each
message string and sending it back.
It also handles ping/pong automatically and will correctly close down a
connection when the client requests it.
To use SSL/TLS: install the `trustme` package from PyPI and run the
`generate-cert.py` script in this directory.
'''
import argparse
import logging
import pathlib
import ssl
import sys
import trio
from trio_websocket import serve_websocket, ConnectionClosed
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
here = pathlib.Path(__file__).parent
def parse_args():
''' Parse command line arguments. '''
parser = argparse.ArgumentParser(description='Example trio-websocket client')
parser.add_argument('--ssl', action='store_true', help='Use SSL')
parser.add_argument('host', help='Host interface to bind. If omitted, '
'then bind all interfaces.', nargs='?')
parser.add_argument('port', type=int, help='Port to bind.')
return parser.parse_args()
async def main(args):
''' Main entry point. '''
logging.info('Starting websocket server…')
if args.ssl:
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
try:
ssl_context.load_cert_chain(here / 'fake.server.pem')
except FileNotFoundError:
logging.error('Did not find file "fake.server.pem". You need to run'
' generate-cert.py')
else:
ssl_context = None
host = None if args.host == '*' else args.host
await serve_websocket(handler, host, args.port, ssl_context)
async def handler(request):
''' Reverse incoming websocket messages and send them back. '''
logging.info('Handler starting on path "%s"' % request.path)
ws = await request.accept()
while True:
try:
message = await ws.get_message()
await ws.send_message(message[::-1])
except ConnectionClosed:
logging.info('Connection closed')
break
logging.info('Handler exiting')
if __name__ == '__main__':
try:
trio.run(main, parse_args())
except KeyboardInterrupt:
print()
|
module.exports = {
...require("@shared/prettier-config"),
endOfLine: "lf",
};
|
<reponame>Kameen744/mcc-cbt-laravel
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["noprefetch-Add-RKSJ-V-bcmap"],{
/***/ "./node_modules/raw-loader/index.js!./node_modules/pdfjs-dist/cmaps/Add-RKSJ-V.bcmap":
/*!**********************************************************************************!*\
!*** ./node_modules/raw-loader!./node_modules/pdfjs-dist/cmaps/Add-RKSJ-V.bcmap ***!
\**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = "\u0003�RCopyright 1990-2009 Adobe Systems Incorporated.\nAll rights reserved.\nSee ./LICENSE�\nAdd-RKSJ-Ha\u000b�A\u0001�O\u0000\u0000�L\u0000\u0000�R\u000b\u0001�Q\t\u0002�S\u0002\u0004�V\u0000\u0000�Z\u0000\u0000�S\u0000\u0000�X\u0000\u0000�U\u0000\u0011�[A\n���n\u0001\u0000\u0001\u0000\u0001\u0000\u0001\u0000\u0019\u0000\u001f\u0000\u0001\u0000\u0001\u0000\u0006\u0000a\u0001��\u0001�HA\n�@�x\u0001\u0000\u0001\u0000\u0001\u0000\u0001\u0000\u0019\u0000 \u0000\u0001\u0000\u0001\u0000\u0006\u0000a\u0007��\u0001�\u0002��a\u0000�\u0007\u0000\u0000�\u0004\u0000\u0000�\t\u0000\u0000�\u0005\u0000\u0000�\n\u0000\u0001�\u0013Q\u000b쀾\t�\u0010�\u000f\u0006�\u0018�\u0017\u0007�\u0012\u0004�\u0013�\ba\u0007�\u0001�\u001d\u0000\u0000�&\u0000\u0000�%\u0000\u0000�!\u0000\u0000�$\u0004\u0000�\u0004�|\u0000�\r"
/***/ })
}]); |
angular
.module('app.core')
.directive('lineChart', lineChart);
function lineChart() {
return {
restrict: 'C',
template: '<div></div>',
scope: {
title: '@',
data: '=',
config: '=',
errormsg: '@',
drilldownurl: '&drilldownurl',
chartfilter: '=',
charttype: '@'
},
link: function (scope, element) {
scope.$watch('data', function () {
var data = [{
"date": 2015,
"Member_Only": 2,
"Leadership_Role": 89,
"Committee_Member": 59,
}, {
"date": 2016,
"Member_Only": 2,
"Leadership_Role": 9,
"Committee_Member": 9,
},
{
"date": 2017,
"Member_Only": 12,
"Leadership_Role": 19,
"Committee_Member": 39,
},
{
"date": 2018,
"Member_Only": 20,
"Leadership_Role": 189,
"Committee_Member": 359,
}
];
$(element).igCategoryChart({
width: "98%",
height: "400px",
legend: {
element: "legend3",
type: 'legend',
width: "98%"
},
title: "Refining & Supply (Org Lvl 1) Participations Over Time",
titleTextColor: "black",
titleTextStyle: "11pt Verdona",
titleBottomMargin: 10,
// subtitle: "$$(Chart_subtitle_countries_1995_v_2005)",
yAxisTitle: "Count of ID",
xAxisTitle: "pDate Added",
dataSource: data,
chartType: "line",
isHorizontalZoomEnabled: false,
isVerticalZoomEnabled: false
});
});
}
};
} |
<filename>RRTS/HttpUnit/httpunit-1.7/test/com/meterware/httpunit/javascript/FrameScriptingTest.java
package com.meterware.httpunit.javascript;
/********************************************************************************************************************
* $Id: FrameScriptingTest.java 659 2004-08-08 17:38:19Z russgold $
*
* Copyright (c) 2003-2004, <NAME>
*
* 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.
*
*******************************************************************************************************************/
import com.meterware.httpunit.*;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* More complex tests of frame functionality.
*
* @author <a href="<EMAIL>"><NAME></a>
* @author <a href="<EMAIL>"><NAME></a>
**/
public class FrameScriptingTest extends HttpUnitTest {
private WebConversation _wc;
public static void main(String args[]) {
junit.textui.TestRunner.run( suite() );
}
public static Test suite() {
return new TestSuite( FrameScriptingTest.class );
}
public FrameScriptingTest( String name ) {
super( name );
}
public void setUp() throws Exception {
super.setUp();
_wc = new WebConversation();
defineWebPage( "Simple", "This is a trivial page." );
defineResource("image.gif", new byte[]{0, 1, 0, 1}, "image/gif");
defineWebPage("Menu/Page/Target", "Target page");
StringBuffer buff = new StringBuffer();
buff.append("This frame contains JavaScript that re-writes the \"red\" frame if it exists.\n");
buff.append("<script language=\"JavaScript\">\n");
buff.append("if (window.parent.red) {\n");
buff.append(" window.parent.red.document.open(\"text/html\")\n");
buff.append(" with (window.parent.red.document) {\n");
final String[] lines = getMenuHtmlLines(getHostPath() + "/Menu/Page/Main.html", "Target.html");
for (int i = 0; i < lines.length; i++) {
buff.append(" write('").append(lines[i]).append("\\n").append("');\n");
}
buff.append(" close();\n");
buff.append(" }\n");
buff.append("}\n");
buff.append("</script>\n");
defineWebPage("frameRewriter", buff.toString());
}
/**
* Creates and returns the lines of HTML to represent a menu page with
* a <code><base ...></code> tag and one link.
* Used where the formulated HTML is to be embedded in JavaScript.
* @param baseUrlString URL string to be used in the href of the 'base' tag.
* @param linkUrlString URL string to be used in the href of the link.
* @return String array representing the lines of HTML.
*/
private String[] getMenuHtmlLines(String baseUrlString, String linkUrlString) {
return new String[]{
"<html><head><title>Menu</title>",
"<base href=\"" + baseUrlString + "\" target=\"blue\"></base>",
"</head>",
"<body>",
"This is the menu.<br>",
"Link to <a href=\""+linkUrlString+"\">target page</a>.",
"</body></html>"};
}
/**
* Creates and returns HTML to represent a menu page with a <code><base ...></code> tag and one link.
* @param baseUrlString URL string to be used in the href of the 'base' tag.
* @param linkUrlString URL string to be used in the href of the link.
* @return String representing the HTML.
*/
private String getMenuHtml(final String baseUrlString, final String linkUrlString) {
final String[] menuLines = getMenuHtmlLines(baseUrlString, linkUrlString);
StringBuffer pageBuffer = new StringBuffer();
for (int i = 0; i < menuLines.length; i++) {
String line = menuLines[i];
pageBuffer.append(line).append("\n");
}
return pageBuffer.toString();
}
/**
* (Re)defines the web page 'Frames.html', which is a frameset containing 'red' and 'blue' frames.
* @param redSrc The source URL string for the 'red' frame.
* @param blueSrc The source URL string for the 'blue' frame.
*/
private void redefineFrames(String redSrc, String blueSrc) {
defineResource("Frames.html",
"<HTML><HEAD><TITLE>Frameset</TITLE></HEAD>" +
"<FRAMESET cols=\"20%,80%\">" +
" <FRAME src=\""+redSrc+"\" name=\"red\">" +
" <FRAME src=\""+blueSrc+"\" name=\"blue\">" +
"</FRAMESET></HTML>");
}
/**
* Test that an image can be used as the source for a frame within a frameset.
*/
public void testImageInFrame() throws Exception {
redefineFrames("/image.gif", "Simple.html");
_wc.getResponse( getHostPath() + "/Frames.html" );
WebResponse redFrame = _wc.getFrameContents("red");
assertEquals("Red frame content-type", "image/gif", redFrame.getContentType());
}
/**
* Test that a link within a frame that contains a <code><base ...></code> element is handled correctly.
*/
public void testFrameContainingBaseElement() throws Exception {
final String TARGET_TITLE = "Somewhere/Else/Target";
defineWebPage( TARGET_TITLE, "This is the target page." );
defineWebPage( "Main", "This is a simple page.");
defineResource( "BaseRelLinker.html", getMenuHtml(getHostPath() + "/Somewhere/Near/", "../Else/Target.html") );
redefineFrames("BaseRelLinker.html", "Main.html");
_wc.getResponse( getHostPath() + "/Frames.html" );
WebLink link = _wc.getFrameContents( "red" ).getLinks()[0];
link.click();
assertEquals("Content of blue frame after link click", TARGET_TITLE, _wc.getFrameContents("blue").getTitle());
}
/**
* Test correct handling of a link within a frame that has been re-written by JavaScript,
* and which contains a <code><base ...></code> element.
*/
public void testFrameRewrittenToUseBaseElement() throws Exception {
redefineFrames("/Simple.html", "frameRewriter.html");
_wc.getResponse(getHostPath() + "/Frames.html");
WebLink link = _wc.getFrameContents("red").getLinks()[0];
link.click();
assertEquals("Content of blue frame after clicking menu link", "Menu/Page/Target", _wc.getFrameContents("blue").getTitle());
}
/**
* Test correct handling of a link within a frame that has been re-written by JavaScript over an image,
* and which contains a <code><base ...></code> element.
*/
public void testImageFrameRewrittenToUseBaseElement() throws Exception {
redefineFrames("/image.gif", "frameRewriter.html");
_wc.getResponse(getHostPath() + "/Frames.html");
WebLink link = _wc.getFrameContents("red").getLinks()[0];
link.click();
assertEquals("Content of blue frame after clicking menu link", "Menu/Page/Target", _wc.getFrameContents("blue").getTitle());
}
/**
* Verifies that a javascript URL which triggers refresh to the parent of a frame resolves with something sensible.
*/
public void testJavaScriptURLToParentFrame() throws Exception {
defineResource( "Frames.html",
"<HTML><HEAD><TITLE>Initial</TITLE></HEAD>" +
"<FRAMESET cols=\"20%,80%\">" +
" <FRAME src='Linker.html' name='red'>" +
" <FRAME src=Form name=blue>" +
"</FRAMESET></HTML>" );
defineWebPage( "Linker", "This is a trivial page with <a href='javascript:window.parent.location.replace( \"Target\" );'>one link</a>" );
defineResource( "Form", "This is a page with nothing we care about");
defineResource( "Target", "You made it!", "text/plain" );
_wc.getResponse( getHostPath() + "/Frames.html" );
WebResponse result = _wc.getFrameContents( "red" ).getLinkWith( "one link" ).click();
assertEquals( "Result of click", "You made it!", result.getText() );
}
/**
* Verifies that when JavaScript overwrites an empty frame, other empty frames stay empty.
*/
public void testJavaScriptOverwritingBlankFrame() throws Exception {
defineResource("Frames.html",
"<HTML><HEAD><TITLE>Initial</TITLE></HEAD>" +
"<FRAMESET>" +
" <FRAME src='Writer.html' name='red'>" +
" <FRAME name=green>" +
" <FRAME name=blue>" +
"</FRAMESET></HTML>");
defineWebPage("Writer", "This page overwrites an empty frame. <script language=\"JavaScript\">"
+ " window.parent.green.document.open(\"text/html\")\n"
+ " window.parent.green.document.write(\"Generated <a href=\\\"#\\\">link</a>\")\n"
+ " window.parent.green.document.close()\n"
+ "</script>");
_wc.getResponse(getHostPath() + "/Frames.html");
assertEquals("Links in green frame", 1, _wc.getFrameContents("green").getLinks().length);
assertEquals("Links in blue frame", 0, _wc.getFrameContents("blue").getLinks().length);
}
/**
* Verifies that the onload event of a frameset can access subframes.
*/
public void testFrameOnLoadEvent() throws Exception {
defineWebPage( "OneForm", "<form name='form'><input name=text value='nothing special'></form>");
defineResource("Frames.html",
"<html><frameset onload='alert( green.document.form.text.value );'>" +
" <frame src='OneForm.html' name='green'>" +
" <frame name=blue>" +
"</frameset></htmlL>");
_wc.getResponse(getHostPath() + "/Frames.html");
assertEquals( "On load message", "nothing special", _wc.popNextAlert() );
}
/**
* Verifies that the onload event of a frameset runs even if there is a noframes tag present that contains a body tag.
*/
public void testFrameOnLoadEventWithNoFrames() throws Exception {
defineWebPage( "OneForm", "<form name='form'><input name=text value='nothing special'></form>");
defineResource("Frames.html",
"<html><frameset onload='alert( green.document.form.text.value );'>" +
" <frame src='OneForm.html' name='green'>" +
" <frame name=blue>" +
" <noframes><body></body></noframes>" +
"</frameset></htmlL>");
_wc.getResponse(getHostPath() + "/Frames.html");
assertEquals( "On load message", "nothing special", _wc.popNextAlert() );
}
/**
* Verifies that IFrames can be found using their id.
*/
public void testIFrameAccessById() throws Exception {
defineWebPage( "Frames",
"<iframe id='frame1'></iframe>" +
"<script>" +
"var frame = document.getElementById('frame1');" +
"</script>" );
_wc.getResponse(getHostPath() + "/Frames.html");
}
}
|
import java.util.HashMap;
import java.util.Map;
public class Order {
private Map<String, Integer> orders = new HashMap<>();
private int orderTotal = 0;
public void createOrder (String[] orderItems, int[] quantities) {
for (int i = 0; i < orderItems.length; i++) {
orders.put(orderItems[i], quantities[i]);
orderTotal += quantities[i];
}
printOrder();
}
public void printOrder() {
for (Map.Entry<String, Integer> entry : orders.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
System.out.println("Order total: " + orderTotal);
}
public static void main(String[] args) {
Order order = new Order();
String[] orderItems = {"Pizza", "Drink"};
int[] quantities = {2, 5};
order.createOrder(orderItems, quantities);
String[] orderItems2 = {"Burger", "Drink"};
int[] quantities2 = {3, 2};
order.createOrder(orderItems2, quantities2);
}
} |
package com.zhcs.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zhcs.dao.SysRoleMenuDao;
import com.zhcs.service.SysRoleMenuService;
import com.zhcs.utils.DateUtil;
import com.zhcs.utils.ShiroUtils;
/**
* 角色与菜单对应关系
*
* @author Alter
* @email <EMAIL>
* @date 2016年9月18日 上午9:44:35
*/
@Service("sysRoleMenuService")
public class SysRoleMenuServiceImpl implements SysRoleMenuService {
@Autowired
private SysRoleMenuDao sysRoleMenuDao;
@Override
@Transactional
public void saveOrUpdate(Long roleId, List<Long> menuIdList) {
if(menuIdList.size() == 0){
return ;
}
//先删除角色与菜单关系
sysRoleMenuDao.delete(roleId);
//保存角色与菜单关系
Map<String, Object> map = new HashMap<String, Object>();
map.put("roleid", roleId);
map.put("menuIdList", menuIdList);
map.put("crtid", ShiroUtils.getUserId());
map.put("updid", ShiroUtils.getUserId());
map.put("crttm", DateUtil.getSystemDate());
map.put("updtm", DateUtil.getSystemDate());
sysRoleMenuDao.save(map);
}
@Override
public List<Long> queryMenuIdList(Long roleId) {
return sysRoleMenuDao.queryMenuIdList(roleId);
}
@Override
@Transactional
public void deleteBatch(Object[] id) {
sysRoleMenuDao.deleteBatch(id);
}
}
|
/*
* Jira Ticket:
* Created Date: Mon, 15th Feb 2021, 10:29:37 am
* Author: <NAME>
* Email: <EMAIL>
* Copyright (c) 2021 The Distance
*/
import gql from 'graphql-tag';
export default gql`
mutation UploadFailed($id: ID!) {
uploadFailed(id: $id)
}
`;
|
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
def peek(self):
if not self.is_empty():
return self.items[-1]
def get_stack(self):
return self.items |
<reponame>zhanpon/toy-jvm
public class StaticMethod {
public static void main(String[] args) {
System.out.println(add(1, 2));
}
public static int add(int m, int n) {
return m + n;
}
}
|
#!/bin/bash
fw_depends java7 maven
export JAVA_OPTS="-Xms2g -Xmx2g -XX:MaxPermSize=256m -XX:+UseG1GC -XX:MaxGCPauseMillis=25 -verbosegc -Xloggc:/tmp/wildfly_gc.log"
mvn clean initialize package -Pbenchmark -Ddatabase.host=${DBHOST}
target/wildfly-9.0.1.Final/bin/standalone.sh -b 0.0.0.0 &
|
<gh_stars>1-10
export const Conditions: {[k: string]: ConditionData} = {
chrienmor: {
name: 'Chrienmor',
onTypePriority: 1,
onType(types, pokemon) {
if (pokemon.transformed || pokemon.ability !== 'prism' && this.gen >= 8) return types;
let type: string | undefined = 'Normal';
if (pokemon.ability === 'prism') {
type = pokemon.getItem().onMemory;
if (!type) {
type = 'Normal';
}
}
return [type];
},
},
}; |
set -euo pipefail
name=forweb_cleaned_exac_r03_march16_z_data_pLI.txt.gz
if [[ ! -e "$name" ]]; then
wget ftp://ftp.broadinstitute.org/pub/ExAC_release/release1/manuscript_data/$name
fi
if [ ! -s pLI.bed.gz ]; then
python make.py $name | bgzip -c > pLI.bed.gz
tabix pLI.bed.gz
fi
|
<reponame>tsabitg23/comp6618036-tnca-week-4<filename>Source/Auth.cpp
#include "Auth.hpp"
#include <regex>
#include "Foundation.hpp"
// Only for admin
const String DEFAULT_SUPERUSER_PASSWORD = "<PASSWORD>";
const String DEFAULT_SUPERUSER_EMAIL = "<EMAIL>";
const String DEFAULT_SUPERUSER_NAME = "Superuser";
const String DEFAULT_SUPERUSER_ADDRESS = "0x0000001";
User Auth::createSuperuser() {
User user = User(DEFAULT_SUPERUSER_EMAIL, DEFAULT_SUPERUSER_PASSWORD);
user.profile.name = DEFAULT_SUPERUSER_NAME;
user.profile.address = DEFAULT_SUPERUSER_ADDRESS;
registedUserIdentifierMap.set(user.email, user.id);
registedUserMap.set(user.id, user);
return user;
}
bool Auth::isValidEmailFormat(String email) {
const std::regex pattern("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+");
return std::regex_match(email, pattern);
}
String Auth::getPasswordInput(String question) {
String password = readLineInput("Please input your password");
// Shouldn't contains 8 size
if (password.size() < 8) {
printError("Password is too weak. Please use at least 8 characters! \n");
return getPasswordInput(question);
}
// Shouldn't contains weak password
if (password == "<PASSWORD>" || password == "<PASSWORD>") {
printError("Password is too easy to gueast. Please use non common password! \n");
return getPasswordInput(question);
}
// Shouldn't contains whitespace
for (int i = 0; i < password.size(); i++) {
if (std::isspace(password[i])) {
printError("Password should not contains whitespace. Please try agin! \n");
return getPasswordInput(question);
}
}
return password;
}
// Handle user sign up flow
// Returns signed up user
User Auth::signUp() {
String email = readLineInput("Please input your email");
if (isValidEmailFormat(email) != true) {
printError("Invalid email format\n");
return signUp();
}
// Create usr
String password = getPasswordInput("Please input your password");
User user = User(email, password);
user.profile.name = readLineInput("Please input your name");
user.profile.address = readLineInput("Please input your address");
registedUserIdentifierMap.set(user.email, user.id);
registedUserMap.set(user.id, user);
printSuccess("User with email " + email + " has been created!\n");
currentUserIdentifier = user.id;
return user;
}
// // Handle sign in flow
// // Returns user signed in
User Auth::signIn() {
// Email validation
String email = readLineInput("Email");
if (registedUserIdentifierMap.contains(email) != true) {
printError("The user with given email not found\n");
return signIn();
}
// Password validation
String password = readLineInput("Password");
UserIdentifier id = registedUserIdentifierMap.get(email);
User user = registedUserMap.get(id);
if (!user.isPasswordMatched(password)) {
printError("The password is incorrect!\n");
return currentUser();
}
currentUserIdentifier = id;
return user;
}
Auth::Auth() {
menuItems.push_back("Sign In");
menuItems.push_back("Sign Up");
menuItems.push_back("Exit");
currentUserIdentifier = 0;
createSuperuser();
}
Auth::~Auth() {}
void Auth::signOut() {
currentUserIdentifier = 0;
}
// Get current authenticated user
// This will handle with sign up and sign in flow if required
User Auth::currentUser() {
if (currentUserIdentifier != 0) {
return registedUserMap.get(currentUserIdentifier);
}
String title = "Welcome!";
String question = "Please input the number associated with the menu";
int selected = readMenuInput(title, question, menuItems);
if (selected == 1) {
return signIn();
} else if (selected == 2) {
return signUp();
} else if(selected == 3) {
printError("Good bye!!");
throw "exit";
} else {
printError("The number you input doesn't match with available selections");
return currentUser();
}
} |
package malte0811.controlengineering.logic.schematic;
import com.google.common.collect.ImmutableList;
import it.unimi.dsi.fastutil.ints.IntArraySet;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntSet;
import malte0811.controlengineering.blockentity.logic.LogicCabinetBlockEntity;
import malte0811.controlengineering.logic.cells.CellCost;
import malte0811.controlengineering.logic.schematic.symbol.PlacedSymbol;
import malte0811.controlengineering.logic.schematic.symbol.SchematicSymbol;
import malte0811.controlengineering.logic.schematic.symbol.SymbolInstance;
import malte0811.controlengineering.util.math.RectangleI;
import malte0811.controlengineering.util.math.Vec2d;
import malte0811.controlengineering.util.math.Vec2i;
import malte0811.controlengineering.util.mycodec.MyCodec;
import malte0811.controlengineering.util.mycodec.MyCodecs;
import malte0811.controlengineering.util.mycodec.record.CodecField;
import malte0811.controlengineering.util.mycodec.record.RecordCodec3;
import net.minecraft.world.level.Level;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.ToDoubleFunction;
public class Schematic {
public static final int GLOBAL_MIN = -512;
public static final int GLOBAL_MAX = 512;
public static final RectangleI BOUNDARY = new RectangleI(GLOBAL_MIN, GLOBAL_MIN, GLOBAL_MAX, GLOBAL_MAX);
public static final MyCodec<Schematic> CODEC = new RecordCodec3<>(
new CodecField<>("symbols", Schematic::getSymbols, MyCodecs.list(PlacedSymbol.CODEC)),
new CodecField<>("nets", Schematic::getNets, MyCodecs.list(SchematicNet.CODEC)),
new CodecField<>("name", Schematic::getName, MyCodecs.STRING),
Schematic::new
);
private final List<PlacedSymbol> symbols;
private final List<SchematicNet> nets;
private String name;
private Schematic(List<PlacedSymbol> symbols, List<SchematicNet> nets, String name) {
this.symbols = new ArrayList<>(symbols);
this.nets = new ArrayList<>(nets);
this.name = name;
this.resetConnectedPins();
}
public Schematic() {
this(ImmutableList.of(), ImmutableList.of(), "New schematic");
}
public boolean addSymbol(PlacedSymbol newSymbol, Level level) {
if (!makeChecker(level).canAdd(newSymbol)) {
return false;
}
symbols.add(newSymbol);
resetConnectedPins();
return true;
}
public void addWire(WireSegment segment) {
IntSet connectedIndices = getConnectedNetIndices(segment);
if (connectedIndices.isEmpty()) {
// New net
nets.add(new SchematicNet(segment));
} else {
// Connected to existing net(s)
IntIterator it = connectedIndices.iterator();
final int netIdToKeep = it.nextInt();
final SchematicNet netToKeep = nets.get(netIdToKeep);
while (it.hasNext()) {
final SchematicNet netToRemove = nets.remove(it.nextInt());
netToKeep.addAll(netToRemove);
}
netToKeep.addSegment(segment);
}
resetConnectedPins();
}
public boolean removeOneContaining(Vec2d mouse, Level level) {
for (Iterator<SchematicNet> iterator = nets.iterator(); iterator.hasNext(); ) {
SchematicNet net = iterator.next();
if (net.removeOneContaining(mouse.floor())) {
iterator.remove();
nets.addAll(net.splitComponents());
resetConnectedPins();
return true;
}
}
for (Iterator<PlacedSymbol> iterator = symbols.iterator(); iterator.hasNext(); ) {
if (iterator.next().containsPoint(mouse, level)) {
iterator.remove();
resetConnectedPins();
return true;
}
}
return false;
}
private boolean isConnected(SchematicNet net, WireSegment wire) {
// Added segment ends inside the net
for (Vec2i end : wire.getEnds()) {
if (net.contains(end)) {
return true;
}
}
// Some net segment ends inside the added segment
for (var netWire : net.getAllSegments()) {
for (var netEnd : netWire.getEnds()) {
if (wire.containsClosed(netEnd)) {
return true;
}
}
}
// Net and added segment have a pin in common (possibly internal to segments in both cases)
for (var pin : net.getOrComputePins(getSymbols())) {
if (wire.containsClosed(pin.getPosition())) {
return true;
}
}
return false;
}
public IntSet getConnectedNetIndices(WireSegment toAdd) {
IntSet indices = new IntArraySet();
for (int i = 0; i < nets.size(); ++i) {
if (isConnected(nets.get(i), toAdd)) {
indices.add(i);
}
}
return indices;
}
@Nullable
public PlacedSymbol getSymbolAt(Vec2d pos, Level level) {
for (PlacedSymbol symbol : symbols) {
if (symbol.containsPoint(pos, level)) {
return symbol;
}
}
return null;
}
private void resetConnectedPins() {
nets.forEach(SchematicNet::resetCachedPins);
}
public List<PlacedSymbol> getSymbols() {
return Collections.unmodifiableList(symbols);
}
public List<SchematicNet> getNets() {
return Collections.unmodifiableList(nets);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SchematicChecker makeChecker(Level level) {
return new SchematicChecker(this, level);
}
private int getTotalCost(ToDoubleFunction<CellCost> individualCost) {
return (int) Math.ceil(
getSymbols().stream()
.map(PlacedSymbol::symbol)
.map(SymbolInstance::getType)
.map(SchematicSymbol::getCost)
.mapToDouble(individualCost)
.sum()
);
}
public int getNumLogicTubes() {
return getTotalCost(CellCost::numTubes);
}
public int getWireLength() {
return getTotalCost(CellCost::wireLength);
}
public int getSolderAmount() {
return getTotalCost(CellCost::getSolderAmount);
}
public int getNumBoards() {
return LogicCabinetBlockEntity.getNumBoardsFor(getNumLogicTubes());
}
public void clear() {
symbols.clear();
nets.clear();
}
public boolean replaceBy(int index, PlacedSymbol newSymbol, Level level) {
final var oldSymbol = symbols.remove(index);
resetConnectedPins();
if (addSymbol(newSymbol, level)) {
return true;
} else {
// Add back old symbol
addSymbol(oldSymbol, level);
return false;
}
}
public boolean isEmpty() {
return symbols.isEmpty() && nets.isEmpty();
}
public static boolean isEmpty(@Nullable Schematic schematic) {
return schematic == null || schematic.isEmpty();
}
}
|
def longestIncreasingSubsequence(arr):
n = len(arr)
lis = [1]*n
for i in range (1 , n):
for j in range(0 , i):
if arr[i] > arr[j] and lis[i]< lis[j] + 1 :
lis[i] = lis[j]+1
maximum = 0
for i in range(n):
maximum = max(maximum , lis[i])
return maximum
arr = [1, 3, 5, 4, 7]
res = longestIncreasingSubsequence(arr);
print(res) |
class CreateUsersAndProperties < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :name, null: false
t.string :email, null: false, unique: true
t.string :password_digest, null: false
end
create_table :properties do |t|
t.belongs_to :user, index: true
t.string :name, null: false
t.string :description, null: false
t.integer :price_per_night, null: false
t.boolean :booked
t.string :image
end
create_table :bookings do |t|
t.belongs_to :property, index: true
t.belongs_to :user, index: true
t.date :check_in, null: false
t.date :check_out, null: false
t.string :image
end
end
end
|
<reponame>riboseinc/url_validator
# (c) Copyright 2017 Ribose Inc.
#
require "net/http"
require "ipaddr"
require "resolv"
require "active_support/core_ext/module/delegation"
module UriFormatValidator
# Reacher is a minimalist net client which purpose is to determine whether
# given URL is resolvable, host is reachable, and content is retrievable.
class Reacher
attr_reader :url
delegate :hostname, :port, :scheme, to: :url
def initialize(url)
@url = url
end
# Tests whether given +url+ is retrievable, that is making a HEAD request
# results with 2xx status code.
def retrievable?
http_or_https? && head_response.is_a?(Net::HTTPSuccess)
end
# Returns +true+ if hostname component of given +url+ is either an IP
# address, or is a domain for which a DNS entry exists.
def resolvable?
return true if hostname.blank?
hostname_is_ip_address? || Resolv.getaddresses(hostname).any?
end
private
def head_response
Net::HTTP.start(hostname, port, use_ssl: use_ssl?) do |http|
http.request_head(url)
end
rescue StandardError
# The NET::HTTP may raise so many different errors that listing them all
# is IMO pretty pointless.
# See: http://tammersaleh.com/posts/rescuing-net-http-exceptions/
# for *incomplete* list.
nil
end
def use_ssl?
scheme == "https"
end
def http_or_https?
%w[http https].include? url.scheme
end
def hostname_is_ip_address?
Util.parse_host(hostname).is_a?(IPAddr)
end
end
end
|
<filename>packages/cli/src/cmds/validate.ts
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
"use strict";
import { Argv, Options } from "yargs";
import * as path from "path";
import { FxError, err, ok, Result, Func } from "@microsoft/teamsfx-api";
import activate from "../activate";
import { YargsCommand } from "../yargsCommand";
import { getSystemInputs } from "../utils";
import CliTelemetry from "../telemetry/cliTelemetry";
import { TelemetryEvent, TelemetryProperty, TelemetrySuccess } from "../telemetry/cliTelemetryEvents";
import HelpParamGenerator from "../helpParamGenerator";
export default class Validate extends YargsCommand {
public readonly commandHead = `validate`;
public readonly command = `${this.commandHead}`;
public readonly description = "Validate the current application.";
public params: { [_: string]: Options } = {};
public builder(yargs: Argv): Argv<any> {
this.params = HelpParamGenerator.getYargsParamForHelp("validate");
return yargs.version(false).options(this.params);
}
public async runCommand(args: {
[argName: string]: string | string[];
}): Promise<Result<null, FxError>> {
const rootFolder = path.resolve(args.folder as string || "./");
CliTelemetry.withRootFolder(rootFolder).sendTelemetryEvent(TelemetryEvent.ValidateManifestStart);
const result = await activate(rootFolder);
if (result.isErr()) {
CliTelemetry.sendTelemetryErrorEvent(TelemetryEvent.ValidateManifest, result.error);
return err(result.error);
}
const core = result.value;
{
const func: Func = {
namespace: "fx-solution-azure",
method: "validateManifest"
};
const result = await core.executeUserTask!(func, getSystemInputs(rootFolder));
if (result.isErr()) {
CliTelemetry.sendTelemetryErrorEvent(TelemetryEvent.ValidateManifest, result.error);
return err(result.error);
}
}
CliTelemetry.sendTelemetryEvent(TelemetryEvent.ValidateManifest, {
[TelemetryProperty.Success]: TelemetrySuccess.Yes
});
return ok(null);
}
}
|
#include "include/push_warnings.h"
#include <Python.h>
/* `datetime.h` must only be included here. */
#include <datetime.h>
#include "include/pop_warnings.h"
#include <sys/types.h>
#include "include/pyutils.h"
int PyObject_SetAttrStringLongValue(PyObject* o, const char* name, long v)
{
int result = -1;
PyObject* value = PyLong_FromLong(v);
if (value)
{
result = PyObject_SetAttrString(o, name, value);
}
Py_XDECREF(value);
return result;
}
int PyDict_SetItemStringLongValue(PyObject* d, const char* name, long v)
{
int result = -1;
PyObject* value = PyLong_FromLong(v);
if (value)
{
result = PyDict_SetItemString(d, name, value);
}
Py_XDECREF(value);
return result;
}
int PyDict_SetItemStringStringValue(PyObject* d, const char* name, const char* v)
{
int result = -1;
PyObject* value = PyUnicode_FromString(v);
if (value)
{
result = PyDict_SetItemString(d, name, value);
}
Py_XDECREF(value);
return result;
}
/* decimal.Decimal reference. */
static PyObject* PyDecimalType = NULL;
int PyDecimalType_init(void)
{
PyObject* moddecimal;
assert(!PyDecimalType); /* should not be importing multiple times. */
moddecimal = PyImport_ImportModule("decimal");
if (moddecimal)
{
PyDecimalType = PyObject_GetAttrString(moddecimal, "Decimal");
Py_DECREF(moddecimal);
}
return !!PyDecimalType;
}
void PyDecimalType_free(void)
{
Py_XDECREF(PyDecimalType);
}
int PyDecimal_Check(PyObject* o)
{
return PyObject_TypeCheck(o, (PyTypeObject*)PyDecimalType);
}
PyObject* PyDecimal_FromString(const char* str, Py_ssize_t size)
{
return PyObject_CallFunction(PyDecimalType, "s#", str, size);
}
PyObject* PyDecimal_ToString(PyObject* odecimal)
{
PyObject* ostr = NULL;
#if PY_MAJOR_VERSION < 3
PyObject* oformat = oformat = PyString_FromString("{0:f}");
#else /* if PY_MAJOR_VERSION < 3 */
PyObject* oformat = PyUnicode_FromString("{0:f}");
#endif /* else if PY_MAJOR_VERSION < 3 */
if (oformat)
{
ostr = PyObject_CallMethod(oformat, "format", "(O)", odecimal);
Py_DECREF(oformat);
}
return ostr;
}
/* uuid.UUID reference */
static PyObject* PyUuidType = NULL;
int PyUuidType_init(void)
{
PyObject* moduuid;
assert(!PyUuidType);
moduuid = PyImport_ImportModule("uuid"); /* should not be importing multiple times. */
if (moduuid)
{
PyUuidType = PyObject_GetAttrString(moduuid, "UUID");
Py_DECREF(moduuid);
}
return !!PyUuidType;
}
void PyUuidType_free(void)
{
Py_XDECREF(PyUuidType);
}
int PyUuid_Check(PyObject* o)
{
return PyObject_TypeCheck(o, (PyTypeObject*)PyUuidType);
}
PyObject* PyUuid_FromBytes(const char* bytes, Py_ssize_t size)
{
PyObject* args = NULL;
PyObject* kwargs = NULL;
PyObject* obytes = NULL;
PyObject* uuid = NULL;
do
{
args = PyTuple_New(0);
if (!args) break;
kwargs = PyDict_New();
if (!kwargs) break;
obytes = PyBytes_FromStringAndSize(bytes, size);
if (!obytes) break;
#ifdef __BIG_ENDIAN__
# define UUID_BYTES "bytes"
#else
# define UUID_BYTES "bytes_le"
#endif
if (0 != PyDict_SetItemString(kwargs, UUID_BYTES, obytes)) break;
uuid = PyObject_Call(PyUuidType, args, kwargs);
}
while (0);
Py_XDECREF(args);
Py_XDECREF(kwargs);
Py_XDECREF(obytes);
return uuid;
}
int PyDateTimeType_init(void)
{
assert(!PyDateTimeAPI);
return !!(PyDateTime_IMPORT);
}
void PyDateTimeType_free(void)
{
Py_XDECREF(PyDateTimeAPI);
}
int PyDateTime_Check_(PyObject* o) { return PyDateTime_Check(o); }
int PyDate_Check_(PyObject* o) { return PyDate_Check(o); }
int PyTime_Check_(PyObject* o) { return PyTime_Check(o); }
PyObject* PyDateTime_FromDateAndTime_(int year, int month, int day, int hour, int minute, int second, int usecond)
{
return PyDateTime_FromDateAndTime(year, month, day, hour, minute, second, usecond);
}
PyObject* PyDateTime_FromTimestamp_(PyObject* args)
{
return PyDateTime_FromTimestamp(args);
}
PyObject* PyDate_FromDate_(int year, int month, int day)
{
return PyDate_FromDate(year, month, day);
}
PyObject* PyDate_FromTimestamp_(PyObject* args)
{
return PyDate_FromTimestamp(args);
}
PyObject* PyTime_FromTime_(int hour, int minute, int second, int usecond)
{
return PyTime_FromTime(hour, minute, second, usecond);
}
int PyDateTime_GET_YEAR_(PyObject* o) { return PyDateTime_GET_YEAR(o); }
int PyDateTime_GET_MONTH_(PyObject* o) { return PyDateTime_GET_MONTH(o); }
int PyDateTime_GET_DAY_(PyObject* o) { return PyDateTime_GET_DAY(o); }
int PyDateTime_DATE_GET_HOUR_(PyObject* o) { return PyDateTime_DATE_GET_HOUR(o); }
int PyDateTime_DATE_GET_MINUTE_(PyObject* o) { return PyDateTime_DATE_GET_MINUTE(o); }
int PyDateTime_DATE_GET_SECOND_(PyObject* o) { return PyDateTime_DATE_GET_SECOND(o); }
int PyDateTime_DATE_GET_MICROSECOND_(PyObject* o) { return PyDateTime_DATE_GET_MICROSECOND(o); }
int PyDateTime_TIME_GET_HOUR_(PyObject* o) { return PyDateTime_TIME_GET_HOUR(o); }
int PyDateTime_TIME_GET_MINUTE_(PyObject* o) { return PyDateTime_TIME_GET_MINUTE(o); }
int PyDateTime_TIME_GET_SECOND_(PyObject* o) { return PyDateTime_TIME_GET_SECOND(o); }
int PyDateTime_TIME_GET_MICROSECOND_(PyObject* o) { return PyDateTime_TIME_GET_MICROSECOND(o); }
|
import React from 'react';
function App() {
const [selected, setSelected] = React.useState(null);
const handleClick = item => {
setSelected(item);
alert(item);
};
return (
<div>
{items.map(item => (
<div key={item} onClick={() => handleClick(item)}>
{item}
</div>
))}
</div>
);
}
export default App; |
<gh_stars>1-10
const _ = require('lodash');
/* eslint-disable no-param-reassign */
const utils = require('../../lib/utils');
const skipDisplayAccount = (argv) =>
_.isEqual(['config', 'wizard'], argv._) ||
_.isEqual(['id', 'register'], argv._);
const handler = async (argv) => {
// argv._ is list of commands
if (argv._[0] === 'env' || argv._[0] === 'setup') {
return undefined;
}
argv.env = argv.env || 'default';
const conf = await utils.getEnvConfig(argv.env);
utils.display(`Current environment: ${argv.env}`);
if (!skipDisplayAccount(argv)) {
utils.display(`Current account: ${conf.account || 'N/A'}`);
}
utils.display('');
return undefined;
};
module.exports = handler;
|
<gh_stars>100-1000
package com.musicplus.utils;
import java.security.MessageDigest;
/*************************************************
* md5 类实现了RSA Data Security, Inc.在提交给IETF 的RFC1321中的MD5 message-digest 算法。
*************************************************/
public class MD5Util {
public static String getMD5Str(String src) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(src.getBytes());
return toHexString(messageDigest.digest());
} catch (Exception e) {
}
return null;
}
private static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(Digit[(b[i] & 0xf0) >>> 4]);
sb.append(Digit[b[i] & 0x0f]);
}
return sb.toString();
}
private static char[] Digit = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
}
|
import React from 'react'
export default function Delete(props) {
return <>
Delete Listener
</>
} |
void printTriangle(int lines)
{
for (int i = 1; i <= lines; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
} |
#!/bin/bash
set -e
if [ "$1" = '/opt/mssql/bin/sqlservr' ]; then
# If this is the container's first run, initialize the application
# database
if [ ! -f /tmp/app-initialized ]; then
# Initialize the application database asynchronously in a
# background process. This allows a) the SQL Server process to be
# the main process in the container, which allows graceful
# shutdown and other goodies, and b) us to only start the SQL
# Server process once, as opposed to starting, stopping, then
# starting it again.
function initialize_app_database() {
# Wait a bit for SQL Server to start. SQL Server's process
# doesn't provide a clever way to check if it's up or not, and
# it needs to be up before we can import the application
# database
sleep 15s
# Run the setup script to create the DB and the schema in the
# DB
/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "Your_password123!" -d master -i /mssql/setup.sql
# Note that the container has been initialized so future
# starts won't wipe changes to the data
touch /tmp/app-initialized
}
initialize_app_database &
fi
fi
exec "$@"
|
<reponame>kradical/Graphics
#include "Sphere.h"
Sphere::Sphere(Vec3 cen, float r, Material* m) : center(cen), radius(r), mat_ptr(m) {};
bool Sphere::hit(const Ray& r, float t_min, float t_max, hit_record& rec) const {
Vec3 oc = r.origin - center;
float a = dot(r.direction, r.direction);
float b = dot(oc, r.direction);
float c = dot(oc, oc) - radius * radius;
float discriminant = b * b - a * c;
if (discriminant > 0) {
// first root
float temp = (-b - sqrt(discriminant)) / a;
if (temp < t_max && temp > t_min) {
rec.t = temp;
rec.p = r.point_at(rec.t);
rec.normal = unit_vector((rec.p - center) / radius);
rec.r_in = r;
rec.mat_ptr = mat_ptr;
return true;
}
// second root
temp = (-b + sqrt(discriminant)) / a;
if (temp < t_max && temp > t_min) {
rec.t = temp;
rec.p = r.point_at(rec.t);
rec.normal = unit_vector((rec.p - center) / radius);
rec.r_in = r;
rec.mat_ptr = mat_ptr;
return true;
}
}
return false;
}
|
#!/bin/bash
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
M_IP=10.10.10.51
C_IP=10.10.20.200
D_IP=10.10.30.51
#RABBIT_PASS=secrete
PASSWORD=PASS
#ADMIN_TOKEN=ADMIN
#MAIL=jshan@nm.gist.ac.kr
sed -i "/#kernel.domainname = example.com/a\
net.ipv4.ip_forward=1\n\
net.ipv4.conf.all.rp_filter=0\n\
net.ipv4.conf.default.rp_filter=0" /etc/sysctl.conf
#1.To create the database, complete these steps:
cat << EOF | mysql -uroot -p$PASSWORD
CREATE DATABASE neutron;
GRANT ALL PRIVILEGES ON neutron.* TO 'neutron'@'localhost' IDENTIFIED BY '$PASSWORD';
GRANT ALL PRIVILEGES ON neutron.* TO 'neutron'@'%' IDENTIFIED BY '$PASSWORD';
quit
EOF
#2.Source the admin credentials to gain access to admin-only CLI commands:
source admin-openrc.sh
#3.To create the service credentials, complete these steps:
#◦Create the neutron user:
openstack user create --domain default --password $PASSWORD neutron
#◦Add the admin role to the neutron user:
openstack role add --project service --user neutron admin
#◦Create the neutron service entity:
openstack service create --name neutron \
--description "OpenStack Networking" network
#4.Create the Networking service API endpoints:
openstack endpoint create --region RegionOne \
network public http://$M_IP:9696
openstack endpoint create --region RegionOne \
network internal http://$C_IP:9696
openstack endpoint create --region RegionOne \
network admin http://$C_IP:9696
#Install the components
sudo apt-get install -y neutron-server neutron-plugin-ml2 \
neutron-openvswitch-agent neutron-l3-agent neutron-dhcp-agent \
neutron-metadata-agent
##•Edit the /etc/neutron/neutron.conf file and complete the following actions:
sed -i "s/connection = sqlite:\/\/\/\/var\/lib\/neutron\/neutron.sqlite/connection = mysql+pymysql:\/\/neutron:$PASSWORD@$C_IP\/neutron/g" /etc/neutron/neutron.conf
sed -i "s/#service_plugins =/service_plugins = router\n\
allow_overlapping_ips = True\n\
rpc_backend = rabbit\n\
auth_strategy = keystone\n\
notify_nova_on_port_status_changes = True\n\
notify_nova_on_port_data_changes = True\n\
router_distributed = True/g" /etc/neutron/neutron.conf
sed -i "s/#rabbit_host = localhost/rabbit_host = $C_IP\n\
rabbit_userid = openstack\n\
rabbit_password = $PASSWORD/g" /etc/neutron/neutron.conf
sed -i "s/#auth_uri = <None>/auth_uri = http:\/\/$C_IP:5000\n\
auth_url = http:\/\/$C_IP:35357\n\
memcached_servers = $C_IP:11211\n\
auth_type = password\n\
project_domain_name = default\n\
user_domain_name = default\n\
project_name = service\n\
username = neutron\n\
password = $PASSWORD/g" /etc/neutron/neutron.conf
sed -i "s/#auth_url = <None>/auth_url = http:\/\/$C_IP:35357\n\
auth_type = password\n\
project_domain_name = default\n\
user_domain_name = default\n\
region_name = RegionOne\n\
project_name = service\n\
username = nova\n\
password = $PASSWORD/g" /etc/neutron/neutron.conf
#•Edit the /etc/neutron/plugins/ml2/ml2_conf.ini file and complete the following actions:
sed -i "s/#type_drivers = local,flat,vlan,gre,vxlan,geneve/type_drivers = flat,vxlan\n\
tenant_network_types = vxlan\n\
mechanism_drivers = openvswitch,l2population\n\
extension_drivers = port_security/g" /etc/neutron/plugins/ml2/ml2_conf.ini
sed -i "s/#vxlan_group = <None>/#vxlan_group = <None>\n\
vni_ranges = 1:1000/g" /etc/neutron/plugins/ml2/ml2_conf.ini
sed -i "s/#flat_networks = \*/flat_networks = external/g" /etc/neutron/plugins/ml2/ml2_conf.ini
sed -i "s/#firewall_driver = <None>/firewall_driver = iptables_hybrid\n\
enable_ipset = True/g" /etc/neutron/plugins/ml2/ml2_conf.ini
#.In the openvswitch_agent.ini file, configure the Open vSwitch agent:
sed -i "s/#local_ip = <None>/local_ip = $D_IP/g" /etc/neutron/plugins/ml2/openvswitch_agent.ini
sed -i "s/#tunnel_types =/tunnel_types = vxlan\n\
l2_population = True/g" /etc/neutron/plugins/ml2/openvswitch_agent.ini
sed -i "s/#firewall_driver = <None>/firewall_driver = iptables_hybrid\n\
enable_security_group = true/g" /etc/neutron/plugins/ml2/openvswitch_agent.ini
sed -i "s/#arp_responder = false/arp_responder = True/g" /etc/neutron/plugins/ml2/openvswitch_agent.ini
sed -i "s/#enable_distributed_routing = false/enable_distributed_routing = True/g" /etc/neutron/plugins/ml2/openvswitch_agent.ini
sed -i "s/#bridge_mappings =/bridge_mappings = external:br-ex/g" /etc/neutron/plugins/ml2/openvswitch_agent.ini
#.In the l3_agent.ini file, configure the L3 agent:
sed -i "s/#interface_driver = <None>/interface_driver = openvswitch/g" /etc/neutron/l3_agent.ini
sed -i "s/#external_network_bridge = br-ex/external_network_bridge = /g" /etc/neutron/l3_agent.ini
sed -i "s/#agent_mode = legacy/agent_mode = dvr_snat/g" /etc/neutron/l3_agent.ini
#.In the dhcp_agent.ini file, configure the DHCP agent:
sed -i "s/#enable_isolated_metadata = false/enable_isolated_metadata = True/g" /etc/neutron/dhcp_agent.ini
sed -i "s/#interface_driver = <None>/interface_driver = openvswitch/g" /etc/neutron/dhcp_agent.ini
touch /etc/neutron/dnsmasq-neutron.conf
echo "dhcp-option-force=26,1400" >> /etc/neutron/dnsmasq-neutron.conf
sed -i "s/#dnsmasq_config_file =/dnsmasq_config_file = \/etc\/neutron\/dnsmasq-neutron.conf/g" /etc/neutron/dhcp_agent.ini
pkill dnsmasq
#.In the metadata_agent.ini file, configure the metadata agent:
sed -i "s/#nova_metadata_ip = 127.0.0.1/nova_metadata_ip = $C_IP/g" /etc/neutron/metadata_agent.ini
sed -i "s/#metadata_proxy_shared_secret =/metadata_proxy_shared_secret = METADATA_SECRET/g" /etc/neutron/metadata_agent.ini
#•Edit the /etc/nova/nova.conf file and complete the following actions:
#◦In the [neutron] section, configure access parameters:
sed -i "s/auth_strategy = keystone/auth_strategy = keystone\n\
\n\
[neutron]\n\
url = http:\/\/$C_IP:9696\n\
auth_url = http:\/\/$C_IP:35357\n\
auth_type = password\n\
project_domain_name = default\n\
user_domain_name = default\n\
region_name = RegionOne\n\
project_name = service\n\
username = neutron\n\
password = $PASSWORD\n\
service_metadata_proxy = True\n\
metadata_proxy_shared_secret = METADATA_SECRET/g" /etc/nova/nova.conf
#Finalize installation
su -s /bin/sh -c "neutron-db-manage --config-file /etc/neutron/neutron.conf \
--config-file /etc/neutron/plugins/ml2/ml2_conf.ini upgrade head" neutron
#Restart the Compute service:
service nova-api restart
service neutron-server restart
service openvswitch-switch restart
service neutron-openvswitch-agent restart
service neutron-l3-agent restart
service neutron-dhcp-agent restart
service neutron-metadata-agent restart
|
#!/bin/sh
../a.out
|
declare module '@timwoods/handlebars';
|
/*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2012 <NAME>. All Rights Reserved.
*/
package org.owasp.dependencycheck;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.junit.Before;
import org.owasp.dependencycheck.data.nvdcve.DatabaseManager;
import org.owasp.dependencycheck.utils.WriteLock;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An abstract database test case that is used to ensure the H2 DB exists prior
* to performing tests that utilize the data contained within.
*
* @author <NAME>
*/
public abstract class BaseDBTestCase extends BaseTest {
protected final static int BUFFER_SIZE = 2048;
private final static Logger LOGGER = LoggerFactory.getLogger(BaseDBTestCase.class);
@Before
@Override
public void setUp() throws Exception {
super.setUp();
synchronized (this) {
ensureDBExists();
}
}
public void ensureDBExists() throws Exception {
try (WriteLock dblock = new WriteLock(getSettings(), DatabaseManager.isH2Connection(getSettings()))) {
File f = new File("./target/data/odc.mv.db");
if (f.exists() && f.isFile() && f.length() < 71680) {
f.delete();
}
File dataPath = getSettings().getH2DataDirectory();
String fileName = getSettings().getString(Settings.KEYS.DB_FILE_NAME);
LOGGER.trace("DB file name {}", fileName);
File dataFile = new File(dataPath, fileName);
LOGGER.trace("Ensuring {} exists", dataFile.toString());
if (!dataPath.exists() || !dataFile.exists()) {
LOGGER.trace("Extracting database to {}", dataPath.toString());
dataPath.mkdirs();
File path = new File(BaseDBTestCase.class.getClassLoader().getResource("data.zip").toURI().getPath());
try (FileInputStream fis = new FileInputStream(path);
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis))) {
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
if (entry.isDirectory()) {
final File d = new File(dataPath, entry.getName());
d.mkdir();
continue;
}
//File o = new File(dataPath, entry.getName());
//o.createNewFile();
dataFile.createNewFile();
try (FileOutputStream fos = new FileOutputStream(dataFile, false);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
IOUtils.copy(zin, dest);
} catch (Throwable ex) {
LOGGER.error("", ex);
}
}
}
//update the schema
DatabaseManager factory = new DatabaseManager(getSettings());
}
}
}
}
|
const router = require('express').Router()
module.exports = router
router.use('/users', require('./users'))
router.use('/products', require('./products'))
router.use('/cart', require('./cart'))
router.use((req, res, next) => {
const err = new Error('API route not found')
err.status = 404
next(err)
})
|
package org.brapi.test.BrAPITestServer.model.entity.geno;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.brapi.test.BrAPITestServer.model.entity.BrAPIPrimaryEntity;
@Entity
@Table(name="reference")
public class ReferenceEntity extends BrAPIPrimaryEntity {
@Column
private Integer length;
@Column
private String md5checksum;
@Column
private String referenceName;
@ManyToOne
private ReferenceSetEntity referenceSet;
@Column
private BigDecimal sourceDivergence;
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public String getMd5checksum() {
return md5checksum;
}
public void setMd5checksum(String md5checksum) {
this.md5checksum = md5checksum;
}
public String getReferenceName() {
return referenceName;
}
public void setReferenceName(String referenceName) {
this.referenceName = referenceName;
}
public ReferenceSetEntity getReferenceSet() {
return referenceSet;
}
public void setReferenceSet(ReferenceSetEntity referenceSet) {
this.referenceSet = referenceSet;
}
public BigDecimal getSourceDivergence() {
return sourceDivergence;
}
public void setSourceDivergence(BigDecimal sourceDivergence) {
this.sourceDivergence = sourceDivergence;
}
}
|
<filename>chapter04/Exercise_4_10.java
package com.company;
import java.util.Scanner;
public class Exercise_4_10 {
public static void main(String[] args) {
int day = 0;
Scanner input = new Scanner(System.in);
// prompt the user to answer questions
System.out.println("Is your birthday in Set1?");
// print set1
System.out.printf("%2d %2d %2d %2d\n",1,3,5,7);
System.out.printf("%2d %2d %2d %2d\n",9,11,13,15);
System.out.printf("%2d %2d %2d %2d\n",17,19,21,23);
System.out.printf("%2d %2d %2d %2d\n",25,27,29,31);
System.out.println("Enter N for No and Y for Yes: ");
String s = input.nextLine();
char answer = s.charAt(0);
if (answer == 'Y')
day += 1;
// prompt the user to answer questions
System.out.println("Is your birthday in Set2?");
// print set2
System.out.printf("%2d %2d %2d %2d\n",2,3,6,7);
System.out.printf("%2d %2d %2d %2d\n",10,11,14,15);
System.out.printf("%2d %2d %2d %2d\n",18,19,22,23);
System.out.printf("%2d %2d %2d %2d\n",26,27,30,31);
System.out.println("Enter N for No and Y for Yes: ");
s = input.nextLine();
answer = s.charAt(0);
if (answer == 'Y')
day += 2;
// prompt the user to answer questions
System.out.println("Is your birthday in Set3?");
// print set3
System.out.printf("%2d %2d %2d %2d\n",4,5,6,7);
System.out.printf("%2d %2d %2d %2d\n",12,13,14,15);
System.out.printf("%2d %2d %2d %2d\n",20,21,22,23);
System.out.printf("%2d %2d %2d %2d\n",28,29,30,31);
System.out.println("Enter N for No and Y for Yes: ");
s = input.nextLine();
answer = s.charAt(0);
if (answer == 'Y')
day += 4;
// prompt the user to answer questions
System.out.println("Is your birthday in Set4?");
// print set4
System.out.printf("%2d %2d %2d %2d\n",8,9,10,11);
System.out.printf("%2d %2d %2d %2d\n",12,13,14,15);
System.out.printf("%2d %2d %2d %2d\n",24,25,26,27);
System.out.printf("%2d %2d %2d %2d\n",28,29,30,31);
System.out.println("Enter N for No and Y for Yes: ");
s = input.nextLine();
answer = s.charAt(0);
if (answer == 'Y')
day += 8;
// prompt the user to answer questions
System.out.println("Is your birthday in Set5?");
// print set5
System.out.printf("%2d %2d %2d %2d\n",16,17,18,19);
System.out.printf("%2d %2d %2d %2d\n",20,21,22,23);
System.out.printf("%2d %2d %2d %2d\n",24,25,26,27);
System.out.printf("%2d %2d %2d %2d\n",28,29,30,31);
System.out.println("Enter N for No and Y for Yes: ");
s = input.nextLine();
answer = s.charAt(0);
if (answer == 'Y')
day += 16;
System.out.printf("Your birthday is %d !\n", day);
}
}
|
import React from 'react'
export default (contextKey, contextType) => Component => {
class WithContext extends React.Component {
render() {
const props = {
...this.props,
[contextKey]: this.context[contextKey],
}
return <Component {...props} />
}
}
const displayName = Component.displayName || Component.name || 'Component'
WithContext.displayName = `WithContext(${displayName})`
WithContext.contextTypes = {
[contextKey]: contextType,
}
return WithContext
}
|
#!/bin/bash -ev
#
# Installation Script
# Written by: Tommy Lincoln <pajamapants3000@gmail.com>
# Github: https://github.com/pajamapants3000
# Legal: See LICENSE in parent directory
#
#
# Dependencies
#**************
# Begin Required
#python-2.7.10 or python-3.4.3
# End required
# Begin recommended
# End recommended
# Begin optional
#check-0.9.14
#doxygen-1.8.10, and valgrind-3.10.1
# End optional
# Begin kernel
#CONFIG_INPUT
#CONFIG_INPUT_EVDEV
#CONFIG_INPUT_MISC
#CONFIG_INPUT_UINPUT
# End Kernel
#
# Installation
#**************
# Check for previous installation:
PROCEED="yes"
REINSTALL=0
grep libevdev-1.4.3 /list-$CHRISTENED"-"$SURNAME > /dev/null && ((\!$?)) &&\
REINSTALL=1 && echo "Previous installation detected, proceed?" && read PROCEED
[ $PROCEED = "yes" ] || [ $PROCEED = "y" ] || exit 0
# Download:
wget http://www.freedesktop.org/software/libevdev/libevdev-1.4.3.tar.xz
# md5sum:
echo "2fc170e2d6f543ba26e7c79f95dc1935 libevdev-1.4.3.tar.xz" | md5sum -c ;\
( exit ${PIPESTATUS[0]} )
#
tar -xvf libevdev-1.4.3.tar.xz
cd libevdev-1.4.3
./configure $XORG_CONFIG
make
# Test (too much trouble!):
#make check
#
as_root make install
cd ..
as_root rm -rf libevdev-1.4.3
#
# Add to installed list for this computer:
echo "libevdev-1.4.3" >> /list-$CHRISTENED"-"$SURNAME
#
###################################################
|
import { I3_0, I3_1, I3_2, IGetResponse, IPostResponse, itemreturn } from '../support/Interfaces';
import { StatusCodes } from 'http-status-codes';
import { product } from '../DatabaseSchemaModels/Product';
import { users } from '../DatabaseSchemaModels/UserData';
import { pickup } from '../DatabaseSchemaModels/Pickup';
import { DatabaseOperations } from '../support/DatabaseOperations';
import { pastorders } from '../DatabaseSchemaModels/PastOrders';
import { bids } from '../DatabaseSchemaModels/Bids';
export class ProductsModel {
static categories = {
"fruits": ["apple", "banana", "pear", "strawberry", "blueberry", "cherry", "raspberry", "orange", "lemon", "mosambi", "kiwi", "grapes", "chickoo", "pomegranate", "mangoes", "watermelon", "muskmelon", "sunmelon", "plum", "peach", "fig", "apricot", "dryfruits", "dryseeds", "otherfruits"],
"dailyvegetables": ["onions", "potatoes", "tomatoes", "beans", "brinjal", "okra", "broccoli", "cabbage", "cauliflower", "karela", "dodka", "lauki", "parwal", "tinda", "pumpkin", "drumstick", "chillies", "garlic", "lemon", "ginger", "cucumber", "redcapsicum", "yellowcapsicum", "greencapsicum", "peas", "corn", "beetroot", "turnip", "radish", "carrot", "otherdailyvegetables"],
"exoticvegetables": ["avacados", "pepper", "broccoli", "zucchini", "asparagus", "artichoke", "celery", "fennel", "leek", "edibleflowers", "lettuce", "leafyveg", "mushrooms", "otherexoticvegetables"],
"organic": ["organicfruits", "organicvegetables"],
"exotic": ["exoticfruits", "exoticvegetables"],
"herbsandseasoning": ["lemon", "ginger", "garlic", "indianherbs", "otherherbsandseasoning"]
}
/**
* The method getCategories. undefined
*
* @param body of type any
* @returns IPostResponse
*/
public static getCategories(body: any): IPostResponse {
let resp: IPostResponse = { "statusCode": StatusCodes.INTERNAL_SERVER_ERROR, "message": "NOT IMPLEMENTED" };
return resp;
}
/**
* The method getItems. undefined
*
* @param body of type any
* @returns IPostResponse
*/
public static getItems(category: string, uid: string): Promise<IGetResponse> {
if (uid) {
return new Promise((resolve, reject) => {
product.find({ uid: uid }).then(val => {
return resolve({ "statusCode": 0, "message": "Items retrieved", "payload": val })
})
.catch(e => {
console.log(e)
return reject({ "statusCode": 2, "message": e, "payload": "" })
})
})
}
else {
var id: "exoticvegetables" | "fruits" | "dailyvegetables" | "organic" | "exotic" | "herbsandseasoning";
if (category === "fruits") id = "fruits";
if (category === "exoticvegetables") id = "exoticvegetables";
if (category === "dailyvegetables") id = "dailyvegetables";
if (category === "organic") id = "organic";
if (category === "exotic") id = "exotic";
if (category === "herbsandseasoning") id = "herbsandseasoning";
// {"$in": [{name: "orange"}, {name: "kiwi"}, {name: "mangoes"}, {name: "exoticfruits"}]}
return new Promise((resolve, reject) => {
product.find({ "categories.name": { "$in": ProductsModel.categories[id] } }).then(val => {
resolve({ "statusCode": 0, "message": "Items retrieved", "payload": val })
})
.catch(e => {
console.log(e)
reject({ "statusCode": 2, "message": e, "payload": "" })
})
})
}
}
public static getFilterItems(category: Array<any>, uid?: string): Promise<IGetResponse> {
console.log(category, uid);
let mquery: { [key: string]: any } = { "categories.name": { "$in": category } }
if (uid) {
mquery.uid = uid;
}
// {"$in": [{name: "orange"}, {name: "kiwi"}, {name: "mangoes"}, {name: "exoticfruits"}]}
return new Promise((resolve, reject) => {
product.find(mquery).then(val => {
console.log(val)
resolve({ "statusCode": 0, "message": "Items retrieved", "payload": val })
})
.catch(e => {
console.log(e)
reject({ "statusCode": 2, "message": e, "payload": "" })
})
})
}
public static ifuserhaspurchased(uid: string, prodid: string): Promise<any> {
return new Promise((resolve, reject) => {
pastorders.findOne({ uid: uid, "Orders.itemsList.itemId": { "$regex": prodid, "$options": "i" } }).then(val => {
if (val) resolve(true);
else resolve(false);
})
.catch(e => {
reject(e);
})
})
}
public static getItem(id: string, uid?: string): Promise<IGetResponse> {
return new Promise((resolve, reject) => {
product.findById(id).then(val => {
let retvalue: any = val;
let itemReturn: itemreturn = {
uid: retvalue.uid!,
image: retvalue.image!,
description: retvalue.description!,
title: retvalue.title!,
categories: retvalue.categories!,
costing: retvalue.costing!,
productRemaining: retvalue.productRemaining!,
rating: retvalue.rating!,
comments: retvalue.comments!,
sellername: '',
baseprice: retvalue.baseprice!,
ratingpermission: false
};
users.findById(retvalue.uid).then(val => {
let user: any = val;
itemReturn["sellername"] = user.name;
// for (let i in itemReturn) console.log(itemReturn[i]);
// this.ifuserhaspurchased().then()
if (uid != undefined) {
this.ifuserhaspurchased(uid, id).then(val => {
if (val) itemReturn["ratingpermission"] = true;
else itemReturn["ratingpermission"] = false;
resolve({ "statusCode": 0, "message": "Item retrieved", "payload": itemReturn })
})
.catch(e => {
reject({ "statusCode": 2, "message": e, "payload": "" })
})
}
else resolve({ "statusCode": 0, "message": "Item retrieved", "payload": itemReturn })
})
.catch(e => {
console.log(e)
reject({ "statusCode": 2, "message": e, "payload": "" })
})
})
.catch(e => {
console.log(e)
reject({ "statusCode": 2, "message": e, "payload": "" })
})
})
}
/**
* The method addProduct. undefined
*
* @param body of type any
* @returns IPostResponse
*/
public static addProduct(body: I3_0): Promise<IPostResponse> {
return new Promise((resolve, reject) => {
if (body?.id) {
let products;
DatabaseOperations.FindOneOp(product, { _id: body.id })
.then((val) => {
products = val; DatabaseOperations.UpdateOneOp(product, { _id: body.id },
{ "$set": { description: (body.description != '' && body?.description) ? body.description : products.ProductId, title: (body.title != '' && body?.title) ? body.title : products.title, categories: (body.categories != null && body?.categories) ? body.categories : products.categories, costing: (body.costing != null && body?.costing) ? body.costing : products.costing, productRemaining: (body.productRemaining != null && body?.productRemaining) ? body.productRemaining : products.productRemaining, baseprice: (body.baseprice != null && body?.baseprice) ? body.baseprice : products.baseprice, image: (body.image != null && body?.image) ? body.image : products.image } })
})
.then((val) => { resolve({ statusCode: 0, message: "Product updated" }); })
.catch(e => { reject({ statusCode: 2, message: e }); })
}
else {
let products = new product(body);
products.save().then(data => {
let pickupadd = new pickup({ productId: data._id, pickupaddress: body.pickupaddress })
pickupadd.save().then(res => {
resolve({ statusCode: 0, message: "Product added" });
}).catch(e => {
console.log(e);
reject({ statusCode: 2, message: e });
})
})
.catch(e => {
reject({ statusCode: 2, message: e });
})
}
})
}
public static addabid(body: I3_2): Promise<IPostResponse> {
return new Promise((resolve, reject) => {
bids.findOneAndUpdate({ uid: body.uid, productId: body.productId }, body).then(val => {
if (val) resolve({ statusCode: 0, message: "Bid added" });
else {
let bid = new bids(body);
bid.save().then(val => {
resolve({ statusCode: 0, message: "Bid added" });
})
.catch(e => {
reject({ statusCode: 2, message: e });
})
}
})
.catch(e => {
reject({ statusCode: 2, message: e });
})
})
}
public static getProduct(id: String): Promise<any> {
return new Promise((resolve, reject) => {
product.find({ uid: id }).then(res => {
return resolve(res);
})
.catch(e => {
return reject(e);
})
})
}
public static getbid(id: String, role: String): Promise<IGetResponse>{
return new Promise((resolve, reject) => {
if(role == "farmer"){
this.getProduct(id).then(res => {
let arr: any = [];
for (let x of res) {
arr.push(x._id);
}
bids.find({productId: { "$in": arr }}).then((val: any) => {
let s1 = new Set()
for(let x of val){
s1.add(x.productId);
}
resolve({ "statusCode": 0, "message": "Bid retrieved", "payload": Array.from(s1) })
})
.catch(e => {
reject({ "statusCode": 2, "message": e, "payload": "" })
})
})
.catch(e => {
reject({ "statusCode": 2, "message": e, "payload": "" })
})
}
else if(role == "consumer"){
bids.find({uid: id}).then(val => {
resolve({ "statusCode": 0, "message": "Bid retrieved", "payload": val })
})
.catch(e => {
reject({ "statusCode": 2, "message": e, "payload": "" })
})
}
else{
bids.find({productId: id}).then(val => {
resolve({ "statusCode": 0, "message": "Bid retrieved", "payload": val })
})
.catch(e => {
reject({ "statusCode": 2, "message": e, "payload": "" })
})
}
})
}
public static addreview(body: I3_1): Promise<IPostResponse> {
return new Promise((resolve, reject) => {
product.findById(body.id).then((prod: any) => {
product.updateOne({ _id: body.id, "comments.uid": body.uid }, { "$set": { "comments.$.content": body.content, "comments.$.rating": body.rating, "comments.$.date": body.date, "comments.$.email": body.email } }).then(val => {
if (val.nModified == 0 && val.n == 0) {
product.updateOne({ _id: body.id }, { $push: { comments: body } }).then(val => {
product.updateOne({ _id: body.id }, { rating: (Number(Number(body.rating) + Number(prod.rating)) / Number(prod.noOfUsers)) }).then(val => {
resolve({ statusCode: 0, message: "Rating added" });
})
.catch(e => {
reject({ statusCode: 2, message: e });
})
})
.catch(e => {
reject({ statusCode: 2, message: e });
})
}
else {
let currrate = 0;
for (let x of prod.comments) {
if (x.uid == body.uid) {
currrate = x.rating;
break;
}
}
console.log(prod.rating, prod.noOfUsers, currrate, body.rating)
product.updateOne({ _id: body.id }, { rating: Number(Number(Number(prod.rating) * Number(prod.noOfUsers) - Number(currrate) + Number(body.rating)) / Number(prod.noOfUsers)) }).then(val => {
resolve({ statusCode: 0, message: "Rating added" });
})
.catch(e => {
reject({ statusCode: 2, message: e });
})
}
})
.catch(e => {
reject({ statusCode: 2, message: e });
})
})
.catch(e => {
reject({ statusCode: 2, message: e });
})
})
}
}
export let productsmodel = new ProductsModel(); |
/*
Game Tracker Router
*/
const express = require('express');
const log = require('../../__utils__/logger');
const responseObject = require('../../__utils__/responseObject');
const router = express.Router();
const gameTrackersService = require('./gameTrackersService');
// Get game tracker game detail full page
router.get('/detail/game=:gameId', async (req, res) => {
try {
const response = await gameTrackersService.getGameTrackerGameDetail(req.params.gameId);
res.status(200).json(response);
} catch (e) {
// Handling your errors
res.status(500).json(e);
}
});
// Get stats of a game's teams
router.get('/detail/team_stats/game=:gameId', async (req, res) => {
// Compare Stats on the Game Detail
try {
const feed = await gameTrackersService.gdTeamStatistics(req.params.gameId);
const response = responseObject(feed, 200);
res.status(response.status).json(response);
} catch (e) {
res.status(409).json({});
}
});
// Get top scores of a game and its teams win-loss ratio
router.get('/top_scores/game=:gameId', async (req, res) => {
try {
const scores = await gameTrackersService.getScoresAndRatio(req.params.gameId);
const response = responseObject(scores, 200);
res.status(response.status).json(response);
} catch (e) {
res.status(500).json(e);
}
});
// Get top scores of a game
router.get('/top_scores/scores/game=:gameId', async (req, res) => {
try {
const scores = await gameTrackersService.getTopScores(req.params.gameId);
const response = responseObject(scores, 200);
res.status(response.status).json(response);
} catch (e) {
res.status(500).json(e);
}
});
// Get win-loss ratio of a team
router.get('/top_scores/win_loss/team=:teamId', async (req, res) => {
try {
const ratio = await gameTrackersService.getWLRatio(req.params.teamId);
const response = responseObject(ratio, 200);
res.status(response.status).json(response);
} catch (e) {
res.status(500).json(e);
}
});
// Get quarter by quarter info of a game
router.get('/qbq/game=:gameId', async (req, res) => {
try {
log.debug(`Request parameters: ${req.params.gameId}`);
const standings = await gameTrackersService.getQbyQ(req.params.gameId);
const response = responseObject(standings, 200);
res.status(response.status).json(response);
} catch (e) {
res.status(500).json(e);
}
});
// Get team leaders of two teams
router.get('/team/leaders/home=:homeTeam&away=:awayTeam', async (req, res) => {
const { params } = req.params;
console.log(params);
const feed = await gameTrackersService.getNbaTeamLeaders(params.homeTeam, params.awayTeam);
const response = responseObject(feed, 200);
res.status(response.status).json(response);
});
// Get team stats of two teams
router.get('/team/stats/home=:homeTeam&away=:awayTeam', async (req, res) => {
const { params } = req.params;
const feed = await gameTrackersService.compareTeamStatistics(params.homeTeam, params.awayTeam);
const response = responseObject(feed, 200);
res.status(response.status).json(response);
});
module.exports = router;
|
const hues = {
whiteAlpha: {
50: 'rgba(255, 255, 255, 0.04)',
100: 'rgba(255, 255, 255, 0.06)',
200: 'rgba(255, 255, 255, 0.08)',
300: 'rgba(255, 255, 255, 0.16)',
400: 'rgba(255, 255, 255, 0.24)',
500: 'rgba(255, 255, 255, 0.36)',
600: 'rgba(255, 255, 255, 0.48)',
700: 'rgba(255, 255, 255, 0.64)',
800: 'rgba(255, 255, 255, 0.80)',
900: 'rgba(255, 255, 255, 0.92)',
},
blackAlpha: {
50: 'rgba(0, 0, 0, 0.04)',
100: 'rgba(0, 0, 0, 0.06)',
200: 'rgba(0, 0, 0, 0.08)',
300: 'rgba(0, 0, 0, 0.16)',
400: 'rgba(0, 0, 0, 0.24)',
500: 'rgba(0, 0, 0, 0.36)',
600: 'rgba(0, 0, 0, 0.48)',
700: 'rgba(0, 0, 0, 0.64)',
800: 'rgba(0, 0, 0, 0.80)',
900: 'rgba(0, 0, 0, 0.92)',
},
gray: {
50: '#F7FAFC',
100: '#EDF2F7',
200: '#E2E8F0',
300: '#CBD5E0',
400: '#A0AEC0',
500: '#718096',
600: '#4A5568',
700: '#2D3748',
800: '#1A202C',
900: '#171923',
},
red: {
50: '#fff5f5',
100: '#fed7d7',
200: '#feb2b2',
300: '#fc8181',
400: '#f56565',
500: '#e53e3e',
600: '#c53030',
700: '#9b2c2c',
800: '#822727',
900: '#63171b',
},
orange: {
50: '#FFFAF0',
100: '#FEEBC8',
200: '#FBD38D',
300: '#F6AD55',
400: '#ED8936',
500: '#DD6B20',
600: '#C05621',
700: '#9C4221',
800: '#7B341E',
900: '#652B19',
},
cyan: {
50: '#EDFDFD',
100: '#C4F1F9',
200: '#9DECF9',
300: '#76E4F7',
400: '#0BC5EA',
500: '#00B5D8',
600: '#00A3C4',
700: '#0987A0',
800: '#086F83',
900: '#065666',
},
rose: {
50: '#ffe7f2',
100: '#ffcfe6',
200: '#ff9fcd',
300: '#ff6fb3',
400: '#ff3f9a',
500: '#ff0f81',
600: '#cc0c67',
700: '#99094d',
800: '#660634',
900: '#33031a',
},
mint: {
100: '#effcf6',
200: '#def9ed',
300: '#cef7e4',
400: '#bdf4db',
500: '#adf1d2',
600: '#8ac1a8',
700: '#68917e',
800: '#456054',
900: '#23302a',
},
}
const colors = {
transparent: 'transparent',
current: 'currentColor',
black: '#000000',
white: '#ffffff',
softBlack: '#16161D',
accent: '#553555',
}
export const colorsDark = {
...colors,
background: colors.black,
backgroundInverse: colors.white,
backgroundAccent: hues.gray[800],
text: colors.white,
textSoft: hues.gray[300],
gray: hues.gray,
primary: hues.rose,
secondary: hues.cyan,
}
export const colorsLight = {
...colors,
background: colors.white,
backgroundInverse: colors.black,
backgroundAccent: hues.gray[100],
text: colors.softBlack,
textSoft: hues.gray[700],
gray: hues.gray,
primary: hues.rose,
secondary: hues.cyan,
}
export type Colors = typeof colorsDark
|
const express = require('express');
const app = express();
const fs = require('fs');
app.get('/reports', (req, res) => {
// Create the CSV file
const reportData = [
[1, 'Task 1', 'John Doe', 'In Progress'],
[2, 'Task 2', 'Jane Smith', 'Completed'],
[3, 'Task 3', 'Albert Einstein', 'Not Started'],
];
let csvContent = 'Id,Description,Assigned to,Status\n';
reportData.forEach((row) => {
csvContent += row.join(',') + '\n';
});
// Serve the CSV file
const fileName = 'report.csv';
fs.writeFile(fileName, csvContent, 'utf8', (err) => {
if (err) {
res.status(500).end('An error occurred');
} else {
res.setHeader(
'Content-disposition',
`attachment; filename=${fileName}`
);
res.sendFile(fileName);
}
});
});
app.listen(3000, () => console.log('Server started')); |
#!/bin/bash
# --------------------------------------
# Google search from terminal
# --------------------------------------
# http://unix.stackexchange.com/questions/159166/can-i-pass-commands-to-vimperator-firefox-through-the-command-line
ggr(){
if [ $(echo $1 | egrep "^-[cfs]$") ]; then
local opt="$1"
shift
fi
local opt="safe=off&num=16"
local queries="&q=${*// /+}"
local noises="+-weblio.jp+-matome.naver.jp+-cookpad.com+-itpro.nikkeibp.co.jp+-rakuten.co.jp"
local url="https://www.google.co.jp/search?${opt}${queries}${noises}"
if [ "$(uname)" = 'Darwin' ]; then
local app="/Applications"
local c="${app}/Google Chrome.app"
local f="${app}/Firefox.app"
local s="${app}/Safari.app"
case ${opt} in
"-c") open "${url}" -a "$c";;
"-f") open "${url}" -a "$f";;
"-s") open "${url}" -a "$s";;
*) open "${url}";;
esac
else
firefox $url
fi
}
ggr $*
|
<reponame>Symphoomc1f/krexusj
package com.java110.things.entity.accessControl;
import com.java110.things.entity.PageDto;
import com.java110.things.entity.user.UserAttrDto;
import java.io.Serializable;
import java.util.List;
public class UserFaceDto extends PageDto implements Serializable {
private String userId;
private String taskId;
private String faceBase64;
private String startTime;
private String endTime;
private String name;
private String idNumber;
private String remark;
private String facePath;
private String machineId;
private String machineCode;
private String machineName;
private String machineIp;
private String departmentId;
private String departmentName;
private String personType;
private String link;
private String extUserId;
private String cardId;
private String cardNumber;
private List<UserAttrDto> userAttrDtos;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFaceBase64() {
return faceBase64;
}
public void setFaceBase64(String faceBase64) {
this.faceBase64 = faceBase64;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getFacePath() {
return facePath;
}
public void setFacePath(String facePath) {
this.facePath = facePath;
}
public String getMachineId() {
return machineId;
}
public void setMachineId(String machineId) {
this.machineId = machineId;
}
public String getMachineCode() {
return machineCode;
}
public void setMachineCode(String machineCode) {
this.machineCode = machineCode;
}
public String getMachineName() {
return machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
public String getMachineIp() {
return machineIp;
}
public void setMachineIp(String machineIp) {
this.machineIp = machineIp;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getPersonType() {
return personType;
}
public void setPersonType(String personType) {
this.personType = personType;
}
public List<UserAttrDto> getUserAttrDtos() {
return userAttrDtos;
}
public void setUserAttrDtos(List<UserAttrDto> userAttrDtos) {
this.userAttrDtos = userAttrDtos;
}
public String getExtUserId() {
return extUserId;
}
public void setExtUserId(String extUserId) {
this.extUserId = extUserId;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
}
|
/*
* Copyright 2014-2016 CyberVision, 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.
*/
package org.kaaproject.kaa.server.admin.client.mvp.place;
import com.google.gwt.place.shared.PlaceHistoryMapper;
import com.google.gwt.place.shared.WithTokenizers;
@WithTokenizers({UserProfilePlace.Tokenizer.class,
ApplicationsPlace.Tokenizer.class,
ApplicationPlace.Tokenizer.class,
SdkProfilesPlace.Tokenizer.class,
SdkProfilePlace.Tokenizer.class,
AddSdkProfilePlace.Tokenizer.class,
ProfileSchemasPlace.Tokenizer.class,
ServerProfileSchemasPlace.Tokenizer.class,
ProfileSchemaPlace.Tokenizer.class,
ServerProfileSchemaPlace.Tokenizer.class,
ConfigurationSchemasPlace.Tokenizer.class,
ConfigurationSchemaPlace.Tokenizer.class,
NotificationSchemasPlace.Tokenizer.class,
NotificationSchemaPlace.Tokenizer.class,
LogSchemasPlace.Tokenizer.class,
LogSchemaPlace.Tokenizer.class,
EndpointGroupsPlace.Tokenizer.class,
EndpointGroupPlace.Tokenizer.class,
EndpointProfilesPlace.Tokenizer.class,
EndpointProfilePlace.Tokenizer.class,
ProfileFilterPlace.Tokenizer.class,
ConfigurationPlace.Tokenizer.class,
TopicsPlace.Tokenizer.class,
TopicPlace.Tokenizer.class,
SendNotificationPlace.Tokenizer.class,
AefMapsPlace.Tokenizer.class,
AefMapPlace.Tokenizer.class,
LogAppendersPlace.Tokenizer.class,
LogAppenderPlace.Tokenizer.class,
UserVerifiersPlace.Tokenizer.class,
UserVerifierPlace.Tokenizer.class,
UpdateUserConfigPlace.Tokenizer.class,
TenantCtlSchemasPlace.Tokenizer.class,
ApplicationCtlSchemasPlace.Tokenizer.class,
GetUserConfigPlace.Tokenizer.class,
CtlSchemaPlace.Tokenizer.class})
public interface TenantDeveloperPlaceHistoryMapper extends PlaceHistoryMapper
{
}
|
#!/bin/bash
#============================================================
# https://github.com/P3TERX/Actions-OpenWrt
# File name: diy-part2.sh
# Description: OpenWrt DIY script part 2 (After Update feeds)
# Lisence: MIT
# Author: P3TERX
# Blog: https://p3terx.com
#============================================================
# Modify default IP
sed -i 's/192.168.1.1/192.168.8.18/g' package/base-files/files/bin/config_generate
|
#!/usr/bin/env bash
# Sandbox does not provide CAP_NET_ADMIN capability but does have ProcFS mounted at /proc
# This ensures that OS metrics can be collected
CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=../shell_config.sh
. "$CURDIR"/../shell_config.sh
function read_numbers_func()
{
$CLICKHOUSE_CLIENT -q "
SELECT * FROM numbers(600000000) FORMAT Null SETTINGS max_threads = 1
";
}
function show_processes_func()
{
while true; do
sleep 0.1;
# These two system metrics for the generating query above are guaranteed to be nonzero when ProcFS is mounted at /proc
$CLICKHOUSE_CLIENT -q "
SELECT count() > 0 FROM system.processes\
WHERE ProfileEvents['OSCPUVirtualTimeMicroseconds'] > 0 AND ProfileEvents['OSReadChars'] > 0 \
SETTINGS max_threads = 1
" | grep '1' && break;
done
}
export -f read_numbers_func;
export -f show_processes_func;
TIMEOUT=3
timeout $TIMEOUT bash -c read_numbers_func &
timeout $TIMEOUT bash -c show_processes_func &
wait
echo "Test OK"
|
import {Component} from 'react'
import Head from 'next/head'
import Header from '../components/Header'
import CenteredContent from '../components/CenteredContent'
import Input from '../components/Input'
import Button, {ButtonColor, ButtonSize, ButtonWidth} from '../components/Button'
import User from '../objects/User'
import {checkPassword, checkPasswords, passwordErrorMessage} from '../lib/verify'
import {preventDefault, renderLoading} from '../lib/util'
import {toast} from 'react-hot-toast'
import axios from 'axios'
import {Router, withRouter} from 'next/router'
import FadeAnimation from '../components/FadeAnimation'
interface Props {
user: User
setUser: Function
userLoaded: boolean
router: Router
}
class ChangePassword extends Component<Props> {
state: {
password: string
newPassword: string
newPasswordRepeat: string
forceError: boolean
}
constructor(props) {
super(props)
this.state = {
password: '',
newPassword: '',
newPasswordRepeat: '',
forceError: false
}
}
changePassword() {
if(checkPassword(this.state.newPassword) && checkPasswords(this.state.newPassword, this.state.newPasswordRepeat)) {
toast.promise(axios.post('/api/user/change_password', {password: this.state.password, newPassword: this.state.newPassword, newPasswordRepeat: this.state.newPasswordRepeat}), {
loading: 'Changing password...',
success: () => {
this.props.router.push('/profile')
return 'Password successfully changed'
},
error: 'Invalid password'
})
}
else {
toast.error('There are errors in form')
this.setState({
forceError: true
})
}
}
render() {
if(!this.props.userLoaded) {
return renderLoading()
}
if(!this.props.user) {
this.props.router.push('/sign_in')
return renderLoading()
}
return (
<div>
<Head>
<title>Change password - WatchInSync</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header user={this.props.user} setUser={this.props.setUser}/>
<FadeAnimation>
<CenteredContent width={600}>
<form onSubmit={preventDefault(() => this.changePassword())}>
<Input
type="password"
placeholder="Current password"
value={this.state.password}
onChange={({target}) => this.setState({password: target.value})}
/>
<Input
type="password"
placeholder="<PASSWORD>"
value={this.state.newPassword}
error={passwordErrorMessage(this.state.newPassword)}
forceError={this.state.forceError}
onChange={({target}) => this.setState({newPassword: target.value})}
/>
<Input
type="password"
placeholder="<PASSWORD> password"
value={this.state.newPasswordRepeat}
error={checkPasswords(this.state.newPassword, this.state.newPasswordRepeat) ? '' : 'Passwords are not equal'}
forceError={this.state.forceError}
onChange={({target}) => this.setState({newPasswordRepeat: target.value})}
/>
<Button size={ButtonSize.small} width={ButtonWidth.fullwidth} color={ButtonColor.primary}>
<b>CHANGE PASSWORD</b>
</Button>
</form>
</CenteredContent>
</FadeAnimation>
</div>
)
}
}
export default withRouter(ChangePassword) |
<filename>src/contexts/D3Context.js
import React, { createContext, useReducer } from 'react';
import { d3Reducer } from "../reducers/d3Reducer";
import CanadaOrgChart from "../data/GovernmentCanadaOrgChart/GovernmentOrgChart";
// TODO: break this into multiple contexts/reducers if required
// TODO: consider initialization function that sets the initial state.
const initialState = {
// Identity to keep track of data elements in the d3 visualization
dataIdentity: 0,
// Hard-coding ESDC as the default starting department
dataRoot: CanadaOrgChart["Employment and Social Development Canada"][0],
// TODO: could replace employeeSearchResults with more generic results (e.g. people in business unit)
searchResultsTitle: "",
// Employee search results
employeeSearchResults: [],
// Business unit search results
businessSearchResults: [],
// See Team search results
seeTeamSearchResults: [],
// Node expansion path (this will highlight the path to the node that was searched for).
nodeExpansionPath: null,
// Tooltip coordinates
tooltipCoordinates: null,
// Tooltip node
tooltipHoveredNode: null,
}
export const D3Context = createContext(initialState);
const D3ContextProvider = (props) => {
const [d3State, dispatch] = useReducer(d3Reducer, initialState);
return (
<D3Context.Provider value={{d3State, dispatch}}>
{props.children}
</D3Context.Provider>
)
}
export default D3ContextProvider; |
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-STWS/7-model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-STWS/7-1024+0+512-common-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_common_words_first_two_thirds_sixth --eval_function penultimate_sixth_eval |
def count_non_orderable_non_searchable_columns(config: dict) -> int:
count = 0
for column in config["columns"]:
if not column["orderable"] and not column["searchable"]:
count += 1
return count |
const messages = require('./generated_pb');
const services = require('./generated_grpc_pb');
const grpc = require('grpc');
let client = new services.GomadServiceClient('localhost:8182', grpc.credentials.createInsecure());
let pizza = new messages.Pizza();
console.log("Pizza ingredients: ", pizza.getIngredientsList().length);
let request = new messages.AddIngredientRequest();
request.setArg1(pizza);
request.setArg2(messages.Ingredient.PEPPERONI);
request.setArg3(3);
client.addIngredient(request, function(err, response) {
if (err) {
console.log("FAILED ", err);
}
console.log(response.getIngredientsList()[0].getIngredient() == messages.Ingredient.PEPPERONI);
console.log(response.getIngredientsList()[0].getPortions());
pizza = response;
let request = new messages.RemoveIngredientRequest();
request.setArg1(pizza);
request.setArg2(messages.Ingredient.HAM);
request.setArg3(4);
client.removeIngredient(request, function(err, response) {
if (err) {
console.log("Failed ", err);
return;
}
console.log(response.getIngredientsList()[0].getIngredient() == messages.Ingredient.PEPPERONI);
console.log(response.getIngredientsList()[0].getPortions());
});
});
|
#include <screen.h>
#include <NOS.h>
void main()
{
clearScreen();
NOS();
kshell();
} |
package com.infamous.framework.persistence;
import com.infamous.framework.logging.ZodLogger;
import com.infamous.framework.logging.ZodLoggerUtil;
import java.util.List;
import javax.persistence.LockModeType;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
public abstract class EntityDataStore implements DataStore {
private static final ZodLogger LOGGER = ZodLoggerUtil.getLogger(EntityDataStore.class, "persistence.app");
public EntityDataStore() {
}
@Override
public void close() {
getEntityManager().close();
}
@Override
public void flush() {
getEntityManager().flush();
}
@Override
public boolean isOpen() {
return getEntityManager().isOpen();
}
@Override
public <E> boolean merge(E entity) {
getEntityManager().merge(entity);
return true;
}
/**
// Not use for removing a detached instance
// Use instead {@link #deleteById(Class, Object)}}
**/
@Override
public <E> boolean delete(E entity) {
LOGGER.trace("Delete entity called for : " + entity);
getEntityManager().remove(entity);
LOGGER.trace("Delete entity returned for : " + entity);
return true;
}
@Override
public <E> int deleteAll(Class<E> clazz) {
LOGGER.trace("deleteAll called for : " + clazz);
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaDelete<E> cd = cb.createCriteriaDelete(clazz);
cd.from(clazz);
Query query = getEntityManager().createQuery(cd);
int removedNum = query.executeUpdate();
LOGGER.trace("deleteAll returned for : " + clazz + "Result: " + removedNum);
return removedNum;
}
@Override
public <E> void lock(E entity, LockModeType lockMode) {
getEntityManager().lock(entity, lockMode);
}
@Override
public <E> void lock(E entity) {
lock(entity, LockModeType.PESSIMISTIC_WRITE);
}
@Override
public <E> boolean persist(E entity) {
LOGGER.trace("Persist entity called for : {}", entity);
getEntityManager().persist(entity);
LOGGER.trace("Persist entity returned for : {}", entity);
return true;
}
@Override
public <E> List<E> findByNativeQuery(Class<E> clazz, String query) {
return getEntityManager().createNativeQuery(query, clazz)
.getResultList();
}
@Override
public List findByNativeQuery(String query) {
return getEntityManager().createNativeQuery(query)
.getResultList();
}
@Override
public <E> E findById(Class<E> clazz, Object primaryKey) {
return findById(clazz, primaryKey, LockModeType.PESSIMISTIC_READ);
}
@Override
public <E> E findById(Class<E> clazz, Object primaryKey, LockModeType lockMode) {
LOGGER.trace("findById called for [" + clazz + "] "
+ "with primary key [" + primaryKey + "] and lock mode [" + lockMode
+ "]");
E result = getEntityManager().find(clazz, primaryKey, lockMode);
LOGGER.trace("findById entity returned " + result);
return result;
}
@Override
public <E> List<E> findAll(Class<E> clazz) {
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<E> criteriaQuery = criteriaBuilder.createQuery(clazz);
Root<E> rootEntry = criteriaQuery.from(clazz);
CriteriaQuery<E> all = criteriaQuery.select(rootEntry);
TypedQuery<E> allQuery = getEntityManager().createQuery(all);
return logAndReturnQueryResult("findAll", clazz, allQuery);
}
private <E> List<E> logAndReturnQueryResult(String methodName, Class<E> clazz, TypedQuery<E> allQuery) {
LOGGER.trace(methodName + " called for class: " + clazz + " and query: " + allQuery);
LockModeType lockModeType = allQuery.getLockMode();
if (lockModeType == null) {
allQuery.setLockMode(LockModeType.PESSIMISTIC_READ);
}
List<E> resultList = allQuery.getResultList();
LOGGER.trace(methodName + " returned for class: " + clazz + " and query: " + allQuery);
return resultList;
}
@Override
public <E> boolean deleteById(Class<E> clazz, Object id) {
E entity = findById(clazz,id);
return delete(entity);
}
}
|
<gh_stars>1-10
package battleship;
import java.io.FileWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ScoreFile {
File scores;
//empty constructor to create an instance of this class elsewhere
public ScoreFile() {
scores = new File("scores.txt");
}
//method to print the final score to a text file
public void printScore(int finalScore) {
try {
PrintWriter printW = new PrintWriter(new FileWriter(scores, true));
printW.println(finalScore);
printW.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//method that consults the text file and returns the highest value in there (highscore)
public int highScore() {
int highScore = 0;
if(scores.length() == 0) {
highScore = 0;
} else if (scores.length() != 0) {
try {
Scanner scanner = new Scanner(new FileReader("scores.txt"));
highScore = scanner.nextInt();
while (scanner.hasNextInt()) {
int n = scanner.nextInt();
if (n > highScore) {
highScore = n;
}
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return highScore;
}
}
|
package repository
import (
"github.com/alhamsya/boilerplate-go/infrastructure/external/omdb"
"github.com/alhamsya/boilerplate-go/infrastructure/external/spotify"
)
type OMDBRepo interface {
GetListMovie(search string, page int64) (*omdb.OMDBList, error)
GetDetailMovie(movieID string) (*omdb.OMDBDetail, error)
}
type SpotifyRepo interface {
GetUser() (responseObject *spotify.Profile, err error)
}
|
<reponame>maksimandrianov/cdstructures
// The MIT License (MIT)
// Copyright (c) 2018 <NAME>
//
// 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.
#define CDC_USE_SHORT_NAMES
#include "cdcontainers/avl-tree.h"
#include "cdcontainers/data-info.h"
#include "cdcontainers/tree-utils.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
CDC_MAKE_FIND_NODE_FN(avl_tree_node_t *)
CDC_MAKE_MIN_NODE_FN(avl_tree_node_t *)
CDC_MAKE_MAX_NODE_FN(avl_tree_node_t *)
CDC_MAKE_SUCCESSOR_FN(avl_tree_node_t *)
CDC_MAKE_PREDECESSOR_FN(avl_tree_node_t *)
static avl_tree_node_t *make_new_node(void *key, void *val)
{
avl_tree_node_t *node = (avl_tree_node_t *)malloc(sizeof(avl_tree_node_t));
if (!node) {
return NULL;
}
node->key = key;
node->value = val;
node->height = 1;
node->parent = NULL;
node->left = NULL;
node->right = NULL;
return node;
}
static void free_node(avl_tree_t *t, avl_tree_node_t *node)
{
assert(t != NULL);
if (CDC_HAS_DFREE(t->dinfo)) {
pair_t pair = {node->key, node->value};
t->dinfo->dfree(&pair);
}
free(node);
}
static void free_avl_tree(avl_tree_t *t, avl_tree_node_t *root)
{
assert(t != NULL);
if (root == NULL) {
return;
}
free_avl_tree(t, root->left);
free_avl_tree(t, root->right);
free_node(t, root);
}
static unsigned char height(avl_tree_node_t *node)
{
return node ? node->height : 0;
}
static int height_diff(avl_tree_node_t *node)
{
return height(node->right) - height(node->left);
}
static void update_height(avl_tree_node_t *node)
{
unsigned char lhs = height(node->left);
unsigned char rhs = height(node->right);
node->height = CDC_MAX(lhs, rhs) + 1;
}
static void update_link(avl_tree_node_t *parent, avl_tree_node_t *old_child,
avl_tree_node_t *new_child)
{
new_child->parent = parent;
if (!parent) {
return;
}
if (parent->left == old_child) {
parent->left = new_child;
} else {
parent->right = new_child;
}
}
static void unlink_list(avl_tree_node_t *parent, avl_tree_node_t *child)
{
if (!parent) {
return;
}
if (parent->left == child) {
parent->left = NULL;
} else {
parent->right = NULL;
}
}
static avl_tree_node_t *rotate_right(avl_tree_node_t *node)
{
avl_tree_node_t *q = node->left;
update_link(node->parent, node, q);
node->left = q->right;
if (node->left) {
node->left->parent = node;
}
q->right = node;
if (q->right) {
q->right->parent = q;
}
update_height(node);
update_height(q);
return q;
}
static avl_tree_node_t *rotate_left(avl_tree_node_t *node)
{
avl_tree_node_t *q = node->right;
update_link(node->parent, node, q);
node->right = q->left;
if (node->right) {
node->right->parent = node;
}
q->left = node;
if (q->left) {
q->left->parent = q;
}
update_height(node);
update_height(q);
return q;
}
static avl_tree_node_t *balance(avl_tree_node_t *node)
{
while (node) {
update_height(node);
int diff = height_diff(node);
if (diff == 2) {
if (height_diff(node->right) < 0) {
node->right = rotate_right(node->right);
}
node = rotate_left(node);
} else if (diff == -2) {
if (height_diff(node->left) > 0) {
node->left = rotate_left(node->left);
}
node = rotate_right(node);
} else {
if (node->parent) {
node = node->parent;
} else {
break;
}
}
}
return node;
}
static avl_tree_node_t *insert_unique(avl_tree_t *t, avl_tree_node_t *node,
avl_tree_node_t *nearest)
{
if (t->root != NULL) {
if (t->dinfo->cmp(node->key, nearest->key)) {
nearest->left = node;
} else {
nearest->right = node;
}
node->parent = nearest;
t->root = balance(nearest);
} else {
t->root = node;
}
++t->size;
return node;
}
static avl_tree_node_t *find_hint(avl_tree_node_t *node, void *key, cdc_binary_pred_fn_t compar)
{
while (node) {
if (compar(key, node->key)) {
if (node->left) {
node = node->left;
} else {
break;
}
} else if (compar(node->key, key)) {
if (node->right) {
node = node->right;
} else {
break;
}
} else {
break;
}
}
return node;
}
static avl_tree_node_t *erase_node(avl_tree_t *t, avl_tree_node_t *node)
{
avl_tree_node_t *parent = NULL;
if (node->left == NULL && node->right == NULL) {
parent = node->parent;
unlink_list(parent, node);
} else if (node->right == NULL) {
parent = node->parent;
if (parent) {
if (parent->left == node) {
parent->left = node->left;
parent->left->parent = parent;
} else {
parent->right = node->left;
parent->right->parent = parent;
}
} else {
parent = node->left;
parent->parent = NULL;
}
} else if (node->left == NULL) {
parent = node->parent;
if (parent) {
if (parent->right == node) {
parent->right = node->right;
parent->right->parent = parent;
} else {
parent->left = node->right;
parent->left->parent = parent;
}
} else {
parent = node->right;
parent->parent = NULL;
}
} else {
avl_tree_node_t *mnode = cdc_min_tree_node(node->right);
CDC_SWAP(void *, node->value, mnode->value);
CDC_SWAP(void *, node->key, mnode->key);
parent = mnode->parent;
if (parent == node) {
parent->right = NULL;
} else if (parent) {
parent->left = mnode->right;
if (mnode->right) {
mnode->right->parent = parent;
}
}
node = mnode;
}
free_node(t, node);
return balance(parent);
}
static stat_t init_varg(avl_tree_t *t, va_list args)
{
pair_t *pair = NULL;
while ((pair = va_arg(args, pair_t *)) != CDC_END) {
stat_t stat = avl_tree_insert(t, pair->first, pair->second, NULL);
if (stat != CDC_STATUS_OK) {
return stat;
}
}
return CDC_STATUS_OK;
}
stat_t avl_tree_ctor(avl_tree_t **t, data_info_t *info)
{
assert(t != NULL);
assert(CDC_HAS_CMP(info));
avl_tree_t *tmp = (avl_tree_t *)calloc(sizeof(avl_tree_t), 1);
if (!tmp) {
return CDC_STATUS_BAD_ALLOC;
}
if (info && !(tmp->dinfo = di_shared_ctorc(info))) {
free(tmp);
return CDC_STATUS_BAD_ALLOC;
}
*t = tmp;
return CDC_STATUS_OK;
}
stat_t avl_tree_ctorl(avl_tree_t **t, data_info_t *info, ...)
{
assert(t != NULL);
assert(CDC_HAS_CMP(info));
va_list args;
va_start(args, info);
stat_t stat = avl_tree_ctorv(t, info, args);
va_end(args);
return stat;
}
stat_t avl_tree_ctorv(avl_tree_t **t, data_info_t *info, va_list args)
{
assert(t != NULL);
assert(CDC_HAS_CMP(info));
stat_t stat = avl_tree_ctor(t, info);
if (stat != CDC_STATUS_OK) {
return stat;
}
return init_varg(*t, args);
}
void avl_tree_dtor(avl_tree_t *t)
{
assert(t != NULL);
free_avl_tree(t, t->root);
di_shared_dtor(t->dinfo);
free(t);
}
stat_t avl_tree_get(avl_tree_t *t, void *key, void **value)
{
assert(t != NULL);
avl_tree_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp);
if (node) {
*value = node->value;
return CDC_STATUS_OK;
}
return CDC_STATUS_NOT_FOUND;
}
size_t avl_tree_count(avl_tree_t *t, void *key)
{
assert(t != NULL);
return (size_t)(cdc_find_tree_node(t->root, key, t->dinfo->cmp) != NULL);
}
void avl_tree_find(avl_tree_t *t, void *key, avl_tree_iter_t *it)
{
assert(t != NULL);
assert(it != NULL);
avl_tree_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp);
if (!node) {
avl_tree_end(t, it);
return;
}
it->container = t;
it->current = node;
it->prev = cdc_tree_predecessor(node);
}
stat_t avl_tree_insert(avl_tree_t *t, void *key, void *value, pair_avl_tree_iter_bool_t *ret)
{
assert(t != NULL);
avl_tree_iter_t *it = NULL;
bool *inserted = NULL;
if (ret) {
it = &ret->first;
inserted = &ret->second;
}
return avl_tree_insert1(t, key, value, it, inserted);
}
stat_t avl_tree_insert1(avl_tree_t *t, void *key, void *value, avl_tree_iter_t *it, bool *inserted)
{
assert(t != NULL);
avl_tree_node_t *node = find_hint(t->root, key, t->dinfo->cmp);
bool finded = node && cdc_eq(t->dinfo->cmp, node->key, key);
if (!finded) {
avl_tree_node_t *new_node = make_new_node(key, value);
if (!new_node) {
return CDC_STATUS_BAD_ALLOC;
}
node = insert_unique(t, new_node, node);
}
if (it) {
it->container = t;
it->current = node;
it->prev = cdc_tree_predecessor(node);
}
if (inserted) {
*inserted = !finded;
}
return CDC_STATUS_OK;
}
stat_t avl_tree_insert_or_assign(avl_tree_t *t, void *key, void *value,
pair_avl_tree_iter_bool_t *ret)
{
assert(t != NULL);
avl_tree_iter_t *it = NULL;
bool *inserted = NULL;
if (ret) {
it = &ret->first;
inserted = &ret->second;
}
return avl_tree_insert_or_assign1(t, key, value, it, inserted);
}
stat_t avl_tree_insert_or_assign1(avl_tree_t *t, void *key, void *value, avl_tree_iter_t *it,
bool *inserted)
{
assert(t != NULL);
avl_tree_node_t *node = find_hint(t->root, key, t->dinfo->cmp);
bool finded = node && cdc_eq(t->dinfo->cmp, node->key, key);
if (!finded) {
avl_tree_node_t *new_node = make_new_node(key, value);
if (!new_node) {
return CDC_STATUS_BAD_ALLOC;
}
node = insert_unique(t, new_node, node);
} else {
node->value = value;
}
if (it) {
it->container = t;
it->current = node;
it->prev = cdc_tree_predecessor(node);
}
if (inserted) {
*inserted = !finded;
}
return CDC_STATUS_OK;
}
size_t avl_tree_erase(avl_tree_t *t, void *key)
{
assert(t != NULL);
avl_tree_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp);
if (!node) {
return 0;
}
t->root = erase_node(t, node);
--t->size;
return 1;
}
void avl_tree_clear(avl_tree_t *t)
{
assert(t != NULL);
free_avl_tree(t, t->root);
t->size = 0;
t->root = NULL;
}
void avl_tree_swap(avl_tree_t *a, avl_tree_t *b)
{
assert(a != NULL);
assert(b != NULL);
CDC_SWAP(avl_tree_node_t *, a->root, b->root);
CDC_SWAP(size_t, a->size, b->size);
CDC_SWAP(data_info_t *, a->dinfo, b->dinfo);
}
void avl_tree_begin(avl_tree_t *t, avl_tree_iter_t *it)
{
assert(t != NULL);
assert(it != NULL);
it->container = t;
it->current = cdc_min_tree_node(t->root);
it->prev = NULL;
}
void avl_tree_end(avl_tree_t *t, avl_tree_iter_t *it)
{
assert(t != NULL);
assert(it != NULL);
it->container = t;
it->current = NULL;
it->prev = cdc_max_tree_node(t->root);
}
void avl_tree_iter_next(avl_tree_iter_t *it)
{
assert(it != NULL);
it->prev = it->current;
it->current = cdc_tree_successor(it->current);
}
void avl_tree_iter_prev(avl_tree_iter_t *it)
{
assert(it != NULL);
it->current = it->prev;
it->prev = cdc_tree_predecessor(it->current);
}
|
<reponame>ppolxda/pydbgen
# -*- coding: utf-8 -*-
import os
import sys
import six
import json
import argparse
import itertools
from collections import OrderedDict
from google.protobuf.compiler import plugin_pb2 as plugin
from google.protobuf.descriptor_pb2 import FieldOptions
from google.protobuf.descriptor_pb2 import DescriptorProto
from google.protobuf.descriptor_pb2 import EnumDescriptorProto
from google.protobuf.descriptor import FieldDescriptor
from pydbgen.pbclass import data_define_pb2
MY_OPTIONS = [
getattr(data_define_pb2, key)
for key in FieldOptions._extensions_by_name.keys()
if hasattr(data_define_pb2, key)
]
LABEL_CHANGE = {
FieldDescriptor.LABEL_OPTIONAL: 'optional',
FieldDescriptor.LABEL_REQUIRED: 'required',
FieldDescriptor.LABEL_REPEATED: 'repeated',
}
TYPE_CHANGE = {
FieldDescriptor.TYPE_DOUBLE: 'double',
FieldDescriptor.TYPE_FLOAT: 'float',
FieldDescriptor.TYPE_INT64: 'int64',
FieldDescriptor.TYPE_UINT64: 'uint64',
FieldDescriptor.TYPE_INT32: 'int32',
FieldDescriptor.TYPE_FIXED64: 'fixed64',
FieldDescriptor.TYPE_FIXED32: 'fixed32',
FieldDescriptor.TYPE_BOOL: 'bool',
FieldDescriptor.TYPE_STRING: 'string',
FieldDescriptor.TYPE_GROUP: 'group',
FieldDescriptor.TYPE_MESSAGE: 'message',
FieldDescriptor.TYPE_BYTES: 'bytes',
FieldDescriptor.TYPE_UINT32: 'uint32',
FieldDescriptor.TYPE_ENUM: 'enum',
FieldDescriptor.TYPE_SFIXED32: 'sfixed32',
FieldDescriptor.TYPE_SFIXED64: 'sfixed64',
FieldDescriptor.TYPE_SINT32: 'sint32',
FieldDescriptor.TYPE_SINT64: 'sint64'
}
TYPE_DEFVAL = {
FieldDescriptor.TYPE_DOUBLE: 0.0,
FieldDescriptor.TYPE_FLOAT: 0.0,
FieldDescriptor.TYPE_INT64: 0,
FieldDescriptor.TYPE_UINT64: 0,
FieldDescriptor.TYPE_INT32: 0,
FieldDescriptor.TYPE_FIXED64: 0,
FieldDescriptor.TYPE_FIXED32: 0,
FieldDescriptor.TYPE_BOOL: False,
FieldDescriptor.TYPE_STRING: '',
FieldDescriptor.TYPE_GROUP: '',
FieldDescriptor.TYPE_MESSAGE: '',
FieldDescriptor.TYPE_BYTES: '',
FieldDescriptor.TYPE_UINT32: 0,
FieldDescriptor.TYPE_ENUM: 0,
FieldDescriptor.TYPE_SFIXED32: 0,
FieldDescriptor.TYPE_SFIXED64: 0,
FieldDescriptor.TYPE_SINT32: 0,
FieldDescriptor.TYPE_SINT64: 0
}
class EnumPathIndex(object):
"""PROTOC PATH INDEX."""
NAME = 1
FIELD = 2
NESTED = 3
MESSAGE = 4
ENUM = 5
SERVICE = 6
class Cmdoptions(object):
def __init__(self):
parser = argparse.ArgumentParser(
description='pydbgen.pbclass.protoc_gen_json')
parser.add_argument('-o', '--output',
type=str, default=None,
help='ouput path')
parser.add_argument('-e', '--encoding', default='utf8',
help='output encoding(default: utf8)')
args = parser.parse_args()
self.output = args.output
self.encoding = args.encoding
def strip(val):
while val and val[0] == '/':
val = val[1:]
return val.strip()
def _locations(locations, pathtype, i, last_path=tuple()):
# location.leading_comments
# location.trailing_comments
# location.leading_detached_comments
# result = locations[local_path + (EnumPathIndex.FIELD, i)]
full_path = last_path + (pathtype, i)
result = locations.get(full_path, None)
if result is None:
class EnumLog(object):
trailing_comments = ''
leading_comments = ''
leading_detached_comments = ''
return EnumLog
return result
def default_json(name, typename, comment='', fields={},
options={}, nesteds={}, enums={}):
assert isinstance(fields, dict)
assert isinstance(options, dict)
assert isinstance(nesteds, dict)
return OrderedDict([
("type", typename),
("name", name),
("comment", comment),
("fields", fields),
("options", options),
("enums", enums),
("nesteds", nesteds),
])
def field_json(name, value, type, defval,
comment, options={}, soptions={}):
options.update(soptions)
return OrderedDict([
("name", name),
("value", value),
("type", type),
("defval", defval),
("comment", comment),
("options", options),
])
def enums2json(items, locations, path=tuple()):
# assert isinstance(items, list)
assert isinstance(locations, dict)
assert isinstance(path, tuple)
# location.leading_comments
# location.trailing_comments
# location.leading_detached_comments
result = {}
for index, item in enumerate(items):
local_path = (EnumPathIndex.ENUM, index)
cur_path = path + local_path
assert isinstance(item, EnumDescriptorProto)
result[item.name] = default_json(
item.name, 'enum',
comment=strip(_locations(locations, EnumPathIndex.ENUM, index, path).leading_comments), # noqa
fields=OrderedDict([(
v.name, field_json(
v.name, v.number, 'int32', 0,
strip(_locations(locations, EnumPathIndex.FIELD, i, cur_path).trailing_comments))) # noqa
for i, v in enumerate(item.value)
]))
return result
def message2json(items, locations, path=tuple()):
# assert isinstance(items, list)
assert isinstance(locations, dict)
assert isinstance(path, tuple)
result = {}
for index, item in enumerate(items):
local_path = (EnumPathIndex.MESSAGE, index)
cur_path = path + local_path
assert isinstance(item, DescriptorProto)
result[item.name] = default_json(
item.name, 'message',
comment=strip(_locations(locations, EnumPathIndex.MESSAGE, index).leading_comments), # noqa
nesteds=message2json(item.nested_type, locations, cur_path),
enums=enums2json(item.enum_type, locations, cur_path),
fields=OrderedDict([(
v.name, field_json(
v.name, v.number,
TYPE_CHANGE.get(v.type, '--'),
v.default_value if v.default_value else TYPE_DEFVAL.get(v.type, ''), # noqa
strip(_locations(locations, EnumPathIndex.FIELD, i, cur_path).trailing_comments), # noqa
options=OrderedDict([
('label', LABEL_CHANGE[v.label]),
('type_name', v.type_name),
('extendee', v.extendee),
('default_value', v.default_value),
('json_name', v.json_name),
]),
soptions=OrderedDict([
(
val.name,
v.options.Extensions[val]
)
for val in MY_OPTIONS
if v.options.HasExtension(val)
]))
) for i, v in enumerate(item.field)
]),
options=OrderedDict([
('message_set_wire_format', item.options.message_set_wire_format), # noqa
('no_standard_descriptor_accessor', item.options.no_standard_descriptor_accessor), # noqa
('deprecated', item.options.deprecated), # noqa
])
)
return result
def generate_json(request, step_files=['pydbgen', 'google/protobuf']):
for filename in request.file_to_generate:
output = OrderedDict([
("type", "root"),
("name", "root"),
("package", "root"),
("filename", filename),
("comment", "root"),
("enums", {}),
("nesteds", {}),
])
for proto_file in request.proto_file:
step = False
for i in step_files:
if proto_file.name.replace('\\', '/').find(i) >= 0:
step = True
if step:
continue
if proto_file.name != filename:
continue
output['filename'] = proto_file.name
output['package'] = proto_file.package
locations = proto_file.source_code_info.location
locations = {
tuple(location.path): location
for location in locations
}
enums = enums2json(proto_file.enum_type, locations)
inset = set(output['enums'].keys()).intersection(set(enums.keys()))
if inset:
raise TypeError('enum name duplicate[{}]'.format(inset))
output['enums'].update(enums)
msgs = message2json(proto_file.message_type, locations)
inset = set(output['nesteds'].keys()).intersection(
set(msgs.keys()))
if inset:
raise TypeError('messages name duplicate[{}]'.format(inset))
output['nesteds'].update(msgs)
yield filename, output
def generate_code(opts, request, response):
for filename, output in generate_json(request):
fout = response.file.add()
if opts.output:
fout.name = opts.output
else:
fout.name = filename + '.json'
fout.content = json.dumps(output, indent=4)
# open('test.json', 'w').write(
# json.dumps(generate_json(request), indent=4))
def main():
# Read request message from stdin
OPTS = Cmdoptions()
if six.PY2:
DATA = sys.stdin.read()
else:
DATA = sys.stdin.buffer.read()
# open('test.dat', 'wb').write(DATA)
# DATA = open('test.dat', 'rb').read()
# Parse request
REQUEST = plugin.CodeGeneratorRequest()
REQUEST.ParseFromString(DATA)
# Create response
RESPONSE = plugin.CodeGeneratorResponse()
# Generate code
generate_code(OPTS, REQUEST, RESPONSE)
# Serialise response message
OUTPUT = RESPONSE.SerializeToString()
# Write to stdout
if six.PY2:
sys.stdout.write(OUTPUT)
else:
sys.stdout.buffer.write(OUTPUT)
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
from enum import Enum
class ConflictAction(Enum):
"""Possible actions to take on a conflict.
"""
NOTHING = "NOTHING"
UPDATE = "UPDATE"
@classmethod
def all(cls):
return [choice for choice in cls]
|
<gh_stars>0
/*
* Copyright (c) 2007-2013 Concurrent, Inc. All Rights Reserved.
*
* Project and contact information: http://www.cascading.org/
*
* This file is part of the Cascading 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.
*/
package cascading.property;
import java.util.Map;
import java.util.Properties;
/**
* Class Props is the base class for frameworks specific properties helper classes.
* <p/>
* Use the sub-classes to either create a {@link Properties} instance with custom or default values to be passed
* to any sub-system that requires a Map or Properties instance of properties and values.
*/
public abstract class Props
{
/**
* Method buildProperties returns a new {@link Properties} instance with all property values for this type.
* <p/>
* If no values have been set, all default properties and values will be returned.
*
* @return a new Properties instance
*/
public Properties buildProperties()
{
return buildProperties( (Properties) null );
}
/**
* Method buildProperties returns a new {@link Properties} instance with all property values for this type
* using the given Map of property values as defaults. The given Map will not be modified.
* <p/>
* If no values have been set, all default properties and values will be returned.
*
* @return a new Properties instance
*/
public Properties buildProperties( Map<Object, Object> defaultProperties )
{
return buildProperties( PropertyUtil.createProperties( defaultProperties, null ) );
}
/**
* Method buildProperties returns a new {@link Properties} instance with all property values for this type
* using the given Iterable<Map.Entry<String, String>> of property values as defaults. The given Iterable will not be modified.
* <p/>
* If no values have been set, all default properties and values will be returned.
*
* @return a new Properties instance
*/
public Properties buildProperties( Iterable<Map.Entry<String, String>> defaultProperties )
{
return buildProperties( PropertyUtil.createProperties( defaultProperties ) );
}
/**
* Method buildProperties returns a new {@link Properties} instance with all property values for this type
* using the given Properties instance of property values as defaults. The given Map will not be modified.
* <p/>
* If no values have been set, all default properties and values will be returned.
*
* @return a new Properties instance
*/
public Properties buildProperties( Properties defaultProperties )
{
defaultProperties = defaultProperties != null ? new Properties( defaultProperties ) : new Properties();
addPropertiesTo( defaultProperties );
return defaultProperties;
}
public ConfigDef setProperties( ConfigDef configDef )
{
return setProperties( configDef, ConfigDef.Mode.REPLACE );
}
public ConfigDef setProperties( ConfigDef configDef, ConfigDef.Mode mode )
{
Properties properties = buildProperties();
for( String name : properties.stringPropertyNames() )
configDef.setProperty( mode, name, properties.getProperty( name ) );
return configDef;
}
protected abstract void addPropertiesTo( Properties properties );
}
|
import dash
import dash_bootstrap_components as dbc
external_stylesheets = [dbc.themes.CERULEAN, 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets, suppress_callback_exceptions=True)
server = app.server |
/**
* jQuery plugin to assist with adding/removing of entries
* from a Palmtree Form CollectionType form field.
*
* Basic usage: $('#collection').palmtreeFormCollection();
* With options: $('#collection').palmtreeFormCollection({
* labels: {
* add: 'Add Thing',
* remove: 'Remove Thing'
* }
* });
*
* @author <NAME>
*/
(function (factory) {
'use strict';
/* global define:false */
if (typeof define !== 'undefined' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory(require('jquery'));
} else {
factory(window.jQuery);
}
})(function ($) {
'use strict';
var pluginName = 'palmtreeFormCollection';
/**
* @param {Element} element
* @param {{}} options
* @constructor
*/
function Plugin(element, options) {
this.$collection = $(element);
this.$entriesWrapper = this.$collection.children('.palmtree-form-collection-entries');
this.options = $.extend(true, {}, $.fn[pluginName].defaults, options);
this.$collection.data('index', this.$entriesWrapper.children().length);
this.$addEntryLink = $('<button type="button" class="add-entry-link btn btn-primary">' + this.options.labels.add + '</button>');
this.removeEntryLink = '<button type="button" class="remove-entry-link btn btn-sm btn-danger">' + this.options.labels.remove + '</button>';
var _this = this;
this.$entriesWrapper.children().each(function () {
_this.addRemoveLink($(this));
});
this.$collection.on('click', '.remove-entry-link', function (e) {
e.preventDefault();
e.stopPropagation();
_this.removeEntry($(this).closest('.palmtree-form-collection-entry'));
});
this.$collection.after(this.$addEntryLink);
this.$addEntryLink.on('click', function (e) {
e.preventDefault();
_this.addEntry();
});
for (var i = this.getTotalEntries(); i < this.options.minEntries; i++) {
this.addEntry();
}
if (this.hasMaxEntries()) {
this.$addEntryLink.addClass('disabled');
}
}
Plugin.prototype = {
addEntry: function () {
if (this.hasMaxEntries()) {
return false;
}
var index = this.$collection.data('index'),
prototype;
if (this.options.prototype) {
prototype = this.options.prototype;
} else {
prototype = this.$collection.data('prototype')
.replace(/\[-1]/g, '[' + index + ']')
.replace(/(id|for)="([^\s]+)--1"/g, '$1="$2-' + index + '"');
}
var $entry = $(prototype);
$entry.data('index', this.$collection.data('index'));
this.addRemoveLink($entry);
this.$entriesWrapper.append($entry);
this.$collection.data('index', index + 1);
this.$collection.trigger('addedEntry.palmtreeFormCollection', [$entry, this]);
if (this.hasMaxEntries()) {
this.$addEntryLink.addClass('disabled');
}
},
/**
*
* @param {jQuery} $entry
*/
removeEntry: function ($entry) {
if (this.options.minEntries === this.getTotalEntries()) {
return;
}
this.$collection.triggerHandler('removeEntry.palmtreeFormCollection', [$entry, this]);
$entry.remove();
this.$collection.triggerHandler('removedEntry.palmtreeFormCollection', [this]);
if (!this.hasMaxEntries()) {
this.$addEntryLink.removeClass('disabled');
}
},
addRemoveLink: function ($entry) {
$entry.append($(this.removeEntryLink));
},
/**
* @returns {number}
*/
getTotalEntries: function () {
return this.$entriesWrapper.children().length;
},
/**
* @returns {boolean}
*/
hasMaxEntries: function () {
return this.options.maxEntries > -1 && this.getTotalEntries() >= this.options.maxEntries;
}
};
$.fn[pluginName] = function () {
var args = arguments;
return this.each(function () {
var plugin = $(this).data(pluginName);
if (!plugin) {
plugin = new Plugin(this, args[0]);
$(this).data(pluginName, plugin);
}
if (typeof args[0] === 'string') {
plugin[args[0]].apply(plugin, Array.prototype.slice.call(args, 1));
}
});
};
$.fn[pluginName].defaults = {
prototype: null,
labels: {
add: 'Add Entry',
remove: 'Remove'
},
minEntries: 0,
maxEntries: -1
};
});
|
package cfg.serialize.cfgdata;
import java.nio.ByteBuffer;
import java.util.List;
import cfg.serialize.FieldDataFormat;
import cfg.serialize.FieldKey;
import cfg.serialize.FieldRangeType;
import cfg.serialize.exceptions.SheetDataException;
import cfg.settings.Settings;
import cfg.settings.sys.BuffSetting;
import cfg.source.data.SheetDefine;
import cfg.source.data.SheetInfo;
public class BinarySheetHandler implements ISheetHandler {
private IItemHandler binaryItemHandler = new BinaryItemHandler();
private ByteBuffer bb = null;
private SheetInfo sheetInfo;
private SheetDefine sheetDefine;
private FieldDataFormat[] attrDataTypes;
private List<String[]> dataList;
public BinarySheetHandler() {
super();
BuffSetting bs = Settings.getInstance().getSysSettings().getBuffSettings();
this.bb = ByteBuffer.allocate(bs.getSheetBuffLen());
this.bb.order(bs.byteOrder());
}
@Override
public void config(SheetInfo sheetInfo) {
this.sheetInfo = sheetInfo;
this.sheetDefine = this.sheetInfo.getDefine();
this.attrDataTypes = this.sheetDefine.getFieldDataFormats();
this.dataList = this.sheetInfo.getDataList();
}
@Override
public Object serialize(FieldRangeType exportType, FieldKey attrKeyType) throws SheetDataException {
this.start();
Integer[] indexs = sheetDefine.getExportInfo(exportType).getValidIndexs();
this.start();
int i = 0;
try {
for (i = 0; i < this.dataList.size(); i++) {
String[] strings = this.dataList.get(i);
binaryItemHandler.start();
binaryItemHandler.appends(indexs, attrDataTypes, null, strings);
binaryItemHandler.finish();
byte[] data = (byte[]) binaryItemHandler.getSerializedData();
this.append(data);
}
} catch (SheetDataException e) {
e.setRow(i + Settings.getInstance().getProjectSettings().getStartRowIndex());
throw e;
}
this.finish();
return this.getSerializedData();
}
@Override
public void start() {
this.bb.clear();
return;
}
@Override
public void append(Object item) {
if (item instanceof byte[]) {
this.bb.put((byte[]) item);
} else if (item instanceof Byte) {
this.bb.put((Byte) item);
}
}
@Override
public void append(Object[] items) {
for (Object b : items) {
this.append(b);
}
}
@Override
public void finish() {
this.bb.flip();
}
@Override
public Object getSerializedData() {
byte[] rs = new byte[this.bb.limit()];
this.bb.get(rs);
return rs;
}
}
|
<reponame>huangbin082/Bin<filename>Algorithm/src/main/java/com/leetcode/Solution_1847.java
package com.leetcode;
import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeSet;
public class Solution_1847 {
public int[] closestRoom(int[][] rooms, int[][] queries) {
TreeSet<Room> treeSet = new TreeSet<>(Comparator.comparingInt(a -> a.id));
int[][] newQ = new int[queries.length][4];
for (int i = 0; i < queries.length; i++) {
newQ[i][0] = queries[i][0];
newQ[i][1] = queries[i][1];
newQ[i][2] = i;
newQ[i][3] = -1;
}
Arrays.sort(rooms, Comparator.comparingInt(a -> a[1]));
Arrays.sort(newQ, Comparator.comparingInt(a -> -a[1]));
for (int i = 0; i < newQ.length; i++) {
if (newQ[i][1] <= rooms[rooms.length - 1][1]) {
for (int j = rooms.length - treeSet.size() - 1; j >= 0; j--) {
if (newQ[i][1] <= rooms[j][1]) {
treeSet.add(new Room(rooms[j][0], rooms[j][1]));
} else {
break;
}
}
Room room = new Room(newQ[i][0], newQ[i][1]);
Room f = treeSet.floor(room);
Room c = treeSet.ceiling(room);
if (f == null) {
newQ[i][3] = c.id;
} else if (c == null) {
newQ[i][3] = f.id;
} else {
newQ[i][3] = Math.abs(newQ[i][0] - f.id) <= Math.abs(newQ[i][0] - c.id) ? f.id : c.id;
}
}
}
int[] ans = new int[newQ.length];
for (int i = 0; i < newQ.length; i++) {
ans[newQ[i][2]] = newQ[i][3];
}
return ans;
}
public class Room {
int id;
int size;
public Room(int id, int size) {
this.id = id;
this.size = size;
}
}
}
|
from enum import Enum
class Description(Enum):
missing_file = "Missing sprite"
missing_file_name = "Missing file name"
missing_fusion_id = "Unable to identify fusion sprite"
different_fusion_id = "Different fusion IDs"
invalid_fusion_id = "Invalid fusion ID"
sprite_error = "Invalid sprite"
sprite_issue = "Controversial sprite"
icon = "Fusion icon"
custom = "Custom sprite"
error = "Please contact Aegide"
test = "Description test" |
with open('input_file.txt', 'r') as infile, open('output_file.txt', 'w') as out:
for inl in infile:
if inl.startswith('#CHROM'):
tem = inl.strip().split('\t')[9:]
out.write('Chr\tPos\tRef\tAlt\t%s\n' % '\t'.join(tem))
out.flush()
if not inl.startswith('#'):
tem = inl.strip().split('\t')
chr = tem[0]
pos = tem[1]
ref = tem[3]
alt = tem[4].split(',')
geno = tem[9:]
res = '%s\t%s\t%s\t%s' % (chr, pos, ref, ','.join(alt))
out.write(res + '\n')
out.flush() |
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
# Set up the sentiment analyzer
sid = SentimentIntensityAnalyzer()
# Get the sentiment from the text
text = "I love this movie!"
scores = sid.polarity_scores(text)
# Output the results
for k in sorted(scores):
print(k, ':', scores[k])
print('Sentiment:', 'positive' if scores['compound'] > 0.05 else 'negative') |
export const bold = (s: string) => `*${s}*`;
export const italic = (s: string) => `_${s}_`;
export const stroke = (s: string) => `~${s}~`;
export const monospace = (s: string) => `\`\`\`${s}\`\`\``;
|
#!/bin/sh
# Copyright 2016 Google 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.
#
################################################################################
pushd $SRC/dropbear
autoconf
autoheader
popd
$SRC/dropbear/configure --enable-fuzz
# force static zlib
sed -i 's@-lz@/usr/lib/x86_64-linux-gnu/libz.a@' Makefile
make -j$(nproc) fuzz-targets FUZZLIB=$LIB_FUZZING_ENGINE
TARGETS="$(make list-fuzz-targets)"
make -C $SRC/dropbear/corpus
cp -v $TARGETS $OUT/
cp -v $SRC/*.options $OUT/
cp -v $SRC/dropbear/corpus/*.zip $OUT/
|
g++ main.cpp -o win_test.exe -DSFML_STATIC -I/c/mingw64/usr/SFML-2.5.0/include/ -L/c/mingw64/usr/SFML-2.5.0/lib/ -lsfml-graphics-s -lsfml-window-s -lsfml-audio-s -lsfml-system-s -lwinmm -lgdi32 -lopengl32 -lfreetype -lopenal32 -lflac -lvorbisenc -lvorbisfile -lvorbis -logg
|
const MongoClient = require('mongodb').MongoClient;
const dbName = "database";
const collection = "collection";
const parameter = {"field": "true"};
MongoClient.connect('mongodb://localhost:27017', (err, db) => {
if (err) throw err;
const dbo = db.db(dbName);
dbo.collection(collection).find(parameter).toArray((err, result) => {
if (err) throw err;
console.log(result);
db.close();
});
}); |
<filename>firebase.config.js
// eslint-disable-next-line import/prefer-default-export
export const firebaseConfig = {
apiKey: '<KEY>',
authDomain: 'splace-9175b.firebaseapp.com',
databaseURL: 'https://splace-9175b-default-rtdb.europe-west1.firebasedatabase.app',
projectId: 'splace-9175b',
storageBucket: 'splace-9175b.appspot.com',
messagingSenderId: '263050248969',
appId: '1:263050248969:web:9f99ac01c89c2c050d49d8',
measurementId: 'G-JT4VN8LJQY',
};
|
<filename>src/compare_files.py
import filecmp
from .types import FsPath
class CompareFiles():
"""Provides the basic interface needed by the filehandler when comparing files.
This implementation simply does a filecmp.
"""
def compare(self, f1: FsPath, f2: FsPath) -> bool:
"""Compare two files"""
if f1.stat().st_size != f2.stat().st_size:
return False
return filecmp.cmp(f1, f2, shallow=False)
|
#!/usr/bin/env bash
cd ~/IF-VAE-Recommendation
python tune_parameters.py -d data/movielens20m/ -n movielens20m/vae-part2.csv -y config/vae-part2.yml
|
#!/bin/bash
#
# Copyright (C) 2016 The CyanogenMod Project
# Copyright (C) 2017-2020 The LineageOS Project
#
# SPDX-License-Identifier: Apache-2.0
#
function blob_fixup() {
case "${1}" in
esac
}
# If we're being sourced by the common script that we called,
# stop right here. No need to go down the rabbit hole.
if [ "${BASH_SOURCE[0]}" != "${0}" ]; then
return
fi
set -e
export DEVICE=gts3lwifi
export DEVICE_COMMON=gts3l-common
export VENDOR=samsung
"./../../${VENDOR}/${DEVICE_COMMON}/extract-files.sh" "$@"
|
<filename>tests/com.archimatetool.jasperreports.tests/src/com/archimatetool/jasperreports/AllTests.java
/**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.jasperreports;
import junit.framework.TestSuite;
import com.archimatetool.jasperreports.data.ArchimateModelDataSourceTests;
import com.archimatetool.jasperreports.data.ElementsDataSourceTests;
import com.archimatetool.jasperreports.data.FieldDataFactoryTests;
import com.archimatetool.jasperreports.data.PropertiesModelDataSourceTests;
import com.archimatetool.jasperreports.data.ViewChildrenDataSourceTests;
import com.archimatetool.jasperreports.data.ViewModelDataSourceTests;
@SuppressWarnings("nls")
public class AllTests {
public static junit.framework.Test suite() {
TestSuite suite = new TestSuite("com.archimatetool.jasperreports");
suite.addTest(JasperReportsExporterTests.suite());
suite.addTest(ArchimateModelDataSourceTests.suite());
suite.addTest(ElementsDataSourceTests.suite());
suite.addTest(FieldDataFactoryTests.suite());
suite.addTest(PropertiesModelDataSourceTests.suite());
suite.addTest(ViewChildrenDataSourceTests.suite());
suite.addTest(ViewModelDataSourceTests.suite());
return suite;
}
} |
class Int100Checker:
def check(self, computation):
output = computation()
# check the postcondition is true
if not isinstance(output, int) or output < 0 or output > 100:
# raise an exception
raise TypeError('output should be an integer between 0 and 100')
return computation() |
import { module, test } from 'qunit';
import { setupApplicationTest } from 'cargo/tests/helpers';
import { visit } from '../helpers/visit-ignoring-abort';
let s = new URLSearchParams(window.location.search);
if (s.has('devmode')) {
/**
* This module will only be available if the "Development Mode" option of QUnit is chosen
* @link http://localhost:4200/tests/?notrycatch&devmode&filter=Development%20Mode
*/
module('Development Mode', function (hooks) {
setupApplicationTest(hooks);
test('authenticated', async function () {
let user = this.server.create('user');
this.authenticateAs(user);
let crate = this.server.create('crate', { name: 'foo' });
this.server.create('version', { crate, num: '0.1.0' });
this.server.create('crate-ownership', { crate, user });
crate = this.server.create('crate', { name: 'bar' });
this.server.create('version', { crate, num: '1.0.0' });
let router = this.owner.lookup('service:router');
router.on('routeDidChange', () => {
console.log(`URL: ${router.currentURL}`);
});
await visit('/');
// eslint-disable-next-line ember/no-pause-test
await this.pauseTest();
});
});
}
|
export * from './mesh.directive'; |
#!/usr/bin/env bash
uwsgi --ini uwsgi.ini --py-autoreload 1
|
#!/bin/bash
# Reads the card ID or the folder name with audio files
# from the command line (see Usage).
# Then attempts to get the folder name from the card ID
# or play audio folder content directly
#
# Usage for card ID
# ./rfid_trigger_play.sh -i=1234567890
# or
# ./rfid_trigger_play.sh --cardid=1234567890
#
# For folder names:
# ./rfid_trigger_play.sh -d='foldername'
# or
# ./rfid_trigger_play.sh --dir='foldername'
#
# or for recursive play of sudfolders
# ./rfid_trigger_play.sh -d='foldername' -v=recursive
# ADD / EDIT RFID CARDS TO CONTROL THE PHONIEBOX
# All controls are assigned to RFID cards in this
# file:
# settings/rfid_trigger_play.conf
# Please consult this file for more information.
# Do NOT edit anything in this file.
# Set the date and time of now
NOW=`date +%Y-%m-%d.%H:%M:%S`
# The absolute path to the folder whjch contains all the scripts.
# Unless you are working with symlinks, leave the following line untouched.
PATHDATA="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
#############################################################
# $DEBUG TRUE|FALSE
# Read debug logging configuration file
. $PATHDATA/../settings/debugLogging.conf
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "########### SCRIPT rfid_trigger_play.sh ($NOW) ##" >> $PATHDATA/../logs/debug.log; fi
# create the configuration file from sample - if it does not exist
if [ ! -f $PATHDATA/../settings/rfid_trigger_play.conf ]; then
cp $PATHDATA/../settings/rfid_trigger_play.conf.sample $PATHDATA/../settings/rfid_trigger_play.conf
# change the read/write so that later this might also be editable through the web app
sudo chown -R pi:www-data $PATHDATA/../settings/rfid_trigger_play.conf
sudo chmod -R 775 $PATHDATA/../settings/rfid_trigger_play.conf
fi
###########################################################
# Read global configuration file (and create is not exists)
# create the global configuration file from single files - if it does not exist
if [ ! -f $PATHDATA/../settings/global.conf ]; then
. inc.writeGlobalConfig.sh
fi
. $PATHDATA/../settings/global.conf
###########################################################
# Read configuration file
. $PATHDATA/../settings/rfid_trigger_play.conf
# Get args from command line (see Usage above)
# see following file for details:
. $PATHDATA/inc.readArgsFromCommandLine.sh
##################################################################
# Check if we got the card ID or the audio folder from the prompt.
# Sloppy error check, because we assume the best.
if [ "$CARDID" ]; then
# we got the card ID
# If you want to see the CARDID printed, uncomment the following line
# echo CARDID = $CARDID
# Add info into the log, making it easer to monitor cards
echo "Card ID '$CARDID' was used at '$NOW'." > $PATHDATA/../shared/latestID.txt
echo "$CARDID" > $PATHDATA/../settings/Latest_RFID
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "Card ID '$CARDID' was used" >> $PATHDATA/../logs/debug.log; fi
# If the input is of 'special' use, don't treat it like a trigger to play audio.
# Special uses are for example volume changes, skipping, muting sound.
case $CARDID in
$CMDSHUFFLE)
# toggles shuffle mode (random on/off)
$PATHDATA/playout_controls.sh -c=playershuffle
;;
$CMDMAXVOL30)
# limit volume to 30%
$PATHDATA/playout_controls.sh -c=setmaxvolume -v=30
;;
$CMDMAXVOL50)
# limit volume to 50%
$PATHDATA/playout_controls.sh -c=setmaxvolume -v=50
;;
$CMDMAXVOL75)
# limit volume to 75%
$PATHDATA/playout_controls.sh -c=setmaxvolume -v=75
;;
$CMDMAXVOL80)
# limit volume to 80%
$PATHDATA/playout_controls.sh -c=setmaxvolume -v=80
;;
$CMDMAXVOL85)
# limit volume to 85%
$PATHDATA/playout_controls.sh -c=setmaxvolume -v=85
;;
$CMDMAXVOL90)
# limit volume to 90%
$PATHDATA/playout_controls.sh -c=setmaxvolume -v=90
;;
$CMDMAXVOL95)
# limit volume to 95%
$PATHDATA/playout_controls.sh -c=setmaxvolume -v=95
;;
$CMDMAXVOL100)
# limit volume to 100%
$PATHDATA/playout_controls.sh -c=setmaxvolume -v=100
;;
$CMDMUTE)
# amixer sset 'PCM' 0%
$PATHDATA/playout_controls.sh -c=mute
;;
$CMDVOL30)
# amixer sset 'PCM' 30%
$PATHDATA/playout_controls.sh -c=setvolume -v=30
;;
$CMDVOL50)
# amixer sset 'PCM' 50%
$PATHDATA/playout_controls.sh -c=setvolume -v=50
;;
$CMDVOL75)
# amixer sset 'PCM' 75%
$PATHDATA/playout_controls.sh -c=setvolume -v=75
;;
$CMDVOL80)
# amixer sset 'PCM' 80%
$PATHDATA/playout_controls.sh -c=setvolume -v=80
;;
$CMDVOL85)
# amixer sset 'PCM' 85%
$PATHDATA/playout_controls.sh -c=setvolume -v=85
;;
$CMDVOL90)
# amixer sset 'PCM' 90%
$PATHDATA/playout_controls.sh -c=setvolume -v=90
;;
$CMDVOL95)
# amixer sset 'PCM' 95%
$PATHDATA/playout_controls.sh -c=setvolume -v=95
;;
$CMDVOL100)
# amixer sset 'PCM' 100%
$PATHDATA/playout_controls.sh -c=setvolume -v=100
;;
$CMDVOLUP)
# increase volume by x% set in Audio_Volume_Change_Step
$PATHDATA/playout_controls.sh -c=volumeup
;;
$CMDVOLDOWN)
# decrease volume by x% set in Audio_Volume_Change_Step
$PATHDATA/playout_controls.sh -c=volumedown
;;
$CMDSTOP)
# kill all running audio players
$PATHDATA/playout_controls.sh -c=playerstop
;;
$CMDSHUTDOWN)
# shutdown the RPi nicely
# sudo halt
$PATHDATA/playout_controls.sh -c=shutdown
;;
$CMDREBOOT)
# shutdown the RPi nicely
# sudo reboot
$PATHDATA/playout_controls.sh -c=reboot
;;
$CMDNEXT)
# play next track in playlist
$PATHDATA/playout_controls.sh -c=playernext
;;
$CMDPREV)
# play previous track in playlist
# echo "prev" | nc.openbsd -w 1 localhost 4212
sudo $PATHDATA/playout_controls.sh -c=playerprev
#/usr/bin/sudo /home/pi/RPi-Jukebox-RFID/scripts/playout_controls.sh -c=playerprev
;;
$CMDREWIND)
# play the first track in playlist
sudo $PATHDATA/playout_controls.sh -c=playerrewind
;;
$CMDSEEKFORW)
# jump 15 seconds ahead
$PATHDATA/playout_controls.sh -c=playerseek -v=+15
;;
$CMDSEEKBACK)
# jump 15 seconds back
$PATHDATA/playout_controls.sh -c=playerseek -v=-15
;;
$CMDPAUSE)
# pause current track
# echo "pause" | nc.openbsd -w 1 localhost 4212
$PATHDATA/playout_controls.sh -c=playerpause
;;
$CMDPLAY)
# play / resume current track
# echo "play" | nc.openbsd -w 1 localhost 4212
$PATHDATA/playout_controls.sh -c=playerplay
;;
$STOPAFTER5)
# stop player after -v minutes
$PATHDATA/playout_controls.sh -c=playerstopafter -v=5
;;
$STOPAFTER15)
# stop player after -v minutes
$PATHDATA/playout_controls.sh -c=playerstopafter -v=15
;;
$STOPAFTER30)
# stop player after -v minutes
$PATHDATA/playout_controls.sh -c=playerstopafter -v=30
;;
$STOPAFTER60)
# stop player after -v minutes
$PATHDATA/playout_controls.sh -c=playerstopafter -v=60
;;
$SHUTDOWNAFTER5)
# shutdown after -v minutes
$PATHDATA/playout_controls.sh -c=shutdownafter -v=5
;;
$SHUTDOWNAFTER15)
# shutdown after -v minutes
$PATHDATA/playout_controls.sh -c=shutdownafter -v=15
;;
$SHUTDOWNAFTER30)
# shutdown after -v minutes
$PATHDATA/playout_controls.sh -c=shutdownafter -v=30
;;
$SHUTDOWNAFTER60)
# shutdown after -v minutes
$PATHDATA/playout_controls.sh -c=shutdownafter -v=60
;;
$SHUTDOWNVOLUMEREDUCTION10)
# reduce volume until shutdown in -v minutes
$PATHDATA/playout_controls.sh -c=shutdownvolumereduction -v=10
;;
$SHUTDOWNVOLUMEREDUCTION15)
# reduce volume until shutdown in -v minutes
$PATHDATA/playout_controls.sh -c=shutdownvolumereduction -v=15
;;
$SHUTDOWNVOLUMEREDUCTION30)
# reduce volume until shutdown in -v minutes
$PATHDATA/playout_controls.sh -c=shutdownvolumereduction -v=30
;;
$SHUTDOWNVOLUMEREDUCTION60)
# reduce volume until shutdown in -v minutes
$PATHDATA/playout_controls.sh -c=shutdownvolumereduction -v=60
;;
$ENABLEWIFI)
$PATHDATA/playout_controls.sh -c=enablewifi
;;
$DISABLEWIFI)
$PATHDATA/playout_controls.sh -c=disablewifi
;;
$TOGGLEWIFI)
$PATHDATA/playout_controls.sh -c=togglewifi
;;
$CMDPLAYCUSTOMPLS)
$PATHDATA/playout_controls.sh -c=playlistaddplay -v="PhonieCustomPLS" -d="PhonieCustomPLS"
;;
$RECORDSTART600)
#start recorder for -v seconds
$PATHDATA/playout_controls.sh -c=recordstart -v=600
;;
$RECORDSTART60)
#start recorder for -v seconds
$PATHDATA/playout_controls.sh -c=recordstart -v=60
;;
$RECORDSTART10)
#start recorder for -v seconds
$PATHDATA/playout_controls.sh -c=recordstart -v=10
;;
$RECORDSTOP)
$PATHDATA/playout_controls.sh -c=recordstop
;;
$RECORDPLAYBACKLATEST)
$PATHDATA/playout_controls.sh -c=recordplaylatest
;;
$CMDREADWIFIIP)
$PATHDATA/playout_controls.sh -c=readwifiipoverspeaker
;;
$CMDBLUETOOTHTOGGLE)
$PATHDATA/playout_controls.sh -c=bluetoothtoggle -v=toggle
;;
*)
# We checked if the card was a special command, seems it wasn't.
# Now we expect it to be a trigger for one or more audio file(s).
# Let's look at the ID, write a bit of log information and then try to play audio.
# Look for human readable shortcut in folder 'shortcuts'
# check if CARDID has a text file by the same name - which would contain the human readable folder name
if [ -f $PATHDATA/../shared/shortcuts/$CARDID ]
then
# Read human readable shortcut from file
FOLDER=`cat $PATHDATA/../shared/shortcuts/$CARDID`
# Add info into the log, making it easer to monitor cards
echo "This ID has been used before." >> $PATHDATA/../shared/latestID.txt
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "This ID has been used before." >> $PATHDATA/../logs/debug.log; fi
else
# Human readable shortcut does not exists, so create one with the content $CARDID
# this file can later be edited manually over the samba network
echo "$CARDID" > $PATHDATA/../shared/shortcuts/$CARDID
FOLDER=$CARDID
# Add info into the log, making it easer to monitor cards
echo "This ID was used for the first time." >> $PATHDATA/../shared/latestID.txt
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "This ID was used for the first time." >> $PATHDATA/../logs/debug.log; fi
fi
# Add info into the log, making it easer to monitor cards
echo "The shortcut points to audiofolder '$FOLDER'." >> $PATHDATA/../shared/latestID.txt
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "The shortcut points to audiofolder '$FOLDER'." >> $PATHDATA/../logs/debug.log; fi
;;
esac
fi
##############################################################
# We should now have a folder name with the audio files.
# Either from prompt of from the card ID processing above
# Sloppy error check, because we assume the best.
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "# Attempting to play: $AUDIOFOLDERSPATH/$FOLDER" >> $PATHDATA/../logs/debug.log; fi
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "# Type of play \$VALUE: $VALUE" >> $PATHDATA/../logs/debug.log; fi
# check if
# - $FOLDER is not empty (! -z "$FOLDER")
# - AND (-a)
# - $FOLDER is set (! -z ${FOLDER+x})
# - AND (-a)
# - and points to existing directory (-d "${AUDIOFOLDERSPATH}/${FOLDER}")
if [ ! -z "$FOLDER" -a ! -z ${FOLDER+x} -a -d "${AUDIOFOLDERSPATH}/${FOLDER}" ]; then
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "\$FOLDER set, not empty and dir exists: ${AUDIOFOLDERSPATH}/${FOLDER}" >> $PATHDATA/../logs/debug.log; fi
# if we play a folder the first time, add some sensible information to the folder.conf
if [ ! -f "${AUDIOFOLDERSPATH}/${FOLDER}/folder.conf" ]; then
# now we create a default folder.conf file by calling this script
# with the command param createDefaultFolderConf
# (see script for details)
# the $FOLDER would not need to be passed on, because it is already set in this script
# see inc.writeFolderConfig.sh for details
. $PATHDATA/inc.writeFolderConfig.sh -c=createDefaultFolderConf -d="${FOLDER}"
fi
# get the name of the last folder played. As mpd doesn't store the name of the last
# playlist, we have to keep track of it via the Latest_Folder_Played file
LASTFOLDER=$(cat $PATHDATA/../settings/Latest_Folder_Played)
LASTPLAYLIST=$(cat $PATHDATA/../settings/Latest_Playlist_Played)
# this might need to go? resume not working... echo ${FOLDER} > $PATHDATA/../settings/Latest_Folder_Played
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Var \$LASTFOLDER: $LASTFOLDER" >> $PATHDATA/../logs/debug.log; fi
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Var \$LASTPLAYLIST: $LASTPLAYLIST" >> $PATHDATA/../logs/debug.log; fi
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "Checking 'recursive' list? VAR \$VALUE: $VALUE" >> $PATHDATA/../logs/debug.log; fi
if [ "$VALUE" == "recursive" ]; then
# set path to playlist
# replace subfolder slashes with " % "
PLAYLISTPATH="${PLAYLISTSFOLDERPATH}/${FOLDER//\//\ %\ }-%RCRSV%.m3u"
PLAYLISTNAME="${FOLDER//\//\ %\ }-%RCRSV%"
$PATHDATA/playlist_recursive_by_folder.php --folder "${FOLDER}" --list 'recursive' > "${PLAYLISTPATH}"
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "recursive? YES" >> $PATHDATA/../logs/debug.log; fi
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "$PATHDATA/playlist_recursive_by_folder.php --folder \"${FOLDER}\" --list 'recursive' > \"${PLAYLISTPATH}\"" >> $PATHDATA/../logs/debug.log; fi
else
# set path to playlist
# replace subfolder slashes with " % "
PLAYLISTPATH="${PLAYLISTSFOLDERPATH}/${FOLDER//\//\ %\ }.m3u"
PLAYLISTNAME="${FOLDER//\//\ %\ }"
$PATHDATA/playlist_recursive_by_folder.php --folder "${FOLDER}" > "${PLAYLISTPATH}"
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "recursive? NO" >> $PATHDATA/../logs/debug.log; fi
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "$PATHDATA/playlist_recursive_by_folder.php --folder \"${FOLDER}\" > \"${PLAYLISTPATH}\"" >> $PATHDATA/../logs/debug.log; fi
fi
# Second Swipe value
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Var \$SECONDSWIPE: ${SECONDSWIPE}" >> $PATHDATA/../logs/debug.log; fi
# Playlist name
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Var \$PLAYLISTNAME: ${PLAYLISTNAME}" >> $PATHDATA/../logs/debug.log; fi
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Var \$LASTPLAYLIST: ${LASTPLAYLIST}" >> $PATHDATA/../logs/debug.log; fi
# Setting a VAR to start "play playlist from start"
# This will be changed in the following checks "if this is the second swipe"
PLAYPLAYLIST=yes
# Check if the second swipe happened
# - The same playlist is cued up ("$LASTPLAYLIST" == "$PLAYLISTNAME")
if [ "$LASTPLAYLIST" == "$PLAYLISTNAME" ]
then
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Second Swipe DID happen: \$LASTPLAYLIST == \$PLAYLISTNAME" >> $PATHDATA/../logs/debug.log; fi
# check if
# - $SECONDSWIPE is set to toggle pause/play ("$SECONDSWIPE" == "PAUSE")
# - AND (-a)
# - check the length of the playlist, if =0 then it was cleared before, a state, which should only
# be possible after a reboot ($PLLENGTH -gt 0)
PLLENGTH=$(echo -e "status\nclose" | nc -w 1 localhost 6600 | grep -o -P '(?<=playlistlength: ).*')
if [ $PLLENGTH -eq 0 ]
then
# after a reboot we want to play the playlist once no matter what the setting is
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Take second wipe as first after fresh boot" >> $PATHDATA/../logs/debug.log; fi
elif [ "$SECONDSWIPE" == "PAUSE" -a $PLLENGTH -gt 0 ]
then
# The following involves NOT playing the playlist, so we set:
PLAYPLAYLIST=no
STATE=$(echo -e "status\nclose" | nc -w 1 localhost 6600 | grep -o -P '(?<=state: ).*')
if [ $STATE == "play" ]
then
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " MPD playing, pausing the player" >> $PATHDATA/../logs/debug.log; fi
sudo $PATHDATA/playout_controls.sh -c=playerpause &>/dev/null
else
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "MPD not playing, start playing" >> $PATHDATA/../logs/debug.log; fi
sudo $PATHDATA/playout_controls.sh -c=playerplay &>/dev/null
fi
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Completed: toggle pause/play" >> $PATHDATA/../logs/debug.log; fi
elif [ "$SECONDSWIPE" == "PLAY" -a $PLLENGTH -gt 0 ]
then
# The following involves NOT playing the playlist, so we set:
PLAYPLAYLIST=no
sudo $PATHDATA/playout_controls.sh -c=playerplay &>/dev/null
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Completed: Resume playback" >> $PATHDATA/../logs/debug.log; fi
elif [ "$SECONDSWIPE" == "NOAUDIOPLAY" ]
then
# The following involves NOT playing the playlist, so we set:
PLAYPLAYLIST=no
# following needs testing (see https://github.com/MiczFlor/RPi-Jukebox-RFID/issues/914)
# Special case for NOAUDIOPLAY because once the playlist has finished,
# it needs to be noted by the system that the second swipe is like a *first* swipe.
currentSong=`mpc current`
if [[ -z "$currentSong" ]]; then
#end of playlist (EOPL) reached. Ignore last played playlist
PLAYPLAYLIST=yes
fi
# "$SECONDSWIPE" == "NOAUDIOPLAY"
# "$LASTPLAYLIST" == "$PLAYLISTNAME" => same playlist triggered again
# => do nothing
# echo "do nothing" > /dev/null 2>&1
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Completed: do nothing" >> $PATHDATA/../logs/debug.log; fi
elif [ "$SECONDSWIPE" == "SKIPNEXT" ]
then
# We will not play the playlist but skip to the next track:
PLAYPLAYLIST=skipnext
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Completed: skip next track" >> $PATHDATA/../logs/debug.log; fi
fi
fi
# now we check if we are still on for playing what we got passed on:
if [ "$PLAYPLAYLIST" == "yes" ]
then
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "We must play the playlist no matter what: \$PLAYPLAYLIST == yes" >> $PATHDATA/../logs/debug.log; fi
# Above we already checked if the folder exists -d "$AUDIOFOLDERSPATH/$FOLDER"
#
# the process is as such - because of the recursive play option:
# - each folder can be played.
# - a single folder will create a playlist with the same name as the folder
# - because folders can live inside other folders, the relative path might contain
# slashes (e.g. audiobooks/Moby Dick/)
# - because slashes can not be in the playlist name, slashes are replaced with " % "
# - the "recursive" option means that the content of the folder AND all subfolders
# is being played
# - in this case, the playlist is related to the same folder name, which means we need
# to make a different name for "recursive" playout
# - a recursive playlist has the suffix " %RCRSV%" - keeping it cryptic to avoid clashes
# with a possible "real" name for a folder
# - with this new logic, there are no more SPECIALFORMAT playlists. Live streams and podcasts
# are now all unfolded into the playlist
# - creating the playlist is now done in the php script with parameters:
# $PATHDATA/playlist_recursive_by_folder.php --folder "${FOLDER}" --list 'recursive'
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " VAR FOLDER: $FOLDER" >> $PATHDATA/../logs/debug.log; fi
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " VAR PLAYLISTPATH: $PLAYLISTPATH" >> $PATHDATA/../logs/debug.log; fi
# save position of current playing list "stop"
$PATHDATA/playout_controls.sh -c=playerstop
# play playlist
# the variable passed on to play is the playlist name -v (NOT the folder name)
# because (see above) a folder can be played recursively (including subfolders) or flat (only containing files)
# load new playlist and play
$PATHDATA/playout_controls.sh -c=playlistaddplay -v="${PLAYLISTNAME}" -d="${FOLDER}"
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Command: $PATHDATA/playout_controls.sh -c=playlistaddplay -v=\"${PLAYLISTNAME}\" -d=\"${FOLDER}\"" >> $PATHDATA/../logs/debug.log; fi
# save latest playlist not to file
sudo echo ${PLAYLISTNAME} > $PATHDATA/../settings/Latest_Playlist_Played
sudo chown pi:www-data $PATHDATA/../settings/Latest_Playlist_Played
sudo chmod 777 $PATHDATA/../settings/Latest_Playlist_Played
fi
if [ "$PLAYPLAYLIST" == "skipnext" ]
then
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "Skip to the next track in the playlist: \$PLAYPLAYLIST == skipnext" >> $PATHDATA/../logs/debug.log; fi
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " VAR FOLDER: $FOLDER" >> $PATHDATA/../logs/debug.log; fi
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " VAR PLAYLISTPATH: $PLAYLISTPATH" >> $PATHDATA/../logs/debug.log; fi
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo " Command: $PATHDATA/playout_controls.sh -c=playernext" >> $PATHDATA/../logs/debug.log; fi
$PATHDATA/playout_controls.sh -c=playernext
fi
else
if [ "${DEBUG_rfid_trigger_play_sh}" == "TRUE" ]; then echo "Path not found $AUDIOFOLDERSPATH/$FOLDER" >> $PATHDATA/../logs/debug.log; fi
fi
|
#!/bin/sh
set -e
# Replace {DOMAIN} with DOMAIN
sed "s/{DOMAIN}/$DOMAIN/g" caddy-template.json > caddy.json
echo "Linking \"/data/caddy/certificates/acme-v02.api.letsencrypt.org-directory/$DOMAIN\" to /srv/app/certs" >> /var/log/certainly_certed
ln -s "/data/caddy/certificates/acme-v02.api.letsencrypt.org-directory/$DOMAIN" /srv/app/certs
if [ -f /run/secrets/digitalocean_token ]
then
export DIGITALOCEAN_TOKEN=$(cat /run/secrets/digitalocean_token)
echo "Loaded digitalocean_token from secret" >> /var/log/certainly_certed
fi
echo "Starting caddy" >> /var/log/certainly_certed
caddy run --config /srv/app/caddy.json
|
// Implementation of the SharpWavefolder class
class SharpWavefolder {
public:
// Process audio signal by folding the waveform
float process(float input, float threshold) {
if (input > threshold) {
return 2 * threshold - input;
} else if (input < -threshold) {
return 2 * (-threshold) - input;
} else {
return input;
}
}
};
// Implementation of the MetallicNoiseGenerator class
class MetallicNoiseGenerator {
public:
// Generate metallic-sounding noise
float generateNoise() {
// Implement the generation algorithm for metallic noise
// Example: using a combination of band-limited noise and filtering to achieve metallic sound
// Return the generated noise signal
}
};
// Example usage of the wavefolder and metallic noise generator
int main() {
SharpWavefolder wavefolder;
float inputSignal = 0.5; // Example input signal
float threshold = 0.3; // Example threshold for wavefolding
float processedSignal = wavefolder.process(inputSignal, threshold);
MetallicNoiseGenerator noiseGenerator;
float metallicNoise = noiseGenerator.generateNoise();
// Use the processed signal and metallic noise in the audio synthesis pipeline
// ...
return 0;
} |
import renderMarkdown from './markdown';
import { RendererArgs } from '@/typings/components/Table';
// one day make this more powerful and create real html from a template maybe
const renderHtml = (args: RendererArgs): Promise<string> => renderMarkdown(args);
export default renderHtml;
|
#!/bin/bash
set -uex
source vars.sh
echo "--------------------Installing Kubernetes binaries--------------------"
curl -L --remote-name-all "https://storage.googleapis.com/kubernetes-release/release/${KUBERNETES_VERSION}/bin/linux/amd64/{kubeadm,kubelet,kubectl}"
sudo chmod a+x kubeadm kubelet kubectl
sudo mv kubeadm kubelet kubectl /usr/local/bin/
sudo mkdir -p /etc/systemd/system/kubelet.service.d
sudo ./retrieve.configuration.files.sh https://raw.githubusercontent.com/kubernetes/release/v0.2.7/cmd/kubepkg/templates/latest/deb/kubelet/lib/systemd/system/kubelet.service /etc/systemd/system/kubelet.service
sudo ./retrieve.configuration.files.sh https://raw.githubusercontent.com/kubernetes/release/v0.2.7/cmd/kubepkg/templates/latest/deb/kubeadm/10-kubeadm.conf /etc/systemd/system/kubelet.service.d/10-kubeadm.conf
sudo apt-get update
sudo apt install -y conntrack socat haproxy keepalived
sudo apt install python3-pip
sudo pip3 install yq
echo "--------------------Installing CRIO--------------------"
sudo ./install_crio.sh |
<reponame>wongoo/alipay-sdk-java-all<gh_stars>0
package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.user.point.authbase.send response.
*
* @author <NAME>
* @since 1.0, 2021-07-14 10:10:09
*/
public class AlipayUserPointAuthbaseSendResponse extends AlipayResponse {
private static final long serialVersionUID = 6345392114697123236L;
/**
* 实际给用户发放的积分数,由于单个用户有日限额,所以实际发放的积分数可能小于请求发放的积分数
*/
@ApiField("send_point")
private Long sendPoint;
public void setSendPoint(Long sendPoint) {
this.sendPoint = sendPoint;
}
public Long getSendPoint( ) {
return this.sendPoint;
}
}
|
<filename>src/api/v2/apiListDetail.js
import axios from 'axios';
export const getApiList = (classificationId) => {
return axios.get(`/api/v2/client/permission/${classificationId}/list`);
};
export const getApiDoc = (docName) => {
return axios.get(`/api/v2/client/open/${docName}`);
};
export const getErrorCode = () => {
return axios.get('/api/v2/client/error/doc');
};
|
/*
* Copyright 2013 Stanford University.
* 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 holders 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.
*/
/***********************************************************************
* AUTHOR: <NAME> <pal>
* FILE: .//ldo_index.cc
* DATE: Fri Oct 25 10:20:13 2013
* DESCR:
***********************************************************************/
#include "src/shared/ldo_index.h"
#include "src/shared/dbg.h"
namespace nimbus {
/**
* \fn nimbus::LdoIndex::LdoIndex()
* \brief Brief description.
* \return
*/
LdoIndex::LdoIndex() {}
/**
* \fn LdoIndex::~LdoIndex()
* \brief Brief description.
* \return
*/
LdoIndex::~LdoIndex() {
LdoVariableIndex::iterator it = index_.begin();
for (; it != index_.end(); ++it) {
LdoList* list = (*it).second;
dbg(DBG_MEMORY, "Deleting LdoList 0x%x\n", list);
delete list;
}
exists_.clear();
index_.clear();
}
/**
* \fn void LdoIndex::addObject(LogicalDataObject *object)
* \brief Brief description.
* \param object
* \return
*/
bool LdoIndex::AddObject(LogicalDataObject *object) {
// If the object already exists, reject it. Otherwise, insert
// it into a list, creating a list if needed.
dbg(DBG_DATA_OBJECTS, "LdoIndex: adding %llu as %s.\n", object->id(), object->variable().c_str()); // NOLINT
if (exists_.find(object->id()) != exists_.end()) {
dbg(DBG_DATA_OBJECTS|DBG_ERROR, " - FAIL LdoIndex: object %llu already in index.\n", object->id()); // NOLINT
return false;
} else {
std::string var = object->variable();
LdoList* list;
if (index_.find(var) == index_.end()) {
list = new LdoList();
dbg(DBG_MEMORY, "Allocating LdoList 0x%x\n", list);
index_[var] = list;
} else {
list = index_[var];
}
list->push_back(object);
exists_[object->id()] = object;
return true;
}
}
bool LdoIndex::HasObject(logical_data_id_t id) {
return (exists_.find(id) != exists_.end());
}
bool LdoIndex::RemoveObject(logical_data_id_t id) {
dbg(DBG_TEMP, "Trying to remove object %llu.\n", id);
if (HasObject(id)) {
LogicalDataObject* obj = exists_[id];
std::string variable = obj->variable();
LdoList* list = index_[variable];
LdoList::iterator it = list->begin();
for (; it != list->end(); ++it) {
LogicalDataObject* ldo = *it;
if (ldo->id() == id) {
list->erase(it);
int cnt = exists_.erase(id);
dbg(DBG_TEMP, "Removing object %llu, removed %i elements from exists_.\n", id, cnt);
return true;
}
}
}
return false;
}
bool LdoIndex::RemoveObject(LogicalDataObject* object) {
return RemoveObject(object->id());
}
/**
* \fn LdoList * LdoIndex::intersectingObjects(std::string variable,
GeometricRegion *region)
* \brief Brief description.
* \param region
* \return
*/
LogicalDataObject* LdoIndex::SpecificObject(logical_data_id_t id) {
if (!HasObject(id)) {
return NULL;
} else {
return exists_[id];
}
}
int LdoIndex::AllObjects(CLdoVector* dest) {
dest->clear();
int count = 0;
LdoIdIndex::iterator it = exists_.begin();
for (; it != exists_.end(); ++it) {
LogicalDataObject* obj = (*it).second;
dest->push_back(obj);
count++;
}
return count;
}
int LdoIndex::AllObjects(const std::string& variable,
CLdoVector* dest) {
dest->clear();
if (index_.find(variable) == index_.end()) { // No such variable
return 0;
}
LdoList* list = index_[variable];
LdoList::iterator iter = list->begin();
int count = 0;
for (; iter != list->end(); ++iter) {
LogicalDataObject* object = *iter;
dest->push_back(object);
count++;
}
return count;
}
int LdoIndex::IntersectingObjects(const std::string& variable,
const GeometricRegion* region,
CLdoVector* dest) {
dest->clear();
if (index_.find(variable) == index_.end()) { // No such variable
return 0;
}
LdoList* list = index_[variable];
LdoList::iterator iter = list->begin();
int count = 0;
for (; iter != list->end(); ++iter) {
LogicalDataObject* object = *iter;
if (region->Intersects(object->region())) {
dest->push_back(object);
count++;
}
}
return count;
}
/**
* \fn LdoList * LdoIndex::coveredObjects(std::string variable,
GeometricRegion *region)
* \brief Brief description.
* \param region
* \return
*/
int LdoIndex::CoveredObjects(const std::string& variable,
const GeometricRegion* region,
CLdoVector* dest) {
dest->clear();
if (index_.find(variable) == index_.end()) { // No such variable
return 0;
}
LdoList* list = index_[variable];
LdoList::iterator iter = list->begin();
int count = 0;
for (; iter != list->end(); ++iter) {
LogicalDataObject* object = *iter;
if (region->Covers(object->region())) {
dest->push_back(object);
count++;
}
}
return count;
}
/**
* \fn LdoList * LdoIndex::adjacentObjects(std::string variable,
GeometricRegion *region)
* \brief Brief description.
* \param region
* \return
*/
int LdoIndex::AdjacentObjects(const std::string& variable,
const GeometricRegion* region,
CLdoVector* dest) {
dest->clear();
if (index_.find(variable) == index_.end()) { // No such variable
return 0;
}
LdoList* list = index_[variable];
LdoList::iterator iter = list->begin();
int count = 0;
for (; iter != list->end(); ++iter) {
LogicalDataObject* object = *iter;
if (region->Adjacent(object->region())) {
dest->push_back(object);
count++;
}
}
return count;
}
} // namespace nimbus
|
bashmenot_internal_get_timestamp () {
if (( ${BASHMENOT_LOG_TIMESTAMP:-0} )); then
if [[ -z "${BASHMENOT_TIMESTAMP_EPOCH:-}" ]]; then
local now
now=$( get_date '+%H:%M:%S' )
echo -e "\033[2m${now}\033[0m "
else
local now diff pad
now=$( get_current_time )
diff=$(( now - BASHMENOT_TIMESTAMP_EPOCH ))
pad=' '
echo -e "\033[2m${pad:0:$(( 10 - ${#diff} ))}${diff}\033[0m "
fi
fi
}
bashmenot_internal_get_empty_timestamp () {
if (( ${BASHMENOT_LOG_TIMESTAMP:-0} )); then
if [[ -z "${BASHMENOT_TIMESTAMP_EPOCH:-}" ]]; then
echo ' '
else
echo ' '
fi
fi
}
prefix_log () {
local now prefix
now=$( bashmenot_internal_get_timestamp )
prefix="$1"
shift
echo "${now}${*:+${prefix}$*}" >&2
}
prefix_log_begin () {
local now prefix
now=$( bashmenot_internal_get_timestamp )
prefix="$1"
shift
printf -- "${now}${*:+${prefix}$* }" >&2
}
log () {
prefix_log '-----> ' "$@"
}
log_begin () {
prefix_log_begin '-----> ' "$@"
}
log_end () {
echo "$@" >&2
}
log_indent () {
prefix_log ' ' "$@"
}
log_indent_begin () {
prefix_log_begin ' ' "$@"
}
log_indent_end () {
echo "$@" >&2
}
log_label () {
local label
label="$1$( printf ' %.0s' {0..41} )"
shift
log "${label:0:41}" "$( echo -en '\033[1m' )$*$( echo -en '\033[0m' )"
}
log_indent_label () {
local label
label="$1$( printf ' %.0s' {0..41} )"
shift
log_indent "${label:0:41}" "$( echo -en '\033[1m' )$*$( echo -en '\033[0m' )"
}
log_debug () {
prefix_log "$( echo -en '\033[1m' ) *** DEBUG: " "$*$( echo -en '\033[0m' )"
}
log_warning () {
prefix_log "$( echo -en '\033[1m' ) *** WARNING: " "$*$( echo -en '\033[0m' )"
}
log_error () {
prefix_log "$( echo -en '\033[1m' ) *** ERROR: " "$*$( echo -en '\033[0m' )"
}
case $( uname -s ) in
'Linux')
quote () {
local prefix
prefix="$( bashmenot_internal_get_empty_timestamp ) "
sed -u "s/^/${prefix}/" >&2 || return 0
}
;;
'Darwin')
quote () {
local prefix
prefix="$( bashmenot_internal_get_empty_timestamp ) "
sed -l "s/^/${prefix}/" >&2 || return 0
}
;;
*)
quote () {
local prefix
prefix="$( bashmenot_internal_get_empty_timestamp ) "
sed "s/^/${prefix}/" >&2 || return 0
}
esac
die () {
if [[ -n "${*:+_}" ]]; then
log_error "$@"
fi
exit 1
}
|
export const WEATHER_RESPONSE = 'WEATHER_RESPONSE';
export const WEATHER_RESPONSE_FAIL = 'WEATHER_RESPONSE_FAIL';
export const SET_CITY = 'SET_CITY';
export const GEOLOCATION_RESPONSE_FAIL = 'GEOLOCATION_RESPONSE_FAIL';
export const GEOLOCATION_RESPONSE = 'GEOLOCATION_RESPONSE';
export const GEOLOCATION_CURRENT = 'GEOLOCATION_CURRENT'; |
<filename>src/main/java/coins/CoinWallet.java<gh_stars>0
/*
* Description: Describes the wallet for an end-user to a given coin
* License: Apache-2.0
* Copyright: x-file.xyz
*/
package coins;
import java.util.ArrayList;
/**
* Date: 2021-06-14
* Place: Zwingenberg, Germany
* @author brito
*/
public class CoinWallet {
// coins available (not locked)
private long valueSpot;
// transactions such as buy/sell/transfer
private ArrayList<CoinTransaction> transactions = new ArrayList();
}
|
const filterByGenre = (books, genre) => {
return books.filter( book => book.genre === genre ).map( book => book.title);
};
let fantasyBooks = filterByGenre(books, 'Fantasy');
//['Harry Potter and the Philosopher's Stone', 'Twilight'] |
<gh_stars>1-10
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.arslorem.hamzah.ejbs;
import com.arslorem.hamzah.entities.SecurityUser;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
/**
*
* @author user
*/
@Stateless
public class SecurityUserBean {
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
@Inject
private DataAccessObject dao;
public void create(SecurityUser obj) {
dao.create(obj);
}
public List<SecurityUser> findAll() {
return dao.findAll("SecurityUser.findAll", SecurityUser.class);
}
public SecurityUser findByUserNamePassword(String userName, String password) {
return dao.findOne("SecurityUser.findByUserNamePassword", SecurityUser.class, "userName", userName, "password", password);
}
public List<SecurityUser> findByUserName(String userName) {
return dao.find("SecurityUser.findByUserName", SecurityUser.class, "userName", userName);
}
public List<SecurityUser> findByOfficialEmail(String officialEmail) {
return dao.find("SecurityUser.findByOfficialEmail", SecurityUser.class, "officialEmail", officialEmail);
}
public List<SecurityUser> findByOfficialPhone(String officialPhone) {
return dao.find("SecurityUser.findByOfficialPhone", SecurityUser.class, "officialPhone", officialPhone);
}
public SecurityUser find(Long id) {
return dao.find(id, SecurityUser.class);
}
public void update(SecurityUser obj) {
dao.update(obj);
}
public void delete(SecurityUser obj) {
dao.delete(obj);
}
}
|
//
// Copyright 2020 <NAME>
//
// 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 AGE_GB_SERIAL_HPP
#define AGE_GB_SERIAL_HPP
//!
//! \file
//!
#include <age_types.hpp>
#include "common/age_gb_clock.hpp"
#include "common/age_gb_device.hpp"
#include "common/age_gb_events.hpp"
#include "common/age_gb_interrupts.hpp"
namespace age
{
enum class gb_sio_state
{
no_transfer,
transfer_external_clock,
transfer_internal_clock
};
class gb_serial
{
AGE_DISABLE_COPY(gb_serial);
AGE_DISABLE_MOVE(gb_serial);
public:
gb_serial(const gb_device& device,
const gb_clock& clock,
gb_interrupt_trigger& interrupts,
gb_events& events);
~gb_serial() = default;
uint8_t read_sb();
[[nodiscard]] uint8_t read_sc() const;
void write_sb(uint8_t value);
void write_sc(uint8_t value);
void update_state();
void after_div_reset();
void set_back_clock(int clock_cycle_offset);
private:
// logging code is header-only to allow for compile time optimization
[[nodiscard]] gb_log_message_stream log() const
{
return m_clock.log(gb_log_category::lc_serial);
}
void start_transfer(uint8_t value_sc);
void stop_transfer(gb_sio_state new_state);
const gb_device& m_device;
const gb_clock& m_clock;
gb_interrupt_trigger& m_interrupts;
gb_events& m_events;
gb_sio_state m_sio_state = gb_sio_state::no_transfer;
int m_sio_clk_started = gb_no_clock_cycle;
int m_sio_clock_shift = 0;
uint8_t m_sio_initial_sb = 0;
uint8_t m_sb = 0;
uint8_t m_sc = 0;
};
} // namespace age
#endif // AGE_GB_SERIAL_HPP
|
require 'spec_helper'
describe LineUp do
let(:application) { :otherApp }
let(:job) { :SendEmail }
let(:args) { [123, some: :thing] }
let(:redis) { $raw_redis }
let(:logger) { double(:logger) }
let(:lineup_job) { LineUp::Job.new job, *args }
let(:lineup) { LineUp }
describe '.push' do
it 'returns true if successful' do
expect(lineup.push(application, job, *args)).to eq(true)
end
it 'registers the queue' do
lineup.push application, job, *args
queues = expect(redis.smembers('other_app:resque:queues')).to eq(%w{ send_email })
end
it 'enqueues the job' do
lineup.push application, job, *args
jobs = redis.lrange('other_app:resque:queue:send_email', 0, -1)
expect(jobs.size).to eq(1)
expect(MultiJson.load(jobs.first)).to eq({ 'class' => 'SendEmail', 'args' => [123, 'some' => 'thing'] })
end
context 'with a Logger' do
before do
lineup.config.logger = logger
end
it 'logs the enqueueing and returns true' do
expect(logger).to receive(:debug) do |string|
expect(string).to include('LINEUP ENQUEUED')
expect(string).to include('line_up_spec.rb')
expect(string).to include(':otherApp')
expect(string).to include(':SendEmail')
expect(string).to include('[123, {:some=>:thing}]')
end
expect(lineup.push(application, job, *args)).to eq(true)
end
end
context 'when the key for the Queue Set is occupied by the wrong data format' do
before do
redis.set 'other_app:resque:queues', :anything_but_a_list
end
it 'catches the error and returns false' do
expect(Trouble).to receive(:notify) do |exception, metadata|
expect(exception).to be_instance_of(Redis::CommandError)
expect(metadata[:code]).to eq(:enqueue_failed)
expect(metadata[:application]).to eq(':otherApp')
expect(metadata[:job]).to eq(':SendEmail')
expect(metadata[:args]).to eq('[123, {:some=>:thing}]')
expect(metadata[:caller]).to include('line_up_spec.rb')
end
expect(lineup.push(application, job, *args)).to eq(false)
end
end
context 'when the key for the List Job Queue is occupied by the wrong data format' do
before do
redis.set 'other_app:resque:queue:send_email', :anything_but_a_list
end
it 'catches the error and returns false' do
expect(Trouble).to receive(:notify) do |exception, metadata|
expect(exception).to be_instance_of Redis::CommandError
expect(metadata[:code]).to eq(:enqueue_failed)
expect(metadata[:application]).to eq(':otherApp')
expect(metadata[:job]).to eq(':SendEmail')
expect(metadata[:args]).to eq('[123, {:some=>:thing}]')
expect(metadata[:caller]).to include('line_up_spec.rb')
end
expect(lineup.push(application, job, *args)).to eq(false)
end
end
end
describe ".queue_length" do
it "returns the length of the given queue in the given application" do
lineup.push(application, job, 1)
lineup.push(application, job, 2)
expect(lineup.queue_length(application, job)).to eq(2)
end
context 'when the key for the List Job Queue is occupied by the wrong data format' do
before do
redis.set 'other_app:resque:queue:send_email', :anything_but_a_list
end
it 'logs the error' do
expect(Trouble).to receive(:notify) do |exception, metadata|
expect(exception).to be_instance_of Redis::CommandError
expect(metadata[:code]).to eq(:getting_queue_length_failed)
expect(metadata[:application]).to eq(':otherApp')
expect(metadata[:job]).to eq(':SendEmail')
expect(metadata[:caller]).to include('line_up_spec.rb')
end
lineup.queue_length(application, job)
end
it "returns false" do
expect(lineup.queue_length(application, job)).to eq(false)
end
end
end
describe ".ensure" do
it "pushes the job if the queue is empty" do
expect(lineup).to receive(:push).with(application, job, *args)
lineup.ensure application, job, *args
end
it "does not push the job if the queue already has a job with the same name" do
lineup.push application, job, *args
expect(lineup).not_to receive(:push)
lineup.ensure application, job, *args
end
end
describe ".push_throttled" do
it "pushes same consecutive job just once" do
expect(lineup).to receive(:push).once
lineup.push_throttled application, job, *args
lineup.push_throttled application, job, *args
end
it "pushes again when previous identical job has expired" do
expect(lineup).to receive(:push).twice
lineup.push_throttled application, job, *args
redis.del "other_app:resque:throttled:#{lineup_job.checksum}"
lineup.push_throttled application, job, *args
end
it "stores throttle with configured ttl" do
lineup.push_throttled application, job, *args
ttl = redis.ttl "other_app:resque:throttled:#{lineup_job.checksum}"
expect(ttl).to eq(lineup.config.recency_ttl)
end
end
end
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: <NAME>
In this PYTHON file I show the MCMC analysis to evaluate the likelihood of the parameters in question for
the tilted Einstein-de Sitter model (t-EdS)
"""
import multiprocessing as mproc
from multiprocessing import Pool
import numpy as np
from numpy import *
from scipy.integrate import quad
from math import sqrt
import matplotlib.pyplot as plt
from scipy import interpolate, linalg, optimize
from scipy.sparse.linalg import inv
from numpy.linalg import multi_dot
from astropy.constants import c
import emcee
from chainconsumer import ChainConsumer
from matplotlib import rcParams as rcp
rcp['figure.figsize'] = [9, 6]
rcp['figure.dpi'] = 80
rcp['xtick.labelsize'] = 15
rcp['ytick.labelsize'] = 15
rcp['axes.formatter.useoffset'] = False
rcp['axes.linewidth'] = 1.5
rcp['axes.axisbelow'] = False
rcp['xtick.major.size'] = 8
rcp['xtick.minor.size'] = 4
rcp['xtick.labelsize'] = 15
rcp['legend.fontsize'] = 15
rcp['xtick.direction'] = 'in'
rcp['ytick.major.width'] = 2
rcp['ytick.minor.width'] = 2
rcp['font.size'] = 20
### some constants ###
c_km = (c.to('km/s').value)
H0 = 70.
####################################
# #
# import the Pantheon SNIa data #
# #
####################################
# import redshifts (cosmological + heliocentric), apparent magnitudes, error of app.magnitudes, systematic errors
# Get the data from the github repository Pantheon of Dan Scolnic #
# https://github.com/dscolnic/Pantheon/blob/master/lcparam_full_long_zhel.txt #
data = np.loadtxt('/home/kerky/anaconda3/SN1A DATA/PANTHEON_DATA/Scolnic_data_updated.txt', usecols=[1,2,4,5])
### list with all the systematics as found in the PANTHEON catalog ###
# get the full systematics from the same repository #
#https://github.com/dscolnic/Pantheon/blob/master/sys_full_long.txt #
sys = np.genfromtxt('/home/kerky/anaconda3/SN1A DATA/PANTHEON_DATA/systematics.txt', skip_header=1)
### The list sn_names contains all the supernovae names in the PANTHEON catalog ###
sn_names = np.genfromtxt('/home/kerky/anaconda3/SN1A DATA/PANTHEON_DATA/Scolnic_data_updated.txt', usecols=[0],dtype='str')
z_cmb= np.array(data[:,0]) ## CMB redshift
z_hel = np.array(data[:,1]) ## heliocentric redshift
mb = np.array(data[:,2]) ## apparent magnitude
dmb = np.array(data[:,3]) ## error on mb
sqdmb = np.square(dmb) ## array with the square of the mb errors
### Construction of the full systematic covariance matrix ###
st = np.array(sys) ## put the systematics in an array
cov = np.reshape(st, (1048, 1048)) ## build the covariance matrix
er_stat = np.zeros((1048, 1048), float)
er_stat[np.diag_indices_from(er_stat)] = sqdmb
er_total = er_stat + cov
diag = np.array([np.diagonal(er_total)])
size = len(z_cmb)
print(size)
C_covn = np.linalg.inv([er_total]).reshape(1048, 1048)### the covariance matrix
### construct a q parameterization with respect to the Einstein de Sitter comoving distance ###
def dc_eds(z): ### comoving distance in EdS Universe
return 2*(1-((1+z)**(-1/2)))
### q parameterization wrt the EdS comoving distance ###
def q_eds(z,a,b):
return 0.5 *(1 -(1/(((np.power(dc_eds(z), 3))*b)+a)))
### Hubble parameter in EdS ###
def H_eds(z,a, b):
f = lambda x: (1+q_eds(x, a, b))/(1+x)
integ = quad(f, 0.0, z, epsabs=np.inf)[0]
ex = np.exp(integ)
return ex*(H0)
### luminosity distance in EdS ###
def dl_eds(z,a,b):
f = lambda y: (1/(H_eds(y,a, b)))
inte = np.real(quad(f, 0.,z, epsabs=np.inf)[0])
return inte*c_km*(1+z)
### Hubble-free luminosity distance in EdS ###
def Dl_eds(z,a, b):
return (H0/c_km)*(dl_eds(z,a, b))
### the theoretical apparent magnitude in EdS ###
def m_eds(z,a, b, Mcal):
#Mcal = M +42.38 - 5*np.log10(cosmo.h)
return np.hstack([5*np.log10(Dl_eds(z[i],a, b)) + Mcal for i in range(size)])
### construct the chi squared function in EdS ###
def chi_eds(params):
a = params[0]
b = params[1]
Mcal = params[2]
res1 = np.array([m_eds(z_cmb, a, b, Mcal) - mb]).reshape(1, 1048)
res3 = np.array([m_eds(z_cmb, a, b, Mcal) - mb]).reshape(1048, )
return np.sum(np.linalg.multi_dot([res1, C_covn, res3]))
#########################
# #
# MCMC #
# #
#########################
theta = [0.52, 6.5, 23.815]
### Define the prior function
def lnprior_eds(theta):
a, b, Mcal = theta
### define priors
if 0.1 < a < 0.9 and 0.0 < b < 35 and 23.0 < Mcal < 24.0:
return 0.0
return -np.inf
print(lnprior_eds(theta))
### combine into full log-probability function
def lnprob_eds(theta):
"""
Return the log posterior for given theta
"""
lp = lnprior_eds(theta)
if not np.isfinite(lp):
return -np.inf
return lp + (-0.5*chi_eds(theta))
### test the result of the posterior
print(lnprob_eds(theta))
### define no of parameters (equals the no of dimensions) and walkers
ndiml, nwalkersl = 3, 100
### define initial positions
### Choose the start location relatively close to the maximum-likelihood point from the minimization process
initial = np.array([0.5, 6.6, 23.81])
posl = [np.array(initial) + 0.0001*np.random.randn(ndiml) for i in range(nwalkersl)]
### run mcmc using multiprocessing to reduce the calcullation time
with Pool() as pool:
#Define the Affine-Invariant chain
sampler_eds = emcee.EnsembleSampler(nwalkersl, ndiml, lnprob_eds, pool=pool)
result_eds = sampler_eds.run_mcmc(posl, 2000, progress = True) # 2000 is the no of steps
#### Calculate the autocorrelation length (ACL) (or time).
####You can use this number to thin out chains to produce independent samples.
a_ac, b_ac, M_cal_ac = sampler_eds.get_autocorr_time(quiet=True)
print("The autocorrelation length for a is {0} and b is {1} and M_cal is {2}".format(a_ac, b_ac, M_cal_ac))
np.savetxt("fullflatchains_eds_2000 ",sampler_eds.get_chain(flat=True))
### thin out the chain
flat_samples_eds = sampler_eds.get_chain(discard=20, flat=True, thin=(int(max[a_ac, b_ac, M_cal_ac])))
np.savetxt("flatchains_eds_2000 ",flat_samples_eds)
print("Number of independent samples is {}".format(len(flat_samples_eds)))
### The flatchains from the MCMC analysis discarded the burn-in steps
flatchains2000 = np.loadtxt("/home/kerky/anaconda3/test_q/resultsfromq(L)/q(l)_EdS_1048/flatchains_eds_2000")
### plot the chains for each parameter
params = ["a", "b", "Mcal"]
for i in range(3):
plt.figure()
plt.title(params[i])
x = np.arange(len(flatchains2000[:,i]))
plt.plot(x,flatchains2000[:,i])
plt.show()
### USE CHAIN CONSUMER TO GENERATE PLOTS ###
cc = ChainConsumer()
params = [r"$\alpha$", "b", r"${\cal{M}}$"]
c = cc.add_chain(flatchains2000[:,:], parameters=params)
c.configure(kde= True, max_ticks=7, summary = False, shade_alpha=0.9, tick_font_size=11, label_font_size=15, sigmas=[1, 2], linewidths=1.2, colors="#673AB7", sigma2d = False, shade =True, flip = False)
### The maximum likelihood values for the t-EdS model can be found using the Analysis class of the Chain Consumer
BF_EdS = c.analysis.get_summary().values()
bf_a = list(BF_EdS)[0][1]
bf_b = list(BF_EdS)[1][1]
bf_mcal = list(BF_EdS)[2][1]
print(bf_a, bf_b, bf_mcal)
fig = c.plotter.plot(figsize=2.0, extents=[[0.39, 0.68], [0, 25], [23.75, 23.875]], display=True, truth = [bf_a, bf_b, bf_mcal])
|
module Discretion
OMNISCIENT_VIEWER = :__discretion_omnisient_viewer_val
OMNIPOTENT_VIEWER = :__discretion_omnipotent_viewer_val
class << self
CURRENT_VIEWER_KEY = :__discretion_current_viewer
CURRENTLY_ACTING_AS_KEY = :__discretion_currently_acting_as
def current_viewer
RequestStore[CURRENT_VIEWER_KEY]
end
def set_current_viewer(current_viewer)
RequestStore[CURRENT_VIEWER_KEY] = current_viewer
end
def currently_acting_as
RequestStore[CURRENTLY_ACTING_AS_KEY]
end
def currently_acting_as?(as)
currently_acting_as == as
end
def set_currently_acting_as(as)
RequestStore[CURRENTLY_ACTING_AS_KEY] = as
end
end
end
|
<filename>Ch21/ex21-09.sql
SELECT count(*)
FROM customers
LEFT JOIN employees
ON (customers.contact_surname=employees.surname
and customers.contact_firstname=employees.firstname
and customers.date_of_birth=employees.date_of_birth)
WHERE employees.surname IS NULL
|
#!/bin/bash
# Automated Installer Save Storage
# filename: lib/functions/logs.sh
# Author: Kevin RUE
# Contributor: Valentin NAINA
# http://www.rkweb.fr
logfileName="${AISS_PID}_$(date '+%Y%m%d_%H%M%S')_${AISS_NAME}.log"
logfile="${logsdir}/${logfileName}"
my_log_success() {
local status="SUCCESS"
local logfileSuccess="${logfile}.success"
printf "[$AISS_PID] $(date '+%Y/%m/%d %H:%M:%S') ${Green}[${status}] ${Color_Off}SVC_INFO "%1s" $*\n" | tee -a $logfile $logfileSuccess
return 0
}
my_log_error() {
local status="ERROR"
local logfileErr="${logfile}.error"
printf "[$AISS_PID] $(date '+%Y/%m/%d %H:%M:%S') ${Red}[${status}] "%1s" ${Color_Off}SVC_ERR "%2s" $*\n" | tee -a $logfile $logfileErr
return 1
}
my_log_warning() {
local status="WARNING"
local logfileWarn="${logfile}.warn"
printf "[$AISS_PID] $(date '+%Y/%m/%d %H:%M:%S') ${Yellow}[${status}] ${Color_Off}SVC_WARN "%1s" $*\n" | tee -a $logfile $logfileWarn
return 2
}
my_log_setup() {
local status="SETUP"
local logfileErr="${logfile}.setup"
printf "[$AISS_PID] $(date '+%Y/%m/%d %H:%M:%S') ${Cyan}[${status}] "%1s" ${Color_Off}SVC_SETUP"%1s" $*\n" | tee -a $logfile $logfileErr
return $?
} |
import matplotlib.pyplot as plt
import numpy as np
# Define the circular target
radius = 1
center = (0, 0)
# Simulate the throwing of darts
num_darts = 1000
x = np.random.uniform(-radius, radius, num_darts)
y = np.random.uniform(-radius, radius, num_darts)
distance = np.sqrt(x**2 + y**2)
# Plot the dart throws on a graph
plt.figure()
plt.scatter(x, y, c=distance <= radius, cmap='viridis', alpha=0.6)
plt.colorbar(label='Distance from center')
plt.axis('equal')
# Set the title of the graph
plt.title('Visual Dart Simulation: ' + str(num_darts) + ' Darts')
# Draw the circular target
theta = np.linspace(0, 2*np.pi, 100)
xcircle = radius * np.cos(theta)
ycircle = radius * np.sin(theta)
plt.plot(xcircle, ycircle, color='purple', alpha=0.6, linestyle='--', linewidth=3)
plt.show() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.