text
stringlengths 1
1.05M
|
|---|
<filename>src/routes/Shop/components/Shop.js
import React from 'react'
import { moneyFormat } from '../../../modules/helpers'
import './shop.scss'
import { Link } from 'react-router'
const Product = ({id, price, name, description, onAddToCart}) => (
<div className="product-box">
<h3>{name}</h3>
<p>{description}</p>
<section className="bottom">
<div className="price">{moneyFormat(price)}</div>
<button
className="add-to-cart"
onClick={ () => onAddToCart( {product: {id, name, price}} ) }
>
Add To Cart
</button>
</section>
</div>
)
export default class Shop extends React.Component{
constructor(props){
super(props);
props.getProducts();
props.getUsers();
}
componentDidUpdate(){
if(this.props.state.shop.displayNotice){
setTimeout(
() => this.props.destroyNoticeMsg(),
3500
)
}
}
selectUser = (e) => {
const { users } = this.props.state.shop;
for(let i = 0; i < users.length; i++){
if(users[i].id === e.target.value){
this.props.setActiveUser(users[i])
break
}
}
}
render(){
const {products, users, displayNotice, noticeMsg} = this.props.state.shop;
// console.log(this.props.state.shop);
return (
<div className="shop">
{users && (
<div className="test-user-select">
Test As:
<select value={this.props.state.shop.user.id} onChange={ this.selectUser }>
<option value="guest">Guest</option>
{users.map( (user) => (
<option key={user.id} value={ user.id }>{user.username}</option>
))}
</select>
</div>)}
{displayNotice && (
<div className="notice">{ noticeMsg }</div>
)}
<div className="checkout-wrapper">
<Link to="/checkout" className="checkout-btn">Checkout Now</Link>
</div>
<div className="products-wrapper center-block">
{products && products.map((p) => (
<Product key={p.id} {...p} onAddToCart={ this.props.addToCart }/>
))}
</div>
</div>
);
}
}
|
package org.rs2server.rs2.packet;
import org.rs2server.rs2.model.player.Player;
import org.rs2server.rs2.net.ActionSender.TabMode;
import org.rs2server.rs2.net.Packet;
public class ResizePacketHandler implements PacketHandler {
@Override
public void handle(Player player, Packet packet) {
int mode = packet.get();
int width = packet.getShort();
int height = packet.getShort();
switch (mode) {
case 1:
player.setAttribute("tabmode", TabMode.FIXED.getPane());
if (player.loadedIn) {
player.getActionSender()
.sendWindowPane(TabMode.FIXED.getPane());
player.getActionSender().sendSidebarInterfaces();
}
break;
case 2:
if (player.getAttribute("tabArranged") == null || player.getAttribute("tabArranged") != null && !(Boolean) player.getAttribute("tabArranged")) {
player.setAttribute("tabmode", TabMode.REARRANGED.getPane());
if (player.loadedIn) {
player.getActionSender().sendWindowPane(
TabMode.REARRANGED.getPane());
player.getActionSender().sendSidebarInterfaces();
}
} else if (player.getAttribute("tabArranged") != null && (Boolean) player.getAttribute("tabArranged")) {
player.setAttribute("tabmode", TabMode.RESIZE.getPane());
if (player.loadedIn) {
player.getActionSender().sendWindowPane(
TabMode.RESIZE.getPane());
player.getActionSender().sendSidebarInterfaces();
}
}
break;
}
}
}
|
/*
* Copyright 2015 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.oic.simulator.client.test;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.oic.simulator.AttributeValue;
import org.oic.simulator.InvalidArgsException;
import org.oic.simulator.SimulatorException;
import org.oic.simulator.SimulatorManager;
import org.oic.simulator.SimulatorResourceAttribute;
import org.oic.simulator.SimulatorResourceModel;
import org.oic.simulator.SimulatorResult;
import org.oic.simulator.client.FindResourceListener;
import org.oic.simulator.client.SimulatorRemoteResource;
import org.oic.simulator.server.SimulatorSingleResource;
import org.oic.simulator.test.ExceptionType;
import org.oic.simulator.utils.ObjectHolder;
import junit.framework.TestCase;
/**
* This class tests the APIs of SimulatorRemoteResource class.
*/
public class SimulatorRemoteResourceTest extends TestCase {
private static final String SINGLE_RES_RAML = "./ramls/oic.r.light.raml";
private static SimulatorSingleResource singleResource = null;
private static SimulatorRemoteResource remoteResource = null;
protected void setUp() throws Exception {
super.setUp();
// Create single resource for first time
if (null == singleResource) {
singleResource = (SimulatorSingleResource) SimulatorManager
.createResource(SINGLE_RES_RAML);
singleResource.start();
}
// Find the created resource for first time
if (null != singleResource && null == remoteResource) {
CountDownLatch lockObject = new CountDownLatch(1);
ObjectHolder<SimulatorRemoteResource> resourceHolder = new ObjectHolder<>();
FindResourceCallbackListener listener = new FindResourceCallbackListener(
lockObject, resourceHolder);
try {
SimulatorManager.findResource(singleResource.getResourceType(),
listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
remoteResource = resourceHolder.get();
}
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testGetUri_P01() {
String serverURI = null;
try {
serverURI = singleResource.getURI();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertNotNull(remoteResource.getURI());
assertEquals(serverURI, remoteResource.getURI());
}
public void testGetConnectivityType_P01() {
assertNotNull(remoteResource.getConnectivityType());
}
public void testGetResourceTypes_P01() {
assertNotNull(remoteResource.getResourceTypes());
assertTrue(remoteResource.getResourceTypes().size() > 0);
}
public void testGetResourceInterfaces_P01() {
assertNotNull(remoteResource.getResourceInterfaces());
assertTrue(remoteResource.getResourceInterfaces().size() > 0);
}
public void testGetHost_P01() {
assertNotNull(remoteResource.getHost());
}
public void testGetId_P01() {
assertNotNull(remoteResource.getId());
}
public void testIsObservable_P01() {
boolean serverObserveState = false;
try {
serverObserveState = singleResource.isObservable();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertEquals(serverObserveState, remoteResource.isObservable());
}
public void testGet_P01() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
GetResponseCallbackListener listener = new GetResponseCallbackListener(
lockObject, response);
try {
remoteResource.get(null, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testGet_P02() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
GetResponseCallbackListener listener = new GetResponseCallbackListener(
lockObject, response);
try {
Map<String, String> queryParams = new HashMap<>();
remoteResource.get(queryParams, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testGet_P03() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
GetResponseCallbackListener listener = new GetResponseCallbackListener(
lockObject, response);
try {
remoteResource.get(remoteResource.getResourceInterfaces().get(0),
null, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testGet_P04() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
GetResponseCallbackListener listener = new GetResponseCallbackListener(
lockObject, response);
try {
Map<String, String> queryParams = new HashMap<>();
remoteResource.get(remoteResource.getResourceInterfaces().get(0),
queryParams, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testGet_N01() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
remoteResource.get(null, null);
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testGet_N02() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
remoteResource.get(remoteResource.getResourceInterfaces().get(0),
null, null);
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testGet_N03() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
Map<String, String> queryParams = new HashMap<>();
remoteResource.get(null, queryParams,
new SimulatorRemoteResource.GetResponseListener() {
@Override
public void onGetResponse(String uid,
SimulatorResult result,
SimulatorResourceModel resourceModel) {
}
});
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testPut_P01() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
PutResponseCallbackListener listener = new PutResponseCallbackListener(
lockObject, response);
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
remoteResource.put(null, resModel, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testPut_P02() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
PutResponseCallbackListener listener = new PutResponseCallbackListener(
lockObject, response);
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
Map<String, String> queryParams = new HashMap<>();
remoteResource.put(queryParams, resModel, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testPut_P03() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
PutResponseCallbackListener listener = new PutResponseCallbackListener(
lockObject, response);
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
remoteResource.put(remoteResource.getResourceInterfaces().get(0),
null, resModel, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testPut_P05() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
PutResponseCallbackListener listener = new PutResponseCallbackListener(
lockObject, response);
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
Map<String, String> queryParams = new HashMap<>();
remoteResource.put(remoteResource.getResourceInterfaces().get(0),
queryParams, resModel, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testPut_P04() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
PutResponseCallbackListener listener = new PutResponseCallbackListener(
lockObject, response);
try {
Map<String, String> queryParams = new HashMap<>();
remoteResource.put(queryParams, null, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testPut_N01() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
remoteResource.put(null, resModel, null);
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testPut_N02() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
remoteResource.put(remoteResource.getResourceInterfaces().get(0),
null, resModel, null);
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testPut_N03() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
Map<String, String> queryParams = new HashMap<>();
remoteResource.put(null, queryParams, resModel,
new SimulatorRemoteResource.PutResponseListener() {
@Override
public void onPutResponse(String uid,
SimulatorResult result,
SimulatorResourceModel resourceModel) {
}
});
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testPost_P01() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
PostResponseCallbackListener listener = new PostResponseCallbackListener(
lockObject, response);
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
remoteResource.post(null, resModel, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testPost_P02() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
PostResponseCallbackListener listener = new PostResponseCallbackListener(
lockObject, response);
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
Map<String, String> queryParams = new HashMap<>();
remoteResource.post(queryParams, resModel, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testPost_P03() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
PostResponseCallbackListener listener = new PostResponseCallbackListener(
lockObject, response);
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
remoteResource.post(remoteResource.getResourceInterfaces().get(0),
null, resModel, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testPost_P04() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
PostResponseCallbackListener listener = new PostResponseCallbackListener(
lockObject, response);
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
Map<String, String> queryParams = new HashMap<>();
remoteResource.post(remoteResource.getResourceInterfaces().get(0),
queryParams, resModel, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testPost_P05() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
PostResponseCallbackListener listener = new PostResponseCallbackListener(
lockObject, response);
try {
Map<String, String> queryParams = new HashMap<>();
remoteResource.post(queryParams, null, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testPost_N01() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
remoteResource.post(null, resModel, null);
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testPost_N02() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
remoteResource.post(remoteResource.getResourceInterfaces().get(0),
null, resModel, null);
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testPost_N03() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
SimulatorResourceModel resModel = singleResource.getResourceModel();
Map<String, String> queryParams = new HashMap<>();
remoteResource.post(null, queryParams, resModel,
new SimulatorRemoteResource.PostResponseListener() {
@Override
public void onPostResponse(String uid,
SimulatorResult result,
SimulatorResourceModel resourceModel) {
}
});
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testStartObserve_P01() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
ObserveNotificationCallbackListener listener = new ObserveNotificationCallbackListener(
lockObject, response);
try {
Map<String, String> queryParams = new HashMap<>();
remoteResource.observe(queryParams, listener);
singleResource.addAttribute(new SimulatorResourceAttribute(
"boolean", new AttributeValue(true), null));
singleResource.removeAttribute("boolean");
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
remoteResource.stopObserve();
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testStartObserve_P02() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
ObserveNotificationCallbackListener listener = new ObserveNotificationCallbackListener(
lockObject, response);
try {
remoteResource.observe(listener);
singleResource.addAttribute(new SimulatorResourceAttribute(
"boolean", new AttributeValue(true), null));
singleResource.removeAttribute("boolean");
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
remoteResource.stopObserve();
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertNotNull(response.get().resourceModel());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testStartObserve_N01() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
Map<String, String> queryParams = new HashMap<>();
remoteResource.observe(queryParams, null);
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testStopObserve_P01() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
ObserveNotificationCallbackListener listener = new ObserveNotificationCallbackListener(
lockObject, response);
try {
Map<String, String> queryParams = new HashMap<>();
remoteResource.observe(queryParams, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
response.set(null);
remoteResource.stopObserve();
singleResource.addAttribute(new SimulatorResourceAttribute(
"boolean", new AttributeValue(true), null));
singleResource.removeAttribute("boolean");
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNull(response.get());
}
public void testSetConfigInfo_P01() {
boolean syncResult = false;
try {
remoteResource.setConfigInfo(SINGLE_RES_RAML);
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
}
public void testSetConfigInfo_N01() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
remoteResource.setConfigInfo("");
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testSetConfigInfo_N02() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
remoteResource.setConfigInfo(null);
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testStartVerification_P01() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
VerificationCallbackListener listener = new VerificationCallbackListener(
lockObject, response);
try {
remoteResource.setConfigInfo(SINGLE_RES_RAML);
remoteResource.startVerification(
SimulatorRemoteResource.RequestType.GET, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testStartVerification_P02() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
VerificationCallbackListener listener = new VerificationCallbackListener(
lockObject, response);
try {
remoteResource.setConfigInfo(SINGLE_RES_RAML);
remoteResource.startVerification(
SimulatorRemoteResource.RequestType.PUT, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testStartVerification_P03() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
VerificationCallbackListener listener = new VerificationCallbackListener(
lockObject, response);
try {
remoteResource.setConfigInfo(SINGLE_RES_RAML);
remoteResource.startVerification(
SimulatorRemoteResource.RequestType.POST, listener);
try {
lockObject.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
assertNotNull(response.get());
assertEquals(remoteResource.getId(), response.get().uid());
}
public void testStartVerification_N01() {
ExceptionType exType = ExceptionType.UNKNOWN;
try {
remoteResource.setConfigInfo(SINGLE_RES_RAML);
remoteResource.startVerification(
SimulatorRemoteResource.RequestType.GET, null);
} catch (InvalidArgsException e) {
exType = ExceptionType.INVALID_ARGS;
} catch (SimulatorException e) {
exType = ExceptionType.SIMULATOR;
}
assertTrue(exType == ExceptionType.INVALID_ARGS);
}
public void testStopVerification_N01() {
CountDownLatch lockObject = new CountDownLatch(1);
boolean syncResult = false;
ObjectHolder<ResponseDetails> response = new ObjectHolder<>();
VerificationCallbackListener listener = new VerificationCallbackListener(
lockObject, response);
try {
remoteResource.setConfigInfo(SINGLE_RES_RAML);
int id = remoteResource.startVerification(
SimulatorRemoteResource.RequestType.POST, listener);
remoteResource.stopVerification(id);
syncResult = true;
} catch (InvalidArgsException e) {
e.printStackTrace();
} catch (SimulatorException e) {
e.printStackTrace();
}
assertTrue(syncResult);
}
}
class ResponseDetails {
private String mUid = null;
private SimulatorResourceModel mResModel = null;
private SimulatorResult mResult = SimulatorResult.SIMULATOR_ERROR;
ResponseDetails(String uid, SimulatorResult result,
SimulatorResourceModel resModel) {
mUid = uid;
mResModel = resModel;
mResult = result;
}
String uid() {
return mUid;
}
SimulatorResourceModel resourceModel() {
return mResModel;
}
SimulatorResult errorCode() {
return mResult;
}
}
class GetResponseCallbackListener
implements SimulatorRemoteResource.GetResponseListener {
private CountDownLatch mLockObject;
private ObjectHolder<ResponseDetails> mResponse;
public GetResponseCallbackListener(CountDownLatch lockObject,
ObjectHolder<ResponseDetails> response) {
mLockObject = lockObject;
mResponse = response;
}
@Override
public void onGetResponse(String uid, SimulatorResult result,
SimulatorResourceModel resourceModel) {
mResponse.set(new ResponseDetails(uid, result, resourceModel));
mLockObject.countDown();
}
}
class PutResponseCallbackListener
implements SimulatorRemoteResource.PutResponseListener {
private CountDownLatch mLockObject;
private ObjectHolder<ResponseDetails> mResponse;
public PutResponseCallbackListener(CountDownLatch lockObject,
ObjectHolder<ResponseDetails> response) {
mLockObject = lockObject;
mResponse = response;
}
@Override
public void onPutResponse(String uid, SimulatorResult result,
SimulatorResourceModel resourceModel) {
mResponse.set(new ResponseDetails(uid, result, resourceModel));
mLockObject.countDown();
}
}
class PostResponseCallbackListener
implements SimulatorRemoteResource.PostResponseListener {
private CountDownLatch mLockObject;
private ObjectHolder<ResponseDetails> mResponse;
public PostResponseCallbackListener(CountDownLatch lockObject,
ObjectHolder<ResponseDetails> response) {
mLockObject = lockObject;
mResponse = response;
}
@Override
public void onPostResponse(String uid, SimulatorResult result,
SimulatorResourceModel resourceModel) {
mResponse.set(new ResponseDetails(uid, result, resourceModel));
mLockObject.countDown();
}
}
class ObserveNotificationCallbackListener
implements SimulatorRemoteResource.ObserveNotificationListener {
private CountDownLatch mLockObject;
private ObjectHolder<ResponseDetails> mResponse;
public ObserveNotificationCallbackListener(CountDownLatch lockObject,
ObjectHolder<ResponseDetails> response) {
mLockObject = lockObject;
mResponse = response;
}
@Override
public void onObserveNotification(String uid,
SimulatorResourceModel resourceModel, int sequenceNumber) {
mResponse.set(new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK,
resourceModel));
mLockObject.countDown();
}
}
class VerificationCallbackListener
implements SimulatorRemoteResource.VerificationListener {
private CountDownLatch mLockObject;
private ObjectHolder<ResponseDetails> mResponse;
public VerificationCallbackListener(CountDownLatch lockObject,
ObjectHolder<ResponseDetails> response) {
mLockObject = lockObject;
mResponse = response;
}
@Override
public void onVerificationStarted(String uid, int id) {
mResponse.set(
new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK, null));
mLockObject.countDown();
}
@Override
public void onVerificationAborted(String uid, int id) {
mResponse.set(
new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK, null));
mLockObject.countDown();
}
@Override
public void onVerificationCompleted(String uid, int id) {
mResponse.set(
new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK, null));
mLockObject.countDown();
}
}
class FindResourceCallbackListener implements FindResourceListener {
private CountDownLatch mLockObject;
private ObjectHolder<SimulatorRemoteResource> mResourceHolder;
public FindResourceCallbackListener(CountDownLatch lockObject,
ObjectHolder<SimulatorRemoteResource> resourceHolder) {
mLockObject = lockObject;
mResourceHolder = resourceHolder;
}
@Override
public void onResourceFound(SimulatorRemoteResource resource) {
mResourceHolder.set(resource);
mLockObject.countDown();
}
}
|
<filename>src/login/login-form.js
import React, {Component} from 'react';
import PropTypes from 'prop-types'
import {
FormLabel,
Button
} from 'react-native-elements'
import {
View,
Text,
TouchableOpacity
} from 'react-native';
import {
Form,
FormInput
} from 'eureka-rn-components';
import Username from './username';
import Password from './password';
const MsgValidation = ({style, message}) => (
<Text style={[
style,
{
position: 'absolute',
left: 20,
top: -10
}
]}>
{message}
</Text>
);
export default class Login extends Component {
static propTypes = {
onSubmit: PropTypes.func,
light: PropTypes.bool,
validationMessage: PropTypes.string
}
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
};
}
getLabels() {
const defaults = {
submit: 'Entrar',
username: 'Email',
password: '<PASSWORD>',
forgetPassword: '<PASSWORD>',
passwordLenghtValidation: 'Senha dever ter 4 ou mais digitos'
};
return {...defaults, ...this.props.labels};
}
getCustomStyles() {
return {
messageValidationColor: '#c4c4c4',
text: '#ffffff',
...this.props.customStyles
};
}
renderSubmit(submit) {
const { customStyles = {}} = this.props;
const labels = this.getLabels();
return (
<Button
Component={ TouchableOpacity }
onPress={ submit }
buttonStyle={[{
marginTop: 15,
}, customStyles.submit]}
raised
icon={{name: 'check'}}
title={ labels.submit } />
);
}
handleSubmit() {
//todo: fazer requisição para login
const {onSubmit = () => {}} = this.props;
const {username, password} = this.state;
onSubmit(username, password);
}
renderFormFields() {
const { style, validationMessage } = this.props;
const customStyles = this.getCustomStyles();
const labels = this.getLabels();
const { username, password } = this.state;
return (
<Form style={style}
onSuccess={this.handleSubmit.bind(this)}
submitButton={this.renderSubmit.bind(this)}>
{ validationMessage ? <MsgValidation
style={{color: customStyles.messageValidationColor}}
message={validationMessage}/> : null }
<Username
label={ labels.username }
value={ username }
onChangeText={username => this.setState({username})}
customStyles={customStyles } />
<Password
labels={ labels }
value={ password }
customStyles={ customStyles }
onChangeText={password => this.setState({password})} />
</Form>
);
}
render() {
return (
<View>
{ this.renderFormFields() }
{ this.props.socialButtons }
</View>
);
}
}
|
#!/bin/bash
#SBATCH --gres=gpu:turing
# You can control the resources and scheduling with '#SBATCH' settings
# (see 'man sbatch' for more information on setting these parameters)
# The default partition is the 'general' partition
#SBATCH --partition=general
# The default Quality of Service is the 'short' QoS (maximum run time: 4 hours)
#SBATCH --qos=medium
# The default run (wall-clock) time is 1 minute
#SBATCH --time=20:00:00
# The default number of parallel tasks per job is 1
#SBATCH --ntasks=1
# Request 1 CPU per active thread of your program (assume 1 unless you specifically set this)
# The default number of CPUs per task is 1 (note: CPUs are always allocated per 2)
#SBATCH --cpus-per-task=8
# The default memory per node is 1024 megabytes (1GB) (for multiple tasks, specify --mem-per-cpu instead)
#SBATCH --mem=24000
# Set mail type to 'END' to receive a mail when the job finishes
# Do not enable mails when submitting large numbers (>20) of jobs at once
#SBATCH --mail-type=END
# 90 seconds before training ends, to help create a checkpoint and requeue the job
#SBATCH --signal=SIGUSR1@90
module use /opt/insy/modulefiles
module load cuda/11.1 cudnn/11.1-8.0.5.39
module load miniconda/3.9
# Complex or heavy commands should be started with 'srun' (see 'man srun' for more information)
# For example: srun python my_program.py
# Use this simple command to check that your sbatch settings are working (verify the resources allocated in the usage statistics)
rnd_uuid=$(uuidgen)
source activate /home/nfs/oshirekar/unsupervised_ml/ai2
# km_clusters below fulfills the role of hdb_min_cluster_size
srun python ../../runner.py protoclr_ae miniimagenet "/home/nfs/oshirekar/unsupervised_ml/data/" \
--lr=1e-3 \
--inner_lr=1e-3 \
--batch_size=50 \
--num_workers=6 \
--eval-ways=5 \
--eval_support_shots=5 \
--distance='euclidean' \
--logging='wandb' \
--clustering_alg="hdbscan" \
--km_clusters=5 \
--cl_reduction="mean" \
--ae=False \
--profiler='simple' \
--train_oracle_mode=False \
--callbacks=False \
--patience=300 \
--no_aug_support=True \
--ckpt_dir="/home/nfs/oshirekar/unsupervised_ml/ckpts" \
--use_umap=False \
--rerank_kjrd=True \
--rrk1=20 \
--rrk2=6 \
--rrlambda=0 \
--uuid=$rnd_uuid
|
package com.biniam.designpatterns.state;
/**
* @author <NAME>
*/
public class EraseTool implements Tool {
@Override
public void mouseDown() {
System.out.println("Erase icon");
}
@Override
public void mouseUp() {
System.out.println("Erase something");
}
}
|
"""Test suite for the nox_poetry package."""
|
package ssjava.cholmod;
/**
* Ordering for sparsity preservation
*/
public enum Order
{
CHOLMOD_NATURAL,
CHOLMOD_GIVEN,
CHOLMOD_AMD,
CHOLMOD_METIS,
CHOLMOD_NESDIS,
CHOLMOD_COLAMD,
CHOLMOD_POSTORDERED
}
|
require './lib/command_line_interface.rb'
require './lib/movie.rb'
require './lib/scraper.rb'
|
/*
* Copyright (c) 2006-2014 <NAME> <<EMAIL>>,
* 2006-2009 <NAME> <<EMAIL>>,
* 2015 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <ctype.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <signal.h>
#include <unistd.h>
#include <sys/param.h>
#include <fcntl.h>
#include <zlib.h>
#include <sys/time.h>
#include <time.h>
#include <errno.h>
#ifdef WINDOWS32
#include "windows.h"
#else
#include <arpa/nameser.h>
#ifdef ANDROID
#include "android_dns.h"
#endif
#ifdef DARWIN
#define BIND_8_COMPAT
#include <arpa/nameser_compat.h>
#endif
#include <grp.h>
#include <pwd.h>
#include <netdb.h>
#endif
#include "common.h"
#include "encoding.h"
#include "base32.h"
#include "base64.h"
#include "base64u.h"
#include "base128.h"
#include "dns.h"
#include "login.h"
#include "tun.h"
#include "version.h"
#include "window.h"
#include "util.h"
#include "client.h"
int
client_set_qtype(char *qtype)
{
if (!strcasecmp(qtype, "NULL"))
this.do_qtype = T_NULL;
else if (!strcasecmp(qtype, "PRIVATE"))
this.do_qtype = T_PRIVATE;
else if (!strcasecmp(qtype, "CNAME"))
this.do_qtype = T_CNAME;
else if (!strcasecmp(qtype, "A"))
this.do_qtype = T_A;
else if (!strcasecmp(qtype, "MX"))
this.do_qtype = T_MX;
else if (!strcasecmp(qtype, "SRV"))
this.do_qtype = T_SRV;
else if (!strcasecmp(qtype, "TXT"))
this.do_qtype = T_TXT;
else if (!strcasecmp(qtype, "PTR"))
this.do_qtype = T_PTR;
else if (!strcasecmp(qtype, "AAAA"))
this.do_qtype = T_AAAA;
else if (!strcasecmp(qtype, "A6"))
this.do_qtype = T_A6;
else if (!strcasecmp(qtype, "DNAME"))
this.do_qtype = T_DNAME;
return (this.do_qtype == T_UNSET);
}
char *
client_get_qtype()
{
char *c = "UNDEFINED";
if (this.do_qtype == T_NULL) c = "NULL";
else if (this.do_qtype == T_PRIVATE) c = "PRIVATE";
else if (this.do_qtype == T_CNAME) c = "CNAME";
else if (this.do_qtype == T_A) c = "A";
else if (this.do_qtype == T_MX) c = "MX";
else if (this.do_qtype == T_SRV) c = "SRV";
else if (this.do_qtype == T_TXT) c = "TXT";
else if (this.do_qtype == T_PTR) c = "PTR";
else if (this.do_qtype == T_AAAA) c = "AAAA";
else if (this.do_qtype == T_A6) c = "A6";
else if (this.do_qtype == T_DNAME) c = "DNAME";
return c;
}
char
parse_encoding(char *encoding)
{
char enc_char = 0;
if (!strcasecmp(encoding, "base32"))
enc_char = 'T';
else if (!strcasecmp(encoding, "base64"))
enc_char = 'S';
else if (!strcasecmp(encoding, "base64u"))
enc_char = 'U';
else if (!strcasecmp(encoding, "base128"))
enc_char = 'V';
else if (!strcasecmp(encoding, "raw"))
enc_char = 'R';
return enc_char;
}
void
client_set_hostname_maxlen(size_t i)
{
if (i <= 0xFF && i != this.hostname_maxlen) {
this.hostname_maxlen = i;
this.maxfragsize_up = get_raw_length_from_dns(this.hostname_maxlen - UPSTREAM_HDR,
this.dataenc, this.topdomain);
if (this.outbuf)
window_buffer_resize(this.outbuf, this.outbuf->length, this.maxfragsize_up);
}
}
const char *
client_get_raw_addr()
{
return format_addr(&this.raw_serv, this.raw_serv_len);
}
void
client_rotate_nameserver()
{
this.current_nameserver ++;
if (this.current_nameserver >= this.nameserv_addrs_count)
this.current_nameserver = 0;
}
void
immediate_mode_defaults()
{
this.send_interval_ms = MIN(this.rtt_total_ms / this.num_immediate, 1000);
this.max_timeout_ms = MAX(4 * this.rtt_total_ms / this.num_immediate, 5000);
this.server_timeout_ms = 0;
}
/* Client-side query tracking for lazy mode */
/* Handy macro for printing this.stats with messages */
#ifdef DEBUG_BUILD
#define QTRACK_DEBUG(l, ...) \
if (this.debug >= l) {\
TIMEPRINT("[QTRACK (%" L "u/%" L "u), ? %" L "u, TO %" L "u, S %" L "u/%" L "u] ", this.num_pending, PENDING_QUERIES_LENGTH, \
this.num_untracked, this.num_timeouts, window_sending(this.outbuf, NULL), this.outbuf->numitems); \
fprintf(stderr, __VA_ARGS__);\
fprintf(stderr, "\n");\
}
#else
#define QTRACK_DEBUG(...)
#endif
static int
update_server_timeout(int handshake)
/* Calculate server timeout based on average RTT, send ping "handshake" to set
* if handshake sent, return query ID */
{
time_t rtt_ms;
static size_t num_rtt_timeouts = 0;
/* Get average RTT in ms */
rtt_ms = (this.num_immediate == 0) ? 1 : this.rtt_total_ms / this.num_immediate;
if (rtt_ms >= this.max_timeout_ms && this.num_immediate > 5) {
num_rtt_timeouts++;
if (num_rtt_timeouts < 3) {
fprintf(stderr, "Target interval of %ld ms less than average round-trip of "
"%ld ms! Try increasing interval with -I.\n", this.max_timeout_ms, rtt_ms);
} else {
/* bump up target timeout */
this.max_timeout_ms = rtt_ms + 1000;
this.server_timeout_ms = 1000;
if (this.lazymode)
fprintf(stderr, "Adjusting server timeout to %ld ms, target interval %ld ms. Try -I%.1f next time with this network.\n",
this.server_timeout_ms, this.max_timeout_ms, this.max_timeout_ms / 1000.0);
num_rtt_timeouts = 0;
}
} else {
/* Set server timeout based on target interval and RTT */
this.server_timeout_ms = this.max_timeout_ms - rtt_ms;
if (this.server_timeout_ms <= 0) {
this.server_timeout_ms = 0;
fprintf(stderr, "Setting server timeout to 0 ms: if this continues try disabling lazy mode. (-L0)\n");
}
}
/* update up/down window timeouts to something reasonable */
this.downstream_timeout_ms = rtt_ms * this.downstream_delay_variance;
this.outbuf->timeout = ms_to_timeval(this.downstream_timeout_ms);
if (handshake) {
/* Send ping handshake to set server timeout */
return send_ping(1, -1, 1, 0);
}
return -1;
}
static void
check_pending_queries()
/* Updates pending queries list */
{
this.num_pending = 0;
struct timeval now, qtimeout, max_timeout;
gettimeofday(&now, NULL);
/* Max timeout for queries is max interval + 1 second extra */
max_timeout = ms_to_timeval(this.max_timeout_ms + 1000);
for (int i = 0; i < PENDING_QUERIES_LENGTH; i++) {
if (this.pending_queries[i].time.tv_sec > 0 && this.pending_queries[i].id >= 0) {
timeradd(&this.pending_queries[i].time, &max_timeout, &qtimeout);
if (!timercmp(&qtimeout, &now, >)) {
/* Query has timed out, clear timestamp but leave ID */
this.pending_queries[i].time.tv_sec = 0;
this.num_timeouts++;
}
this.num_pending++;
}
}
}
static void
query_sent_now(int id)
{
int i = 0, found = 0;
if (!this.pending_queries)
return;
if (id < 0 || id > 65535)
return;
/* Replace any empty queries first, then timed out ones if necessary */
for (i = 0; i < PENDING_QUERIES_LENGTH; i++) {
if (this.pending_queries[i].id < 0) {
found = 1;
break;
}
}
if (!found) {
for (i = 0; i < PENDING_QUERIES_LENGTH; i++) {
if (this.pending_queries[i].time.tv_sec == 0) {
found = 1;
break;
}
}
}
/* if no slots found after both checks */
if (!found) {
QTRACK_DEBUG(1, "Buffer full! Failed to add id %d.", id);
} else {
/* Add query into found location */
this.pending_queries[i].id = id;
gettimeofday(&this.pending_queries[i].time, NULL);
this.num_pending ++;
QTRACK_DEBUG(4, "Adding query id %d into this.pending_queries[%d]", id, i);
id = -1;
}
}
static void
got_response(int id, int immediate, int fail)
/* immediate: if query was replied to immediately (see below) */
{
struct timeval now, rtt;
time_t rtt_ms;
static time_t rtt_min_ms = 1;
gettimeofday(&now, NULL);
QTRACK_DEBUG(4, "Got answer id %d (%s)%s", id, immediate ? "immediate" : "lazy",
fail ? ", FAIL" : "");
for (int i = 0; i < PENDING_QUERIES_LENGTH; i++) {
if (id >= 0 && this.pending_queries[i].id == id) {
if (this.num_pending > 0)
this.num_pending--;
if (this.pending_queries[i].time.tv_sec == 0) {
if (this.num_timeouts > 0) {
/* If query has timed out but is still stored - just in case
* ID is kept on timeout in check_pending_queries() */
this.num_timeouts --;
immediate = 0;
} else {
/* query is empty */
continue;
}
}
if (immediate || this.debug >= 4) {
timersub(&now, &this.pending_queries[i].time, &rtt);
rtt_ms = timeval_to_ms(&rtt);
}
QTRACK_DEBUG(5, " found answer id %d in pending queries[%d], %ld ms old", id, i, rtt_ms);
if (immediate) {
/* If this was an immediate response we can use it to get
more detailed connection statistics like RTT.
This lets us determine and adjust server lazy response time
during the session much more accurately. */
this.rtt_total_ms += rtt_ms;
this.num_immediate++;
if (this.autodetect_server_timeout) {
if (this.autodetect_delay_variance) {
if (rtt_ms > 0 && (rtt_ms < rtt_min_ms || 1 == rtt_min_ms)) {
rtt_min_ms = rtt_ms;
}
this.downstream_delay_variance = (double) (this.rtt_total_ms /
this.num_immediate) / rtt_min_ms;
}
update_server_timeout(0);
}
}
/* Remove query info from buffer to mark it as answered */
id = -1;
this.pending_queries[i].id = -1;
this.pending_queries[i].time.tv_sec = 0;
break;
}
}
if (id > 0) {
QTRACK_DEBUG(4, " got untracked response to id %d.", id);
this.num_untracked++;
}
}
static int
send_query(uint8_t *hostname)
/* Returns DNS ID of sent query */
{
uint8_t packet[4096];
struct query q;
size_t len;
DEBUG(3, "TX: pkt len %" L "u: hostname '%s'", strlen((char *)hostname), hostname);
this.chunkid += 7727;
if (this.chunkid == 0)
/* 0 is used as "no-query" in iodined.c */
this.chunkid = rand() & 0xFF;
q.id = this.chunkid;
q.type = this.do_qtype;
len = dns_encode((char *)packet, sizeof(packet), &q, QR_QUERY, (char *)hostname, strlen((char *)hostname));
if (len < 1) {
warnx("dns_encode doesn't fit");
return -1;
}
DEBUG(4, " Sendquery: id %5d name[0] '%c'", q.id, hostname[0]);
sendto(this.dns_fd, packet, len, 0, (struct sockaddr*) &this.nameserv_addrs[this.current_nameserver].addr,
this.nameserv_addrs[this.current_nameserver].len);
client_rotate_nameserver();
/* There are DNS relays that time out quickly but don't send anything
back on timeout.
And there are relays where, in lazy mode, our new query apparently
_replaces_ our previous query, and we get no answers at all in
lazy mode while legacy immediate-ping-pong works just fine.
In this case, the up/down windowsizes may need to be set to 1 for there
to only ever be one query pending.
Here we detect and fix these situations.
(Can't very well do this anywhere else; this is the only place
we'll reliably get to in such situations.)
Note: only start fixing up connection AFTER we have this.connected
and if user hasn't specified server timeout/window timeout etc. */
this.num_sent++;
if (this.send_query_sendcnt > 0 && this.send_query_sendcnt < 100 &&
this.lazymode && this.connected && this.autodetect_server_timeout) {
this.send_query_sendcnt++;
if ((this.send_query_sendcnt > this.windowsize_down && this.send_query_recvcnt <= 0) ||
(this.send_query_sendcnt > 2 * this.windowsize_down && 4 * this.send_query_recvcnt < this.send_query_sendcnt)) {
if (this.max_timeout_ms > 500) {
this.max_timeout_ms -= 200;
double secs = (double) this.max_timeout_ms / 1000.0;
fprintf(stderr, "Receiving too few answers. Setting target timeout to %.1fs (-I%.1f)\n", secs, secs);
/* restart counting */
this.send_query_sendcnt = 0;
this.send_query_recvcnt = 0;
} else if (this.lazymode) {
fprintf(stderr, "Receiving too few answers. Will try to switch lazy mode off, but that may not"
" always work any more. Start with -L0 next time on this network.\n");
this.lazymode = 0;
this.server_timeout_ms = 0;
}
update_server_timeout(1);
}
}
return q.id;
}
static void
send_raw(uint8_t *buf, size_t buflen, int cmd)
{
char packet[4096];
int len;
len = MIN(sizeof(packet) - RAW_HDR_LEN, buflen);
memcpy(packet, raw_header, RAW_HDR_LEN);
if (len) {
memcpy(&packet[RAW_HDR_LEN], buf, len);
}
len += RAW_HDR_LEN;
packet[RAW_HDR_CMD] = (cmd & 0xF0) | (this.userid & 0x0F);
sendto(this.dns_fd, packet, len, 0, (struct sockaddr*)&this.raw_serv, sizeof(this.raw_serv));
}
static void
send_raw_data(uint8_t *data, size_t datalen)
{
send_raw(data, datalen, RAW_HDR_CMD_DATA);
}
static int
send_packet(char cmd, const uint8_t *data, const size_t datalen)
/* Base32 encodes data and sends as single DNS query
* cmd becomes first byte of query, followed by hex userid, encoded
* data and 3 bytes base32 encoded CMC
* Returns ID of sent query */
{
uint8_t buf[512], data_with_cmc[datalen + 2];
if (data)
memcpy(data_with_cmc, data, datalen);
*(uint16_t *) (data_with_cmc + datalen) = this.rand_seed;
this.rand_seed++;
buf[0] = cmd;
buf[1] = this.userid_char;
build_hostname(buf, sizeof(buf), data_with_cmc, datalen + 2,
this.topdomain, b32, this.hostname_maxlen, 2);
return send_query(buf);
}
int
send_ping(int ping_response, int ack, int set_timeout, int disconnect)
{
this.num_pings++;
if (this.conn == CONN_DNS_NULL) {
uint8_t data[12];
int id;
/* Build ping header (see doc/proto_xxxxxxxx.txt) */
data[0] = ack & 0xFF;
if (this.outbuf && this.inbuf) {
data[1] = this.outbuf->windowsize & 0xff; /* Upstream window size */
data[2] = this.inbuf->windowsize & 0xff; /* Downstream window size */
data[3] = this.outbuf->start_seq_id & 0xff; /* Upstream window start */
data[4] = this.inbuf->start_seq_id & 0xff; /* Downstream window start */
}
*(uint16_t *) (data + 5) = htons(this.server_timeout_ms);
*(uint16_t *) (data + 7) = htons(this.downstream_timeout_ms);
/* update server frag/lazy timeout, ack flag, respond with ping flag */
data[9] = ((disconnect & 1) << 5) | ((set_timeout & 1) << 4) |
((set_timeout & 1) << 3) | ((ack < 0 ? 0 : 1) << 2) | (ping_response & 1);
data[10] = (this.rand_seed >> 8) & 0xff;
data[11] = (this.rand_seed >> 0) & 0xff;
this.rand_seed += 1;
DEBUG(3, " SEND PING: %srespond %d, ack %d, %s(server %ld ms, downfrag %ld ms), flags %02X, wup %u, wdn %u",
disconnect ? "DISCONNECT! " : "", ping_response, ack, set_timeout ? "SET " : "",
this.server_timeout_ms, this.downstream_timeout_ms,
data[8], this.outbuf->windowsize, this.inbuf->windowsize);
id = send_packet('p', data, sizeof(data));
/* Log query ID as being sent now */
query_sent_now(id);
return id;
} else {
send_raw(NULL, 0, RAW_HDR_CMD_PING);
return -1;
}
}
static void
send_next_frag()
/* Sends next available fragment of data from the outgoing window buffer */
{
static uint8_t buf[MAX_FRAGSIZE], hdr[5];
int code, id;
static int datacmc = 0;
static char *datacmcchars = "abcdefghijklmnopqrstuvwxyz0123456789";
fragment *f;
size_t buflen;
/* Get next fragment to send */
f = window_get_next_sending_fragment(this.outbuf, &this.next_downstream_ack);
if (!f) {
if (this.outbuf->numitems > 0) {
/* There is stuff to send but we're out of sync, so send a ping
* to get things back in order and keep the packets flowing */
send_ping(1, this.next_downstream_ack, 1, 0);
this.next_downstream_ack = -1;
}
return; /* nothing to send */
}
/* Build upstream data header (see doc/proto_xxxxxxxx.txt) */
buf[0] = this.userid_char; /* First byte is hex this.userid */
buf[1] = datacmcchars[datacmc]; /* Second byte is data-CMC */
/* Next 3 bytes is seq ID, downstream ACK and flags */
code = ((f->ack_other < 0 ? 0 : 1) << 3) | (f->compressed << 2)
| (f->start << 1) | f->end;
hdr[0] = f->seqID & 0xFF;
hdr[1] = f->ack_other & 0xFF;
hdr[2] = code << 4; /* Flags are in upper 4 bits - lower 4 unused */
buflen = sizeof(buf) - 1;
/* Encode 3 bytes data into 2 bytes after buf */
b32->encode(buf + 2, &buflen, hdr, 3);
/* Encode data into buf after header (6 = user + CMC + 4 bytes header) */
build_hostname(buf, sizeof(buf), f->data, f->len, this.topdomain,
this.dataenc, this.hostname_maxlen, 6);
datacmc++;
if (datacmc >= 36)
datacmc = 0;
DEBUG(3, " SEND DATA: seq %d, ack %d, len %" L "u, s%d e%d c%d flags %1X",
f->seqID, f->ack_other, f->len, f->start, f->end, f->compressed, hdr[2] >> 4);
id = send_query(buf);
/* Log query ID as being sent now */
query_sent_now(id);
window_tick(this.outbuf);
this.num_frags_sent++;
}
static void
write_dns_error(struct query *q, int ignore_some_errors)
/* This is called from:
1. handshake_waitdns() when already checked that reply fits to our
latest query.
2. tunnel_dns() when already checked that reply is for a ping or data
packet, but possibly timed out.
Errors should not be ignored, but too many can be annoying.
*/
{
static size_t errorcounts[24] = {0};
if (!q) return;
if (q->rcode < 24) {
errorcounts[q->rcode]++;
if (errorcounts[q->rcode] == 20) {
warnx("Too many error replies, not logging any more.");
return;
} else if (errorcounts[q->rcode] > 20) {
return;
}
}
switch (q->rcode) {
case NOERROR: /* 0 */
if (!ignore_some_errors)
warnx("Got reply without error, but also without question and/or answer");
break;
case FORMERR: /* 1 */
warnx("Got FORMERR as reply: server does not understand our request");
break;
case SERVFAIL: /* 2 */
if (!ignore_some_errors)
warnx("Got SERVFAIL as reply: server failed or recursion timeout");
break;
case NXDOMAIN: /* 3 */
warnx("Got NXDOMAIN as reply: domain does not exist");
break;
case NOTIMP: /* 4 */
warnx("Got NOTIMP as reply: server does not support our request");
break;
case REFUSED: /* 5 */
warnx("Got REFUSED as reply");
break;
default:
warnx("Got RCODE %u as reply", q->rcode);
break;
}
}
static size_t
dns_namedec(uint8_t *outdata, size_t outdatalen, uint8_t *buf, size_t buflen)
/* Decodes *buf to *outdata.
* *buf WILL be changed by undotify.
* Note: buflen must be _exactly_ strlen(buf) before undotifying.
* (undotify of reduced-len won't copy \0, base-X decode will decode too much.)
* Returns #bytes usefully filled in outdata.
*/
{
size_t outdatalenu = outdatalen;
switch (buf[0]) {
case 'h': /* Hostname with base32 */
case 'H':
/* Need 1 byte H, 3 bytes ".xy", >=1 byte data */
if (buflen < 5)
return 0;
/* this also does undotify */
return unpack_data(outdata, outdatalen, buf + 1, buflen - 4, b32);
case 'i': /* Hostname++ with base64 */
case 'I':
/* Need 1 byte I, 3 bytes ".xy", >=1 byte data */
if (buflen < 5)
return 0;
/* this also does undotify */
return unpack_data(outdata, outdatalen, buf + 1, buflen - 4, b64);
case 'j': /* Hostname++ with base64u */
case 'J':
/* Need 1 byte J, 3 bytes ".xy", >=1 byte data */
if (buflen < 5)
return 0;
/* this also does undotify */
return unpack_data(outdata, outdatalen, buf + 1, buflen - 4, b64u);
case 'k': /* Hostname++ with base128 */
case 'K':
/* Need 1 byte J, 3 bytes ".xy", >=1 byte data */
if (buflen < 5)
return 0;
/* this also does undotify */
return unpack_data(outdata, outdatalen, buf + 1, buflen - 4, b128);
case 't': /* plain base32(Thirty-two) from TXT */
case 'T':
if (buflen < 2)
return 0;
return b32->decode(outdata, &outdatalenu, buf + 1, buflen - 1);
case 's': /* plain base64(Sixty-four) from TXT */
case 'S':
if (buflen < 2)
return 0;
return b64->decode(outdata, &outdatalenu, buf + 1, buflen - 1);
case 'u': /* plain base64u (Underscore) from TXT */
case 'U':
if (buflen < 2)
return 0;
return b64u->decode(outdata, &outdatalenu, buf + 1, buflen - 1);
case 'v': /* plain base128 from TXT */
case 'V':
if (buflen < 2)
return 0;
return b128->decode(outdata, &outdatalenu, buf + 1, buflen - 1);
case 'r': /* Raw binary from TXT */
case 'R':
/* buflen>=1 already checked */
buflen--;
buflen = MIN(buflen, outdatalen);
memcpy(outdata, buf + 1, buflen);
return buflen;
default:
warnx("Received unsupported encoding");
return 0;
}
/* notreached */
return 0;
}
static int
read_dns_withq(uint8_t *buf, size_t buflen, struct query *q)
/* Returns -1 on receive error or decode error, including DNS error replies.
Returns 0 on replies that could be correct but are useless, and are not
DNS error replies.
Returns >0 on correct replies; value is #valid bytes in *buf.
*/
{
struct sockaddr_storage from;
uint8_t data[64*1024];
socklen_t addrlen;
int r;
addrlen = sizeof(from);
if ((r = recvfrom(this.dns_fd, data, sizeof(data), 0,
(struct sockaddr*)&from, &addrlen)) < 0) {
warn("recvfrom");
return -1;
}
if (this.conn == CONN_DNS_NULL) {
int rv;
if (r <= 0)
/* useless packet */
return 0;
rv = dns_decode((char *)buf, buflen, q, QR_ANSWER, (char *)data, r);
if (rv <= 0)
return rv;
if (q->type == T_CNAME || q->type == T_TXT ||
q->type == T_PTR || q->type == T_A6 || q->type == T_DNAME)
/* CNAME can also be returned from an A question */
{
/*
* buf is a hostname or txt stream that we still need to
* decode to binary
*
* also update rv with the number of valid bytes
*
* data is unused here, and will certainly hold the smaller binary
*/
rv = dns_namedec(data, sizeof(data), buf, rv);
rv = MIN(rv, buflen);
if (rv > 0)
memcpy(buf, data, rv);
} else if (q->type == T_MX || q->type == T_SRV) {
/* buf is like "Hname.com\0Hanother.com\0\0" */
int buftotal = rv; /* idx of last \0 */
int bufoffset = 0;
int dataoffset = 0;
int thispartlen, dataspace, datanew;
while (1) {
thispartlen = strlen((char *)buf);
thispartlen = MIN(thispartlen, buftotal-bufoffset);
dataspace = sizeof(data) - dataoffset;
if (thispartlen <= 0 || dataspace <= 0)
break;
datanew = dns_namedec(data + dataoffset, dataspace,
buf + bufoffset, thispartlen);
if (datanew <= 0)
break;
bufoffset += thispartlen + 1;
dataoffset += datanew;
}
rv = dataoffset;
rv = MIN(rv, buflen);
if (rv > 0)
memcpy(buf, data, rv);
}
DEBUG(2, "RX: id %5d name[0]='%c'", q->id, q->name[0]);
return rv;
} else { /* CONN_RAW_UDP */
size_t datalen;
uint8_t buf[64*1024];
/* minimum length */
if (r < RAW_HDR_LEN)
return 0;
/* should start with header */
if (memcmp(data, raw_header, RAW_HDR_IDENT_LEN))
return 0;
/* should be my user id */
if (RAW_HDR_GET_USR(data) != this.userid)
return 0;
if (RAW_HDR_GET_CMD(data) == RAW_HDR_CMD_DATA ||
RAW_HDR_GET_CMD(data) == RAW_HDR_CMD_PING)
this.lastdownstreamtime = time(NULL);
/* should be data packet */
if (RAW_HDR_GET_CMD(data) != RAW_HDR_CMD_DATA)
return 0;
r -= RAW_HDR_LEN;
datalen = sizeof(buf);
if (uncompress(buf, &datalen, data + RAW_HDR_LEN, r) == Z_OK) {
write_tun(this.tun_fd, buf, datalen);
}
/* all done */
return 0;
}
}
int
handshake_waitdns(char *buf, size_t buflen, char cmd, int timeout)
/* Wait for DNS reply fitting to our latest query and returns it.
Returns length of reply = #bytes used in buf.
Returns 0 if fitting reply happens to be useless.
Returns -2 on (at least) DNS error that fits to our latest query,
error message already printed.
Returns -3 on timeout (given in seconds).
Returns -1 on other errors.
Timeout is restarted when "wrong" (previous/delayed) replies are received,
so effective timeout may be longer than specified.
*/
{
struct query q;
int r, rv;
fd_set fds;
struct timeval tv;
char qcmd;
cmd = toupper(cmd);
while (1) {
tv.tv_sec = timeout;
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(this.dns_fd, &fds);
r = select(this.dns_fd + 1, &fds, NULL, NULL, &tv);
if (r < 0)
return -1; /* select error */
if (r == 0)
return -3; /* select timeout */
q.id = -1;
q.name[0] = '\0';
rv = read_dns_withq((uint8_t *)buf, buflen, &q);
qcmd = toupper(q.name[0]);
if (q.id != this.chunkid || qcmd != cmd) {
DEBUG(1, "Ignoring unfitting reply id %d starting with '%c'", q.id, q.name[0]);
continue;
}
/* if still here: reply matches our latest query */
/* Non-recursive DNS servers (such as [a-m].root-servers.net)
return no answer, but only additional and authority records.
Can't explicitly test for that here, just assume that
NOERROR is such situation. Only trigger on the very first
requests (Y or V, depending if -T given).
*/
if (rv < 0 && q.rcode == NOERROR &&
(q.name[0] == 'Y' || q.name[0] == 'y' ||
q.name[0] == 'V' || q.name[0] == 'v')) {
fprintf(stderr, "Got empty reply. This nameserver may not be resolving recursively, use another.\n");
fprintf(stderr, "Try \"iodine [options] %s ns.%s\" first, it might just work.\n",
this.topdomain, this.topdomain);
return -2;
}
/* If we get an immediate SERVFAIL on the handshake query
we're waiting for, wait a while before sending the next.
SERVFAIL reliably happens during fragsize autoprobe, but
mostly long after we've moved along to some other queries.
However, some DNS relays, once they throw a SERVFAIL, will
for several seconds apply it immediately to _any_ new query
for the same this.topdomain. When this happens, waiting a while
is the only option that works.
*/
if (rv < 0 && q.rcode == SERVFAIL)
sleep(1);
if (rv < 0) {
write_dns_error(&q, 1);
return -2;
}
/* rv either 0 or >0, return it as is. */
return rv;
}
/* not reached */
return -1;
}
int
parse_data(uint8_t *data, size_t len, fragment *f, int *immediate, int *ping)
{
size_t headerlen = DOWNSTREAM_HDR;
int error;
f->seqID = data[0];
/* Flags */
f->end = data[2] & 1;
f->start = (data[2] >> 1) & 1;
f->compressed = (data[2] >> 2) & 1;
f->ack_other = (data[2] >> 3) & 1 ? data[1] : -1;
if (ping) *ping = (data[2] >> 4) & 1;
error = (data[2] >> 6) & 1;
if (immediate)
*immediate = (data[2] >> 5) & 1;
if (ping && *ping) { /* Handle ping stuff */
static unsigned dn_start_seq, up_start_seq, dn_wsize, up_wsize;
headerlen = DOWNSTREAM_PING_HDR;
if (len < headerlen) return -1; /* invalid packet - continue */
/* Parse data/ping header */
dn_wsize = data[3];
up_wsize = data[4];
dn_start_seq = data[5];
up_start_seq = data[6];
DEBUG(3, "PING pkt data=%" L "u WS: up=%u, dn=%u; Start: up=%u, dn=%u",
len - headerlen, up_wsize, dn_wsize, up_start_seq, dn_start_seq);
}
f->len = len - headerlen;
if (f->len > 0)
memcpy(f->data, data + headerlen, MIN(f->len, this.inbuf->maxfraglen));
return error;
}
static ssize_t
tunnel_stdin()
{
size_t datalen;
uint8_t out[64*1024];
uint8_t in[64*1024];
uint8_t *data;
ssize_t readlen;
readlen = read(STDIN_FILENO, in, sizeof(in));
DEBUG(4, " IN: %" L "d bytes on stdin, to be compressed: %d", readlen, this.compression_up);
if (readlen == 0) {
DEBUG(2, "EOF on stdin!");
return -1;
} else if (readlen < 0) {
warnx("Error %d reading from stdin: %s", errno, strerror(errno));
return -1;
}
if (this.conn != CONN_DNS_NULL || this.compression_up) {
datalen = sizeof(out);
compress2(out, &datalen, in, readlen, 9);
data = out;
} else {
datalen = readlen;
data = in;
}
if (this.conn == CONN_DNS_NULL) {
/* Check if outgoing buffer can hold data */
if (window_buffer_available(this.outbuf) < (datalen / MAX_FRAGSIZE) + 1) {
DEBUG(1, " Outgoing buffer full (%" L "u/%" L "u), not adding data!",
this.outbuf->numitems, this.outbuf->length);
return -1;
}
window_add_outgoing_data(this.outbuf, data, datalen, this.compression_up);
/* Don't send anything here to respect min. send interval */
} else {
send_raw_data(data, datalen);
}
return datalen;
}
static int
tunnel_tun()
{
size_t datalen;
uint8_t out[64*1024];
uint8_t in[64*1024];
uint8_t *data;
ssize_t read;
if ((read = read_tun(this.tun_fd, in, sizeof(in))) <= 0)
return -1;
DEBUG(2, " IN: %" L "u bytes on tunnel, to be compressed: %d", read, this.compression_up);
if (this.conn != CONN_DNS_NULL || this.compression_up) {
datalen = sizeof(out);
compress2(out, &datalen, in, read, 9);
data = out;
} else {
datalen = read;
data = in;
}
if (this.conn == CONN_DNS_NULL) {
/* Check if outgoing buffer can hold data */
if ((this.windowsize_up == 0 && this.outbuf->numitems != 0) ||
window_buffer_available(this.outbuf) < (read / MAX_FRAGSIZE) + 1) {
DEBUG(1, " Outgoing buffer full (%" L "u/%" L "u), not adding data!",
this.outbuf->numitems, this.outbuf->length);
return -1;
}
window_add_outgoing_data(this.outbuf, data, datalen, this.compression_up);
/* Don't send anything here to respect min. send interval */
} else {
send_raw_data(data, datalen);
}
return read;
}
static int
tunnel_dns()
{
struct query q;
size_t datalen, buflen;
uint8_t buf[64*1024], cbuf[64*1024], *data, compressed;
fragment f;
int read, ping, immediate, error, pkt = 1;
memset(&q, 0, sizeof(q));
memset(buf, 0, sizeof(buf));
memset(cbuf, 0, sizeof(cbuf));
read = read_dns_withq(cbuf, sizeof(cbuf), &q);
if (this.conn != CONN_DNS_NULL)
return 1; /* everything already done */
/* Don't process anything that isn't data for us; usually error
replies from fragsize probes etc. However a sequence of those,
mostly 1 sec apart, will continuously break the >=2-second select
timeout, which means we won't send a proper ping for a while.
So make select a bit faster, <1sec. */
if (q.name[0] != 'P' && q.name[0] != 'p' &&
q.name[0] != this.userid_char && q.name[0] != this.userid_char2) {
this.send_ping_soon = 700;
got_response(q.id, 0, 0);
return -1; /* nothing done */
}
if (read < DOWNSTREAM_HDR) {
/* Maybe SERVFAIL etc. Send ping to get things back in order,
but wait a bit to prevent fast ping-pong loops.
Only change options if user hasn't specified server timeout */
if (read < 0)
write_dns_error(&q, 0);
if (q.rcode == SERVFAIL && read < 0) {
this.num_servfail++;
if (this.lazymode) {
if (this.send_query_recvcnt < 500 && this.num_servfail < 4) {
fprintf(stderr, "Hmm, that's %" L "d SERVFAILs. Your data should still go through...\n", this.num_servfail);
} else if (this.send_query_recvcnt < 500 && this.num_servfail >= 10 &&
this.autodetect_server_timeout && this.max_timeout_ms >= 500 && this.num_servfail % 5 == 0) {
this.max_timeout_ms -= 200;
double target_timeout = (float) this.max_timeout_ms / 1000.0;
fprintf(stderr, "Too many SERVFAILs (%" L "d), reducing timeout to"
" %.1f secs. (use -I%.1f next time on this network)\n",
this.num_servfail, target_timeout, target_timeout);
/* Reset query counts this.stats */
this.send_query_sendcnt = 0;
this.send_query_recvcnt = 0;
update_server_timeout(1);
} else if (this.send_query_recvcnt < 500 && this.num_servfail >= 40 &&
this.autodetect_server_timeout && this.max_timeout_ms < 500) {
/* last-ditch attempt to fix SERVFAILs - disable lazy mode */
immediate_mode_defaults();
fprintf(stderr, "Attempting to disable lazy mode due to excessive SERVFAILs\n");
handshake_switch_options(0, this.compression_down, this.downenc);
}
}
}
this.send_ping_soon = 900;
/* Mark query as received */
got_response(q.id, 0, 1);
return -1; /* nothing done */
}
this.send_query_recvcnt++; /* unlikely we will ever overflow (2^64 queries is a LOT) */
if (read == 5 && !strncmp("BADIP", (char *)cbuf, 5)) {
this.num_badip++;
if (this.num_badip % 5 == 1) {
fprintf(stderr, "BADIP (%" L "d): Server rejected sender IP address (maybe iodined -c will help), or server "
"kicked us due to timeout. Will exit if no downstream data is received in 60 seconds.\n", this.num_badip);
}
return -1; /* nothing done */
}
/* Okay, we have a recent downstream packet */
this.lastdownstreamtime = time(NULL);
this.num_recv++;
/* Decode the downstream data header and fragment-ify ready for processing */
f.data = buf;
error = parse_data(cbuf, read, &f, &immediate, &ping);
/* Mark query as received */
got_response(q.id, immediate, 0);
if ((this.debug >= 3 && ping) || (this.debug >= 2 && !ping))
fprintf(stderr, " RX %s; frag ID %3u, ACK %3d, compression %d, datalen %" L "u, s%d e%d\n",
ping ? "PING" : "DATA", f.seqID, f.ack_other, f.compressed, f.len, f.start, f.end);
if (f.ack_other >= 0) {
window_ack(this.outbuf, f.ack_other);
window_tick(this.outbuf);
}
/* respond to TCP forwarding errors by shutting down */
if (error && this.use_remote_forward) {
f.data[f.len] = 0;
warnx("server: TCP forwarding error: %s", f.data);
this.running = 0;
return -1;
}
/* In lazy mode, we shouldn't get immediate replies to our most-recent
query, only during heavy data transfer. Since this means the server
doesn't have any packets to send, send one relatively fast (but not
too fast, to avoid runaway ping-pong loops..) */
/* Don't send anything too soon; no data waiting from server */
if (f.len == 0) {
if (!ping)
DEBUG(1, "[WARNING] Received downstream data fragment with 0 length and NOT a ping!");
if (!this.lazymode)
this.send_ping_soon = 100;
else
this.send_ping_soon = 700;
return -1;
}
/* Get next ACK if nothing already pending: if we get a new ack
* then we must send it immediately. */
if (this.next_downstream_ack >= 0) {
/* If this happens something is wrong (or last frag was a re-send)
* May result in ACKs being delayed. */
DEBUG(1, "this.next_downstream_ack NOT -1! (%d), %u resends, %u oos", this.next_downstream_ack, this.outbuf->resends, this.outbuf->oos);
}
/* Downstream data traffic + ack data fragment */
this.next_downstream_ack = f.seqID;
window_process_incoming_fragment(this.inbuf, &f);
this.num_frags_recv++;
/* Continue reassembling packets until not possible to do so.
* This prevents a buildup of fully available packets (with one or more fragments each)
* in the incoming window buffer. */
while (pkt == 1) {
datalen = sizeof(cbuf);
pkt = window_reassemble_data(this.inbuf, cbuf, &datalen, &compressed);
if (datalen > 0) {
if (compressed) {
buflen = sizeof(buf);
if ((ping = uncompress(buf, &buflen, cbuf, datalen)) != Z_OK) {
DEBUG(1, "Uncompress failed (%d) for data len %" L "u: reassembled data corrupted or incomplete!", ping, datalen);
datalen = 0;
} else {
datalen = buflen;
}
data = buf;
} else {
data = cbuf;
}
if (datalen) {
if (this.use_remote_forward) {
if (write(STDOUT_FILENO, data, datalen) != datalen) {
warn("write_stdout != datalen");
}
} else {
write_tun(this.tun_fd, data, datalen);
}
}
}
}
return read;
}
int
client_tunnel()
{
struct timeval tv, nextresend, tmp, now, now2;
fd_set fds;
int rv;
int i, use_min_send;
int sending, total, maxfd;
time_t last_stats;
size_t sent_since_report, recv_since_report;
this.connected = 1;
/* start counting now */
rv = 0;
this.lastdownstreamtime = time(NULL);
last_stats = time(NULL);
/* reset connection statistics */
this.num_badip = 0;
this.num_servfail = 0;
this.num_timeouts = 0;
this.send_query_recvcnt = 0;
this.send_query_sendcnt = 0;
this.num_sent = 0;
this.num_recv = 0;
this.num_frags_sent = 0;
this.num_frags_recv = 0;
this.num_pings = 0;
sent_since_report = 0;
recv_since_report = 0;
use_min_send = 0;
window_debug = this.debug;
while (this.running) {
if (!use_min_send)
tv = ms_to_timeval(this.max_timeout_ms);
/* TODO: detect DNS servers which drop frequent requests
* TODO: adjust number of pending queries based on current data rate */
if (this.conn == CONN_DNS_NULL && !use_min_send) {
/* Send a single query per loop */
sending = window_sending(this.outbuf, &nextresend);
total = sending;
check_pending_queries();
if (this.num_pending < this.windowsize_down && this.lazymode)
total = MAX(total, this.windowsize_down - this.num_pending);
else if (this.num_pending < 1 && !this.lazymode)
total = MAX(total, 1);
QTRACK_DEBUG(2, "sending=%d, total=%d, next_ack=%d, outbuf.n=%" L "u",
sending, total, this.next_downstream_ack, this.outbuf->numitems);
/* Upstream traffic - this is where all ping/data queries are sent */
if (sending > 0 || total > 0 || this.next_downstream_ack >= 0) {
if (sending > 0) {
/* More to send - next fragment */
send_next_frag();
} else {
/* Send ping if we didn't send anything yet */
send_ping(0, this.next_downstream_ack, (this.num_pings > 20 &&
this.num_pings % 50 == 0), 0);
this.next_downstream_ack = -1;
}
sending--;
total--;
QTRACK_DEBUG(3, "Sent a query to fill server lazy buffer to %" L "u, will send another %d",
this.lazymode ? this.windowsize_down : 1, total);
if (sending > 0 || (total > 0 && this.lazymode)) {
/* If sending any data fragments, or server has too few
* pending queries, send another one after min. interval */
/* TODO: enforce min send interval even if we get new data */
tv = ms_to_timeval(this.min_send_interval_ms);
if (this.min_send_interval_ms)
use_min_send = 1;
tv.tv_usec += 1;
} else if (total > 0 && !this.lazymode) {
/* In immediate mode, use normal interval when needing
* to send non-data queries to probe server. */
tv = ms_to_timeval(this.send_interval_ms);
}
if (sending == 0 && !use_min_send) {
/* check next resend time when not sending any data */
if (timercmp(&nextresend, &tv, <))
tv = nextresend;
}
this.send_ping_soon = 0;
}
}
if (this.stats) {
if (difftime(time(NULL), last_stats) >= this.stats) {
/* print useful statistics report */
fprintf(stderr, "\n============ iodine connection statistics (user %1d) ============\n", this.userid);
fprintf(stderr, " Queries sent: %8" L "u" ", answered: %8" L "u" ", SERVFAILs: %4" L "u\n",
this.num_sent, this.num_recv, this.num_servfail);
fprintf(stderr, " last %3d secs: %7" L "u" " (%4" L "u/s), replies: %7" L "u" " (%4" L "u/s)\n",
this.stats, this.num_sent - sent_since_report, (this.num_sent - sent_since_report) / this.stats,
this.num_recv - recv_since_report, (this.num_recv - recv_since_report) / this.stats);
fprintf(stderr, " num IP rejected: %4" L "u, untracked: %4" L "u, lazy mode: %1d\n",
this.num_badip, this.num_untracked, this.lazymode);
fprintf(stderr, " Min send: %5" L "d ms, Avg RTT: %5" L "d ms Timeout server: %4" L "d ms\n",
this.min_send_interval_ms, this.rtt_total_ms / this.num_immediate, this.server_timeout_ms);
fprintf(stderr, " Queries immediate: %5" L "u, timed out: %4" L "u target: %4" L "d ms\n",
this.num_immediate, this.num_timeouts, this.max_timeout_ms);
if (this.conn == CONN_DNS_NULL) {
fprintf(stderr, " Frags resent: %4u, OOS: %4u down frag: %4" L "d ms\n",
this.outbuf->resends, this.inbuf->oos, this.downstream_timeout_ms);
fprintf(stderr, " TX fragments: %8" L "u" ", RX: %8" L "u" ", pings: %8" L "u" "\n",
this.num_frags_sent, this.num_frags_recv, this.num_pings);
}
fprintf(stderr, " Pending frags: %4" L "u\n", this.outbuf->numitems);
/* update since-last-report this.stats */
sent_since_report = this.num_sent;
recv_since_report = this.num_recv;
last_stats = time(NULL);
}
}
if (this.send_ping_soon && !use_min_send) {
tv.tv_sec = 0;
tv.tv_usec = this.send_ping_soon * 1000;
this.send_ping_soon = 0;
}
FD_ZERO(&fds);
maxfd = 0;
if (this.conn != CONN_DNS_NULL || 0 == this.windowsize_up || window_buffer_available(this.outbuf) > 1) {
/* Fill up outgoing buffer with available data if it has enough space
* The windowing protocol manages data retransmits, timeouts etc. */
if (this.use_remote_forward) {
FD_SET(STDIN_FILENO, &fds);
maxfd = MAX(STDIN_FILENO, maxfd);
} else {
FD_SET(this.tun_fd, &fds);
maxfd = MAX(this.tun_fd, maxfd);
}
}
FD_SET(this.dns_fd, &fds);
maxfd = MAX(this.dns_fd, maxfd);
DEBUG(4, "Waiting %ld ms before sending more... (min_send %d)", timeval_to_ms(&tv), use_min_send);
if (use_min_send) {
gettimeofday(&now, NULL);
}
i = select(maxfd + 1, &fds, NULL, NULL, &tv);
if (use_min_send && i > 0) {
/* enforce min_send_interval if we get interrupted by new tun data */
gettimeofday(&now2, NULL);
timersub(&now2, &now, &tmp);
timersub(&tv, &tmp, &now);
tv = now;
} else {
use_min_send = 0;
}
if (difftime(time(NULL), this.lastdownstreamtime) > 60) {
fprintf(stderr, "No downstream data received in 60 seconds, shutting down.\n");
this.running = 0;
}
if (this.running == 0)
break;
if (i < 0)
err(1, "select < 0");
if (i == 0) {
/* timed out - no new packets recv'd */
} else {
if (!this.use_remote_forward && FD_ISSET(this.tun_fd, &fds)) {
if (tunnel_tun() <= 0)
continue;
/* Returns -1 on error OR when quickly
dropping data in case of DNS congestion;
we need to _not_ do tunnel_dns() then.
If chunk sent, sets this.send_ping_soon=0. */
}
if (this.use_remote_forward && FD_ISSET(STDIN_FILENO, &fds)) {
if (tunnel_stdin() <= 0) {
fprintf(stderr, "server: closing remote TCP forward connection\n");
/* send ping to disconnect, don't care if it comes back */
send_ping(0, 0, 0, 1);
this.running = 0;
break;
}
}
if (FD_ISSET(this.dns_fd, &fds)) {
tunnel_dns();
}
}
if (this.running == 0)
break;
}
return rv;
}
static void
send_upenctest(char *s)
/* NOTE: String may be at most 63-4=59 chars to fit in 1 dns chunk. */
{
char buf[512] = "zCMC";
size_t buf_space = 3;
uint32_t cmc = rand();
b32->encode((uint8_t *)buf + 1, &buf_space, (uint8_t *) &cmc, 4);
/* Append test string without changing it */
strncat(buf, ".", 512 - strlen(buf));
strncat(buf, s, 512 - strlen(buf));
strncat(buf, ".", 512 - strlen(buf));
strncat(buf, this.topdomain, 512 - strlen(buf));
send_query((uint8_t *)buf);
}
static void
send_downenctest(char downenc, int variant)
{
char buf[512] = "yTaCMC.";
size_t buf_space = 4;
buf[1] = tolower(downenc);
buf[2] = b32_5to8(variant);
/* add 3 bytes base32 CMC (random) */
uint32_t cmc = rand();
b32->encode((uint8_t *)buf + 3, &buf_space, (uint8_t *) &cmc, 2);
strncat(buf, ".", 512 - strlen(buf));
strncat(buf, this.topdomain, 512 - strlen(buf));
send_query((uint8_t *)buf);
}
static void
send_version(uint32_t version)
{
uint8_t data[8], buf[512];
*(uint32_t *) data = htonl(version);
*(uint32_t *) (data + 4) = (uint32_t) rand(); /* CMC */
buf[0] = 'v';
build_hostname(buf, sizeof(buf), data, sizeof(data),
this.topdomain, b32, this.hostname_maxlen, 1);
send_query(buf);
}
static void
send_login(char *login, int len)
/* Send DNS login packet. See doc/proto_xxxxxxxx.txt for details */
{
uint8_t flags = 0, data[100];
int length = 17, addrlen = 0;
uint16_t port;
if (len != 16)
DEBUG(1, "Login calculated incorrect length hash! len=%d", len);
memcpy(data + 1, login, 16);
/* if remote forward address is specified and not currently connecting */
if (this.remote_forward_connected != 2 &&
this.remote_forward_addr.ss_family != AF_UNSPEC) {
struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) &this.remote_forward_addr;
struct sockaddr_in *s = (struct sockaddr_in *) &this.remote_forward_addr;
port = (this.remote_forward_addr.ss_family == AF_INET ? s->sin_port : s6->sin6_port);
*(uint16_t *) (data + length) = port;
flags |= 1;
length += 2;
/* set remote IP to be non-localhost if this.remote_forward_addr set */
if (this.remote_forward_addr.ss_family == AF_INET && s->sin_addr.s_addr != INADDR_LOOPBACK) {
if (this.remote_forward_addr.ss_family == AF_INET6) { /* IPv6 address */
addrlen = sizeof(s6);
flags |= 4;
memcpy(data + length, &s6->sin6_addr, addrlen);
} else { /* IPv4 address */
flags |= 2;
addrlen = sizeof(s);
memcpy(data + length, &s->sin_addr, addrlen);
}
length += addrlen;
}
DEBUG(2, "Sending TCP forward login request: port %hu, length %d, addrlen %d",
port, length, addrlen);
} else if (this.remote_forward_connected == 2) {
/* remote TCP forward connection in progress */
DEBUG(2, "Sending TCP forward login/poll request to check connection status.");
flags |= (1 << 4);
}
data[0] = flags;
DEBUG(6, "Sending login request: length=%d, flags=0x%02x, hash=0x%016llx%016llx",
length, flags, *(unsigned long long *) (data + 1), *(unsigned long long *) (data + 9));
send_packet('l', data, length);
}
static void
send_fragsize_probe(uint16_t fragsize)
{
uint8_t data[256];
/* Probe downstream fragsize packet */
/* build a large query domain which is random and maximum size,
* will also take up maximum space in the return packet */
memset(data, MAX(1, this.rand_seed & 0xff), sizeof(data));
*(uint16_t *) (data) = htons(fragsize);
this.rand_seed++;
send_packet('r', data, sizeof(data));
}
static void
send_set_downstream_fragsize(uint16_t fragsize)
{
uint8_t data[2];
*(uint16_t *) data = htons(fragsize);
send_packet('n', data, sizeof(data));
}
static void
send_ip_request()
{
send_packet('i', NULL, 0);
}
static void
send_raw_udp_login(int seed)
{
char buf[16];
login_calculate(buf, sizeof(buf), this.password, seed + 1);
send_raw((uint8_t *) buf, sizeof(buf), RAW_HDR_CMD_LOGIN);
}
static void
send_codec_switch(uint8_t bits)
{
send_packet('s', &bits, 1);
}
static void
send_server_options(int lazy, int compression, char denc)
{
uint8_t optflags = 0;
if (denc == 'T') /* Base32 */
optflags |= 1 << 6;
else if (denc == 'S') /* Base64 */
optflags |= 1 << 5;
else if (denc == 'U') /* Base64u */
optflags |= 1 << 4;
else if (denc == 'V') /* Base128 */
optflags |= 1 << 3;
else if (denc == 'R') /* Raw */
optflags |= 1 << 2;
optflags |= (compression & 1) << 1;
optflags |= lazy & 1;
send_packet('o', &optflags, 1);
}
static int
handshake_version(int *seed)
{
char hex[] = "0123456789abcdef";
char hex2[] = "0123456789ABCDEF";
char in[4096];
uint32_t payload;
int i;
int read;
for (i = 0; this.running && i < 5; i++) {
send_version(PROTOCOL_VERSION);
read = handshake_waitdns(in, sizeof(in), 'V', i+1);
if (read >= 9) {
payload = ntohl(*(uint32_t *) (in + 4));
if (strncmp("VACK", (char *)in, 4) == 0) {
/* Payload is login challenge */
*seed = payload;
this.userid = in[8];
this.userid_char = hex[this.userid & 15];
this.userid_char2 = hex2[this.userid & 15];
DEBUG(2, "Login challenge: 0x%08x", *seed);
fprintf(stderr, "Version ok, both using protocol v 0x%08x. You are user #%d\n",
PROTOCOL_VERSION, this.userid);
return 0;
} else if (strncmp("VNAK", (char *)in, 4) == 0) {
/* Payload is server version */
warnx("You use protocol v 0x%08x, server uses v 0x%08x. Giving up",
PROTOCOL_VERSION, payload);
return 1;
} else if (strncmp("VFUL", (char *)in, 4) == 0) {
/* Payload is max number of users on server */
warnx("Server full, all %d slots are taken. Try again later", payload);
return 1;
}
} else if (read > 0)
warnx("did not receive proper login challenge");
fprintf(stderr, "Retrying version check...\n");
}
warnx("couldn't connect to server (maybe other -T options will work)");
return 1;
}
static int
handshake_login(int seed)
{
char in[4096], login[16], server[65], client[65], flag;
int mtu, netmask, read, numwaiting = 0;
login_calculate(login, 16, this.password, seed);
for (int i = 0; this.running && i < 5; i++) {
send_login(login, 16);
read = handshake_waitdns(in, sizeof(in), 'L', i + 1);
in[MIN(read, sizeof(in))] = 0; /* Null terminate */
if (read > 0) {
if (strncmp("LNAK", in, 4) == 0) {
fprintf(stderr, "Bad password\n");
return 1;
/* not reached */
}
flag = toupper(in[0]);
switch (flag) {
case 'I':
if (sscanf(in, "%c-%64[^-]-%64[^-]-%d-%d",
&flag, server, client, &mtu, &netmask) == 5) {
server[64] = 0;
client[64] = 0;
if (tun_setip(client, server, netmask) == 0 &&
tun_setmtu(mtu) == 0) {
fprintf(stderr, "Server tunnel IP is %s\n", server);
return 0;
} else {
errx(4, "Failed to set IP and MTU");
}
} else {
goto bad_handshake;
}
break;
case 'C':
if (!this.use_remote_forward) {
goto bad_handshake;
}
this.remote_forward_connected = 1;
fprintf(stderr, " done.");
return 0;
case 'W':
if (!this.use_remote_forward || this.remote_forward_connected == 1) {
goto bad_handshake;
}
this.remote_forward_connected = 2;
if (numwaiting == 0)
fprintf(stderr, "server: Opening Remote TCP forward.\n");
else
fprintf(stderr, "%.*s", numwaiting, "...............");
numwaiting ++;
/* wait a while before re-polling server, max 5 tries (14 seconds) */
if (numwaiting > 1)
sleep(numwaiting);
continue;
case 'E':
if (!this.use_remote_forward)
goto bad_handshake;
char errormsg[100];
strncpy(errormsg, in + 1, MIN(read, sizeof(errormsg)));
errormsg[99] = 0;
fprintf(stderr, "server: Remote TCP forward connection failed: %s\n", errormsg);
return 1;
default:
/* undefined flag */
bad_handshake:
fprintf(stderr, "Received bad handshake: %.*s\n", read, in);
break;
}
}
fprintf(stderr, "Retrying login...\n");
}
if (numwaiting != 0)
warnx("Remote TCP forward connection timed out after 5 tries.");
else
warnx("couldn't login to server");
return 1;
}
static int
handshake_raw_udp(int seed)
{
struct timeval tv;
char in[4096];
fd_set fds;
int i;
int r;
int len;
int got_addr;
memset(&this.raw_serv, 0, sizeof(this.raw_serv));
got_addr = 0;
fprintf(stderr, "Testing raw UDP data to the server (skip with -r)");
for (i=0; this.running && i<3 ;i++) {
send_ip_request();
len = handshake_waitdns(in, sizeof(in), 'I', i+1);
if (len == 5 && in[0] == 'I') {
/* Received IPv4 address */
struct sockaddr_in *raw4_serv = (struct sockaddr_in *) &this.raw_serv;
raw4_serv->sin_family = AF_INET;
memcpy(&raw4_serv->sin_addr, &in[1], sizeof(struct in_addr));
raw4_serv->sin_port = htons(53);
this.raw_serv_len = sizeof(struct sockaddr_in);
got_addr = 1;
break;
}
if (len == 17 && in[0] == 'I') {
/* Received IPv6 address */
struct sockaddr_in6 *raw6_serv = (struct sockaddr_in6 *) &this.raw_serv;
raw6_serv->sin6_family = AF_INET6;
memcpy(&raw6_serv->sin6_addr, &in[1], sizeof(struct in6_addr));
raw6_serv->sin6_port = htons(53);
this.raw_serv_len = sizeof(struct sockaddr_in6);
got_addr = 1;
break;
}
fprintf(stderr, ".");
fflush(stderr);
}
fprintf(stderr, "\n");
if (!this.running)
return 0;
if (!got_addr) {
fprintf(stderr, "Failed to get raw server IP, will use DNS mode.\n");
return 0;
}
fprintf(stderr, "Server is at %s, trying raw login: ", format_addr(&this.raw_serv, this.raw_serv_len));
fflush(stderr);
/* do login against port 53 on remote server
* based on the old seed. If reply received,
* switch to raw udp mode */
for (i=0; this.running && i<4 ;i++) {
tv.tv_sec = i + 1;
tv.tv_usec = 0;
send_raw_udp_login(seed);
FD_ZERO(&fds);
FD_SET(this.dns_fd, &fds);
r = select(this.dns_fd + 1, &fds, NULL, NULL, &tv);
if(r > 0) {
/* recv() needed for windows, dont change to read() */
len = recv(this.dns_fd, in, sizeof(in), 0);
if (len >= (16 + RAW_HDR_LEN)) {
char hash[16];
login_calculate(hash, 16, this.password, seed - 1);
if (memcmp(in, raw_header, RAW_HDR_IDENT_LEN) == 0
&& RAW_HDR_GET_CMD(in) == RAW_HDR_CMD_LOGIN
&& memcmp(&in[RAW_HDR_LEN], hash, sizeof(hash)) == 0) {
fprintf(stderr, "OK\n");
return 1;
}
}
}
fprintf(stderr, ".");
fflush(stderr);
}
fprintf(stderr, "failed\n");
return 0;
}
static int
handshake_upenctest(char *s)
/* NOTE: *s may be max 59 chars; must start with "aA" for case-swap check
Returns:
-1: case swap, no need for any further test: error printed; or Ctrl-C
0: not identical or error or timeout
1: identical string returned
*/
{
char in[4096];
unsigned char *uin = (unsigned char *) in;
unsigned char *us = (unsigned char *) s;
int i, read, slen;
slen = strlen(s);
for (i=0; this.running && i<3 ;i++) {
send_upenctest(s);
read = handshake_waitdns(in, sizeof(in), 'Z', i+1);
if (read == -2)
return 0; /* hard error */
if (read > 0 && read < slen + 4)
return 0; /* reply too short (chars dropped) */
if (read > 0) {
int k;
/* quick check if case swapped, to give informative error msg */
if (in[4] == 'A') {
fprintf(stderr, "DNS queries get changed to uppercase, keeping upstream codec Base32\n");
return -1;
}
if (in[5] == 'a') {
fprintf(stderr, "DNS queries get changed to lowercase, keeping upstream codec Base32\n");
return -1;
}
for (k = 0; k < slen; k++) {
if (in[k+4] != s[k]) {
/* Definitely not reliable */
if (in[k+4] >= ' ' && in[k+4] <= '~' &&
s[k] >= ' ' && s[k] <= '~') {
fprintf(stderr, "DNS query char '%c' gets changed into '%c'\n",
s[k], in[k+4]);
} else {
fprintf(stderr, "DNS query char 0x%02X gets changed into 0x%02X\n",
(unsigned int) us[k],
(unsigned int) uin[k+4]);
}
return 0;
}
}
/* if still here, then all okay */
return 1;
}
fprintf(stderr, "Retrying upstream codec test...\n");
}
if (!this.running)
return -1;
/* timeout */
return 0;
}
static int
handshake_upenc_autodetect()
/* Returns:
0: keep Base32
1: Base64 is okay
2: Base64u is okay
3: Base128 is okay
*/
{
/* Note: max 59 chars, must start with "aA".
pat64: If 0129 work, assume 3-8 are okay too.
RFC1035 par 2.3.1 states that [A-Z0-9-] allowed, but only
[A-Z] as first, and [A-Z0-9] as last char _per label_.
Test by having '-' as last char.
*/
char *pat64="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ+0129-";
char *pat64u="<KEY>";
char *pat128a="aA-Aaahhh-Drink-mal-ein-J\344germeister-";
char *pat128b="aA-La-fl\373te-na\357ve-fran\347aise-est-retir\351-\340-Cr\350te";
char *pat128c="<KEY>";
char *pat128d="aA0123456789\274\275\276\277"
"\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317";
char *pat128e="aA"
"\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337"
"\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357"
"\360\361\362\363\364\365\366\367\370\371\372\373\374\375";
int res;
/* Try Base128, starting very gently to not draw attention */
while (1) {
res = handshake_upenctest(pat128a);
if (res < 0) {
/* DNS swaps case, msg already printed; or Ctrl-C */
return 0;
} else if (res == 0) {
/* Probably not okay, skip Base128 entirely */
break;
}
res = handshake_upenctest(pat128b);
if (res < 0)
return 0;
else if (res == 0)
break;
/* if this works, we can test the real stuff */
res = handshake_upenctest(pat128c);
if (res < 0)
return 0;
else if (res == 0)
break;
res = handshake_upenctest(pat128d);
if (res < 0)
return 0;
else if (res == 0)
break;
res = handshake_upenctest(pat128e);
if (res < 0)
return 0;
else if (res == 0)
break;
/* if still here, then base128 works completely */
return 3;
}
/* Try Base64 (with plus sign) */
res = handshake_upenctest(pat64);
if (res < 0) {
/* DNS swaps case, msg already printed; or Ctrl-C */
return 0;
} else if (res > 0) {
/* All okay, Base64 msg will be printed later */
return 1;
}
/* Try Base64u (with _u_nderscore) */
res = handshake_upenctest(pat64u);
if (res < 0) {
/* DNS swaps case, msg already printed; or Ctrl-C */
return 0;
} else if (res > 0) {
/* All okay, Base64u msg will be printed later */
return 2;
}
/* if here, then nonthing worked */
fprintf(stderr, "Keeping upstream codec Base32\n");
return 0;
}
static int
handshake_downenctest(char trycodec)
/* Returns:
0: not identical or error or timeout
1: identical string returned
*/
{
char in[4096];
int i;
int read;
char *s = DOWNCODECCHECK1;
int slen = DOWNCODECCHECK1_LEN;
for (i=0; this.running && i<3 ;i++) {
send_downenctest(trycodec, 1);
read = handshake_waitdns(in, sizeof(in), 'Y', i+1);
if (read == -2)
return 0; /* hard error */
if (read > 0 && read != slen)
return 0; /* reply incorrect = unreliable */
if (read > 0) {
int k;
for (k = 0; k < slen; k++) {
if (in[k] != s[k]) {
/* Definitely not reliable */
return 0;
}
}
/* if still here, then all okay */
return 1;
}
fprintf(stderr, "Retrying downstream codec test...\n");
}
/* timeout */
return 0;
}
static char
handshake_downenc_autodetect()
/* Returns codec char (or ' ' if no advanced codec works) */
{
int base64ok = 0;
int base64uok = 0;
int base128ok = 0;
if (this.do_qtype == T_NULL || this.do_qtype == T_PRIVATE) {
/* no other choice than raw */
fprintf(stderr, "No alternative downstream codec available, using default (Raw)\n");
return 'R';
}
fprintf(stderr, "Autodetecting downstream codec (use -O to override)\n");
/* Try Base64 */
if (handshake_downenctest('S'))
base64ok = 1;
else if (this.running && handshake_downenctest('U'))
base64uok = 1;
/* Try Base128 only if 64 gives us some perspective */
if (this.running && (base64ok || base64uok)) {
if (handshake_downenctest('V'))
base128ok = 1;
}
/* If 128 works, then TXT may give us Raw as well */
if (this.running && (base128ok && this.do_qtype == T_TXT)) {
if (handshake_downenctest('R'))
return 'R';
}
if (!this.running)
return ' ';
if (base128ok)
return 'V';
if (base64ok)
return 'S';
if (base64uok)
return 'U';
fprintf(stderr, "No advanced downstream codecs seem to work, using default (Base32)\n");
return ' ';
}
static int
handshake_qtypetest(int timeout)
/* Returns:
0: doesn't work with this timeout
1: works properly
*/
{
char in[4096];
int read;
char *s = DOWNCODECCHECK1;
int slen = DOWNCODECCHECK1_LEN;
int trycodec;
int k;
if (this.do_qtype == T_NULL || this.do_qtype == T_PRIVATE)
trycodec = 'R';
else
trycodec = 'T';
/* We could use 'Z' bouncing here, but 'Y' also tests that 0-255
byte values can be returned, which is needed for NULL/PRIVATE
to work. */
send_downenctest(trycodec, 1);
read = handshake_waitdns(in, sizeof(in), 'Y', timeout);
if (read != slen)
return 0; /* incorrect */
for (k = 0; k < slen; k++) {
if (in[k] != s[k]) {
/* corrupted */
return 0;
}
}
/* if still here, then all okay */
return 1;
}
static int
handshake_qtype_numcvt(int num)
{
switch (num) {
case 0: return T_NULL;
case 1: return T_PRIVATE;
case 2: return T_TXT;
case 3: return T_SRV;
case 4: return T_MX;
case 5: return T_DNAME;
case 6: return T_PTR;
case 7: return T_CNAME;
case 8: return T_A6;
case 9: return T_AAAA;
case 10: return T_A;
}
return T_UNSET;
}
static int
handshake_qtype_autodetect()
/* Returns:
0: okay, this.do_qtype set
1: problem, program exit
*/
{
int highestworking = 100;
int timeout;
int qtypenum;
fprintf(stderr, "Autodetecting DNS query type (use -T to override)");
fflush(stderr);
/* Method: try all "interesting" qtypes with a 1-sec timeout, then try
all "still-interesting" qtypes with a 2-sec timeout, etc.
"Interesting" means: qtypes that (are expected to) have higher
bandwidth than what we know is working already (highestworking).
Note that DNS relays may not immediately resolve the first (NULL)
query in 1 sec, due to long recursive lookups, so we keep trying
to see if things will start working after a while.
*/
for (timeout = 1; this.running && timeout <= 3; timeout++) {
for (qtypenum = 0; this.running && qtypenum < highestworking; qtypenum++) {
this.do_qtype = handshake_qtype_numcvt(qtypenum);
if (this.do_qtype == T_UNSET)
break; /* this round finished */
fprintf(stderr, ".");
fflush(stderr);
if (handshake_qtypetest(timeout)) {
/* okay */
highestworking = qtypenum;
DEBUG(1, " Type %s timeout %d works", client_get_qtype(), timeout);
break;
/* try others with longer timeout */
}
/* else: try next qtype with same timeout */
}
if (highestworking == 0)
/* good, we have NULL; abort immediately */
break;
}
fprintf(stderr, "\n");
if (!this.running) {
warnx("Stopped while autodetecting DNS query type (try setting manually with -T)");
return 1; /* problem */
}
/* finished */
this.do_qtype = handshake_qtype_numcvt(highestworking);
if (this.do_qtype == T_UNSET) {
/* also catches highestworking still 100 */
warnx("No suitable DNS query type found. Are you this.connected to a network?");
warnx("If you expect very long roundtrip delays, use -T explicitly.");
warnx("(Also, connecting to an \"ancient\" version of iodined won't work.)");
return 1; /* problem */
}
/* "using qtype" message printed in handshake function */
return 0; /* okay */
}
static int
handshake_edns0_check()
/* Returns:
0: EDNS0 not supported; or Ctrl-C
1: EDNS0 works
*/
{
char in[4096];
int i;
int read;
char *s = DOWNCODECCHECK1;
int slen = DOWNCODECCHECK1_LEN;
char trycodec;
if (this.do_qtype == T_NULL)
trycodec = 'R';
else
trycodec = 'T';
for (i=0; this.running && i<3 ;i++) {
send_downenctest(trycodec, 1);
read = handshake_waitdns(in, sizeof(in), 'Y', i+1);
if (read == -2)
return 0; /* hard error */
if (read > 0 && read != slen)
return 0; /* reply incorrect = unreliable */
if (read > 0) {
int k;
for (k = 0; k < slen; k++) {
if (in[k] != s[k]) {
/* Definitely not reliable */
return 0;
}
}
/* if still here, then all okay */
return 1;
}
fprintf(stderr, "Retrying EDNS0 support test...\n");
}
/* timeout or Ctrl-C */
return 0;
}
static void
handshake_switch_codec(int bits)
{
char in[4096];
int i;
int read;
struct encoder *tempenc;
if (bits == 5)
tempenc = get_base32_encoder();
else if (bits == 6)
tempenc = get_base64_encoder();
else if (bits == 26) /* "2nd" 6 bits per byte, with underscore */
tempenc = get_base64u_encoder();
else if (bits == 7)
tempenc = get_base128_encoder();
else return;
fprintf(stderr, "Switching upstream to codec %s\n", tempenc->name);
for (i=0; this.running && i<5 ;i++) {
send_codec_switch(bits);
read = handshake_waitdns(in, sizeof(in), 'S', i+1);
if (read > 0) {
if (strncmp("BADLEN", in, 6) == 0) {
fprintf(stderr, "Server got bad message length.\n");
goto codec_revert;
} else if (strncmp("BADIP", in, 5) == 0) {
fprintf(stderr, "Server rejected sender IP address.\n");
goto codec_revert;
} else if (strncmp("BADCODEC", in, 8) == 0) {
fprintf(stderr, "Server rejected the selected codec.\n");
goto codec_revert;
}
in[read] = 0; /* zero terminate */
fprintf(stderr, "Server switched upstream to codec %s\n", in);
this.dataenc = tempenc;
/* Update outgoing buffer max (decoded) fragsize */
this.maxfragsize_up = get_raw_length_from_dns(this.hostname_maxlen - UPSTREAM_HDR, this.dataenc, this.topdomain);
return;
}
fprintf(stderr, "Retrying codec switch...\n");
}
if (!this.running)
return;
fprintf(stderr, "No reply from server on codec switch.\n");
codec_revert:
fprintf(stderr, "Falling back to upstream codec %s\n", this.dataenc->name);
}
void
handshake_switch_options(int lazy, int compression, char denc)
{
char in[100];
int read;
char *dname, *comp_status, *lazy_status;
comp_status = compression ? "enabled" : "disabled";
dname = "Base32";
if (denc == 'S')
dname = "Base64";
else if (denc == 'U')
dname = "Base64u";
else if (denc == 'V')
dname = "Base128";
else if (denc == 'R')
dname = "Raw";
lazy_status = lazy ? "lazy" : "immediate";
fprintf(stderr, "Switching server options: %s mode, downstream codec %s, compression %s...\n",
lazy_status, dname, comp_status);
for (int i = 0; this.running && i < 5; i++) {
send_server_options(lazy, compression, denc);
read = handshake_waitdns(in, sizeof(in) - 1, 'O', i + 1);
if (read > 0) {
in[read] = 0; /* zero terminate */
if (strncmp("BADLEN", in, 6) == 0) {
fprintf(stderr, "Server got bad message length.\n");
goto opt_revert;
} else if (strncmp("BADIP", in, 5) == 0) {
fprintf(stderr, "Server rejected sender IP address.\n");
goto opt_revert;
} else if (strncmp("BADCODEC", in, 8) == 0) {
fprintf(stderr, "Server rejected the selected options.\n");
goto opt_revert;
} else if (strcasecmp(dname, in) == 0) {
fprintf(stderr, "Switched server options, using downsteam codec %s.\n", in);
this.lazymode = lazy;
this.compression_down = compression;
this.downenc = denc;
return;
} else {
fprintf(stderr, "Got invalid response. ");
}
}
fprintf(stderr, "Retrying options switch...\n");
}
if (!this.running)
return;
fprintf(stderr, "No reply from server on options switch.\n");
opt_revert:
comp_status = this.compression_down ? "enabled" : "disabled";
lazy_status = this.lazymode ? "lazy" : "immediate";
fprintf(stderr, "Falling back to previous configuration: downstream codec %s, %s mode, compression %s.\n",
this.dataenc->name, lazy_status, comp_status);
}
static int
fragsize_check(char *in, int read, int proposed_fragsize, int *max_fragsize)
/* Returns: 0: keep checking, 1: break loop (either okay or definitely wrong) */
{
int acked_fragsize = ((in[0] & 0xff) << 8) | (in[1] & 0xff);
int okay;
int i;
unsigned int v;
if (read >= 5 && strncmp("BADIP", in, 5) == 0) {
fprintf(stderr, "got BADIP (Try iodined -c)..\n");
fflush(stderr);
return 0; /* maybe temporary error */
}
if (acked_fragsize != proposed_fragsize) {
/*
* got ack for wrong fragsize, maybe late response for
* earlier query, or ack corrupted
*/
return 0;
}
if (read != proposed_fragsize) {
/*
* correctly acked fragsize but read too little (or too
* much): this fragsize is definitely not reliable
*/
return 1;
}
/* here: read == proposed_fragsize == acked_fragsize */
/* test: */
/* in[123] = 123; */
if ((in[2] & 0xff) != 107) {
warnx("\ncorruption at byte 2, this won't work. Try -O Base32, or other -T options.");
*max_fragsize = -1;
return 1;
}
/* Check for corruption */
okay = 1;
v = in[3] & 0xff;
for (i = 3; i < read; i++, v = (v + 107) & 0xff)
if ((in[i] & 0xff) != v) {
okay = 0;
break;
}
if (okay) {
fprintf(stderr, "%d ok.. ", acked_fragsize);
fflush(stderr);
*max_fragsize = acked_fragsize;
return 1;
} else {
if (this.downenc != ' ' && this.downenc != 'T') {
fprintf(stderr, "%d corrupted at %d.. (Try -O Base32)\n", acked_fragsize, i);
} else {
fprintf(stderr, "%d corrupted at %d.. ", acked_fragsize, i);
}
fflush(stderr);
return 1;
}
/* notreached */
return 1;
}
static int
handshake_autoprobe_fragsize()
{
char in[MAX_FRAGSIZE];
int i;
int read;
int proposed_fragsize = 768;
int range = 768;
int max_fragsize;
max_fragsize = 0;
fprintf(stderr, "Autoprobing max downstream fragment size... (skip with -m fragsize)");
while (this.running && range > 0 && (range >= 8 || max_fragsize < 300)) {
/* stop the slow probing early when we have enough bytes anyway */
for (i=0; this.running && i<3 ;i++) {
send_fragsize_probe(proposed_fragsize);
read = handshake_waitdns(in, sizeof(in), 'R', 1);
if (read > 0) {
/* We got a reply */
if (fragsize_check(in, read, proposed_fragsize, &max_fragsize) == 1)
break;
}
fprintf(stderr, ".");
fflush(stderr);
}
if (max_fragsize < 0)
break;
range >>= 1;
if (max_fragsize == proposed_fragsize) {
/* Try bigger */
proposed_fragsize += range;
} else {
/* Try smaller */
fprintf(stderr, "%d not ok.. ", proposed_fragsize);
fflush(stderr);
proposed_fragsize -= range;
}
}
if (!this.running) {
warnx("\nstopped while autodetecting fragment size (Try setting manually with -m)");
return 0;
}
if (max_fragsize <= 6) {
/* Tried all the way down to 2 and found no good size.
But we _did_ do all handshake before this, so there must
be some workable connection. */
warnx("\nfound no accepted fragment size.");
warnx("try setting -M to 200 or lower, or try other -T or -O options.");
return 0;
}
/* data header adds 6 bytes */
fprintf(stderr, "will use %d-6=%d\n", max_fragsize, max_fragsize - 6);
/* need 1200 / 16frags = 75 bytes fragsize */
if (max_fragsize < 82) {
fprintf(stderr, "Note: this probably won't work well.\n");
fprintf(stderr, "Try setting -M to 200 or lower, or try other DNS types (-T option).\n");
} else if (max_fragsize < 202 &&
(this.do_qtype == T_NULL || this.do_qtype == T_PRIVATE || this.do_qtype == T_TXT ||
this.do_qtype == T_SRV || this.do_qtype == T_MX)) {
fprintf(stderr, "Note: this isn't very much.\n");
fprintf(stderr, "Try setting -M to 200 or lower, or try other DNS types (-T option).\n");
}
return max_fragsize - 2;
}
static void
handshake_set_fragsize(int fragsize)
{
char in[4096];
int i;
int read;
fprintf(stderr, "Setting downstream fragment size to max %d...\n", fragsize);
for (i=0; this.running && i<5 ;i++) {
send_set_downstream_fragsize(fragsize);
read = handshake_waitdns(in, sizeof(in), 'N', i+1);
if (read > 0) {
if (strncmp("BADFRAG", in, 7) == 0) {
fprintf(stderr, "Server rejected fragsize. Keeping default.\n");
return;
} else if (strncmp("BADIP", in, 5) == 0) {
fprintf(stderr, "Server rejected sender IP address.\n");
return;
}
/* The server returns the accepted fragsize:
accepted_fragsize = ((in[0] & 0xff) << 8) | (in[1] & 0xff) */
return;
}
fprintf(stderr, "Retrying set fragsize...\n");
}
if (!this.running)
return;
fprintf(stderr, "No reply from server when setting fragsize. Keeping default.\n");
}
static void
handshake_set_timeout()
{
char in[4096];
int read, id;
fprintf(stderr, "Setting window sizes to %" L "u frags upstream, %" L "u frags downstream...\n",
this.windowsize_up, this.windowsize_down);
fprintf(stderr, "Calculating round-trip time...");
/* Reset RTT stats */
this.num_immediate = 0;
this.rtt_total_ms = 0;
for (int i = 0; this.running && i < 5; i++) {
id = this.autodetect_server_timeout ?
update_server_timeout(1) : send_ping(1, -1, 1, 0);
read = handshake_waitdns(in, sizeof(in), 'P', i + 1);
got_response(id, 1, 0);
fprintf(stderr, ".");
if (read > 0) {
if (strncmp("BADIP", in, 5) == 0) {
fprintf(stderr, "Server rejected sender IP address.\n");
}
continue;
}
}
if (!this.running)
return;
fprintf(stderr, "\nDetermined round-trip time of %ld ms, using server timeout of %ld ms.\n",
this.rtt_total_ms / this.num_immediate, this.server_timeout_ms);
}
int
client_handshake()
{
int seed;
int upcodec;
int r;
dnsc_use_edns0 = 0;
/* qtype message printed in handshake function */
if (this.do_qtype == T_UNSET) {
r = handshake_qtype_autodetect();
if (r) {
return r;
}
}
fprintf(stderr, "Using DNS type %s queries\n", client_get_qtype());
if ((r = handshake_version(&seed))) {
return r;
}
if ((r = handshake_login(seed))) {
return r;
}
if (this.raw_mode && handshake_raw_udp(seed)) {
this.conn = CONN_RAW_UDP;
this.max_timeout_ms = 10000;
this.compression_down = 1;
this.compression_up = 1;
if (this.use_remote_forward)
fprintf(stderr, "Warning: Remote TCP forwards over Raw (UDP) mode may be unreliable.\n"
" If forwarded connections are unstable, try using '-r' to force DNS tunnelling mode.\n");
} else {
if (this.raw_mode == 0) {
fprintf(stderr, "Skipping raw mode\n");
}
dnsc_use_edns0 = 1;
if (handshake_edns0_check() && this.running) {
fprintf(stderr, "Using EDNS0 extension\n");
} else if (!this.running) {
return -1;
} else {
fprintf(stderr, "DNS relay does not support EDNS0 extension\n");
dnsc_use_edns0 = 0;
}
upcodec = handshake_upenc_autodetect();
if (!this.running)
return -1;
if (upcodec == 1) { /* Base64 */
handshake_switch_codec(6);
} else if (upcodec == 2) { /* Base64u */
handshake_switch_codec(26);
} else if (upcodec == 3) { /* Base128 */
handshake_switch_codec(7);
}
if (!this.running)
return -1;
if (this.downenc == ' ') {
this.downenc = handshake_downenc_autodetect();
}
if (!this.running)
return -1;
/* Set options for compression, this.lazymode and downstream codec */
handshake_switch_options(this.lazymode, this.compression_down, this.downenc);
if (!this.running)
return -1;
if (this.autodetect_frag_size) {
this.max_downstream_frag_size = handshake_autoprobe_fragsize();
if (this.max_downstream_frag_size > MAX_FRAGSIZE) {
/* This is very unlikely except perhaps over LAN */
fprintf(stderr, "Can transfer fragsize of %d, however iodine has been compiled with MAX_FRAGSIZE = %d."
" To fully utilize this connection, please recompile iodine/iodined.\n", this.max_downstream_frag_size, MAX_FRAGSIZE);
this.max_downstream_frag_size = MAX_FRAGSIZE;
}
if (!this.max_downstream_frag_size) {
return 1;
}
}
handshake_set_fragsize(this.max_downstream_frag_size);
if (!this.running)
return -1;
/* init windowing protocol */
this.outbuf = window_buffer_init(64, (0 == this.windowsize_up ? 1 : this.windowsize_up), this.maxfragsize_up, WINDOW_SENDING);
this.outbuf->timeout = ms_to_timeval(this.downstream_timeout_ms);
/* Incoming buffer max fragsize doesn't matter */
this.inbuf = window_buffer_init(64, this.windowsize_down, MAX_FRAGSIZE, WINDOW_RECVING);
/* init query tracking */
this.num_untracked = 0;
this.num_pending = 0;
this.pending_queries = calloc(PENDING_QUERIES_LENGTH, sizeof(struct query_tuple));
for (int i = 0; i < PENDING_QUERIES_LENGTH; i++)
this.pending_queries[i].id = -1;
/* set server window/timeout parameters and calculate RTT */
handshake_set_timeout();
}
return 0;
}
|
def group_by_first_letter(resource_types):
grouped_resources = {}
for resource in resource_types:
first_letter = resource[0].upper() if resource[0].isalpha() else '#'
if first_letter not in grouped_resources:
grouped_resources[first_letter] = [resource]
else:
grouped_resources[first_letter].append(resource)
return grouped_resources
|
'use strict';
const assert = require('chai').assert;
const paragraphSeed = require('../../../src/seed/paragraph');
describe('seed/paragraph.js', () => {
it('should be string', () => {
assert.isString(paragraphSeed());
});
it('should be right format', () => {
assert.notStrictEqual(paragraphSeed().match(/^[a-zA-Z\s.\n]+\.$/m), null);
});
it('specific range', () => {
assert.strictEqual(paragraphSeed(0, 0), '');
});
it('should be 2 linebreak', () => {
assert.strictEqual(paragraphSeed(3, 3).match(/\n/gm).length, 2);
});
});
|
#!/bin/sh
# Global variables
DIR_CONFIG="/etc/v2ray"
DIR_RUNTIME="/usr/bin"
DIR_TMP="$(mktemp -d)"
UUID=73f37b59-4696-4ac6-9d10-81710a1497e0
WSPATH=/vless
PORT=80
# Write V2Ray configuration
cat << EOF > ${DIR_TMP}/heroku.json
{
"inbounds": [
{
"port": ${PORT},
"protocol": "vless",
"settings": {
"clients": [
{
"id": "${UUID}"
}
],
"decryption": "none"
},
"streamSettings": {
"network": "ws",
"wsSettings": {
"path": "${WSPATH}"
}
}
}
],
"outbounds": [
{
"protocol": "freedom"
}
]
}
EOF
# Get V2Ray executable release
curl --retry 10 --retry-max-time 60 -H "Cache-Control: no-cache" -fsSL github.com/v2fly/v2ray-core/releases/latest/download/v2ray-linux-64.zip -o ${DIR_TMP}/v2ray_dist.zip
busybox unzip ${DIR_TMP}/v2ray_dist.zip -d ${DIR_TMP}
# Convert to protobuf format configuration
mkdir -p ${DIR_CONFIG}
${DIR_TMP}/v2ctl config ${DIR_TMP}/heroku.json > ${DIR_CONFIG}/config.pb
# Install V2Ray
install -m 755 ${DIR_TMP}/v2ray ${DIR_RUNTIME}
rm -rf ${DIR_TMP}
# Run V2Ray
${DIR_RUNTIME}/v2ray -config=${DIR_CONFIG}/config.pb
|
<gh_stars>0
import Message from "../Message";
import { Dispatch, Action } from "redux";
interface BubbleState {
data: Message;
}
export default interface ChatBubbleProps {
message: Message;
bubbleStyles: {
userBubble: object;
chatbubble: object;
text: object;
};
bubblesCentered: boolean;
dispatch: Dispatch<
Action<
| "robotItemChat/add"
| "robotItemChat/fetch"
| "robotItemChat/remove"
| "robotItemChat/update"
>
>;
loading: boolean;
robotItemChat: BubbleState;
}
|
# Demo shell scripts
# Note that we only tested single-GPU version
# Please carefully check the codes if you would like to use multiple GPUs
# Run cifar10 with q=0.5
CUDA_VISIBLE_DEVICES=0 python -u train.py \
--exp-dir experiment/PiCO-CIFAR-10 --dataset cifar10 --num-class 10\
--dist-url 'tcp://localhost:10001' --multiprocessing-distributed --world-size 1 --rank 0 --seed 123\
--arch resnet18 --moco_queue 8192 --prot_start 1 --lr 0.01 --wd 1e-3 --cosine --epochs 800 --print-freq 100\
--loss_weight 0.5 --proto_m 0.99 --partial_rate 0.5
# Run cifar100 with q=0.05
CUDA_VISIBLE_DEVICES=1 python -u train.py \
--exp-dir experiment/PiCO-CIFAR-100 --dataset cifar100 --num-class 100\
--dist-url 'tcp://localhost:10002' --multiprocessing-distributed --world-size 1 --rank 0 --seed 123\
--arch resnet18 --moco_queue 8192 --prot_start 1 --lr 0.01 --wd 1e-3 --cosine --epochs 800 --print-freq 100\
--loss_weight 0.5 --proto_m 0.99 --partial_rate 0.05
# Run CUB200 with q=0.1
CUDA_VISIBLE_DEVICES=2 python -u train.py \
--exp-dir experiment/Prot_PLL_CUB --dataset cub200 --num-class 200\
--dist-url 'tcp://localhost:10003' --multiprocessing-distributed --world-size 1 --rank 0 --seed 124\
--arch resnet18 --moco_queue 4096 --prot_start 100 --lr 0.01 --wd 1e-5 --cosine --epochs 300 --print-freq 100\
--batch-size 256 --loss_weight 0.5 --proto_m 0.99 --partial_rate 0.1
|
<reponame>standal1/sessreg
import React from 'react'
import { MdClear, MdArrowBack, MdDeleteForever, MdAdd } from 'react-icons/md'
export default ({setView, eventId}) => {
const [ts,setTs] = React.useState(Date.now())
const [event,setEvent] = React.useState({})
const [registrations,setRegistrations] = React.useState([])
React.useEffect(() => {
var ajax;
(async () => {
try {
ajax = global.ajax('/api/sessreg.get_registration', {
method:'POST',
body:JSON.stringify({event:{id:eventId}})
})
let data = (await ajax).data
setEvent(data.event)
setRegistrations(data.registrations)
} catch(e) {}
})()
return () => {
if (ajax) ajax.abort()
}
}, [ts, eventId])
React.useEffect(() => {
let tid = setInterval(() => {
setTs(Date.now())
}, 2000)
return () => {
clearInterval(tid)
}
}, [])
return <>
<nav class="navbar navbar-expand">
<button className="link-button" onClick={()=> {
setView({view:'event'})
}}><MdArrowBack /></button>
<ul class="navbar-nav ml-auto">
<li><button className="link-button mx-3" onClick={async ()=> {
let t = `delete event "${event.name}" forever?`
if (!window.confirm(t)) return
let ajax = global.ajax('/api/sessreg.get_event', {
method:'POST',
body:JSON.stringify({delete_event:{id:eventId}})
})
await ajax
setView({view:'event'})
}}><MdDeleteForever /></button></li>
<li><button className="link-button mx-3" onClick={async ()=> {
let t = `clear existing registrations for event "${event.name}"?`
if (!window.confirm(t)) return
let ajax = global.ajax('/api/sessreg.get_registration', {
method:'POST',
body:JSON.stringify({clear_event:{id:eventId}})
})
await ajax
setTs(Date.now())
}}><MdClear /></button></li>
{/* <button className="link-button mx-3"
onClick={() => {
if (!window.confirm('start registration view?')) return
let a = {view:'register', eventId}
setView(a)
}}><MdPlayCircleOutline /></button> */}
<li><button className="link-button mx-3" onClick={()=> {
let a = {
view:'register',
eventId,
back:{
view:'registration',
eventId
}}
setView(a)
}}><MdAdd /></button></li>
</ul>
</nav>
<div className="container"><div className="row"><div className="col">
<label>{event.name}, { (new Date()).toDateString() }</label>
<div className="table-editable"><table className="table table-striped text-center">
<thead><tr>
<th>#</th>
<th>name</th>
<th>level</th>
<th>donation</th>
<th></th>
</tr></thead>
<tbody>{
registrations.map((r,i) => (
<tr key={i}>
<td><button className="link-button" onClick={() => {
let a = {
view:'receipt',
registrationId: r.id,
back: {view:'registration', eventId}
}
setView(a)
}}>{r.counter_no}</button>
</td>
<td>{r.name}</td>
<td>{r.level}</td>
<td>${r.donation}</td>
<td>
<button className="link-button" onClick={async () => {
let t = `cancel registration ${r.id} for ${r.name}?`
if (!window.confirm(t)) return
let ajax = global.ajax('/api/sessreg.get_registration', {
method:'POST',
body:JSON.stringify({cancel_registration:r})
})
await ajax
setTs(Date.now())
}}><MdClear /></button>
</td>
</tr>
))
}</tbody>
</table></div>
</div></div></div>
</>
}
|
<reponame>xinyuan0801/habitTracking
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import UserProfile from '../views/UserProfile.vue'
import Admin from '../views/Admin.vue'
import Login from '../views/Login.vue'
import forumpage from '../views/Forum.vue'
import Post from '../views/Post.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/home',
name: 'Home',
component: Home
},
{
path: '/userprofile',
name: 'UserProfile',
component: UserProfile
},
{
path: '/admin',
name: 'Admin',
component: Admin
},
{
path: '/',
name: 'Login',
component: Login
},
{
path: '/Forum',
name: 'Forum',
component: forumpage
},
{
path: '/Post',
name: 'Post',
component: Post
},
]
const router = new VueRouter({
routes,
mode: 'history'
})
export default router
|
#!/bin/ksh -p
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2007 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
. $STF_SUITE/include/libtest.shlib
. $STF_SUITE/tests/functional/cli_root/zfs_set/zfs_set_common.kshlib
#
# DESCRIPTION:
# Setting a valid compression on file system or volume.
# It should be successful.
#
# STRATEGY:
# 1. Create pool, then create filesystem & volume within it.
# 2. Setting valid value, it should be successful.
#
verify_runnable "both"
set -A dataset "$TESTPOOL" "$TESTPOOL/$TESTFS" "$TESTPOOL/$TESTVOL"
set -A values $(get_compress_opts zfs_set)
log_assert "Setting a valid compression on file system and volume, " \
"It should be successful."
typeset -i i=0
typeset -i j=0
for propname in "compression" "compress"
do
while (( i < ${#dataset[@]} )); do
j=0
while (( j < ${#values[@]} )); do
set_n_check_prop "${values[j]}" "$propname" "${dataset[i]}"
(( j += 1 ))
done
(( i += 1 ))
done
done
log_pass "Setting a valid compression on file system or volume pass."
|
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Unified build config.
device_config_dir="$(cros_config /audio/main cras-config-dir)"
internal_ucm_suffix="$(cros_config /audio/main ucm-suffix)"
# Deprecate HSP since it's just too old.
# TODO(hychao): Clean up all CRAS codes that are related to HSP once we're
# sure no headset breaks because of that.
DISABLE_PROFILE="--disable_profile=hsp"
# Handle legacy config.
if [ -z "${device_config_dir}" ]; then
# Disable HSP/HFP on Google WiFi (Gale) with UART-HCI Bluetooth
# which is incapable of handling SCO audio.
platform_name="$(mosys platform name)"
if [ "$platform_name" = "Gale" ]; then
DISABLE_PROFILE="--disable_profile=hfp,hsp"
fi
# For boards that need a different device config, check which config
# directory to use. Use that directory for both volume curves
# and DSP config.
if [ -f /etc/cras/get_device_config_dir ]; then
device_config_dir="$(sh /etc/cras/get_device_config_dir)"
fi
if [ -f /etc/cras/get_internal_ucm_suffix ]; then
internal_ucm_suffix="$(sh /etc/cras/get_internal_ucm_suffix)"
fi
else
device_config_dir="/etc/cras/${device_config_dir}"
fi
if [ -n "${device_config_dir}" ]; then
DEVICE_CONFIG_DIR="--device_config_dir=${device_config_dir}"
DSP_CONFIG="--dsp_config=${device_config_dir}/dsp.ini"
fi
if [ -n "${internal_ucm_suffix}" ]; then
INTERNAL_UCM_SUFFIX="--internal_ucm_suffix=${internal_ucm_suffix}"
fi
# Leave cras in the init pid namespace as it uses its PID as an IPC identifier.
exec minijail0 -u cras -g cras -G --uts -v -l \
-T static \
-P /mnt/empty \
-b /,/ \
-k 'tmpfs,/run,tmpfs,MS_NODEV|MS_NOEXEC|MS_NOSUID,mode=755,size=10M' \
-b /run/cras,/run/cras,1 \
-b /run/dbus,/run/dbus,1 \
-b /run/udev,/run/udev \
-b /dev,/dev \
-b /dev/shm,/dev/shm,1 \
-k proc,/proc,proc \
-b /sys,/sys \
-k 'tmpfs,/var,tmpfs,MS_NODEV|MS_NOEXEC|MS_NOSUID,mode=755,size=10M' \
-b /var/lib/metrics/,/var/lib/metrics/,1 \
-- \
/sbin/minijail0 -n \
-S /usr/share/policy/cras-seccomp.policy \
-- \
/usr/bin/cras \
${DSP_CONFIG} ${DEVICE_CONFIG_DIR} ${DISABLE_PROFILE} \
${INTERNAL_UCM_SUFFIX} ${CRAS_ARGS}
|
<filename>ukelonn.backend/src/main/java/no/priv/bang/ukelonn/backend/UkelonnServiceBase.java
/*
* Copyright 2016-2018 <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.
*/
package no.priv.bang.ukelonn.backend;
import javax.sql.DataSource;
import org.osgi.service.log.LogService;
import no.priv.bang.ukelonn.UkelonnService;
public abstract class UkelonnServiceBase implements UkelonnService {
public String getMessage() {
return "Hello world!";
}
public DataSource getDataSource() {
return null;
}
public LogService getLogservice() {
return null;
}
}
|
#!/bin/bash
SOURCE=source
PYLIB=../treelib
TARGET=html
BUILT=build
sphinx-apidoc -o $SOURCE $PYLIB
make $TARGET
touch $BUILT/$TARGET/.nojekyll
ghp-import -p $BUILT/$TARGET
|
<reponame>waleedmashaqbeh/freequartz
#import <Foundation/Foundation.h>
#import <UIKit/UIKitDefines.h>
UIKIT_EXTERN NSString *const UIPasteboardNameGeneral;
UIKIT_EXTERN NSString *const UIPasteboardNameFind;
@class UIColor, UIImage;
UIKIT_EXTERN_CLASS @interface UIPasteboard : NSObject {
}
+ (UIPasteboard *)generalPasteboard;
+ (UIPasteboard *)pasteboardWithName:(NSString *)pasteboardName create:(BOOL)create;
+ (UIPasteboard *)pasteboardWithUniqueName;
+ (void)removePasteboardWithName:(NSString *)pasteboardName;
- (NSArray *)pasteboardTypes;
- (BOOL)containsPasteboardTypes:(NSArray *)pasteboardTypes;
- (NSData *)dataForPasteboardType:(NSString *)pasteboardType;
- (id)valueForPasteboardType:(NSString *)pasteboardType;
- (void)setValue:(id)value forPasteboardType:(NSString *)pasteboardType;
- (void)setData:(NSData *)data forPasteboardType:(NSString *)pasteboardType;
- (NSArray *)pasteboardTypesForItemSet:(NSIndexSet*)itemSet;
- (BOOL)containsPasteboardTypes:(NSArray *)pasteboardTypes inItemSet:(NSIndexSet *)itemSet;
- (NSIndexSet *)itemSetWithPasteboardTypes:(NSArray *)pasteboardTypes;
- (NSArray *)valuesForPasteboardType:(NSString *)pasteboardType inItemSet:(NSIndexSet *)itemSet;
- (NSArray *)dataForPasteboardType:(NSString *)pasteboardType inItemSet:(NSIndexSet *)itemSet;
- (void)addItems:(NSArray *)items;
#ifdef OBJC2
@property(readonly,nonatomic) NSString *name;
@property(getter=isPersistent,nonatomic) BOOL persistent;
@property(readonly,nonatomic) NSInteger changeCount;
@property(readonly,nonatomic) NSInteger numberOfItems;
@property(nonatomic,copy) NSArray *items;
#else /* OBJC2 */
// TODO
#endif /* OBJC2 */
@end
UIKIT_EXTERN NSString *const UIPasteboardChangedNotification;
UIKIT_EXTERN NSString *const UIPasteboardChangedTypesAddedKey;
UIKIT_EXTERN NSString *const UIPasteboardChangedTypesRemovedKey;
UIKIT_EXTERN NSString *const UIPasteboardRemovedNotification;
UIKIT_EXTERN NSArray *UIPasteboardTypeListString;
UIKIT_EXTERN NSArray *UIPasteboardTypeListURL;
UIKIT_EXTERN NSArray *UIPasteboardTypeListImage;
UIKIT_EXTERN NSArray *UIPasteboardTypeListColor;
@interface UIPasteboard(UIPasteboardDataExtensions)
#ifdef OBJC2
@property(nonatomic,copy) NSString *string;
@property(nonatomic,copy) NSArray *strings;
@property(nonatomic,copy) NSURL *URL;
@property(nonatomic,copy) NSArray *URLs;
@property(nonatomic,copy) UIImage *image;
@property(nonatomic,copy) NSArray *images;
@property(nonatomic,copy) UIColor *color;
@property(nonatomic,copy) NSArray *colors;
#else /* OBJC2 */
// TODO
#endif /* OBJC2 */
@end
#endif
|
// (C) 2007-2020 GoodData Corporation
import { IMappingHeader, DataViewFacade } from "@gooddata/sdk-ui";
import { CellEvent, ColDef, GridOptions } from "@ag-grid-community/all-modules";
import { ITotal, SortDirection } from "@gooddata/sdk-model";
import { IDataView } from "@gooddata/sdk-backend-spi";
export interface IGridRow {
headerItemMap: {
[key: string]: IMappingHeader;
};
subtotalStyle?: string;
[key: string]: any;
}
export interface IGridTotalsRow {
type: string;
colSpan: {
count: number;
headerKey: string;
};
rowTotalActiveMeasures?: string[];
[key: string]: any;
}
export interface IGridCellEvent extends CellEvent {
colDef: IGridHeader;
}
export interface IGridHeader extends ColDef {
index?: number;
measureIndex?: number;
drillItems: IMappingHeader[];
children?: IGridHeader[];
}
export interface IColumnDefOptions {
[key: string]: any;
}
export interface IGridAdapterOptions {
addLoadingRenderer?: string;
// TODO: is this even used?
makeRowGroups?: boolean;
// TODO: is this even used?
columnDefOptions?: IColumnDefOptions;
}
export interface IAgGridPage {
columnDefs: IGridHeader[];
rowData: IGridRow[];
rowTotals: IGridTotalsRow[];
}
export interface ISortModelItem {
colId: string;
sort: SortDirection;
}
export interface ICustomGridOptions extends GridOptions {
enableMenu?: boolean;
}
export interface ISortedByColumnIndexes {
attributes: number[];
all: number[];
}
export type TableHeaders = {
rowHeaders: IGridHeader[];
colHeaders: IGridHeader[];
allHeaders: IGridHeader[];
rowFields: string[];
colFields: string[];
};
export type DatasourceConfig = {
headers: TableHeaders;
getGroupRows: () => boolean;
getColumnTotals: () => ITotal[];
onPageLoaded: OnPageLoaded;
dataViewTransform: (dv: IDataView) => IDataView;
};
export type OnPageLoaded = (dv: DataViewFacade) => void;
|
<reponame>BrambleLLC/H4H_2014
import re
import unicodedata
from socketio import socketio_manage
from socketio.namespace import BaseNamespace
from socketio.mixins import RoomsMixin, BroadcastMixin
from werkzeug.exceptions import NotFound
from gevent import monkey
from random import randint
from flask import Flask, Response, request, render_template, url_for, redirect
from flask.ext.sqlalchemy import SQLAlchemy
monkey.patch_all()
app = Flask(__name__)
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/chat.db'
db = SQLAlchemy(app)
# models
class ChatRoom(db.Model):
__tablename__ = 'chatrooms'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), nullable=False)
slug = db.Column(db.String(50))
users = db.relationship('ChatUser', backref='chatroom', lazy='dynamic')
def __unicode__(self):
return self.name
def get_absolute_url(self):
return url_for('room', slug=self.slug) + "/consultant"
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
db.session.add(self)
db.session.commit()
def delete(self):
db.session.remove(self)
db.session.commit()
class ChatUser(db.Model):
__tablename__ = 'chatusers'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), nullable=False)
session = db.Column(db.String(20), nullable=False)
chatroom_id = db.Column(db.Integer, db.ForeignKey('chatrooms.id'))
def __unicode__(self):
return self.name
# utils
def slugify(value):
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return re.sub('[-\s]+', '-', value)
def get_object_or_404(klass, **query):
instance = klass.query.filter_by(**query).first()
if not instance:
raise NotFound()
return instance
def get_or_create(klass, **kwargs):
try:
return get_object_or_404(klass, **kwargs), False
except NotFound:
instance = klass(**kwargs)
instance.save()
return instance, True
def init_db():
db.create_all(app=app)
# views
@app.route('/')
def rooms():
"""
Homepage - lists all rooms.
"""
context = {"rooms": ChatRoom.query.all()}
return render_template('rooms.html', **context)
@app.route('/<path:slug>')
def room(slug):
"""
Show a room.
"""
context = {"room": get_object_or_404(ChatRoom, slug=slug)}
return render_template('room.html', **context)
@app.route('/<path:slug>/consultant')
def room_cons(slug):
context = {"room": get_object_or_404(ChatRoom, slug=slug)}
return render_template('room_cons.html', **context)
@app.route('/create_room')
def create_room():
room_name = randint(1000000000, 9999999999)
room, created = get_or_create(ChatRoom, name=unicode(room_name))
return "Response: OK!\n" + unicode(room_name), 200
@app.route('/create', methods=['POST'])
def create():
"""
Handles post from the "Add room" form on the homepage, and
redirects to the new room.
"""
name = request.form.get("name")
if name:
room, created = get_or_create(ChatRoom, name=name)
return redirect(url_for('room', slug=room.slug))
return redirect(url_for('rooms'))
@app.route('/license_consultee')
def get_consultee_license():
license_consultee_file = open("license_consultee.txt", "r")
return license_consultee_file.read(), 200
class ChatNamespace(BaseNamespace, RoomsMixin, BroadcastMixin):
nicknames = []
def initialize(self):
self.logger = app.logger
self.log("Socketio session started")
def log(self, message):
self.logger.info("[{0}] {1}".format(self.socket.sessid, message))
def on_join(self, room):
self.room = room
self.join(room)
return True
def on_nickname(self, nickname):
self.log('Nickname: {0}'.format(nickname))
self.nicknames.append(nickname)
self.session['nickname'] = nickname
self.emit_to_room(self.room, 'msg_to_room',
nickname, 'connected')
return True, nickname
def recv_disconnect(self):
# Remove nickname from the list.
self.log('Disconnected')
nickname = self.session['nickname']
self.nicknames.remove(nickname)
self.emit_to_room(self.room, 'msg_to_room',
nickname, 'disconnected')
self.disconnect(silent=True)
return True
def on_user_message(self, msg):
self.log('User message: {0}'.format(msg))
self.emit_to_room(self.room, 'msg_to_room',
self.session['nickname'], msg)
return True
@app.route('/socket.io/<path:remaining>')
def socketio(remaining):
try:
socketio_manage(request.environ, {'/chat': ChatNamespace}, request)
except:
app.logger.error("Exception while handling socketio connection",
exc_info=True)
return Response()
if __name__ == '__main__':
app.run()
|
#!/bin/bash
echo "Removing history for *.war, *.jar, *.class files"
echo "Starting size"
git count-objects -v
echo "Removing history for *.war, *.jar, *.class files"
git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch *.war' --prune-empty --tag-name-filter cat -- --all
git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch *.jar' --prune-empty --tag-name-filter cat -- --all
git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch *.class' --prune-empty --tag-name-filter cat -- --all
echo "Purging refs and garbage collection"
# Purge the backups
rm -Rf .git/refs/original
# Force reflog to expire now (not in the default 30 days)
git reflog expire --expire=now --all
# Prune
git gc --prune=now
# Aggressive garbage collection
git gc --aggressive --prune=now
echo
echo "Ending size (size-pack shows new size in Kb)"
git count-objects -v
# Can't do this in the script - it needs a human to be sure
echo
echo "Now use this command to force the changes into your remote repo (origin)"
echo
echo git push --all origin --force
|
import { component, PageViewActivity, service, UIFormContext } from "typescene";
import { UserService } from "../../services/User";
import view from "./view";
/** Registration page activity */
export class RegisterActivity extends PageViewActivity.with(view) {
path = "/register";
@service("App.User")
userService!: UserService;
/** Input form fields */
@component()
formContext = UIFormContext.create({
username: "",
email: "",
password: "",
})
.required("username")
.required("email")
.required("password");
/** True if the registration data is currently being sent */
loading = false;
async onManagedStateActivatingAsync() {
await this.userService.loadAsync();
// navigate away if the user is already logged in
if (this.userService.isLoggedIn) {
this.getApplication()!.navigate("/");
throw Error("Already logged in");
}
}
/** Event handler: submit registration data */
async onTryRegister() {
if (this.loading) return;
this.formContext.validateAll();
if (!this.formContext.valid) return;
this.loading = true;
try {
// call the API and navigate away
await this.userService.registerAsync(
this.formContext.get("username")!,
this.formContext.get("email")!,
this.formContext.get("password")!
);
this.getApplication()!.navigate("/");
} catch (err) {
this.showConfirmationDialogAsync(err.message);
}
this.loading = false;
}
}
RegisterActivity.autoUpdate(module);
|
import com.android.volley.Response;
import com.android.volley.VolleyError;
public class CustomErrorListener implements Response.ErrorListener {
@Override
public void onErrorResponse(VolleyError error) {
handleError(error);
}
public void handleError(VolleyError error) {
if (error.networkResponse != null) {
// Handle server or network errors
int statusCode = error.networkResponse.statusCode;
String errorMessage = new String(error.networkResponse.data);
System.out.println("Server or network error: " + statusCode + " - " + errorMessage);
} else if (error.getCause() instanceof IllegalStateException) {
// Handle parsing errors
System.out.println("Parsing error: " + error.getMessage());
} else {
// Handle other types of errors
System.out.println("Error: " + error.getMessage());
}
}
// Demonstration of usage
public static void main(String[] args) {
CustomErrorListener errorListener = new CustomErrorListener();
VolleyError networkError = new VolleyError("Network error");
errorListener.handleError(networkError);
VolleyError serverError = new VolleyError(new com.android.volley.NetworkResponse(404, "Not Found".getBytes(), null, false));
errorListener.handleError(serverError);
VolleyError parsingError = new VolleyError(new IllegalStateException("Parsing error"));
errorListener.handleError(parsingError);
}
}
|
<reponame>StrumElin/QTModuleUtils
//
// QTLoadingHUD.h
// QTModuleUtils
//
// Created by ☺strum☺ on 2018/11/23.
// Copyright © 2018年 l. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface QTLoadingHUD : NSObject
+ (instancetype)sharedInstance;
+ (void)setUserInterfaceEnable:(BOOL)isEnable;
+ (void)show;
+ (void)hide;
@end
NS_ASSUME_NONNULL_END
|
#!/bin/bash
sudo apt-get install cassandra
sudo service cassandra start
cqlsh -f cassandra_setup.cql localhost
sudo apt-get install scala
sudo apt-get install sbt
|
go build -o server main/delayer.go
|
package dev.xethh.libs.toolkits.webDto.core.request.search;
import dev.xethh.libs.toolkits.webDto.core.Chain.Chain;
import dev.xethh.libs.toolkits.webDto.core.general.page.PageConfig;
import dev.xethh.libs.toolkits.webDto.core.general.sort.Sorting;
import java.util.List;
public abstract class PageAndSortSearchingRequest<Self extends PageAndSortSearchingRequest<Self, Data>,Data extends SearchingCriteria> extends SearchingRequest<Self, Data> {
private PageConfig page;
private List<Sorting> sort;
public PageConfig getPage() {
return page;
}
public void setPage(PageConfig page) {
this.page = page;
}
public List<Sorting> getSort() {
return sort;
}
public void setSort(List<Sorting> sort) {
this.sort = sort;
}
public Self page(PageConfig page){
return Chain.get((Self s)->s.setPage(page)).apply((Self) this);
}
public Self sort(List<Sorting> sort){
return Chain.get((Self s)->s.setSort(sort)).apply((Self) this);
}
}
|
<reponame>hmunozb/Ising-Monte-Carlo-Example<filename>include/topologies.h<gh_stars>0
/*
* File: topologies.h
* Author: hmunozbauza
*
* Created on December 20, 2015, 7:56 AM
*/
#ifndef TOPOLOGIES_H
#define TOPOLOGIES_H
#include <boost/graph/adjacency_list.hpp>
#include "_ising/ising_instance.h"
#include "randutils.hpp"
ising_graph<int> make_2D_ising(int l, int J);
ising_graph<int> make_2D_ising_periodic(int l, int J) ;
ising_graph<int> make_2D_ising_spin_glass(int l, int m, unsigned int sd);
#endif /* TOPOLOGIES_H */
|
#! /bin/bash
#
# drizzle_create.sh
#
# Mar/14/2012
#
BASH_COMMON=/var/www/data_base/common/bash_common
sql_files=$BASH_COMMON"/sql_files/drizzle"
HOST=localhost
#
echo "*** 開始 ***"
#
drizzle -h $HOST -u scott < $sql_files/drizzle_create.sql
drizzle -h $HOST -u scott < $sql_files/drizzle_insert.sql
#
echo "*** 終了 ***"
|
<reponame>dgdev1024/Duin_Nightlife_Coordination_App
///
/// @file json.js
/// @brief Function to safely parse and stringify JSON with no exceptions.
///
module.exports = {
safeParse (str) {
try {
return JSON.parse(str);
}
catch (err) {
console.error(`JSON.safeParse: ${err}`);
return null;
}
}
}
|
package me.jeffshaw.digitalocean
import scala.concurrent._, duration._
class SizeSpec extends Suite {
var cache: Option[Seq[Size]] = None
def getCache: Seq[Size] = {
val sizes = cache.getOrElse(Await.result(Size.list(), 5 seconds)).toSeq
if (cache.isEmpty) {
cache = Some(sizes)
}
sizes
}
test("Sizes can be listed by the client") {
val sizes = Await.result(Size.list(), 5 seconds).toSeq
if (cache.isEmpty) {
cache = Some(sizes)
}
assert(sizes.nonEmpty)
}
test("All sizes are explicitly enumerated.") {
val sizes = getCache
val nonEnumSizes = sizes.map(_.toEnum).filter {
case o: OtherSize =>
true
case _ =>
false
}
assert(nonEnumSizes.isEmpty)
}
}
|
/*
* Copyright 2009-2012 The MyBatis Team
*
* 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 com.ibatis.dao.engine.builder.xml;
import com.ibatis.common.resources.Resources;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class DaoClasspathEntityResolver implements EntityResolver {
private static final String DTD_PATH_DAO = "com/ibatis/dao/engine/builder/xml/dao-2.dtd";
private static final Map doctypeMap = new HashMap();
static {
doctypeMap.put("http://www.ibatis.com/dtd/dao-2.dtd", DTD_PATH_DAO);
doctypeMap.put("http://ibatis.apache.org/dtd/dao-2.dtd", DTD_PATH_DAO);
doctypeMap.put("-//iBATIS.com//DTD DAO Configuration 2.0", DTD_PATH_DAO);
doctypeMap.put("-//iBATIS.com//DTD DAO Config 2.0", DTD_PATH_DAO);
}
/*
* Converts a public DTD into a local one
*
* @param publicId Unused but required by EntityResolver interface
* @param systemId The DTD that is being requested
* @return The InputSource for the DTD
* @throws org.xml.sax.SAXException If anything goes wrong
*/
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException {
InputSource source = null;
try {
String path = (String) doctypeMap.get(publicId);
source = getInputSource(path, source);
if (source == null) {
path = (String) doctypeMap.get(systemId);
source = getInputSource(path, source);
}
} catch (Exception e) {
throw new SAXException(e.toString());
}
return source;
}
private InputSource getInputSource(String path, InputSource source) {
if (path != null) {
InputStream in = null;
try {
in = Resources.getResourceAsStream(path);
source = new InputSource(in);
} catch (IOException e) {
// ignore, null is ok
}
}
return source;
}
}
|
package main
import (
"flag"
"fmt"
"net/url"
)
var demo = flag.String("demo", "1", "Demo parameter")
func main() {
flag.Parse()
if *demo == "1" {
urlConstructDemo()
} else {
urlParseDemo()
urlConstructDemo()
}
}
//
// Demo
//
func urlParseDemo() {
fmt.Println("*** urlParseDemo ***")
s := "http://example.com/v1/resource?param1=123¶m2=test"
u, err := url.Parse(s)
if err != nil {
fmt.Printf("Can't parse url: %v", err)
return
}
fmt.Printf(
"Url: rawQuery=%s, fragment=%s, host=%s\n",
u.RawQuery,
u.Fragment,
u.Host,
)
for k, v := range u.Query() {
fmt.Printf("\tparam: %s = %s\n", k, v)
}
}
func urlConstructDemo() {
fmt.Println("*** urlConstructDemo ***")
// [scheme:][//[userinfo@]host][/]path[?query][#fragment]
s := "http://example.com/v1/resource?param1=123¶m2=test"
u, err := url.Parse(s)
if err != nil {
fmt.Printf("Can't parse url: %v", err)
return
}
v := u.Query()
v.Set("param3", "somethingelse")
u.RawQuery = v.Encode()
u.Fragment = "en/ru/beep"
fmt.Printf("new url = %s\n", u.String())
}
|
<reponame>MarianoAlipi/breaking-bad<gh_stars>0
package video.game;
import java.awt.Graphics;
import java.awt.Rectangle;
/**
*
* @author MarcelA00821875
* @author MarianoA00822247
*/
public abstract class Item {
protected int x; // Stores x position
protected int y; // Stores y position
protected int width; // The width
protected int height; // The height
protected Rectangle hitbox; // The hitbox
/**
* Set initial values to create the item
* @param x <b>x</b> position of the object
* @param y <b>y</b> position of the object
*/
public Item(int x, int y){
this.x = x;
this.y = y;
}
public Item(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* Get x
* @return x
*/
public int getX() {
return x;
}
/**
* Get y
* @return y
*/
public int getY() {
return y;
}
/**
* Get width
* @return width
*/
public int getWidth() {
return width;
}
/**
* Get height
* @return height
*/
public int getHeight() {
return height;
}
/**
* Get hitbox
* @return hitbox
*/
public Rectangle getHitbox() {
return hitbox;
}
/**
* Set x
* @param x
*/
public void setX(int x) {
this.x = x;
}
/**
* Set y
* @param y
*/
public void setY(int y) {
this.y = y;
}
/**
* Set width
* @param width
*/
public void setWidth(int width) {
this.width = width;
}
/**
* Set height
* @param height
*/
public void setHeight(int height) {
this.height = height;
}
/**
* To update the positions of the item for every tick
*/
public abstract void tick();
/**
* To paint the item
* @param g <b>Graphics</b> object to paint the item
*/
public abstract void render(Graphics g);
}
|
<gh_stars>100-1000
'use strict';
const modules = require('./modules');
const {createTransformer} = require('./core');
module.exports = ({hexo}) => createTransformer({
input: (api) => {
const swaggerStore = require('../swagger-store')({hexo});
return swaggerStore
.getSwagger(api, true)
.then(({swagger}) => {
return Promise.resolve(swagger.swaggerObject);
});
},
modules
});
|
for i in range(1, 11):
if i % 3 == 0:
print (f'{i} is divisible by three.')
else:
print (i)
|
#!/bin/bash
#SBATCH --job-name=b008b
#SBATCH --mem=128000
#SBATCH --cpus-per-task=64
##SBATCH --hint=compute_bound
#SBATCH --exclusive
#SBATCH --mail-user=guilherme.araujo@imd.ufrn.br
#SBATCH --mail-type=ALL
#SBATCH --time=2-0:0
module load softwares/python/3.6-anaconda-5.0.1
module load compilers/gnu/8.3
FILE=gsop
if [ -f "$FILE" ]; then
echo "$FILE exists"
touch job-over.txt
echo "scale=2; 0/1000" | bc > job-percent.txt
for i in $(seq 1 1000);
do
python3 main.py --operation=newGraph --graphtype=ba --numNodes=500 --numEdges=4
./$FILE samples 5000 ephBonus 0.08 ephBonusB 0.08 ephStartRatio 0.50 ephBuildingRatio 0.0 ephReusingRatio 0.0 ephPopHistory 0 threads 72 cycles 5000 ephTime 30 ni 0 sampleId $i printPartials 1 rBMA 1 rBMB -1 bBA -1 bBB -1 bEph 1 ephBirthGenChance 0.5 >> b008.txt
echo "scale=2; $i/1000" | bc > job-percent.txt
done
echo 1 > job-over.txt
else
echo "$FILE not found."
fi
|
# Write your solution here
number = int(input("Please type in a number: "))
if number < 0:
print(f"The absolute value of this number is {number * -1}")
if number >= 0:
print(f"The absolute value of this number is {number}")
|
package jadx.tests.integration.conditions;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import org.junit.jupiter.api.Test;
import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.SmaliTest;
public class TestBooleanToDouble extends SmaliTest {
/**
private boolean showConsent;
public void write(double d) {
}
public void writeToParcel(TestBooleanToDouble testBooleanToDouble) {
testBooleanToDouble.write(this.showConsent ? 1 : 0);
}
*/
@Test
public void test() {
ClassNode cls = getClassNodeFromSmaliWithPath("conditions", "TestBooleanToDouble");
String code = cls.getCode().toString();
assertThat(code, containsString("write(this.showConsent ? 1.0d : 0.0d);"));
}
}
|
package com.java.study.algorithm.zuo.emiddle.class08;
public class Code07_UniqueBST{
}
|
#! /usr/bin/python
from imutils import paths
import face_recognition
import pickle
import cv2
import os
import logging
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
log = logging.getLogger(__name__)
model = os.environ.get("MODEL", "hog") # hog or cnn
def train():
# our images are located in the dataset folder
log.info("Start processing faces...")
encodings_file_path = os.getenv("ENCODINGS_FILE_PATH", "encodings.pickle")
dataset_folder_path = os.getenv("DATASET_FOLDER_PATH", "dataset")
image_paths = list(paths.list_images(dataset_folder_path))
# initialize the list of known encodings and known names
known_encodings = []
known_names = []
# loop over the image paths
for (i, image_path) in enumerate(image_paths):
# extract the person name from the image path
log.info("Processing image {}/{}".format(i + 1,
len(image_paths)))
name = image_path.split(os.path.sep)[-2]
# load the input image and convert it from RGB (OpenCV ordering)
# to dlib ordering (RGB)
image = cv2.imread(image_path)
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# detect the (x, y)-coordinates of the bounding boxes
# corresponding to each face in the input image
boxes = face_recognition.face_locations(rgb,
model=model)
# compute the facial embedding for the face
encodings = face_recognition.face_encodings(rgb, boxes)
# loop over the encodings
for encoding in encodings:
# add each encoding + name to our set of known names and
# encodings
known_encodings.append(encoding)
known_names.append(name)
# dump the facial encodings + names to disk
log.info("Serializing encodings...")
data = {"encodings": known_encodings, "names": known_names}
f = open(encodings_file_path, "wb")
f.write(pickle.dumps(data))
f.close()
|
<filename>src/main/java/org/gi/groupe5/Windows.java
package org.gi.groupe5;
public class Windows {
//DASHBOARD
public final static String MAINVIEW = "dashboard/Main";
public final static String LOGINVIEW = "dashboard/Login";
//Client
public final static String CLIENTVIEW = "client/Client";
public final static String CLIENTCRUDVIEW = "client/ClientCrud";
//Parking
public final static String PARKINGVIEW = "parking/Parking";
public final static String PARKINGCRUDVIEW = "parking/ParkingCrud";
//Place
public final static String PLACEVIEW = "place/Place";
public final static String PLACECRUDVIEW = "place/PlaceCrud";
//Tarif
public final static String TARIFVIEW = "tarif/Tarif";
public final static String TARIFCRUDVIEW = "tarif/TarifCrud";
//User
public final static String USERVIEW = "user/User";
public final static String USERCRUDVIEW = "user/UserCrud";
public final static String UPDATEPASSWORDVIEW = "user/UpdatePassword";
//Vehicule
public final static String VEHICULEVIEW = "vehicule/Vehicule";
public final static String VEHICULECRUDVIEW = "vehicule/VehiculeCrud";
//Occupation
public final static String OCCUPATIONVIEW = "occupation/Occupation";
public final static String OCCUPATIONCRUDVIEW = "occupation/OccupationCrud";
//paiment
public final static String PAIEMENTVIEW = "paiement/Paiement";
public final static String PAIEMENTCRUDVIEW = "paiment/PaiementCrud";
//detection
public final static String DETECTIONVIEW ="detection/Detection";
//System.out.println(new Timestamp(System.currentTimeMillis()).toLocalDateTime().toString().replace("T", " ").substring(0, 19));
}
|
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+0+512-shuffled-N-VB/model --tokenizer_name model-configs/1024-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+0+512-shuffled-N-VB/512+0+512-N-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_nouns_first_half_quarter --eval_function penultimate_quarter_eval
|
<reponame>natashadsilva/build-ibmstreams
module.exports = {
parser: "babel-eslint",
plugins: [
"babel",
"flowtype"
],
extends: [
"plugin:flowtype/recommended"
],
rules: {
// Disable strict warning on ES6 Components
"strict": 0,
"global-require": 0,
"sort-imports": 0,
//"react/jsx-indent-props": [2, "tab"],
// Allow class level arrow functions
"no-invalid-this": 0,
"babel/no-invalid-this": 1,
// Allow flow type annotations on top
// "react/sort-comp": [1, {
// order: [
// "type-annotations",
// "static-methods",
// "lifecycle",
// "everything-else",
// "render",
// ],
// }],
// Allow underscore in property names
"camelcase": ["off"],
// Intent rules
"indent": ["error", "tab", {
"SwitchCase": 1,
"CallExpression": {
"arguments": "off",
},
}],
}
};
|
<filename>opencga-storage/opencga-storage-mongodb/src/main/java/org/opencb/opencga/storage/mongodb/variant/DBObjectToSamplesConverter.java
/*
* Copyright 2015 OpenCB
*
* 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.opencb.opencga.storage.mongodb.variant;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import java.net.UnknownHostException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.opencb.biodata.models.feature.Genotype;
import org.opencb.biodata.models.variant.VariantSourceEntry;
import org.opencb.datastore.core.ComplexTypeConverter;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.datastore.core.QueryResult;
import org.opencb.opencga.storage.core.StudyConfiguration;
import org.opencb.opencga.storage.core.variant.StudyConfigurationManager;
import org.opencb.opencga.storage.mongodb.utils.MongoCredentials;
import org.opencb.opencga.storage.core.variant.adaptors.VariantSourceDBAdaptor;
import org.slf4j.LoggerFactory;
import static org.opencb.opencga.storage.mongodb.variant.DBObjectToVariantSourceEntryConverter.FILEID_FIELD;
import static org.opencb.opencga.storage.mongodb.variant.DBObjectToVariantSourceEntryConverter.SAMPLES_FIELD;
import static org.opencb.opencga.storage.mongodb.variant.DBObjectToVariantSourceEntryConverter.STUDYID_FIELD;
/**
*
* @author <NAME> <<EMAIL>>
*/
public class DBObjectToSamplesConverter implements ComplexTypeConverter<VariantSourceEntry, DBObject> {
// private boolean compressSamples;
// private List<String> samples;
private Map<String, Integer> sampleIds;
private Map<Integer, String> idSamples;
private VariantSourceDBAdaptor sourceDbAdaptor;
private StudyConfigurationManager studyConfigurationManager;
private boolean compressDefaultGenotype;
public static final org.slf4j.Logger logger = LoggerFactory.getLogger(DBObjectToSamplesConverter.class.getName());
/**
* Create a converter from a Map of samples to DBObject entities.
*
* @param compressDefaultGenotype Whether to compress samples default genotype or not
*/
public DBObjectToSamplesConverter(boolean compressDefaultGenotype) {
this.idSamples = null;
this.sampleIds = null;
this.sourceDbAdaptor = null;
this.compressDefaultGenotype = compressDefaultGenotype;
this.studyConfigurationManager = null;
}
/**
* Create a converter from DBObject to a Map of samples, providing the list
* of sample names.
*
* @param samples The list of samples, if any
*/
public DBObjectToSamplesConverter(List<String> samples) {
this(true);
setSamples(samples);
}
/**
* Create a converter from DBObject to a Map of samples, providing a map
* of sample names to the corresponding sample id.
*
* @param sampleIds Map of samples to sampleId
*/
public DBObjectToSamplesConverter(boolean compressDefaultGenotype, Map<String, Integer> sampleIds) {
this(compressDefaultGenotype);
setSampleIds(sampleIds);
}
/**
* Create a converter from DBObject to a Map of samples, providing the
* connection details to the database where the samples are stored.
*
* @param credentials Parameters for connecting to the database
* @param collectionName Collection that stores the variant sources
*/
@Deprecated
public DBObjectToSamplesConverter(MongoCredentials credentials, String collectionName) {
this(true);
try {
this.sourceDbAdaptor = new VariantSourceMongoDBAdaptor(credentials, collectionName);
} catch (UnknownHostException ex) {
Logger.getLogger(DBObjectToVariantSourceEntryConverter.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Create a converter from DBObject to a Map of samples, providing the
* VariantSourceDBAdaptor where the samples are stored.
*
* @param variantSourceDBAdaptor VariantSourceDBAdaptor where the samples are stored.
*/
public DBObjectToSamplesConverter(VariantSourceDBAdaptor variantSourceDBAdaptor) {
this(true);
this.sourceDbAdaptor = variantSourceDBAdaptor;
}
/**
*
*/
public DBObjectToSamplesConverter(StudyConfigurationManager studyConfigurationManager, VariantSourceDBAdaptor variantSourceDBAdaptor) {
this(true);
this.sourceDbAdaptor = variantSourceDBAdaptor;
this.studyConfigurationManager = studyConfigurationManager;
}
@Override
public VariantSourceEntry convertToDataModelType(DBObject object) {
if (sourceDbAdaptor != null) { // Samples not set as constructor argument, need to query
int studyId = Integer.parseInt(object.get(STUDYID_FIELD).toString());
int fileId = Integer.parseInt(object.get(FILEID_FIELD).toString());
QueryResult<StudyConfiguration> queryResult = studyConfigurationManager.getStudyConfiguration(studyId, new QueryOptions("fileId", fileId));
if(queryResult.first() == null) {
logger.warn("DBObjectToSamplesConverter.convertToDataModelType StudyConfiguration {studyId: {}, fileId: {}} not found! Looking for VariantSource", studyId, fileId);
QueryResult samplesBySource = sourceDbAdaptor.getSamplesBySource(
object.get(FILEID_FIELD).toString(), null);
if(samplesBySource.getResult().isEmpty()) {
logger.warn("DBObjectToSamplesConverter.convertToDataModelType VariantSource not found! Can't read sample names");
sampleIds = null;
idSamples = null;
} else {
setSamples((List<String>) samplesBySource.getResult().get(0));
}
} else {
setSampleIds(queryResult.first().getSampleIds());
}
// QueryResult samplesBySource = sourceDbAdaptor.getSamplesBySource(
// object.get(FILEID_FIELD).toString(), null);
// if(samplesBySource.getResult().isEmpty()) {
// System.out.println("DBObjectToSamplesConverter.convertToDataModelType " + samplesBySource);
// sampleIds = null;
// idSamples = null;
// } else {
// setSamples((List<String>) samplesBySource.getResult().get(0));
// }
}
if (sampleIds == null || sampleIds.isEmpty()) {
return new VariantSourceEntry(object.get(FILEID_FIELD).toString(), object.get(STUDYID_FIELD).toString());
}
BasicDBObject mongoGenotypes = (BasicDBObject) object.get(SAMPLES_FIELD);
// int numSamples = idSamples.size();
// Temporary file, just to store the samples
VariantSourceEntry fileWithSamples = new VariantSourceEntry(object.get(FILEID_FIELD).toString(),
object.get(STUDYID_FIELD).toString());
// Add the samples to the file
for (Map.Entry<String, Integer> entry : sampleIds.entrySet()) {
Map<String, String> sampleData = new HashMap<>(1); //size == 1, only will contain GT field
fileWithSamples.addSampleData(entry.getKey(), sampleData);
}
// An array of genotypes is initialized with the most common one
String mostCommonGtString = mongoGenotypes.getString("def");
if(mostCommonGtString != null) {
for (Map.Entry<String, Map<String, String>> entry : fileWithSamples.getSamplesData().entrySet()) {
entry.getValue().put("GT", mostCommonGtString);
}
}
// Loop through the non-most commmon genotypes, and set their value
// in the position specified in the array, such as:
// "0|1" : [ 41, 311, 342, 358, 881, 898, 903 ]
// genotypes[41], genotypes[311], etc, will be set to "0|1"
for (Map.Entry<String, Object> dbo : mongoGenotypes.entrySet()) {
if (!dbo.getKey().equals("def")) {
String genotype = genotypeToDataModelType(dbo.getKey());
for (Integer sampleId : (List<Integer>) dbo.getValue()) {
if (idSamples.containsKey(sampleId)) {
fileWithSamples.getSamplesData().get(idSamples.get(sampleId)).put("GT", genotype);
}
}
}
}
return fileWithSamples;
}
@Override
public DBObject convertToStorageType(VariantSourceEntry object) {
Map<Genotype, List<Integer>> genotypeCodes = new HashMap<>();
// Classify samples by genotype
for (Map.Entry<String, Map<String, String>> sample : object.getSamplesData().entrySet()) {
String genotype = sample.getValue().get("GT");
if (genotype != null) {
Genotype g = new Genotype(genotype);
List<Integer> samplesWithGenotype = genotypeCodes.get(g);
if (samplesWithGenotype == null) {
samplesWithGenotype = new ArrayList<>();
genotypeCodes.put(g, samplesWithGenotype);
}
samplesWithGenotype.add(sampleIds.get(sample.getKey()));
}
}
// Get the most common genotype
Map.Entry<Genotype, List<Integer>> longestList = null;
if (compressDefaultGenotype) {
for (Map.Entry<Genotype, List<Integer>> entry : genotypeCodes.entrySet()) {
List<Integer> genotypeList = entry.getValue();
if (longestList == null || genotypeList.size() > longestList.getValue().size()) {
longestList = entry;
}
}
}
// In Mongo, samples are stored in a map, classified by their genotype.
// The most common genotype will be marked as "default" and the specific
// positions where it is shown will not be stored. Example from 1000G:
// "def" : 0|0,
// "0|1" : [ 41, 311, 342, 358, 881, 898, 903 ],
// "1|0" : [ 262, 290, 300, 331, 343, 369, 374, 391, 879, 918, 930 ]
BasicDBObject mongoSamples = new BasicDBObject();
for (Map.Entry<Genotype, List<Integer>> entry : genotypeCodes.entrySet()) {
String genotypeStr = genotypeToStorageType(entry.getKey().toString());
if (longestList != null && entry.getKey().equals(longestList.getKey())) {
mongoSamples.append("def", genotypeStr);
} else {
mongoSamples.append(genotypeStr, entry.getValue());
}
}
return mongoSamples;
}
public void setSamples(List<String> samples) {
int i = 0;
int size = samples == null? 0 : samples.size();
sampleIds = new HashMap<>(size);
idSamples = new HashMap<>(size);
if (samples != null) {
for (String sample : samples) {
sampleIds.put(sample, i);
idSamples.put(i, sample);
i++;
}
}
}
public void setSampleIds(Map<String, Integer> sampleIds) {
this.sampleIds = sampleIds;
this.idSamples = new HashMap<>(sampleIds.size());
for (Map.Entry<String, Integer> entry : sampleIds.entrySet()) {
idSamples.put(entry.getValue(), entry.getKey());
}
assert sampleIds.size() == idSamples.size();
}
private VariantSourceEntry getLegacyNoncompressedSamples(BasicDBObject object) {
VariantSourceEntry variantSourceEntry = new VariantSourceEntry(object.get(FILEID_FIELD).toString(),
object.get(STUDYID_FIELD).toString());
BasicDBObject mongoGenotypes = (BasicDBObject) object.get(SAMPLES_FIELD);
for (Object entry : mongoGenotypes.toMap().entrySet()) {
Map.Entry sample = (Map.Entry) entry;
variantSourceEntry.addSampleData(sample.getKey().toString(), ((DBObject) sample.getValue()).toMap());
}
// for (String sample : samples) {
// Map<String, String> sampleData = ((DBObject) mongoGenotypes.get(sample)).toMap();
// fileWithSamples.addSampleData(sample, sampleData);
// System.out.println("Sample processed: " + sample);
// }
return variantSourceEntry;
}
private DBObject getLegacyNoncompressedSamples(VariantSourceEntry object) {
BasicDBObject mongoSamples = new BasicDBObject();
for (Map.Entry<String, Map<String, String>> entry : object.getSamplesData().entrySet()) {
BasicDBObject sampleData = new BasicDBObject();
for (Map.Entry<String, String> sampleEntry : entry.getValue().entrySet()) {
sampleData.put(sampleEntry.getKey(), sampleEntry.getValue());
}
mongoSamples.put(entry.getKey(), sampleData);
}
return mongoSamples;
}
public static String genotypeToDataModelType(String genotype) {
return genotype.replace("-1", ".");
}
public static String genotypeToStorageType(String genotype) {
return genotype.replace(".", "-1");
}
}
|
#!/usr/bin/python3
import sys
import json
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('RESULT', help='chainer result file')
parser.add_argument('--data',default="main/loss",
help='source sentence list for validation')
parser.add_argument('--cmd',default="max min avg",
help='data pickup command')
args = parser.parse_args()
log_file = json.load(open(args.RESULT))
data = list(map(lambda x:x[args.data] , log_file ))
cmds = args.cmd.split(" ")
for cmd in cmds:
value = 0
if cmd == "max":
value = max(data)
if cmd == "min":
value = min(data)
if cmd == "avg":
value = sum(data)/len(data)
print(cmd+":\t"+str(value))
|
<gh_stars>1-10
import { addedItemId, fakeItemList, fakeUser, newItemListAfterAddingNewItem } from '../../../test/fake-data'
export function fetchIdsByType(type) {
return Promise.resolve(Object.keys(fakeItemList))
}
export function fetchItem (id) {
return Promise.resolve(fakeItemList[id])
}
export function watchList (type, cb) {
cb(newItemListAfterAddingNewItem)
}
export function fetchItems (ids) {
return Promise.all(ids.map(id => fetchItem(id)))
}
export function fetchUser (id) {
if (id === fakeUser.id) return Promise.resolve(fakeUser)
return Promise.reject('User not found')
}
|
#!/bin/bash
set -e
export SHELLOPTS
# prepare gitbook
./node_modules/.bin/gitbook install
# all files to the same date to reduce the amount of updated files after each new generation
touch -t 201811111111.11 workshop/*
# patch gitbook so START_TIME remains the same in the generated html
#sed -i 's/var START_TIME = new Date();/var START_TIME = new Date(2018, 10, 11, 11, 11, 11);/g' ~/.gitbook/versions/3.2.3/lib/gitbook.js
# build the book
./node_modules/.bin/gitbook build
|
<gh_stars>1-10
import home from "./components/home"
export default [{
path: '/',
component: home,
name: 'home',
// beforeEnter(to, from, next) {
// if (!localStorage.getItem('inventory')) {
// next();
// } else {
// next('/sales');
// }
// }
}]
|
/**
* @file CCFScrollableTabViewDelegate.h
* @author <NAME> (www.cocoafactory.com)
*
* @date 2012-03-09 04:21:30
* @version 1.0
*
* @note Copyright 2011 Cocoa Factory, LLC. All rights reserved
*/
@class CCFScrollableTabView;
/** CCFScrollableTabViewDelegate
This protocol describes the required methods that delegates of CCFScrollableTabView must implement
*/
@protocol CCFScrollableTabViewDelegate <NSObject>
/** Item selection
This method notifies that the delegate of CCFScrollableTabView that an item was selected
@param tabView The CCFScrollableTabView instance that is sending the message
@param index The index of the item that was selected.
*/
- (void)scrollableTabView:(CCFScrollableTabView *)tabView didSelectItemAtIndex:(NSInteger)index;
@end
|
function sumOfEvenPages($startPage, $endPage) {
$sum = 0;
// Adjust startPage if it's odd to include the first even page
if ($startPage % 2 != 0) {
$startPage++;
}
// Calculate the sum of even pages within the range
for ($i = $startPage; $i <= $endPage; $i += 2) {
$sum += $i;
}
return $sum;
}
// Test the function
$startPage = 3;
$endPage = 8;
echo sumOfEvenPages($startPage, $endPage); // Output: 20
|
#!/bin/bash
python TrainLogSpiral.py --batch_size=4096 --Vec_loss=1 --q_entropy=0.1 --lr=0.01 --save_dir='./output/0203/Fold4' --device='2' --epochs=200 --wandb --Foldstart=4 --Foldend=8 --data_path='./data/Multi_2dim_log_spiral'
python TrainLogSpiral.py --batch_size=3072 --Vec_loss=1 --q_entropy=0.1 --lr=0.01 --save_dir='./output/0203/Fold3' --device='2' --epochs=200 --wandb --Foldstart=5 --Foldend=8 --data_path='./data/Multi_2dim_log_spiral'
python TrainLogSpiral.py --batch_size=2048 --Vec_loss=1 --q_entropy=0.1 --lr=0.01 --save_dir='./output/0203/Fold2' --device='2' --epochs=200 --wandb --Foldstart=6 --Foldend=8 --data_path='./data/Multi_2dim_log_spiral'
python TrainLogSpiral.py --batch_size=1024 --Vec_loss=1 --q_entropy=0.1 --lr=0.01 --save_dir='./output/0203/Fold1' --device='2' --epochs=200 --wandb --Foldstart=7 --Foldend=8 --data_path='./data/Multi_2dim_log_spiral'
|
#!/usr/bin/env bash
#
# Copyright 2012 HellaSec, LLC
#
# 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.
#
# ==== env.sh ====
#
# defines some shell variables
#
# $DIR is the absolute path for the directory containing this bash script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source $DIR/../../../dependencies/env.sh
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SOLR_LOCAL_PATH=$SOLR_LOCAL_PATH_TOMCAT
export SOLR_HOME="$SOLR_LOCAL_PATH/example/solr"
SOLR_DATA_DIR="$SOLR_HOME/data"
|
# The name of this experiment.
name=$2
# Save logs and models under snap/gqa; make backup.
output=/storage/$name
mkdir -p $output/src
cp -r src/* $output/src/
cp $0 $output/run.bash
# See Readme.md for option details.
CUDA_VISIBLE_DEVICES=$1 PYTHONPATH=$PYTHONPATH:./src \
python src/tasks/gqa.py \
--train train,valid --valid testdev \
--llayers 9 --xlayers 5 --rlayers 5 \
--loadLXMERTQA /pretrain/model \
--batchSize 32 --optim bert --lr 1e-5 --epochs 4 \
--tqdm --output $output ${@:3} \
--adv_training \
--adv_modality ["text"] \
--adv_lr_txt 1e-2 \
--adv_lr_img 1e-2 \
--adv_steps 3 \
--adv_init_mag 0 \
--norm_type l2 \
--adv_max_norm 0 \
--adv_kl_weight 1.5
|
<reponame>javisantos/paseto<filename>lib/v2/decrypt.js
const { 'xchacha20-poly1305-decrypt': decrypt } = require('../help/crypto_worker')
const { decode } = require('../help/base64url')
const { PasetoDecryptionFailed, PasetoInvalid } = require('../errors')
const assertPayload = require('../help/assert_payload')
const checkKey = require('../help/symmetric_key_check').bind(undefined, 'v2.local')
const pae = require('../help/pae')
const parse = require('../help/parse_paseto_payload')
const h = 'v2.local.'
module.exports = async function v2Decrypt (token, key, { complete = false, ...options } = {}) {
if (typeof token !== 'string') {
throw new TypeError(`token must be a string, got: ${typeof token}`)
}
key = checkKey(key)
if (token.substr(0, h.length) !== h) {
throw new PasetoInvalid('token is not a v2.local PASETO')
}
const { 0: b64, 1: b64f = '', length } = token.substr(h.length).split('.')
if (length > 2) {
throw new PasetoInvalid('token value is not a PASETO formatted value')
}
const f = decode(b64f)
const raw = decode(b64)
const n = raw.slice(0, 24)
const c = raw.slice(24)
const k = key.export()
const preAuth = pae(h, n, f)
let payload = await decrypt(c, n, k, preAuth)
if (!payload) {
throw new PasetoDecryptionFailed('decryption failed')
}
payload = parse(payload)
assertPayload(options, payload)
if (complete) {
return { payload, footer: f.length ? f : undefined, version: 'v2', purpose: 'local' }
}
return payload
}
|
<filename>src/gui/file_views/SearchBar.cpp
/**
* @author <NAME> <<EMAIL>>
*
* @section LICENSE
* See LICENSE for more informations.
*
*/
#include <QIcon>
#include "SearchBar.h"
#include "ui_SearchBar.h"
SearchBar::SearchBar(QWidget *parent) :
QFrame(parent),
ui(new Ui::SearchBar)
{
ui->setupUi(this);
initActions();
setResultNumberAndCount(0, 0);
createConnections();
}
SearchBar::~SearchBar()
{
delete ui;
}
int SearchBar::resultNumber() const
{
return ui->resultLabel->text().toInt();
}
void SearchBar::setResultNumber(int number)
{
ui->resultLabel->setText(QString::number(number));
}
int SearchBar::resultCount() const
{
return ui->resultCountLabel->text().toInt();
}
void SearchBar::setResultCount(int count)
{
ui->resultCountLabel->setText(QString::number(count));
}
void SearchBar::setResultNumberAndCount(int number, int count)
{
setResultNumber(number);
setResultCount(count);
}
void SearchBar::startSearch(const QString &text)
{
ui->searchLineEdit->setText(text);
on_searchButton_clicked();
}
void SearchBar::textEdited(const QString &text)
{
if (text.isEmpty()) {
emit searchCleared();
}
}
void SearchBar::on_searchButton_clicked()
{
emit searchTriggered(ui->searchLineEdit->text(),
(ui->caseCheckBox->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive));
}
void SearchBar::on_nextResultButton_clicked()
{
emit gotoNextResult();
}
void SearchBar::on_previousResultButton_clicked()
{
emit gotoPreviousResult();
}
void SearchBar::createConnections()
{
connect(ui->firstResultButton, &QToolButton::clicked,
this, &SearchBar::gotoFirstResult);
connect(ui->lastResultButton, &QToolButton::clicked,
this, &SearchBar::gotoLastResult);
connect(ui->searchLineEdit, &QLineEdit::textEdited,
this, &SearchBar::textEdited);
}
void SearchBar::initActions()
{
// Find next
QKeySequence findNextShortcut(QKeySequence::FindNext);
QAction *findNextAction = new QAction(QIcon("://resources/icons/actions/go-down.png"),
tr("Go to next result %1").arg(findNextShortcut.toString()),
this);
findNextAction->setShortcut(findNextShortcut);
ui->nextResultButton->setDefaultAction(findNextAction);
connect(findNextAction, &QAction::triggered,
this, &SearchBar::on_nextResultButton_clicked);
// Find previous
QKeySequence findPreviousShortcut(QKeySequence::FindPrevious);
QAction *findPreviousAction = new QAction(QIcon("://resources/icons/actions/go-up.png"),
tr("Go to previous result %1").arg(findPreviousShortcut.toString()),
this);
findPreviousAction->setShortcut(findPreviousShortcut);
ui->previousResultButton->setDefaultAction(findPreviousAction);
connect(findPreviousAction, &QAction::triggered,
this, &SearchBar::on_previousResultButton_clicked);
}
|
package com.ibm.socialcrm.notesintegration.files.utils;
/****************************************************************
* IBM OpenSource
*
* (C) Copyright IBM Corp. 2012
*
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
***************************************************************/
import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.commons.json.JSONObject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import com.ibm.socialcrm.notesintegration.core.ConnectionsDocument;
import com.ibm.socialcrm.notesintegration.core.utils.AbderaConnectionsFileOperations;
import com.ibm.socialcrm.notesintegration.core.utils.SugarWebservicesOperations;
import com.ibm.socialcrm.notesintegration.files.FilesPluginActivator;
import com.ibm.socialcrm.notesintegration.ui.custom.SFAMessageDialogWithHyperlink;
import com.ibm.socialcrm.notesintegration.utils.ConstantStrings;
import com.ibm.socialcrm.notesintegration.utils.GenericUtils;
import com.ibm.socialcrm.notesintegration.utils.SFAImageManager;
import com.ibm.socialcrm.notesintegration.utils.UtilsPlugin;
import com.ibm.socialcrm.notesintegration.utils.UtilsPluginNLSKeys;
public class DocumentDownloadOperations {
public final static int DOCUMENT_DOWNLOAD_OPEN = 1;
public final static int DOCUMENT_DOWNLOAD_SAVE = 2;
private final static int Forbidden_403 = 403;
private int _option = 0;
private ConnectionsDocument _cd = null;
private File _targetFile = null;
public DocumentDownloadOperations(int option, ConnectionsDocument cd) {
_option = option;
_cd = cd;
}
public void toExecute() {
if (_option == DOCUMENT_DOWNLOAD_OPEN || _option == DOCUMENT_DOWNLOAD_SAVE) {
boolean isOK = toDownloadFile();
if (!isOK && isUnauthorized()) {
// call download validation API
String output = SugarWebservicesOperations.getInstance().validateDownload(_cd.getSugarId());
isOK = isDownloadValidated(output);
if (isOK) {
isOK = toDownloadFile();
} else {
return;
}
}
if (isOK) {
if (_option == DOCUMENT_DOWNLOAD_OPEN) {
try {
Desktop.getDesktop().open(_targetFile);
} catch (Exception e) {
e.printStackTrace();
}
// _targetFile.deleteOnExit();
}
} else {
StringBuffer sb = new StringBuffer(ConstantStrings.EMPTY_STRING);
sb.append(UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.DOCUMENTS_DOWNLAOD_FAILED)).append(ConstantStrings.LEFT_PARENTHESIS).append(
AbderaConnectionsFileOperations._downloadStatus).append(ConstantStrings.RIGHT_PARENTHESIS);
final String msg = sb.toString();
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
SFAMessageDialogWithHyperlink.open(UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.DOCUMENTS_DOWNLOAD_ERROR_TITLE), SFAImageManager
.getImage(SFAImageManager.SALES_CONNECT), msg);
}
});
}
}
}
private boolean isUnauthorized() {
boolean isUnauthorized = false;
if (AbderaConnectionsFileOperations._downloadStatus == Forbidden_403) {
isUnauthorized = true;
}
return isUnauthorized;
}
public boolean buildTargetFile() {
boolean isOK = true;
String directory = null;
if (_option == DOCUMENT_DOWNLOAD_SAVE) {
DirectoryDialog dd = new DirectoryDialog(Display.getDefault().getActiveShell(), SWT.NONE);
directory = dd.open();
} else if (_option == DOCUMENT_DOWNLOAD_OPEN) {
directory = GenericUtils.getUniqueTempDir();
}
if (directory != null) {
File dir = new File(directory);
if (!dir.exists()) {
dir.mkdirs();
}
_targetFile = new File(directory, _cd.getFilename());
} else {
isOK = false;
}
return isOK;
}
private boolean toDownloadFile() {
boolean isOK = false;
AbderaConnectionsFileOperations._downloadStatus = 0;
InputStream in = null;
FileOutputStream out = null;
try {
in = AbderaConnectionsFileOperations.downloadFile(_cd.getDocUrl());
if (in != null) {
out = new FileOutputStream(_targetFile);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
out.close();
isOK = true;
}
} catch (Exception e) {
UtilsPlugin.getDefault().logException(e, FilesPluginActivator.PLUGIN_ID);
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (Exception e) {
// Eat it
}
}
return isOK;
}
private boolean isDownloadValidated(String output) {
boolean isOK = false;
if (output != null && !output.equals(ConstantStrings.EMPTY_STRING)) {
try {
JSONObject jsonObject = new JSONObject(output);
boolean isTrueResponse = jsonObject.getBoolean("response"); //$NON-NLS-1$
int errorCode = jsonObject.getInt("code"); //$NON-NLS-1$
String errorMsg = jsonObject.getString("message"); //$NON-NLS-1$
if (isTrueResponse) {
isOK = true;
} else {
StringBuffer sb = new StringBuffer(ConstantStrings.EMPTY_STRING);
// not authorized, but no fancy message from API
if (errorCode == 0) {
sb.append(UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.DOCUMENTS_DOWNLAOD_NOT_AUTHORIZED));
} else
// error from our API
if (errorCode < 0) {
sb.append(UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.DOCUMENTS_DOWNLAOD_FAILED)).append(ConstantStrings.LEFT_PARENTHESIS).append(errorCode).append(
ConstantStrings.RIGHT_PARENTHESIS);
} else
{
sb.append(errorMsg).append(ConstantStrings.LEFT_PARENTHESIS).append(errorCode).append(ConstantStrings.RIGHT_PARENTHESIS);
}
final String msg = sb.toString();
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
SFAMessageDialogWithHyperlink.open(UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.DOCUMENTS_DOWNLOAD_ERROR_TITLE), SFAImageManager
.getImage(SFAImageManager.SALES_CONNECT), msg);
}
});
}
} catch (Exception e) {
UtilsPlugin.getDefault().logException(e, FilesPluginActivator.PLUGIN_ID);
}
}
return isOK;
}
}
|
<reponame>Davidniw/chain-service<gh_stars>0
package blockchain
import (
fcutil "github.com/hyperledger/fabric-sdk-go/pkg/util"
api "github.com/hyperledger/fabric-sdk-go/api"
"fmt"
)
// QueryHello query the chaincode to get the state of hello
func (setup *FabricSetup) QueryHello() (string, error) {
// Prepare arguments
var args []string
args = append(args, "invoke")
args = append(args, "query")
args = append(args, "hello")
// Make the proposal and submit it to the network (via our primary peer)
transactionProposalResponses, _, err := fcutil.CreateAndSendTransactionProposal(
setup.Channel,
setup.ChaincodeId,
setup.ChannelId,
args,
[]api.Peer{setup.Channel.GetPrimaryPeer()}, // Peer contacted when submitted the proposal
nil,
)
if err != nil {
return "", fmt.Errorf("Create and send transaction proposal return error in the query hello: %v", err)
}
var arrayLength = len(transactionProposalResponses)
var test = transactionProposalResponses[arrayLength - 1].ProposalResponse.GetResponse().Payload
fmt.Println("transactionProposalResponses: ",test)
return string(transactionProposalResponses[0].ProposalResponse.GetResponse().Payload), nil
}
|
<gh_stars>1-10
import React from 'react';
import {
Card,
CardBody,
CardHeader,
Row,
Col,
TabContent,
TabPane,
CardTitle,
CardText,
Nav,
NavItem,
NavLink,
ListGroupItem,
FormGroup,
Label,
Input,
Form,
Badge,
Button,
Table,
} from 'reactstrap';
import Page from 'components/Page';
class generateTickets extends React.Component {
render() {
return (
<Page
title="Generate Tickets"
breadcrumbs={[{ name: 'generateTickets', active: true }]}>
<Row>
<Col >
<Card>
<CardHeader>Create New</CardHeader>
<CardBody>
<Form check inline>
<FormGroup check>
<Label >Subject:</Label>
<Col >
<Input size="35"
type="text"
name="name"
placeholder="Enter Project Name"
/>
</Col>
</FormGroup>
<FormGroup check>
<Label >Project:</Label>
<Col>
<Input
type="select"
name="selectProject"
>
<option>Facebook</option>
<option>Twitter</option>
<option>Instagram</option>
<option>Linkedin</option>
</Input>
</Col>
</FormGroup>
<FormGroup check>
<Label>Add Attachment:</Label>
<Input
type="file"
name="file"
/>
</FormGroup>
<FormGroup >
<Button>Submit</Button>
</FormGroup>
</Form>
</CardBody>
</Card>
</Col>
</Row>
<Row>
<Col>
<Card>
<CardHeader>Support Tickets</CardHeader>
<CardBody>
<Table hover>
<thead>
<tr>
<th>REF #</th>
<th>Ticket</th>
<th>Project</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>TCK-000005</td>
<td>Installation issue</td>
<td>Scrum</td>
<td><Badge color="warning" className="mr-1">new</Badge></td>
</tr>
<tr>
<td>TCK-000001</td>
<td>Server Error</td>
<td>Facebook</td>
<td><Badge color="warning" className="mr-1">new</Badge></td>
</tr>
<tr>
<td>TCK-000003</td>
<td>Sample</td>
<td>Twitter</td>
<td><Badge color="success" className="mr-1">Done</Badge></td>
</tr>
<tr>
<td>TCK-000009</td>
<td>Installation issue</td>
<td>Linkedin</td>
<td><Badge color="warning" className="mr-1">New</Badge></td>
</tr>
<tr>
<td>TCK-000007</td>
<td>Server Error</td>
<td>Scrum</td>
<td><Badge color="success" className="mr-1">Done</Badge></td>
</tr>
</tbody>
</Table>
</CardBody>
</Card>
</Col>
</Row>
</Page>
);
}
}
export default generateTickets;
|
#!/bin/sh
python3 /app/training.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt normalize
python3 /app/training.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt -n "stemming_" normalize stemm -l "en"
python3 /app/training.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt -n "lemming_" normalize lemm -l "en"
python3 /app/training.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt -n "stopwords_" normalize stopwords -l "res/custom_en_stopwords.txt"
python3 /app/training.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt -n "stopwords_stemming_" normalize stopwords -l "res/custom_en_stopwords.txt" stemm -l "en"
python3 /app/training.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt -n "stopwords_lemming_" normalize stopwords -l "res/custom_en_stopwords.txt" lemm -l "en"
python3 /app/training_w2v.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt normalize
python3 /app/training_w2v.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt -n "stemming_" normalize stemm -l "en"
python3 /app/training_w2v.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt -n "lemming_" normalize lemm -l "en"
python3 /app/training_w2v.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt -n "stopwords_" normalize stopwords -l "res/custom_en_stopwords.txt"
python3 /app/training_w2v.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt -n "stopwords_stemming_" normalize stopwords -l "res/custom_en_stopwords.txt" stemm -l "en"
python3 /app/training_w2v.py -w /mnt/data/raw/wiki/en/ -q /mnt/data/raw/stackexchange_questions.txt -n "stopwords_lemming_" normalize stopwords -l "res/custom_en_stopwords.txt" lemm -l "en"
|
<reponame>AmanPriyanshu/Bavardez
import pandas as pd
import numpy as np
import json
PATH = './config/'
def read_all_intents():
df = pd.read_csv(PATH+'intents.csv')
intents = df.to_dict('dict')
intents = {key: [i for i in list(value.values()) if str(i)!='nan'] for key, value in intents.items()}
return intents
def read_all_responses():
df = pd.read_csv(PATH+'responses.csv')
responses = df.to_dict('dict')
responses = {key: [i for i in list(value.values()) if str(i)!='nan'] for key, value in responses.items()}
return responses
def initialize():
df = pd.DataFrame(list())
df.to_csv(PATH+'intents.csv', index=False)
df.to_csv(PATH+'responses.csv', index=False)
def create_new_intent():
intent = input("Enter input Title of Intent:\t")
patterns = []
flag = True
while(flag):
pattern = input("Enter pattern examples (enter -1 to stop):\t")
if(pattern == "-1"):
flag = False
else:
patterns.append(pattern)
print("\nNow recording responses...\n")
responses = []
flag = True
while(flag):
response = input("Enter response examples (enter -1 to stop):\t")
if(response == '-1'):
flag = False
else:
responses.append(response)
print("\nCompleted and Saved both Intents and Responses.")
return intent, patterns, responses
def main_intent_initializer():
while(1):
choice = int(input("Enter:\n\t0. If you wish to initialize all the intents.\n\t1. If you wish to add another intent.\n\t2. If you wish to edit one of the intents.\nChoice:\t"))
if choice == 0:
initialize()
intent, patterns, responses = create_new_intent()
patterns = pd.DataFrame({intent: patterns})
responses = pd.DataFrame({intent: responses})
patterns.to_csv(PATH+'intents.csv', index=False)
responses.to_csv(PATH+'responses.csv', index=False)
elif choice == 1:
df_intents = read_all_intents()
df_responses = read_all_responses()
intent, patterns, responses = create_new_intent()
df_intents.update({intent: patterns})
df_responses.update({intent: responses})
df_responses = pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in df_responses.items() ]))
df_intents = pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in df_intents.items() ]))
df_intents.to_csv(PATH+'intents.csv', index=False)
df_responses.to_csv(PATH+'responses.csv', index=False)
elif choice == 2:
df_intents = read_all_intents()
df_responses = read_all_responses()
print("KEYS: "+str(list(df_intents.keys())))
else:
print("Closing MENU")
break
print("\n\n")
def generate_json():
"""
To be Completed.
"""
df_intents = read_all_intents()
df_responses = read_all_responses()
pass
if __name__ == '__main__':
main_intent_initializer()
|
<gh_stars>100-1000
import * as jsep from 'jsep';
import { Expression } from 'jsep';
export const name: string;
export function init(this: typeof jsep): void;
export interface NewExpression extends Expression {
type: 'NewExpression';
arguments: Expression[];
callee: Expression;
}
|
/*
* Copyright 2019 NAVER Corp.
*
* 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 com.navercorp.pinpoint.profiler.sender.grpc;
import com.navercorp.pinpoint.grpc.client.ChannelFactoryOption;
import com.google.protobuf.Empty;
import com.navercorp.pinpoint.grpc.trace.PSpan;
import com.navercorp.pinpoint.grpc.trace.PSpanChunk;
import com.navercorp.pinpoint.grpc.trace.PSpanMessage;
import com.navercorp.pinpoint.grpc.trace.SpanGrpc;
import com.navercorp.pinpoint.profiler.context.thrift.MessageConverter;
import com.google.protobuf.GeneratedMessageV3;
import io.grpc.stub.StreamObserver;
import static com.navercorp.pinpoint.grpc.MessageFormatUtils.debugLog;
/**
* @author jaehong.kim
*/
public class SpanGrpcDataSender extends GrpcDataSender {
private final SpanGrpc.SpanStub spanStub;
private final ExecutorAdaptor reconnectExecutor;
private volatile StreamObserver<PSpanMessage> spanStream;
private final Reconnector spanStreamReconnector;
public SpanGrpcDataSender(String host, int port, int executorQueueSize, MessageConverter<GeneratedMessageV3> messageConverter, ChannelFactoryOption channelFactoryOption) {
super(host, port, executorQueueSize, messageConverter, channelFactoryOption);
this.spanStub = SpanGrpc.newStub(managedChannel);
this.reconnectExecutor = newReconnectExecutor();
{
final Runnable spanStreamReconnectJob = new Runnable() {
@Override
public void run() {
spanStream = newSpanStream();
}
};
this.spanStreamReconnector = new ReconnectAdaptor(reconnectExecutor, spanStreamReconnectJob);
this.spanStream = newSpanStream();
}
}
private ExecutorAdaptor newReconnectExecutor() {
return new ExecutorAdaptor(GrpcDataSender.reconnectScheduler);
}
private StreamObserver<PSpanMessage> newSpanStream() {
StreamId spanId = StreamId.newStreamId("span");
ResponseStreamObserver<PSpanMessage, Empty> responseStreamObserver = new ResponseStreamObserver<PSpanMessage, Empty>(spanId, spanStreamReconnector);
return spanStub.sendSpan(responseStreamObserver);
}
public boolean send0(Object data) {
final GeneratedMessageV3 message = messageConverter.toMessage(data);
if (logger.isDebugEnabled()) {
logger.debug("Send message={}", debugLog(message));
}
if (message instanceof PSpanChunk) {
final PSpanChunk spanChunk = (PSpanChunk) message;
final PSpanMessage spanMessage = PSpanMessage.newBuilder().setSpanChunk(spanChunk).build();
spanStream.onNext(spanMessage);
return true;
}
if (message instanceof PSpan) {
final PSpan pSpan = (PSpan) message;
final PSpanMessage spanMessage = PSpanMessage.newBuilder().setSpan(pSpan).build();
spanStream.onNext(spanMessage);
return true;
}
throw new IllegalStateException("unsupported message " + data);
}
@Override
public void stop() {
logger.info("spanStream.close()");
StreamUtils.close(this.spanStream);
super.stop();
}
}
|
while [ true ] ; do curl -X POST http://192.168.33.22:8080/function/figlet -d '-=< PKS >=-' ; done
|
<gh_stars>1-10
//
// Copyright 2021 <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.
//
#include "age_gb_lcd_palettes.hpp"
namespace
{
void set_colors(std::array<age::pixel, 4>& colors, int color00, int color01, int color10, int color11)
{
colors = {age::pixel(color00), age::pixel(color01), age::pixel(color10), age::pixel(color11)};
}
bool is_nintendo_rom(const uint8_t* rom_header)
{
int licensee = rom_header[0x14B];
if (licensee == 0x33)
{
return (rom_header[0x144] == '0') && (rom_header[0x145] == '1');
}
return licensee == 0x01;
}
//!
//! Initialize Game Boy Color palettes for classic roms.
//! Based on:
//! https://tcrf.net/Notes:Game_Boy_Color_Bootstrap_ROM#Assigned_Palette_Configurations
//! https://web.archive.org/web/20170830061747/http://www.vcfed.org/forum/showthread.php?19247-Disassembling-the-GBC-Boot-ROM&p=128734
//!
void init_dmg_colors(std::array<age::pixel, 4>& bgp,
std::array<age::pixel, 4>& obp0,
std::array<age::pixel, 4>& obp1,
const age::uint8_t* rom_header)
{
uint8_t rom_name_hash = 0;
if (is_nintendo_rom(rom_header))
{
for (int i = 0x134; i <= 0x143; ++i)
{
rom_name_hash += rom_header[i];
}
}
age::uint8_t rom_name_char4 = rom_header[0x134 + 3];
switch (rom_name_hash)
{
case 0x00: // dummy entry: no Nintendo rom
break;
case 0x01:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
return;
case 0x0C:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x0D:
if (rom_name_char4 == 0x45)
{
set_colors(bgp, 0xFFFFFF, 0x8C8CDE, 0x52528C, 0x000000);
set_colors(obp0, 0xFFC542, 0xFFD600, 0x943A00, 0x4A0000);
obp1 = bgp;
return;
}
if (rom_name_char4 == 0x52)
{
set_colors(bgp, 0xFFFFFF, 0xFFFF00, 0xFF0000, 0x000000);
obp0 = bgp;
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
}
break;
case 0x10:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
return;
case 0x14:
set_colors(bgp, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
obp1 = bgp;
return;
case 0x15:
set_colors(bgp, 0xFFFFFF, 0xFFFF00, 0xFF0000, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x16:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x17:
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
return;
case 0x18:
if (rom_name_char4 == 0x49)
{
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x0063C5, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = obp0;
return;
}
if (rom_name_char4 == 0x4B)
{
set_colors(bgp, 0xFFFFFF, 0x8C8CDE, 0x52528C, 0x000000);
set_colors(obp0, 0xFFC542, 0xFFD600, 0x943A00, 0x4A0000);
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
}
break;
case 0x19:
set_colors(bgp, 0xFFFFFF, 0xFF9C00, 0xFF0000, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = bgp;
return;
case 0x1D:
set_colors(bgp, 0xA59CFF, 0xFFFF00, 0x006300, 0x000000);
set_colors(obp0, 0xFF6352, 0xD60000, 0x630000, 0x000000);
obp1 = bgp;
return;
case 0x27:
if (rom_name_char4 == 0x42)
{
set_colors(bgp, 0xA59CFF, 0xFFFF00, 0x006300, 0x000000);
set_colors(obp0, 0xFF6352, 0xD60000, 0x630000, 0x000000);
set_colors(obp1, 0x0000FF, 0xFFFFFF, 0xFFFF7B, 0x0084FF);
return;
}
if (rom_name_char4 == 0x4E)
{
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
return;
}
break;
case 0x28:
if (rom_name_char4 == 0x41)
{
set_colors(bgp, 0x000000, 0x008484, 0xFFDE00, 0xFFFFFF);
obp0 = bgp;
obp1 = bgp;
return;
}
if (rom_name_char4 == 0x46)
{
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x4A0000);
obp1 = obp0;
return;
}
break;
case 0x29:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
return;
case 0x34:
set_colors(bgp, 0xFFFFFF, 0x7BFF00, 0xB57300, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = obp0;
return;
case 0x35:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x36:
set_colors(bgp, 0x52DE00, 0xFF8400, 0xFFFF00, 0xFFFFFF);
set_colors(obp0, 0xFFFFFF, 0xFFFFFF, 0x63A5FF, 0x0000FF);
set_colors(obp1, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
return;
case 0x39:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x4A0000);
obp1 = obp0;
return;
case 0x3C:
set_colors(bgp, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
obp0 = bgp;
set_colors(obp1, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
return;
case 0x3D:
set_colors(bgp, 0xFFFFFF, 0x52FF00, 0xFF4200, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = bgp;
return;
case 0x3E:
set_colors(bgp, 0xFFFFFF, 0xFF9C00, 0xFF0000, 0x000000);
obp0 = bgp;
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
case 0x3F:
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x0063C5, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = obp0;
return;
case 0x43:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x4A0000);
obp1 = obp0;
return;
case 0x46:
if (rom_name_char4 == 0x45)
{
set_colors(bgp, 0xB5B5FF, 0xFFFF94, 0xAD5A42, 0x000000);
set_colors(obp0, 0x000000, 0xFFFFFF, 0xFF8484, 0x943A3A);
obp1 = bgp;
return;
}
if (rom_name_char4 == 0x52)
{
set_colors(bgp, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
set_colors(obp0, 0xFFFF00, 0xFF0000, 0x630000, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
return;
}
break;
case 0x49:
set_colors(bgp, 0xA59CFF, 0xFFFF00, 0x006300, 0x000000);
set_colors(obp0, 0xFF6352, 0xD60000, 0x630000, 0x000000);
set_colors(obp1, 0x0000FF, 0xFFFFFF, 0xFFFF7B, 0x0084FF);
return;
case 0x4B:
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x4A0000);
obp1 = obp0;
return;
case 0x4E:
set_colors(bgp, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
set_colors(obp1, 0xFFFFFF, 0xFFFF7B, 0x0084FF, 0xFF0000);
return;
case 0x52:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
return;
case 0x58:
set_colors(bgp, 0xFFFFFF, 0xA5A5A5, 0x525252, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x59:
set_colors(bgp, 0xFFFFFF, 0xADAD84, 0x42737B, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF7300, 0x944200, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
case 0x5C:
set_colors(bgp, 0xA59CFF, 0xFFFF00, 0x006300, 0x000000);
set_colors(obp0, 0xFF6352, 0xD60000, 0x630000, 0x000000);
set_colors(obp1, 0x0000FF, 0xFFFFFF, 0xFFFF7B, 0x0084FF);
return;
case 0x5D:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
return;
case 0x61:
if (rom_name_char4 == 0x41)
{
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
return;
}
if (rom_name_char4 == 0x45)
{
set_colors(bgp, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = bgp;
return;
}
break;
case 0x66:
if (rom_name_char4 == 0x45)
{
set_colors(bgp, 0xFFFFFF, 0x7BFF00, 0xB57300, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = obp0;
return;
}
if (rom_name_char4 == 0x4C)
{
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x0063C5, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = obp0;
return;
}
break;
case 0x67:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x68:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
return;
case 0x69:
set_colors(bgp, 0xFFFFFF, 0xFFFF00, 0xFF0000, 0x000000);
obp0 = bgp;
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
case 0x6A:
if (rom_name_char4 == 0x49)
{
set_colors(bgp, 0xFFFFFF, 0x52FF00, 0xFF4200, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = bgp;
return;
}
if (rom_name_char4 == 0x4B)
{
set_colors(bgp, 0xFFFFFF, 0x8C8CDE, 0x52528C, 0x000000);
set_colors(obp0, 0xFFC542, 0xFFD600, 0x943A00, 0x4A0000);
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
}
break;
case 0x6B:
set_colors(bgp, 0xFFFFFF, 0x8C8CDE, 0x52528C, 0x000000);
set_colors(obp0, 0xFFC542, 0xFFD600, 0x943A00, 0x4A0000);
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
case 0x6D:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
return;
case 0x6F:
set_colors(bgp, 0xFFFFFF, 0xFFCE00, 0x9C6300, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x70:
set_colors(bgp, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x00FF00, 0x318400, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
return;
case 0x71:
set_colors(bgp, 0xFFFFFF, 0xFF9C00, 0xFF0000, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x75:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x86:
set_colors(bgp, 0xFFFF9C, 0x94B5FF, 0x639473, 0x003A3A);
set_colors(obp0, 0xFFC542, 0xFFD600, 0x943A00, 0x4A0000);
set_colors(obp1, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
return;
case 0x88:
set_colors(bgp, 0xA59CFF, 0xFFFF00, 0x006300, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x8B:
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
return;
case 0x8C:
set_colors(bgp, 0xFFFFFF, 0xADAD84, 0x42737B, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF7300, 0x944200, 0x000000);
obp1 = bgp;
return;
case 0x90:
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x4A0000);
obp1 = obp0;
return;
case 0x92:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x95:
set_colors(bgp, 0xFFFFFF, 0x52FF00, 0xFF4200, 0x000000);
obp0 = bgp;
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
case 0x97:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x4A0000);
obp1 = obp0;
return;
case 0x99:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0x9A:
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x4A0000);
obp1 = obp0;
return;
case 0x9C:
set_colors(bgp, 0xFFFFFF, 0x8C8CDE, 0x52528C, 0x000000);
obp0 = bgp;
set_colors(obp1, 0xFFC542, 0xFFD600, 0x943A00, 0x4A0000);
return;
case 0x9D:
set_colors(bgp, 0xFFFFFF, 0x8C8CDE, 0x52528C, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
set_colors(obp1, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
return;
case 0xA2:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
return;
case 0xA5:
if (rom_name_char4 == 0x41)
{
set_colors(bgp, 0x000000, 0x008484, 0xFFDE00, 0xFFFFFF);
obp0 = bgp;
obp1 = bgp;
return;
}
if (rom_name_char4 == 0x52)
{
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x7BFF31, 0x008400, 0x4A0000);
obp1 = obp0;
return;
}
break;
case 0xA8:
set_colors(bgp, 0xFFFF9C, 0x94B5FF, 0x639473, 0x003A3A);
set_colors(obp0, 0xFFC542, 0xFFD600, 0x943A00, 0x4A0000);
set_colors(obp1, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
return;
case 0xAA:
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x0063C5, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = bgp;
return;
case 0xB3:
if (rom_name_char4 == 0x42)
{
set_colors(bgp, 0xA59CFF, 0xFFFF00, 0x006300, 0x000000);
set_colors(obp0, 0xFF6352, 0xD60000, 0x630000, 0x000000);
set_colors(obp1, 0x0000FF, 0xFFFFFF, 0xFFFF7B, 0x0084FF);
return;
}
if (rom_name_char4 == 0x52)
{
set_colors(bgp, 0xFFFFFF, 0x52FF00, 0xFF4200, 0x000000);
obp0 = bgp;
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
}
if (rom_name_char4 == 0x55)
{
set_colors(bgp, 0xFFFFFF, 0xADAD84, 0x42737B, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF7300, 0x944200, 0x4A0000);
obp1 = obp0;
return;
}
break;
case 0xB7:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0xBD:
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x4A0000);
obp1 = obp0;
return;
case 0xBF:
if (rom_name_char4 == 0x20)
{
set_colors(bgp, 0xFFFFFF, 0x8C8CDE, 0x52528C, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = bgp;
return;
}
if (rom_name_char4 == 0x43)
{
set_colors(bgp, 0x6BFF00, 0xFFFFFF, 0xFF524A, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFFFFFF, 0x63A5FF, 0x0000FF);
set_colors(obp1, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
return;
}
break;
case 0xC6:
if (rom_name_char4 == 0x20)
{
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x0063C5, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = obp0;
return;
}
if (rom_name_char4 == 0x41)
{
set_colors(bgp, 0xFFFFFF, 0xADAD84, 0x42737B, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF7300, 0x944200, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
}
break;
case 0xC9:
set_colors(bgp, 0xFFFFCE, 0x63EFEF, 0x9C8431, 0x5A5A5A);
set_colors(obp0, 0xFFFFFF, 0xFF7300, 0x944200, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
return;
case 0xCE:
case 0xD1:
set_colors(bgp, 0x6BFF00, 0xFFFFFF, 0xFF524A, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFFFFFF, 0x63A5FF, 0x0000FF);
set_colors(obp1, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
return;
case 0xD3:
if (rom_name_char4 == 0x49)
{
set_colors(bgp, 0xFFFFFF, 0xADAD84, 0x42737B, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
return;
}
if (rom_name_char4 == 0x52)
{
set_colors(bgp, 0xFFFFFF, 0x8C8CDE, 0x52528C, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = bgp;
return;
}
break;
case 0xDB:
set_colors(bgp, 0xFFFFFF, 0xFFFF00, 0xFF0000, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
case 0xE0:
set_colors(bgp, 0xFFFFFF, 0xFF9C00, 0xFF0000, 0x000000);
obp0 = bgp;
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
case 0xE8:
set_colors(bgp, 0x000000, 0x008484, 0xFFDE00, 0xFFFFFF);
obp0 = bgp;
obp1 = bgp;
return;
case 0xF0:
set_colors(bgp, 0x6BFF00, 0xFFFFFF, 0xFF524A, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFFFFFF, 0x63A5FF, 0x0000FF);
set_colors(obp1, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
return;
case 0xF2:
set_colors(bgp, 0xFFFFFF, 0xFFFF00, 0xFF0000, 0x000000);
obp0 = bgp;
set_colors(obp1, 0xFFFFFF, 0x5ABDFF, 0xFF0000, 0x0000FF);
return;
case 0xF4:
if (rom_name_char4 == 0x20)
{
set_colors(bgp, 0xFFFFFF, 0x7BFF00, 0xB57300, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
obp1 = obp0;
return;
}
if (rom_name_char4 == 0x2D)
{
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x0063C5, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
return;
}
break;
case 0xF6:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
return;
case 0xF7:
set_colors(bgp, 0xFFFFFF, 0xFFAD63, 0x843100, 0x000000);
set_colors(obp0, 0xFFFFFF, 0x7BFF31, 0x008400, 0x000000);
set_colors(obp1, 0xFFFFFF, 0x63A5FF, 0x0000FF, 0x000000);
return;
case 0xFF:
set_colors(bgp, 0xFFFFFF, 0xFF9C00, 0xFF0000, 0x000000);
obp0 = bgp;
obp1 = bgp;
return;
default:
break;
}
// default colors
// set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x0063C5, 0x000000);
// set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000);
//
// minor adjustments to be compatible to dmg-acid2.gb on CGB
set_colors(bgp, 0xFFFFFF, 0x7BFF31, 0x0063C6, 0x000000);
set_colors(obp0, 0xFFFFFF, 0xFF8484, 0x943939, 0x000000);
obp1 = obp0;
}
} // namespace
void age::gb_lcd_palettes::init_dmg_colors(const age::uint8_t* rom_header)
{
::init_dmg_colors(m_bgp_colors, m_obp0_colors, m_obp1_colors, rom_header);
}
|
<reponame>PhuongLe/clean-starter
import { IUserRepository } from "../../application/repositories/IUserRepository";
import { Key } from "../../domain/entities/Key";
import { User } from "../../domain/entities/User";
const upnUser = new User({
id: "<EMAIL>",
email: "<EMAIL>",
password: "<PASSWORD>",
challenge: "123456"
})
const tfaDemoUser = new User({
id: "2fa-tester-id",
email: "<EMAIL>",
password: "<PASSWORD>",
challenge: ""
})
var users:User[] = [upnUser, tfaDemoUser];
export default class UserRepository implements IUserRepository {
public async updateUserChallenge(user: User, challenge: string): Promise<void> {
user.challenge = challenge
}
public async loadByEmail(email: string): Promise<User> {
let foundUser = undefined;
users.forEach(user => {
if (user.email == email){
foundUser = user;
}
});
return foundUser;
}
public async addKeyToUser(user: User, key: Key): Promise<void> {
user.key = key;
user.challenge = "";
}
public async loadByChallenge(challenge: string): Promise<User> {
let foundUser = undefined;
users.forEach(user => {
if (user.challenge == challenge){
foundUser = user;
}
});
return foundUser;
}
public async create(email: string, challenge: string): Promise<User> {
let existed = false;
users.forEach(user => {
if (user.email == email){
existed = true;
}
});
if (existed){
return undefined
}
let user = new User({ "email": email, "challenge": challenge })
users.push(user);
return user
}
public async loadByEmailAndPassword(email: string, password: string): Promise<User> {
// tslint:disable-next-line: possible-timing-attack
let foundUser = undefined;
users.forEach(user => {
if (email === user.email && password === user.password){
foundUser = user;
}
});
return foundUser;
}
public async loadById(id: string): Promise<User> {
let foundUser = undefined;
users.forEach(user => {
if (user.id === id){
foundUser = user;
}
});
return foundUser;
}
}
|
<filename>src/com/biniam/designpatterns/chainOfResponsibility/foobarmotorco/GeneralEmailHandler.java
package com.biniam.designpatterns.chainOfResponsibility.foobarmotorco;
/**
* @author <NAME>
*/
public class GeneralEmailHandler extends AbstractEmailHandler {
@Override
protected String[] matchingWords() {
return new String[0]; // match anything
}
@Override
protected void handleHere(String email) {
System.out.println("Email handled by general enquiries.");
}
}
|
import numpy as np
def convert_to_double(y):
cpu_y = np.asarray(y).astype(np.double)
return cpu_y
|
<gh_stars>0
import axios from 'axios';
export const FETCHING_ACTIVITY_START = 'FETCHING_ACTIVITY_START';
export const FETCHING_ACTIVITY_SUCCESS = 'FETCHING_ACTIVITY_SUCCESS';
export const FETCHING_ACTIVITY_FAILURE = 'FETCHING_ACTIVITY_FAILURE';
export const DATE_SELECTED = 'DATE_SELECTED';
export const fetchActivity = () => dispatch => {
dispatch({ type: FETCHING_ACTIVITY_START });
dispatch({ type: DATE_SELECTED, payload: dispatch.date });
var randomDate;
var minYear = 2000;
var maxYear = 2019;
var randomYear = minYear + Math.round(Math.random() * (maxYear - minYear));
var minMonth = 1;
var maxMonth = 12;
var randomMonth = minMonth + Math.round(Math.random() * (maxMonth - minMonth));
var minDay = 1;
var maxDay = 28;
var randomDay = minDay + Math.round(Math.random() * (maxDay - minDay));
randomDate = randomYear + '-' + randomMonth + '-' + randomDay;
axios
.get('https://api.nasa.gov/planetary/apod?date=' + randomDate + '&api_key=' + process.env.REACT_APP_API_KEY)
.then(response => {
console.log('done contacting NASA apod');
console.log(response.data);
dispatch({ type: FETCHING_ACTIVITY_SUCCESS, payload: response.data });
})
.catch(error => {
console.log('done contacting NASA apod');
console.log(error.response);
dispatch({ type: FETCHING_ACTIVITY_FAILURE, payload: error.response });
console.log(error);
});
};
// const thunk = action => next => store => {
// if (typeof action === 'function') {
// action(store.dispatch);
// } else if (typeof action === 'object') {
// next(action);
// }
// };
/*
var minYear = 2000;
var maxYear = 2020;
var randomYear = minYear + Math.round(Math.random() * (maxYear - minYear));
var minMonth = 1;
var maxMonth = 12;
var randomMonth = minMonth + Math.round(Math.random() * (maxMonth - minMonth));
var minDay = 1;
var maxDay = 28;
var randomDay = minDay + Math.round(Math.random() * (maxDay - minDay));
var randomDate = randomYear + '-' + randomMonth + '-' + randomDay;
axios
.get('https://api.nasa.gov/planetary/apod?date=' + randomDate + '&api_key=' + process.env.REACT_APP_API_KEY)
.then(response => {
this.setState({ imgURL: response.data.hdurl });
this.setState({ copyright: response.data.copyright });
this.setState({ date: response.data.date });
this.setState({ explanation: response.data.explanation });
console.log('done contacting NASA apod');
})
.catch(error => {
console.log(error);
});
*/
|
/*
* BDSup2Sub++ (C) 2012 <NAME>.
* Based on code from BDSup2Sub by Copyright 2009 <NAME> (0xdeadbeef)
* and Copyright 2012 <NAME> (mjuhasz)
*
*
* 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.
*/
#include "bitstream.h"
BitStream::BitStream(QVector<uchar> &buffer) :
byteOfs(0),
b(buffer[0] & 0xff),
bits(8),
buf(buffer)
{
}
int BitStream::readBits(int n)
{
int retval = 0;
while (n > 0)
{
// bit by bit
retval <<= 1;
if ((b & 0x80) == 0x80)
{
retval |= 1; // get next bit
}
b <<= 1;
n--;
if (--bits == 0)
{
if (byteOfs < (buf.size() - 1))
{
b = buf[++byteOfs] & 0xff;
bits = 8;
}
else
{
bits = 0;
}
}
}
return retval;
}
void BitStream::syncToByte()
{
if (bits !=8)
{
if (byteOfs < (buf.size() - 1))
{
b = buf[++byteOfs] & 0xff;
bits = 8;
}
else
{
bits = 0;
}
}
}
|
package server
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"sync"
"github.com/aukbit/pluto/v6/common"
"github.com/aukbit/pluto/v6/discovery"
"github.com/aukbit/pluto/v6/server/router"
"github.com/rs/zerolog"
"golang.org/x/net/context"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc"
)
const (
// DefaultName server prefix name
DefaultName = "server"
)
// A Server defines parameters for running an HTTP server.
// The zero value for Server is a valid configuration.
type Server struct {
close chan bool
cfg Config
wg *sync.WaitGroup
httpServer *http.Server
grpcServer *grpc.Server
health *health.Server
logger zerolog.Logger
}
// New returns a new http server with cfg passed in
func New(opts ...Option) *Server {
return newServer(opts...)
}
// newServer will instantiate a new defaultServer with the given config
func newServer(opts ...Option) *Server {
s := &Server{
cfg: newConfig(),
close: make(chan bool),
wg: &sync.WaitGroup{},
health: health.NewServer(),
}
s.logger = zerolog.New(os.Stderr).With().Timestamp().Logger()
if len(opts) > 0 {
s = s.WithOptions(opts...)
}
return s
}
// WithOptions clones the current Client, applies the supplied Options, and
// returns the resulting Client. It's safe to use concurrently.
func (s *Server) WithOptions(opts ...Option) *Server {
for _, opt := range opts {
opt.apply(s)
}
return s
}
// Run Server
func (s *Server) Run(opts ...Option) error {
// set last configs
for _, opt := range opts {
opt.apply(s)
}
s.logger = s.logger.With().Dict("server", zerolog.Dict().
Str("id", s.cfg.ID).
Str("name", s.cfg.Name).
Str("format", s.cfg.Format).
Str("port", s.cfg.Addr),
).Logger()
// register at service discovery
if err := s.register(); err != nil {
return err
}
// start server
if err := s.start(); err != nil {
return err
}
// set health
s.health.SetServingStatus(s.cfg.ID, 1)
// wait for go routines to finish
s.wg.Wait()
s.logger.Warn().Msg(fmt.Sprintf("%s has just exited", s.Name()))
return nil
}
// Stop stops server by sending a message to close the listener via channel
func (s *Server) Stop() {
// set health as not serving
s.health.SetServingStatus(s.cfg.ID, 2)
// close listener
s.close <- true
}
func (s *Server) Health() *healthpb.HealthCheckResponse {
switch s.cfg.Format {
case "grpc":
s.healthGRPC()
default:
s.healthHTTP()
}
hcr, err := s.health.Check(
context.Background(), &healthpb.HealthCheckRequest{Service: s.cfg.ID})
if err != nil {
s.logger.Error().Msg(err.Error())
return &healthpb.HealthCheckResponse{Status: 2}
}
return hcr
}
// Name returns server name
func (s *Server) Name() string {
return s.cfg.Name
}
// Logger returns server logger
func (s *Server) Logger() zerolog.Logger {
return s.logger
}
func (s *Server) setHTTPServer() {
if s.cfg.Mux == nil {
s.cfg.Mux = router.New()
}
// set health check handler
s.cfg.Mux.GET("/_health", router.Wrap(healthHandler))
s.cfg.mu.Lock()
// append logger
s.cfg.Middlewares = append(s.cfg.Middlewares,
loggerMiddleware(s), eidMiddleware(s), serverMiddleware(s),
)
// wrap Middlewares
s.cfg.Mux.WrapperMiddleware(s.cfg.Middlewares...)
s.cfg.mu.Unlock()
// initialize http server
s.httpServer = &http.Server{
// handler to invoke, http.DefaultServeMux if nil
Handler: s.cfg.Mux,
// ReadTimeout is used by the http server to set a maximum duration before
// timing out read of the request. The default timeout is 10 seconds.
ReadTimeout: s.cfg.ReadTimeout,
// WriteTimeout is used by the http server to set a maximum duration before
// timing out write of the response. The default timeout is 10 seconds.
WriteTimeout: s.cfg.WriteTimeout,
TLSConfig: s.cfg.TLSConfig,
}
}
func (s *Server) start() (err error) {
s.logger.Info().Msg(fmt.Sprintf("starting %s %s, listening on %s", s.cfg.Format, s.Name(), s.cfg.Addr))
var ln net.Listener
switch s.cfg.Format {
case "https":
// append strict security header
s.cfg.mu.Lock()
s.cfg.Middlewares = append(s.cfg.Middlewares, strictSecurityHeaderMiddleware())
s.cfg.mu.Unlock()
ln, err = s.listenTLS()
if err != nil {
return err
}
default:
ln, err = s.listen()
if err != nil {
return err
}
}
switch s.cfg.Format {
case "grpc":
s.setGRPCServer()
if err := s.serveGRPC(ln); err != nil {
return err
}
default:
s.setHTTPServer()
if err := s.serve(ln); err != nil {
return err
}
}
// add go routine to WaitGroup
s.wg.Add(1)
go s.waitUntilStop(ln)
return nil
}
// listen based on http.ListenAndServe
// listens on the TCP network address srv.Addr
// If srv.Addr is blank, ":http" is used.
// returns nil or new listener
func (s *Server) listen() (net.Listener, error) {
addr := s.cfg.Addr
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
ln = net.Listener(TCPKeepAliveListener{ln.(*net.TCPListener)})
return ln, nil
}
// listenTLS based on http.ListenAndServeTLS
// listens on the TCP network address srv.Addr
// If srv.Addr is blank, ":https" is used.
// returns nil or new listener
func (s *Server) listenTLS() (net.Listener, error) {
addr := s.cfg.Addr
if addr == "" {
addr = ":https"
}
ln, err := tls.Listen("tcp", addr, s.cfg.TLSConfig)
if err != nil {
return nil, err
}
return ln, nil
}
// serve based on http.ListenAndServe
// calls Serve to handle requests on incoming connections.
// Accepted connections are configured to enable TCP keep-alives.
// serve always returns a non-nil error.
func (s *Server) serve(ln net.Listener) error {
// add go routine to WaitGroup
s.wg.Add(1)
go func(s *Server, ln net.Listener) {
defer s.wg.Done()
if err := s.httpServer.Serve(ln); err != nil {
if err.Error() == errClosing(ln).Error() {
return
}
s.logger.Error().Msg(err.Error())
return
}
}(s, ln)
return nil
}
// errClosing is the currently error raised when we gracefull
// close the listener. If this is the case there is no point to log
func errClosing(ln net.Listener) error {
return fmt.Errorf("accept tcp %v: use of closed network connection", ln.Addr().String())
}
// waitUntilStop waits for close channel
func (s *Server) waitUntilStop(ln net.Listener) {
defer s.wg.Done()
// Waits for call to stop
<-s.close
s.unregister()
switch s.cfg.Format {
case "grpc":
s.grpcServer.GracefulStop()
default:
if err := ln.Close(); err != nil {
s.logger.Error().Msg(err.Error())
}
}
}
// register Server within the service discovery system
func (s *Server) register() error {
if _, ok := s.cfg.Discovery.(discovery.Discovery); ok {
// define service
dse := discovery.Service{
Name: s.cfg.Name,
Address: common.IPaddress(),
Port: s.cfg.Port(),
Tags: []string{s.cfg.ID},
}
// define check
dck := discovery.Check{
Name: fmt.Sprintf("Service '%s' check", s.cfg.Name),
Notes: fmt.Sprintf("Ensure the server is listening on port %s", s.cfg.Addr),
DeregisterCriticalServiceAfter: "10m",
HTTP: fmt.Sprintf("http://%s:9090/_health/server/%s", common.IPaddress(), s.cfg.Name),
Interval: "30s",
Timeout: "1s",
ServiceID: s.cfg.Name,
}
if err := s.cfg.Discovery.Register(discovery.ServicesCfg(dse), discovery.ChecksCfg(dck)); err != nil {
return err
}
}
return nil
}
// unregister Server from the service discovery system
func (s *Server) unregister() error {
if _, ok := s.cfg.Discovery.(discovery.Discovery); ok {
if err := s.cfg.Discovery.Unregister(); err != nil {
return err
}
}
return nil
}
func (s *Server) healthHTTP() {
r, err := http.Get(fmt.Sprintf(`http://localhost:%d/_health`, s.cfg.Port()))
if err != nil {
s.logger.Error().Msg(err.Error())
s.health.SetServingStatus(s.cfg.ID, 2)
return
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
s.logger.Error().Msg(err.Error())
s.health.SetServingStatus(s.cfg.ID, 2)
return
}
defer r.Body.Close()
hcr := &healthpb.HealthCheckResponse{}
if err := json.Unmarshal(b, hcr); err != nil {
s.logger.Error().Msg(err.Error())
s.health.SetServingStatus(s.cfg.ID, 2)
return
}
s.health.SetServingStatus(s.cfg.ID, hcr.Status)
}
func (s *Server) healthGRPC() {
conn, err := grpc.Dial(fmt.Sprintf("localhost:%d", s.cfg.Port()), grpc.WithInsecure())
if err != nil {
s.logger.Error().Msg(err.Error())
s.health.SetServingStatus(s.cfg.ID, 2)
return
}
defer conn.Close()
c := healthpb.NewHealthClient(conn)
hcr, err := c.Check(context.Background(), &healthpb.HealthCheckRequest{Service: s.cfg.ID})
if err != nil {
s.logger.Error().Msg(err.Error())
s.health.SetServingStatus(s.cfg.ID, 2)
return
}
s.health.SetServingStatus(s.cfg.ID, hcr.Status)
}
func (s *Server) setGRPCServer() {
s.cfg.mu.Lock()
// add default interceptors
s.cfg.UnaryServerInterceptors = append(s.cfg.UnaryServerInterceptors,
loggerUnaryServerInterceptor(s),
serverUnaryServerInterceptor(s))
s.cfg.StreamServerInterceptors = append(s.cfg.StreamServerInterceptors,
loggerStreamServerInterceptor(s),
serverStreamServerInterceptor(s))
// initialize grpc server
s.grpcServer = grpc.NewServer(
grpc.UnaryInterceptor(WrapperUnaryServer(s.cfg.UnaryServerInterceptors...)),
grpc.StreamInterceptor(WrapperStreamServer(s.cfg.StreamServerInterceptors...)),
)
s.cfg.mu.Unlock()
// register grpc internal health handlers
healthpb.RegisterHealthServer(s.grpcServer, s.health)
// register grpc handlers
s.cfg.GRPCRegister(s.grpcServer)
}
// serveGRPC serves *grpc.Server
func (s *Server) serveGRPC(ln net.Listener) (err error) {
// add go routine to WaitGroup
s.wg.Add(1)
go func(s *Server, ln net.Listener) {
defer s.wg.Done()
if err := s.grpcServer.Serve(ln); err != nil {
if err.Error() == errClosing(ln).Error() {
return
}
s.logger.Error().Msg(err.Error())
return
}
}(s, ln)
return nil
}
|
package org.larizmen.analysis.domain;
import io.debezium.outbox.quarkus.ExportedEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Value object returned from an Order. Contains the Order aggregate and a List ExportedEvent
*/
public class OrderEventResult {
private Order order;
private List<ExportedEvent<?, ?>> outboxEvents;
private List<OrderTicket> regularTickets;
private List<OrderTicket> virusTickets;
private List<OrderUpdate> orderUpdates;
public OrderEventResult() {
}
public Order getOrder() {
return order;
}
public void addEvent(final ExportedEvent<?, ?> event) {
if (this.outboxEvents == null) {
this.outboxEvents = new ArrayList<>();
}
this.outboxEvents.add(event);
}
public void addUpdate(final OrderUpdate orderUpdate) {
if (this.orderUpdates == null) {
this.orderUpdates = new ArrayList<>();
}
this.orderUpdates.add(orderUpdate);
}
public void addRegularTicket(final OrderTicket orderTicket) {
if (this.regularTickets == null) {
this.regularTickets = new ArrayList<>();
}
this.regularTickets.add(orderTicket);
}
public void addVirusTicket(final OrderTicket orderTicket) {
if (this.virusTickets == null) {
this.virusTickets = new ArrayList<>();
}
this.virusTickets.add(orderTicket);
}
public Optional<List<OrderTicket>> getRegularTickets() {
return Optional.ofNullable(this.regularTickets);
}
public Optional<List<OrderTicket>> getVirusTickets() {
return Optional.ofNullable(this.virusTickets);
}
@Override
public String toString() {
return "OrderEventResult{" +
"order=" + order +
", outboxEvents=" + outboxEvents +
", regularTickets=" + regularTickets +
", virusTickets=" + virusTickets +
", orderUpdates=" + orderUpdates +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OrderEventResult)) return false;
OrderEventResult that = (OrderEventResult) o;
if (getOrder() != null ? !getOrder().equals(that.getOrder()) : that.getOrder() != null) return false;
if (outboxEvents != null ? !outboxEvents.equals(that.outboxEvents) : that.outboxEvents != null) return false;
if (regularTickets != null ? !regularTickets.equals(that.regularTickets) : that.regularTickets != null)
return false;
if (virusTickets != null ? !virusTickets.equals(that.virusTickets) : that.virusTickets != null)
return false;
return orderUpdates != null ? orderUpdates.equals(that.orderUpdates) : that.orderUpdates == null;
}
@Override
public int hashCode() {
int result = getOrder() != null ? getOrder().hashCode() : 0;
result = 31 * result + (outboxEvents != null ? outboxEvents.hashCode() : 0);
result = 31 * result + (regularTickets != null ? regularTickets.hashCode() : 0);
result = 31 * result + (virusTickets != null ? virusTickets.hashCode() : 0);
result = 31 * result + (orderUpdates != null ? orderUpdates.hashCode() : 0);
return result;
}
public List<ExportedEvent<?, ?>> getOutboxEvents() {
return outboxEvents;
}
public void setOutboxEvents(List<ExportedEvent<?, ?>> outboxEvents) {
this.outboxEvents = outboxEvents;
}
public void setRegularTickets(List<OrderTicket> regularTickets) {
this.regularTickets = regularTickets;
}
public void setVirusTickets(List<OrderTicket> virusTickets) {
this.virusTickets = virusTickets;
}
public List<OrderUpdate> getOrderUpdates() {
return orderUpdates;
}
public void setOrderUpdates(List<OrderUpdate> orderUpdates) {
this.orderUpdates = orderUpdates;
}
public void setOrder(final Order order) {
this.order = order;
}
}
|
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
// Adding more stuff
// Detect request animation frame
var scroll = window.requestAnimationFrame ||
// IE Fallback
function(callback){ window.setTimeout(callback, 1000/60)};
var elementsToShow = document.querySelectorAll('.skillpic');
var mastheadavatar = document.querySelectorAll('.masthead-avatar');
var topstar = document.querySelectorAll('#topstar');
var gradcap = document.querySelectorAll('#gradcap');
var education = document.querySelectorAll('#education');
var workexperience = document.querySelectorAll('#workexperience');
function loop() {
Array.prototype.forEach.call(education, function(element){
if (isElementInViewport(element)) {
element.classList.add('zoomIn');
} else {
element.classList.remove('zoomIn');
}
});
Array.prototype.forEach.call(workexperience, function(element){
if (isElementInViewport(element)) {
element.classList.add('zoomIn');
} else {
element.classList.remove('zoomIn');
}
});
Array.prototype.forEach.call(gradcap, function(element){
if (isElementInViewport(element)) {
element.classList.add('tada');
} else {
element.classList.remove('tada');
}
});
Array.prototype.forEach.call(topstar, function(element){
if (isElementInViewport(element)) {
element.classList.add('tada');
} else {
element.classList.remove('tada');
}
});
Array.prototype.forEach.call(mastheadavatar, function(element){
if (isElementInViewport(element)) {
element.classList.add('bounceIn');
} else {
element.classList.remove('bounceIn');
}
});
Array.prototype.forEach.call(elementsToShow, function(element){
if (isElementInViewport(element)) {
element.classList.add('bounceIn');
} else {
element.classList.remove('bounceIn');
}
});
scroll(loop);
}
// Call the loop for the first time
loop();
// Helper function from: http://stackoverflow.com/a/7557433/274826
function isElementInViewport(el) {
// special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
(rect.top <= 0
&& rect.bottom >= 0)
||
(rect.bottom >= (window.innerHeight || document.documentElement.clientHeight) &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight))
||
(rect.top >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight))
);
}
|
<filename>FEBioFluid/FERealGas.cpp
/*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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.*/
#include "FERealGas.h"
#include <FECore/FEModel.h>
#include <FECore/log.h>
#include <FECore/FEFunction1D.h>
#include "FEFluidMaterialPoint.h"
#include "FEThermoFluidMaterialPoint.h"
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FERealGas, FEElasticFluid)
// material parameters
ADD_PARAMETER(m_nvc , FE_RANGE_GREATER_OR_EQUAL(0), "nvc");
ADD_PROPERTY(m_a0 , "a0");
ADD_PROPERTY(m_A[0], "A1", FEProperty::Optional);
ADD_PROPERTY(m_A[1], "A2", FEProperty::Optional);
ADD_PROPERTY(m_A[2], "A3", FEProperty::Optional);
ADD_PROPERTY(m_A[3], "A4", FEProperty::Optional);
ADD_PROPERTY(m_A[4], "A5", FEProperty::Optional);
ADD_PROPERTY(m_A[5], "A6", FEProperty::Optional);
ADD_PROPERTY(m_A[6], "A7", FEProperty::Optional);
END_FECORE_CLASS();
FERealGas::FERealGas(FEModel* pfem) : FEElasticFluid(pfem)
{
m_nvc = 0;
m_R = m_Pr = m_Tr = 0;
m_a0 = nullptr;
m_A[0] = m_A[1] = m_A[2] = m_A[3] = m_A[4] = m_A[5] = m_A[6] = nullptr;
}
//-----------------------------------------------------------------------------
//! initialization
bool FERealGas::Init()
{
m_R = GetFEModel()->GetGlobalConstant("R");
m_Tr = GetFEModel()->GetGlobalConstant("T");
m_Pr = GetFEModel()->GetGlobalConstant("P");
if (m_R <= 0) { feLogError("A positive universal gas constant R must be defined in Globals section"); return false; }
if (m_Tr <= 0) { feLogError("A positive referential absolute temperature T must be defined in Globals section"); return false; }
if (m_Pr <= 0) { feLogError("A positive referential absolute pressure P must be defined in Globals section"); return false; }
m_pMat = dynamic_cast<FEThermoFluid*>(GetParent());
m_rhor = m_pMat->ReferentialDensity();
// check if we should assume ideal gas
if (m_nvc == 0) {
m_A[0] = new FELinearFunction(GetFEModel(), 0, 1);
m_nvc = 1;
}
m_a0->Init();
for (int k=0; k<m_nvc; ++k)
if (m_A[k]) m_A[k]->Init();
return true;
}
//-----------------------------------------------------------------------------
//! gage pressure
double FERealGas::Pressure(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double dq = tf.m_T/m_Tr;
double J = fp.m_Jf;
double x = (1+dq)/J - 1;
double p = 0;
for (int k=1; k<=m_nvc; ++k)
p += m_A[k-1]->value(dq)*pow(x,k);
return p*m_Pr;
}
//-----------------------------------------------------------------------------
//! tangent of pressure with respect to strain J
double FERealGas::Tangent_Strain(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double dq = tf.m_T/m_Tr;
double q = 1 + dq;
double J = fp.m_Jf;
double x = q/J - 1;
double dpJ = m_A[0]->value(dq);
for (int k=2; k<=m_nvc; ++k)
dpJ += k*m_A[k-1]->value(dq)*pow(x,k-1);
return -dpJ*m_Pr*q/pow(J,2);
}
//-----------------------------------------------------------------------------
//! 2nd tangent of pressure with respect to strain J
double FERealGas::Tangent_Strain_Strain(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double dq = tf.m_T/m_Tr;
double q = 1 + dq;
double J = fp.m_Jf;
double x = q/J - 1;
double dpJ2 = 2*m_A[0]->value(dq);
for (int k=2; k<=m_nvc; ++k)
dpJ2 += k*m_A[k-1]->value(dq)*(2*x+(k-1)*q/J)*pow(x,k-2);
return dpJ2*m_Pr*q/pow(J,3);
}
//-----------------------------------------------------------------------------
//! tangent of pressure with respect to temperature T
double FERealGas::Tangent_Temperature(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double dq = tf.m_T/m_Tr;
double q = 1 + dq;
double J = fp.m_Jf;
double x = q/J - 1;
double dpT = 0;
for (int k=1; k<=m_nvc; ++k)
dpT += (m_A[k-1]->derive(dq)*x + k/J*m_A[k-1]->value(dq))*pow(x,k-1);
return dpT*m_Pr/m_Tr;
}
//-----------------------------------------------------------------------------
//! 2nd tangent of pressure with respect to temperature T
double FERealGas::Tangent_Temperature_Temperature(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double dq = tf.m_T/m_Tr;
double q = 1 + dq;
double J = fp.m_Jf;
double x = q/J - 1;
double dpT2 = m_A[0]->deriv2(dq)*x + 2/J*m_A[0]->derive(dq);
for (int k=2; k<=m_nvc; ++k)
dpT2 += (m_A[k-1]->deriv2(dq)*pow(x,2) + 2*k/J*m_A[k-1]->derive(dq)*x
+ k*(k-1)/pow(J,2)*m_A[k-1]->value(dq))*pow(x,k-2);
return dpT2*m_Pr/pow(m_Tr,2);
}
//-----------------------------------------------------------------------------
//! tangent of pressure with respect to strain J and temperature T
double FERealGas::Tangent_Strain_Temperature(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double dq = tf.m_T/m_Tr;
double q = 1 + dq;
double J = fp.m_Jf;
double x = q/J - 1;
double dpJT = m_A[0]->value(dq) + q*m_A[0]->derive(dq);
for (int k=2; k<=m_nvc; ++k)
dpJT += k*(q*m_A[k-1]->derive(dq)*x + m_A[k-1]->value(dq)*(x+(k-1)*q/J))*pow(x,k-2);
return -dpJT*m_Pr/(m_Tr*pow(J, 2));
}
//-----------------------------------------------------------------------------
//! specific free energy
double FERealGas::SpecificFreeEnergy(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double dq = tf.m_T/m_Tr;
double q = 1 + dq;
double q2 = q*q, q3 = q2*q, q4 = q3*q, q5 = q4*q, q6 = q5*q, q7 = q6*q;
double lnq = log(q);
double J = fp.m_Jf;
double J2 = J*J, J3 = J2*J, J4 = J3*J, J5 = J4*J, J6 = J5*J, J7 = J6*J;
double lnJ = log(J);
double A[MAX_NVC];
for (int k=0; k<m_nvc; ++k)
A[k] = m_A[k]->value(dq);
double a = m_a0->value(dq);
a += (-60*J6*q*A[0] - 60*J6*lnJ*q*A[0] + 60*J6*lnq*q*A[0] + 120*J6*lnJ*q*A[1] -
120*J6*lnq*q*A[1] + 60*J5*q2*A[1] + 90*J6*q*A[2] - 180*J6*lnJ*q*A[2] +
180*J6*lnq*q*A[2] - 180*J5*q2*A[2] + 30*J4*q3*A[2] - 200*J6*q*A[3] +
240*J6*lnJ*q*A[3] - 240*J6*lnq*q*A[3] + 360*J5*q2*A[3] - 120*J4*q3*A[3] +
20*J3*q4*A[3] + 325*J6*q*A[4] - 300*J6*lnJ*q*A[4] + 300*J6*lnq*q*A[4] -
600*J5*q2*A[4] + 300*J4*q3*A[4] - 100*J3*q4*A[4] + 15*J2*q5*A[4] -
462*J6*q*A[5] + 360*J6*lnJ*q*A[5] - 360*J6*lnq*q*A[5] + 900*J5*q2*A[5] -
600*J4*q3*A[5] + 300*J3*q4*A[5] - 90*J2*q5*A[5] + 12*J*q6*A[5] + 609*J6*q*A[6] -
420*J6*lnJ*q*A[6] + 420*J6*lnq*q*A[6] - 1260*J5*q2*A[6] + 1050*J4*q3*A[6] -
700*J3*q4*A[6] + 315*J2*q5*A[6] - 84*J*q6*A[6] + 10*q7*A[6] +
60*J7*(A[0] - A[1] + A[2] - A[3] + A[4] - A[5] + A[6]))/
(60.*J6);
return a*m_Pr/m_rhor;
}
//-----------------------------------------------------------------------------
//! specific entropy
double FERealGas::SpecificEntropy(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double dq = tf.m_T/m_Tr;
double q = 1 + dq;
double q2 = q*q, q3 = q2*q, q4 = q3*q, q5 = q4*q, q6 = q5*q, q7 = q6*q;
double lnq = log(q);
double J = fp.m_Jf;
double J2 = J*J, J3 = J2*J, J4 = J3*J, J5 = J4*J, J6 = J5*J, J7 = J6*J;
double lnJ = log(J);
double A[MAX_NVC], dA[MAX_NVC];
for (int k=0; k<m_nvc; ++k) {
A[k] = m_A[k]->value(dq);
dA[k] = m_A[k]->derive(dq);
}
double da0 = m_a0->derive(dq);
double s = -((60*da0*J6 + 120*J5*q*A[1] - 360*J5*q*A[2] + 90*J4*q2*A[2] + 720*J5*q*A[3] -
360*J4*q2*A[3] + 80*J3*q3*A[3] - 1200*J5*q*A[4] + 900*J4*q2*A[4] -
400*J3*q3*A[4] + 75*J2*q4*A[4] + 1800*J5*q*A[5] - 1800*J4*q2*A[5] +
1200*J3*q3*A[5] - 450*J2*q4*A[5] + 72*J*q5*A[5] - 2520*J5*q*A[6] +
3150*J4*q2*A[6] - 2800*J3*q3*A[6] + 1575*J2*q4*A[6] - 504*J*q5*A[6] +
70*q6*A[6] + 60*J7*dA[0] - 60*J7*dA[1] + 60*J5*q2*dA[1] + 60*J7*dA[2] -
180*J5*q2*dA[2] + 30*J4*q3*dA[2] - 60*J7*dA[3] + 360*J5*q2*dA[3] -
120*J4*q3*dA[3] + 20*J3*q4*dA[3] + 60*J7*dA[4] - 600*J5*q2*dA[4] +
300*J4*q3*dA[4] - 100*J3*q4*dA[4] + 15*J2*q5*dA[4] - 60*J7*dA[5] +
900*J5*q2*dA[5] - 600*J4*q3*dA[5] + 300*J3*q4*dA[5] - 90*J2*q5*dA[5] +
12*J*q6*dA[5] + 60*J7*dA[6] - 1260*J5*q2*dA[6] + 1050*J4*q3*dA[6] -
700*J3*q4*dA[6] + 315*J2*q5*dA[6] - 84*J*q6*dA[6] + 10*q7*dA[6] +
J6*(-120*A[1] + 270*A[2] - 440*A[3] + 625*A[4] - 822*A[5] + 1029*A[6] -
60*q*dA[0] + 90*q*dA[2] - 200*q*dA[3] + 325*q*dA[4] - 462*q*dA[5] +
609*q*dA[6] - 60*lnJ*(A[0] - 2*A[1] + 3*A[2] - 4*A[3] + 5*A[4] - 6*A[5] +
7*A[6] + q*dA[0] - 2*q*dA[1] + 3*q*dA[2] - 4*q*dA[3] + 5*q*dA[4] -
6*q*dA[5] + 7*q*dA[6]) +
60*lnq*(A[0] - 2*A[1] + 3*A[2] - 4*A[3] + 5*A[4] - 6*A[5] + 7*A[6] +
q*dA[0] - 2*q*dA[1] + 3*q*dA[2] - 4*q*dA[3] + 5*q*dA[4] - 6*q*dA[5] +
7*q*dA[6]))))/(60.*J6);
return s*m_Pr/(m_Tr*m_rhor);
}
//-----------------------------------------------------------------------------
//! specific strain energy
double FERealGas::SpecificStrainEnergy(FEMaterialPoint& mp)
{
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
// get the specific free energy
double a = SpecificFreeEnergy(mp);
double dq = tf.m_T/m_Tr;
double a0 = m_a0->value(dq)*m_Pr/m_rhor;
// the specific strain energy is the difference between these two values
return a - a0;
}
//-----------------------------------------------------------------------------
//! isochoric specific heat capacity
double FERealGas::IsochoricSpecificHeatCapacity(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double dq = tf.m_T/m_Tr;
double q = 1 + dq;
double q2 = q*q, q3 = q2*q, q4 = q3*q, q5 = q4*q, q6 = q5*q, q7 = q6*q;
double lnq = log(q);
double J = fp.m_Jf;
double J2 = J*J, J3 = J2*J, J4 = J3*J, J5 = J4*J, J6 = J5*J, J7 = J6*J;
double lnJ = log(J);
double A[MAX_NVC], dA[MAX_NVC], d2A[MAX_NVC];
for (int k=0; k<m_nvc; ++k) {
A[k] = m_A[k]->value(dq);
dA[k] = m_A[k]->derive(dq);
d2A[k] = m_A[k]->deriv2(dq);
}
double d2a0 = m_a0->deriv2(dq);
double cv = -q*(60*d2a0*J6 + 120*J5*A[1] - (120*J*J5*A[1])/q - 360*J5*A[2] + 180*J4*q*A[2] +
720*J5*A[3] - 720*J4*q*A[3] + 240*J3*q2*A[3] - 1200*J5*A[4] + 1800*J4*q*A[4] -
1200*J3*q2*A[4] + 300*J2*q3*A[4] + 1800*J5*A[5] - 3600*J4*q*A[5] +
3600*J3*q2*A[5] - 1800*J2*q3*A[5] + 360*J*q4*A[5] - 2520*J5*A[6] +
6300*J4*q*A[6] - 8400*J3*q2*A[6] + 6300*J2*q3*A[6] - 2520*J*q4*A[6] +
420*q5*A[6] + 60*J7*d2A[0] - 60*J7*d2A[1] + 60*J5*q2*d2A[1] + 60*J7*d2A[2] -
180*J5*q2*d2A[2] + 30*J4*q3*d2A[2] - 60*J7*d2A[3] + 360*J5*q2*d2A[3] -
120*J4*q3*d2A[3] + 20*J3*q4*d2A[3] + 60*J7*d2A[4] - 600*J5*q2*d2A[4] +
300*J4*q3*d2A[4] - 100*J3*q4*d2A[4] + 15*J2*q5*d2A[4] - 60*J7*d2A[5] +
900*J5*q2*d2A[5] - 600*J4*q3*d2A[5] + 300*J3*q4*d2A[5] - 90*J2*q5*d2A[5] +
12*J*q6*d2A[5] + 60*J7*d2A[6] - 1260*J5*q2*d2A[6] + 1050*J4*q3*d2A[6] -
700*J3*q4*d2A[6] + 315*J2*q5*d2A[6] - 84*J*q6*d2A[6] + 10*q7*d2A[6] +
240*J5*q*dA[1] - 720*J5*q*dA[2] + 180*J4*q2*dA[2] + 1440*J5*q*dA[3] -
720*J4*q2*dA[3] + 160*J3*q3*dA[3] - 2400*J5*q*dA[4] + 1800*J4*q2*dA[4] -
800*J3*q3*dA[4] + 150*J2*q4*dA[4] + 3600*J5*q*dA[5] - 3600*J4*q2*dA[5] +
2400*J3*q3*dA[5] - 900*J2*q4*dA[5] + 144*J*q5*dA[5] - 5040*J5*q*dA[6] +
6300*J4*q2*dA[6] - 5600*J3*q3*dA[6] + 3150*J2*q4*dA[6] - 1008*J*q5*dA[6] +
140*q6*dA[6] + J6*((60*(A[0] + 3*A[2] - 4*A[3] + 5*A[4] - 6*A[5] + 7*A[6]))/q +
q*(-60*(1 + lnJ - lnq)*d2A[0] - 120*lnq*d2A[1] + 90*d2A[2] +
180*lnq*d2A[2] - 200*d2A[3] - 240*lnq*d2A[3] + 325*d2A[4] +
300*lnq*d2A[4] - 462*d2A[5] - 360*lnq*d2A[5] +
60*lnJ*(2*d2A[1] - 3*d2A[2] + 4*d2A[3] - 5*d2A[4] + 6*d2A[5] -
7*d2A[6]) + 609*d2A[6] + 420*lnq*d2A[6]) -
2*(120*dA[1] - 270*dA[2] + 440*dA[3] - 625*dA[4] + 822*dA[5] - 1029*dA[6] +
60*lnJ*(dA[0] - 2*dA[1] + 3*dA[2] - 4*dA[3] + 5*dA[4] - 6*dA[5] +
7*dA[6]) - 60*lnq*(dA[0] - 2*dA[1] + 3*dA[2] - 4*dA[3] + 5*dA[4] -
6*dA[5] + 7*dA[6]))))/(60.*J6);
return cv*m_Pr/(m_Tr*m_rhor);
}
//-----------------------------------------------------------------------------
//! tangent of isochoric specific heat capacity with respect to strain J
double FERealGas::Tangent_cv_Strain(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double dq = tf.m_T/m_Tr;
double q = 1 + dq;
double q2 = q*q, q3 = q2*q, q4 = q3*q, q5 = q4*q, q6 = q5*q, q7 = q6*q;
double lnq = log(q);
double J = fp.m_Jf;
double J2 = J*J, J3 = J2*J, J4 = J3*J, J5 = J4*J, J6 = J5*J, J7 = J6*J;
double lnJ = log(J);
double A[MAX_NVC], dA[MAX_NVC], d2A[MAX_NVC];
for (int k=0; k<m_nvc; ++k) {
A[k] = m_A[k]->value(dq);
dA[k] = m_A[k]->derive(dq);
d2A[k] = m_A[k]->deriv2(dq);
}
double d2a0 = m_a0->deriv2(dq);
double dcvJ = -(q*(60*d2a0*J6 + 120*J5*A[1] - (120*J*J5*A[1])/q - 360*J5*A[2] + 180*J4*q*A[2] +
720*J5*A[3] - 720*J4*q*A[3] + 240*J3*q2*A[3] - 1200*J5*A[4] + 1800*J4*q*A[4] -
1200*J3*q2*A[4] + 300*J2*q3*A[4] + 1800*J5*A[5] - 3600*J4*q*A[5] +
3600*J3*q2*A[5] - 1800*J2*q3*A[5] + 360*J*q4*A[5] - 2520*J5*A[6] +
6300*J4*q*A[6] - 8400*J3*q2*A[6] + 6300*J2*q3*A[6] - 2520*J*q4*A[6] +
420*q5*A[6] + 60*J7*d2A[0] - 60*J7*d2A[1] + 60*J5*q2*d2A[1] + 60*J7*d2A[2] -
180*J5*q2*d2A[2] + 30*J4*q3*d2A[2] - 60*J7*d2A[3] + 360*J5*q2*d2A[3] -
120*J4*q3*d2A[3] + 20*J3*q4*d2A[3] + 60*J7*d2A[4] - 600*J5*q2*d2A[4] +
300*J4*q3*d2A[4] - 100*J3*q4*d2A[4] + 15*J2*q5*d2A[4] - 60*J7*d2A[5] +
900*J5*q2*d2A[5] - 600*J4*q3*d2A[5] + 300*J3*q4*d2A[5] - 90*J2*q5*d2A[5] +
12*J*q6*d2A[5] + 60*J7*d2A[6] - 1260*J5*q2*d2A[6] + 1050*J4*q3*d2A[6] -
700*J3*q4*d2A[6] + 315*J2*q5*d2A[6] - 84*J*q6*d2A[6] + 10*q7*d2A[6] +
240*J5*q*dA[1] - 720*J5*q*dA[2] + 180*J4*q2*dA[2] + 1440*J5*q*dA[3] -
720*J4*q2*dA[3] + 160*J3*q3*dA[3] - 2400*J5*q*dA[4] + 1800*J4*q2*dA[4] -
800*J3*q3*dA[4] + 150*J2*q4*dA[4] + 3600*J5*q*dA[5] - 3600*J4*q2*dA[5] +
2400*J3*q3*dA[5] - 900*J2*q4*dA[5] + 144*J*q5*dA[5] - 5040*J5*q*dA[6] +
6300*J4*q2*dA[6] - 5600*J3*q3*dA[6] + 3150*J2*q4*dA[6] - 1008*J*q5*dA[6] +
140*q6*dA[6] + J6*((60*(A[0] + 3*A[2] - 4*A[3] + 5*A[4] - 6*A[5] + 7*A[6]))/q +
q*(-60*(1 + lnJ - lnq)*d2A[0] - 120*lnq*d2A[1] + 90*d2A[2] +
180*lnq*d2A[2] - 200*d2A[3] - 240*lnq*d2A[3] + 325*d2A[4] +
300*lnq*d2A[4] - 462*d2A[5] - 360*lnq*d2A[5] +
60*lnJ*(2*d2A[1] - 3*d2A[2] + 4*d2A[3] - 5*d2A[4] + 6*d2A[5] -
7*d2A[6]) + 609*d2A[6] + 420*lnq*d2A[6]) -
2*(120*dA[1] - 270*dA[2] + 440*dA[3] - 625*dA[4] + 822*dA[5] - 1029*dA[6] +
60*lnJ*(dA[0] - 2*dA[1] + 3*dA[2] - 4*dA[3] + 5*dA[4] - 6*dA[5] +
7*dA[6]) - 60*lnq*(dA[0] - 2*dA[1] + 3*dA[2] - 4*dA[3] + 5*dA[4] -
6*dA[5] + 7*dA[6])))))/(60.*J6);
return dcvJ*m_Pr/(m_Tr*m_rhor);
}
//-----------------------------------------------------------------------------
//! tangent of isochoric specific heat capacity with respect to temperature T
double FERealGas::Tangent_cv_Temperature(FEMaterialPoint& mp)
{
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double T = m_Tr + tf.m_T;
double dcvT = IsochoricSpecificHeatCapacity(mp)/T; // this is incomplete
return dcvT;
}
//-----------------------------------------------------------------------------
//! isobaric specific heat capacity
double FERealGas::IsobaricSpecificHeatCapacity(FEMaterialPoint& mp)
{
FEThermoFluidMaterialPoint& tf = *mp.ExtractData<FEThermoFluidMaterialPoint>();
double cv = IsochoricSpecificHeatCapacity(mp);
double p = Pressure(mp);
double dpT = Tangent_Temperature(mp);
double dpJ = Tangent_Strain(mp);
double cp = cv + (dpT/dpJ)/m_rhor*(p - (m_Tr + tf.m_T)*dpT);
return cp;
}
//-----------------------------------------------------------------------------
//! dilatation from temperature and pressure
bool FERealGas::Dilatation(const double T, const double p, const double c, double& e)
{
double errrel = 1e-6;
double errabs = 1e-6;
int maxiter = 100;
switch (m_nvc) {
case 0:
return false;
break;
case 1:
{
double q = T/m_Tr;
double x = p/m_Pr/m_A[0]->value(q);
e = (q+1)/(x+1) - 1;
return true;
}
break;
case 2:
{
double q = T/m_Tr;
double A1 = m_A[0]->value(q);
double A2 = m_A[1]->value(q);
double det = A1*A1 + 4*A2*p/m_Pr;
if (det < 0) return false;
det = sqrt(det);
// only one root of this quadratic equation is valid.
double x = (-A1+det)/(2*A2);
e = (q+1)/(x+1) - 1;
return true;
}
break;
default:
{
FEFluidMaterialPoint* fp = new FEFluidMaterialPoint();
FEThermoFluidMaterialPoint* ft = new FEThermoFluidMaterialPoint(fp);
ft->m_T = T;
bool convgd = false;
bool done = false;
int iter = 0;
do {
++iter;
fp->m_Jf = 1 + e;
double f = Pressure(*ft) - p;
double df = Tangent_Strain(*ft);
double de = (df != 0) ? -f/df : 0;
e += de;
if ((fabs(de) < errrel*fabs(e)) ||
(fabs(f/m_Pr) < errabs)) { convgd = true; done = true; }
if (iter > maxiter) done = true;
} while (!done);
return convgd;
}
break;
}
return false;
}
//-----------------------------------------------------------------------------
//! pressure from state variables
double FERealGas::Pressure(const double ef, const double T)
{
FEFluidMaterialPoint* fp = new FEFluidMaterialPoint();
FEThermoFluidMaterialPoint* ft = new FEThermoFluidMaterialPoint(fp);
fp->m_Jf = 1 + ef;
ft->m_T = T;
return Pressure(*ft);
}
|
import React from 'react';
export class MyText extends React.Component {
render() {
return (
<div>
This is the text I want to display.
</div>
)
}
}
|
import { useEffect } from "react";
import { useRouter } from "next/router";
import { pageView } from "./gtag";
export function usePagesViews(): void {
const router = useRouter();
useEffect(() => {
const handleRouteChange = (url: URL): void => {
if (!process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID) {
return;
}
pageView({ path: url.toString() });
};
router.events.on("routeChangeComplete", handleRouteChange);
return () => {
router.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);
}
|
<reponame>jjhlzn/ContractApp_Android
package com.jinjunhang.contract.controller;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import com.jinjunhang.contract.R;
import com.jinjunhang.contract.service.ApprovalQueryObject;
import com.jinjunhang.contract.service.PriceReportQueryObject;
import com.jinjunhang.contract.service.SearchPriceReportsRequest;
import com.jinjunhang.framework.controller.PagableController;
import com.jinjunhang.contract.model.PriceReport;
import com.jinjunhang.framework.service.BasicService;
import com.jinjunhang.framework.service.PagedServerResponse;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* Created by lzn on 16/6/14.
*/
public class PriceReportListFragment extends android.support.v4.app.Fragment implements
AbsListView.OnScrollListener {
private final static String TAG = "PriceReportListFragment";
private PagableController mPagableController;
private PriceReportQueryObject mQueryObject;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.d(TAG, "onCreateView called");
View v = inflater.inflate(R.layout.activity_fragement_pushdownrefresh, container, false);
ListView listView = (ListView) v.findViewById(R.id.listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PriceReport priceReport = (PriceReport)((mPagableController.getPagableArrayAdapter()).getItem(position));
Intent i = new Intent(getActivity(), PriceReportDetailActivity.class)
.putExtra(PriceReportDetailFragment.EXTRA_PRICEREPORT, priceReport);
startActivity(i);
}
});
SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout)v.findViewById(R.id.swipe_refresh_layout);
if (mPagableController == null) {
Log.d(TAG, "create PagableController");
mPagableController = new PagableController();
}
mPagableController.setActivity(getActivity());
mPagableController.setListView(listView);
if ( mPagableController.getPagableArrayAdapter() != null) {
mPagableController.setPagableArrayAdapter(new PriceReportAdapter(mPagableController, mPagableController.getPagableArrayAdapter().getDataSet()));
} else {
mPagableController.setPagableArrayAdapter(new PriceReportAdapter(mPagableController, new ArrayList<PriceReport>()));
}
mPagableController.setPagableRequestHandler(new PriceReportRequestHandler());
mPagableController.setSwipeRefreshLayout(swipeRefreshLayout);
mPagableController.setOnScrollListener(this);
final ImageButton searchApprovalButton = (ImageButton)((AppCompatActivity)getActivity()).getSupportActionBar().getCustomView().
findViewById(R.id.actionbar_searchApprovalButton);
searchApprovalButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), PriceReportSearchActivity.class)
.putExtra(PriceReportSearchFragment.EXTRA_QUERYOBJECT, mQueryObject);
startActivity(i);
}
});
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated called");
if (mQueryObject == null) {
Intent i = getActivity().getIntent();
mQueryObject = (PriceReportQueryObject) i.getSerializableExtra(PriceReportSearchFragment.EXTRA_QUERYOBJECT);
//if (i.getBooleanExtra(EXTRA_FROMSEARCH, false)) {
// mMoreDataAvailable = true;
//}
}
if (mQueryObject == null) {
createQueryObject();
}
}
private void createQueryObject() {
mQueryObject = new PriceReportQueryObject();
Calendar cal = Calendar.getInstance();
final Date tomorrow;
final Date oneMonthAgo;
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
cal.add(Calendar.DAY_OF_MONTH, -31);
oneMonthAgo = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, 32);
tomorrow = cal.getTime();
mQueryObject.setKeyword("");
mQueryObject.setStartDate(dt.format(oneMonthAgo));
mQueryObject.setEndDate(dt.format(tomorrow));
mQueryObject.setPageSize(Utils.PAGESIZE_PRICEREPORT);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
mPagableController.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
class PriceReportRequestHandler implements PagableController.PagableRequestHandler {
@Override
public PagedServerResponse handle() {
SearchPriceReportsRequest req = new SearchPriceReportsRequest();
req.setKeyword(mQueryObject.getKeyword());
req.setStartDate(mQueryObject.getStartDate());
req.setEndDate(mQueryObject.getEndDate());
req.setUserId(PrefUtils.getFromPrefs(getActivity(), PrefUtils.PREFS_LOGIN_USERNAME_KEY, ""));
req.setPageSize(mQueryObject.getPageSize());
req.setPageIndex(mPagableController.getPageIndex());
return new BasicService().sendRequest(req);
}
}
class PriceReportAdapter extends PagableController.PagableArrayAdapter<PriceReport> implements Serializable {
public PriceReportAdapter(PagableController controller, List<PriceReport> dataSet) {
super(controller, dataSet);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_pricereport, null);
}
PriceReport report = getItem(position);
TextView idTextView = (TextView) convertView.findViewById(R.id.pricereport_list_item_id);
idTextView.setText(report.getId());
TextView validDaysTextView = (TextView) convertView.findViewById(R.id.pricereport_list_item_validDays);
validDaysTextView.setText(report.getValidDays()+"天");
TextView statusTextView = (TextView) convertView.findViewById(R.id.pricereport_list_item_status);
statusTextView.setText(report.getStatus());
TextView reportTextView = (TextView) convertView.findViewById(R.id.pricereport_list_item_reporter);
reportTextView.setText(report.getReporter());
TextView dateTextView = (TextView) convertView.findViewById(R.id.pricereport_list_item_date);
dateTextView.setText(report.getDate());
TextView detailInfoTextView = (TextView) convertView.findViewById(R.id.pricereport_list_item_detailInfo);
detailInfoTextView.setText(report.getDetailInfo());
return convertView;
}
}
}
|
import React from 'react';
import { Filter as CrudFilter, ReferenceInput, SelectInput } from 'rest-ui/lib/mui';
const Filter = ({ ...props }) => (
<CrudFilter {...props}>
<ReferenceInput source="post_id" reference="posts">
<SelectInput optionText="title" />
</ReferenceInput>
</CrudFilter>
);
export default Filter;
|
#!/bin/bash
#===- llvm/utils/docker/build_docker_image.sh ----------------------------===//
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===----------------------------------------------------------------------===//
set -e
IMAGE_SOURCE=""
DOCKER_REPOSITORY=""
DOCKER_TAG=""
BUILDSCRIPT_ARGS=""
function show_usage() {
usage=$(cat << EOF
Usage: build_docker_image.sh [options] [-- [cmake_args]...]
Available options:
General:
-h|--help show this help message
Docker-specific:
-s|--source image source dir (i.e. debian8, nvidia-cuda, etc)
-d|--docker-repository docker repository for the image
-t|--docker-tag docker tag for the image
LLVM-specific:
-b|--branch svn branch to checkout, i.e. 'trunk',
'branches/release_40'
(default: 'trunk')
-r|--revision svn revision to checkout
-p|--llvm-project name of an svn project to checkout. Will also add the
project to a list LLVM_ENABLE_PROJECTS, passed to CMake.
For clang, please use 'clang', not 'cfe'.
Project 'llvm' is always included and ignored, if
specified.
Can be specified multiple times.
-i|--install-target name of a cmake install target to build and include in
the resulting archive. Can be specified multiple times.
Required options: --source and --docker-repository, at least one
--install-target.
All options after '--' are passed to CMake invocation.
For example, running:
$ build_docker_image.sh -s debian8 -d mydocker/debian8-clang -t latest \
-p clang -i install-clang -i install-clang-headers
will produce two docker images:
mydocker/debian8-clang-build:latest - an intermediate image used to compile
clang.
mydocker/clang-debian8:latest - a small image with preinstalled clang.
Please note that this example produces a not very useful installation, since it
doesn't override CMake defaults, which produces a Debug and non-boostrapped
version of clang.
To get a 2-stage clang build, you could use this command:
$ ./build_docker_image.sh -s debian8 -d mydocker/clang-debian8 -t "latest" \
-p clang -i stage2-install-clang -i stage2-install-clang-headers \
-- \
-DLLVM_TARGETS_TO_BUILD=Native -DCMAKE_BUILD_TYPE=Release \
-DBOOTSTRAP_CMAKE_BUILD_TYPE=Release \
-DCLANG_ENABLE_BOOTSTRAP=ON \
-DCLANG_BOOTSTRAP_TARGETS="install-clang;install-clang-headers"
EOF
)
echo "$usage"
}
SEEN_INSTALL_TARGET=0
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help)
show_usage
exit 0
;;
-s|--source)
shift
IMAGE_SOURCE="$1"
shift
;;
-d|--docker-repository)
shift
DOCKER_REPOSITORY="$1"
shift
;;
-t|--docker-tag)
shift
DOCKER_TAG="$1"
shift
;;
-i|--install-target|-r|--revision|-b|--branch|-p|--llvm-project)
if [ "$1" == "-i" ] || [ "$1" == "--install-target" ]; then
SEEN_INSTALL_TARGET=1
fi
BUILDSCRIPT_ARGS="$BUILDSCRIPT_ARGS $1 $2"
shift 2
;;
--)
shift
BUILDSCRIPT_ARGS="$BUILDSCRIPT_ARGS -- $*"
shift $#
;;
*)
echo "Unknown argument $1"
exit 1
;;
esac
done
command -v docker >/dev/null ||
{
echo "Docker binary cannot be found. Please install Docker to use this script."
exit 1
}
if [ "$IMAGE_SOURCE" == "" ]; then
echo "Required argument missing: --source"
exit 1
fi
if [ "$DOCKER_REPOSITORY" == "" ]; then
echo "Required argument missing: --docker-repository"
exit 1
fi
if [ $SEEN_INSTALL_TARGET -eq 0 ]; then
echo "Please provide at least one --install-target"
exit 1
fi
cd $(dirname $0)
if [ ! -d $IMAGE_SOURCE ]; then
echo "No sources for '$IMAGE_SOURCE' were found in $PWD"
exit 1
fi
echo "Building from $IMAGE_SOURCE"
if [ "$DOCKER_TAG" != "" ]; then
DOCKER_TAG=":$DOCKER_TAG"
fi
echo "Building $DOCKER_REPOSITORY-build$DOCKER_TAG"
docker build -t "$DOCKER_REPOSITORY-build$DOCKER_TAG" \
--build-arg "buildscript_args=$BUILDSCRIPT_ARGS" \
-f "$IMAGE_SOURCE/build/Dockerfile" .
echo "Copying clang installation to release image sources"
docker run -v "$PWD/$IMAGE_SOURCE:/workspace" "$DOCKER_REPOSITORY-build$DOCKER_TAG" \
cp /tmp/clang.tar.gz /workspace/release
trap "rm -f $PWD/$IMAGE_SOURCE/release/clang.tar.gz" EXIT
echo "Building release image"
docker build -t "${DOCKER_REPOSITORY}${DOCKER_TAG}" \
"$IMAGE_SOURCE/release"
echo "Done"
|
#!/bin/sh
sudo `stack exec which fingerd`
|
#!/usr/bin/env bash
main() {
# """
# Install Apache Portable Runtime (APR) library.
# @note Updated 2022-04-09.
#
# @seealso
# - https://github.com/Homebrew/homebrew-core/blob/master/Formula/apr.rb
# - macOS build issue:
# https://bz.apache.org/bugzilla/show_bug.cgi?id=64753
# """
local app conf_args dict
koopa_assert_has_no_args "$#"
if koopa_is_macos
then
koopa_activate_build_opt_prefix 'autoconf' 'automake' 'libtool'
fi
declare -A app=(
[make]="$(koopa_locate_make)"
)
if koopa_is_macos
then
app[autoreconf]="$(koopa_locate_autoreconf)"
app[patch]="$(koopa_locate_patch)"
fi
declare -A dict=(
[jobs]="$(koopa_cpu_count)"
[name]='apr'
[prefix]="${INSTALL_PREFIX:?}"
[version]="${INSTALL_VERSION:?}"
)
dict[file]="${dict[name]}-${dict[version]}.tar.bz2"
dict[url]="https://archive.apache.org/dist/${dict[name]}/${dict[file]}"
koopa_download "${dict[url]}" "${dict[file]}"
koopa_extract "${dict[file]}"
conf_args=(
"--prefix=${dict[prefix]}"
)
if koopa_is_macos
then
# Apply r1871981 which fixes a compile error on macOS 11.0.
koopa_cd "${dict[name]}-${dict[version]}"
koopa_download \
"https://raw.githubusercontent.com/Homebrew/\
formula-patches/7e2246542543bbd3111a4ec29f801e6e4d538f88/\
apr/r1871981-macos11.patch" \
'patch1.patch'
"${app[patch]}" -p0 --input='patch1.patch'
# Apply r1882980+1882981 to fix implicit exit() declaration
# Remove with the next release, along with autoconf dependency.
koopa_cd ..
koopa_download \
"https://raw.githubusercontent.com/Homebrew/\
formula-patches/fa29e2e398c638ece1a72e7a4764de108bd09617/apr/\
r1882980%2B1882981-configure.patch" \
'patch2.patch'
"${app[patch]}" -p0 --input='patch2.patch'
koopa_cd "${dict[name]}-${dict[version]}"
koopa_rm 'configure'
# This step requires autoconf, automake, and libtool.
"${app[autoreconf]}" --install
koopa_cd ..
fi
koopa_cd "${dict[name]}-${dict[version]}"
./configure "${conf_args[@]}"
"${app[make]}" --jobs="${dict[jobs]}"
"${app[make]}" install
return 0
}
|
<gh_stars>10-100
package org.googlielmo.cifar10scala
import org.datavec.image.loader.CifarLoader
import org.deeplearning4j.datasets.iterator.impl.CifarDataSetIterator
import org.deeplearning4j.eval.Evaluation
//import org.deeplearning4j.ui.api.UIServer
//import org.deeplearning4j.ui.stats.StatsListener
//import org.deeplearning4j.ui.storage.InMemoryStatsStorage
//import org.deeplearning4j.optimize.listeners.ScoreIterationListener
import org.deeplearning4j.nn.api.OptimizationAlgorithm
import org.deeplearning4j.nn.conf.CacheMode
import org.deeplearning4j.nn.conf.ConvolutionMode
import org.deeplearning4j.nn.conf.GradientNormalization
import org.deeplearning4j.nn.conf.layers.ConvolutionLayer
import org.deeplearning4j.nn.conf.layers.DenseLayer
import org.deeplearning4j.nn.conf.layers.DropoutLayer
import org.deeplearning4j.nn.conf.layers.OutputLayer
import org.deeplearning4j.nn.conf.layers.SubsamplingLayer
import org.deeplearning4j.nn.conf.layers.PoolingType
import org.deeplearning4j.nn.conf.MultiLayerConfiguration
import org.deeplearning4j.nn.conf.NeuralNetConfiguration
import org.deeplearning4j.nn.conf.inputs.InputType
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork
import org.deeplearning4j.nn.weights.WeightInit
import org.nd4j.linalg.activations.Activation
import org.nd4j.linalg.api.ndarray.INDArray
import org.nd4j.linalg.dataset.DataSet
import org.nd4j.linalg.learning.config.Adam
import org.nd4j.linalg.lossfunctions.LossFunctions
object Cifar10Simple {
private val channels = 3
private val height = 32
private val width = 32
private val numLabels = CifarLoader.NUM_LABELS
private val seed = 123
private val epochs = 1
private val batchSize = 10
@throws[Exception]
def main(args: Array[String]) {
val trainDataSetIterator =
new CifarDataSetIterator(2, 5000, true)
val testDataSetIterator =
new CifarDataSetIterator(2, 200, false)
println(trainDataSetIterator.getLabels)
// Create the neural network
val conf = defineModelConfiguration
val model = new MultiLayerNetwork(conf)
model.init
// Set the UI Server
// val uiServer = UIServer.getInstance();
// val statsStorage = new InMemoryStatsStorage();
// uiServer.attach(statsStorage);
// model.setListeners(new StatsListener( statsStorage),new ScoreIterationListener(1))
val labelStr =
(trainDataSetIterator.getLabels.toArray(new Array[String](trainDataSetIterator.getLabels().size()))).mkString(",")
for(i <- 0 to epochs) {
println("Epoch=====================" + i)
model.fit(trainDataSetIterator)
}
println("=====eval model========")
val eval = new Evaluation(testDataSetIterator.getLabels());
while(testDataSetIterator.hasNext()) {
val testDS = testDataSetIterator.next(batchSize);
val output = model.output(testDS.getFeatures());
eval.eval(testDS.getLabels(), output);
}
System.out.println(eval.stats());
println("--- Application end. ---")
}
def defineModelConfiguration(): MultiLayerConfiguration =
new NeuralNetConfiguration.Builder()
.seed(seed)
.cacheMode(CacheMode.DEVICE)
.updater(new Adam(1e-2))
.biasUpdater(new Adam(1e-2*2))
.gradientNormalization(GradientNormalization.RenormalizeL2PerLayer)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.l1(1e-4)
.l2(5 * 1e-4)
.list
.layer(0, new ConvolutionLayer.Builder(Array(4, 4), Array(1, 1), Array(0, 0)).name("cnn1").convolutionMode(ConvolutionMode.Same)
.nIn(3).nOut(64).weightInit(WeightInit.XAVIER_UNIFORM).activation(Activation.RELU)
.biasInit(1e-2).build)
.layer(1, new ConvolutionLayer.Builder(Array(4, 4), Array(1, 1), Array(0, 0)).name("cnn2").convolutionMode(ConvolutionMode.Same)
.nOut(64).weightInit(WeightInit.XAVIER_UNIFORM).activation(Activation.RELU)
.biasInit(1e-2).build)
.layer(2, new SubsamplingLayer.Builder(PoolingType.MAX, Array(2,2)).name("maxpool2").build())
.layer(3, new ConvolutionLayer.Builder(Array(4, 4), Array(1, 1), Array(0, 0)).name("cnn3").convolutionMode(ConvolutionMode.Same)
.nOut(96).weightInit(WeightInit.XAVIER_UNIFORM).activation(Activation.RELU)
.biasInit(1e-2).build)
.layer(4, new ConvolutionLayer.Builder(Array(4, 4), Array(1, 1), Array(0, 0)).name("cnn4").convolutionMode(ConvolutionMode.Same)
.nOut(96).weightInit(WeightInit.XAVIER_UNIFORM).activation(Activation.RELU)
.biasInit(1e-2).build)
.layer(5, new ConvolutionLayer.Builder(Array(3,3), Array(1, 1), Array(0, 0)).name("cnn5").convolutionMode(ConvolutionMode.Same)
.nOut(128).weightInit(WeightInit.XAVIER_UNIFORM).activation(Activation.RELU)
.biasInit(1e-2).build)
.layer(6, new ConvolutionLayer.Builder(Array(3,3), Array(1, 1), Array(0, 0)).name("cnn6").convolutionMode(ConvolutionMode.Same)
.nOut(128).weightInit(WeightInit.XAVIER_UNIFORM).activation(Activation.RELU)
.biasInit(1e-2).build)
.layer(7, new ConvolutionLayer.Builder(Array(2,2), Array(1, 1), Array(0, 0)).name("cnn7").convolutionMode(ConvolutionMode.Same)
.nOut(256).weightInit(WeightInit.XAVIER_UNIFORM).activation(Activation.RELU)
.biasInit(1e-2).build)
.layer(8, new ConvolutionLayer.Builder(Array(2,2), Array(1, 1), Array(0, 0)).name("cnn8").convolutionMode(ConvolutionMode.Same)
.nOut(256).weightInit(WeightInit.XAVIER_UNIFORM).activation(Activation.RELU)
.biasInit(1e-2).build)
.layer(9, new SubsamplingLayer.Builder(PoolingType.MAX, Array(2,2)).name("maxpool8").build())
.layer(10, new DenseLayer.Builder().name("ffn1").nOut(1024).updater(new Adam(1e-3)).biasInit(1e-3).biasUpdater(new Adam(1e-3*2)).build)
.layer(11,new DropoutLayer.Builder().name("dropout1").dropOut(0.2).build)
.layer(12, new DenseLayer.Builder().name("ffn2").nOut(1024).biasInit(1e-2).build)
.layer(13,new DropoutLayer.Builder().name("dropout2").dropOut(0.2).build)
.layer(14, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.name("output")
.nOut(numLabels)
.activation(Activation.SOFTMAX)
.build)
.backprop(true)
.pretrain(false)
.setInputType(InputType.convolutional(height, width, channels))
.build
}
|
<filename>src/utils/colorise.ts
/**
* List of ANSI escapes codes for colors
*/
export enum AnsiEscapesColors {
BLACK = 90,
RED = 91,
GREEN = 92,
YELLOW = 93,
BLUE = 94,
MAGENTA = 95,
CYAN = 96,
WHITE = 97
}
/**
* Prints a text in color
* @param text {string} - The text to print
* @param color {number} - The ANSI escape code
*/
export const colorise = (
text: string,
color: number = AnsiEscapesColors.WHITE
): string => {
return `\x1b[${color}m${text}\x1b[m`;
};
|
#!/bin/bash
trap "rm server;kill 0" EXIT
go build -o server
./server -port=8001 &
./server -port=8002 &
./server -port=8003 -api=1 &
sleep 2
echo ">>> start test"
curl "http://localhost:9999/api?key=Tom" &
curl "http://localhost:9999/api?key=Tom" &
curl "http://localhost:9999/api?key=Tom" &
curl "http://localhost:9999/api?key=Tom" &
curl "http://localhost:9999/api?key=Tom" &
curl "http://localhost:9999/api?key=Tom" &
curl "http://localhost:9999/api?key=Tom" &
wait
|
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('stock_prices.csv')
# Preprocessing the data
# Convert the date column to datetime
dataset['date'] = pd.to_datetime(dataset['date'])
# Select the feature columns and target column
X = dataset.iloc[:, 1:-1].values
y = dataset.iloc[:, -1].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Fitting the model to the Training set
# Importing the regressor
from sklearn.svm import SVR
# Create regressor object
regressor = SVR(kernel='rbf')
# Fit the regressor to the training dataset
regressor.fit(X_train, y_train)
# Predicting the Test set results
y_pred = regressor.predict(X_test)
# Calculate the RMSE (Root Mean Squared Error)
from sklearn.metrics import mean_squared_error
rmse = (mean_squared_error(y_test, y_pred)**0.5)
# Print the RMSE
print('Root Mean Squared Error =', rmse)
|
<filename>snippety/src/main/java/com/fueled/snippety/span/HorizontalLineSpan.java
package com.fueled.snippety.span;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.style.ReplacementSpan;
/**
* source: https://medium.com/@efemoney/i-drew-lines-in-a-textview-using-text-spans-31bce948acaf
*/
import java.lang.ref.WeakReference;
/**
* Draws a line with specified Drawable.
*
* source: @link{https://medium.com/@efemoney/i-drew-lines-in-a-textview-using-text-spans-31bce948acaf}
*/
public class HorizontalLineSpan extends ReplacementSpan {
private Drawable drawable;
public HorizontalLineSpan(Drawable drawable) {
this.drawable = drawable;
}
@Override
public int getSize(Paint paint, CharSequence text,
int start, int end,
Paint.FontMetricsInt fm) {
return 0;
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y,
int bottom, Paint paint) {
Paint.FontMetricsInt fmi = paint.getFontMetricsInt();
int height = fmi.descent - fmi.ascent; // set the drawable height to the height of the current font
Drawable b = getDrawable(canvas.getWidth(), height);
canvas.save();
int transY = bottom - b.getBounds().bottom;
canvas.translate(x, transY);
b.draw(canvas);
canvas.restore();
}
private Drawable getDrawable(int width, int height) {
// We copy the implementation of getCachedDrawable in DynamicDrawableSpan
Drawable d = getCachedDrawable();
d.setBounds(0, 0, width, height);
return d;
}
public Drawable getDrawable() {
return drawable;
}
// Redefined locally because it is a private member from DynamicDrawableSpan
private Drawable getCachedDrawable() {
WeakReference<Drawable> wr = mDrawableRef;
Drawable d = null;
if (wr != null)
d = wr.get();
if (d == null) {
d = getDrawable();
mDrawableRef = new WeakReference<>(d);
}
return d;
}
private WeakReference<Drawable> mDrawableRef;
}
|
package glutton
import (
"bufio"
"context"
"fmt"
"net"
"strings"
)
func readFTP(conn net.Conn, g *Glutton) (msg string, err error) {
msg, err = bufio.NewReader(conn).ReadString('\n')
if err != nil {
g.logger.Error(fmt.Sprintf("[ftp ] error: %v", err))
}
g.logger.Info(fmt.Sprintf("[ftp ] recv: %q", msg))
return
}
// HandleFTP takes a net.Conn and does basic FTP communication
func (g *Glutton) HandleFTP(ctx context.Context, conn net.Conn) (err error) {
defer func() {
err = conn.Close()
if err != nil {
g.logger.Error(fmt.Sprintf("[ftp ] error: %v", err))
}
}()
conn.Write([]byte("220 Welcome!\r\n"))
for {
g.updateConnectionTimeout(ctx, conn)
msg, err := readFTP(conn, g)
if len(msg) < 4 || err != nil {
break
}
cmd := strings.ToUpper(msg[:4])
if cmd == "USER" {
conn.Write([]byte("331 OK.\r\n"))
} else if cmd == "PASS" {
conn.Write([]byte("230 OK.\r\n"))
} else {
conn.Write([]byte("200 OK.\r\n"))
}
}
return nil
}
|
#!/bin/bash
# Check your password at haveibeenpwned.com
# KH 2019
URL="https://api.pwnedpasswords.com/range"
echo -n "Enter password (No echo): "
read -s pw
echo
SHA1=$(echo -n "$pw" | sha1sum | awk '{print toupper($1)}')
SHA5C=$(echo -n "$SHA1" | cut -c1-5);
SHAREST=$(echo -n "$SHA1" | cut -c6-);
RES=$(curl -A "My agent" -s $URL/$SHA5C | sed 's/\r//' | grep "$SHAREST")
if [ ! -z "$RES" ]; then
TIMES=$(echo -n $RES | cut -d ':' -f 2);
echo "Password found $TIMES times";
else
echo "Password not found";
fi
|
/**
* Constants and static configuration used by the {@link SolrIndexInstaller}
*
* @author <NAME>
*
*/
public final class IndexInstallerConstants {
private IndexInstallerConstants() { /* do not create instances */}
/**
* The schema used for transformed resources.
*/
public static final String SOLR_INDEX_ARCHIVE_RESOURCE_TYPE = "solrarchive";
/**
* The type of transformed resources.
*/
public static final String SOLR_INDEX_TRANSFORMED_RESOURCE_TYPE = "transformed";
/**
* Retrieves the type of transformed resources.
*
* @return the type of transformed resources
*/
public static String getTransformedResourceType() {
return SOLR_INDEX_TRANSFORMED_RESOURCE_TYPE;
}
}
|
<gh_stars>1-10
const { clone } = require("../../utils");
const { getLocalBdnsEntryListExcludingSelfAsync, getHeadersWithExcludedProvidersIncludingSelf } = require("../../utils/request-utils");
function convertReadableStreamToBuffer(readStream, callback) {
let buffers = [];
readStream.on("data", (chunk) => buffers.push(chunk));
readStream.on("error", (error) => callback(error));
readStream.on("end", () => callback(undefined, $$.Buffer.concat(buffers)));
}
function getBricksDomainConfig(domain) {
const config = require("../../config");
const domainConfiguration = config.getDomainConfig(domain);
if (!domainConfiguration) {
return;
}
let domainConfig = domainConfiguration.bricking;
domainConfig = clone(domainConfig || {});
domainConfig.path = require("path").join(config.getConfig("externalStorage"), `domains/${domain}/brick-storage`);
return domainConfig;
}
async function getBrickFromExternalProvidersAsync(request, domain, hashLink) {
let brickingProviders = await getLocalBdnsEntryListExcludingSelfAsync(request, domain, "brickStorages");
if (!brickingProviders || !brickingProviders.length) {
throw new Error(`[Bricking] Found no fallback bricking providers!`);
}
const http = require("opendsu").loadApi("http");
for (let i = 0; i < brickingProviders.length; i++) {
const providerUrl = brickingProviders[i];
try {
const brickUrl = `${providerUrl}/bricking/${domain}/get-brick/${hashLink}`;
let providerResponse = await http.fetch(brickUrl, {
headers: getHeadersWithExcludedProvidersIncludingSelf(request),
});
providerResponse = await providerResponse.text();
return providerResponse;
} catch (error) {
// console.warn(`[Bricking] Failed to get brick ${hashLink} from ${providerUrl}!`, error);
}
}
throw new Error(`[Bricking] Could not load brick ${hashLink} from external providers`);
}
async function getBrickWithExternalProvidersFallbackAsync(request, domain, hashLink, fsBrickStorage) {
try {
const brick = await fsBrickStorage.getBrickAsync(hashLink);
if (brick) {
return brick;
}
} catch (error) {
console.warn(`[Bricking] Brick ${hashLink} not found. Trying to fallback to other providers...`);
}
try {
const externalBrick = await getBrickFromExternalProvidersAsync(request, domain, hashLink);
// saving the brick in the next cycle in order to not block the get brick request
setTimeout(async () => {
try {
console.info(`[Bricking] Saving external brick ${hashLink} to own storage...`);
await fsBrickStorage.addBrickAsync(externalBrick);
console.info(`[Bricking] Saved external brick ${hashLink} to own storage`);
} catch (error) {
console.warn("[Bricking] Fail to manage external brick saving!", error);
}
});
return externalBrick;
} catch (error) {
console.warn(`[Bricking] Error while trying to get missing brick from fallback providers!`, error);
throw error;
}
}
module.exports = {
convertReadableStreamToBuffer,
getBricksDomainConfig,
getBrickWithExternalProvidersFallbackAsync,
};
|
#!/bin/bash
### Script to install frameworks ###
# Any subsequent(*) commands which fail will cause the shell script to exit immediately
set -e
declare -a tests_frameworks=("github \"Quick\/Nimble\"" "github \"Quick\/Quick\"" "github \"uber\/ios-snapshot-test-case\"" "github \"ashfurrow\/Nimble-Snapshots\"")
disableTestsFramework() {
previous_cartfile=`cat "Cartfile.resolved"`
for i in "${tests_frameworks[@]}"; do
sed -i '' "/$i/d" "Cartfile.resolved"
done
trap "enableTestsFramework" ERR
trap "enableTestsFramework" INT
}
enableTestsFramework() {
echo "$previous_cartfile" > "Cartfile.resolved"
trap '' ERR
trap '' INT
}
# Assume scripts are placed in /Scripts/Carthage dir
base_dir=$(dirname "$0")
cd "$base_dir"
# includes
. ./utils.sh
cd ..
cd ..
applyXcode12Workaround
# Try one level up if didn't find Cartfile.
if [ ! -f "Cartfile" ]; then
cd ..
if [ ! -f "Cartfile" ]; then
printf >&2 "\n${red_color}Unable to locate 'Cartfile'${no_color}\n\n"
exit 1
fi
fi
mkdir -p "Carthage"
touch "Carthage/cartSum.txt"
if [ ! -f "Carthage/cartSum.txt" ]; then
prevSum="null";
else
prevSum=`cat Carthage/cartSum.txt`;
fi
# Get checksum
cartSum=`{ cat Cartfile.resolved; xcrun swift -version; } | md5`
if [ "$prevSum" != "$cartSum" ] || [ ! -d "Carthage/Build/iOS" ]; then
echo "Carthage frameworks are outdated. Updating..."
rm "$cart_sum_file" 2> /dev/null || :
# Install main app frameworks. Ignore tests frameworks.
disableTestsFramework
carthage bootstrap --platform iOS --cache-builds
enableTestsFramework
echo ""
# Update checksum file
cartSum=`{ cat Cartfile.resolved; xcrun swift -version; } | md5`
echo $cartSum > Carthage/cartSum.txt
else
echo "Carthage frameworks up to date"
fi
|
#!/bin/bash
# Run from directory containing SibeliaZ output directories
# Creates CSV, with one line per maf2synteny "b" value per SibeliaZ "m" value, containing block length and total
# Requires 2 flags: "s" should be set to the number of genomes in the sample, "p" should be set to the prefix of SibeliaZ
# output directory names in order to differentiate them from other present directories
echo "Starting."
# Handling flags
while getopts ":s:p:" flag
do
case "$flag" in
s) span=$OPTARG;;
p) prefix="$OPTARG";;
\?) echo "Unrecognized flag."
esac
done
# Setup
py="/home/davidb/Desktop/scripts/get_core_genome_length.py"
op="`pwd`/core_genome_lengths.csv"
span=10
# Clear pre-existing output file
if [ -f $op ]; then
rm $op
fi
# Create header
echo "m,b,count,length" >> $op
# Iterate through SibeliaZ outputs
for mdir in ${prefix}*; do
echo $mdir
cd $mdir
#Iterate through maf2synteny outputs
for bdir in *; do
if [ -d $bdir ]; then
cd $bdir
echo -n "${mdir//[!0-9]/},${bdir}," >> $op
# Run Python script to count number of full-span synteny blocks and core genome length
python $py $span >> $op
echo $bdir
cd ../
fi
done
cd ../
done
echo "Done."
|
#!/bin/bash -e
GH_BOM_BRANCH="7.5.x"
GH_PROD_BRANCH="$GH_BOM_BRANCH-devel"
GH_PROD_VERSION=$(curl -s https://raw.githubusercontent.com/redhat-developer/redhat-sso-boms/$GH_BOM_BRANCH/pom.xml | grep -m1 "<version>" | sed 's/<[^>]*>//g' | tr -d ' ')
KEYCLOAK_VERSION=$(curl -s https://raw.githubusercontent.com/redhat-developer/redhat-sso-boms/$GH_BOM_BRANCH/pom.xml | grep -m1 "<version.keycloak>" | sed 's/<[^>]*>//g' | tr -d ' ')
if [ "$GH_USER_NAME" != "" ] && [ "$GH_USER_EMAIL" != "" ] && [ "$GH_TOKEN" != "" ] && [ "$GH_REF" != "" ]; then
DRY_RUN="false"
else
DRY_RUN="true"
fi
if [ "$DRY_RUN" == "false" ]; then
git config user.name "${GH_USER_NAME}"
git config user.email "{GH_USER_EMAIL}"
fi
if [ "$DRY_RUN" == "true" ]; then
if ( git branch | grep 'prod_staging' &>/dev/null ); then
echo "prod_staging branch already exists, please delete and re-run"
exit 1
fi
fi
# Rename Keycloak to Red Hat SSO
find . -type f \( -name "*README*" -o -name "*getting-started*" -o -name "*test-development*" \) -exec sed -i 's@<span>Keycloak</span>@Red Hat SSO@g' {} +
# Rename repository links
find . -type f \( -name "*README*" -o -name "*getting-started*" -o -name "*test-development*" \) -exec sed -i 's@keycloak/keycloak-quickstarts@redhat-developer/redhat-sso-quickstarts@g' {} +
# Rename WildFly to JBoss EAP
find . -type f \( -name "*README*" -o -name "*getting-started*" -o -name "*test-development*" \) -exec sed -i 's@<span>WildFly 10</span>@JBoss EAP 7.1.0@g' {} +
find . -type f \( -name "*README*" -o -name "*getting-started*" -o -name "*test-development*" \) -exec sed -i 's@<span>WildFly</span>@JBoss EAP@g' {} +
# Rename env
find . -type f \( -name "*README*" -o -name "*getting-started*" -o -name "*test-development*" \) -exec sed -i 's@<span>KEYCLOAK_HOME</span>@RHSSO_HOME@g' {} +
find . -type f \( -name "*README*" -o -name "*getting-started*" -o -name "*test-development*" \) -exec sed -i 's@<span>WILDFLY_HOME</span>@EAP_HOME@g' {} +
# Rename commands
find . -type f \( -name "*README*" -o -name "*getting-started*" -o -name "*test-development*" \) -exec sed -i 's@KEYCLOAK_HOME/bin@RHSSO_HOME/bin@g' {} +
find . -type f \( -name "*README*" -o -name "*getting-started*" -o -name "*test-development*" \) -exec sed -i 's@KEYCLOAK_HOME\\bin@RHSSO_HOME\\bin@g' {} +
find . -type f \( -name "*README*" -o -name "*getting-started*" -o -name "*test-development*" \) -exec sed -i 's@WILDFLY_HOME/bin@EAP_HOME/bin@g' {} +
find . -type f \( -name "*README*" -o -name "*getting-started*" -o -name "*test-development*" \) -exec sed -i 's@WILDFLY_HOME\\bin@EAP_HOME\\bin@g' {} +
# Remove JBoss Repo
sed -i '/<repositories>/,/<\/repositories>/ d' pom.xml
# Add RHSSO Repo
sed -i '/<\/modules>/{
a \ </modules>
a \
r scripts/ssorepo.txt
d
}' pom.xml
# Update version to productized versions
find . -type f -name "*pom.xml*" -exec sed -i "s/<version>.*SNAPSHOT/<version>$GH_PROD_VERSION/g" {} +
find . -type f -name "*pom.xml*" -exec sed -i "s@<version.keycloak>.*</version.keycloak>@<version.keycloak>$KEYCLOAK_VERSION</version.keycloak>@g" {} +
# Switch to productized artifacts
new_version='${project.version}'
find . -type f -name "*pom.xml*" -exec sed -i '/<dependency>/ {
:start
N
/<\/dependency>$/!b start
/<groupId>org.keycloak.bom<\/groupId>/ {
s/\(<version>\).*\(<\/version>\)/\1'"$new_version"'\2/
}
}' {} +
find . -type f -name "*pom.xml*" -exec sed -i 's@org.keycloak.bom@com.redhat.bom.rh-sso@g' {} +
find . -type f -name "*pom.xml*" -exec sed -i 's@keycloak-adapter-bom@rh-sso-adapter-bom@g' {} +
find . -type f -name "*pom.xml*" -exec sed -i 's@keycloak-spi-bom@rh-sso-spi-bom@g' {} +
find . -type f -name "*pom.xml*" -exec sed -i 's@keycloak-misc-bom@rh-sso-misc-bom@g' {} +
# Rename names in POMs
find . -type f -name "*pom.xml*" -exec sed -i 's@<name>Keycloak Quickstart@<name>Red Hat SSO Quickstart@g' {} +
git checkout -b prod_staging
git checkout action-token-authenticator/pom.xml
git checkout action-token-required-action/pom.xml
git checkout app-springboot/pom.xml
git checkout app-springboot/README.md
git checkout event-listener-sysout/pom.xml
git checkout event-store-mem/pom.xml
git rm -r -f action-token-authenticator
git rm -r -f action-token-required-action
git rm -r -f app-springboot
git rm -r -f kubernetes-examples
git rm -r -f openshift-examples
git rm -r -f event-listener-sysout
git rm -r -f event-store-mem
git rm -r -f applications/app-vue
git status
git commit . -m "Converted to RH-SSO QuickStarts"
if [ "$DRY_RUN" == "false" ]; then
git push --force "https://${GH_TOKEN}@${GH_REF}" prod_staging:$GH_PROD_BRANCH
else
echo ""
echo "Dry run, not committing"
echo ""
fi
|
import os
import scipy
import numpy as np
from ImageStatistics import UsefulImDirectory
import scipy as sp
import ast
from bokeh.charts import Histogram, show
import pandas as pd
class Game(object):
def __init__(self, gamefolder):
self.gamefolder = os.path.abspath(gamefolder)
file = open(os.path.join(gamefolder, "sales"))
self.releaseplayers = int(file.readline().rstrip("\n").split(": ")[1])
file.close()
file = open(os.path.join(gamefolder, "imagelinks"))
self.gameid = int(file.readline().rstrip("\n"))
file.close()
self.images = UsefulImDirectory.ImAggregate(os.path.join(gamefolder, "imgs"))
self.stats = ["means", "variances", "medians", "iqrs", "stddevs", "contrast"]
self.data = None
def getdata(self):
if self.data is None:
self.data = [self.images.getdata("reds"), self.images.getdata("greens"), self.images.getdata("blues")]
return self.data
else:
return self.data
def getcontrast(self):
return self.images.getdata("contrast")
def getplayers(self):
return self.releaseplayers
def calcstat(self, stat):
if stat not in self.stats:
raise AssertionError("Please choose a valid stat")
if stat == "means":
return [np.mean(x) for x in self.getdata()]
elif stat == "variances":
return [np.var(x) for x in self.getdata()]
elif stat == "medians":
return [np.median(x) for x in self.getdata()]
elif stat == "iqrs":
return [sp.stats.iqr(x) for x in self.getdata()]
elif stat == "stddevs":
return [np.std(x) for x in self.getdata()]
elif stat == "contrast":
return self.getcontrast()
def storestats(self):
file = open(os.path.join(self.gamefolder, "stats"), 'w+')
for x in self.stats:
towrite = self.calcstat(x)
file.write(x + ": " + str(towrite) + "\n")
file.close()
def readstats(self):
file = open(os.path.join(self.gamefolder, "stats"))
means = ast.literal_eval(file.readline().rstrip("\n").split(": ")[1])
variances = ast.literal_eval(file.readline().rstrip("\n").split(": ")[1])
medians = ast.literal_eval(file.readline().rstrip("\n").split(": ")[1])
iqrs = ast.literal_eval(file.readline().rstrip("\n").split(": ")[1])
stddevs = ast.literal_eval(file.readline().rstrip("\n").split(": ")[1])
line = file.readline().rstrip("\n").split(": ")[1]
try:
contrast = ast.literal_eval(line)
except ValueError:
tocont = line.replace("nan, ", "")
contrast = ast.literal_eval(tocont)
file.close()
return {"means": means, "variances": variances, "medians": medians, "iqrs": iqrs, "stddevs": stddevs, "contrast": contrast}
def colorhistogram(self, color):
colors = ["red", "green", "blue"]
if color.lower() not in colors:
raise AssertionError("Please pick a valid color")
self.histograms = {}
tohist = {"red": 0, "green": 1, "blue": 2}
self.histograms[color.lower()] = Histogram(pd.DataFrame(self.getdata()[tohist[color.lower()]], columns=[color.lower()]),values=color.lower(),color=color.capitalize(),bins=255)
show(self.histograms[color.lower()])
|
export PATH=/usr/local/python3.7.5/bin:/usr/local/Ascend/ascend-toolkit/latest/atc/ccec_compiler/bin:/usr/local/Ascend/ascend-toolkit/latest/atc/bin:$PATH
export PYTHONPATH=/usr/local/Ascend/ascend-toolkit/latest/atc/python/site-packages/:$PYTHONPATH
export LD_LIBRARY_PATH=/usr/local/Ascend/ascend-toolkit/latest/atc/lib64:$LD_LIBRARY_PATH
export ASCEND_OPP_PATH=/usr/local/Ascend/ascend-toolkit/latest/opp
# export DUMP_GE_GRAPH=2
export ASCEND_SLOG_PRINT_TO_STDOUT=1
/usr/local/Ascend/ascend-toolkit/latest/atc/bin/atc --model=$1 --framework=5 --output=$2 --input_format=ND --input_shape="input:1,4,224,224,160" --log=info --soc_version=Ascend310 --out_nodes="Conv_80:0"
|
<gh_stars>10-100
/* mbed USBHost Library
* Copyright (c) 2006-2013 ARM Limited
*
* 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 USBHOSTKEYBOARD_H
#define USBHOSTKEYBOARD_H
#include "USBHostConf.h"
#if USBHOST_KEYBOARD
#include "USBHost.h"
/**
* A class to communicate a USB keyboard
*/
class USBHostKeyboard : public IUSBEnumerator
{
public:
/**
* Constructor
*/
USBHostKeyboard();
/**
* Try to connect a keyboard device
*
* @return true if connection was successful
*/
bool connect();
/**
* Check if a keyboard is connected
*
* @returns true if a keyboard is connected
*/
bool connected();
/**
* Attach a callback called when a keyboard event is received
*
* @param ptr function pointer
*/
inline void attach(void (*ptr)(uint8_t key))
{
if (ptr != NULL) {
onKey = ptr;
}
}
/**
* Attach a callback called when a keyboard event is received
*
* @param ptr function pointer
*/
inline void attach(void (*ptr)(uint8_t keyCode, uint8_t modifier))
{
if (ptr != NULL) {
onKeyCode = ptr;
}
}
protected:
//From IUSBEnumerator
virtual void setVidPid(uint16_t vid, uint16_t pid);
virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed
virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used
private:
USBHost * host;
USBDeviceConnected * dev;
USBEndpoint * int_in;
uint8_t report[9];
int keyboard_intf;
bool keyboard_device_found;
bool dev_connected;
void rxHandler();
void (*onKey)(uint8_t key);
void (*onKeyCode)(uint8_t key, uint8_t modifier);
int report_id;
void init();
};
#endif
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.