content
stringlengths 7
2.61M
|
---|
Q:
A few questions about basic capacitor concepts
So say you a typical setup like in this diagram.
How does current flow while the capacitors charge? To elaborate, what is the mechanic that makes capacitors mimic the functionality of a wire instead of acting like the gap in the wire that they are?
When the capacitor is fully charged, the left plate is positive and the right plate is negative right? So does that mean when you disconnect the battery the capacitor discharges in the opposite direction that the batteries current was in?
A:
The Master of Analogies is here again...
You can think of the capacitor as a balloon.
While you're blowing the balloon up air is flowing out of your lungs (battery) and into the balloon (current flowing to charge the capacitor). As the balloon increases in size it displaces the air around it (the repulsed charge from the opposite plate of the capacitor). That is, until you have blown the balloon up as far as you can, at which point the air (current) can no longer flow.
If you put too much air pressure (voltage) the balloon bursts (just like a capacitor - have you ever seen an electrolytic explode?).
If you look at the charge curve of a capacitor it's actually very similar to the air flow curve you get when blowing up a balloon - rapid initial inflation then it gradually tapers off as it gets harder to get more air into it.
And yes, when you release the balloon the air flows out the way it came - in reverse.
A:
The mechanism is electrostatic repulsion -- the Coulomb force. The battery forces extra electrons onto the negative plate of the capacitor. The excess charge pushes an equal number of electrons off of the other plate and into the rest of the circuit. To the rest of the circuit, it looks like there's a current through the capacitor, since electrons go into one end and come out the other.
If you replace the battery with a short circuit, the capacitor will indeed produce a discharge current in the opposite direction of the charging current. (It's sort of like a spring.) If you replace the battery with an open circuit, no current flows and the capacitor remains charged. |
Q:
Submit button on top of the long form
For example user have Options page with long form in it. The most popular options are often on the top of the form, so user is changing them and have to scroll to the bottom of the form to hit "Submit" button. Imagine if user have to change something often and each time user should scroll to the bottom of the page to submit the form. IMHO it would be better for users to put "Submit" button above the form and they would scroll less. Example for testing two different types of forms on jsfiddle.
Sometimes long forms are splitted into tabs for making the form easier to use. But still it would be better to place "Submit" button above the tabs, because the height of tabs are different and the position on "Submit" button will not be the same.
Advantages of placing "Submit" button on the top:
"Submit" button is always on the same place no matter of how long form is
if the most frequently used options of the form are placed on the top part of form (as it should be) than in most cases "Submit" button will be visible for user without the scroll
Is there any disadvantages in placing "Submit" button on the top of the long form?
Possible compromise: maybe it would be good for users to put two "Submit" buttons in the long forms (one on the top of the form, another - at the bottom).
Similar question.
P.S. In the login or registration or survey forms "Submit" button should be in the bottom of the form because user will fill the text-inputs one-by-one and in the end user will hit "Submit" button. It would not be useful to place "Submit" button on the top of the form in these (or similar) cases.
A:
Expanding on my comment, a possibility is to simply use a floating header/footer submit button. This way the submit button is always visible and can easily be accessed regardless of one's position on the form.
This has a potential to be confusing though; it should be clear that you can't just press the submit button whenever (unless you can, of course). Instead you should use some inline validation to show what's missing on the form. A possibility is scrolling to the error on the form when clicking the submit button (since it might not be on screen) but I'd want to test that. Automatically moving the user's scroll position is rarely desired.
Consider the linearity of your form as well; a floating submit button would be best if your form is:
Multiple, scrollable pages in length
Either doesn't have a definite ending point or invites editing multiple parts of the form out of order
Often accessed to edit previously completed forms.
I can see this pattern being especially effective if the form were something like customer information where I might repeatedly need to access and edit an already filled out form. This becomes more like editing a document in Google Documents; Submit is now an easily accessible Save feature more than a final note on a sequential form. |
package com.jwisniowski.katas;
import org.junit.Before;
import org.junit.Test;
import java.util.LinkedList;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class KnightsTripTest {
private KnightsTrip sut;
@Before
public void setUp() throws Exception {
sut = new KnightsTrip();
}
@Test
public void cornerCaseTc1() {
// act
int result = sut.solve(1, 0);
// assert
assertThat(result, is(equalTo(3)));
}
@Test
public void cornerCaseTc2() {
int result = sut.solve(2, 2);
assertThat(result, is(equalTo(4)));
}
@Test
public void cornerCaseTc3() {
// act
int result = sut.solve(0, 1);
// assert
assertThat(result, is(equalTo(3)));
}
@Test
public void cornerCaseTc4() {
// act
int result = sut.solve(0, -1);
// assert
assertThat(result, is(equalTo(3)));
}
@Test
public void cornerCaseTc5() {
// act
int result = sut.solve(-1, 0);
// assert
assertThat(result, is(equalTo(3)));
}
@Test
public void cornerCaseTc6() {
// act
int result = sut.solve(0, 0);
// assert
assertThat(result, is(equalTo(0)));
}
@Test
public void cornerCaseTc7() {
// act
int result = sut.solve(1000000000, 1000000000);
// assert
assertThat(result, is(equalTo(666666668)));
}
@Test
public void cornerCaseTc8() {
// act
int result = sut.solve(-1000000000, -1000000000);
// assert
assertThat(result, is(equalTo(666666668)));
}
@Test
public void cornerCaseTc9() {
// act
int result = sut.solve(1000000000, -1000000000);
// assert
assertThat(result, is(equalTo(666666668)));
}
@Test
public void cornerCaseTc10() {
// act
int result = sut.solve(-1000000000, 1000000000);
// assert
assertThat(result, is(equalTo(666666668)));
}
@Test
public void basicTc1() {
// act
int result = sut.solve(7, 7);
// assert
assertThat(result, is(equalTo(6)));
}
@Test
public void basicTc2() {
// act
int result = sut.solve(9, 4);
// assert
assertThat(result, is(equalTo(5)));
}
@Test
public void basicTc3() {
// act
int result = sut.solve(9, 3);
// assert
assertThat(result, is(equalTo(6)));
}
@Test
public void basicTc4() {
// act
int result = sut.solve(4, 2);
// assert
assertThat(result, is(equalTo(2)));
}
@Test
public void basicTc5() {
// act
int result = sut.solve(5, 2);
// assert
assertThat(result, is(equalTo(3)));
}
@Test
public void basicTc6() {
// act
int result = sut.solve(6, 2);
// assert
assertThat(result, is(equalTo(4)));
}
@Test
public void basicTc7() {
// act
int result = sut.solve(7, -2);
// assert
assertThat(result, is(equalTo(5)));
}
@Test
public void basicTc8() {
// act
int result = sut.solve(-1, 1);
// assert
assertThat(result, is(equalTo(2)));
}
@Test
public void firstQuarterTc() {
// act
int rows = 13;
int cols = 13;
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < cols; i++) {
LinkedList<Integer> rowValues = new LinkedList<>();
for (int j = 0; j < rows; j++) {
rowValues.add(sut.solve(j, i));
}
resultBuilder.append(rowValues.stream().map(Object::toString).collect(joining(",")));
resultBuilder.append("|");
}
// assert
assertThat(resultBuilder.toString(),
is(equalTo(
"0,3,2,3,2,3,4,5,4,5,6,7,6|" +
"3,2,1,2,3,4,3,4,5,6,5,6,7|" +
"2,1,4,3,2,3,4,5,4,5,6,7,6|" +
"3,2,3,2,3,4,3,4,5,6,5,6,7|" +
"2,3,2,3,4,3,4,5,4,5,6,7,6|" +
"3,4,3,4,3,4,5,4,5,6,5,6,7|" +
"4,3,4,3,4,5,4,5,6,5,6,7,6|" +
"5,4,5,4,5,4,5,6,5,6,7,6,7|" +
"4,5,4,5,4,5,6,5,6,7,6,7,8|" +
"5,6,5,6,5,6,5,6,7,6,7,8,7|" +
"6,5,6,5,6,5,6,7,6,7,8,7,8|" +
"7,6,7,6,7,6,7,6,7,8,7,8,9|" +
"6,7,6,7,6,7,6,7,8,7,8,9,8|")));
}
} |
<filename>src/main/java/au/org/ands/vocabs/registry/api/context/JsonParseExceptionMapper.java
/** See the file "LICENSE" for the full license governing this code. */
package au.org.ands.vocabs.registry.api.context;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.core.JsonParseException;
import au.org.ands.vocabs.registry.api.user.ErrorResult;
/** Handler for {@link JsonParseException}s thrown during unmarshaling
* of JSON data provided as input to API calls.
* For the {@link ExceptionMapper} that handles
* errors with XML input data, see {@link BadRequestExceptionMapper}.
*/
// @Priority specified, in order to override the JsonParseExceptionMapper
// classes that come with Jackson.
@Priority(Priorities.ENTITY_CODER)
@Provider
public class JsonParseExceptionMapper
implements ExceptionMapper<JsonParseException> {
/** Return a response that is an {@link ErrorResult} which includes
* the generated parse error.
*/
@Override
public Response toResponse(final JsonParseException jpe) {
return Response.status(Response.Status.BAD_REQUEST).
entity(new ErrorResult("Bad request: "
+ jpe.toString())).
build();
}
}
|
/**
* Adds all tree production of other grammar to this grammar.
*
* @param other
*/
public void addAll(final TSGrammar<T> other) {
for (final ConcurrentHashMultiset<TreeNode<T>> treeSet : other.grammar
.values()) {
for (final Multiset.Entry<TreeNode<T>> entry : treeSet.entrySet()) {
addTree(entry.getElement(), entry.getCount());
}
}
} |
extern crate tui;
use tui::{Terminal, Frame};
use tui::backend::Backend;
use tui::layout::{Alignment, Rect};
use tui::style::{Color, Style};
use tui::text::Text;
use tui::widgets::Paragraph;
use crate::userinterface::widgets::{BORDERS, EMPTY_SPACES};
const TEXT_HEIGHT: u16 = 6;
const MIN_WIDTH: u16 = 50;
const MIN_HEIGHT: u16 = TEXT_HEIGHT + EMPTY_SPACES;
pub fn render<B: Backend>(terminal: &mut Terminal<B>) {
terminal.draw(|frame| {
let frame_area = frame.size();
let frame_left = frame_area.left();
let frame_top = frame_area.top();
let frame_width = frame_area.right() - frame_left;
let frame_height = frame_area.bottom() - frame_top;
if (frame_width >= MIN_WIDTH) && (frame_height >= MIN_HEIGHT) {
let text_area =
Rect::new(frame_left + 1, frame_top + frame_height/2 - TEXT_HEIGHT/2,
frame_width - BORDERS, TEXT_HEIGHT);
render_text(frame, &text_area);
}
}).unwrap();
}
fn render_text<B: Backend>(frame: &mut Frame<B>, area: &Rect) {
let exit_text = Paragraph::new(Text::from("The interface can't be displayed
correctly if your terminal size is too small.
If you continue to reduce the terminal
size, this message will be erased but the
application will still run until your
terminal will be bigger."))
.alignment(Alignment::Center)
.style(Style::default().fg(Color::Red));
frame.render_widget(exit_text, *area);
}
|
Cine MRI using steady state free precession in the radial long axis orientation is a fast accurate method for obtaining volumetric data of the left ventricle In this study we assessed the use of a steady state free precession (SSFP) cine sequence in a series of radially orientated long axis slices for the measurement of left ventricular volumes and mass. We validated the radial long axis approach in phantoms and ex vivo porcine hearts and applied it to normal volunteers and patients using the SSFP and turbo gradientecho (TGE) sequences. High quality images were obtained for analysis, and the measured volumes with radial long axis SSFP sequence correlated well with short axis TGE and SSFP volumes (r > 0.98). The best interobserver agreement for left ventricular volumes was obtained using SSFP in the long axis radial orientation (variability < 2.3%). We conclude that this combination of sequence and scan orientation has intrinsic advantages for image analysis due to the improved contrast and the avoidance of errors associated with the basal slice in the short axis orientation. J. Magn. Reson. Imaging 2001;14:685692. © 2001 WileyLiss, Inc. |
The Upward Occupational Mobility of Immigrant Women in Spain This paper studies the upward occupational mobility trajectories of immigrant women performing unskilled work as a first job in Spain. The goals of the research are to go beyond the debate that focuses on the structural elements that condition their labour trajectories in Spain and to include both personal factors and the way in which these women use their agency in order to shape their labour trajectories. We have opted for a mixed-method approach, using data from the National Immigrant Survey ENI-2007, combined with 42 socio-biographical interviews with immigrant women from Latin America living in the metropolitan areas of Barcelona and Madrid. |
Worsening back pain in a patient with established ankylosing spondylitis A 50-year-old man with established AS woke with severe central back pain. On bending, he felt a cracking sensation. He attended the emergency department, where plain radiographs of the thoracic and lumbar spine showed no obvious fracture. MRI of the spine was requested for a later date. Review of the plain films 6 days later identified a step in the thoracolumbar region (Fig. 1A). The patient had emergency MRI and CT scan of the spine. This showed a three-column fracture at T11/T12 (Fig. 1B), involving the anterior syndesmophyte, both laminae and T11 spinous process, with anterolisthesis. In AS, there is fusion of the vertebral bodies by syndesmophytes and fusion of the posterior vertebral elements (so-called bamboo spine). The altered biomechanics of the spine increase the risk of unstable three-column (anterior, middle and posterior) fractures following minimal trauma, with seemingly minor findings on plain radiographs. Subtle signs on plain radiographs include fractured syndesmophytes, widening of the disc space and anterolisthesis. Clinicians should be aware of these subtle radiographic findings, which should lead to cross-sectional imaging (MRI and CT) to assess the entire extent of the injury. The patient underwent T9L2 fixation. Four months on, he is well and has returned to work. |
#include "STDAgent.h"
#include "STDAgentManager.h"
#include "../STDEngine/STDEngine.h"
#include "../OSEnvironment/OSEnvironment.h"
#include "../World/WorldInfoManager.h"
#include "../STDParticleSystem/STDParticleSystemManager.h"
STDAgent::STDAgent(const std::string& name, const std::string& modelName)
: mAnimationState(NULL)
, mSelected(false)
, mSpeed(30)
, mElevation(0)
, mTurnSpeed(10)
, mHoverSpeed(10)
, mAlignment(Vector3::UNIT_X)
, mGun(NULL)
, mLife(1000)
, mCollisionRadius(2)
, mDestructable(true)
, mExplosionPSName("XS/Explosion")
, mExplosionDuration(1)
{
mAgentName=name;
mEntityName=name;
mNodeName=OSEnvironment::append(name, "Node");
SceneManager* sceneMgr=STDEngine::getSingletonPtr()->getSceneMgr();
mEntity=sceneMgr->createEntity(name, modelName);
mNode=sceneMgr->getRootSceneNode()->createChildSceneNode(mNodeName);
mNode->attachObject(mEntity);
const AnimationStateSet* ass=mEntity->getAllAnimationStates();
if(ass != NULL)
{
ConstAnimationStateIterator asi=ass->getAnimationStateIterator();
while(asi.hasMoreElements())
{
mAnimationStateNames.push_back(asi.peekNextKey());
asi.moveNext();
}
mAnimable=true;
}
else
{
mAnimable=false;
}
}
Gun* STDAgent::createGun()
{
mGun=new Gun(this);
return mGun;
}
STDAgent::~STDAgent()
{
if(mGun != NULL)
{
delete mGun;
mGun=NULL;
}
SceneManager* sceneMgr=STDEngine::getSingletonPtr()->getSceneMgr();
mNode->detachAllObjects();
sceneMgr->getRootSceneNode()->removeAndDestroyChild(mNodeName);
sceneMgr->destroyEntity(mEntityName);
}
void STDAgent::setPosition(const Vector3& pos)
{
Vector3 pos1(pos.x, pos.y + mElevation, pos.z);
mNode->setPosition(pos1);
}
void STDAgent::setPosition(const Real& x, const Real& y, const Real& z)
{
this->setPosition(Vector3(x, y, z));
}
void STDAgent::setScale(Real x, Real y, Real z)
{
mNode->scale(x, y, z);
}
void STDAgent::run(const Real& dt)
{
if(mAnimationState != NULL)
{
mAnimationState->addTime(dt);
}
if(mGun != NULL)
{
mGun->update(dt);
}
}
void STDAgent::yaw(const Real& degree)
{
mNode->yaw(Degree(degree));
}
void STDAgent::pitch(const Real& degree)
{
mNode->pitch(Degree(degree));
}
void STDAgent::roll(const Real& degree)
{
mNode->roll(Degree(degree));
}
void STDAgent::setAnimationState(const std::string& animation)
{
AnimationState* as=mEntity->getAnimationState(animation);
if(mAnimationState != as)
{
if(mAnimationState != NULL)
{
mAnimationState->setEnabled(false);
mAnimationState->setLoop(false);
}
mAnimationState=as;
mAnimationState->setEnabled(true);
mAnimationState->setLoop(true);
}
}
void STDAgent::addCamera(const std::string& camName, Ogre::Camera *cam, const Vector3& offset)
{
mCameras[camName]=cam;
SceneNode* camNode=cam->getParentSceneNode();
camNode->getParentSceneNode()->removeChild(camNode);
mNode->addChild(camNode);
camNode->setPosition(offset);
}
void STDAgent::removeCamera(const std::string& camName)
{
std::map<std::string, Ogre::Camera*>::iterator fnd=mCameras.find(camName);
if(fnd != mCameras.end())
{
mCameras.erase(fnd);
}
}
bool STDAgent::hasCamera(const std::string& camName) const
{
std::map<std::string, Ogre::Camera*>::const_iterator fnd=mCameras.find(camName);
return fnd != mCameras.end();
}
Ogre::Camera* STDAgent::getCamera(const std::string& camName)
{
std::map<std::string, Ogre::Camera*>::iterator fnd=mCameras.find(camName);
if(fnd != mCameras.end())
{
return fnd->second;
}
else
{
return NULL;
}
}
Vector3 STDAgent::getCamOffsetPosition(const std::string &camName) const
{
std::map<std::string, Ogre::Camera*>::const_iterator fnd=mCameras.find(camName);
if(fnd != mCameras.end())
{
return fnd->second->getParentSceneNode()->getPosition();
}
else
{
throw Exception(42, "fnd == mCameras.end()", "STDAgent::getCamPosition(const std::string&) const");
}
return Vector3(0, 0, 0);
}
Vector3 STDAgent::getCamDirection(const std::string& camName) const
{
// Vector3 direction = mCameras[camName]->getParentSceneNode()->getOrientation() * (mNode->getOrientation() * mAlignment);
/*
worldPos = parentWorldPos + parentWorldOrientation * position
worldPos - parentWorldPos = parentWorldOrientation * position
inv(parentWorldOrientation) * (worldPos-parentWorldPos) = inv(parentWorldOrientation) * parentWorldOrientation * position
position = inv(parentWorldOrientation) * (worldPos-parentWorldPos)
*/
std::map<std::string, Ogre::Camera*>::const_iterator fnd=mCameras.find(camName);
if(fnd != mCameras.end())
{
Vector3 direction = fnd->second->getParentSceneNode()->_getDerivedOrientation() * mAlignment;
direction.normalise();
return direction;
}
else
{
throw Exception(42, "fnd == mCameras.end()", "STDAgent::getCamPosition(const std::string&) const");
}
return Vector3(0, 0, 0);
}
void STDAgent::setSelected(bool selected)
{
mSelected=selected;
mNode->showBoundingBox(selected);
}
bool STDAgent::isSelected() const
{
return mSelected;
}
bool STDAgent::hasEntity(MovableObject* mo) const
{
return mEntity==mo;
}
void STDAgent::move(Real dt, bool landcraft)
{
Vector3 direction=mNode->getOrientation() * mAlignment;
direction.y=0;
direction.normalise();
Vector3 pos=mNode->getPosition() + direction * (dt * mSpeed);
if(landcraft)
{
Vector3 pos1(pos.x, getWorldHeight(pos.x, pos.z), pos.z);
this->setPosition(pos1);
}
else
{
this->setPosition(pos);
}
}
void STDAgent::turn(Real dt)
{
this->yaw(mTurnSpeed * dt);
}
void STDAgent::hover(Real dt)
{
this->setPosition(mNode->getPosition()+Vector3(0, mHoverSpeed * dt, 0));
}
bool STDAgent::isAnimable() const
{
return mAnimable;
}
void STDAgent::setMaterial(const String& materialName)
{
mEntity->setMaterialName(materialName);
}
void STDAgent::setElevation(const Real& value)
{
mElevation=value;
}
void STDAgent::setAlignment(const Ogre::Vector3 &align)
{
mAlignment=align;
}
Vector3 STDAgent::getCenter() const
{
Vector3 pos=mNode->getPosition();
pos.y+=(mEntity->getBoundingRadius() * mNode->getScale().y);
return pos;
}
void STDAgent::pitchCamera(const std::string& camName, const Real& dt, const Real& speed)
{
mCameras[camName]->getParentSceneNode()->pitch(Degree(dt * speed));
}
void STDAgent::yawCamera(const std::string& camName, const Real& dt, const Real& speed)
{
mCameras[camName]->getParentSceneNode()->yaw(Degree(dt * speed));
}
Vector3 STDAgent::getDirection() const
{
Vector3 direction = mNode->getOrientation() * mAlignment;
direction.normalise();
return direction;
}
void STDAgent::getHit(const Ogre::Real &damage)
{
if(mDestructable==false)
{
return;
}
Real pLife=mLife;
mLife-=damage;
if(mLife * pLife <= 0)
{
STDParticleSystem* ps=STDParticleSystemManager::getSingletonPtr()->createParticleSystem(mExplosionPSName, mExplosionDuration);
ps->setPosition(this->getPosition());
}
} |
<filename>webappfoundation/src/main/java/io/rtdi/bigdata/connector/connectorframework/rest/ProducerService.java
package io.rtdi.bigdata.connector.connectorframework.rest;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.annotation.security.RolesAllowed;
import jakarta.servlet.ServletContext;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Configuration;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import io.rtdi.bigdata.connector.connectorframework.IConnectorFactoryProducer;
import io.rtdi.bigdata.connector.connectorframework.WebAppController;
import io.rtdi.bigdata.connector.connectorframework.controller.ConnectionController;
import io.rtdi.bigdata.connector.connectorframework.controller.ConnectorController;
import io.rtdi.bigdata.connector.connectorframework.controller.ProducerController;
import io.rtdi.bigdata.connector.connectorframework.controller.ProducerInstanceController;
import io.rtdi.bigdata.connector.connectorframework.exceptions.ConnectorTemporaryException;
import io.rtdi.bigdata.connector.connectorframework.servlet.ServletSecurityConstants;
import io.rtdi.bigdata.connector.pipeline.foundation.PipelineAbstract;
import io.rtdi.bigdata.connector.pipeline.foundation.entity.ErrorEntity;
import io.rtdi.bigdata.connector.pipeline.foundation.entity.LoadInfo;
import io.rtdi.bigdata.connector.pipeline.foundation.entity.OperationLogContainer.StateDisplayEntry;
import io.rtdi.bigdata.connector.pipeline.foundation.enums.ControllerExitType;
import io.rtdi.bigdata.connector.properties.ProducerProperties;
import io.rtdi.bigdata.connector.properties.atomic.PropertyRoot;
@Path("/")
public class ProducerService {
@Context
private Configuration configuration;
@Context
private ServletContext servletContext;
private static IConnectorFactoryProducer<?,?> getConnectorFactory(ConnectorController connector) {
return (IConnectorFactoryProducer<?, ?>) connector.getConnectorFactory();
}
@GET
@Path("/connections/{connectionname}/producers")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ServletSecurityConstants.ROLE_VIEW)
public Response getProducers(@PathParam("connectionname") String connectionname) {
try {
ConnectorController connector = WebAppController.getConnectorOrFail(servletContext);
ConnectionController conn = connector.getConnectionOrFail(connectionname);
return Response.ok(new ProducersEntity(conn)).build();
} catch (Exception e) {
return JAXBErrorResponseBuilder.getJAXBResponse(e);
}
}
@GET
@Path("/connections/{connectionname}/producers/{producername}")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ServletSecurityConstants.ROLE_VIEW)
public Response getProperties(@PathParam("connectionname") String connectionname, @PathParam("producername") String producername) {
try {
ConnectorController connector = WebAppController.getConnectorOrFail(servletContext);
ConnectionController conn = connector.getConnectionOrFail(connectionname);
ProducerController producer = conn.getProducerOrFail(producername);
return Response.ok(producer.getProducerProperties().getPropertyGroupNoPasswords()).build();
} catch (Exception e) {
return JAXBErrorResponseBuilder.getJAXBResponse(e);
}
}
@GET
@Path("/connections/{connectionname}/producers/{producername}/transactions")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ServletSecurityConstants.ROLE_VIEW)
public Response getTransactions(@PathParam("connectionname") String connectionname, @PathParam("producername") String producername) {
try {
ConnectorController connector = WebAppController.getConnectorOrFail(servletContext);
ConnectionController conn = connector.getConnectionOrFail(connectionname);
ProducerController producer = conn.getProducerOrFail(producername);
Map<Integer, Map<String, LoadInfo>> m = connector.getPipelineAPI().getLoadInfo(producername);
TransactionInfo t = new TransactionInfo(m, producer);
return Response.ok(t).build();
} catch (Exception e) {
return JAXBErrorResponseBuilder.getJAXBResponse(e);
}
}
@POST
@Path("/connections/{connectionname}/producers/{producername}/transactions")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ServletSecurityConstants.ROLE_CONFIG)
public Response setTransactions(@PathParam("connectionname") String connectionname, @PathParam("producername") String producername, TransactionInfo data) {
try {
ConnectorController connector = WebAppController.getConnectorOrFail(servletContext);
ConnectionController conn = connector.getConnectionOrFail(connectionname);
ProducerController producer = conn.getProducer(producername);
producer.disableController(); // stop controller and keep it stopped so it is not recovered automatically
producer.joinAll(ControllerExitType.ABORT);
if (data.getProducertransactions() != null) {
for (ProducerTransactions p : data.getProducertransactions()) {
if (p.getDeltatransaction() != null && p.getDeltatransaction().size() > 0) {
if (p.getDeltatransaction().get(0).isResetdelta()) {
connector.getPipelineAPI().rewindDeltaLoad(producername, p.getInstanceno(), p.getDeltatransaction().get(0).getTransactionid());
}
}
if (p.getInitialloadtransactions() != null) {
for (SchemaTransaction init : p.getInitialloadtransactions()) {
if (init.isReset()) {
connector.getPipelineAPI().resetInitialLoad(producername, init.getSchemaname(), p.getInstanceno());
}
}
}
}
}
producer.startController();
return JAXBSuccessResponseBuilder.getJAXBResponse("created");
} catch (Exception e) {
return JAXBErrorResponseBuilder.getJAXBResponse(e);
}
}
@GET
@Path("/connections/{connectionname}/producer/template")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ServletSecurityConstants.ROLE_CONFIG)
public Response getPropertiesTemplate(@PathParam("connectionname") String connectionname) {
try {
ConnectorController connector = WebAppController.getConnectorOrFail(servletContext);
// Create an empty properties structure so the UI can show all properties needed
return Response.ok(getConnectorFactory(connector).createProducerProperties(null).getPropertyGroup()).build();
} catch (Exception e) {
return JAXBErrorResponseBuilder.getJAXBResponse(e);
}
}
@GET
@Path("/connections/{connectionname}/producers/{producername}/stop")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ServletSecurityConstants.ROLE_OPERATOR)
public Response stopProducer(@PathParam("connectionname") String connectionname, @PathParam("producername") String producername) {
try {
ConnectorController connector = WebAppController.getConnectorOrFail(servletContext);
ConnectionController conn = connector.getConnectionOrFail(connectionname);
ProducerController producer = conn.getProducerOrFail(producername);
producer.disableController();
producer.joinAll(ControllerExitType.ABORT);
return JAXBSuccessResponseBuilder.getJAXBResponse("stopped");
} catch (Exception e) {
return JAXBErrorResponseBuilder.getJAXBResponse(e);
}
}
@GET
@Path("/connections/{connectionname}/producers/{producername}/start")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ServletSecurityConstants.ROLE_OPERATOR)
public Response startProducer(@PathParam("connectionname") String connectionname, @PathParam("producername") String producername) {
try {
ConnectorController connector = WebAppController.getConnectorOrFail(servletContext);
ConnectionController conn = connector.getConnectionOrFail(connectionname);
ProducerController producer = conn.getProducerOrFail(producername);
if (!conn.isRunning()) {
throw new ConnectorTemporaryException("Cannot start a producer when its connection is not running", null, "First start the connection", connectionname);
}
File dir = new File(conn.getDirectory(), ConnectionController.DIR_PRODUCERS);
producer.getProducerProperties().read(dir);
producer.startController();
//TODO: Return if the producer was started correctly.
return JAXBSuccessResponseBuilder.getJAXBResponse("started");
} catch (Exception e) {
return JAXBErrorResponseBuilder.getJAXBResponse(e);
}
}
@POST
@Path("/connections/{connectionname}/producers/{producername}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ServletSecurityConstants.ROLE_CONFIG)
public Response setProperties(@PathParam("connectionname") String connectionname, @PathParam("producername") String producername, PropertyRoot data) {
try {
ConnectorController connector = WebAppController.getConnectorOrFail(servletContext);
ConnectionController conn = connector.getConnectionOrFail(connectionname);
ProducerController producer = conn.getProducer(producername);
File dir = new File(conn.getDirectory(), ConnectionController.DIR_PRODUCERS);
if (producer == null) {
ProducerProperties props = getConnectorFactory(connector).createProducerProperties(producername);
props.setValue(data);
if (dir.exists() == false) {
dir.mkdirs();
}
props.write(dir);
producer = conn.addProducer(props);
} else {
producer.stopController(ControllerExitType.ABORT);
producer.getProducerProperties().setValue(data);
producer.getProducerProperties().write(dir);
}
producer.startController();
return JAXBSuccessResponseBuilder.getJAXBResponse("created");
} catch (Exception e) {
return JAXBErrorResponseBuilder.getJAXBResponse(e);
}
}
@DELETE
@Path("/connections/{connectionname}/producers/{producername}")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ServletSecurityConstants.ROLE_CONFIG)
public Response deleteProperties(@PathParam("connectionname") String connectionname, @PathParam("producername") String producername) {
try {
ConnectorController connector = WebAppController.getConnectorOrFail(servletContext);
ConnectionController conn = connector.getConnectionOrFail(connectionname);
ProducerController producer = conn.getProducerOrFail(producername);
if (conn.removeProducer(producer)) {
return JAXBSuccessResponseBuilder.getJAXBResponse("deleted");
} else {
return JAXBSuccessResponseBuilder.getJAXBResponse("deleted but not shutdown completely");
}
} catch (Exception e) {
return JAXBErrorResponseBuilder.getJAXBResponse(e);
}
}
public static class ProducersEntity {
private List<ProducerEntity> producers;
public ProducersEntity(ConnectionController connection) {
if (connection.getProducers() != null) {
Collection<ProducerController> set = connection.getProducers().values();
this.producers = new ArrayList<>();
for (ProducerController producer : set) {
this.producers.add(new ProducerEntity(producer));
}
}
}
public List<ProducerEntity> getProducers() {
return producers;
}
}
public static class ProducerEntity {
private String name;
private String text;
private int instancecount;
private long rowsprocessedcount;
private String state;
List<ErrorEntity> messages;
private List<String> instancestates;
public ProducerEntity(ProducerController producer) {
ProducerProperties props = producer.getProducerProperties();
this.name = props.getName();
this.text = props.getPropertyGroup().getText();
instancecount = producer.getInstanceCount();
rowsprocessedcount = producer.getRowsProcessedCount();
state = producer.getState().name();
messages = producer.getErrorListRecursive();
instancestates = producer.getInstanceStates();
}
public long getRowsprocessedcount() {
return rowsprocessedcount;
}
public String getName() {
return name;
}
public String getText() {
return text;
}
public int getInstancecount() {
return instancecount;
}
public String getState() {
return state;
}
public List<ErrorEntity> getMessages() {
return messages;
}
public List<String> getInstancestates() {
return instancestates;
}
}
public static class TransactionInfo {
List<ProducerTransactions> p;
public TransactionInfo() {
}
public TransactionInfo(Map<Integer, Map<String, LoadInfo>> m, ProducerController producer) {
Map<Integer, ProducerTransactions> map = new HashMap<>();
if (m != null) {
for (Integer instanceno : m.keySet()) {
ProducerTransactions t = new ProducerTransactions(instanceno, m.get(instanceno));
map.put(instanceno, t);
}
}
HashMap<String, ProducerInstanceController> instances = producer.getInstances();
if (instances != null) {
for (ProducerInstanceController e : instances.values()) {
ProducerTransactions t = map.get(e.getInstanceNumber());
if (t == null) {
t = new ProducerTransactions(e.getInstanceNumber(), null);
map.put(e.getInstanceNumber(), t);
}
t.setOperationlogs(e.getOperationLog().asList());
}
}
if (map.size() != 0) {
p = new ArrayList<>();
p.addAll(map.values());
} else {
p = null;
}
}
public List<ProducerTransactions> getProducertransactions() {
return p;
}
public void setProducertransactions(List<ProducerTransactions> p) {
this.p = p;
}
}
public static class ProducerTransactions {
private Integer instanceno;
private List<SchemaTransaction> schematransactions;
private List<LoadInfo> deltatransaction;
private List<StateDisplayEntry> operationlogs;
public ProducerTransactions() {
}
public ProducerTransactions(Integer instanceno, Map<String, LoadInfo> schemamap) {
this.instanceno = instanceno;
if (schemamap != null) {
schematransactions = new ArrayList<>();
for (String s : schemamap.keySet()) {
if (s.equals(PipelineAbstract.ALL_SCHEMAS)) {
deltatransaction = Collections.singletonList(schemamap.get(s));
} else {
schematransactions.add(new SchemaTransaction(s, schemamap.get(s)));
}
}
}
}
public Integer getInstanceno() {
return instanceno;
}
public List<SchemaTransaction> getInitialloadtransactions() {
return schematransactions;
}
public List<LoadInfo> getDeltatransaction() {
return deltatransaction;
}
public void setInstanceno(Integer instanceno) {
this.instanceno = instanceno;
}
public void setInitialloadtransactions(List<SchemaTransaction> schematransactions) {
this.schematransactions = schematransactions;
}
public void setDeltatransaction(List<LoadInfo> deltatransaction) {
this.deltatransaction = deltatransaction;
}
public void setOperationlogs(List<StateDisplayEntry> operationlogs) {
this.operationlogs = operationlogs;
}
public List<StateDisplayEntry> getOperationlogs() {
return operationlogs;
}
}
public static class SchemaTransaction {
private String schemaname;
private LoadInfo transaction;
private boolean reset;
public SchemaTransaction() {
}
public SchemaTransaction(String schemaname, LoadInfo transaction) {
this.schemaname = schemaname;
this.transaction = transaction;
}
public String getSchemaname() {
return schemaname;
}
public LoadInfo getTransaction() {
return transaction;
}
public boolean isReset() {
return reset;
}
public void setReset(boolean reset) {
this.reset = reset;
}
public void setSchemaname(String schemaname) {
this.schemaname = schemaname;
}
public void setTransaction(LoadInfo transaction) {
this.transaction = transaction;
}
}
}
|
<gh_stars>0
const Box2D = require("box2dweb");
import {PLAYER_DENSITY, PLAYER_FRICTION, PLAYER_RESTITUTION, HINGE_SIZE, SHORT_LEG_LENGTH, LONG_LEG_LENGTH, PLAYER_JOINT_TORQUE} from "./constants";
export default class Player {
public shortLeg: any;
public longLeg: any;
public joint: any;
constructor(world: any, x: number, y: number) {
//start with the definitions of the fixtures and bodies
const playerLegFixtureDef = new Box2D.Dynamics.b2FixtureDef();
playerLegFixtureDef.density = PLAYER_DENSITY;
playerLegFixtureDef.friction = PLAYER_FRICTION;
playerLegFixtureDef.restitution = PLAYER_RESTITUTION;
playerLegFixtureDef.shape = new Box2D.Collision.Shapes.b2PolygonShape();
playerLegFixtureDef.shape.SetAsArray([
new Box2D.Common.Math.b2Vec2(HINGE_SIZE, 0),
new Box2D.Common.Math.b2Vec2(0, SHORT_LEG_LENGTH),
new Box2D.Common.Math.b2Vec2(-HINGE_SIZE, 0),
new Box2D.Common.Math.b2Vec2(0, -HINGE_SIZE)
], 4);
const playerLegBodyDef = new Box2D.Dynamics.b2BodyDef();
playerLegBodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
playerLegBodyDef.position.x = x;
playerLegBodyDef.position.y = y;
//then create instances of those definitions
this.shortLeg = world.CreateBody(playerLegBodyDef);
this.shortLeg.CreateFixture(playerLegFixtureDef);
//change definition's shape for long leg
playerLegFixtureDef.shape.SetAsArray([
new Box2D.Common.Math.b2Vec2(HINGE_SIZE, 0),
new Box2D.Common.Math.b2Vec2(0, LONG_LEG_LENGTH),
new Box2D.Common.Math.b2Vec2(-HINGE_SIZE, 0),
new Box2D.Common.Math.b2Vec2(0, -HINGE_SIZE)
], 4);
playerLegFixtureDef.density *= 2;
this.longLeg = world.CreateBody(playerLegBodyDef);
this.longLeg.CreateFixture(playerLegFixtureDef);
//gotta do the joint afterwards.
const jointDef = new Box2D.Dynamics.Joints.b2RevoluteJointDef();
jointDef.bodyA = this.shortLeg;
jointDef.bodyB = this.longLeg;
jointDef.anchorPoint = this.shortLeg.GetPosition();
jointDef.maxMotorTorque = PLAYER_JOINT_TORQUE;
jointDef.motorSpeed = 0;
jointDef.enableMotor = true;
this.joint = world.CreateJoint(jointDef);
}
get x() {
return this.shortLeg.GetPosition().x;
}
get y() {
return this.shortLeg.GetPosition().y;
}
}
|
<reponame>Gitman1989/chromium
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/profiles/profile_impl.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/scoped_ptr.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/appcache/chrome_appcache_service.h"
#include "chrome/browser/autocomplete/autocomplete_classifier.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/background_contents_service.h"
#include "chrome/browser/background_mode_manager.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_signin.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/chrome_blob_storage_context.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/dom_ui/ntp_resource_cache.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/default_apps.h"
#include "chrome/browser/extensions/extension_devtools_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/extensions/extension_info_map.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/browser/extensions/extension_pref_store.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/favicon_service.h"
#include "chrome/browser/file_system/browser_file_system_helper.h"
#include "chrome/browser/geolocation/geolocation_content_settings_map.h"
#include "chrome/browser/geolocation/geolocation_permission_context.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/history/top_sites.h"
#include "chrome/browser/host_zoom_map.h"
#include "chrome/browser/instant/instant_controller.h"
#include "chrome/browser/in_process_webkit/webkit_context.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/browser/net/gaia/token_service.h"
#include "chrome/browser/net/net_pref_observer.h"
#include "chrome/browser/net/pref_proxy_config_service.h"
#include "chrome/browser/net/ssl_config_service_manager.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/password_manager/password_store_default.h"
#include "chrome/browser/policy/configuration_policy_provider.h"
#include "chrome/browser/policy/configuration_policy_pref_store.h"
#include "chrome/browser/policy/profile_policy_context.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/browser/prefs/pref_value_store.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/search_engines/template_url_fetcher.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/browser/sessions/session_service.h"
#include "chrome/browser/sessions/tab_restore_service.h"
#include "chrome/browser/spellcheck_host.h"
#include "chrome/browser/ssl/ssl_host_state.h"
#include "chrome/browser/status_icons/status_tray.h"
#include "chrome/browser/sync/profile_sync_factory_impl.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/tabs/pinned_tab_service.h"
#include "chrome/browser/themes/browser_theme_provider.h"
#include "chrome/browser/transport_security_persister.h"
#include "chrome/browser/ui/find_bar/find_bar_state.h"
#include "chrome/browser/user_style_sheet_watcher.h"
#include "chrome/browser/visitedlink/visitedlink_event_listener.h"
#include "chrome/browser/visitedlink/visitedlink_master.h"
#include "chrome/browser/web_resource/web_resource_service.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "grit/browser_resources.h"
#include "grit/locale_settings.h"
#include "net/base/transport_security_state.h"
#include "webkit/database/database_tracker.h"
#if defined(TOOLKIT_USES_GTK)
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
#if defined(OS_WIN)
#include "chrome/browser/instant/promo_counter.h"
#include "chrome/browser/password_manager/password_store_win.h"
#include "chrome/installer/util/install_util.h"
#elif defined(OS_MACOSX)
#include "chrome/browser/keychain_mac.h"
#include "chrome/browser/password_manager/password_store_mac.h"
#elif defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/enterprise_extension_observer.h"
#include "chrome/browser/chromeos/proxy_config_service_impl.h"
#elif defined(OS_POSIX) && !defined(OS_CHROMEOS)
#include "base/nix/xdg_util.h"
#if defined(USE_GNOME_KEYRING)
#include "chrome/browser/password_manager/native_backend_gnome_x.h"
#endif
#include "chrome/browser/password_manager/native_backend_kwallet_x.h"
#include "chrome/browser/password_manager/password_store_x.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/preferences.h"
#endif
using base::Time;
using base::TimeDelta;
namespace {
void CleanupRequestContext(ChromeURLRequestContextGetter* context) {
if (context)
context->CleanupOnUIThread();
}
// Delay, in milliseconds, before we explicitly create the SessionService.
static const int kCreateSessionServiceDelayMS = 500;
enum ContextType {
kNormalContext,
kMediaContext
};
// Gets the cache parameters from the command line. |type| is the type of
// request context that we need, |cache_path| will be set to the user provided
// path, or will not be touched if there is not an argument. |max_size| will
// be the user provided value or zero by default.
void GetCacheParameters(ContextType type, FilePath* cache_path,
int* max_size) {
DCHECK(cache_path);
DCHECK(max_size);
// Override the cache location if specified by the user.
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDiskCacheDir)) {
*cache_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
switches::kDiskCacheDir);
}
const char* arg = kNormalContext == type ? switches::kDiskCacheSize :
switches::kMediaCacheSize;
std::string value =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(arg);
// By default we let the cache determine the right size.
*max_size = 0;
if (!base::StringToInt(value, max_size)) {
*max_size = 0;
} else if (max_size < 0) {
*max_size = 0;
}
}
FilePath GetCachePath(const FilePath& base) {
return base.Append(chrome::kCacheDirname);
}
FilePath GetMediaCachePath(const FilePath& base) {
return base.Append(chrome::kMediaCacheDirname);
}
// Simple task to log the size of the current profile.
class ProfileSizeTask : public Task {
public:
explicit ProfileSizeTask(const FilePath& path) : path_(path) {}
virtual ~ProfileSizeTask() {}
virtual void Run();
private:
FilePath path_;
};
void ProfileSizeTask::Run() {
int64 size = file_util::ComputeFilesSize(path_, FILE_PATH_LITERAL("*"));
int size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.TotalSize", size_MB);
size = file_util::ComputeFilesSize(path_, FILE_PATH_LITERAL("History"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.HistorySize", size_MB);
size = file_util::ComputeFilesSize(path_, FILE_PATH_LITERAL("History*"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.TotalHistorySize", size_MB);
size = file_util::ComputeFilesSize(path_, FILE_PATH_LITERAL("Cookies"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.CookiesSize", size_MB);
size = file_util::ComputeFilesSize(path_, FILE_PATH_LITERAL("Bookmarks"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.BookmarksSize", size_MB);
size = file_util::ComputeFilesSize(path_, FILE_PATH_LITERAL("Favicons"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.FaviconsSize", size_MB);
size = file_util::ComputeFilesSize(path_, FILE_PATH_LITERAL("Top Sites"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.TopSitesSize", size_MB);
size = file_util::ComputeFilesSize(path_, FILE_PATH_LITERAL("Visited Links"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.VisitedLinksSize", size_MB);
size = file_util::ComputeFilesSize(path_, FILE_PATH_LITERAL("Web Data"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.WebDataSize", size_MB);
size = file_util::ComputeFilesSize(path_, FILE_PATH_LITERAL("Extension*"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.ExtensionSize", size_MB);
}
} // namespace
// static
Profile* Profile::CreateProfile(const FilePath& path) {
return new ProfileImpl(path);
}
// static
void ProfileImpl::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kSavingBrowserHistoryDisabled, false);
DefaultApps::RegisterUserPrefs(prefs);
}
ProfileImpl::ProfileImpl(const FilePath& path)
: path_(path),
visited_link_event_listener_(new VisitedLinkEventListener()),
extension_devtools_manager_(NULL),
request_context_(NULL),
media_request_context_(NULL),
extensions_request_context_(NULL),
host_content_settings_map_(NULL),
host_zoom_map_(NULL),
history_service_created_(false),
favicon_service_created_(false),
created_web_data_service_(false),
created_password_store_(false),
created_download_manager_(false),
created_theme_provider_(false),
start_time_(Time::Now()),
spellcheck_host_(NULL),
spellcheck_host_ready_(false),
#if defined(OS_WIN)
checked_instant_promo_(false),
#endif
shutdown_session_service_(false) {
DCHECK(!path.empty()) << "Using an empty path will attempt to write " <<
"profile files to the root directory!";
create_session_service_timer_.Start(
TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this,
&ProfileImpl::EnsureSessionServiceCreated);
PrefService* prefs = GetPrefs();
pref_change_registrar_.Init(prefs);
pref_change_registrar_.Add(prefs::kSpellCheckDictionary, this);
pref_change_registrar_.Add(prefs::kEnableSpellCheck, this);
pref_change_registrar_.Add(prefs::kEnableAutoSpellCorrect, this);
pref_change_registrar_.Add(prefs::kClearSiteDataOnExit, this);
// Convert active labs into switches. Modifies the current command line.
about_flags::ConvertFlagsToSwitches(prefs, CommandLine::ForCurrentProcess());
// It would be nice to use PathService for fetching this directory, but
// the cache directory depends on the profile directory, which isn't available
// to PathService.
chrome::GetUserCacheDirectory(path_, &base_cache_path_);
file_util::CreateDirectory(base_cache_path_);
// Listen for theme installations from our original profile.
registrar_.Add(this, NotificationType::THEME_INSTALLED,
Source<Profile>(GetOriginalProfile()));
#if !defined(OS_CHROMEOS)
// Listen for bookmark model load, to bootstrap the sync service.
// On CrOS sync service will be initialized after sign in.
registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
Source<Profile>(this));
#endif
ssl_config_service_manager_.reset(
SSLConfigServiceManager::CreateDefaultManager(this));
#if defined(OS_CHROMEOS)
chromeos_preferences_.reset(new chromeos::Preferences());
chromeos_preferences_->Init(prefs);
#endif
pinned_tab_service_.reset(new PinnedTabService(this));
// Initialize the BackgroundModeManager - this has to be done here before
// InitExtensions() is called because it relies on receiving notifications
// when extensions are loaded. BackgroundModeManager is not needed under
// ChromeOS because Chrome is always running (no need for special keep-alive
// or launch-on-startup support).
#if !defined(OS_CHROMEOS)
background_mode_manager_.reset(new BackgroundModeManager(this,
CommandLine::ForCurrentProcess()));
#endif
background_contents_service_.reset(
new BackgroundContentsService(this, CommandLine::ForCurrentProcess()));
extension_info_map_ = new ExtensionInfoMap();
GetPolicyContext()->Initialize();
clear_local_state_on_exit_ = prefs->GetBoolean(prefs::kClearSiteDataOnExit);
// Log the profile size after a reasonable startup delay.
BrowserThread::PostDelayedTask(BrowserThread::FILE, FROM_HERE,
new ProfileSizeTask(path_), 112000);
InstantController::RecordMetrics(this);
}
void ProfileImpl::InitExtensions() {
if (user_script_master_ || extensions_service_)
return; // Already initialized.
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(
switches::kEnableExtensionTimelineApi)) {
extension_devtools_manager_ = new ExtensionDevToolsManager(this);
}
extension_process_manager_.reset(ExtensionProcessManager::Create(this));
extension_event_router_.reset(new ExtensionEventRouter(this));
extension_message_service_ = new ExtensionMessageService(this);
ExtensionErrorReporter::Init(true); // allow noisy errors.
FilePath script_dir; // Don't look for user scripts in any directory.
// TODO(aa): We should just remove this functionality,
// since it isn't used anymore.
user_script_master_ = new UserScriptMaster(script_dir, this);
extensions_service_ = new ExtensionService(
this,
CommandLine::ForCurrentProcess(),
GetPath().AppendASCII(ExtensionService::kInstallDirectoryName),
extension_prefs_.get(),
true);
RegisterComponentExtensions();
extensions_service_->Init();
InstallDefaultApps();
// Load any extensions specified with --load-extension.
if (command_line->HasSwitch(switches::kLoadExtension)) {
FilePath path = command_line->GetSwitchValuePath(switches::kLoadExtension);
extensions_service_->LoadExtension(path);
}
}
void ProfileImpl::RegisterComponentExtensions() {
// Register the component extensions.
typedef std::list<std::pair<std::string, int> > ComponentExtensionList;
ComponentExtensionList component_extensions;
// Bookmark manager.
component_extensions.push_back(
std::make_pair("bookmark_manager", IDR_BOOKMARKS_MANIFEST));
#if defined(TOUCH_UI)
component_extensions.push_back(
std::make_pair("keyboard", IDR_KEYBOARD_MANIFEST));
#endif
// Web Store.
component_extensions.push_back(
std::make_pair("web_store", IDR_WEBSTORE_MANIFEST));
for (ComponentExtensionList::iterator iter = component_extensions.begin();
iter != component_extensions.end(); ++iter) {
FilePath path;
if (PathService::Get(chrome::DIR_RESOURCES, &path)) {
path = path.AppendASCII(iter->first);
} else {
NOTREACHED();
}
std::string manifest =
ResourceBundle::GetSharedInstance().GetRawDataResource(
iter->second).as_string();
extensions_service_->register_component_extension(
ExtensionService::ComponentExtensionInfo(manifest, path));
}
}
void ProfileImpl::InstallDefaultApps() {
// The web store only supports en-US at the moment, so we don't install
// default apps in other locales.
if (g_browser_process->GetApplicationLocale() != "en-US")
return;
ExtensionService* extensions_service = GetExtensionService();
const ExtensionIdSet* app_ids =
extensions_service->default_apps()->GetAppsToInstall();
if (!app_ids)
return;
for (ExtensionIdSet::const_iterator iter = app_ids->begin();
iter != app_ids->end(); ++iter) {
extensions_service->AddPendingExtensionFromDefaultAppList(*iter);
}
}
void ProfileImpl::InitWebResources() {
if (web_resource_service_)
return;
web_resource_service_ = new WebResourceService(this);
web_resource_service_->StartAfterDelay();
}
NTPResourceCache* ProfileImpl::GetNTPResourceCache() {
if (!ntp_resource_cache_.get())
ntp_resource_cache_.reset(new NTPResourceCache(this));
return ntp_resource_cache_.get();
}
FilePath ProfileImpl::last_selected_directory() {
return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
}
void ProfileImpl::set_last_selected_directory(const FilePath& path) {
GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
}
ProfileImpl::~ProfileImpl() {
NotificationService::current()->Notify(
NotificationType::PROFILE_DESTROYED,
Source<Profile>(this),
NotificationService::NoDetails());
GetPolicyContext()->Shutdown();
tab_restore_service_ = NULL;
StopCreateSessionServiceTimer();
// TemplateURLModel schedules a task on the WebDataService from its
// destructor. Delete it first to ensure the task gets scheduled before we
// shut down the database.
template_url_model_.reset();
// DownloadManager is lazily created, so check before accessing it.
if (download_manager_.get()) {
// The download manager queries the history system and should be shutdown
// before the history is shutdown so it can properly cancel all requests.
download_manager_->Shutdown();
download_manager_ = NULL;
}
// The theme provider provides bitmaps to whoever wants them.
theme_provider_.reset();
// Remove pref observers
pref_change_registrar_.RemoveAll();
// Delete the NTP resource cache so we can unregister pref observers.
ntp_resource_cache_.reset();
// The sync service needs to be deleted before the services it calls.
sync_service_.reset();
// Both HistoryService and WebDataService maintain threads for background
// processing. Its possible each thread still has tasks on it that have
// increased the ref count of the service. In such a situation, when we
// decrement the refcount, it won't be 0, and the threads/databases aren't
// properly shut down. By explicitly calling Cleanup/Shutdown we ensure the
// databases are properly closed.
if (web_data_service_.get())
web_data_service_->Shutdown();
if (top_sites_.get())
top_sites_->Shutdown();
if (history_service_.get())
history_service_->Cleanup();
if (spellcheck_host_.get())
spellcheck_host_->UnsetObserver();
if (default_request_context_ == request_context_)
default_request_context_ = NULL;
CleanupRequestContext(request_context_);
CleanupRequestContext(media_request_context_);
CleanupRequestContext(extensions_request_context_);
// HistoryService may call into the BookmarkModel, as such we need to
// delete HistoryService before the BookmarkModel. The destructor for
// HistoryService will join with HistoryService's backend thread so that
// by the time the destructor has finished we're sure it will no longer call
// into the BookmarkModel.
history_service_ = NULL;
bookmark_bar_model_.reset();
// FaviconService depends on HistoryServce so make sure we delete
// HistoryService first.
favicon_service_ = NULL;
if (extension_message_service_)
extension_message_service_->DestroyingProfile();
if (extensions_service_)
extensions_service_->DestroyingProfile();
if (pref_proxy_config_tracker_)
pref_proxy_config_tracker_->DetachFromPrefService();
// This causes the Preferences file to be written to disk.
MarkAsCleanShutdown();
}
ProfileId ProfileImpl::GetRuntimeId() {
return reinterpret_cast<ProfileId>(this);
}
FilePath ProfileImpl::GetPath() {
return path_;
}
bool ProfileImpl::IsOffTheRecord() {
return false;
}
Profile* ProfileImpl::GetOffTheRecordProfile() {
if (!off_the_record_profile_.get()) {
scoped_ptr<Profile> p(CreateOffTheRecordProfile());
off_the_record_profile_.swap(p);
NotificationService::current()->Notify(
NotificationType::OTR_PROFILE_CREATED,
Source<Profile>(off_the_record_profile_.get()),
NotificationService::NoDetails());
}
return off_the_record_profile_.get();
}
void ProfileImpl::DestroyOffTheRecordProfile() {
off_the_record_profile_.reset();
}
bool ProfileImpl::HasOffTheRecordProfile() {
return off_the_record_profile_.get() != NULL;
}
Profile* ProfileImpl::GetOriginalProfile() {
return this;
}
ChromeAppCacheService* ProfileImpl::GetAppCacheService() {
if (!appcache_service_) {
appcache_service_ = new ChromeAppCacheService;
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(appcache_service_.get(),
&ChromeAppCacheService::InitializeOnIOThread,
GetPath(), IsOffTheRecord(),
make_scoped_refptr(GetHostContentSettingsMap())));
}
return appcache_service_;
}
webkit_database::DatabaseTracker* ProfileImpl::GetDatabaseTracker() {
if (!db_tracker_) {
db_tracker_ = new webkit_database::DatabaseTracker(
GetPath(), IsOffTheRecord());
}
return db_tracker_;
}
VisitedLinkMaster* ProfileImpl::GetVisitedLinkMaster() {
if (!visited_link_master_.get()) {
scoped_ptr<VisitedLinkMaster> visited_links(
new VisitedLinkMaster(visited_link_event_listener_.get(), this));
if (!visited_links->Init())
return NULL;
visited_link_master_.swap(visited_links);
}
return visited_link_master_.get();
}
ExtensionService* ProfileImpl::GetExtensionService() {
return extensions_service_.get();
}
BackgroundContentsService* ProfileImpl::GetBackgroundContentsService() const {
return background_contents_service_.get();
}
StatusTray* ProfileImpl::GetStatusTray() {
if (!status_tray_.get())
status_tray_.reset(StatusTray::Create());
return status_tray_.get();
}
UserScriptMaster* ProfileImpl::GetUserScriptMaster() {
return user_script_master_.get();
}
ExtensionDevToolsManager* ProfileImpl::GetExtensionDevToolsManager() {
return extension_devtools_manager_.get();
}
ExtensionProcessManager* ProfileImpl::GetExtensionProcessManager() {
return extension_process_manager_.get();
}
ExtensionMessageService* ProfileImpl::GetExtensionMessageService() {
return extension_message_service_.get();
}
ExtensionEventRouter* ProfileImpl::GetExtensionEventRouter() {
return extension_event_router_.get();
}
SSLHostState* ProfileImpl::GetSSLHostState() {
if (!ssl_host_state_.get())
ssl_host_state_.reset(new SSLHostState());
DCHECK(ssl_host_state_->CalledOnValidThread());
return ssl_host_state_.get();
}
net::TransportSecurityState*
ProfileImpl::GetTransportSecurityState() {
if (!transport_security_state_.get()) {
transport_security_state_ = new net::TransportSecurityState();
transport_security_persister_ =
new TransportSecurityPersister();
transport_security_persister_->Initialize(
transport_security_state_.get(), path_);
}
return transport_security_state_.get();
}
PrefService* ProfileImpl::GetPrefs() {
if (!prefs_.get()) {
ExtensionPrefStore* extension_pref_store = new ExtensionPrefStore;
prefs_.reset(PrefService::CreatePrefService(GetPrefFilePath(),
extension_pref_store,
GetOriginalProfile()));
// The Profile class and ProfileManager class may read some prefs so
// register known prefs as soon as possible.
Profile::RegisterUserPrefs(prefs_.get());
browser::RegisterUserPrefs(prefs_.get());
// The last session exited cleanly if there is no pref for
// kSessionExitedCleanly or the value for kSessionExitedCleanly is true.
last_session_exited_cleanly_ =
prefs_->GetBoolean(prefs::kSessionExitedCleanly);
// Mark the session as open.
prefs_->SetBoolean(prefs::kSessionExitedCleanly, false);
// Make sure we save to disk that the session has opened.
prefs_->ScheduleSavePersistentPrefs();
// Ensure that preferences set by extensions are restored in the profile
// as early as possible. The constructor takes care of that.
extension_prefs_.reset(new ExtensionPrefs(
prefs_.get(),
GetPath().AppendASCII(ExtensionService::kInstallDirectoryName),
extension_pref_store));
DCHECK(!net_pref_observer_.get());
net_pref_observer_.reset(new NetPrefObserver(prefs_.get()));
}
return prefs_.get();
}
FilePath ProfileImpl::GetPrefFilePath() {
FilePath pref_file_path = path_;
pref_file_path = pref_file_path.Append(chrome::kPreferencesFilename);
return pref_file_path;
}
URLRequestContextGetter* ProfileImpl::GetRequestContext() {
if (!request_context_) {
FilePath cookie_path = GetPath();
cookie_path = cookie_path.Append(chrome::kCookieFilename);
FilePath cache_path = base_cache_path_;
int max_size;
GetCacheParameters(kNormalContext, &cache_path, &max_size);
cache_path = GetCachePath(cache_path);
request_context_ = ChromeURLRequestContextGetter::CreateOriginal(
this, cookie_path, cache_path, max_size);
// The first request context is always a normal (non-OTR) request context.
// Even when Chromium is started in OTR mode, a normal profile is always
// created first.
if (!default_request_context_) {
default_request_context_ = request_context_;
request_context_->set_is_main(true);
// TODO(eroman): this isn't terribly useful anymore now that the
// URLRequestContext is constructed by the IO thread...
NotificationService::current()->Notify(
NotificationType::DEFAULT_REQUEST_CONTEXT_AVAILABLE,
NotificationService::AllSources(), NotificationService::NoDetails());
}
}
return request_context_;
}
URLRequestContextGetter* ProfileImpl::GetRequestContextForMedia() {
if (!media_request_context_) {
FilePath cache_path = base_cache_path_;
int max_size;
GetCacheParameters(kMediaContext, &cache_path, &max_size);
cache_path = GetMediaCachePath(cache_path);
media_request_context_ =
ChromeURLRequestContextGetter::CreateOriginalForMedia(
this, cache_path, max_size);
}
return media_request_context_;
}
FaviconService* ProfileImpl::GetFaviconService(ServiceAccessType sat) {
if (!favicon_service_created_) {
favicon_service_created_ = true;
scoped_refptr<FaviconService> service(new FaviconService(this));
favicon_service_.swap(service);
}
return favicon_service_.get();
}
URLRequestContextGetter* ProfileImpl::GetRequestContextForExtensions() {
if (!extensions_request_context_) {
FilePath cookie_path = GetPath();
cookie_path = cookie_path.Append(chrome::kExtensionsCookieFilename);
extensions_request_context_ =
ChromeURLRequestContextGetter::CreateOriginalForExtensions(
this, cookie_path);
}
return extensions_request_context_;
}
void ProfileImpl::RegisterExtensionWithRequestContexts(
const Extension* extension) {
// AddRef to ensure the data lives until the other thread gets it. Balanced in
// OnNewExtensions.
extension->AddRef();
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(extension_info_map_.get(),
&ExtensionInfoMap::AddExtension,
extension));
}
void ProfileImpl::UnregisterExtensionWithRequestContexts(
const Extension* extension) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(extension_info_map_.get(),
&ExtensionInfoMap::RemoveExtension,
extension->id()));
}
net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
return ssl_config_service_manager_->Get();
}
HostContentSettingsMap* ProfileImpl::GetHostContentSettingsMap() {
if (!host_content_settings_map_.get())
host_content_settings_map_ = new HostContentSettingsMap(this);
return host_content_settings_map_.get();
}
HostZoomMap* ProfileImpl::GetHostZoomMap() {
if (!host_zoom_map_)
host_zoom_map_ = new HostZoomMap(this);
return host_zoom_map_.get();
}
GeolocationContentSettingsMap* ProfileImpl::GetGeolocationContentSettingsMap() {
if (!geolocation_content_settings_map_.get())
geolocation_content_settings_map_ = new GeolocationContentSettingsMap(this);
return geolocation_content_settings_map_.get();
}
GeolocationPermissionContext* ProfileImpl::GetGeolocationPermissionContext() {
if (!geolocation_permission_context_.get())
geolocation_permission_context_ = new GeolocationPermissionContext(this);
return geolocation_permission_context_.get();
}
UserStyleSheetWatcher* ProfileImpl::GetUserStyleSheetWatcher() {
if (!user_style_sheet_watcher_.get()) {
user_style_sheet_watcher_ = new UserStyleSheetWatcher(GetPath());
user_style_sheet_watcher_->Init();
}
return user_style_sheet_watcher_.get();
}
FindBarState* ProfileImpl::GetFindBarState() {
if (!find_bar_state_.get()) {
find_bar_state_.reset(new FindBarState());
}
return find_bar_state_.get();
}
HistoryService* ProfileImpl::GetHistoryService(ServiceAccessType sat) {
// If saving history is disabled, only allow explicit access.
if (GetPrefs()->GetBoolean(prefs::kSavingBrowserHistoryDisabled) &&
sat != EXPLICIT_ACCESS)
return NULL;
if (!history_service_created_) {
history_service_created_ = true;
scoped_refptr<HistoryService> history(new HistoryService(this));
if (!history->Init(GetPath(), GetBookmarkModel()))
return NULL;
history_service_.swap(history);
// Send out the notification that the history service was created.
NotificationService::current()->
Notify(NotificationType::HISTORY_CREATED, Source<Profile>(this),
Details<HistoryService>(history_service_.get()));
}
return history_service_.get();
}
HistoryService* ProfileImpl::GetHistoryServiceWithoutCreating() {
return history_service_.get();
}
TemplateURLModel* ProfileImpl::GetTemplateURLModel() {
if (!template_url_model_.get())
template_url_model_.reset(new TemplateURLModel(this));
return template_url_model_.get();
}
TemplateURLFetcher* ProfileImpl::GetTemplateURLFetcher() {
if (!template_url_fetcher_.get())
template_url_fetcher_.reset(new TemplateURLFetcher(this));
return template_url_fetcher_.get();
}
AutocompleteClassifier* ProfileImpl::GetAutocompleteClassifier() {
if (!autocomplete_classifier_.get())
autocomplete_classifier_.reset(new AutocompleteClassifier(this));
return autocomplete_classifier_.get();
}
WebDataService* ProfileImpl::GetWebDataService(ServiceAccessType sat) {
if (!created_web_data_service_)
CreateWebDataService();
return web_data_service_.get();
}
WebDataService* ProfileImpl::GetWebDataServiceWithoutCreating() {
return web_data_service_.get();
}
void ProfileImpl::CreateWebDataService() {
DCHECK(!created_web_data_service_ && web_data_service_.get() == NULL);
created_web_data_service_ = true;
scoped_refptr<WebDataService> wds(new WebDataService());
if (!wds->Init(GetPath()))
return;
web_data_service_.swap(wds);
}
PasswordStore* ProfileImpl::GetPasswordStore(ServiceAccessType sat) {
if (!created_password_store_)
CreatePasswordStore();
return password_store_.get();
}
void ProfileImpl::CreatePasswordStore() {
DCHECK(!created_password_store_ && password_store_.get() == NULL);
created_password_store_ = true;
scoped_refptr<PasswordStore> ps;
FilePath login_db_file_path = GetPath();
login_db_file_path = login_db_file_path.Append(chrome::kLoginDataFileName);
LoginDatabase* login_db = new LoginDatabase();
if (!login_db->Init(login_db_file_path)) {
LOG(ERROR) << "Could not initialize login database.";
delete login_db;
return;
}
#if defined(OS_WIN)
ps = new PasswordStoreWin(login_db, this,
GetWebDataService(Profile::IMPLICIT_ACCESS));
#elif defined(OS_MACOSX)
ps = new PasswordStoreMac(new MacKeychain(), login_db);
#elif defined(OS_CHROMEOS)
// For now, we use PasswordStoreDefault. We might want to make a native
// backend for PasswordStoreX (see below) in the future though.
ps = new PasswordStoreDefault(login_db, this,
GetWebDataService(Profile::IMPLICIT_ACCESS));
#elif defined(OS_POSIX)
// On POSIX systems, we try to use the "native" password management system of
// the desktop environment currently running, allowing GNOME Keyring in XFCE.
// (In all cases we fall back on the default store in case of failure.)
base::nix::DesktopEnvironment desktop_env;
std::string store_type =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kPasswordStore);
if (store_type == "kwallet") {
desktop_env = base::nix::DESKTOP_ENVIRONMENT_KDE4;
} else if (store_type == "gnome") {
desktop_env = base::nix::DESKTOP_ENVIRONMENT_GNOME;
} else if (store_type == "detect") {
scoped_ptr<base::Environment> env(base::Environment::Create());
desktop_env = base::nix::GetDesktopEnvironment(env.get());
VLOG(1) << "Password storage detected desktop environment: "
<< base::nix::GetDesktopEnvironmentName(desktop_env);
} else {
// TODO(mdm): If the flag is not given, or has an unknown value, use the
// default store for now. Once we're confident in the other stores, we can
// default to detecting the desktop environment instead.
desktop_env = base::nix::DESKTOP_ENVIRONMENT_OTHER;
}
scoped_ptr<PasswordStoreX::NativeBackend> backend;
if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4) {
// KDE3 didn't use DBus, which our KWallet store uses.
VLOG(1) << "Trying KWallet for password storage.";
backend.reset(new NativeBackendKWallet());
if (backend->Init())
VLOG(1) << "Using KWallet for password storage.";
else
backend.reset();
} else if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_GNOME ||
desktop_env == base::nix::DESKTOP_ENVIRONMENT_XFCE) {
#if defined(USE_GNOME_KEYRING)
VLOG(1) << "Trying GNOME keyring for password storage.";
backend.reset(new NativeBackendGnome());
if (backend->Init())
VLOG(1) << "Using GNOME keyring for password storage.";
else
backend.reset();
#endif // defined(USE_GNOME_KEYRING)
}
// TODO(mdm): this can change to a WARNING when we detect by default.
if (!backend.get())
VLOG(1) << "Using default (unencrypted) store for password storage.";
ps = new PasswordStoreX(login_db, this,
GetWebDataService(Profile::IMPLICIT_ACCESS),
backend.release());
#else
NOTIMPLEMENTED();
#endif
if (!ps)
delete login_db;
if (!ps || !ps->Init()) {
NOTREACHED() << "Could not initialize password manager.";
return;
}
password_store_.swap(ps);
}
DownloadManager* ProfileImpl::GetDownloadManager() {
if (!created_download_manager_) {
scoped_refptr<DownloadManager> dlm(
new DownloadManager(g_browser_process->download_status_updater()));
dlm->Init(this);
created_download_manager_ = true;
download_manager_.swap(dlm);
}
return download_manager_.get();
}
bool ProfileImpl::HasCreatedDownloadManager() const {
return created_download_manager_;
}
PersonalDataManager* ProfileImpl::GetPersonalDataManager() {
if (!personal_data_manager_.get()) {
personal_data_manager_ = new PersonalDataManager();
personal_data_manager_->Init(this);
}
return personal_data_manager_.get();
}
fileapi::SandboxedFileSystemContext* ProfileImpl::GetFileSystemContext() {
if (!file_system_context_.get())
file_system_context_ = CreateFileSystemContext(
GetPath(), IsOffTheRecord());
DCHECK(file_system_context_.get());
return file_system_context_.get();
}
void ProfileImpl::InitThemes() {
if (!created_theme_provider_) {
#if defined(TOOLKIT_USES_GTK)
theme_provider_.reset(new GtkThemeProvider);
#else
theme_provider_.reset(new BrowserThemeProvider);
#endif
theme_provider_->Init(this);
created_theme_provider_ = true;
}
}
void ProfileImpl::SetTheme(const Extension* extension) {
InitThemes();
theme_provider_.get()->SetTheme(extension);
}
void ProfileImpl::SetNativeTheme() {
InitThemes();
theme_provider_.get()->SetNativeTheme();
}
void ProfileImpl::ClearTheme() {
InitThemes();
theme_provider_.get()->UseDefaultTheme();
}
const Extension* ProfileImpl::GetTheme() {
InitThemes();
std::string id = theme_provider_.get()->GetThemeID();
if (id == BrowserThemeProvider::kDefaultThemeID)
return NULL;
return extensions_service_->GetExtensionById(id, false);
}
BrowserThemeProvider* ProfileImpl::GetThemeProvider() {
InitThemes();
return theme_provider_.get();
}
SessionService* ProfileImpl::GetSessionService() {
if (!session_service_.get() && !shutdown_session_service_) {
session_service_ = new SessionService(this);
session_service_->ResetFromCurrentBrowsers();
}
return session_service_.get();
}
void ProfileImpl::ShutdownSessionService() {
if (shutdown_session_service_)
return;
// We're about to exit, force creation of the session service if it hasn't
// been created yet. We do this to ensure session state matches the point in
// time the user exited.
GetSessionService();
shutdown_session_service_ = true;
session_service_ = NULL;
}
bool ProfileImpl::HasSessionService() const {
return (session_service_.get() != NULL);
}
bool ProfileImpl::HasProfileSyncService() const {
return (sync_service_.get() != NULL);
}
bool ProfileImpl::DidLastSessionExitCleanly() {
// last_session_exited_cleanly_ is set when the preferences are loaded. Force
// it to be set by asking for the prefs.
GetPrefs();
return last_session_exited_cleanly_;
}
BookmarkModel* ProfileImpl::GetBookmarkModel() {
if (!bookmark_bar_model_.get()) {
bookmark_bar_model_.reset(new BookmarkModel(this));
bookmark_bar_model_->Load();
}
return bookmark_bar_model_.get();
}
bool ProfileImpl::IsSameProfile(Profile* profile) {
if (profile == static_cast<Profile*>(this))
return true;
Profile* otr_profile = off_the_record_profile_.get();
return otr_profile && profile == otr_profile;
}
Time ProfileImpl::GetStartTime() const {
return start_time_;
}
TabRestoreService* ProfileImpl::GetTabRestoreService() {
if (!tab_restore_service_.get())
tab_restore_service_ = new TabRestoreService(this);
return tab_restore_service_.get();
}
history::TopSites* ProfileImpl::GetTopSites() {
if (!top_sites_.get()) {
top_sites_ = new history::TopSites(this);
top_sites_->Init(GetPath().Append(chrome::kTopSitesFilename));
}
return top_sites_;
}
history::TopSites* ProfileImpl::GetTopSitesWithoutCreating() {
return top_sites_;
}
void ProfileImpl::ResetTabRestoreService() {
tab_restore_service_ = NULL;
}
SpellCheckHost* ProfileImpl::GetSpellCheckHost() {
return spellcheck_host_ready_ ? spellcheck_host_.get() : NULL;
}
void ProfileImpl::ReinitializeSpellCheckHost(bool force) {
// If we are already loading the spellchecker, and this is just a hint to
// load the spellchecker, do nothing.
if (!force && spellcheck_host_.get())
return;
spellcheck_host_ready_ = false;
bool notify = false;
if (spellcheck_host_.get()) {
spellcheck_host_->UnsetObserver();
spellcheck_host_ = NULL;
notify = true;
}
PrefService* prefs = GetPrefs();
if (prefs->GetBoolean(prefs::kEnableSpellCheck)) {
// Retrieve the (perhaps updated recently) dictionary name from preferences.
spellcheck_host_ = new SpellCheckHost(
this,
prefs->GetString(prefs::kSpellCheckDictionary),
GetRequestContext());
spellcheck_host_->Initialize();
} else if (notify) {
// The spellchecker has been disabled.
SpellCheckHostInitialized();
}
}
void ProfileImpl::SpellCheckHostInitialized() {
spellcheck_host_ready_ = spellcheck_host_ &&
(spellcheck_host_->bdict_file() != base::kInvalidPlatformFileValue ||
spellcheck_host_->use_platform_spellchecker());
NotificationService::current()->Notify(
NotificationType::SPELLCHECK_HOST_REINITIALIZED,
Source<Profile>(this), NotificationService::NoDetails());
}
WebKitContext* ProfileImpl::GetWebKitContext() {
if (!webkit_context_.get())
webkit_context_ = new WebKitContext(this, clear_local_state_on_exit_);
DCHECK(webkit_context_.get());
return webkit_context_.get();
}
DesktopNotificationService* ProfileImpl::GetDesktopNotificationService() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!desktop_notification_service_.get()) {
desktop_notification_service_.reset(new DesktopNotificationService(
this, g_browser_process->notification_ui_manager()));
}
return desktop_notification_service_.get();
}
void ProfileImpl::MarkAsCleanShutdown() {
if (prefs_.get()) {
// The session cleanly exited, set kSessionExitedCleanly appropriately.
prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
// NOTE: If you change what thread this writes on, be sure and update
// ChromeFrame::EndSession().
prefs_->SavePersistentPrefs();
}
}
void ProfileImpl::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (NotificationType::PREF_CHANGED == type) {
std::string* pref_name_in = Details<std::string>(details).ptr();
PrefService* prefs = Source<PrefService>(source).ptr();
DCHECK(pref_name_in && prefs);
if (*pref_name_in == prefs::kSpellCheckDictionary ||
*pref_name_in == prefs::kEnableSpellCheck) {
ReinitializeSpellCheckHost(true);
} else if (*pref_name_in == prefs::kEnableAutoSpellCorrect) {
NotificationService::current()->Notify(
NotificationType::SPELLCHECK_AUTOSPELL_TOGGLED,
Source<Profile>(this), NotificationService::NoDetails());
} else if (*pref_name_in == prefs::kClearSiteDataOnExit) {
clear_local_state_on_exit_ =
prefs->GetBoolean(prefs::kClearSiteDataOnExit);
if (webkit_context_)
webkit_context_->set_clear_local_state_on_exit(
clear_local_state_on_exit_);
}
} else if (NotificationType::THEME_INSTALLED == type) {
DCHECK_EQ(Source<Profile>(source).ptr(), GetOriginalProfile());
const Extension* extension = Details<const Extension>(details).ptr();
SetTheme(extension);
} else if (NotificationType::BOOKMARK_MODEL_LOADED == type) {
GetProfileSyncService(); // Causes lazy-load if sync is enabled.
registrar_.Remove(this, NotificationType::BOOKMARK_MODEL_LOADED,
Source<Profile>(this));
}
}
void ProfileImpl::StopCreateSessionServiceTimer() {
create_session_service_timer_.Stop();
}
TokenService* ProfileImpl::GetTokenService() {
if (!token_service_.get()) {
token_service_.reset(new TokenService());
}
return token_service_.get();
}
ProfileSyncService* ProfileImpl::GetProfileSyncService() {
#if defined(OS_CHROMEOS)
// If kLoginManager is specified, we shouldn't call this unless login has
// completed and specified cros_user. Guard with if (HasProfileSyncService())
// where this might legitimately get called before login has completed.
if (!sync_service_.get() &&
CommandLine::ForCurrentProcess()->HasSwitch(switches::kLoginManager)) {
LOG(FATAL) << "GetProfileSyncService() called before login complete.";
}
#endif
return GetProfileSyncService("");
}
ProfileSyncService* ProfileImpl::GetProfileSyncService(
const std::string& cros_user) {
if (!ProfileSyncService::IsSyncEnabled())
return NULL;
if (!sync_service_.get())
InitSyncService(cros_user);
return sync_service_.get();
}
BrowserSignin* ProfileImpl::GetBrowserSignin() {
if (!browser_signin_.get()) {
browser_signin_.reset(new BrowserSignin(this));
}
return browser_signin_.get();
}
CloudPrintProxyService* ProfileImpl::GetCloudPrintProxyService() {
if (!cloud_print_proxy_service_.get())
InitCloudPrintProxyService();
return cloud_print_proxy_service_.get();
}
void ProfileImpl::InitSyncService(const std::string& cros_user) {
profile_sync_factory_.reset(
new ProfileSyncFactoryImpl(this, CommandLine::ForCurrentProcess()));
sync_service_.reset(
profile_sync_factory_->CreateProfileSyncService(cros_user));
sync_service_->Initialize();
}
void ProfileImpl::InitCloudPrintProxyService() {
cloud_print_proxy_service_ = new CloudPrintProxyService(this);
cloud_print_proxy_service_->Initialize();
}
ChromeBlobStorageContext* ProfileImpl::GetBlobStorageContext() {
if (!blob_storage_context_) {
blob_storage_context_ = new ChromeBlobStorageContext();
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(blob_storage_context_.get(),
&ChromeBlobStorageContext::InitializeOnIOThread));
}
return blob_storage_context_;
}
ExtensionInfoMap* ProfileImpl::GetExtensionInfoMap() {
return extension_info_map_.get();
}
policy::ProfilePolicyContext* ProfileImpl::GetPolicyContext() {
if (!profile_policy_context_.get())
profile_policy_context_.reset(new policy::ProfilePolicyContext(this));
return profile_policy_context_.get();
}
PromoCounter* ProfileImpl::GetInstantPromoCounter() {
#if defined(OS_WIN)
// TODO: enable this when we're ready to turn on the promo.
/*
if (!checked_instant_promo_) {
checked_instant_promo_ = true;
PrefService* prefs = GetPrefs();
if (!prefs->GetBoolean(prefs::kInstantEnabledOnce) &&
!InstantController::IsEnabled(this) &&
InstallUtil::IsChromeSxSProcess()) {
DCHECK(!instant_promo_counter_.get());
instant_promo_counter_.reset(
new PromoCounter(this, prefs::kInstantPromo, "Instant.Promo", 3, 3));
}
}
*/
return instant_promo_counter_.get();
#else
return NULL;
#endif
}
#if defined(OS_CHROMEOS)
chromeos::ProxyConfigServiceImpl*
ProfileImpl::GetChromeOSProxyConfigServiceImpl() {
if (!chromeos_proxy_config_service_impl_) {
chromeos_proxy_config_service_impl_ =
new chromeos::ProxyConfigServiceImpl();
}
return chromeos_proxy_config_service_impl_;
}
void ProfileImpl::SetupChromeOSEnterpriseExtensionObserver() {
DCHECK(!chromeos_enterprise_extension_observer_.get());
chromeos_enterprise_extension_observer_.reset(
new chromeos::EnterpriseExtensionObserver(this));
}
#endif // defined(OS_CHROMEOS)
PrefProxyConfigTracker* ProfileImpl::GetProxyConfigTracker() {
if (!pref_proxy_config_tracker_)
pref_proxy_config_tracker_ = new PrefProxyConfigTracker(GetPrefs());
return pref_proxy_config_tracker_;
}
PrerenderManager* ProfileImpl::GetPrerenderManager() {
CommandLine* cl = CommandLine::ForCurrentProcess();
if (!cl->HasSwitch(switches::kEnablePagePrerender))
return NULL;
if (!prerender_manager_.get())
prerender_manager_.reset(new PrerenderManager(this));
return prerender_manager_.get();
}
|
<reponame>hetanthakkar1/fluentui<filename>packages/fluentui/react-builder/src/components/BrowserWindow.tsx
import * as React from 'react';
const SCALE = 4;
const HEADER_HEIGHT = SCALE * 10;
const HEADER_BUTTON_SIZE = SCALE * 3;
const NAVBAR_HEIGHT = SCALE * 9;
const NAVBAR_BUTTON_SIZE = SCALE * 6;
const PADDING = SCALE * 4;
const buttonStyle = (color): React.CSSProperties => ({
display: 'inline-block',
width: `${HEADER_BUTTON_SIZE}px`,
height: `${HEADER_BUTTON_SIZE}px`,
lineHeight: `${HEADER_BUTTON_SIZE}px`,
marginRight: `${HEADER_BUTTON_SIZE / 1.5}px`,
background: color,
borderRadius: '999px',
boxShadow: `inset 0 0 1px rgba(0, 0, 0, 0.2)`,
});
const styles: {
root: React.CSSProperties;
header: React.CSSProperties;
close: React.CSSProperties;
minimize: React.CSSProperties;
maximize: React.CSSProperties;
navBar: React.CSSProperties;
navButton: React.CSSProperties;
input: React.CSSProperties;
content: React.CSSProperties;
} = {
root: {
display: 'flex',
flexDirection: 'column',
height: '800px',
overflow: 'hidden',
background: '#FFF',
border: '1px solid #CCC',
borderRadius: '4px',
userSelect: 'none',
},
header: {
display: 'flex',
flex: '0 0 auto',
alignItems: 'center',
height: `${HEADER_HEIGHT}px`,
lineHeight: `${HEADER_HEIGHT}px`,
padding: `0 ${PADDING}px`,
background: 'rgb(230, 232, 234)',
},
close: buttonStyle('rgb(237,84,74)'),
minimize: buttonStyle('#f5b638'),
maximize: buttonStyle('#4ec441'),
navBar: {
display: 'flex',
flex: '0 0 auto',
alignItems: 'center',
padding: `4px ${PADDING}px`,
height: `${NAVBAR_HEIGHT}px`,
lineHeight: `${NAVBAR_HEIGHT}px`,
background: '#ffffff',
borderBottom: '1px solid #ddd',
},
input: {
flex: 1,
alignSelf: 'stretch',
background: 'rgba(0, 16, 32, 0.05)',
borderRadius: '999px',
},
navButton: {
flex: '0 0 auto',
marginRight: `${NAVBAR_BUTTON_SIZE / 3}px`,
width: `${NAVBAR_BUTTON_SIZE}px`,
lineHeight: 1,
fontSize: `${NAVBAR_HEIGHT / 2}px`,
color: 'rgba(0, 0, 0, 0.2)',
},
content: {
flex: 1,
overflow: 'hidden',
},
};
export type BrowserWindowProps = {
children: React.ReactNode | React.ReactNodeArray;
showNavBar: boolean;
style?: React.CSSProperties;
headerItems?: React.ReactNode | React.ReactNodeArray;
} & React.HTMLAttributes<HTMLDivElement>;
export const BrowserWindow: React.FunctionComponent<BrowserWindowProps> = ({
children,
style,
showNavBar,
headerItems,
...rest
}) => (
<div key="bar" {...rest} style={{ ...styles.root, ...style }}>
<div key="header" style={styles.header}>
<div key="close" style={styles.close} />
<div key="minimize" style={styles.minimize} />
<div key="maximize" style={styles.maximize} />
{headerItems}
</div>
{showNavBar && (
<div key="navBar" style={styles.navBar}>
<div key="back" style={styles.navButton}>
❮
</div>
<div key="next" style={styles.navButton}>
❯
</div>
<div key="refresh" style={styles.navButton}>
↻
</div>
<div key="input" style={styles.input} />
</div>
)}
<div key="content" style={styles.content}>
{children}
</div>
</div>
);
BrowserWindow.defaultProps = { showNavBar: true };
|
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
/**
* CDI SL4F producer
*
* @author tuxtor
*
*/
@ApplicationScoped
public class LogProducer {
@Produces
public Logger produceLog(InjectionPoint injectionPoint) {
return LoggerFactory.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}
}
|
package com.benefire.waldder.vertex.log;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* @author jiang
*/
public class CustomLoggingHandler extends LoggingHandler {
public CustomLoggingHandler(LogLevel level){
super(level);
}
}
|
def index_for_scope(scope_type, scope_name):
scope = Scope(scope_type, scope_name)
snippets = snippet_service.get_snippets_for_scope_with_current_versions(
scope
)
user_ids = {snippet.current_version.creator_id for snippet in snippets}
users = user_service.get_users(user_ids, include_avatars=True)
users_by_id = user_service.index_users_by_id(users)
brand = find_brand_for_scope(scope)
site = find_site_for_scope(scope)
return {
'scope': scope,
'snippets': snippets,
'users_by_id': users_by_id,
'brand': brand,
'site': site,
} |
package com.learndblshared.plugin;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.util.ReflectionUtils;
@Intercepts({ @Signature(args = { Connection.class }, method = "prepare", type = StatementHandler.class) })
public class TestPlugin implements Interceptor {
private Properties properties;
@Override
public Object intercept(Invocation invocation) throws Throwable {
// TODO Auto-generated method stub
RoutingStatementHandler handler = (RoutingStatementHandler) invocation
.getTarget();
BaseStatementHandler deleteHandler = getField(
BaseStatementHandler.class, handler, "delegate");
MappedStatement mappedStatement = getField(MappedStatement.class,
deleteHandler, "mappedStatement");
disStatementInfos(deleteHandler, mappedStatement);
return invocation.proceed();
}
/**
* 显示MappedStatement相关信息
*
* @param mappedStatement
*/
private void disStatementInfos(BaseStatementHandler deleteHandler,
MappedStatement mappedStatement) {
// TODO Auto-generated method stub
StringBuilder builder = new StringBuilder();
builder.append("id").append(":").append(mappedStatement.getId())
.append("\n");
builder.append("statementType").append(":")
.append(mappedStatement.getStatementType()).append("\n");
builder.append("sqlCommandType").append(":")
.append(mappedStatement.getSqlCommandType()).append("\n");
builder.append("boundSql.sql").append(":")
.append(deleteHandler.getBoundSql().getSql()).append("\n");
builder.append("boundSql.parameterObject").append(":")
.append(deleteHandler.getBoundSql().getParameterObject())
.append("\n");
System.out.println(builder.toString());
}
/**
* 查找到制定对象字段的对象
*
* @param clazz
* @param target
* @param attributeName
* @return
*/
private <T> T getField(Class<T> clazz, Object target, String attributeName) {
// TODO Auto-generated method stub
Field field = ReflectionUtils.findField(target.getClass(),
attributeName);
field.setAccessible(true);
return (T) ReflectionUtils.getField(field, target);
}
@Override
public Object plugin(Object target) {
// TODO Auto-generated method stub
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// TODO Auto-generated method stub
this.properties = properties;
}
}
|
// Copyright 2017 The CRT Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package crt
// uint64_t __builtin_bswap64 (uint64_t x)
func X__builtin_bswap64(tls *TLS, x uint64) uint64 {
return x&0x00000000000000ff<<56 |
x&0x000000000000ff00<<40 |
x&0x0000000000ff0000<<24 |
x&0x00000000ff000000<<8 |
x&0x000000ff00000000>>8 |
x&0x0000ff0000000000>>24 |
x&0x00ff000000000000>>40 |
x&0xff00000000000000>>56
}
|
def cmd_commit(self, arguments):
c_git_entry = None
c_title = None
c_type = None
git_status = self.get_git_status()
if len(git_status) == 0:
self.message("No dirty/untracked files to commit")
self.exit(JournalCtl.ERR_NONE_FOUND)
else:
valid_entries = []
if len(arguments) == 0:
self.log("cmd_commit: no args, choosing from all dirty files")
valid_entries = git_status
else:
for line in git_status:
entry = self.get_entry_from_git_path(line[1])
if all(word in entry for word in arguments):
valid_entries.append(line)
if len(valid_entries) == 0:
self.message("No dirty entries found for your query.")
self.exit(JournalCtl.ERR_NONE_FOUND)
else:
index = self.interactive_number_chooser(
[self.get_entry_from_git_path(line[1])
for line in valid_entries])
if index == -1:
self.message("Selection cancelled, exiting")
self.exit(JournalCtl.ERR_SELECT_CANCEL)
c_type = valid_entries[index][0]
c_git_entry = valid_entries[index][1]
if self.commit_msg:
c_title = self.commit_msg
else:
c_title = None
self.commit_entry(c_git_entry, c_type, c_title) |
I didn't even know what anyone was saying, but I understood all of it, nonetheless....
"Brothers" is a game that borders more on being an
I didn't even know what anyone was saying, but I understood all of it, nonetheless....
"Brothers" is a game that borders more on being an art-form than on just being a video game. You are forced, as the player, to pay attention to all the other 80% of communication that comes in the form of facial expressions, visual cues, posture, tone of voice, etc. in order to follow the story of these two sons journeying to find the cure for their father's illness.
We see in the very beginning how Nyee, the younger brother, watched firsthand as his mother drowned in the sea. Then at a slightly later point in time, he and his older brother, Nya, need to journey to the land of the giants to find a special cure for their ailing father. Along the way, we discover, through having the boys interact with in-game characters, exactly what they are like, personality-wise. Nya, the older brother, is responsible and considerate of others. Nyee is the goof who likes to have a lot of fun. And, we see their beautiful relationship with each other revealed as they encounter life-threatening situation after life-threatening situation.
The gameplay is difficult at first, but you get used to it after a little while. You use both sticks on your controller to move the boys at the same time, and at no point can they be physically too far away from each other. Imagine they both have a rope tied around their waists and that's how it plays (they literally have a rope between them for some platforming levels). Many puzzles and platforming require good coordination skills, so some may become frustrated as a result.
You play as both brothers, solving puzzles and figuring out how to get them from point A to point B. There is no combat in this game at all. Neither of these brothers has some sort of weapon or martial arts move-set to use against an enemy. They do face a couple of bosses, but they have to work together to outsmart them David vs. Goliath-style, minus the sling-shot.
Not only is the world amazing and the story poignant, enough to punch me in the gut harder than most stories ever have before, but this game is rich in symbolism. If you love symbolism, you will love trying to figure out what it all means. I think the giants serve to symbolize adulthood, and how the giants live their lives represents the loss of boyhood, childhood and innocence. Even Nya, the older brother, will find because of his age (early teens), he is more easily corruptible than his much younger brother, Nyee.
For $15, this is an experience like nothing else, and you won't be sorry you spent it on this game. You may feel like the only reason you're not jumping back in to play it again and again is simply because the game made you feel TOO much, and you need a break before returning to it.
Don't play this because you want a mind-numbing game to help you forget how crappy your life is. Play it because you want to question life itself and what your childhood really meant. Why did you have to leave it behind? And, to become what--a society-made monster? Perhaps you will realize you want to keep a piece of your former innocence with you at all times. This game is all about how tragic it is to lose that childhood innocence, especially at a young age.
I give this game either a 10 or at least a 9.5. It deserves every point.
… |
/**
* Test method which tests the functionality of the areFieldsValid method
* It generates random names and tests the functionality of the patterns.
*/
@Test
public void areFieldsValid() {
Faker faker = new Faker();
String firstname = faker.name().firstName();
String lastname = faker.name().lastName();
String email = EMAIL;
boolean validFirstName = (!(firstname.isEmpty())&&(firstname.matches(NAME_PATTERN)));
boolean validLastName = (!(lastname.isEmpty())&&(lastname.matches(NAME_PATTERN)));
boolean validEmail = (!(email.isEmpty())&&(email.matches(EMAIL_PATTERN)));
assertTrue(validFirstName && validLastName && validEmail);
} |
import React, { useLayoutEffect, useRef, useState } from "react";
import styled from "styled-components";
import ContextMenuOption, { Option } from "./ContextMenuOption";
const StyledContextMenu = styled.div`
position: absolute;
bottom: 0;
height: 0;
left: 0;
width: 100%;
`;
const Options = styled.div`
position: absolute;
top: 100%;
left: 50%;
transform: translateX(-50%);
background-color: var(--bg-mid);
border-radius: 10px;
box-shadow: var(--shadow);
display: flex;
flex-direction: column;
padding: 10px 15px;
z-index: 2;
font-size: 16px;
overflow-y: auto;
`;
const Exit = styled.div`
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
background-color: var(--main-light);
`;
class State {
selected: string[] = [];
}
type Props = {
open: boolean;
options: Option[];
close: (selected: string[]) => void;
multiSelect: boolean;
};
const ContextMenu = (props: Props) => {
const [state, setState] = useState(new State());
const contextMenuRef = useRef<HTMLHeadingElement>(null);
const optionsRef = useRef<HTMLHeadingElement>(null);
const setOptionsPosition = (
left: string,
right: string,
pos: string,
maxHeight?: string
) => {
let options = optionsRef.current;
if (!options) return;
options.style.left = left;
options.style.right = right;
options.style.transform = "translateX(" + pos + ") ";
if (maxHeight) options.style.maxHeight = maxHeight;
};
const correctPosition = () => {
const padding = 10;
let options = optionsRef.current;
const contextMenu = contextMenuRef.current;
if (!contextMenu || !options) return;
const contextPosition = contextMenu.getBoundingClientRect();
const maxHeight = window.innerHeight - contextPosition.y - padding + "px";
setOptionsPosition("50%", "auto", "-50%", maxHeight);
let optionsPosition = options.getBoundingClientRect();
const rightMax = window.outerWidth - padding;
if (optionsPosition.x < padding) {
const position = -contextPosition.x + padding;
setOptionsPosition("0", "auto", position + "px");
} else if (optionsPosition.x + optionsPosition.width > rightMax) {
const position = rightMax - contextPosition.x - contextPosition.width;
setOptionsPosition("auto", "0", position + "px");
}
};
useLayoutEffect(() => {
correctPosition();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.open]);
if (!props.open) return null;
return (
<StyledContextMenu ref={contextMenuRef}>
<Exit
onClick={() => {
props.close(state.selected);
}}
/>
<Options ref={optionsRef}>
{props.options.map((option: Option) => (
<ContextMenuOption
key={option.text}
option={option}
multiSelect={props.multiSelect}
selected={state.selected.indexOf(option.text) >= 0}
close={() => props.close([option.text])}
add={() => {
let newSelected = state.selected;
newSelected.push(option.text);
setState({ ...state, selected: newSelected });
}}
remove={() => {
let newSelected = state.selected;
newSelected.splice(newSelected.indexOf(option.text), 1);
setState({ ...state, selected: newSelected });
}}
/>
))}
</Options>
</StyledContextMenu>
);
};
export default ContextMenu;
|
Ecological Awareness: Matrimony of Agriculture and Art © 2020 The Author(s). This open access article is distributed under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike (CC-BY-NC-SA) International Public License (https://creativecommons.org/licenses/by-nc-sa/4.0/), which permits noncommercial re-use, distribution, and reproduction in any medium or format, provided the original work is properly cited and such creations are licensed under the identical terms. Social Inquiry: Journal of Social Science Research 2020, Vol. 2, No. 2, pp. 234-252 Introduction Mithila art is a visual commentary of local people whose main occupation is farming. Farming goes parallel to creation which is seen through the ethnic art version. The history of folk art goes back almost to the history of human civilization when people had different mode of living. As the time passes, mode of living consequently changes and leaves certain impact on art form. The contemporary Mithila art reflects agrarian culture where all sorts of phenomena occurring in the daily life of Maithili people are depicted. -The topics ranged from family planning, the literacy campaign, and the dowry problem to environmental issues such as the planting of trees (Hauser, 2002, p. 114). In this way, art captures the age of people and their culture. In this regard, Mithila art captures complex rituals of agrarian culture in the visual form to direct the society for better creation in the days to come. Social Inquiry: Journal of Social Science Research, Volume 2, Issue 2, 2020 The glorious tradition of Mithila folk arts has always represented the different ages of human civilization. In the very beginning, the cave painting, primitive frescos in iconic forms, and stone carvings were the first rudimentary forms of folk arts. Ancient Mithila was a fertile land for art and civilization. Although initial inspiration for these folk arts like other arts was religion, later their horizon of subject matter was broadened. In contemporary Mithila paintings, familiar subject matters like daily life, works, toils, beliefs, animals, plants, and the like can be found. Besides, -the art emerges as the suggestive sound pictures of the various environments; each art reflects the mental perception and awareness of the physical and cultural milieu (Karan & Mather, 1976, p. 502). Maithili artists exploit various cultural symbols to reflect their social position regarding their surrounding environment. Mithila society at present maintains agrarian mode of living where agriculture determines everything in public life. So, Mithila art exploits farming life style and identity of the locale in relation to their living. In course of representing geography and people, art visualizes the age and beyond. Therefore, art happens to form its root within surrounding nature and ethnicity. Hence, Mithila art is the product of local natural objects and ethnic culture. As a cultural practice of collective life pattern, Mithila art is often ceremonial. The ceremonial significance of this ethnic art is so much that any auspicious occasion becomes incomplete without it. It denotes the importance of art in Maithili society. Life is incomplete without art as reading between the lines of living reveals. Moreover, the content of art is ecological in nature. Ecology has been viewed as -nature and has served either as a back-ground in art or as the major theme in landscape art (Neperud, 1997, p. 14). From the time of birth to death, art expresses every happenings of social life whether they are birth, marriage or death rituals without the expression of all these rituals in art forms every celebration is incomplete. Therefore, art always merges the immediate surrounding with culture so that people won't feel dislocated and can construct themselves during destruction. So Neperud focuses how -art develops a sense of empowerment to recognize, improve, and reconstruct neglected environments Social Inquiry: Journal of Social Science Research, Volume 2, Issue 2, 2020 through individual and communal actions (pp. 235-236). More often than not, agrarian art strives to remind and educate viewers of the value that the land holds, preserving the heritage and history of our agrarian roots for future generations. Methodology This research employs qualitative method of study with observation, interview and questionnaire as tools to data collection and environmental theme for data analysis. The resultant outcome figures out the local mode of preservation of the surrounding nature with locally developed traditional values, geographical flora-fauna and agrarian lifestyle. In Mithila culture, spiritual life remains integrated with day-to-day activities targeted at earning livelihood, this article contends that an individual lives intertwined with natural surroundings, the folk art dramatizes this phenomena. The attainment of selfrealization, while still eking out bread and butter, comes from the philosophy of native wisdom. The philosophy of a balance between worldly pleasures and the mystical ecstasy, which the art exemplifies, also informs this art. In Maithili agrarian society, the philosophy manifests in the way the everyday matters find primacy of space in artistic creations which also embody the artists' ardour to be one with the divine/natue. In this regard, Chaudhuri asserts that Maithils seek spiritualism by not cutting themselves from atman (affection, intimacy) (p. 163). Original inspiration for the protection of local flora and fauna seems inherent in the farming chores that make life and living of the native folks inseparable. Discussion/Analysis The sacred art of indigenous people offer them a medium to communicate with their ancestors, forefathers and family deities. In addition, ingenuity has kept the agrarian mindset resilient. The land and agrarian mindset are vital components to the success and preservation of our current culture. Besides, symbiotic relationship between art and the land, highlighting both artists who take their inspiration from agriculture and farmers who use art to inspire their labors are the traditional theme of Mithila art. In this regard, Aran aptly notes that traditionally Maithils have been drawing on mud walls and recently shifted on paper. In this way, agrarian culture teaches responsibility to protect, preserve and celebrate life. Agrarian Maithili culture inspires its ethnic art to exploit cultural artifices of its own location. To a great extent, all art forms¬¬-whether they are religious, social and agricultural as well as the fine blending of all these forms-are reflection of the available materials and their interaction with farming skills. Hence, art acts as a tool to manipulate people to preserve their surroundings. -Art is a tool for illustrating ecological concerns and a technology for conveying messages about ecology (Neperud, 1997, p. 14). Thus, art brings agrarian values into light. The farming knowledge and its consequent change due to the regular challenge to fulfill the demands of food to the society modifies the art forms regularly to cope with changing ethos of time. The artists shape their forms and develop it according to their intuitive organization of ideas. How these arts are a vital part of the Maithili culture can be understood in the words of Bhavnani -a deep need to create these things of beauty and utility since they are a vital part of their very existence and life pattern (p. 9). But the commercialization of these art forms has made artists depict even unique rituals on paper and clothes. Thus, agrarian culture is gradually shifting towards industrial sector simply to fulfill the demand of consumers in the market. However, the real ceremonial and cult value lies only in their ritualistic performance, not on professional reproduction of arts. The wide depiction of every activities from the very beginning of the start of annual farming ceremony to the harvesting period easily communicate that Mithila art reflects agrarian culture of the region. Nevertheless, the women play a great role to hand over it from one generation to another. Likewise, Maithili women discharge the entire household activities like praying sibling god, and fasting on all the religious and social worships. Besides, they also commemorate and purify the occasion wearing ornaments and fasting sometimes for two or three days continuously. While doing so, they can meditate for long on art activities to confiscate the occasion in real sense. Maithili women draw the figure of plough and other assisting articles like sickle, axe, spade, the symbols of good omen so that they can grow enough food to maintain the family well. -Paintings which were pure and based on the artistic tradition of Mithila were most valuable (Jain, 1980, p. 214). Because each lines and forms carry meanings, each performance is a moment of spiritual vow. The significance of performance mood is all that matters for the artists and the women are the artists to protect and enhance their cultural legacy. -The stooped figure concentrates, as if in prayer (Jain, 1980, p. 211). An artist has to work as if she is coaxing the cosmic energy and interacting with the divine. Such meditative silence makes the art form a kind of prayer to god whom, as it is believed, to make all ends meet. Besides, farmers plough the land and sow the seed, caring them as well as harvesting is the common practice among artists to portray. On the whole, farmers consider domestic animals as their own sibling, and worship them for their help and milk. Not only the terrestrial animals but also the aquatic ones are drawn to denote different motifs in daily and personal life of people. For instance, fish covers enough space in the local art form in Mithila region because it awakens the feeling for fertility and freshness. In addition, other animals like snakes, scorpions and frogs, which play various roles to balance human life, are portrayed with great fun in different occasions. And, these figures are drawn traditionally with mud on the mud walls of house, pots, and large vessels of grain. In this way, mud plays an integral part in the lives of agrarian Maithili people. In addition, women bring these motives in their art and empower themselves with several symbols used in their art. Besides, -art empowers not only to women but also to their off springs (Jain, 1980, p. 209). Hence, the whole family cultivates an opportunity to move forward economically, socially and educationally. Similarly, they enjoy and express their love towards birds as well. For example, cuckoo's song inspires them to work diligently even in the scorching heat. Likewise, the parrot and its beautiful appearance provoke them to praise beautiful works and keep on trying for the best. In addition, love for migrated birds to Mithila region is enjoyed a lot by young girls and they sing song together making idols of the birds, and offer them so much love and care so that they will come every year. Birds with the major appendage in natural Social Inquiry: Journal of Social Science Research, Volume 2, Issue 2, 2020 beauty are also the beauty of this ethnic art. It inspires artists to move continuously in the work of creation. Moreover, the innocent manners and performance of birds actually broaden the horizon of creation on the part of artists. Hence, nature is the major inspiration behind folk art, according to Bhavnani, -Nature seems to have set the pattern for almost every creative urge and artistic endeavors, not only among the people in India but throughout the world (p. 11). Learning by observing is natural among human since ancient time. Because of the constant touch with nature and their surroundings, people frame certain perception in their mind and the occupied acuity reflects through their expression. Consequently, the frame of ideas happens to generate originality after the interaction with other objects and living pattern of people. Likewise these contiguous objects become symbols in the hands of artists to universalize the personal feelings. Mithila art is marked for the use of natural symbols rather than eccentric private symbols. However, modern art is deciphered after analyzing the private symbols which originally do not fulfill the public demands of easy information in the fast growing age. Furthermore, the wide spread public symbol is understood by all in a folk artists' community. Bell quotes Carl Jung, -the effective living symbol that evokes a universal response must contain an understanding shared by large number of people (p. 213). Nevertheless, the symbols exploited in folk art are originally derived from their own primitive surrounding objects or their modified form at present. The purpose of the use of symbols is to transmit the common consciousness in open form so that unity among people and their identity can be framed simultaneously. Besides, these symbols set common goals in front of whole society to achieve together for all round welfare of the members inhabiting there. Mithila art in general carries the legacy of people from antiquity. It demonstrates how people in the region have been carrying their culture since time immemorial. People are the product of their culture: they understand the world on the basis of the cultural glass they wear since their childhood. Besides the visual history, the folk art provides are not limited to its literal meaning; rather, it goes beyond and represents the entire custom, legacy, living ways, and ritual occurrences in various occasion at different time intervals of their ancestor's life. The mutual blending of local colors, flora, fauna, and human sentiment make every folk art living throughout the history. However, art carries manifolds of meaning to envisage even what our naked eyes cannot. In this connection, Bell quotes Anton Ackermann, -All culture always appears to us in a double form. Culture is first the totality of material goods that a folk has created through its diligence (p. 84). Mithila art is the landscape where people of the region perform their regular ritual. The art in the form of a window provides a panorama of the culture where not only human beings but also the nature appears to be taking part in the struggle of life and living. Moreover, -landscape painting is essentially a romantic art, an art invented by a lowland people who had no landscape of their own (Read, 1992, p. 163). Art is not confined within the fixed objects: the whole objects are treated as an art form. For instance, pottery, basket weaving, and the objects of daily use are considered as the single art form. In addition, the dolls which act as both playing materials for children as well as a purse for adults are the single object having multiple businesses. Besides, -the more we understand art, the more we understand ourselves and the complexities of our world (Cole & Gealt, 1989, p. vii). Thus, the entire culture can be viewed through the single artifact of society. Therefore, Herbert Read mentions, -art is the direct measure of man's spiritual vision (p. 267). Moreover, every product of society has participatory role which generates meaning through visual language to guide an individual in collective form. The whole agricultural mass at times depicted in art form carries special meaning. To illustrate, the bamboo and its collective root together denote to have many children in Kohbar painting; however, there are multiple meanings of the same object. Moreover, agrarian culture modifies the same object in various forms and the change in form leads to alter in structure that consequently shifts the meaning. However, the form provides holistic picture of the object. -The content, subject matter or meaning of a work of art is inextricably, related with its forms (form is a holistic term for mediums, Social Inquiry: Journal of Social Science Research, Volume 2, Issue 2, 2020 texture, structure, color, balance, proportion and space etc.) (Bell, 1979, p. 213). Artists use all these things extracting from their surrounding that makes these local art carry its own geographical identity. The fine combination of all these local products provides Mithila art its own kind of form. The plants which provide life to people supply content to their arts. The background of all art forms begins with flora available in the province which decodes art from the womb of nature. The juxtaposition of birds, animals and plants are largely the subject matter of Mithila art. The dolls which are the lovely companion of children are depicted on the walls, clothes, and almost all the objects which children look at and find wonderful. Since their childhood, they set a secure mission to live with common attitude with their fellow social mates. Thus, Mithila art becomes an indispensable form of Maithili culture which cannot remain without expressing the mute glory of agrarian life and culture. In this way, art for Maithili people is a means to express and communicate themselves with gods, nature and social realm in which they live. Yet, the symbols carry more or less the same meaning because they are derived from the mutually acknowledged resources. The reflection of the charm of art qualifies it to have certain value like beauty. In addition, the beauty of art attracts every individual to look at it and gain aesthetic pleasure the same time. As Cassirer notices that -Beauty appears to be one of the most clearly known of human phenomena (p. 926). It is this inclination towards beauty of art that makes people to experience the social standard. The interaction with art takes people closer to truth. The artist fulfills the gap left by nature through several ethnic emblems. The emblems are the local icons familiar to all. In this regard, Cassirer further adds, -Art most of the time constructs and organizes our sense of human experience according to its own formal principles (p. 925). In fact, these ideologies carved as an art form gives originality and permanency of the ascribed truth of that community. For Gombrich, -All art is fundamentally the making of images; the making of images is based psychologically on the making of substitutes (p. 1082). Thus, the natural artifacts are imprinted as an art form to generate confidence among people to implement their belief in practical life. The depiction of animals and plants in art not only conveys the general form of the object; rather, it also associates their potential qualities with their portrayal. For example, fish is swift as well as productive aquatic animal that gets place in nuptial chamber painting to help visualize the social message to be productive after marriage. Similarly, elephant as a fine portrayal suggests that one can be strong even on vegetarian food. Traditionally, people like to be vegetarian than non-vegetarian. Such message along with the social symbols is quite common phenomena of Mithila art basically to Maithili people. More often than not, symbols used in this folk art are permanent in nature and convey solid picture of the society. It is not like mainstream art as Gombrich quotes Heraclitus -The sun is new everyday is true for the sun of the artist if not for the sun of the scientist (p. 930). The artist captures the moment, not the ever durable scene because of its special importance in artistic world. The exploitation of structure leads artist to intensify reality because it provides pleasure to them. The artist's imitative mood becomes an inexhaustible source of delight for them. Cassirer quotes Aristotle -the reason of the delight in seeing the picture is that one is at the same time learninggathering the meaning of things (p. 927). Besides, art is conceived as an allegory, a figurative expression which under its sensuous form conceals an ethical sense. This ethical sense in art develops among people when it is regularly observed as part and parcel of living. While celebrating life through rituals in the form of festivals, occasions, and other various social nuances it ultimately ends in departing some message to the observer. However, art possesses no independent value of its own. The same symbol appears different to each individual or it may seem the same. Moreover, art prepares people to live well and live for some goals: goals of progress drives people forward to achieve collective aspiration. Therefore, Cassirer mentions, -in the hierarchy of human knowledge and of human life art is only a preparatory stage, a subordinate and subservient means pointing to some higher end (p. 926). It is more useful in the social setting where one needs other to cooperate and move forward like the juxtaposition of different materials to produce a fine art. Likewise, Cassirer quotes Simonides -Painting is mute poetry and poetry a speaking picture (p. 927). Where the silence of materials in art keep on conveying people with its own visible form, everything people like to derive. Besides, Cassirer points out, -Artist releases his forms from the necessity of belief, the work of art tells us what it tells us by its total structure, not by assertions abstracted from its reality (p. 925). Hence, the format designed out of locally available materials indicate the purpose of Mithila art to fulfill local motive spreading its own social message. Social values in Mithila largely depend on the occasion. Basically, Kohbar painting serves as the juncture from where social ethics can be easily interpreted. Nuptial chamber is the vibrant place where exotic, intricate, and exuberant paints are employed with many symbolic images like the lotus plant, bamboo grove, fish, birds and snakes in union. Each symbol carries its own ideals but the major ones are fertility, sexual ability and proliferation of life. Nevertheless, there is one thing special about the red color: it is taken as auspicious and hence it is widely used. Moreover, the elephant, horse, and palanquin are the symbols of royalty and richness. Likewise, the goose and peacock are symbols of welfare and calmness. Similarly, Paan (betel leaves) and lotus symbolize good luck. Finally, -bans (bamboo) is the symbol of future progeny (Rakesh, 1991, p. 94). These symbols are so common that people take no time to understand and apply them in their daily life. The abundance of these symbols in Mithila has made social values a part of living well. While exploiting these symbols, ignorant Maithili women do not use any idea rather express whatever they feel spontaneously. But, without violating any traditional structure, they use their feelings, emotions and tradition alive through the folk art form. Cassirer quotes Rousseau, -Art is not a description or reproduction of the empirical world but an overflow of emotions and passions (p. 927).This rightly justifies the overall sentiment of Maithili women. Moreover, Cassirer also quotes Mallarme, -Art is not written with ideas, it is written with words, images, sounds, and rhythms (p. 929). Maithili women use lines, colors, pigments, symbols, and metaphors to keep the age old social values living through their ethnic art. Social values like integration, harmony, co-operation, and co-existence are the major theme of Mithila art. This age old common style points out the equilibrium in the society and the whole proprietorship goes to the values allocated in the folk art. According to Eliot, -the age which manifests the greatest extremes of individual style will be an age of immaturity or an age of senility (p. 498). The content of art and people has very long rooted relationship even if by chance there is something wrong they feel deeply hurt. The relation between values and people is quite sensitive and strict in that it binds their entire life within the set standard. So, the subject in art marks public feeling and even moves them for certain activity. Edgar points out that -the subject is rather the unfolding product of an engagement with nature and the given cultural environment (p. 115). Hence, nature and culture mix together to produce for people certain values which have provided a systematic outlook of the society. Politically speaking, Mithila art sets standard for inclusive society. In fact, it constitutes all locally available materials, plants, and animals to justify that politically there is a set standard to practice. The social structure may fall down if there is a lack of practice of the inclusive mode of politics. Even if real life does not experience it, nature dilutes the political pressures and conflict in the society. Therefore, Edgar quotes Lowenthal -The identification of the individual with nature represents the possibility of an escape from social pressures and conflicts (p. 111). Women express themselves politically through the folk art from the ancient time which symbolizes the fine arrangement of the society because the communication purgates people and the art provide the context to do in the purification of the inner contents of mindset. Edgar further quotes Lowenthal -A work of art communicates with its audience (p. 112). Obviously, art possesses some fixed ideology through which to shape an individual politically. Democratically, art values everyone equal and does not discriminate one from another. Mithila art includes all on the basis of their occupation. Although people are divided according to occupational castes, they are united to make a whole out of parts. Nevertheless, the casteism in the present time appears burden as well as invites psychological gloom. Only the best work of art heals people out of anguish. Therefore, Edgar suggests -Genuine works of art objectify this despair (p. 113). Is there a classic type of set standard for the voice of the voiceless or not? The answer is quite clear as art clarifies society and particularly, the Mithila art has participatory mode of presentation where even the people from the lowest caste participate to silhouette the complete art work. Movement towards complexity in the folk art reveals the progress towards classic version of art. Such type of revolutionary step marks the overall change in the belief system which ultimately emancipates each category of people. Moreover, the collective shades of feeling are evaporated for the healthy political society. More often than not, artists have represented their age, society, political system, and economical base where common people are clearly seen through the contemporary art form. But the progress is vivid when Eliot marks -One of the signs of approach towards a classic style is a development towards greater complexity of sentence and period structure (p. 499). Furthermore, Edgar quotes Adorno -Art works to riddles, each work is an attempt to solve the riddles posed by its predecessors (p. 118). Thus, society experiences liberation to express each individual exactly what they are. Similarly, religious depiction is the most common content of Mithila art. The entire locality is in the grip of Hindu mythology since time immemorial. The Hindu epics like the Ramayana, the Mahabharata, and the Geeta, and their true lesson equally applicable in all the ages of human life reveal the essence of this folk art. The religion is the metaphor of moral truth as Cassirer states, -art can be described as an emblem of moral truth (p. 926). Although Hindu priests have developed fatalism in the society imposing caste system, -casteism developed fatalistic society (Bista, 1991, p. 4). The fine blending of religion and morality helped people easily accept the imposed norms though it was against their equality. As work is worship, art equalizes everyone through its expressive mode of imparting education, -the distinction between scientific knowledge and knowledge in art lies only in art's mode of presentation (Edgar, 2001, p. 117). And the staging of Mithila art is always participatory that makes the age old religious tradition lively even during the present period. It is the religion which creates balance in society despite several revolutionary steps. And it is the art which exploits religion to reflect all the virtues of human life. Art can be compared to adolescent as Eliot argues, -the young artist revolts as well as preserves essential family characteristic (p. 499). In fact, the depiction of religious content makes Mithila art full of epical nuances where standard is always to be met and the folk art makes public life ever progressive to achieve the virtues like patience, noble, respect to older, love to younger, loyalty to wife, and model for all in all round behavior as mentioned in the Hindu epics. Thus, the age old religion inspires people to preserve one's culture as Eliot further mentions, -the collective personality, so to speak, realized in the literature of the past-and the Social Inquiry: Journal of Social Science Research, Volume 2, Issue 2, 2020 originality of the living generation (p. 499). Hence, the continuation of creating art is possible due to religious motive to capture the essence of the society despite the changing time to bring people on track at all times. Commercialization has really wrought the modern world and its effect is easily seen at every corner. Mithila art is not the exception. The emerging artists take creation of art as both from professional as well as artistic purpose because they have to fulfill their economical and artistic need at the same time. The economy at the present time matters a lot to determine individual life style as Edgar quotes Lowenthal -Art would manifest traces of its mediation by the economic and class structures of the society within which it was produced and consumed (p. 115). The economic base of society shapes the artistic creation produced there. However, commercial motive of art has exploited current exciting theme which can easily be popular in the market. Despite the aesthetic value of art, it does contain economic value to sustain artists with their art. Meanwhile, they entertain vulgar theme in their creation which can lead society towards vulgarity as well as people from outside may figure out something misleading about the culture. It should be objective than having other sentiment on the part of artist while designing art. In this regard, Cassirer adds, -Art is an intensification of reality as well as art is one of the ways leading to an objective view of things and of human life (p. 929). If the current trend persists, it will damage originality of the culture and society that will further lead people having no importance of advocating their ancestral root. In other words, people will find themselves without identity. So, it must be preserved and art should only be for its own sake. In the course of time, increasing population is certainly the cause of environmental degradation but the large amount of symbols used in art signifies that the balance of ecology is essential in the surrounding. The bond of people with their environment is so profound that they plant siblings on the birth of their babies and keep on planting every year on the occasion of their birth day. People know that coming generation may suffer if ecological balance is not maintained. Regarding this attitude, Thapa asserts, -Cause of all suffering of mankind is the mistake of their past lives (p. 110). The anthology of all these things in Mithila art reveals the essence of Maithili culture towards ecology on agrarian, religion, and social ground. Thus, art alerts people from deviation. The depiction of agrarian values throughout the local art vividly pronounces the affinity of people with their surroundings. On the one hand, over-population limits the resource while, on the other hand, environmental degradation affects the economic condition of people. Consequently, the bitter experience of poverty perverts standard culture of society. According to Hamal and Pokhrel, -Massive poverty increases people's dependency on environment resulting depletion of the resources (p. 123). Environmental degradation limits the survival opportunities of the poor and thereby pushing them into poverty trap. Thus, poverty does not become a cause; rather, it is a consequence of misuse of environmental resources. People in agrarian society totally base themselves on the available natural resources. The plenty of them provide people confidence to step forward the social development. In fact, environment provides endowment and entitlement of opportunities to those who do not own other resources especially in Maithili society. However, unequal distribution of the environmental opportunities and limited survival strategies are the catalysts that influence environment and economy. Moreover, Hamal and Pokhrel add, -the state of the natural environment is therefore central to the livelihoods, health and security of millions of people living in poverty and therefore to pro-poor growth (p. 124). Mithila art captures this entire scenario to mirror the life and living ways of people in detail focusing the flora and fauna at the centre. Along with agriculture, religious mode of society further exploits natural entities at the centre to commemorate life on earth. While talking about the life of Ram, the protagonist in the Ramayana, or the life of Pandawas (characters in the Mahabharata) in the forest, the art does not describe their ethos of life only but depicts the ecological importance in the life of human beings. More often than not, the illustration of the empathy towards nature and people traditionally provokes the indigenous art to centralize it while depicting socio-cultural aspects of the region. In this connection, Bhattarai explains, -how from the ancient time literature has been describing the Social Inquiry: Journal of Social Science Research, Volume 2, Issue 2, 2020 beauty and ugly faces of nature (p. 102). The Maithili art visualizes this religious panorama of the locality to fulfill the inherent mission of society for ecological balance. People in Mithila have specially two extra things which really function as the balancing factors for ecology in the region: they are women and soil, equally fertile in nature. On the one hand, women are creative and progenitor of Mithila art to reflect exactly the way things happen. On the other hand, soil is so fertile that anything grows vehemently in abundant amount, enough for people to enjoy life. Moreover, Thapa mentions, -Soil is of good quality for agriculture and sufficient rainfall for healthy crops in Mithila region (p. 131). Likewise, women's affinity with natural objects of the surrounding makes them draw fish, elephant, and bird on their daily use products which indicate how nature closely guard the eventual feat of people in Mithila. Gombrich quotes Sesson, -Women are closer to nature than men (p. 1083). However, women do not forget to add male activities in their art; rather, they capture them to show their life is incomplete without each other. The representation of the self through art and depiction of nature in the art juxtaposes society and nature to balance life through art. The deep ecological vision of the society gets its nurturing through its identification with surrounding environment. Thus, a kind of spontaneous relation is established with immediate nature where saving environment is saving oneself. In this context, Schopenhauer quotes Arne Naess, -if reality is like it is experienced by the ecological self, our behavior naturally and beautifully follows norms of strict environmental ethics (p. 1). Moreover, art makes itself living through the utilization of well-balanced social and natural phenomena in Mithila where one is indistinguishable from another. Consequently, the fine blend of life and surrounding in Mithila art makes people connote life is nature, and nature, the life. In this way, any sad event on the part of nature hurts human, hence, people attempt for no natural imbalance in the region. Conclusion To sum up, art borrows agrarian structure to mold itself into a system where mode of living in conjugation with immediate environment becomes a |
Q:
Gestalt Factotum//Artificer vs Factotum//Wizard
So my friend and I are looking at doing a solo gestalt campaign starting at level 8. It's going to be relatively high-wealth, set in Eberron. Basically, the idea is that since our current DM makes a bunch of weird and arbitrary houserules(see my other questions), we want to take an opportunity away from that to explore the higher tiers and just what they're capable of. The general idea will be to powergame the crap out of my character and then throw me into situations any normal character shouldn't be able to ever deal with. Here are the specifics:
"Epic fantasy" point buy
More feats: Feats at 1, 2 and every even level (like fighter)
1.5 times normal wealth
Starting at level 8
The only thing off-limits is iterable infinite or near infinite cheese, like Gating Effritis for infinite wishes or stacking Time Stops for infinite rounds
I'm looking at either Artificer//Factotum or Wizard//Factotum, but I'm not sure which to go with. I was figuring that Artificer would give me more versatility with preparation than wizard, but I'm not sure if it's worth not having full casting on a per-day rather than per-dollar basis.
So the final question is: Given a solo campaign with in this situation, which build will be more usable, survivable, and able to efficiently complete the quests it starts out on? What would be my staple spells/items/general combat approach for each?
A:
As it stands, the question cannot be answered on its face: “over-the-top, completely unrealistic cheese” is undefined and critical to try to do a comparison of the mechanical advantages of each class. This answer, however, is challenging the frame of the question, since it compares the two classes regardless of what each is or isn’t allowed to do.
Artificer is maybe theoretically more powerful, but you almost certainly don’t want to play a theoretical-optimization artificer
Artificer is the most complicated class in the game to play. It is hands-down, indisputably, utterly without competition in that regard. You need to track gold, XP, expensive material components, and time, and you need to have exceptional preparation, organization, and planning skills. You also need to literally know every item ever published and what they cost; there are literally thousands of those. Spreadsheets are almost mandatory to put the class to good use. To actually optimize it, get as much out of it as possible, you might consider becoming or hiring an actual accountant.
That difficulty comes from the artificer’s extreme versatility, and versatility is a huge advantage in 3.5. All of those options before the artificer could, from another perspective, represent opportunities. Unfortunately, you need to choose correctly from among all those options the overwhelming majority of the time. It is very, very easy to create a thoroughly mediocre artificer.
The wizard, on the other hand, has one thing and one thing only to worry about: spells. They’re a fundamental component of the class, that the wizard automatically gains as he levels up, and they are phenomenally powerful. Magic items are still super-useful tools for the wizard, the wizard can also take Item Creation feats, but the spells are always there. The wizard is still a very-complex class; the Sor/Wiz spell list is immense. But planning out a day’s spells is still orders of magnitude simpler than planning out when and how you’ll make each of the items that take many weeks to complete you’ll be working on.
And even at the absolute edge of optimization, the wizard is still definitely competitive with the artificer. The advantages of the artificer only might put it ahead, maybe. Assuming you do everything right. Both classes are astonishingly capable. |
<filename>py_rpb/data.py
domaind={
'GREETING_MORNING':'politeness',
'GREETING_INFORMAL':'politeness',
'GREETING_LEAVE':'politeness',
'PLEASE':'politeness',
'THANKS':'politeness',
'SORRY':'politeness',
'SHOWER':'hygiene',
'WASH':'hygiene',
'VERMIN':'hygiene',
'SOAP':'hygiene',
'FRUIT':'food',
'VEGETABLES':'food',
'MEAT':'food',
'PORK':'food',
'FISH':'food',
'POTATO':'food',
'ALCOHOL':'food',
'JUICE':'food',
'MILK':'food',
'RICE':'food',
'LENTILS':'food',
'WATER':'food',
'TRAIN':'transport',
'CAR':'transport',
'PLANE':'transport',
'TRUCK':'transport',
'BUS':'transport',
'PEDESTRIAN':'transport',
'TRAMWAY':'transport',
'TUBE':'transport',
'UNDERPANTS':'dress',
'UNDERSHIRT':'dress',
'SOCKS':'dress',
'TROUSERS':'dress',
'SHIRT':'dress',
'PULLOVER':'dress',
'BLOUSE':'dress',
'TSHIRT':'dress',
'SHOES':'dress',
'SCARF':'dress',
'GLOVES':'dress',
'CAP':'dress',
'JACKET':'dress',
'SLIPPERS':'dress',
'BRA':'dress',
'FATHER':'kin',
'MOTHE':'kin',
'PARENTS':'kin',
'CHILD':'kin',
'SON':'kin',
'DAUGHTER':'kin',
'BROTHER':'kin',
'SISTER':'kin',
'BROTHER_ELDER':'kin',
'BROTHER_YOUNGER':'kin',
'SISTER_ELDER':'kin',
'SISTER_YOUNGER':'kin',
'UNCLE':'kin',
'AUNT':'kin',
'GRANDMOTHER':'kin',
'GRANDFATHER':'kin',
'GRANDCHILD':'kin',
'HUSBAND':'kin',
'WIFE':'kin',
'PERSON_FEMALE':'humans',
'PERSON_MALE':'humans',
'PERSON_UNDERAGE':'humans',
'PERSON_ADULT':'humans',
'MALE':'humans',
'FEMALE':'humans',
'BABY':'humans',
'ADDRESS_SELF':'humans',
'ADDRESS_2PERSON':'humans',
'ADDRESS_3PERSON_MALE':'humans',
'ADDRESS_3PERSON_FEMALE':'humans',
'ADDRESS_3PERSON_NEUTRAL':'humans',
'ADDRESS_SELF_GROUP':'humans',
'ADDRESS_2PERSON_GROUP':'humans',
'ADDRESS_3PERSON_PLURAL':'humans',
'SIZE_BIG':'adjectives',
'SIZE_SMALL':'adjectives',
'TEMPERATURE_HIGH':'adjectives',
'TEMPERATURE_HIGH_VERY':'adjectives',
'TEMPERATURE_LOW':'adjectives',
'PRICE_HIGH':'adjectives',
'PRICE_LOW':'adjectives',
'FEEL_HUNGRY':'adjectives',
'FEEL_THIRSTY':'adjectives',
'FEEL_TIRED':'adjectives',
'GOOD':'adjectives',
'BAD':'adjectives',
'YES':'basics',
'NO':'basics',
'QUESTION_PERSON':'basics',
'QUESTION_OBJECT':'basics',
'QUESTION_LOCATION':'basics',
'QUESTION_TIME':'basics',
'QUESTION_TIME_DURATION':'basics',
'QUESTION_REASON':'basics',
'DIRECTION_LEFT':'basics',
'DIRECTION_RIGHT':'basics',
'DIRECTION_FRONT':'basics',
'DIRECTION_BACK':'basics',
'DIRECTION_UP':'basics',
'DIRECTION_DOWN':'basics',
'CLOTHES_DON':'activities',
'CLOTHES_UNDRESS':'activities',
'MOVE_SELF_UP':'activities',
'MOVE_SELF_FLOOR':'activities',
'MOVE_SELF_OBJECT':'activities',
'WAIT':'activities',
'ACTION_RETURN':'activities',
'ACTION_REST':'activities',
'ACTION_EAT':'activities',
'ACTION':'activities',
'ACTION_GIVE':'activities',
'ACTION_TAKE':'activities',
'GEOGRAPHY_BORDER':'politics',
'SPECIALIST_SOLDIER':'politics',
'SPECIALIST_POLICE':'politics',
'DOCUMENT_PASSPORT':'politics',
'WAR_GUN':'politics',
'KNIFE':'politics',
'WAR_FIGHT':'politics',
'LOCATION_PRISON':'politics',
'LOCATION_CAMP':'politics',
'OBJECT_FENCE':'politics',
'PERSECUTION':'politics',
'DOCUMENT_UNSPECIFIED':'politics',
'TORTURE':'politics',
'PERSECUTION':'politics',
'ISIS':'politics',
'RELIGION':'politics',
'RELIGION_CHRISTIAN':'politics',
'RELIGION_ISLAM':'politics',
'RELIGION_JESIDE':'politics',
'RELIGION_JEW':'politics',
'POVERTY':'politics',
'WAR':'politics',
'WAR_BOMB':'politics',
'KILL_PERSON':'politics',
'ISO_3166-1_alpha-2_HU':'geography',
'ISO_3166-1_alpha-2_AF':'geography',
'ISO_3166-1_alpha-2_DE':'geography',
'ISO_3166-1_alpha-2_SY':'geography',
'ISO_3166-1_alpha-2_IR':'geography',
'ISO_3166-1_alpha-2_IQ':'geography',
'ISO_3166-1_alpha-2_TR':'geography',
'STATE_GROUP_EUROPE':'geography',
'STATE_COASTAL':'geography',
'GEOGRAPHY_SEA':'geography',
'GEOGRAPHY_SEA_MEDITERRANEAN':'geography',
'GEOGRAPHY_ISLAND':'geography',
'GEOGRAPHY_COAST':'geography',
'GEOGRAPHY_MOUNTAIN':'geography',
'ETHNIC_ROM':'geography',
'TIME_NOW':'time',
'TIME_LATER':'time',
'TIME_DATE':'time',
'TIME_TODAY':'time',
'TIME_TOMORROW':'time',
'TIME_YESTERDAY':'time',
'WIKIDATA_Q11574':'time',
'WIKIDATa_Q7724':'time',
'WIKIDATA_Q25235':'time',
'WIKIDATA_Q573':'time',
'WIKIDATA_Q23387':'time',
'WIKIDATA_Q151':'time',
'UNIT_YEAR':'time',
'TIME_DAY_EARLY':'time',
'TIME_DAY_MIDDAY':'time',
'TIME_DAY_LATE':'time',
'TIME_DAY_NIGHT':'time',
'LOCATION_HOSPITAL':'health',
'LOCATION_CLINIC':'health',
'SPECIALIST_DOCTOR':'health',
'SPECIALIST_PARAMEDIC':'health',
'SPECIALIST_NURSE':'health',
'DIAGNOSE_INJURY':'health',
'DIAGNOSE_WOUND':'health',
'DIAGNOSE_ILL':'health',
'DIAGNOSE_DISEASE':'health',
'DIAGNOSE_INFECTION':'health',
'DIAGNOSE_HAEMATOME':'health',
'DIAGNOSE_FRACTURE':'health',
'DIAGNOSE_BURN':'health',
'DIAGNOSE_SPRAIN':'health',
'SYMPTOM_PAIN':'health',
'ACCIDENT':'health',
'SYMPTOM_FEVER':'health',
'PREGNANCY':'health',
'DIAGNOSE_ALLERGY':'health',
'DIAGNOSE_ASTHMA':'health',
'DIAGNOSE_DIABETES':'health',
'DIAGNOSE_EPILEPSY':'health',
'LOCATION_PHARMACY':'health',
'BLOOD':'health',
'SYMPTOM_BREATHING':'health',
'DIAGNOSE_DIARRHEA':'health',
'DIAGNOSE_DEHYDRATION':'health',
'FEEL_HUNGER':'health',
'SYMPTOM_RASH':'health',
'SYMPTOM_ITCH':'health',
'SYMPTOM_CRAMP':'health',
'SYMPTOM_CRAMP_MENSTRUAL':'health',
'SYMPTOM_FATIGUE':'health',
'SYMPTOM_DIZZINESS':'health',
'SYMPTOM_NAUSEA':'health',
'MEDICAL_REMOVALOFBLOOD':'medicalmeasures',
'MEDICAL_VACCACINATION':'medicalmeasures',
'MEDICAL_NARCOSIS':'medicalmeasures',
'MEDICAL_PLASTER':'medicalmeasures',
'MEDICAL_INJECTION':'medicalmeasures',
'MEDICAL_BANDAGE':'medicalmeasures',
'MEDICAL_CAST':'medicalmeasures',
'MEDICAL_AMPUTAION':'medicalmeasures',
'MEDICINE':'medicalmeasures',
'MEDICAL_SUPPOSITORY':'medicalmeasures',
'PILL':'medicalmeasures',
'FLUID_DROP':'medicalmeasures',
'SYRUP':'medicalmeasures',
'FLUID_SPRAY':'medicalmeasures',
'FLUID_OINTMENT':'medicalmeasures',
'MEDICAL_XRAY':'medicalmeasures',
'MEDICAL_ULTRASONIC':'medicalmeasures',
'MEDICAL_OPERATION':'medicalmeasures',
'MEDICAL_STOOLSAMPLE':'medicalmeasures',
'MEDICAL_URINESAMPLE':'medicalmeasures',
'MEDICAL_SWAB':'medicalmeasures',
'MEDICAL_SPLINT':'medicalmeasures',
'MEDICAL_CRUTCH':'medicalmeasures',
'MEDICAL_DRESSING':'medicalmeasures',
'MEDICAL_DESINFECTANT':'medicalmeasures',
'NEWSPAPER':'media',
'TELEVISION':'media',
'RADIO':'media',
'INTERNET_CONNECTION':'media',
'COMPUTER':'media',
'BATTERY':'media',
'TELEPHONE':'media',
'CELLPHONE':'media',
'BED':'housing',
'BLANKET':'housing',
'DOOR':'housing',
'CUPBOARD':'housing',
'CHAIR':'housing',
'TABLE':'housing',
'APARTMENT':'housing',
'WALL':'housing',
'BOOK':'living',
'SHAMPOO':'hygiene',
'HANDKERCHIEF':'hygiene',
'TOILET':'hygiene',
'TOILET_PAPER':'hygiene',
'TOOTHBRUSH':'hygiene',
'TOOTHPASTE':'hygiene',
'WINDOW':'housing',
'ROOM':'housing',
'DRESS':'clothing',
'SKIRT':'clothing',
'COAT':'clothing',
'HEADSCARF':'clothing',
'SHOE':'clothing',
'GLOVE':'clothing',
'SOCK':'clothing',
'UNDERWEAR':'clothing',
'GREETING_EVENING':'politeness',
'GREETING_DEPARTURE':'politeness',
'REPLY_THANKS':'politeness',
'GIVE_OWN_NAME':'politeness',
'ASK_OTHERS_NAME':'politeness',
'GIVE_OWN_PROVENANCE':'politeness',
'FAMILY':'kin',
'PRESENT_HUSBAND':'politeness',
'CHILDREN':'kin',
'MOTHER':'kin',
'SUFFER_HUNGER':'basics',
'CHILD_HUNGRY':'basics',
'SUFFER_THIRST':'basics',
'AVAILABLE_Q':'basics',
'LOCATION_Q':'basics',
'TOILET_LOCATION_Q':'basics',
'NEED_SHOWER':'hygiene',
'SHOWER_LOCATION_Q':'basics',
'SANITARYPAD':'hygiene',
'DIAPER':'hygiene',
'NEED_MAKE_PHONECALL':'basics',
'PRAY_LOCATION_Q':'basics',
'PURCHASE_X_LOCATION_Q':'basics',
'LOCATION_X_Q':'basics',
'TIME_CLOCK_Q':'basics',
'NEED_SLEEP':'basics',
'SUBWAY_LOCATION_Q':'transport',
'NO_MONEY':'basics',
'SPEAK_X_Q':'basics',
'SPEAK_LITTLE_X':'basics',
'WRITE_DOWN_X_REQUEST':'basics',
'NO_UNDERSTAND':'basics',
'HELP_REQUEST':'basics',
'IGNORANCE':'basics',
'EVENT_Q':'basics',
'SUFFER_FREEZING':'sensations',
'EXPERIENCE_HAPPINESS':'basics',
'SUFFER_FEAR':'sensations',
'SUFFER_SADNESS':'sensations',
'EXPERIENCE_LIKING_ADDRESSEE':'sensations',
'DONT_WORRY':'politeness',
'NEED_APPOINTMENT':'basics',
'ROOM_NUMBER_N_LOCATION_Q':'basics',
'REGISTRATION_CENTRE_LOCATION_Q':'basics',
'MUST_WAIT':'basics',
'WAITING_TIME_DURATION_Q':'basics',
'1_DAY':'time',
'1_HOUR':'time',
'1_MONTH':'time',
'VERYSOON':'time',
'TOMORROW':'time',
'DAY_AFTER_TOMORROW':'time',
'NEXT_WEEK':'time',
'RETURN_SOON':'time',
'ONE':'basics',
'TWO':'basics',
'THREE':'basics',
'FOUR':'basics',
'FIVE':'basics',
'SIX':'basics',
'SEVEN':'basics',
'EIGHT':'basics',
'NINE':'basics',
'TEN':'basics',
'MONDAY':'time',
'TUESDAY':'time',
'WEDNESDAY':'time',
'THURSDAY':'time',
'FRIDAY':'time',
'SATURDAY':'time',
'SUNDAY':'time',
'JANUARY':'time',
'FEBRUARY':'time',
'MARCH':'time',
'APRIL':'time',
'MAY':'time',
'JUNE':'time',
'JULY':'time',
'AUGUST':'time',
'SEPTEMBER':'time',
'OCTOBER':'time',
'NOVEMBER':'time',
'DECEMBER':'time',
'NEED_DOCTOR':'medical',
'SUFFER_ICD10_R11':'medical',
'EXPERIENCE_ILLNESS':'medical',
'CHILD_ILL':'medical',
'PREGNANT':'medical',
'SUFFER_ICD10_T78.4':'medical',
'SUFFER_ICD10_H81':'medical',
'SUFFER_ICD10_E10':'medical',
'NEED_INSULIN':'medical',
'SUFFERED_RAPE':'crime',
'SUFFER_ICD10_R10':'medical',
'SUFFER_ICD10_R50':'medical',
'SUFFER_ICD10_R51':'medical',
'SUFFER_ICD10_R05':'medical',
'CHILD_SUFFER_ICD10_R7.0':'medical',
'FLU':'medical',
'DIARRHEA':'medical',
'ICD10_K59.0':'medical',
'ICD10_B73.3':'medical',
'ICD10_B53.3':'medical',
'ICD10_B85':'medical',
'MEAL_NOON':'food',
'MEAL_EVENING':'food',
'FOOD_HALAL_Q':'food',
'ALLERGY_AGAINST_X':'medical',
'PORK_MEAT':'food',
'POULTRY_MEAT':'food',
'NO_EAT_PORK':'food',
'SELF_VEGETARIAN':'food',
'SELF_VEGAN':'food',
'BREAD':'food',
'LEMONADE':'food',
'COFFEE':'food',
'TEA':'food',
'BEER':'food',
'FRUITS':'food',
'APPLE':'food',
'PEAR':'food',
'GRAPEFRUIT':'food',
'APRICOT':'food',
'POTATOE':'food',
'BEAN':'food',
'PEA':'food',
'CHICKPEA':'food',
'AUBERGINE':'food',
'CARROT':'food',
'TOMATO':'food',
'TURNIP':'food',
'FLOUR':'food',
'HONEY':'food',
'CHEESE':'food',
'QUARK':'food',
'PAPRIKA':'food',
'SAUCE':'food',
'BUTTER':'food',
'OIL':'food',
'CHEWING_GUM':'food',
'SPOON':'food',
'PLATE':'food',
'GLASS':'food',
'MUG':'food',
'TEAPOT':'food',
'LAMP':'housing',
'ELECTRICITY':'housing',
'BATHTUB':'housing',
'HOUSE':'housing'
}
|
Ringo Starr has talked about working with John Lennon on the album ‘John Lennon/Plastic Ono Band’.
‘John Lennon/Plastic Ono Band’ was recorded following The Beatles‘ break-up in 1970 and released later that year. Starr played drums on the album, one of the three core musicians who formed the Plastic Ono Band collective alongside Lennon and Klaus Voormann, the German artist who played bass.
Yoko Ono recently paid tribute to Ringo Starr by dubbing the drummer “the most influential Beatle” as Starr was inducted into the Rock And Roll Hall Of Fame in April. “No one is probably going to believe it but he was the most influential Beatle,” said Ono.
Meanwhile, Ringo Starr recently complained that people are “only interested in the eight years I was in The Beatles”. |
Interaction of indole-3-acetic acid with horseradish peroxidase as a potential anticancer agent: from docking to molecular dynamics simulation Abstract The oxidation process, catalyzed by the peroxidase enzymes, occurs in all domains of life to detoxify the hydrogen peroxide toxicity. The most well-known, applicable and vastly studied member of the peroxidases family is horseradish peroxidase (HRP), especially the isoenzyme C (HRP C). HRP (primarily HRP C) is commercially available and applicable in biotechnology and diagnosis. Recently, a novel application of HRP has been introduced in cancer therapy as the combination of HRP with indole-3-acetic acid (IAA). The anticancer activity of HRP/IAA complex is through oxidation of IAA by HRP in hypoxic tumor condition, which leads to apoptosis and cancerous cell death. However, the molecular interaction of HRP/IAA has not been elucidated. Identifying the interaction of IAA with HRP would provide a better insight into its function and applications. In this study, molecular docking and molecular dynamics (MD) simulation were applied to determine the molecular interaction of the IAA/HRP complex. The docking study represented that IAA bound at the exposed heme edge of the HRP enzyme, and the IAA entrance to the enzyme was situated at the carboxymethyl side-chain of the selected structure. Our computational results showed the HRP/IAA complex structure stability. While hydrogen bond formation with ARG38 and HIS42 stabilized the substrate, hydrophobic interactions with Phe68, Gly69, Leu138, Pro139, Pro141 and Phe179 contributed to IAA/HRP complex stability. The results can help to better understand peroxidase enzyme activity and would pave the way for future development of new therapeutics with improved anticancer efficacy. Communicated by Ramaswamy H. Sarma |
/**
* In case of static password or HOTP yubikey returns HID codes which needs to be mapped to Android KeyEvent codes
* Using KeyEvent codes KeyCharacterMap returns charecters
* @param data part of payload from NDEF message that contains only otp data
* NOTE: Format of initial payload: first byte of payload is 0x04, then uri prefix and than data that contains otp
* @param keyboardLayout provide your own ScanCode to Character mapping
* or use the one that provided by library in KeyboardLayoutProvider.getKeyboardLayout()
* @return value without Uri prefix
*/
private static String parseKeyboardCodes(byte[] data, KeyboardLayout keyboardLayout) {
StringBuilder sb = new StringBuilder();
for (byte hid_key_code : data) {
if (hid_key_code == 0) {
break;
}
boolean shiftOn = (0x80 & hid_key_code) == 0x80;
int code = 0x7f & hid_key_code;
sb.append((char)keyboardLayout.get(code, shiftOn));
}
return sb.toString();
} |
Which Games Sold The Most, In Australia, During 2008?
Seen America's. Seen Japan's. Seen Britain's. Now let's see which ten games sold the most copies in...Australia. Anyone expecting a break from the Nintendothon, don't bother, but the list isn't entirely devoid of surprises.
It's Wii, Wii, Wii at both the top and bottom of the list (Big Beach Sports? Really?), but in the middle? Yes, that's the PS3 version of Grand Theft Auto IV outselling the 360 one.
As for Guitar Hero, Rock Band, Call of Duty or anything else made by anyone else that's not Nintendo...sorry. Not your time, not your place. |
Full house of fears: evidence that people high in attachment anxiety are more accurate in detecting deceit. Lying is deep-rooted in our nature, as over 90% of all people lie. Laypeople, however, do only slightly better than chance when detecting lies and deceptions. Recently, attachment anxiety was linked with people's hypervigilance toward threat-related cues. Accordingly, we tested whether attachment anxiety predicts people's ability to detect deceit and to play poker-a game that is based on players' ability to detect cheating. In Study 1, 202 participants watched a series of interpersonal interactions that comprised subtle clues to the honesty or dishonesty of the speakers. In Study 2, 58 participants watched clips in which such cues were absent. Participants were asked to decide whether the main characters were honest or dishonest. In Study 3, we asked 35 semiprofessional poker players to participate in a poker tournament, and then we predicted the amount of money won during the game. Results indicated that attachment anxiety, but not other types of anxiety, predicted more accurate detection of deceitful statements (Studies 1-2) and a greater amount of money won during a game of poker (Study 3). Results are discussed in relation to the possible adaptive functions of certain personality characteristics, such as attachment anxiety, often viewed as undesirable. |
INCA (Peru) Study: Impact of NonInvasive Cardiac Magnetic Resonance Assessment in the Developing World Background Advanced cardiac imaging permits optimal targeting of cardiac treatment but needs to be faster, cheaper, and easier for global delivery. We aimed to pilot rapid cardiac magnetic resonance (CMR) with contrast in a developing nation, embedding it within clinical care along with training and mentoring. Methods and Results A crosssectional study of CMR delivery and clinical impact assessment performed 20162017 in an upper middleincome country. An International partnership (clinicians in Peru and collaborators from the United Kingdom, United States, Brazil, and Colombia) developed and tested a 15minute CMR protocol in the United Kingdom, for cardiac volumes, function and scar, and delivered it with reporting combined with training, education and mentoring in 2 centers in the capital city, Lima, Peru, 100 patients referred by local doctors from 6 centers. Management changes related to the CMR were reviewed at 12 months. Onehundred scans were conducted in 98 patients with no complications. Final diagnoses were cardiomyopathy (hypertrophic, 26%; dilated, 22%; ischemic, 15%) and 12 other pathologies including tumors, congenital heart disease, iron overload, amyloidosis, genetic syndromes, vasculitis, thrombi, and valve disease. Scan cost was $150 USD, and the average scan duration was 18±7 minutes. Findings impacted management in 56% of patients, including previously unsuspected diagnoses in 19% and therapeutic management changes in 37%. Conclusions Advanced cardiac diagnostics, here CMR with contrast, is possible using existing infrastructure in the developing world in 18 minutes for $150, resulting in important changes in patient care. C ardiovascular disease (CVD) is the leading cause of death in developed countries, accounting for 17.9 million deaths per year causing 30% of global deaths. 1 However, CVD disease and death rates are highest in low-and middle-income countries, despite there being a lower burden of classical risk factors. For example, in Peru, CVD affects 3.2 million (16% of the adult population), leading to a significant loss of well-being, estimated at 281 829 Disability Adjusted Life Years. The agestandardized death rate is 142 per 100 000 inhabitants, resulting in productivity losses of 0.69 bn USD and health costs of 0.24 bn USD, representing 2.1% of total health spending, which the country can ill afford. 5,6 A key aspect of cardiovascular care is diagnostic testing. Without this, clinical care is inefficient at best, inaccurate or mistaken at worst. The hierarchy of diagnostic testing is used optimally by employing guidance and care pathways, taking into account local resource availability and cost constraints. Cardiac magnetic resonance (CMR) imaging is an emerging imaging technique with the capacity to transform cardiology in an analogous way to the impact of brain MRI in neurology. 7,8 Multiple different techniques are available using CMR (function, scar, perfusion, flow, mapping, angiography), delivering valuable clinical insights with the potential of a high impact. However, these varied techniques may make it slow (typically 45 minutes), expensive and complex, potentially out of reach for most inhabitants in the developing world. In Peru, although MRI scanners are available for other indications, just 2 public hospitals undertake CMR, performing a total of 6 scans per week (%1 scan per million population per year), at a cost of $400 to $800. This compares to the United Kingdom where there are %60 UK centers performing %1000 scans per million population per year, at a cost of $640. 12 However, we contend that CMR could be made faster, cheaper, and easier, which would increase its utility in the developing world. The core incremental diagnostic utility of CMR over other methods is left ventricular (LV) function and late gadolinium enhancement (LGE) imaging for scar. Previously, we implemented an ultrafast CMR protocol without contrast in Thailand for the relatively uncommon indication of iron assessment in a specific patient cohort (Thalassemia). Scanning was performed in 8 minutes, reducing costs 4-fold. 13 The purpose of the INCA (Impact of Non-Invasive CMR Assessment) Peru study was to assess the potential of faster, cheaper, easier rapid contrast-enhanced CMR program for wider cardiology indications in an upper middle-income country. Methods The imaging data, analytic methods and study materials of this study are all anonymized and are available to other researchers upon (reasonable) request. Rapid CMR Protocol Development The protocol (cardiac volumes, function and scar via LGE) was developed and assessed in 45 participants (33 patients with cardiomyopathy, 12 healthy volunteers) at Heart Hospital, London, using a 1.5T scanner (Avanto, SIEMENS Healthineers, Erlangen Germany), Figure 1. All volunteers had no history of cardiovascular disease, hypertension or diabetes mellitus, and were not on regular medications. The protocol included: 1. Localizers, pilot 2 chamber, 3 slice short axis stack, and a transverse dark blood single shot fast spin echo stack for anatomic evaluation. 2. Volume and cardiac structure assessment: four, two, three chamber and aortic valve segmented k-space cine acquisitions. 3. Hand-contrast injection: gadolinium-based contrast agent Gadoterate meglumine (Dotarem. Guerbet S.A France, 0.1 mmol/kg). 4. Short axis cine stack (7-mm slice thickness, 3 mm interslice gap). 5. Scar imaging: repeating cine views as needed, followed by an optional sequence to determine the optimal inversion Clinical Perspective What Is New? Cardiac Magnetic Resonance imaging improves the care of cardiac patients in high income countries by improving diagnostic accuracy and better targeting expensive treatments. It is, however, too expensive for developing countries. We developed and tested a rapid cardiac magnetic resonance protocol focusing on just measuring cardiac volumes and scar for deployment on existing scanners in the developing world. What Are the Clinical Implications? In a trial deployment at 2 sites in a capital city of an upper middle-income country, rapid cardiac magnetic resonance could be delivered faster, cheaper, and easier than is conventionally done. The rapid Cardiac Magnetic Resonance protocol was embedded in clinical care with training and education, which resulted in important and frequent patient management changes that appear beneficial for both patients and the healthcare system. The impression is that resource scarcity is not a justification for the absence of key diagnostic tests in the developing world. This protocol is focused on the essential: cardiac volumes and scar. It can be implemented in a capital city with existing infrastructure, and it has a major impact for sustainability if it is delivered with quality, education and training. time and segmented k-space late gadolinium enhancement acquisitions in multiple planes with phase sensitive and magnitude reconstructions. Protocol Implementation We CMR Complications Major complications were predefined as death, resuscitation, complication requiring admission for at least 1 night. Mild complications were defined as any others clinically significant events, such as dyspnea, chest pain, and allergic reactions without shock). CMR Analysis Images were analyzed using dedicated software (cvi42, Circle Cardiovascular Imaging, Calgary Canada). Scans were reported Image Quality Images that did not answer the clinical question were considered poor; those with artifact but still interpretable as moderate, and images with optimal quality allowing definitive assessment of the clinical question were graded as good. Patient Outcomes After 12 months, management changes related to CMR results were reviewed in consultation with general cardiologists or other physicians (hematologists) in the 6 referral centers. A change of patient management was reported if CMR resulted in new diagnosis (eg cardiac amyloidosis diagnosed in a hypertrophic cardiomyopathy patient) medication changes (eg suspension of secondary prevention drugs after detection of myocarditis and nonischemic disease; commencement of anticoagulation for thrombus) interventional treatment (eg coronary artery bypass grafting) or new testing (eg, ordering invasive angiography, biopsy). Many of these resulted in hospital admission/discharge (eg a large apical thrombus in a patient with previous RCA infarction). Cost Evaluation Reference CMR costs in Peru are difficult to determine given the complex healthcare structure (public-coverage of 84% of the population in three sectors; private covering 4% with multiple insurance companies; 12% uncovered). We took as reference the average cost from the 2 public and 2 private hospitals offering CMR in Lima. 14,15 To determine the cost of rapid CMR, we included the following parameters: hospital charges, contrast and cannula costs, and physician, nurse and technologist fees, but not opportunity cost (eg, displaced MRI scanning for other organs) or training costs. Statistical Analysis Absolute numbers and percentages expressed as meanAESD if they had a normal distribution, and range, if not. Normal distribution formally tested using Shapiro-Wilk test. Association of two categorical variables was analyzed by Chi-square test. To predict the response of two categories and ordinal level dependent variables with a set of categorical independent variable, binary and ordinal logistic regression analysis were used, respectively. Values of P<0.05 were considered statistically significant. Results The baseline patient characteristics are shown in Table 1. Scanning Contrast was administered in 95% of cases with 5 being evaluated for cardiac iron so not requiring contrast. The contrast dose was 0.1 mmol/kg (0.2 mL/kg). All studies were performed without major complication. There was 1 minor complication (panic attack). Good image quality was reported in 91% of cases, moderate in 7%. Images were non-diagnostic in 2% and therefore graded as poor. In reality, the image quality was good but the LGE was so abnormal that we repeated scanning to confirm that contrast had actually been administered and that the cases were indeed cardiac amyloidosis (which they were). Image quality of exam was not influenced by age (trend assessed across 4 age categories: <44, 45-59, 60-74 and >75 year-old, P>0.05). However, impact on patient care (new diagnosis and change of medication) was more likely with age (P<0.05), Table 2. Extra-Cardiac Findings Incidental extra-cardiac findings were found in 21% of cases but were mainly not incrementally important compared with existing clinical knowledge-2% were judged new important findings (example: malignant liver mass). The most common findings were: dilated great vessels (13%) and lung parenchymal abnormalities (3%). Cardiac Findings and Impact CMR directly impacted clinical management at 12 months in 56% of patients, either by revealing an unsuspected new diagnosis (19%) and/or leading to a change in management with therapeutic consequences (37%), Table 3. In 5%, a change in management was suggested but not delivered due to access barriers (cardiac surgery or device therapy)-we did not count these patients in the 56% (ie rapid CMR could have changed care in 61%). Figure 3 shows the impact of the rapid CMR on patient management by the 3 main indications: non-ischemic cardiomyopathy (hypertrophic cardiomyopathy, dilated cardiomyopathy); ischemic cardiomyopathy, and other. Rapid CMR satisfied all imaging needs in 89% of patients. In 7%, where CMR was the first imaging technique performed, no further non-invasive imaging was needed. Figures 4 and 5 show 2 cases demonstrating the impact of CMR on the management. Although non-blinded, CMR did not miss any diagnoses initially found by echocardiography. Cost The rapid CMR strategy was 3 to 5 times less expensive than current CMR exams in Peru: costing 62%, 75%, and 81% less compared with existing public/private (for public) or private (for insurer) fees. Discussion Cardiac MRI is a key diagnostic imaging technology that helps target often expensive treatments, but uptake is limited in middle-income countries because, although cardiac enabled systems are present, barriers exist to delivery. This may result in the poor targeting of already rationed treatments such as drugs, surgery, stenting, and device therapy. We did 3 things to make CMR suitable for major centers in developing world healthcare systems, using Peru as the exemplar: firstly, created national/international support structures for a service at the political and healthcare system levels; secondly, created an education/mentoring system for both those delivering the technology and referrers;and thirdly, by focusing on the core utility of CMR, volumes and scar imaging, we made CMR faster, cheaper, and easier. We delivered high quality CMR at 2 (capital city) sites in 2 parts of the healthcare system on patients from 10 clinicians at 6 sites that was 2 to 3 times faster and 3 to 5 times cheaper than usual and changed the care in 56% of subjects scanned. The morbidity and mortality from cardiovascular disease in the developing world is high. 4 Healthcare systems need to be cost appropriate, accessible, and capable of making a diagnosis, implementing appropriate therapy and monitoring that therapy. In cardiology, the key diagnostic tests are the ECG, echocardiogram, angiography, cardiac CT, and cardiac MRI, typically embedded in a framework of education, training, and guidelines/protocols for their delivery and quality control. In middle-income countries, this hierarchy is typically truncated with absence of the more expensive, technically demanding tests such as CMR. Echocardiogram is still the first imaging technique option for cardiac patients as it is portable, inexpensive, and recommended by international guidelines. 16,17 This exam remains the first line exam to assess cardiac structure, but this is not sufficient to get critical information on causation, risk, therapeutic strategy, and reversibility across a wide range of diseases. CMR tissue characterization using the late gadolinium enhancement technique adds major value in many clinical scenarios, providing information that cannot be obtained any other way (myocarditis, 18 amyloidosis, 19 takotsubo, small apical thrombi, sarcoid 20 for example), risk stratification 21 and prognostic information and is becoming essential in several key clinical scenarios (chest pain, troponin rise, normal coronaries, to confirm/refute history of ischemic scarring, some cardiomyopathies). With forthcoming developments in cardiac personalized care, an appreciation of inflammation and scarring is likely to prove essential to arbitrate novel therapies. With expensive technology, usage patterns should reflect the ratio of capital costs to labor costs that the payee can bear: so, an MRI scanner operational day in the United Kingdom may be 12 hours, 6 days a week but 20 hours, 7 days a week in Argentina, for example. Modern MRI scanners can all do cardiac MRI with the addition of ECG gating and proper sequences, the basic examples being supplied routinely with scanner purchase. However, CMR is perceived as slow, expensive, and complex, not only for imager to analyze and interpret, but also to the clinician "gatekeepers", who decide whom to refer. We had previously shown that CMR could be performed quickly in Thailand 13 for a single indication, evaluation of cardiac iron, in a cohort where the clinical value for mortality and morbidity of this measurement is established. 25 However, in this first pilot project, an approach was taken focusing on technology delivery with less investment in education and mentoring. In Peru, a broader landscape was emphasized in a generalize cohort of patients, where the evaluation of cardiac function, volumes and scar are important diagnostic criteria. Some less apparent aspects of the study merit attention. Firstly, CMR has new technologies (sequences) that make scanning easier-for example motion corrected (MOCO) late enhancement sequences. We wanted to install these in Peru (and test their incremental utility), but the industry waiver form stipulations made these onerous for the local hospitals to sign (eg, all liability for sequence use was laid on the hospital not the manufacturer). Secondly, cultural aspects are important: we were able to scan on Saturday and Sunday at both sites, and both cardiologists and radiologists worked together, but at 1 site, a 1 hour lunch-break was mandated. Thirdly, we could have delivered 15-minute scanning, focusing on core utility, but the clinical disease stopped this-we had decided not to do complex imaging particularly congenital heart disease, but clinician demand meant that we had several such cases, increasing scan-length (but also adding to yield). At one stage, we dropped the aortic valve short axis view-but we soon realized that this was a step too far as there are high levels of congenital (bicuspid) and acquired (stenosis/regurgitation) aortic valve disease in clinical care. Fourthly, we were not expecting the high clinical utility we encountered. Focusing on 1 familiar disease, hypertrophic cardiomyopathy is illuminating: the hypertrophic cardiomyopathy referred in Peru was far more extreme than in the United Kingdom (more hypertrophy, more syndromic, more scar, and more obstruction). We believe that this reflects not a different disease profile, but the test scarcity-only the most concerning patients were referred by clinicians. The images from this rapid CMR had routine and conventional volumes, mass and ejection fraction quantified. Other measurements are also possible. There is indeed 26,27 and the myocardial contraction fraction (stroke volume over myocardial volume) is an underused indexless measure that imports more prognostic information than the ejection fraction in many clinical scenarios. 28,29 The cine images acquired in the rapid protocol are conventional and may also be used for more advanced analysis even without the use of contrast. However, specialist software requirements and the incomplete development of clinical utilities means this was outside the key priorities for this study. Development over time would help its implementation and it would make CMR even easier to implement. The clinical utility found in Peru of 56% having changed care after CMR is somewhat less than demonstrated in international registries, as European/US registries have reported that CMR changed care in 61.8% of patients. 30,31 However, we would have reached these levels in our study by including the 5% of patients in which a change in management was appropriate but not possible due to access barriers. This study was structured to result in a sustainable service, however, this requires multiple aspects: Local champions: The project conducted as a Peruvian fellow (KM) came to learn CMR in the United Kingdom and wanted to translate CMR to Peru-her PhD title is "the $100, 15-minute CMR scan". Political support: was from the UK Overseas Development Office via the embassy to one of five the sectors which administers healthcare in Peru: EsSalud, with scanning in both the public and private sector. We also were careful to include software solutions so analysis was not perceived as a barrier. Education/training in depth: Four Peruvians came to the United Kingdom to train (a cardiologist, radiologist, technologist, and physicist). We implemented a 2-day training course for cardiologists and radiologists with a specific technologist track-including lectures delivered by technologists. Partnership: all scanning conducted in partnership (day 1 mainly overseas technologists; day 2 mainly Peruvian); slots for attendance at scanning were available to clinicians and all reporting made by overseas level 3 reporters (expertise is known to be important 32 ) but within a level 1 reporting course as a training exercise in partnership, and subsequent free 1year membership to an international society. Quality: The rapid CMR protocol was tested in advance using freely available video conferencing software. We used low-dose gadolinium (0.1 mmol/L per kg) for cost and so the bloodpool was not bright at the time of LGE imaging. 33 The CMR studies were conducted within a safe environment, with only one minor complication which was a panic attack. The images of the protocol answered the clinical question in 91% of studies-we used criteria for quality based not directly on artifact, but on ability of the scan to answer the clinical questions. Follow-up: the 12-month outcome adjudication was to ensure outcomes were not just technical but clinical (care changed in 56%), to make sure there were not major added investigations triggered (91% of patients) and to engender engagement. Since the project ended, a clinical service at the public hospital is continuing, 2 more public hospitals in Lima have adopted the rapid CMR protocol (1 of them had never done CMR before), 2 of them initially scanned 4 to 6 patients per week and included 2 research programs (1 on HIV cardiomyopathy, and the other on the effect of chronic altitude exposure during gestation). Study Limitations This protocol did not include advanced magnetic resonance sequences (there was no mapping, no perfusion, and flow only for selected cases). Perfusion CMR is a safe, accurate, and cost-efficient test for inducible ischemia 34 with superior or similar performance compared with SPECT 35 or invasive Fractional flow reserve 36 However, as alternatives and delivery are complex, it is outside the scope of rapid CMR with currently available infrastructure, although this may change with the latest sequences and developments over time. 37 Finally, outcomes were clinical change in management rather than objective gold standards (not easily available when CMR is often that standard). The study is described as assessing CMR in the developing world, but it is perhaps better described as in the capital city/leading centers in the developing world, and we have not unequivocally demonstrated sustainability. Conclusions The advanced diagnostic technique cardiac MRI can be made faster, cheaper, and easier for deployment in the developing world. This can be done safely with high diagnostic quality on existing infrastructure and it changes patients care in most of cases. Finally, this rapid CMR protocol includes an educational and support package in order to ensure sustainability. |
Reportedly, Saudi Arabia has finally agreed to offer Pakistan a US$6 billion support package to overcome its prevailing precarious current account deficit crisis. According to the details the Kingdom will transfer US$3 billion directly to Pakistan, while another one-year deferred payment facility of up to US$3 billion for oil import will be made available. This arrangement will be in place for three years, which will be reviewed thereafter.
During the election campaign and even after taking oath as Prime Minister of Pakistan, Imran khan has been expressing reluctance in approaching International Monetary Fund (IMF). Ever since coming to power, Khan has been trying to solicit financial support from friendly countries including China, Saudi Arabia and the United Arab Emirates, but his efforts hardly yielded any result. From the day one, Finance Minister Asad Umar has been saying that Pakistan needs more than US$12 billion to keep imports and foreign debt servicing at sustainable level.
Negotiating funding with IMF was not deemed easy because of a host of reasons that include: 1) it will be Pakistan’s 13th agreement since late 1980s, 2) the United States enjoying significant control over IMF Board has emerged an opponent of lending to Pakistan and 3) Pakistan has been put at an odd position due to ongoing proxy wars in South Asia, Middle East and North Africa (MENA). The US keeps on singing ‘do more mantra’, Pakistan does not enjoy cordial relationship with three of its immediate neighbors; Afghanistan, India and Iran. It is evident to all and sundry that string will be attached to any assistance be it from IMF, United States, Saudi Arabia and China. In such a scenario, taking small bit from all the lenders may not be a bad idea.
All the political parties have initiated a debate, why should Pakistan approach IMF? Some of the critics say, “It may be true that Saudi package is handsome, but won’t address Pakistan’ all the woes. Having signed a deal with Saudi Arabia has reduced pressure on Pakistan substantially. It will also help it to negotiate a smaller facility with IMF with less stringent conditions”.
South Asia’s second-largest economy is facing balance-of-payments crisis due to bad policies of the previous two governments. These policies have resulted in dismal FDI inflow in the recent years, paltry exports and ever rising imports. Further woes have been added due to the hike in international crude oil prices. Though, remittances are on the rise but fall too short to bridge ever widening current account deficit.
Pakistan’s foreign exchange reserves have plunged to an alarming level, hinting towards virtual default if no immediate solution is found. Since friendly countries are not willing to give the desired amount, the incumbent government has no option but to go to the IMF, seeking help of the lender of last resort can reduce the pain. Shrinking reserves has also put Pak rupee under pressure, adding to the woes in two ways, increasing cost of imported items particularly energy products and eroding competitiveness of ‘Made in Pakistan’ Products. Therefore, the country has to boost its reserves to keep imports and debt servicing at sustainable levels.
Does Pakistan have other options?
Without mincing world Pakistan does not have too many options. Though, China was considered a savior but there is a negative propaganda going on “CPEC is another East India Company”. Therefore, both the countries have to be more careful. The US is opposing extension of funding to Pakistan for paying off Chinese loans. Whatever may be the reality, putting all the eggs in one basket is not advisable.
Would IMF be willing to extend yet another loan?
Let one point be very clear that IMF is in the business of lending money to the countries in distress, and it is always on the search for clients. Pakistan has been a regular and tested client that has not defaulted, though have been borrowing to pay off the loans in the past. Pakistan has enormous undiscovered/unexploited resources and a bit of lending can keep the lifeline. However, our own weaknesses, give opportunities to IMF to add the shackles.
What would a next bailout look like?
Reportedly, Pakistan needs more than $12 billion, Umar said in August. That would be higher than the biggest IMF package extended to Pakistan until now. The IMF typically provides three-year loan programs under its Extended Fund Facility to help countries facing balance-of-payments crises. The loans are often tied to economic targets that the government has to meet, for example curbing fiscal or current-account deficits, trimming inflation or allowing more flexibility in currency policy.
Till what time Pakistan keep on borrowing?
In 2013, the government of Nawaz Sharif signed an assistance program of US$6.6 billion disbursed over 36 months. During that time, the government mostly fell short of broadening the tax base or privatizing money-losing state-owned companies. Nevertheless, the economy rebounded after the IMF program, with growth accelerating, stocks soaring, the currency stabilizing and foreign-exchange reserves tripling to a record. All of that was undone last year as higher oil prices and the growth boom pushed up demand for imports, the current-account gap widened and reserves started to slide. To add to the insult PML-N government kept on borrowing from open market at much higher interest rates.
It is believed that IMF will extend the assistance program. However, it is yet to be seen how Khan’s government contains budget and current deficits. It has to boost exports, contain import, attract FDI and channelize remittances though the formal banking system. |
ANYONE who has eczema is no stranger to the constant dry skin and itching.
Chances are you'll try anything just to stop it flaring up - but it turns out a "magic cure" could already be in your kitchen cupboard.
Sunflower oil can help keep the symptoms of eczema at bay and some studies have even found it has anti-inflammatory properties, which is good for keeping any redness and swelling at bay.
When it comes to treating eczema, the most important thing is to keep the skin moisturised.
This can help prevent the skin becoming dry, flaky, irritated and itchy.
"The most important part of treating eczema is moisturising," Dr Anton Alexandroff, spokesman for the British Association of Dermatologists, told The Sun Online.
"Sometimes you'll need something else, like a topical steroid, but usually you just need a good moisturiser.
"Sunflower oil is a moisturiser and is actually included in some moisturisers.
"There are some research papers that suggest some patients saw some anti-inflammatory results [when using sunflower oil] but I've not seen any clinical studies that prove it's better than other moisturisers.
"But it's fine to try and see if it works for people."
Most children suffer eczema at some point, but the condition usually clears as they grow up, Dr Alexandroff explained.
But adults that suffer the condition tend to have it far worse - the condition is recurring and usually worse than childhood eczema.
FIND OUT MORE What is eczema, what are the signs and causes and how can you treat the painful skin condition?
That's why keeping the skin moist is vital.
If you've tried using sunflower oil but you've not seen any results, Dr Alexandroff suggests using ointments.
"Ideally people should be using ointments, but some people find that too greasy for the skin," he added.
"In that case you can use more water-based moisturisers like lotions or creams, but you'll have to use it more often.
"It's also important not to soaps and shower gels - you should wash with moisturisers.
"Soap and shower gel just dry out the skin and cause eczema to flare-up.
"Bubble baths are also really bad for eczema, but on the other hand bath oils and additives are really good." |
def index(self, instance, vocab, sentences):
raise NotImplementedError |
<gh_stars>10-100
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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.
*/
#include <tencentcloud/sqlserver/v20180328/model/ModifyBackupMigrationRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Sqlserver::V20180328::Model;
using namespace std;
ModifyBackupMigrationRequest::ModifyBackupMigrationRequest() :
m_instanceIdHasBeenSet(false),
m_backupMigrationIdHasBeenSet(false),
m_migrationNameHasBeenSet(false),
m_recoveryTypeHasBeenSet(false),
m_uploadTypeHasBeenSet(false),
m_backupFilesHasBeenSet(false)
{
}
string ModifyBackupMigrationRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_instanceIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_instanceId.c_str(), allocator).Move(), allocator);
}
if (m_backupMigrationIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupMigrationId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_backupMigrationId.c_str(), allocator).Move(), allocator);
}
if (m_migrationNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MigrationName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_migrationName.c_str(), allocator).Move(), allocator);
}
if (m_recoveryTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RecoveryType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_recoveryType.c_str(), allocator).Move(), allocator);
}
if (m_uploadTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UploadType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_uploadType.c_str(), allocator).Move(), allocator);
}
if (m_backupFilesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupFiles";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_backupFiles.begin(); itr != m_backupFiles.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string ModifyBackupMigrationRequest::GetInstanceId() const
{
return m_instanceId;
}
void ModifyBackupMigrationRequest::SetInstanceId(const string& _instanceId)
{
m_instanceId = _instanceId;
m_instanceIdHasBeenSet = true;
}
bool ModifyBackupMigrationRequest::InstanceIdHasBeenSet() const
{
return m_instanceIdHasBeenSet;
}
string ModifyBackupMigrationRequest::GetBackupMigrationId() const
{
return m_backupMigrationId;
}
void ModifyBackupMigrationRequest::SetBackupMigrationId(const string& _backupMigrationId)
{
m_backupMigrationId = _backupMigrationId;
m_backupMigrationIdHasBeenSet = true;
}
bool ModifyBackupMigrationRequest::BackupMigrationIdHasBeenSet() const
{
return m_backupMigrationIdHasBeenSet;
}
string ModifyBackupMigrationRequest::GetMigrationName() const
{
return m_migrationName;
}
void ModifyBackupMigrationRequest::SetMigrationName(const string& _migrationName)
{
m_migrationName = _migrationName;
m_migrationNameHasBeenSet = true;
}
bool ModifyBackupMigrationRequest::MigrationNameHasBeenSet() const
{
return m_migrationNameHasBeenSet;
}
string ModifyBackupMigrationRequest::GetRecoveryType() const
{
return m_recoveryType;
}
void ModifyBackupMigrationRequest::SetRecoveryType(const string& _recoveryType)
{
m_recoveryType = _recoveryType;
m_recoveryTypeHasBeenSet = true;
}
bool ModifyBackupMigrationRequest::RecoveryTypeHasBeenSet() const
{
return m_recoveryTypeHasBeenSet;
}
string ModifyBackupMigrationRequest::GetUploadType() const
{
return m_uploadType;
}
void ModifyBackupMigrationRequest::SetUploadType(const string& _uploadType)
{
m_uploadType = _uploadType;
m_uploadTypeHasBeenSet = true;
}
bool ModifyBackupMigrationRequest::UploadTypeHasBeenSet() const
{
return m_uploadTypeHasBeenSet;
}
vector<string> ModifyBackupMigrationRequest::GetBackupFiles() const
{
return m_backupFiles;
}
void ModifyBackupMigrationRequest::SetBackupFiles(const vector<string>& _backupFiles)
{
m_backupFiles = _backupFiles;
m_backupFilesHasBeenSet = true;
}
bool ModifyBackupMigrationRequest::BackupFilesHasBeenSet() const
{
return m_backupFilesHasBeenSet;
}
|
<gh_stars>0
package com.groupon.seleniumgridextras.config;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class JvmParamsTest {
private Config config;
@Before
public void setUp() throws Exception {
config = new Config();
config.addGridExtrasJvmOptions("http.proxyHost", "www.google.com");
config.addGridExtrasJvmOptions("fakeBool", true);
config.addGridExtrasJvmOptions("http.proxyPort", 5555);
config.addGridJvmOptions("http.proxyHost", "www.bing.com");
config.addGridJvmOptions("fakeBool", false);
config.addGridJvmOptions("http.proxyPort", 9999);
}
@Test
public void testGridExtrasJvmParams() throws Exception {
assertEquals("-Dhttp.proxyPort=5555 -DfakeBool=true -Dhttp.proxyHost=www.google.com ", config.getGridExtrasJvmOptions());
}
@Test
public void testGridJvmParams() throws Exception {
assertEquals("-Dhttp.proxyPort=9999 -DfakeBool=false -Dhttp.proxyHost=www.bing.com ", config.getGridJvmOptions());
}
@Test
public void testEmptyJvmParams() throws Exception {
Config emptyConfig = new Config();
assertEquals("", emptyConfig.getGridExtrasJvmOptions());
assertEquals("", emptyConfig.getGridJvmOptions());
}
}
|
<reponame>calblueprint/nbjc
import prisma from 'utils/prisma';
import { OrganizationProject } from '@prisma/client';
import Joi, { ValidationError } from 'joi';
import { NextApiRequest, NextApiResponse } from 'next';
import OrgProjSchema from 'interfaces/orgProjects';
import CreateError, { MethodNotAllowed } from 'utils/error';
/**
* Update an OrgProject by the given ID and fields and return the updated OrgProject
* @param id - the ID of the OrgProject
* @param body - the fields of the OrgProject to update
*/
export const updateOrgProject = async (
id: string,
body: OrganizationProject
): Promise<OrganizationProject | null> => {
const { error, value } = OrgProjSchema.validate(body);
if (error) {
throw error;
}
const data = value as OrganizationProject;
const updatedProj = await prisma.organizationProject.update({
where: { id: Number(id) },
data,
});
return updatedProj;
};
/**
* Delete the OrgProject by the given ID
* @param id - the ID of the OrgProject
*/
export const deleteOrgProject = async (
id: string
): Promise<OrganizationProject | null> => {
const deletedProj = await prisma.organizationProject.delete({
where: { id: Number(id) },
});
return deletedProj;
};
export default async (
req: NextApiRequest,
res: NextApiResponse
): Promise<void> => {
const orgId = req.query.id as string;
// No GET requests being exposed.
if (Joi.number().validate(orgId).error) {
return CreateError(400, `ID ${orgId} is not a number`, res);
}
if (req.method === 'PATCH') {
try {
const response = await updateOrgProject(orgId, req.body);
return res.json(response);
} catch (err) {
if (err instanceof ValidationError) {
return CreateError(400, err.message, res);
}
return CreateError(500, `Failed to patch org project ${orgId}`, res);
}
}
if (req.method === 'DELETE') {
try {
const deletedProj = await deleteOrgProject(orgId);
return res.json(deletedProj);
} catch (err) {
return CreateError(500, `Failed to delete org project ${orgId}`, res);
}
}
return MethodNotAllowed(req.method, res);
};
|
(Beirut) – Houthi forces apparently used unnecessary lethal force against demonstrators in Taizz and al-Turbba on March 24, 2015. Houthi authorities should immediately investigate the incidents, in which at least 7 people were killed and more than 83 others were injured. Houthi commanders should make sure their forces comply with international law enforcement standards when dealing with demonstrations.
In Taizz, Yemen’s third largest city, Houthi fighters and government security forces fired without warning on a crowd of at least 1,000 protesters, killing or fatally injuring at least 4 and wounding more than 70 others, witnesses told Human Rights Watch. A similarly mixed force, including snipers, opened fire on about 100 demonstrators in al-Turbba, a town 70 kilometers from Taizz, killing 3 and wounding at least 10 others.
“Yemen’s spiraling conflict is causing a calamitous breakdown in law and order,” said Joe Stork, deputy Middle East and North Africa director. “Security forces in control, whatever side they are on, have responsibilities to uphold and protect people’s rights and to take action against their members who commit abuses.”
In January, Ansar Allah, a Zaidi Shia group from the far northern part of the country known as the Houthis, ousted the government of President Abdu Rabu Mansour Hadi, sparking widespread protests. On February 8, Yemen’s interim interior minister, citing “the exceptional circumstances” prevailing in Yemen, ordered police in Sanaa, the capital, to prevent all unauthorized demonstrations. This indefinite ban on public protests violates the right to peaceful assembly. Since January, Ansar Allah, and security and police forces have arbitrarily arrested and increasingly used excessive force against protesters and journalists covering demonstrations.
Daily protests calling for Ansar Allah to cease using Taizz as a base for military operations on southern Yemen started on March 22.
An activist, Ola al-Aghbari, 23, told Human Rights Watch that starting at about 11:30 a.m. on March 24, at least 1,000 had peacefully gathered in front of the Arab Bank main branch in Taizz. About half-an-hour later, al-Aghbari saw dozens of armed men, some in traditional Houthi clothing bearing Houthi slogans, and others in uniforms of the Yemeni Special Security Forces (SSF), surround the crowd and open fire without any warning or order to disperse.
She told Human Rights Watch that she was not hit but that she went immediately to Ibn Sina Hospital: “The hospital was full of people suffering from gunshot wounds. I saw one man with a bullet through his neck, another woman, a first aid volunteer, got shrapnel in her left eye. One man caught a bullet that tore through his intestines … he died the next day.”
Another witness to the protest told Human Rights Watch that some protesters began throwing rocks and Molotov cocktails, but only after the security forces opened fire.
Muhammad Adnan, a volunteer who helped transport wounded protesters to hospitals on his motorbike, told Human Rights Watch: “I transported 10 gunshot victims, including a man with a terrible gunshot wound to his head, another man with a bullet that went through his knee, and two other men shot in their hands.”
The statistics officer at Taizz’s Ibn Sina Hospital said that the hospital had received 73 patients with gunshot wounds. Mithaq Turboosh, a nurse at the hospital, said that most of the gunshot wound patients he and his colleagues received had wounds in their arms and legs, but that at least 10 had been shot in the neck, chest, or head. Ambulances transferred most of the seriously wounded to other hospitals after they had been stabilized.
Medical authorities reported that four protesters died, each at one of four major hospitals in the city. Following the March 24 incident, the governor of Taizz announced his resignation.
In al-Turbba, men believed to be Houthis and others in SSF uniforms opened fire on a crowd of peaceful protesters from an Ansar Allah office, killing 3 and wounding 10. Abu Bakr Abdullah al-Asbahi, 42, a teacher who was at the protest, told Human Rights Watch that at least 100 people assembled by 10:30 a.m. and began marching peacefully from al-Nasr square to a military checkpoint to protest the arrival in town of about 150 members of the SSF.
Al-Asbahi said that as they approached the checkpoint near the entrance to the town, about 20 armed men bearing Houthi slogans withdrew to the Ansar Allah office about 20 meters away. Then, without warning, unidentified gunmen opened fire on the protesters from the office’s second-floor windows and from the street in front of the office’s door. Three men were fatally shot, said Al-Asbahi and another activist who attended their funerals, and at least 10 others who survived had bullet and shrapnel wounds. A fourth man died when a car driven by an SSF officer collided with his motorcycle, perhaps accidentally, Al-Asbahi said.
Ansar Allah, the SSF, and all other forces involved in policing demonstrations and other law enforcement measures in Yemen should abide at all times with relevant international human rights standards, notably the United Nations Basic Principles on the Use of Force and Firearms by Law Enforcement Officials.
The Basic Principles provide that all security forces shall as far as possible use nonviolent means before resorting to force. Whenever the lawful use of force is unavoidable, the authorities must use restraint and act in proportion to the seriousness of the offense. Law enforcement officials should not use firearms against people except in self-defense or to protect others against the imminent threat of death or serious injury.
As Ansar Allah forces advanced into Aden and other southern areas of Yemen, on March 26 a Saudi-led coalition began a campaign of airstrikes against them, hitting Sanaa, Saada, Hodaida, Taizz, Lahj, al-Dale`a, and Aden. The ground fighting and airstrikes are governed by international humanitarian law, or the laws of war. However, even during armed conflict, international human rights law remains in effect. Parties in effective control of areas should apply human rights law to law enforcement situations.
“Houthi and other commanders engaged in the fighting in Yemen should recognize that they may be held accountable for unlawful killings and other abuses their forces commit,” Stork said. “Troops need to understand that when dealing with protests, they need to apply the rules of law enforcement.” |
def load(pseudo_name, symb):
if os.path.isfile(pseudo_name):
return parse_cp2k.load(pseudo_name, symb)
name, suffix = _format_pseudo_name(pseudo_name)
pseudomod = ALIAS[name]
symb = ''.join(i for i in symb if i.isalpha())
p = parse_cp2k.load(os.path.join(os.path.dirname(__file__), pseudomod), symb, suffix)
return p |
One of the first legal challenges to Donald Trump’s ban on bump stocks, the $200 devices that can enable semi-automatic rifles to fire almost as quickly as machine guns, has been rejected by a federal court. Owners of the devices have until March 26 to dispose of the accessories after U.S. District Judge Dabney Friedrich in Washington rejected arguments that the rule was rushed through or improperly issued. The Firearms Policy Coalition, one of the plaintiffs in the lawsuit, denounced the ruling and vowed to appeal to reign in “a rogue and growing Executive Branch.” In October 2017, a single gunman killed 58 people and injured more than 800 others in Las Vegas with the assistance of a bump stock attachment. |
/**
* This abstracts the {@link Session}, and {@link YbridPlayer}
* in a way suitable for Android.
*/
public final class AndroidPlayer implements Closeable {
private static final @NotNull URI STREAM_URI = URI.create("https://democast.ybrid.io/adaptive-demo");
private final @NotNull HandlerThread handlerThread;
private final @NotNull Handler handler;
private @Nullable Session session;
private @Nullable MetadataConsumer metadataConsumer;
private MediaController player;
{
// Create a Thread to run the player in. This is required
// as Android does not allow network activity on the main thread.
handlerThread = new HandlerThread("Android Ybrid Player Handler"); //NON-NLS
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
switchURI(STREAM_URI);
}
public void switchURI(@NotNull URI uri) {
final @NotNull Session nextSession;
// Create a MediaEndpoint, and a Session from it.
try {
final @NotNull MediaEndpoint mediaEndpoint = new MediaEndpoint(uri);
final @NotNull LocaleList list = LocaleList.getAdjustedDefault();
final @NotNull List<Locale.LanguageRange> languages = new ArrayList<>(list.size());
for (int i = 0; i < list.size(); i++) {
// Use a weight of 1.0 for the default language, and 0.5 for every other language.
//noinspection MagicNumber
languages.add(new Locale.LanguageRange(list.get(i).toLanguageTag(), i == 0 ? 1 : 0.5));
}
mediaEndpoint.setAcceptedLanguages(languages);
nextSession = mediaEndpoint.createSession();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
// Connect the session.
handler.post(() -> {
try {
stopOnSameThread();
session = nextSession;
session.connect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
});
}
public synchronized void setMetadataConsumer(@NotNull MetadataConsumer metadataConsumer) {
this.metadataConsumer = metadataConsumer;
if (player != null)
player.setMetadataConsumer(metadataConsumer);
}
/**
* Start Playback.
*/
public void play() {
handler.post(() -> {
synchronized (AndroidPlayer.this) {
if (player != null)
return;
player = new YbridPlayer(Objects.requireNonNull(session));
if (metadataConsumer != null)
player.setMetadataConsumer(metadataConsumer);
player.play();
}
});
}
private synchronized void stopOnSameThread() {
if (player != null)
player.stop();
player = null;
}
/**
* Stop playback.
*/
public void stop() {
if (player != null) {
handler.post(this::stopOnSameThread);
}
}
/**
* Swap current item.
*/
public void swap() {
handler.post(() -> player.swapItem(SwapMode.END2END));
}
@Override
public void close() throws IOException {
handlerThread.quitSafely();
}
} |
The Making of Unknown Heroes : National System of Learning, OEM, and Taiwan s IT Industry. ( draft only ) This paper discusses two related issues regarding the development of Taiwans IT industry. The first question is how Taiwan has achieved it technology capability in the IT industry and to become one of the major players in the world IT market. The second is why Taiwans manufacturing products are, and continue to be, sold under the brands of world major firms without their own identities, even though Taiwanese firms has gained the technology capability almost at the front edge as the leading firms? By utilizing the model of the national system of learning, this paper argues that the national system of learning in Taiwan has characteristics of states involvements, overseas Chinese networks, learning firms, and OEM/ODM relationships. These factors together enhanced the learning capability of the firms and synergized to a system that generated technology learning and innovations. However, I also argue that the dependence of the firms upon the state and the close relationship with the leading firms through OEM/ODM model in consequence held up their incentives to engage into frontier innovation activities and confront directly with the OEM buyers in the market. In the end, the Taiwanese firms have increased investment into the Chinese market enormously in order to enlarge their production scale and to lower their production cost. The benefit of this out-ward investment is the increase of the organizational capability in building global logistic capacity rather than involving the deepening of the ability technology innovation. |
Modeling and Simulation of Hydraulic System of the Tower-Belt Based on Power Bond Graph Based on the working principle of the TC2400 Tower-belt, the power bond graph of the hoisting mechanism hydraulic system was established under the listing loads condition. The dynamic equations of the system were deduced according to the logical relations amongst the established power bond graph variables. Based on the dynamic equations of the system, the systems simulation model was established using the block diagram of SIMULINK. By setting the simulation parameters of the hydraulic system, this simulation was carried out, and the performance curve of the hydraulic system was obtained. The simulation results checked the validity of the simulation method, proved the feasibility to build model and simulate the hydraulic system of the large construction machinery by combining power bond graph with SIMULINK, and provided a theoretical direction for improving and optimizing the system. |
By City News Service
Plans to build an NFL-caliber stadium in Inglewood are moving at lightning speed and could win approval from city leaders as soon as a Feb. 24 council meeting, it was reported Friday.
Election officials confirmed Thursday there are more than enough valid signatures to put the project on the June ballot, but the Inglewood City Council also has the option to approve the plan for an 80,000-seat venue outright, a course that appears likely, the Los Angeles Times reported.
Approval is required to amend existing plans for the 238-acre Hollywood Park site to include the football stadium. Skipping a public vote could save the city time and money — about $110,000 for an election, officials told The Times.
Inglewood Mayor James T. Butts Jr. said he’s waiting to hear the results of economic and environmental reports before making a decision. Those reports are expected to be presented at the council meeting.
“I’m leaning toward whatever would get us down the road the fastest,” Butts said.
Hollywood Park Land Co. — the development company that includes St. Louis Rams owner Stan Kroenke — said it hoped to break ground on the project by the end of the year. Officials close to the project have expressed hope that the stadium plan is a first step toward bringing back an NFL team to the Los Angeles area.
The developers proposed zoning changes for the stadium through a ballot initiative, which would allow them to skip lengthy reviews that civic and environmental activists say protect surrounding neighborhoods. City officials said environmental studies were performed on the land in 2009, before the stadium was added to the project.
Last month, organizers filed 22,183 signatures, twice as many as needed to put the initiative on the ballot. The Los Angeles County registrar’s office verified 11,490 signatures, surpassing the 9,000 needed to move forward, Inglewood City Clerk Yvonne Horton said. |
Policy, Office or Votes? How Political Parties in Western Europe Make Hard Decisions Edited by Wolfgang C. Mller and Kaare Strm. Cambridge: Cambridge University Press, 1999. 319p. $59.95 cloth, $21.95 paper. This book is about the motivations of political actors. Many of the most commonly used models of party competition and government formation are grounded in explicit assumptions about the motivations of party strategists. These tend to assume one of three basic and interrelated motivationsthe desire to fulfill policy objectives, the desire to control the perquisites of office, and the desire to maximize votes. While recognizing that living and breathing people may be driven by any or all of these motivations, among others, and that these may interact with each other in complex ways, most theorists ground their models in assumptions of policy-seeking OR office-seeking OR vote-maximizing by key political decision makers. Indeed this distinction between motivational assumptions is one of the most common ways to classify models of party competition. In part the grounding of models in a single motivational assumption is for the sake of analytical tractability; in part it is because the heuristic insights made possible by these approaches are enhanced if the models are kept simple and their relationship to core assumptions is kept straightforward. |
Data Analytics for Low Voltage Electrical Grids At the consumer level in the electrical grid, the increase in distributed power generation from renewable energy resources creates operational challenges for the DSOs. Nowadays, grid data is only used for billing purposes. Intelligent management tools can facilitate enhanced control of the power system, where the first step is the ability to monitor the grid state in near-real-time. Therefore, the concepts of smart grids and Internet of Things can enable future enhancements via the application of smart analytics. This paper introduces a use case for low voltage grid observability. The proposal involves a state estimation algorithm (DSSE) that aims to eliminate errors in the received meter data and provide an estimate of the actual grid state by replacing missing or insufficient data for the DSSE by pseudo-measurements acquired from historical data. A state of the art of historical and near-real-time analytics techniques is further presented. Based on the proposed study model and the survey, the team near-real-time is defined. The proposal concludes with an evaluation of the different analytical methods and a subsequent set of recommendations best suited for low voltage grid observability. |
Unlike Kyrie Irving's view of the planet Earth, Celtics forward Al Horford wants to make sure that Boston's offense doesn't fall flat after it's amazing 16-game win streak.
Al Horford says the C's need to pick it up on the offensive end. pic.twitter.com/VtCzNTwPDX — theScore (@theScore) November 24, 2017
The Celtics' offense remained in the bottom half of the league d espite their month-long run , with their three-point shooting percentage ranked No. 17.
While Irving (22.5 PPG, 47.0 FG%) is having a great year, he simply can't carry the team by himself. Much of their struggles are coming off of the bench, and Marcus Smart, Terry Rozier, and Aron Baynes are not playing up to their potential.
.@BostonSportsBSJ: The Celtics have the worst shooting bench backcourt in the NBA over 19 games https://t.co/H0nbr1caqc pic.twitter.com/PjH0QmGRqj — BostonSportsJournal (@BostonSportsBSJ) November 24, 2017
Now, with the weight of the steak off their shoulders, the Celtics must get back to basics and relearn how to function as an offense. Despite rallying from behind several times during the streak, having success long term with that come-from-behind is not sustainable. |
Effect of Reservoirs on Transport Properties of Doped Structures It is generally accepted that electronic devices can be treated as open systems because they exchange both carriers and energy with connected contacts. Therefore, a theoretical description of transport properties of such systems requires some methods developed for analysis of nonequilibrium states in the classical or quantum phase space of position and momentum variables. Such possibility is created by the kinetic method based on the integro-differential equation in the form : |
Version 3 of Personal Software Inspector (PSI), Secunia's free program updater, has been released with a much simplified user interface, enabling less technically astute users to keep their Windows applications up to date as well.
According to Secunia, the automatic updater has also been enhanced. PSI is now able to keep programs from more than 3,000 companies up to date, though, as before, PSI only cares about updates which fix security vulnerabilities. Version 3 also includes additional translations, including German. The software checks the user's computer for outdated program versions known to contain vulnerabilities and either installs updates or provides links to download them.
Secunia has reintroduced a number of functions found in previous versions which had been missing from February's beta version. The new version includes up to date programs in its list of detected applications again and there is now an indicator that shows installation progress.
PSI is free for private use. Secunia also offers a commercial alternative for businesses in the form of its Corporate Software Inspector, which has extended administration options.
Now reveal your missing patches! |
Please be sure to read our Community Guidelines before getting started.
Meet and greet. What should we know about you?
This forum is for those who are trying to locate other service members, or find information about specific individuals, events, etc.
This is the place to ask questions about the forum. It\'s a great place to ask others about the workings of the forums and various communities within.
All times are GMT. The time now is 04:54 AM. |
/* Draw coordinate for last point. */
static void drawCoord(pdwCtx h, float ax, float ay) {
if (h->level == 0)
return;
if (h->path.cnt >= 2) {
float x;
float y;
char buf[15];
Vector s = makeVec(h->path.bx - ax, h->path.by - ay);
Vector t = makeVec(h->path.cx - h->path.bx, h->path.cy - h->path.by);
Vector u = makeVec(s.x + t.x, s.y + t.y);
Vector v;
v.x = -u.y * TO_EM(5.5);
v.y = u.x * TO_EM(5.5);
if (h->flags & PDW_FLIP_TICS) {
v.x = -v.x;
v.y = -v.y;
}
x = (float)RND(1, h->path.bx + v.x);
y = (float)RND(1, h->path.by + v.y);
stmPrint(h, STM_TICS,
"%.2f %.2f m\n"
"%.2f %.2f l\n",
h->path.bx, h->path.by,
x, y);
sprintf(buf, "%.0f %.0f", h->path.bx, h->path.by);
if (v.x < 0 && v.y >= 0)
x -= textLength(h, buf);
else if (v.x <= 0 && v.y < 0) {
x -= textLength(h, buf);
y -= textBaseline(h);
} else if (v.x > 0 && v.y <= 0)
y -= textBaseline(h);
textSetPos(h, x, y);
textShow(h, buf);
}
savePt(h, ax, ay);
} |
A couple of days ago, Bethesda officially confirmed the next installment in the Doom franchise in the form of DOOM Eternal. The game was announced for multiple consoles which includes the Nintendo Switch, although given that the Switch isn’t as powerful in terms of hardware compared to other consoles, we’re sure some are wondering how the game holds up.
Speaking to Eurogamer, the game’s executive producer Marty Stratton revealed that the game will run at 30fps on the Switch. Eurogamer asked Stratton to clarify this as prior to this, it was said that the game would run at 60fps, but Stratton has since confirmed that for the Switch, it will run at 30fps, while other consoles like the PS4 and Xbox One will run at 60fps, or at least that’s the goal.
Stratton also highlights how the 2016 port of DOOM onto the Switch ran at 30fps, so if you were fine with those frame rates then DOOM Eternal shouldn’t be a problem either. As for a launch date, it seems that no specifics have been mentioned yet as it appears that the game is still being worked on.
Filed in Gaming. Read more about Bethesda, Doom, Nintendo and Nintendo Switch. |
Handbook of health, health care, and the health professions tributors from several countries. The dictionary contains about five hundred entries, many of them associated with the related disciplines of microbiology, genetics, demography and biostatistics. Proceeding from 'acceptable risk' to ' zoonosis' the list of terms is rather idiosyncratic, but the definitions are lively and there are several biographical sketches of interest. While there is no direct reference to mental disorder, several of the items carry obvious implications for psychological medicine, as, for example, 'Biological Plausibility: The criterion that an observed, presumably or putatively causal association fits previously existing biological or medical knowledge. This judgement should be used cautiously since it could impede new knowledge that does not fit existing ideas'. |
def xor_pixels(self) -> None:
for i in range(self.m):
for j in range(self.n):
xor_operand_1 = self.Kc[j] if i%2==1 else self.rotate180(self.Kc[j])
xor_operand_2 = self.Kr[i] if j%2==0 else self.rotate180(self.Kr[i])
self.new_rgb_array[i,j,0] = self.new_rgb_array[i,j,0] ^ xor_operand_1 ^ xor_operand_2
self.new_rgb_array[i,j,1] = self.new_rgb_array[i,j,1] ^ xor_operand_1 ^ xor_operand_2
self.new_rgb_array[i,j,2] = self.new_rgb_array[i,j,2] ^ xor_operand_1 ^ xor_operand_2 |
A/N: I promise you that I will finish this one. I'm taking a different approach here. I'm trying to be more professional about the execution. I have the entire plot already planned out and I even drew up an outline. This time I'm chiseling my story out of a block of marble instead of building it up brick by brick like I did with my last two stories. What went wrong with those is that I ran out of bricks.
Anyways, please give feedback. There's going to be longer gaps in between chapters here because I'm going to be careful with my writing and read it over multiple times before pushing out the chapter. I'm shooting for quality over quantity here.
"It's a real turn off how little she's enjoying it." –BushDidNyne11
"She clearly hates her job. You'd think she'd have earned enough money by now to quit." –LilTitt
"Her moans are so fake. Only got off because of mute button." –SelfAdmittedPervert48
"She's got an amazing body, but she's just not sexy." –TimminyTimTimTim
"Tip: Her solo vids are SOOO much better." –ExpertPornCritic04
Annabeth stopped scrolling through the comments and closed her laptop. She slid on a pair of shoes and grabbed her keys.
"You're right," she muttered to herself. "You're all one hundred percent right." She opened the door of her apartment and then descended the staircase.
In actuality, her videos got very positive feedback overall. They get very few negative comments. Annabeth just takes note of them due to the fact that she agrees with them so much.
She got to the bottom of the staircase and left the building. She started walking down the sidewalk until she found a pub she'd never been to before and entered the building. There were about twenty people there, all talking, drinking, and having a good time.
Annabeth sat down at the bar and looked around. The bartender was at the other end. It was a guy who looked around twenty-one, same age as Annabeth. He had shaggy black hair and looked to be pretty fit. When he turned around she saw he had sea-green eyes.
He spotted her and immediately filled a cup with beer and walked down to her end of the bar. He stopped and held out his hand. "I.D.?"
Annabeth handed him her driver's license and he examined it.
"Annabeth? That's a pretty name," he said whilst handing her back her license and the cup of beer.
"Thanks, but I haven't ordered anything yet," said Annabeth.
"I know," said the bartender. "It's on the house." He pointed to a sign on the back wall that read, New Faces Special: Never Been Here Before? Come Up To The Bar And Get A Free Beer
"Couldn't I just come back when there's another bartender and get another free beer?" she asked.
"There is no other bartender," he said.
"That seems like a risky business move for your employers."
"Well I own the place, so I think my 'employer' can trust me to not walk out on him," he said with a sarcastic smile.
"You're a bit young to be owning your own business," Annabeth said.
"It was my dad's. He died a couple years ago and I inherited it."
"I'm sorry."
"I've come to terms with it. Running the bar was an easy way to take my mind off it. Good coping strategy."
A waitress walked up to the bar and sat a tray down. "Two beers and a scotch on the rocks."
The bartender got the drinks and put them on the tray for the waitress to deliver.
"You couldn't have been twenty one when he died though," said Annabeth.
"Nineteen," he said. "In New York you only have to be eighteen to legally serve alcohol."
"Interesting."
"So what do you do?"
Annabeth tensed. "Uh, I'm in between jobs at the moment," she lied.
"You looking for anything in particular? We have openings here."
Annabeth hesitated and took a drink from her beer just as another waiter walked up to a bar. "Two martinis," he said.
"You got it, G-Man," said the bartender.
Annabeth watched as he quickly made the drinks and gave them to "G-Man".
"You're pretty good at that," said Annabeth, eager to change the subject.
"Well I've had two and a half years of practice," said the bartender with that same sarcastic smile.
"So do you get a lot of crazy customers around here?"
"Not many. We do get a few every now and again, though. But that's the business."
"Hey, bartender!" a guy from the other end of the bar called out whilst holding up his empty cup. The bartender walked down there and served him another beer.
"Would you like a refill too?" he asked when he got back down to Annabeth's end of the bar.
Annabeth looked at the clock on the back wall. "Bourbon," she said.
The bartender drew a glass and poured the drink before handing it to Annabeth.
The two continued to converse for a bit, stopping every once in awhile when another customer needed a drink. Finally, Annabeth finished her bourbon.
"Want another refill?" said the barman.
Annabeth glanced at the clock. "No, I should be going. How much do I owe you?"
"Six thirty-six," he said. Annabeth gave him a ten and he walked to the cash register then came back and handed her her change and receipt. "Do you have a ride?"
"I only live a few blocks down," she said.
"Well it was nice talking with you, Annabeth," he said.
"You too, uh. . ." she paused, realizing she didn't know his name.
"Percy," he filled in for her.
"Well seeya, Percy," she said.
"Hope to see you around here again sometime."
She smiled at him and gave a quick wave before leaving the bar.
Three days later, Annabeth was just getting dressed and showered after a filming. She exited the bathroom and walked out onto the set where the camera crew and the director were. Her "co worker" exited his bathroom fully dressed and smiled at Annabeth.
"Want to go get a drink?" he asked her.
"No thanks," she said. She almost always got asked out after they finished filming. She'd accepted the first couple of times but she'd learned that it was always best to say no.
"Why not? Come on, it's just one drink."
"I don't date costars."
"We had great chemistry out there. There are plenty more good times like that ahead."
"I disagree. Our relationship begins and ends in front of that camera."
Annabeth walked up to the director. "We finished?" she asked.
"Yeah," said the director. "You're free to go. Expect your check in the mail sometime this week."
"Thanks," she said. She left the building and made straight toward her car. The car kicked into ignition and she drove off.
She'd intended on driving home but she saw a building with a sign that read "The Trident" and parked there. She got of her car and pushed open the door of the pub.
Annabeth sat down and spotted the bartender, Percy, farther along down the bar. He spotted her and gave a wave. After finishing up with his customer, he made his way toward her.
"She's back!" he said with triumph in his voice.
"Missed me?" she said with a smirk.
He lowered his voice a tiny bit. "All of my customers are so boring. You proved to be an exception."
"Interesting. Because this is my first time visiting the same bar twice."
"I guess we're both special, then. So, what'll you be having?"
Annabeth started coming by his bar more often. Percy never knew when she'd show up, but when she did it definitely brightened his day quite a bit. He always made it a point to try and strike up a conversation with lone customers, but most of them never had much to say. And those who did didn't care about what Percy had to say. So it was a nice change of pace to chat with someone who did an equal amount of talking and listening.
His good friend Grover worked at the bar as a waiter, but he was always kept busy either serving customers or washing cups so conversing with him during work hours never happened.
"You know what I noticed?" Annabeth said.
"What's that?" Percy said.
"In the movies the bartender is always wiping the counter whenever talking to a customer, yet you never do that."
"Ah, you mean like this," he said and drew a rag from under the counter before mockingly wiping the counter with it and staring straight at Annabeth. "You like it better like this?" he said jokingly.
"Oh definitely," she said sarcastically. "Much better."
"But it's not always like that," he said and stopped wiping the table. "Sometimes you'll get your mysterious bartender type who's out to talk as little as possible." He drew a glass mug and leaned against the back counter, staring intently at it as he wiped it with the rag. "And he'll never even take a glance in your direction when he talks to you."
Annabeth gave a small chuckle.
"Need a refill over here!" called out a customer from the other end of the bar. Percy set the rag and cup down and went to fill the customer's cup.
When Percy got back to Annabeth's end of the bar he saw a drunk man of around forty hitting on her.
"I'm not interested," she said.
"Just let me take you back to my place and show you I know my way around a mattress," said the drunk who put his free hand on her shoulder. She immediately smacked it away. "Oho, she's a feisty one!"
"Back off," Percy said. "She said she's not interested."
"What do you know? She's already mine, even if she don't know it yet." he said and wrapped his arm around her neck. Percy slid over the counter and shoved the guy back.
"Oh you just want the girl for yourself!" yelled the drunk who attempted to shove Percy, but he caught his arms and pushed him back hard enough for him to fall to the ground. The entire bar was silent now and all attention was on them.
The drunk slowly and unsteadily stood and turned toward Percy before throwing his now empty glass, which missed by a foot and hit the back wall and shattered.
"Alright, get the hell out of my bar," Percy said.
"Whatever, your beer's shit anyway," the drunk man said and stumbled out of the bar.
"Show's over people," Percy said loudly and returned to his side of the counter.
"Thanks," Annabeth said.
"It's not the first time I've had to do that," he said with his back turned because he was cleaning up the broken glass from the cup.
"You know, to be completely honest I wasn't even sure if you had legs," she joked.
Percy finished throwing the glass shards away and stood across from Annabeth again. "Oh yeah?" he said with a smirk.
"Every time I've seen you you've been behind that counter. For all I knew there was just a metal rod with a couple of wheels down there."
"Well it is now confirmed: Percy Jackson does indeed have legs."
Annabeth smiled. "Glad that's off my conscience. I can finally sleep at night."
"You're looking kind of empty there," Percy said while pointing at her cup.
"Yeah, I'm calling this my last. What do I owe you?"
"Don't worry about it, it's on me."
"It's on you?"
"Yeah. Bill's covered. Call it an apology from the pub for the public disruption."
"Well alright. Guess I'm heading off, then."
"Seeya. Walk home safe, Annabeth." |
ASSESSMENT OF INDICATORS OF ECONOMIC EFFICIENCY OF TRANSPORT LOGISTICS In the modern economy, the problems associated with transport logistics (TL) have become important. The strategic goal of the TS is to increase the level of competitiveness of firms in the market, as a result of which, TL is that special direction of the economy, which will contribute to the growth of its level of efficiency and lead to high commercial results. A consistent assessment of the effectiveness of the functioning of the enterprise's TL is a guide to its activities, since the results of the assessment help managers to identify complex components of the system and make optimal management decisions. All this leads to the need to develop assessment mechanisms that will help to calculate the level and degree of efficiency of the TL functioning, because modern assessment methods do not make it possible to identify the integral level of TL efficiency based on the TL efficiency levels. Consequently, the development of a systematic assessment of the effectiveness of TL, based on identifying the levels of efficiency of subsystems, plays a major role in finding its place in the market. A systematic approach to assessing the effectiveness of TL functioning is confirmed by a logistic approach to their management, as well as the properties they own. The significance of the research is confirmed by the fact that the development and improvement of methods for assessing the effectiveness of THB processes in a firm contributes to the implementation of specific use of theoretical provisions in the activities of commercial entities of the Republic of Azerbaijan. |
import { EventEmitter } from 'events';
import SDKDriver from '../../../lib/sdkdriver/src';
import LocalParticipantDriver from './localparticipant';
import { ParticipantSID } from './participant';
import RemoteParticipantDriver from './remoteparticipant';
const { difference } = require('../../../../lib/util');
/**
* A {@link RoomSID} is a 34-character string starting with "RM"
* that uniquely identifies a {@link Room}.
* @type string
* @typedef RoomSID
*/
type RoomSID = string;
/**
* {@link Room} driver.
* @classdesc A {@link RoomDriver} manages the execution of the
* corresponding {@link Room}'s methods in the browser and
* re-emits itsevents.
* @extends EventEmitter
* @property {LocalParticipantDriver} localParticipant
* @property {string} name
* @property {Map<ParticipantSID, RemoteParticipantDriver>} participants
* @property {RoomSID} sid
* @property {string} state
* @fires RoomDriver#disconnected
* @fires RoomDriver#participantConnected
* @fires RoomDriver#participantDisconnected
* @fires RoomDriver#recordingStarted
* @fires RoomDriver#recordingStopped
* @fires RoomDriver#trackDisabled
* @fires RoomDriver#trackEnabled
* @fires RoomDriver#trackMessage
* @fires RoomDriver#trackStarted
* @fires RoomDriver#trackSubscribed
* @fires RoomDriver#trackUnsubscribed
*/
export default class RoomDriver extends EventEmitter {
private readonly _resourceId: string;
private readonly _sdkDriver: SDKDriver;
readonly localParticipant: LocalParticipantDriver;
readonly name: string;
readonly participants: Map<ParticipantSID, RemoteParticipantDriver>;
readonly sid: RoomSID;
state: string;
/**
* Constructor.
* @param {SDKDriver} sdkDriver
* @param {object} serializedRoom
*/
constructor(sdkDriver: SDKDriver, serializedRoom: any) {
super();
this.localParticipant = new LocalParticipantDriver(sdkDriver, serializedRoom.localParticipant);
this.name = serializedRoom.name;
this.participants = new Map();
this.sid = serializedRoom.sid;
this._resourceId = serializedRoom._resourceId;
this._sdkDriver = sdkDriver;
this._update(serializedRoom);
sdkDriver.on('event', (data: any) => {
const { type, source, args } = data;
if (source._resourceId !== this._resourceId) {
return;
}
switch (type) {
case 'disconnected':
this._reemitDisconnected(source, args);
break;
case 'participantConnected':
this._reemitParticipantConnected(source, args);
break;
case 'participantDisconnected':
this._reemitParticipantDisconnected(source, args);
break;
case 'recordingStarted':
this._reemitRecordingStarted(source);
break;
case 'recordingStopped':
this._reemitRecordingStopped(source);
break;
case 'trackAdded':
this._reemitTrackAdded(source, args);
break;
case 'trackDisabled':
this._reemitTrackDisabled(source, args);
break;
case 'trackEnabled':
this._reemitTrackEnabled(source, args);
break;
case 'trackMessage':
this._reemitTrackMessage(source, args);
break;
case 'trackRemoved':
this._reemitTrackRemoved(source, args);
break;
case 'trackStarted':
this._reemitTrackStarted(source, args);
break;
case 'trackSubscribed':
this._reemitTrackSubscribed(source, args);
break;
case 'trackUnsubscribed':
this._reemitTrackUnsubscribed(source, args);
break;
}
});
}
/**
* Re-emit the "disconnected" event from the browser.
* @private
* @param {object} source
* @param {Array<*>} args
* @returns {void}
*/
private _reemitDisconnected(source: any, args: any): void {
this._update(source);
const [, serializedError] = args;
let error: any = null;
if (serializedError) {
error = new Error(serializedError.message);
error.code = serializedError.code;
}
this.emit('disconnected', this, error);
}
/**
* Re-emit the "participantConnected" event from the browser.
* @private
* @param {object} source
* @param {Array<*>} args
* @returns {void}
*/
private _reemitParticipantConnected(source: any, args: any): void {
this._update(source);
const serializedParticipant: any = args[0];
this.emit('participantConnected', this.participants.get(serializedParticipant.sid));
}
/**
* Re-emit the "participantConnected" event from the browser.
* @private
* @param {object} source
* @param {Array<*>} args
* @returns {void}
*/
private _reemitParticipantDisconnected(source: any, args: any): void {
const serializedParticipant: any = args[0];
const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid);
this._update(source);
this.emit('participantDisconnected', participant);
}
/**
* Re-emit the "recordingStarted" event from the browser.
* @private
* @param {object} source
* @returns {void}
*/
private _reemitRecordingStarted(source: any): void {
this._update(source);
this.emit('recordingStarted');
}
/**
* Re-emit the "recordingStopped" event from the browser.
* @private
* @param {object} source
* @returns {void}
*/
private _reemitRecordingStopped(source: any): void {
this._update(source);
this.emit('recordingStopped');
}
/**
* Re-emit the "trackAdded" event from the browser.
* @private
* @param {object} source
* @param {Array<*>} args
* @returns {void}
*/
private _reemitTrackAdded(source: any, args: any): void {
this._update(source);
const [ serializedTrack, serializedParticipant ] = args;
const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid);
if (participant) {
this.emit('trackAdded', participant.tracks.get(serializedTrack.id), participant);
}
}
/**
* Re-emit the "trackDisabled" event from the browser.
* @private
* @param {object} source
* @param {Array<*>} args
* @returns {void}
*/
private _reemitTrackDisabled(source: any, args: any): void {
this._update(source);
const [ serializedTrack, serializedParticipant ] = args;
const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid);
if (participant) {
this.emit('trackDisabled', participant.tracks.get(serializedTrack.id), participant);
}
}
/**
* Re-emit the "trackEnabled" event from the browser.
* @private
* @param {object} source
* @param {Array<*>} args
* @returns {void}
*/
private _reemitTrackEnabled(source: any, args: any): void {
this._update(source);
const [ serializedTrack, serializedParticipant ] = args;
const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid);
if (participant) {
this.emit('trackEnabled', participant.tracks.get(serializedTrack.id), participant);
}
}
/**
* Re-emit the "trackMessage" event from the browser.
* @private
* @param {object} source
* @param {Array<*>} args
* @returns {void}
*/
private _reemitTrackMessage(source: any, args: any): void {
this._update(source);
const [ data, serializedTrack, serializedParticipant ] = args;
const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid);
if (participant) {
this.emit('trackMessage', data, participant.tracks.get(serializedTrack.id), participant);
}
}
/**
* Re-emit the "trackRemoved" event from the browser.
* @private
* @param {object} source
* @param {Array<*>} args
* @returns {void}
*/
private _reemitTrackRemoved(source: any, args: any): void {
this._update(source);
const [ serializedTrack, serializedParticipant ] = args;
const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid);
if (participant) {
this.emit('trackRemoved', participant.getRemovedTrack(serializedTrack.id), participant);
}
}
/**
* Re-emit the "trackStarted" event from the browser.
* @private
* @param {object} source
* @param {Array<*>} args
* @returns {void}
*/
private _reemitTrackStarted(source: any, args: any): void {
this._update(source);
const [ serializedTrack, serializedParticipant ] = args;
const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid);
if (participant) {
this.emit('trackStarted', participant.tracks.get(serializedTrack.id), participant);
}
}
/**
* Re-emit the "trackSubscribed" event from the browser.
* @private
* @param {object} source
* @param {Array<*>} args
* @returns {void}
*/
private _reemitTrackSubscribed(source: any, args: any): void {
this._update(source);
const [ serializedTrack, serializedParticipant ] = args;
const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid);
if (participant) {
this.emit('trackSubscribed', participant.tracks.get(serializedTrack.id), participant);
}
}
/**
* Re-emit the "trackUnsubscribed" event from the browser.
* @private
* @param {object} source
* @param {Array<*>} args
* @returns {void}
*/
private _reemitTrackUnsubscribed(source: any, args: any): void {
this._update(source);
const [ serializedTrack, serializedParticipant ] = args;
const participant: RemoteParticipantDriver | undefined = this.participants.get(serializedParticipant.sid);
if (participant) {
this.emit('trackUnsubscribed', participant.getRemovedTrack(serializedTrack.id), participant);
}
}
/**
* Update the {@link RoomDriver}'s properties.
* @param {object} serializedRoom
* @returns {void}
*/
private _update(serializedRoom: any): void {
const { participants, state } = serializedRoom;
this.state = state;
const serializedParticipants: Map<ParticipantSID, any> = new Map(participants.map((serializedParticipant: any) => [
serializedParticipant.sid,
serializedParticipant
]));
const participantsToAdd: Set<ParticipantSID> = difference(
Array.from(serializedParticipants.keys()),
Array.from(this.participants.keys()));
const participantsToRemove: Set<ParticipantSID> = difference(
Array.from(this.participants.keys()),
Array.from(serializedParticipants.keys()));
participantsToAdd.forEach((sid: ParticipantSID) => {
this.participants.set(sid, new RemoteParticipantDriver(this._sdkDriver, serializedParticipants.get(sid)));
});
participantsToRemove.forEach((sid: ParticipantSID) => {
this.participants.delete(sid);
});
}
/**
* Disconnect from the {@link Room} in the browser.
* @returns {void}
*/
disconnect(): void {
this._sdkDriver.sendRequest({
api: 'disconnect',
target: this._resourceId
}).then(() => {
// Do nothing.
}, () => {
// Do nothing.
});
}
/**
* Get WebRTC stats for the {@link Room} from the browser.
* @returns {Promise<Array<object>>}
*/
async getStats(): Promise<Array<any>> {
const { error, result } = await this._sdkDriver.sendRequest({
api: 'getStats',
target: this._resourceId
});
if (error) {
throw new Error(error.message);
}
return result;
}
}
/**
* @param {RoomDriver} room
* @param {?TwilioError} error
* @event RoomDriver#disconnected
*/
/**
* @param {RemoteParticipantDriver} participant
* @event RoomDriver#participantConnected
*/
/**
* @param {RemoteParticipantDriver} participant
* @event RoomDriver#participantDisconnected
*/
/**
* @event RoomDriver#recordingStarted
*/
/**
* @event RoomDriver#recordingStopped
*/
/**
* @param {RemoteMediaTrackDriver} track
* @param {RemoteParticipantDriver} participant
* @event RoomDriver#trackDisabled
*/
/**
* @param {RemoteMediaTrackDriver} track
* @param {RemoteParticipantDriver} participant
* @event RoomDriver#trackEnabled
*/
/**
* @param {string} data
* @param {RemoteDataTrackDriver} track
* @param {RemotreParticipantDriver} participant
* @event RoomDriver#trackMessage
*/
/**
* @param {RemoteMediaTrackDriver} track
* @param {RemoteParticipantDriver} participant
* @event RoomDriver#trackStarted
*/
/**
* @param {RemoteDataTrackDriver | RemoteMediaTrackDriver} track
* @param {RemoteParticipantDriver} participant
* @event RoomDriver#trackAdded
*/
/**
* @param {RemoteDataTrackDriver | RemoteMediaTrackDriver} track
* @param {RemoteParticipantDriver} participant
* @event RoomDriver#trackRemoved
*/
/**
* @param {RemoteDataTrackDriver | RemoteMediaTrackDriver} track
* @param {RemoteParticipantDriver} participant
* @event RoomDriver#trackSubscribed
*/
/**
* @param {RemoteDataTrackDriver | RemoteMediaTrackDriver} track
* @param {RemoteParticipantDriver} participant
* @event RoomDriver#trackUnsubscribed
*/
|
//
// PickableItem.h
// PickOne
//
// Created by <NAME> on 4/22/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef enum {
PriorityDisabled = 0,
PriorityLow,
PriorityNormal,
PriorityHigh,
} Priority;
@interface PickableItem : NSObject {
NSString* title;
Priority priority;
}
@property (nonatomic, retain) NSString* title;
@property (nonatomic) Priority priority;
- (id)initWithTitle:(NSString*)inTitle;
+ (NSString*)priorityToString:(Priority)inPriority;
+ (Priority)lookUpPriority:(NSInteger)inNumber;
@end
|
cityscape Rebelling Over Postal Station K
Locals rally to save a historic building on a key Rebellion of 1837 site.
One hundred and seventy-five years after William Lyon Mackenzie assembled his rebels at Montgomery’s Tavern, another group of angry citizens seems ready to rise up against the government on the same site, or at least let a crown corporation know they are unhappy about the possible fallout from its sale—especially if that fallout proves to involve a high-rise condo, as at least one commercial realtor has predicted.
Monday night, a crowd cried things like, “No more condos!” and, “Our history is not for sale!” at a rally in front of Postal Station K, which is what stands on the Montgomery’s Tavern site today. The protest was organized by Eglinton-Lawrence MPP Mike Colle. As a modest crowd listened to speeches about the history of the site and its value to the community, a steady stream of passers-by lined up to sign a petition to save the building.
“There’s really not much going on right now,” noted Canada Post spokesperson John Caines in a phone interview yesterday. An RFP (request for proposals) was made in April for Postal Station K, along with Canada Post properties at 50 Charles Street East and 1780 Avenue Road. “We’re considering selling them, but only if the purchaser provides a suitable replacement property or properties in return. We’re not looking to leave the area but upgrade and modernize our network.”
While the property is a national historic site, because of its role in the rebellion of 1837, Postal Station K is listed but not historically designated by the City of Toronto, affording it few protections under the law. Designed in art-deco style by Murray Brown, whose other works include the nearby Belsize Theatre (now the Regent) on Mount Pleasant Road and the Capitol Theatre in Port Hope, Postal Station K is one of the few buildings in the British Empire to bear the insignia of King Edward VIII. Built in 1936, it replaced a structure originally known as Oulcott’s Tavern, which had been used as a post office from 1912 onward. Besides sorting neighbourhood mail, the building has also, at times, provided space for businesses and a halfway house.
Colle first heard rumblings about a potential sale while on a Heritage Toronto walk through the neighbourhood several weeks ago. He decided to mobilize the community before any clashes with developers could occur. “It’s a great place to take a stand,” Colle noted in a phone interview, referring to the property’s symbolic value. During the fight against amalgamation in 1997, Colle participated in a march that stopped at the site. He believes Canada Post is “totally remote from the public” and he will do his “darndest to make sure they realize that the taxpayers of Toronto paid for that building and they can’t just sell it off willy-nilly without listening to us.” Beyond the building, Colle stressed the property’s role as a public gathering place, especially for wheelchair users who find its lack of barriers ideal for relaxing and meeting others.
Anti-high rise sentiments in the neighbourhood should not be discounted, especially when a high number of condos are underway or being proposed. Though community efforts failed to stop the Minto towers south of Eglinton Avenue, anger at former city councillor Anne Johnston’s role in brokering the deal that allowed the project to proceed led to her defeat in Ward 16 by Karen Stintz in 2004. Though Stintz was unable to attend the rally because she was on vacation, neighbouring councillor Josh Matlow (Ward 22, St. Paul’s) was on hand to lend his support.
If a condo doesn’t become part of the site’s future, what could the building be used for? Colle said that the Anne Johnston Health Centre, located across the street, had expressed interest in additional space for their programs. Eglinton Park Residents’ Association chair Tom Cohen imagined a commercial tavern paired with a museum celebrating the rebellion of 1837. Whatever happens, it’s likely that a creative solution that utilizes most or all of Postal Station K (which seems to be a condition of any sale) will be better received than a high-rise that does little to acknowledge the site’s history. Otherwise, any march down Yonge Street to mark the anniversary of Mackenzie’s rebellion this December might not be a mere re-enactment.
Photos by Jamie Bradburn/Torontoist. |
Children who are picky eaters do more than annoy their parents, finds new research published in the journal Pediatrics.
Picky eating habits, also referred to as selective eating disorder, are often considered a phase. But researchers from Duke University found these habits to coincide with more serious childhood problems, like depression and anxiety. Researchers cited over 20 percent of children between ages 2 and 4 are picky eaters. Of them, nearly 18 percent are moderately picky and 3 percent are severely selective. The latter group of children have such limited food preferences that it restricts their ability to eat with others.
"The question for many parents and physicians is: when is picky eating truly a problem?" said Dr. Nancy Zucker, lead study author and director of the Duke Center for Eating Disorders, in a press release. "The children we're talking about are not just misbehaving kids who refuse to eat their broccoli."
When Zucker looked at children with both levels of selective eating habits, she found they had an elevated risk for depression, social anxiety, and generalized anxiety. These children were also found to be twice as likely as other children to have increased symptoms of generalized anxiety at follow-up visits.
"These are children whose eating has become so limited or selective that it's starting to cause problems," Zucker said. "Impairment can take many different forms. It can affect the child's health, growth, social functioning, and the parent-child relationship. The child can feel like no one believes them, and parents can feel blamed for the problem."
The study also showed that parents are consistently in conflict with their children over food, and this conflict, as well as poor nutrition and frustrated parents can all factor into a kid’s unwillingness to try different foods. Researchers concluded families and doctors need new ways to deal with this problem.
"There's no question that not all children go on to have chronic selective eating in adulthood," Zucker said. "But because these children are seeing impairment in their health and well-being now, we need to start developing ways to help these parents and doctors know when and how to intervene."
Some children who refuse to eat certain foods may have heightened senses, said Zucker, which can make the taste, smell, and textures of certain foods overwhelming. Some children also may have had a bad experience with a food and develop anxiety when forced to try the offending food again.
Zucker also suggested children may benefit from therapy, but that conventional methods do not address children who may have the aforementioned sensory sensitivity. Not only do these children need new treatments, but they need treatments tailored to their age.
Spotting a picky eater is easy for parents to do (we list seven hacks right here), and it could be useful in identifying which children may be at risk for mental health issues.
"It's a good way to get high-risk children into interventions, especially if the parents are asking for help," Zucker said.
Source: Zucker N, et al. Even moderate picky eating can have negative effects on children’s health. Pediatrics. 2015 |
def _get_environment(self):
env = []
job_env = try_key(self._queue_job["data"], [], "docker", "environment")
if isinstance(job_env, list):
env.extend(job_env)
elif isinstance(job_env, dict):
for k, v in job_env.items():
env.append("%s=%s" % (k, v))
else:
raise ValueError("Invalid environment in job spec: %s" % job_env)
env.extend(self._worker_env)
return env |
Catheters have long been used for the treatment of diseases of the cardiovascular system, such as treatment or removal of stenosis. For example, in a percutaneous transluminal coronary angioplasty (PTCA) procedure, a catheter is used to transport a balloon into a patient's cardiovascular system, position the balloon at a desired treatment location, inflate the balloon, and remove the balloon from the patient. Another example of a common catheter-based treatment is the placement of an intravascular stent in the body on a permanent or semi-permanent basis to support weakened or diseased vascular walls, or to avoid closure, re-closure or rupture thereof. More recently, catheters have been used for replacement of heart valves, in particular, the aortic valve in a procedure sometimes known as transcatheter aortic valve implantation (“TAVI”) or transcatheter aortic valve replacement (“TAVR”).
These non-surgical interventional procedures often avoid the necessity of major surgical operations. However, one common problem associated with these procedures is the potential release of embolic debris into the bloodstream that can occlude distal vasculature and cause significant health problems to the patient.
Medical devices have been developed to attempt to deal with the problem created when debris or fragments enter the circulatory system during vessel treatment. One technique includes the placement of a filter or trap downstream from the treatment site to capture embolic debris before it reaches the smaller blood vessels downstream. The placement of a filter in the patient's vasculature during treatment of the vascular lesion can collect embolic debris in the bloodstream.
It is known to attach an expandable filter to a distal end of a guidewire or guidewire-like member that allows the filtering device to be placed in the patient's vasculature. The guidewire allows the physician to steer the filter to a location downstream from the area of treatment. Once the guidewire is in proper position in the vasculature, the embolic filter can be deployed to capture embolic debris. Some embolic filtering devices utilize a restraining sheath to maintain the expandable filter in its collapsed configuration. Once the proximal end of the restraining sheath is retracted by the physician, the expandable filter will transform into its fully expanded configuration in apposition with the vessel wall. The restraining sheath can then be removed from the guidewire allowing the guidewire to be used by the physician to deliver interventional devices, such as a balloon angioplasty catheter or a stent delivery catheter, into the area of treatment. After the interventional procedure is completed, a recovery sheath can be delivered over the guidewire using over-the-wire techniques to collapse the expanded filter (with the trapped embolic debris) for removal from the patient's vasculature. Both the delivery sheath and recovery sheath should be relatively flexible to track over the guide-wire and to avoid straightening the body vessel once in place.
Another distal protection device known in the art includes a filter mounted on a distal portion of a hollow guidewire or tube. A moveable core wire is used to open and close the filter. The filter is coupled at a proximal end to the tube and at a distal end to the core wire. Pulling on the core wire while pushing on the tube draws the ends of the filter toward each other, causing the filter framework between the ends to expand outward into contact with the vessel wall. Filter mesh material is mounted to the filter framework. To collapse the filter, the procedure is reversed, i.e., pulling the tube proximally while pushing the core wire distally to force the filter ends apart. A sheath catheter may be used as a retrieval catheter at the end of the interventional procedure to reduce the profile of the “push-pull” filter, as due to the embolic particles collected, the filter may still be in a somewhat expanded state. The retrieval catheter may be used to further collapse the filter and/or smooth the profile thereof, so that the filter guidewire may pass through the treatment area without disturbing any stents or otherwise interfering with the treated vessel.
TAVR procedures present difficulties not encountered in other procedures. For example, three branch vessels extend from the aortic arch towards the upper body. In particular, the right common carotid artery, which branches from the brachiocephalic artery, and the left common carotid artery deliver blood to the brain. Emboli entering these arteries pose an increased risk of stroke by blocking the smaller blood vessels in the brain. Further, many TAVR procedures provide access through the femoral artery, up through abdominal aortic, the aortic arch, and then crossing the aortic valve. Filter devices to be deployed to protect the carotid in many cases need to be delivered through a different pathway so that the delivery device for the filter does not interfere with the delivery device for the replacement valve. This requires an additional access site, such as the brachial artery.
Accordingly, there is a need for improved embolic protection devices for TAVR procedures. |
Finding New Homes for Dress Collections: The Case Study of the Suddon-Cleaver Collection Abstract When private collectors amass collections of significant size, there often comes a point where disposition must be addressed. This article will explore the complex process of finding new homes for dress collections, using the case study of the Suddon-Cleaver collection and linking it to Walter Benjamins reflections on book collecting in the essay Unpacking my Library. Although the process of breaking up a collection is associated with negative connotations, this Canadian case study will show how the process can serve to optimize access and value, especially at a time when museum resources are limited and overstretched. Other examples of redistributed dress collections will be reviewed including the dispersal of the wardrobe of Georgian banker Thomas Coutts and the Brooklyn Museum dress collection transfer to the Metropolitan Museum of Art. We argue that the process of finding multiple new homes should be viewed as a way of liberating the best pieces in the collection from the burden of items that are of low value or in poor condition. In carefully articulating the process of distributing the Suddon-Cleaver collection, this article outlines a process that may be adapted for similar dispersals. |
from datetime import datetime
import uuid
from django.http import JsonResponse, HttpResponse
from rest_framework.views import APIView
from atlas.creator import assert_or_throw
from atlas.guarantor import use_serializer, any_exception_throws_400
from atlas.locator import AModule
from .serializers import CompleteReservationSerializer, CreateReservationSerializer, ReservationSerializer
from .models import Reservation
from slot.models.timeslot import TimeSlot
from slot.models.slotbind import SlotBind
from errors.reservation import InsufficientSpaceException, ImmutableFieldException
reservation_module = AModule()
def _try_assign_timeslot(timeslot, reservation=None):
num_reg = SlotBind.objects.filter(timeslot=timeslot).count()
assert_or_throw(num_reg < timeslot.availability, InsufficientSpaceException())
bind = SlotBind.objects.create(
timeslot=timeslot,
reservation=reservation
)
return bind
@reservation_module.route("create", name="reservation_init")
class InitialCreate(APIView):
@any_exception_throws_400
@use_serializer(Serializer=CreateReservationSerializer, pass_in='data')
def put(self, payload, format=None):
res_id = uuid.uuid4()
slotbind = _try_assign_timeslot(payload['timeslot'])
new_reservation = Reservation.objects.create(res_id=res_id, **payload)
slotbind.reservation_id = new_reservation
slotbind.save()
return JsonResponse({'rid': res_id})
@reservation_module.route(r"(?<resid>.+?)/update", name="reservation_update")
class Update(APIView):
@any_exception_throws_400
@use_serializer(Serializer=CompleteReservationSerializer, pass_in='data')
def post(self, updated_fields, resid, format=None):
resid = uuid.UUID(resid)
reservation = Reservation.objects.get(res_id=resid)
if (reservation.commit_at is not None) and \
(set(CompleteReservationSerializer.Meta._on_commit_finalize_fields) & set(updated_fields.keys())):
raise ImmutableFieldException(field="Slot", when="after reservation submitted")
# TODO: Similar restriction should apply to other fields if the translation process starts!
if "timeslot" in updated_fields:
curr_slot = SlotBind.objects.filter(reservation_id=resid)[0]
new_slot = _try_assign_timeslot(updated_fields['timeslot'], reservation=reservation)
curr_slot.delete()
for attr, value in updated_fields.items():
setattr(reservation, attr, value)
reservation.save()
return JsonResponse({'updated_fields': list(updated_fields.keys())})
@reservation_module.route(r"(?<resid>.+?)/info", name="reservation_get")
class GetReservationInfo(APIView):
@any_exception_throws_400
def get(self, request, resid, format=None):
reservation = Reservation.objects.get(res_id=uuid.UUID(resid))
return JsonResponse(ReservationSerializer(reservation).data)
@reservation_module.route(r"(?<resid>.+?)/commit", name="reservation_commit")
class Commit(APIView):
@any_exception_throws_400
def post(self, request, resid, format=None):
resid = uuid.UUID(resid)
reservation = Reservation.objects.get(res_id=resid)
assert reservation.commit_at is None, "Reservation has already been submitted!"
assert reservation.timeslot_id, "Reservation with empty slot info cannot be submitted!"
assert reservation.first_hospital and reservation.first_doctor_name and reservation.first_doctor_contact, \
"Reservation with empty medical history cannot be submitted!"
reservation.commit_at = datetime.now()
reservation.save()
return HttpResponse(status=204)
# TODO: payment endpoint
urlpatterns = reservation_module.urlpatterns |
Regulatory peptides modulate adhesion of polymorphonuclear leukocytes to bronchial epithelial cells through regulation of interleukins, ICAM-1 and NF-kappaB/IkappaB. A complex network of regulatory neuropeptides controls airway inflammation reaction, in which airway epithelial cells adhering to and activating leukocytes is a critical step. To study the effect of intrapulmonary regulatory peptides on adhesion of polymorphonuclear leukocytes (PMNs) to bronchial epithelial cells (BECs) and its mechanism, several regulatory peptides including vasoactive intestinal peptide (VIP), epidermal growth factor (EGF), endothelin-1 (ET-1) and calcitonin gene-related peptide (CGRP), were investigated. The results demonstrated that VIP and EGF showed inhibitory effects both on the secretion of IL-1, IL-8 and the adhesion of PMNs to BECs, whereas ET-1 and CGRP had the opposite effect. Anti-intercellular adhesion molecule-1 (ICAM-1) antibody could block the adhesion of PMNs to ozone-stressed BECs. Using immunocytochemistry and reverse transcription-polymerase chain reaction (RT-PCR), it was shown that VIP and EGF down-regulated the expression of ICAM-1 in BECs, while ET-1 and CGRP up-regulated ICAM-1 expression. NF-kappaB inhibitor MG132 blocked ICAM-1 expression induced by ET-1 and CGRP. Furthermore, in electric mobility shift assay (EMSA), VIP and EGF restrained the binding activity of NF-kappaB to the NF-kappaB binding site within the ICAM-1 promoter in ozone-stressed BECs, while CGRP and ET-1 promoted this binding activity. IkappaB degradation was consistent with NF-kappaB activation. These observations indicate that VIP and EGF inhibit inflammation, while ET-1 and CGRP enhance the inflammation reaction. |
package main
import (
"io"
"net/http"
)
func home(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Home page route")
}
func contact(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "contact route")
}
func main() {
http.HandleFunc("/", home)
http.HandleFunc("/contact", contact)
// This server is using the default mux
http.ListenAndServe(":8080", nil)
}
|
// Get the Installer of the specified installable.
func (r *Repo) Get(name, version string) (repository.Installer, error) {
index, err := r.BuildIndex()
if err != nil {
return nil, errors.Wrap(err, "can't build helm index configSetup")
}
res := index.Search(name, version)
if len(res) != 1 {
return nil, ErrNotFound
}
if len(res[0].URLs) == 0 {
return nil, ErrNoValidURL
}
var buf *bytes.Buffer
err = nil
for i := range res[0].URLs {
buf, err = r.httpGetter.Get(res[0].URLs[i])
if err != nil {
continue
}
break
}
if err != nil {
return nil, errors.Wrap(err, "GET target file failed")
}
ch, err := loader.LoadArchive(buf)
if err != nil {
return nil, errors.Wrap(err, "Load archive to struct Chart failed")
}
brief := res[0].ToInstallerBrief()
i := NewHelmInstaller(brief.Name, ch, *brief, r.namespace, r.actionConfig)
return &i, nil
} |
def convert_labels(self):
print("\t *** Converting the labels to binary matrix... ***")
print("Labels shape BEFORE conversion: ", self._x_train.shape)
print("Individual label shape and type BEFORE conversion: ", self._x_train[0].shape)
print()
print("Labels shape AFTER conversion: ", self._x_train.shape)
print("Individual label shape and type AFTER conversion: ", self._x_train[0].shape)
print()
return None |
Effect of surface modifications to single and multilayer graphene temperature coefficient of resistance. Interfacial effects on single-layer graphene (SLG) or multilayer graphene (MLG) properties greatly affect device performance. Thus, the effect of the interface on the temperature coefficient of resistance (TCR) on SLG and MLG due to surface deposited core-shell metallic nanoparticles (MNPs) and various substrates was experimentally investigated. Observed substrates included glass, SiO2, and Si3N4. We show that these modifications can be used to strongly influence SLG interface effects, thus increasing TCR up to a 0.456% per K resistance change when in contact with SiO2 substrate at the bottom surface and MNPs on the top surface. However, these surface interactions are muted in MLG due to the screening effect of non-superficial layers, only achieving a -0.0998% per K resistance change in contact with the bottom Si3N4 substrate and the top MNPs. We also demonstrate contrary thermal sensitivity responses between SLG and MLG after the addition of MNP to the surface. |
One of the most frightening things about October 31st apparently isn’t the ghosts and goblins that may be appearing at your door.
John Pecchio, a spokesman for AAA-Iowa, says Halloween is one of the top three days of the year for pedestrian injuries and deaths.
“The scariest part of Halloween isn’t the spooky costumes or scary pranks, it’s the alcohol-impaired drivers,” Pecchio says. “Tragically, Halloween drunk driving fatalities are on the rise.” A federal report finds 44% of those killed in motor vehicle crashes on Halloween night from 2012 to 2016 were in crashes involving an impaired driver. Getting caught driving under the influence on trick or treat night — or any other time — is no treat.
He recommends all Iowans drive slower through neighborhoods. Driving five miles per hour slower than the posted speed limit will give you extra time to react to children who may dart out in front of you. |
<filename>Components/6410/gpio/gpio.h
/*
* gpio.h
*
* Created on: 2012-12-17
* Author: cya
*/
#ifndef GPIO_H_
#define GPIO_H_
#include <stdint.h>
typedef struct
{
uint32_t GPACON; // 000
uint32_t GPADAT; // 004
uint32_t GPAPUD; // 008
uint32_t GPACONSLP; // 00c
uint32_t GPAPUDSLP; // 010
uint32_t PAD1[3]; // 014~01f
uint32_t GPBCON; // 020
uint32_t GPBDAT; // 024
uint32_t GPBPUD; // 028
uint32_t GPBCONSLP; // 02c
uint32_t GPBPUDSLP; // 030
uint32_t PAD2[3]; // 034~03f
uint32_t GPCCON; // 040
uint32_t GPCDAT; // 044
uint32_t GPCPUD; // 048
uint32_t GPCCONSLP; // 04c
uint32_t GPCPUDSLP; // 050
uint32_t PAD3[3]; // 054~05f
uint32_t GPDCON; // 060
uint32_t GPDDAT; // 064
uint32_t GPDPUD; // 068
uint32_t GPDCONSLP; // 06c
uint32_t GPDPUDSLP; // 070
uint32_t PAD4[3]; // 074~07f
uint32_t GPECON; // 080
uint32_t GPEDAT; // 084
uint32_t GPEPUD; // 088
uint32_t GPECONSLP; // 08c
uint32_t GPEPUDSLP; // 090
uint32_t PAD5[3]; // 094~09f
uint32_t GPFCON; // 0a0
uint32_t GPFDAT; // 0a4
uint32_t GPFPUD; // 0a8
uint32_t GPFCONSLP; // 0ac
uint32_t GPFPUDSLP; // 0b0
uint32_t PAD6[3]; // 0b4~0bf
uint32_t GPGCON; // 0c0
uint32_t GPGDAT; // 0c4
uint32_t GPGPUD; // 0c8
uint32_t GPGCONSLP; // 0cc
uint32_t GPGPUDSLP; // 0d0
uint32_t PAD7[3]; // 0d4~0df
uint32_t GPHCON0; // 0e0
uint32_t GPHCON1; // 0e4
uint32_t GPHDAT; // 0e8
uint32_t GPHPUD; // 0ec
uint32_t GPHCONSLP; // 0f0
uint32_t GPHPUDSLP; // 0f4
uint32_t PAD8[2]; // 0f8~0ff
uint32_t GPICON; // 100
uint32_t GPIDAT; // 104
uint32_t GPIPUD; // 108
uint32_t GPICONSLP; // 10c
uint32_t GPIPUDSLP; // 110
uint32_t PAD9[3]; // 114~11f
uint32_t GPJCON; // 120
uint32_t GPJDAT; // 124
uint32_t GPJPUD; // 128
uint32_t GPJCONSLP; // 12c
uint32_t GPJPUDSLP; // 130
uint32_t PAD10[3]; // 134~13f
// GPK, GPL, GPM, GPN are Below
uint32_t GPOCON; // 140
uint32_t GPODAT; // 144
uint32_t GPOPUD; // 148
uint32_t GPOCONSLP; // 14c
uint32_t GPOPUDSLP; // 150
uint32_t PAD11[3]; // 154~15f
uint32_t GPPCON; // 160
uint32_t GPPDAT; // 164
uint32_t GPPPUD; // 168
uint32_t GPPCONSLP; // 16c
uint32_t GPPPUDSLP; // 170
uint32_t PAD12[3]; // 174~17f
uint32_t GPQCON; // 180
uint32_t GPQDAT; // 184
uint32_t GPQPUD; // 188
uint32_t GPQCONSLP; // 18c
uint32_t GPQPUDSLP; // 190
uint32_t PAD13[3]; // 194~19f
uint32_t SPCON; // 1a0
uint32_t PAD14[3]; // 1a4~1af
uint32_t MEM0CONSTOP; // 1b0
uint32_t MEM1CONSTOP; // 1b4
uint32_t PAD15[2]; // 1b8~1bf
uint32_t MEM0CONSLP0; // 1c0
uint32_t MEM0CONSLP1; // 1c4
uint32_t MEM1CONSLP; // 1c8
uint32_t PAD16; // 1cc
uint32_t MEM0DRVCON; // 1d0
uint32_t MEM1DRVCON; // 1d4
uint32_t PAD17[2]; // 1d8~1df
uint32_t PAD18[8]; // 1e0~1ff
uint32_t EINT12CON; // 200
uint32_t EINT34CON; // 204
uint32_t EINT56CON; // 208
uint32_t EINT78CON; // 20c
uint32_t EINT9CON; // 210
uint32_t PAD19[3]; // 214~21f
uint32_t EINT12FLTCON; // 220
uint32_t EINT34FLTCON; // 224
uint32_t EINT56FLTCON; // 228
uint32_t EINT78FLTCON; // 22c
uint32_t EINT9FLTCON; // 230
uint32_t PAD20[3]; // 234~23f
uint32_t EINT12MASK; // 240
uint32_t EINT34MASK; // 244
uint32_t EINT56MASK; // 248
uint32_t EINT78MASK; // 24c
uint32_t EINT9MASK; // 250
uint32_t PAD21[3]; // 254~25f
uint32_t EINT12PEND; // 260
uint32_t EINT34PEND; // 264
uint32_t EINT56PEND; // 268
uint32_t EINT78PEND; // 26c
uint32_t EINT9PEND; // 270
uint32_t PAD22[3]; // 274~27f
uint32_t PRIORITY; // 280
uint32_t SERVICE; // 284
uint32_t SERVICEPEND; // 288
uint32_t PAD23; // 28f
uint32_t PAD24[348]; // 290~7ff
uint32_t GPKCON0; // 800
uint32_t GPKCON1; // 804
uint32_t GPKDAT; // 808
uint32_t GPKPUD; // 80c
uint32_t GPLCON0; // 810
uint32_t GPLCON1; // 814
uint32_t GPLDAT; // 818
uint32_t GPLPUD; // 81c
uint32_t GPMCON; // 820
uint32_t GPMDAT; // 824
uint32_t GPMPUD; // 828
uint32_t PAD25; // 82f
uint32_t GPNCON; // 830
uint32_t GPNDAT; // 834
uint32_t GPNPUD; // 838
uint32_t PAD26; // 83f
uint32_t PAD27[16]; // 840~87f
uint32_t SPCONSLP; // 880
uint32_t PAD28[3]; // 884~88f
uint32_t PAD29[28]; // 890~8ff
uint32_t EINT0CON0; // 900
uint32_t EINT0CON1; // 904
uint32_t PAD30[2]; // 908~90f
uint32_t EINT0FLTCON0; // 910
uint32_t EINT0FLTCON1; // 914
uint32_t EINT0FLTCON2; // 918
uint32_t EINT0FLTCON3; // 91c
uint32_t EINT0MASK; // 920
uint32_t EINT0PEND; // 924
uint32_t PAD31[2]; // 928~92f
uint32_t SLPEN; // 930
uint32_t PAD32[3]; // 934~93f
} S3C6410_GPIO_REG_TypeDef;
#define S3C6410_GPIO_REG ((volatile S3C6410_GPIO_REG_TypeDef *) 0x7F008000)
#endif /* GPIO_H_ */
|
<filename>test/Studio/typescript/autocomplete/rql.spec.ts
/// <reference path="../../../../src/Raven.Studio/typings/tsd.d.ts" />
import chai = require("chai");
const assert = chai.assert;
import rqlTestUtils = require("autocomplete/rqlTestUtils");
import queryCompleter = require("src/Raven.Studio/typescript/common/queryCompleter");
const emptyProvider = rqlTestUtils.emptyProvider;
const northwindProvider = rqlTestUtils.northwindProvider;
describe("RQL Autocomplete", () => {
const emptyList: autoCompleteWordList[] = [
{caption: "from", value: "from ", score: 3, meta: "clause", snippet: "from ${1:Collection} as ${2:alias}\r\n"},
{caption: "from index", value: "from index ", score: 2, meta: "clause", snippet: "from index ${1:Index} as ${2:alias}\r\n"},
{caption: "declare", value: "declare ", score: 1, meta: "JS function", snippet: `declare function \${1:Name}() {
\${0}
}
`}
];
const collectionsList = [
{caption: "index", value: "index ", score: 4, meta: "keyword"},
{caption: "@all_docs", value: "@all_docs ", score: 3, meta: "collection"},
{caption: "Regions", value: "Regions ", score: 2, meta: "collection"},
{caption: "Suppliers", value: "Suppliers ", score: 2, meta: "collection"},
{caption: "Employees", value: "Employees ", score: 2, meta: "collection"},
{caption: "Categories", value: "Categories ", score: 2, meta: "collection"},
{caption: "Products", value: "Products ", score: 2, meta: "collection"},
{caption: "Shippers", value: "Shippers ", score: 2, meta: "collection"},
{caption: "Companies", value: "Companies ", score: 2, meta: "collection"},
{caption: "Orders", value: "Orders ", score: 2, meta: "collection"},
{caption: "Collection With Space", value: "'Collection With Space' ", score: 2, meta: "collection"},
{caption: "Collection!", value: "'Collection!' ", score: 2, meta: "collection"},
{caption: "Collection With ' And \" in name", value: "'Collection With '' And \" in name' ", score: 2, meta: "collection"}
];
const indexesList = [
{caption: "Orders/ByCompany", value: "'Orders/ByCompany' ", score: 101, meta: "index"},
{caption: "Product/Sales", value: "'Product/Sales' ", score: 101, meta: "index"},
{caption: "Orders/Totals", value: "'Orders/Totals' ", score: 101, meta: "index"},
{caption: "Index With ' And \" in name", value: "'Index With '' And \" in name' ", score: 101, meta: "index"},
];
const functionsList = [
{caption: "ID", value: "ID() ", score: 11, meta: "document ID"}
];
const aliasList: autoCompleteWordList[] = [
{caption: "o", value: "o.", score: 999, meta: "Orders"}
];
const aliasListAfterWhere: autoCompleteWordList[] = _.sortBy(aliasList.concat(functionsList).concat(queryCompleter.whereFunctionsOnly), (x: autoCompleteWordList) => x.score).reverse();
const aliasesList: autoCompleteWordList[] = aliasList.concat([
{caption: "c", value: "c.", score: 998, meta: "Company"},
{caption: "e", value: "e.", score: 997, meta: "Employee"},
{caption: "s", value: "s.", score: 996, meta: "ShipVia"}
]);
const aliasesListWithFunctions: autoCompleteWordList[] = _.sortBy(aliasesList.concat(queryCompleter.functionsList), (x: autoCompleteWordList) => x.score).reverse();
const fieldsList: autoCompleteWordList[] = [
{caption: "Company", value: "Company ", score: 114, meta: "string field"},
{caption: "Employee", value: "Employee ", score: 113, meta: "string field"},
{caption: "Freight", value: "Freight ", score: 112, meta: "number field"},
{caption: "Lines", value: "Lines ", score: 111, meta: "object[] field"},
{caption: "OrderedAt", value: "OrderedAt ", score: 110, meta: "string field"},
{caption: "RequireAt", value: "RequireAt ", score: 109, meta: "string field"},
{caption: "ShipTo", value: "ShipTo ", score: 108, meta: "object field"},
{caption: "ShipVia", value: "ShipVia ", score: 107, meta: "string field"},
{caption: "ShippedAt", value: "ShippedAt ", score: 106, meta: "string field"},
{caption: "With ' and \" quotes", value: "'With '' and \" quotes' ", score: 105, meta: "string field"},
{caption: "With Space", value: "'With Space' ", score: 104, meta: "string field"},
{caption: "With*Star", value: "'With*Star' ", score: 103, meta: "string field"},
{caption: "With.Dot", value: "'With.Dot' ", score: 102, meta: "string field"},
{caption: "@metadata", value: "@metadata ", score: 101, meta: "object field"}
];
const fieldsListWithFunctions: autoCompleteWordList[] = fieldsList.concat(functionsList);
const whereFieldsList: autoCompleteWordList[] = _.sortBy(fieldsListWithFunctions.concat(queryCompleter.whereFunctionsOnly), (x: autoCompleteWordList) => x.score).reverse();
const whereFieldsListAfterOrAnd = queryCompleter.notList.concat(whereFieldsList);
const allDocsFieldsList = [
{caption: "Address", value: "Address ", score: 138, meta: "object field"},
{caption: "Birthday", value: "Birthday ", score: 137, meta: "string field"},
{caption: "Category", value: "Category ", score: 136, meta: "string field"},
{caption: "Company", value: "Company ", score: 135, meta: "string field"},
{caption: "Contact", value: "Contact ", score: 134, meta: "object field"},
{caption: "Description", value: "Description ", score: 133, meta: "string field"},
{caption: "Discontinued", value: "Discontinued ", score: 132, meta: "boolean field"},
{caption: "Employee", value: "Employee ", score: 131, meta: "string field"},
{caption: "Extension", value: "Extension ", score: 130, meta: "string field"},
{caption: "ExternalId", value: "ExternalId ", score: 129, meta: "string field"},
{caption: "Fax", value: "Fax ", score: 128, meta: "string field"},
{caption: "FirstName", value: "FirstName ", score: 127, meta: "string field"},
{caption: "Freight", value: "Freight ", score: 126, meta: "number field"},
{caption: "HiredAt", value: "HiredAt ", score: 125, meta: "string field"},
{caption: "HomePage", value: "HomePage ", score: 124, meta: "null field"},
{caption: "HomePhone", value: "HomePhone ", score: 123, meta: "string field"},
{caption: "LastName", value: "LastName ", score: 122, meta: "string field"},
{caption: "Lines", value: "Lines ", score: 121, meta: "object[] field"},
{caption: "Max", value: "Max ", score: 120, meta: "number field"},
{caption: "Na.me", value: "'Na.me' ", score: 119, meta: "string field"},
{caption: "Name", value: "Name ", score: 118, meta: "string field"},
{caption: "Notes", value: "Notes ", score: 117, meta: "null field"},
{caption: "OrderedAt", value: "OrderedAt ", score: 116, meta: "string field"},
{caption: "Phone", value: "Phone ", score: 115, meta: "string field"},
{caption: "PricePerUnit", value: "PricePerUnit ", score: 114, meta: "number field"},
{caption: "QuantityPerUnit", value: "QuantityPerUnit ", score: 113, meta: "string field"},
{caption: "ReorderLevel", value: "ReorderLevel ", score: 112, meta: "number field"},
{caption: "ReportsTo", value: "ReportsTo ", score: 111, meta: "string field"},
{caption: "RequireAt", value: "RequireAt ", score: 110, meta: "string field"},
{caption: "ShipTo", value: "ShipTo ", score: 109, meta: "object field"},
{caption: "ShipVia", value: "ShipVia ", score: 108, meta: "string field"},
{caption: "ShippedAt", value: "ShippedAt ", score: 107, meta: "null field"},
{caption: "Supplier", value: "Supplier ", score: 106, meta: "string field"},
{caption: "Territories", value: "Territories ", score: 105, meta: "object[] | string[] field"},
{caption: "Title", value: "Title ", score: 104, meta: "string field"},
{caption: "UnitsInStock", value: "UnitsInStock ", score: 103, meta: "number field"},
{caption: "UnitsOnOrder", value: "UnitsOnOrder ", score: 102, meta: "number field"},
{caption: "@metadata", value: "@metadata ", score: 101, meta: "object field"}
].concat(functionsList);
const orderByFieldsList = _.sortBy(fieldsList.concat([
{caption: "score", value: "score() ", snippet: "score() ", score: 22, meta: "function"}, // TODO: snippet
{caption: "random", value: "random() ", snippet: "random() ", score: 21, meta: "function"} // TODO: snippet
]), (x: autoCompleteWordList) => x.score).reverse();
const orderBySortAfterList = [
{caption: ",", value: ", ", score: 23, meta: "separator"},
{caption: "load", value: "load ", score: 20, meta: "clause", snippet: "load ${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 19, meta: "keyword"},
{caption: "select {", value: "select { ", score: 18, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 17, meta: "keyword"}
];
const groupByAfterList = [
{caption: ",", value: ", ", score: 23, meta: "separator"},
{caption: "where", value: "where ", score: 20, meta: "keyword"},
{caption: "order", value: "order ", score: 19, meta: "keyword"},
{caption: "load", value: "load ", score: 18, meta: "clause", snippet: "load ${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 17, meta: "keyword"},
{caption: "select {", value: "select { ", score: 16, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 15, meta: "keyword"}
];
const orderBySortList = _.sortBy(orderBySortAfterList.concat([
{caption: "desc", value: "desc ", score: 22, meta: "descending sort"},
{caption: "asc", value: "asc ", score: 21, meta: "ascending sort"}
]), (x: autoCompleteWordList) => x.score).reverse();
const fieldsShipToList = [
{caption: "City", value: "City ", score: 106, meta: "string field"},
{caption: "Country", value: "Country ", score: 105, meta: "string field"},
{caption: "Line1", value: "Line1 ", score: 104, meta: "string field"},
{caption: "Line2", value: "Line2 ", score: 103, meta: "null field"},
{caption: "PostalCode", value: "PostalCode ", score: 102, meta: "string field"},
{caption: "Region", value: "Region ", score: 101, meta: "string field"}
];
const afterFromList = [
{caption: "as", value: "as ", score: 21, meta: "keyword"},
{caption: "group", value: "group ", score: 20, meta: "keyword"},
{caption: "where", value: "where ", score: 19, meta: "keyword"},
{caption: "order", value: "order ", score: 18, meta: "keyword"},
{caption: "load", value: "load ", score: 17, meta: "clause", snippet: "load ${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 16, meta: "keyword"},
{caption: "select {", value: "select { ", score: 15, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 14, meta: "keyword"}
];
const afterFromAsList = [
{caption: "group", value: "group ", score: 20, meta: "keyword"},
{caption: "where", value: "where ", score: 19, meta: "keyword"},
{caption: "order", value: "order ", score: 18, meta: "keyword"},
{caption: "load", value: "load ", score: 17, meta: "clause", snippet: "load o.${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 16, meta: "keyword"},
{caption: "select {", value: "select { ", score: 15, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 14, meta: "keyword"}
];
const afterFromIndexList = [
{caption: "as", value: "as ", score: 21, meta: "keyword"},
{caption: "where", value: "where ", score: 20, meta: "keyword"},
{caption: "order", value: "order ", score: 19, meta: "keyword"},
{caption: "load", value: "load ", score: 18, meta: "clause", snippet: "load ${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 17, meta: "keyword"},
{caption: "select {", value: "select { ", score: 16, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 15, meta: "keyword"}
];
const afterFromIndexAsList = [
{caption: "where", value: "where ", score: 20, meta: "keyword"},
{caption: "order", value: "order ", score: 19, meta: "keyword"},
{caption: "load", value: "load ", score: 18, meta: "clause", snippet: "load o.${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 17, meta: "keyword"},
{caption: "select {", value: "select { ", score: 16, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 15, meta: "keyword"}
];
const afterGroupWithoutSpaceList = [
{caption: "group", value: "group ", score: 20, meta: "keyword"},
{caption: "where", value: "where ", score: 19, meta: "keyword"},
{caption: "order", value: "order ", score: 18, meta: "keyword"},
{caption: "load", value: "load ", score: 17, meta: "clause", snippet: "load ${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 16, meta: "keyword"},
{caption: "select {", value: "select { ", score: 15, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 14, meta: "keyword"}
];
const afterIncludeWithoutSpaceList = [
{caption: "include", value: "include ", score: 20, meta: "keyword"}
];
const afterWhereList = [
{caption: "and", value: "and ", score: 22, meta: "binary operation"},
{caption: "or", value: "or ", score: 21, meta: "binary operation"},
{caption: "order", value: "order ", score: 20, meta: "keyword"},
{caption: "load", value: "load ", score: 19, meta: "clause", snippet: "load ${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 18, meta: "keyword"},
{caption: "select {", value: "select { ", score: 17, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 16, meta: "keyword"}
];
const afterWhereListWithFromAs = [
{caption: "and", value: "and ", score: 22, meta: "binary operation"},
{caption: "or", value: "or ", score: 21, meta: "binary operation"},
{caption: "order", value: "order ", score: 20, meta: "keyword"},
{caption: "load", value: "load ", score: 19, meta: "clause", snippet: "load o.${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 18, meta: "keyword"},
{caption: "select {", value: "select { ", score: 17, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 16, meta: "keyword"}
];
const afterWhereWithoutSpaceList = [
{caption: "where", value: "where ", score: 20, meta: "keyword"},
{caption: "order", value: "order ", score: 19, meta: "keyword"},
{caption: "load", value: "load ", score: 18, meta: "clause", snippet: "load ${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 17, meta: "keyword"},
{caption: "select {", value: "select { ", score: 16, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 15, meta: "keyword"}
];
const afterOrderWithoutSpaceList = [
{caption: "order", value: "order ", score: 20, meta: "keyword"},
{caption: "load", value: "load ", score: 19, meta: "clause", snippet: "load ${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 18, meta: "keyword"},
{caption: "select {", value: "select { ", score: 17, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 16, meta: "keyword"}
];
const afterLoad = [
{caption: ",", value: ", ", score: 21, meta: "separator", snippet: ", o.${1:field} as ${2:alias} "},
{caption: "select", value: "select ", score: 20, meta: "keyword"},
{caption: "select {", value: "select { ", score: 19, meta: "JS projection", snippet: `select {
\${1:Name}: \${2:Value}
}
`},
{caption: "include", value: "include ", score: 18, meta: "keyword"}
];
const afterSelect = [
{caption: ",", value: ", ", score: 23, meta: "separator"},
{caption: "as", value: "as ", score: 21, meta: "keyword"},
{caption: "include", value: "include ", score: 20, meta: "keyword"}
];
const afterSelectAs = [
{caption: ",", value: ", ", score: 23, meta: "separator"},
{caption: "include", value: "include ", score: 20, meta: "keyword"}
];
const afterOrderOrGroupList = [
{caption: "by", value: "by ", score: 21, meta: "keyword"}
];
const searchOrAndList = [
{caption: "or", value: "or ", score: 22, meta: "any term"},
{caption: "and", value: "and ", score: 21, meta: "all terms"}
];
it('empty query should start with from or declare', done => {
rqlTestUtils.autoComplete("|", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, emptyList);
assert.isNull(lastKeyword);
done();
})
});
it('from without space should complete the from itself', done => {
rqlTestUtils.autoComplete("from|", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "from");
assert.deepEqual(wordlist, emptyList);
assert.equal(lastKeyword.keyword, "from");
assert.equal(lastKeyword.dividersCount, 0);
done();
});
});
it('from should get collection names', done => {
rqlTestUtils.autoComplete("from |", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, collectionsList);
assert.equal(lastKeyword.keyword, "from");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('keyword with new lines', done => {
rqlTestUtils.autoComplete(`from
|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, collectionsList);
assert.equal(lastKeyword.keyword, "from");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('from collection with new lines', done => {
rqlTestUtils.autoComplete(`from
Orders|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "Orders");
assert.deepEqual(wordlist, collectionsList);
assert.equal(lastKeyword.keyword, "from");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('from Orders| should not list anything but have the Orders prefix', done => {
rqlTestUtils.autoComplete("from Orders|", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "Orders");
assert.deepEqual(wordlist, collectionsList);
assert.equal(lastKeyword.keyword, "from");
assert.equal(lastKeyword.dividersCount, 1);
assert.isUndefined(lastKeyword.info.alias);
done();
});
});
it('from Collection | should list collections', done => {
rqlTestUtils.autoComplete("from Orders |", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterFromList);
assert.equal(lastKeyword.keyword, "from");
assert.equal(lastKeyword.dividersCount, 2);
assert.isUndefined(lastKeyword.info.alias);
done();
});
});
it('from collection with a new line', done => {
rqlTestUtils.autoComplete(`from Orders
|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterFromList);
assert.equal(lastKeyword.keyword, "from");
assert.equal(lastKeyword.dividersCount, 2);
assert.isUndefined(lastKeyword.info.alias);
done();
});
});
it('from collection as without space | should list as with prefix', done => {
rqlTestUtils.autoComplete(`from Orders as|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "as");
assert.deepEqual(wordlist, afterFromList);
assert.equal(lastKeyword.keyword, "from");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 2);
assert.isUndefined(lastKeyword.info.alias);
done();
});
});
it('from collection as | should not list anything', done => {
rqlTestUtils.autoComplete(`from Orders as |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(errors, ["empty completion"]);
assert.isNull(wordlist);
assert.equal(lastKeyword.keyword, "from");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 3);
assert.isUndefined(lastKeyword.info.alias);
done();
});
});
it('from collection as alias without space', done => {
rqlTestUtils.autoComplete(`from Orders as o|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "o");
assert.deepEqual(errors, ["empty completion"]);
assert.isNull(wordlist);
assert.equal(lastKeyword.keyword, "from");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 3);
assert.isUndefined(lastKeyword.info.alias);
done();
});
});
it('from collection as alias | should list next keywords', done => {
rqlTestUtils.autoComplete(`from Orders as o |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterFromAsList);
assert.equal(lastKeyword.keyword, "from");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 4);
assert.equal(lastKeyword.info.alias, "o");
done();
});
});
it('from collection as alias, where | should list aliases with functions', done => {
rqlTestUtils.autoComplete(`from Orders as o
where |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, aliasListAfterWhere);
assert.equal(lastKeyword.keyword, "where");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 1);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.equal(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders"});
done();
});
});
it('from collection as alias, where and alias with dot | should list collection fields', done => {
rqlTestUtils.autoComplete(`from Orders as o
where c.|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 1);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.equal(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders"});
done();
});
});
it('from collection as alias, load | should list alias', done => {
rqlTestUtils.autoComplete(`from Orders as o
load |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, aliasList);
assert.equal(lastKeyword.keyword, "load");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 1);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.equal(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders"});
done();
});
});
it('from collection as alias, load and alias with dot | should list collection fields', done => {
rqlTestUtils.autoComplete(`from Orders as o
load o.|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "load");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 1);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.equal(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders"});
done();
});
});
it('from collection as alias, load and alias with dot than space | should list as only', done => {
rqlTestUtils.autoComplete(`from Orders as o
load o.Company |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, queryCompleter.asList);
assert.equal(lastKeyword.keyword, "load");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 2);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.equal(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders"});
done();
});
});
it('from collection as alias, load and alias with space | should list nothing', done => {
rqlTestUtils.autoComplete(`from Orders as o
load o.Company as |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.isNull(wordlist);
assert.equal(lastKeyword.keyword, "load");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 3);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.equal(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders"});
done();
});
});
it('from collection as alias, load and alias specified | should list separator and next keywords', done => {
rqlTestUtils.autoComplete(`from Orders as o
load o.Company as c |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterLoad);
assert.equal(lastKeyword.keyword, "load");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 4);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.equal(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders", c: "Company"});
done();
});
});
it('from collection as alias, load and separator without space | should list separator and next keywords', done => {
rqlTestUtils.autoComplete(`from Orders as o
load o.Company as c,|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, aliasesList.slice(0, 2));
assert.equal(lastKeyword.keyword, "load");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 1);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.equal(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders", c: "Company"});
done();
});
});
it('from collection as alias, load and separator | should list separator and next keywords', done => {
rqlTestUtils.autoComplete(`from Orders as o
load o.Company as c, |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, aliasesList.slice(0, 2));
assert.equal(lastKeyword.keyword, "load");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 1);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.equal(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders", c: "Company"});
done();
});
});
it('from collection as alias, where | should list aliases with functions', done => {
rqlTestUtils.autoComplete(`from Orders as o
load o.Company as c, o.Employee as e, o.ShipVia as s
select |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, aliasesListWithFunctions);
assert.equal(lastKeyword.keyword, "select");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 1);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.equal(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders", c: "Company", e: "Employee", s: "ShipVia"});
done();
});
});
it('from collection as alias without as and without space', done => {
rqlTestUtils.autoComplete(`from Orders o|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "o");
assert.deepEqual(wordlist, afterFromList);
assert.equal(lastKeyword.keyword, "from");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('from collection as alias without as | should list next keywords', done => {
rqlTestUtils.autoComplete(`from Orders o |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterFromAsList);
assert.equal(lastKeyword.keyword, "from");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 3);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.deepEqual(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders"});
done();
});
});
it('from Collection select | should list fields', done => {
rqlTestUtils.autoComplete("from Orders select |", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsListWithFunctions);
assert.equal(lastKeyword.keyword, "select");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('from Collection select nested field | should list nested fields with in prefix', done => {
rqlTestUtils.autoComplete(`from Orders
select ShipTo.in|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "in");
assert.deepEqual(wordlist, fieldsShipToList);
assert.equal(lastKeyword.keyword, "select");
assert.equal(lastKeyword.dividersCount, 1);
assert.deepEqual(lastKeyword.fieldPrefix, ["ShipTo"]);
done();
});
});
it('from Collection select nested field | without sapce should list fields with the City prefix', done => {
rqlTestUtils.autoComplete(`from Orders
select ShipTo.City|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "City");
assert.deepEqual(wordlist, fieldsShipToList);
assert.equal(lastKeyword.keyword, "select");
assert.equal(lastKeyword.dividersCount, 1);
assert.deepEqual(lastKeyword.fieldPrefix, ["ShipTo"]);
done();
});
});
it('from Collection select multi nested field | without sapce should list fields with the ShipTo.Nested.NestedObject. field prefix', done => {
rqlTestUtils.autoComplete(`from Orders
select ShipTo.Nested.NestedObject.|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, [
{caption: "C2", value: "C2 ", score: 103, meta: "string field"},
{caption: "P2", value: "P2 ", score: 102, meta: "string field"},
{caption: "R2", value: "R2 ", score: 101, meta: "string field"}
]);
assert.equal(lastKeyword.keyword, "select");
assert.equal(lastKeyword.dividersCount, 1);
assert.deepEqual(lastKeyword.fieldPrefix, ["ShipTo", "Nested", "NestedObject"]);
done();
});
});
it('from Collection select nested field | after should list as keyword and next keywords', done => {
rqlTestUtils.autoComplete(`from Orders
select ShipTo.City |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterSelect);
assert.equal(lastKeyword.keyword, "select");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 2);
assert.deepEqual(lastKeyword.fieldPrefix, ["ShipTo"]);
done();
});
});
it('from Collection select nested field with as | should not list anything', done => {
rqlTestUtils.autoComplete(`from Orders
select ShipTo.City as |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.isNull(wordlist);
assert.equal(lastKeyword.keyword, "select");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 3);
assert.deepEqual(lastKeyword.fieldPrefix, ["ShipTo"]);
done();
});
});
it('from Collection select nested field with as specified | should list separator and next keywords', done => {
rqlTestUtils.autoComplete(`from Orders
select ShipTo.City as c |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterSelectAs);
assert.equal(lastKeyword.keyword, "select");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 4);
assert.deepEqual(lastKeyword.fieldPrefix, ["ShipTo"]);
done();
});
});
it('from Collection select nested field | after comma should show more fields', done => {
rqlTestUtils.autoComplete(`from Orders
select ShipTo.City, |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsListWithFunctions);
assert.equal(lastKeyword.keyword, "select");
assert.equal(lastKeyword.dividersCount, 1);
assert.isUndefined(lastKeyword.fieldPrefix);
done();
});
});
it('from Collection select nested field | right after comma should show more fields', done => {
rqlTestUtils.autoComplete(`from Orders
select ShipTo.City,|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsListWithFunctions);
assert.equal(lastKeyword.keyword, "select");
assert.equal(lastKeyword.dividersCount, 1);
assert.isUndefined(lastKeyword.fieldPrefix);
done();
});
});
it('from AllDocs select nested field | after should list as keyword only', done => {
rqlTestUtils.autoComplete(`from @all_docs
select |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, allDocsFieldsList);
assert.equal(lastKeyword.keyword, "select");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 1);
assert.equal(lastKeyword.info.collection, "@all_docs");
assert.isUndefined(lastKeyword.info.index);
assert.isUndefined(lastKeyword.info.alias);
assert.isUndefined(lastKeyword.info.aliases);
done();
});
});
it('from a should get @all_docs', done => {
rqlTestUtils.autoComplete("from a|", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "a");
assert.deepEqual(wordlist, collectionsList);
assert.equal(lastKeyword.keyword, "from");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('from @ should get @all_docs', done => {
rqlTestUtils.autoComplete("from @|", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "@");
assert.deepEqual(wordlist, collectionsList);
assert.equal(lastKeyword.keyword, "from");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('from Collection w | should has w prefix and select the where keyword', done => {
rqlTestUtils.autoComplete(`from Orders
w|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "w");
assert.deepEqual(wordlist, afterFromList);
assert.equal(lastKeyword.keyword, "from");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('from Collection w| without space should has w prefix and select the where keyword', done => {
rqlTestUtils.autoComplete(`from Orders
w|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "w");
assert.deepEqual(wordlist, afterFromList);
assert.equal(lastKeyword.keyword, "from");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('After where| without space should has where prefix and should complete itself', done => {
rqlTestUtils.autoComplete(`from Orders
where|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "where");
assert.deepEqual(wordlist, afterWhereWithoutSpaceList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 0);
done();
});
});
it('from Collection where | should list fields', done => {
rqlTestUtils.autoComplete("from Orders where |", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, whereFieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After where field without space | should list itself with prefix', done => {
rqlTestUtils.autoComplete(`from Orders
where OrderedAt|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "OrderedAt");
assert.deepEqual(wordlist, whereFieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After where field | should list binary operators', done => {
rqlTestUtils.autoComplete(`from Orders
where Freight |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, queryCompleter.whereOperators);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('After where field and equal operator without space | should list binray operators with prefix', done => {
rqlTestUtils.autoComplete(`from Orders
where OrderedAt =|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "=");
assert.deepEqual(wordlist, queryCompleter.whereOperators);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it.skip('After where field and equal operator | ?????????????????????????????', done => {
rqlTestUtils.autoComplete(`from Orders
where OrderedAt = |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it.skip('After where field and in operator | ?????????????????????????????', done => {
rqlTestUtils.autoComplete(`from Orders
where OrderedAt in |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it.skip('After where field and in operator | ?????????????????????????????', done => {
rqlTestUtils.autoComplete(`from Orders
where OrderedAt in (|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it.skip('After where field and all in operator | ?????????????????????????????', done => {
rqlTestUtils.autoComplete(`from Orders
where OrderedAt all in |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it.skip('After where field and all in operator | ?????????????????????????????', done => {
rqlTestUtils.autoComplete(`from Orders
where OrderedAt all in (|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it.skip('After where field and between operator | ?????????????????????????????', done => {
rqlTestUtils.autoComplete(`from Orders
where OrderedAt between |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it.skip('After where field and between operator 2 | ?????????????????????????????', done => {
rqlTestUtils.autoComplete(`from Orders
where OrderedAt between (1) |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it.skip('After where field and between operator 3 | ?????????????????????????????', done => {
rqlTestUtils.autoComplete(`from Orders
where OrderedAt between (1) and |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it.skip('After where field and between operator 4 | ?????????????????????????????', done => {
rqlTestUtils.autoComplete(`from Orders
where OrderedAt between (1) and (2) |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('After where function without open parentheses | should list itself', done => {
rqlTestUtils.autoComplete(`from Orders
where search|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "search");
assert.deepEqual(wordlist, whereFieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.whereFunction, "search");
assert.equal(lastKeyword.whereFunctionParameters, 0);
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After where function first parameter | should list fields without where functions', done => {
rqlTestUtils.autoComplete(`from Orders
where search(|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.whereFunction, "search");
assert.equal(lastKeyword.whereFunctionParameters, 1);
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After where function first parameter with prefix | should list itself with prefix.', done => {
rqlTestUtils.autoComplete(`from Orders
where search(OrderedAt|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "OrderedAt");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.whereFunction, "search");
assert.equal(lastKeyword.whereFunctionParameters, 1);
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After where function second parameter without space | should list terms. TODO.', done => {
rqlTestUtils.autoComplete(`from Orders
where search(OrderedAt,|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.isNull(wordlist);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.whereFunction, "search");
assert.equal(lastKeyword.whereFunctionParameters, 2);
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After where function second parameter | should list terms. TODO.', done => {
rqlTestUtils.autoComplete(`from Orders
where search(OrderedAt, |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.isNull(wordlist);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.whereFunction, "search");
assert.equal(lastKeyword.whereFunctionParameters, 2);
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After where function third parameter | should list OR and AND.', done => {
rqlTestUtils.autoComplete(`from Orders
where search(OrderedAt, '1996*', |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, searchOrAndList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.whereFunction, "search");
assert.equal(lastKeyword.whereFunctionParameters, 3);
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After where function third parameter with prefix | should list OR and AND with prefix.', done => {
rqlTestUtils.autoComplete(`from Orders
where search(OrderedAt , '1996*' , and|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "and");
assert.deepEqual(wordlist, searchOrAndList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.whereFunction, "search");
assert.equal(lastKeyword.whereFunctionParameters, 3);
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After where function without space | should list binary operation and next keywords', done => {
rqlTestUtils.autoComplete(`from Orders
where search(OrderedAt, '1996*')|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterWhereList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.whereFunction, "search");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('After where function | should list binary operation and next keywords', done => {
rqlTestUtils.autoComplete(`from Orders
where search(OrderedAt, '1996*') |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterWhereList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.whereFunction, "search");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('After where function | complex combination of where functions', done => {
rqlTestUtils.autoComplete(`from Orders as o
where search(OrderedAt, "*1997*", or) or Freight = "" or (Freight = "" or Freight = "")
and (Freight = "" and Freight = "") and search(OrderedAt, "*1997*", and)|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterWhereListWithFromAs);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.binaryOperation, "and");
assert.equal(lastKeyword.whereFunction, "search");
assert.equal(lastKeyword.whereFunctionParameters, 3);
assert.equal(lastKeyword.parentheses, 0);
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 2);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.deepEqual(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders"});
done();
});
});
it('After where | should list binary operation and next keywords', done => {
rqlTestUtils.autoComplete(`from Orders
where ShipTo.Country = 'France' |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterWhereList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 4);
//TODO: assert.equal(lastKeyword.operator, "=");
done();
});
});
it('WHERE and than AND without space should have AND prefix', done => {
rqlTestUtils.autoComplete(`from Orders
where ShipTo.Country = 'France' and|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "and");
assert.deepEqual(wordlist, afterWhereList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 0);
assert.equal(lastKeyword.binaryOperation, "and");
assert.isFalse(lastKeyword.asSpecified);
done();
});
});
it('WHERE and than AND | should list fields and NOT keyword', done => {
rqlTestUtils.autoComplete(`from Orders
where ShipTo.Country = 'France' and |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, whereFieldsListAfterOrAnd);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('WHERE and than OR | should list fields and NOT keyword', done => {
rqlTestUtils.autoComplete(`from Orders
where ShipTo.Country = 'France' or |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, whereFieldsListAfterOrAnd);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('WHERE and than AND and NOT | should list fields with where functions', done => {
rqlTestUtils.autoComplete(`from Orders
where ShipTo.Country = 'France' and not |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, whereFieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('WHERE and than OR and NOT | should list fields with where functions', done => {
rqlTestUtils.autoComplete(`from Orders
where ShipTo.Country = 'France' or not |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, whereFieldsList);
assert.equal(lastKeyword.keyword, "where");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After order| without space should has order prefix and should complete itself', done => {
rqlTestUtils.autoComplete(`from Orders
order|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "order");
assert.deepEqual(wordlist, afterOrderWithoutSpaceList);
assert.equal(lastKeyword.keyword, "order");
assert.equal(lastKeyword.dividersCount, 0);
done();
});
});
it('After order | should list BY', done => {
rqlTestUtils.autoComplete(`from Orders
order |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterOrderOrGroupList);
assert.equal(lastKeyword.keyword, "order");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After order by| without space should has BY prefix and should complete itself', done => {
rqlTestUtils.autoComplete(`from Orders
order by|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "by");
assert.deepEqual(wordlist, afterOrderOrGroupList);
assert.equal(lastKeyword.keyword, "order by");
assert.equal(lastKeyword.dividersCount, 0);
done();
});
});
it('After order by | should list fields and functions', done => {
rqlTestUtils.autoComplete(`from Orders
order by |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, orderByFieldsList);
assert.equal(lastKeyword.keyword, "order by");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After order by field| without space should list the fields with prefix', done => {
rqlTestUtils.autoComplete(`from Orders
order by OrderedAt|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "OrderedAt");
assert.deepEqual(wordlist, orderByFieldsList);
assert.equal(lastKeyword.keyword, "order by");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it.skip('After order by field with dot | without space should list the fields without the functions', done => {
rqlTestUtils.autoComplete(`from Orders
order by OrderedAt.|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, orderByFieldsList);
assert.equal(lastKeyword.keyword, "order by");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After order by field | should list the sort functions and comma separator', done => {
rqlTestUtils.autoComplete(`from Orders
order by OrderedAt |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, orderBySortList);
assert.equal(lastKeyword.keyword, "order by");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('After order by field and desc| without space should list desc prefix', done => {
rqlTestUtils.autoComplete(`from Orders
order by OrderedAt desc|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "desc");
assert.deepEqual(wordlist, orderBySortList);
assert.equal(lastKeyword.keyword, "order by");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('After order by field with sort | should list the comma separator without the sort functions', done => {
rqlTestUtils.autoComplete(`from Orders
order by OrderedAt desc |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, orderBySortAfterList);
assert.equal(lastKeyword.keyword, "order by");
assert.equal(lastKeyword.dividersCount, 3);
done();
});
});
it('After order by field and comma | should list the fields', done => {
rqlTestUtils.autoComplete(`from Orders
order by OrderedAt, |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, orderByFieldsList);
assert.equal(lastKeyword.keyword, "order by");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After order by field and comma without space | should list the fields', done => {
rqlTestUtils.autoComplete(`from Orders
order by OrderedAt,|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, orderByFieldsList);
assert.equal(lastKeyword.keyword, "order by");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After order by field, sort and comma without space | should list the fields', done => {
rqlTestUtils.autoComplete(`from Orders
order by OrderedAt desc, |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, orderByFieldsList);
assert.equal(lastKeyword.keyword, "order by");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After order by field, sort and comma without space | should list the fields', done => {
rqlTestUtils.autoComplete(`from Orders
order by OrderedAt desc,|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, orderByFieldsList);
assert.equal(lastKeyword.keyword, "order by");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After include| without space should complete itself with prefix', done => {
rqlTestUtils.autoComplete(`from Orders
include|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "include");
assert.deepEqual(wordlist, afterIncludeWithoutSpaceList);
assert.equal(lastKeyword.keyword, "include");
assert.equal(lastKeyword.dividersCount, 0);
done();
});
});
it('After include | should list fields', done => {
rqlTestUtils.autoComplete(`from Orders
include |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "include");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After include and field without space | should list fields with prefix', done => {
rqlTestUtils.autoComplete(`from Orders
include Employee|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "Employee");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "include");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After include and field | should not list anything', done => {
rqlTestUtils.autoComplete(`from Orders
include Employee |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.isNull(wordlist);
assert.equal(lastKeyword.keyword, "include");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('After group| without space should has group prefix and should complete itself', done => {
rqlTestUtils.autoComplete(`from Orders
group|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "group");
assert.deepEqual(wordlist, afterGroupWithoutSpaceList);
assert.equal(lastKeyword.keyword, "group");
assert.equal(lastKeyword.dividersCount, 0);
done();
});
});
it('After group | should list BY', done => {
rqlTestUtils.autoComplete(`from Orders
group |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterOrderOrGroupList);
assert.equal(lastKeyword.keyword, "group");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After group by| without space should has BY prefix and should complete itself', done => {
rqlTestUtils.autoComplete(`from Orders
group by|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "by");
assert.deepEqual(wordlist, afterOrderOrGroupList);
assert.equal(lastKeyword.keyword, "group by");
assert.equal(lastKeyword.dividersCount, 0);
done();
});
});
it('After group by | should list fields', done => {
rqlTestUtils.autoComplete(`from Orders
group by |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "group by");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After group by without space | should list itself with prefix', done => {
rqlTestUtils.autoComplete(`from Orders
group by ShippedAt|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "ShippedAt");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "group by");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After group by | should list comma or next keywords', done => {
rqlTestUtils.autoComplete(`from Orders
group by ShippedAt |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, groupByAfterList);
assert.equal(lastKeyword.keyword, "group by");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('After group by comma without space | should fields', done => {
rqlTestUtils.autoComplete(`from Orders
group by ShippedAt,|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "group by");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('After group by comma | should fields', done => {
rqlTestUtils.autoComplete(`from Orders
group by ShippedAt, |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, fieldsList);
assert.equal(lastKeyword.keyword, "group by");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('from index should get index names', done => {
rqlTestUtils.autoComplete("from index |", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, indexesList);
assert.equal(lastKeyword.keyword, "from index");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('from index inside index name should complete with prefix', done => {
rqlTestUtils.autoComplete("from index 'Orders/Tot|", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "'Orders/Tot");
assert.deepEqual(wordlist, indexesList);
assert.equal(lastKeyword.keyword, "from index");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('from index after index name without space should complete with prefix', done => {
rqlTestUtils.autoComplete("from index 'Orders/Totals'|", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "'Orders/Totals'");
assert.deepEqual(wordlist, indexesList);
assert.equal(lastKeyword.keyword, "from index");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('from index after index name should complete with after from', done => {
rqlTestUtils.autoComplete("from index 'Orders/Totals' |", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterFromIndexList);
assert.equal(lastKeyword.keyword, "from index");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('from index as without space | should list as with prefix', done => {
rqlTestUtils.autoComplete("from index 'Orders/Totals' as|", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "as");
assert.deepEqual(wordlist, afterFromIndexList);
assert.equal(lastKeyword.keyword, "from index");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('from index as | should not list anything', done => {
rqlTestUtils.autoComplete("from index 'Orders/Totals' as |", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(errors, ["empty completion"]);
assert.isNull(wordlist);
assert.equal(lastKeyword.keyword, "from index");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 3);
done();
});
});
it('from index as alias without space', done => {
rqlTestUtils.autoComplete(`from index 'Orders/Totals' as o|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "o");
assert.deepEqual(errors, ["empty completion"]);
assert.isNull(wordlist);
assert.equal(lastKeyword.keyword, "from index");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 3);
done();
});
});
it('from index as alias | should list next keywords', done => {
rqlTestUtils.autoComplete(`from index 'Orders/Totals' as o |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterFromIndexAsList);
assert.equal(lastKeyword.keyword, "from index");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 4);
done();
});
});
it('from index as alias without as and without space', done => {
rqlTestUtils.autoComplete(`from index 'Orders/Totals' o|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "o");
assert.deepEqual(wordlist, afterFromIndexList);
assert.equal(lastKeyword.keyword, "from index");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('from index as alias without as | should list next keywords', done => {
rqlTestUtils.autoComplete(`from index 'Orders/Totals' o |`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterFromIndexAsList);
assert.equal(lastKeyword.keyword, "from index");
assert.isFalse(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 3);
done();
});
});
it('show fields of index', done => {
rqlTestUtils.autoComplete("from index 'Orders/Totals' select |", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, [
{caption: "Employee", value: "Employee ", score: 101, meta: "field"},
{caption: "Company", value: "Company ", score: 101, meta: "field"},
{caption: "Total", value: "Total ", score: 101, meta: "field"}
].concat(functionsList));
assert.equal(lastKeyword.keyword, "select");
assert.equal(lastKeyword.dividersCount, 1);
assert.isUndefined(lastKeyword.fieldPrefix);
done();
});
});
it('dec| should list the declare function with prefix', done => {
rqlTestUtils.autoComplete(`dec|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "dec");
assert.deepEqual(wordlist, emptyList);
assert.isNull(lastKeyword);
done();
});
});
it('declare should suggest function', done => {
rqlTestUtils.autoComplete("declare |", northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, [
{caption: "function", value: "function ", score: 0, meta: "keyword"},
]);
assert.equal(lastKeyword.keyword, "declare");
assert.equal(lastKeyword.dividersCount, 1);
done();
});
});
it('decalre function should list empty list', done => {
rqlTestUtils.autoComplete(`declare function CustomFunctionName(){}
|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, emptyList);
assert.equal(lastKeyword.keyword, "declare function");
assert.equal(lastKeyword.dividersCount, 3);
done();
});
});
it('decalre function without name should list empty list', done => {
rqlTestUtils.autoComplete(`declare function(){}
|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, emptyList);
assert.equal(lastKeyword.keyword, "declare function");
assert.equal(lastKeyword.dividersCount, 2);
done();
});
});
it('decalre function with 3 new lines should list empty list', done => {
rqlTestUtils.autoComplete(`declare function Name() {
}
|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, emptyList);
assert.equal(lastKeyword.keyword, "declare function");
assert.equal(lastKeyword.dividersCount, 5);
done();
});
});
it('decalre function with nested function. After semi colon | should not list anything', done => {
rqlTestUtils.autoComplete(`declare function Name() {
var a = "s{tri}}}ng'";
var b = function () {
var a = "";
}
var c = 's{tri}}}ng"';
|
}
from Orders as o
where o.Company == ""
load o.Company as c, o.ShipTo as e, o.ShipVia as s
`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.isNull(wordlist);
assert.equal(lastKeyword.keyword, "declare function");
assert.equal(lastKeyword.dividersCount, 9);
done();
});
});
it('decalre function with nested function. After error | should not list anything', done => {
rqlTestUtils.autoComplete(`declare function Name() {
var a = "s{tri}}}ng'";
var b = function () {
var a = "";
}
var c = 's{tri}}}ng"';
#|
}
from Orders as o
where o.Company == ""
load o.Company as c, o.ShipTo as e, o.ShipVia as s
`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.isNull(wordlist);
assert.equal(lastKeyword.keyword, "declare function");
assert.equal(lastKeyword.dividersCount, 9);
done();
});
});
it('decalre function with nested function with error. After load | should detect the load keyword', done => {
rqlTestUtils.autoComplete(`declare function Name() {
var a = "s{tri}}}ng'";
var b = function () {
var a = "";
}
var c = 's{tri}}}ng"';
#
}
from Orders as o
where o.Company == ""
load o.Company as c, o.ShipTo as e, o.ShipVia as s
|`, northwindProvider(), (errors, wordlist, prefix, lastKeyword) => {
assert.equal(prefix, "");
assert.deepEqual(wordlist, afterLoad);
assert.equal(lastKeyword.keyword, "load");
assert.isTrue(lastKeyword.asSpecified);
assert.equal(lastKeyword.dividersCount, 4);
assert.equal(lastKeyword.info.collection, "Orders");
assert.isUndefined(lastKeyword.info.index);
assert.equal(lastKeyword.info.alias, "o");
assert.deepEqual(lastKeyword.info.aliases, {o: "Orders"});
done();
});
});
});
|
Site Targeted Press Coated Delivery of Methylprednisolone Using Eudragit RS 100 and Chitosan for Treatment of Colitis. BACKGROUND Inflammatory bowel disease (IBD) is one of the five most prevalent gastrointestinal disease burdens which commonly require lifetime care. Worldwide incidence rate of ulcerative colitis and Crohn's disease is about 16.8% and 13.4% respectively. Colitis is an inflammation of the colon. Colon targeted drug delivery will direct the drug to the colon. The drug will reach at the site of action and hence its side effects as well as dose can be reduced. Recent patent describes treatment of ulcerative colitis using anti CD3 antibodies, with nicotine and anti-depressant drugs, budesonide foam etc. OBJECTIVE Present study deals with optimization of site targeted methylprednisolone delivery for treatment of colitis. METHOD Chitosan and Eudragit RS 100 were used as coating polymers. Tablets were prepared by press coated technology. The core tablets contain drug, avicel as binder, croscarmellose sodium as super disintegrant and dicalcium phosphate as diluent. Drug excipient compatibility was carried out using FTIR, UV and DSC. Design of experiment was used to optimize the formulation. Tablets were evaluated for thickness, weight variation, hardness, swelling index, in-vitro drug release and release of drug in simulated media. RESULTS Optimized batch (B2) contained chitosan 40% and eudragit RS 100 17.5%. B2 showed in-vitro drug release 85.65 ± 7.6% in 6.8 pH phosphate buffer and 96.7 ±9.1% in simulated media after 7.5 hours. CONCLUSION In-vivo x-ray placebo study for formulation B2 had shown that the tablet reached to the ascending colon after 5 hours. This indicated a potential site targeted delivery of optimized batch B2. |
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2018 Jérémie Dumas <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
////////////////////////////////////////////////////////////////////////////////
#include "ImGuiMenu.h"
#include "ImGuiHelpers.h"
#include <igl/project.h>
#include <imgui/imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <imgui_fonts_droid_sans.h>
#include <GLFW/glfw3.h>
#include <iostream>
////////////////////////////////////////////////////////////////////////////////
namespace igl
{
namespace opengl
{
namespace glfw
{
namespace imgui
{
IGL_INLINE void ImGuiMenu::init(igl::opengl::glfw::Viewer *_viewer)
{
ViewerPlugin::init(_viewer);
// Setup ImGui binding
if (_viewer)
{
IMGUI_CHECKVERSION();
if (!context_)
{
// Single global context by default, but can be overridden by the user
static ImGuiContext * __global_context = ImGui::CreateContext();
context_ = __global_context;
}
const char* glsl_version = "#version 150";
ImGui_ImplGlfw_InitForOpenGL(viewer->window, false);
ImGui_ImplOpenGL3_Init(glsl_version);
ImGui::GetIO().IniFilename = nullptr;
ImGui::StyleColorsDark();
ImGuiStyle& style = ImGui::GetStyle();
style.FrameRounding = 5.0f;
reload_font();
}
}
IGL_INLINE void ImGuiMenu::reload_font(int font_size)
{
hidpi_scaling_ = hidpi_scaling();
pixel_ratio_ = pixel_ratio();
ImGuiIO& io = ImGui::GetIO();
io.Fonts->Clear();
io.Fonts->AddFontFromMemoryCompressedTTF(droid_sans_compressed_data,
droid_sans_compressed_size, font_size * hidpi_scaling_);
io.FontGlobalScale = 1.0 / pixel_ratio_;
}
IGL_INLINE void ImGuiMenu::shutdown()
{
// Cleanup
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
// User is responsible for destroying context if a custom context is given
// ImGui::DestroyContext(*context_);
}
IGL_INLINE bool ImGuiMenu::pre_draw()
{
glfwPollEvents();
// Check whether window dpi has changed
float scaling = hidpi_scaling();
if (std::abs(scaling - hidpi_scaling_) > 1e-5)
{
reload_font();
ImGui_ImplOpenGL3_DestroyDeviceObjects();
}
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
return false;
}
IGL_INLINE bool ImGuiMenu::post_draw()
{
draw_menu();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
return false;
}
IGL_INLINE void ImGuiMenu::post_resize(int width, int height)
{
if (context_)
{
ImGui::GetIO().DisplaySize.x = float(width);
ImGui::GetIO().DisplaySize.y = float(height);
}
}
// Mouse IO
IGL_INLINE bool ImGuiMenu::mouse_down(int button, int modifier)
{
ImGui_ImplGlfw_MouseButtonCallback(viewer->window, button, GLFW_PRESS, modifier);
return ImGui::GetIO().WantCaptureMouse;
}
IGL_INLINE bool ImGuiMenu::mouse_up(int button, int modifier)
{
//return ImGui::GetIO().WantCaptureMouse;
// !! Should not steal mouse up
return false;
}
IGL_INLINE bool ImGuiMenu::mouse_move(int mouse_x, int mouse_y)
{
return ImGui::GetIO().WantCaptureMouse;
}
IGL_INLINE bool ImGuiMenu::mouse_scroll(float delta_y)
{
ImGui_ImplGlfw_ScrollCallback(viewer->window, 0.f, delta_y);
return ImGui::GetIO().WantCaptureMouse;
}
// Keyboard IO
IGL_INLINE bool ImGuiMenu::key_pressed(unsigned int key, int modifiers)
{
ImGui_ImplGlfw_CharCallback(nullptr, key);
return ImGui::GetIO().WantCaptureKeyboard;
}
IGL_INLINE bool ImGuiMenu::key_down(int key, int modifiers)
{
ImGui_ImplGlfw_KeyCallback(viewer->window, key, 0, GLFW_PRESS, modifiers);
return ImGui::GetIO().WantCaptureKeyboard;
}
IGL_INLINE bool ImGuiMenu::key_up(int key, int modifiers)
{
ImGui_ImplGlfw_KeyCallback(viewer->window, key, 0, GLFW_RELEASE, modifiers);
return ImGui::GetIO().WantCaptureKeyboard;
}
// Draw menu
IGL_INLINE void ImGuiMenu::draw_menu()
{
// Text labels
draw_labels_window();
// Viewer settings
if (callback_draw_viewer_window) { callback_draw_viewer_window(); }
else { draw_viewer_window(); }
// Other windows
if (callback_draw_custom_window) { callback_draw_custom_window(); }
else { draw_custom_window(); }
}
IGL_INLINE void ImGuiMenu::draw_viewer_window()
{
float menu_width = 180.f * menu_scaling();
ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f), ImGuiSetCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(0.0f, 0.0f), ImGuiSetCond_FirstUseEver);
ImGui::SetNextWindowSizeConstraints(ImVec2(menu_width, -1.0f), ImVec2(menu_width, -1.0f));
bool _viewer_menu_visible = true;
ImGui::Begin(
"Viewer", &_viewer_menu_visible,
ImGuiWindowFlags_NoSavedSettings
| ImGuiWindowFlags_AlwaysAutoResize
);
ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.4f);
if (callback_draw_viewer_menu) { callback_draw_viewer_menu(); }
else { draw_viewer_menu(); }
ImGui::PopItemWidth();
ImGui::End();
}
IGL_INLINE void ImGuiMenu::draw_viewer_menu()
{
// Workspace
if (ImGui::CollapsingHeader("Workspace", ImGuiTreeNodeFlags_DefaultOpen))
{
float w = ImGui::GetContentRegionAvailWidth();
float p = ImGui::GetStyle().FramePadding.x;
if (ImGui::Button("Load##Workspace", ImVec2((w-p)/2.f, 0)))
{
viewer->load_scene();
}
ImGui::SameLine(0, p);
if (ImGui::Button("Save##Workspace", ImVec2((w-p)/2.f, 0)))
{
viewer->save_scene();
}
}
// Mesh
if (ImGui::CollapsingHeader("Mesh", ImGuiTreeNodeFlags_DefaultOpen))
{
float w = ImGui::GetContentRegionAvailWidth();
float p = ImGui::GetStyle().FramePadding.x;
if (ImGui::Button("Load##Mesh", ImVec2((w-p)/2.f, 0)))
{
viewer->open_dialog_load_mesh();
}
ImGui::SameLine(0, p);
if (ImGui::Button("Save##Mesh", ImVec2((w-p)/2.f, 0)))
{
viewer->open_dialog_save_mesh();
}
}
// Viewing options
if (ImGui::CollapsingHeader("Viewing Options", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ImGui::Button("Center object", ImVec2(-1, 0)))
{
viewer->core().align_camera_center(viewer->data().V, viewer->data().F);
}
if (ImGui::Button("Snap canonical view", ImVec2(-1, 0)))
{
viewer->snap_to_canonical_quaternion();
}
// Zoom
ImGui::PushItemWidth(80 * menu_scaling());
ImGui::DragFloat("Zoom", &(viewer->core().camera_zoom), 0.05f, 0.1f, 20.0f);
// Select rotation type
int rotation_type = static_cast<int>(viewer->core().rotation_type);
static Eigen::Quaternionf trackball_angle = Eigen::Quaternionf::Identity();
static bool orthographic = true;
if (ImGui::Combo("Camera Type", &rotation_type, "Trackball\0Two Axes\0002D Mode\0\0"))
{
using RT = igl::opengl::ViewerCore::RotationType;
auto new_type = static_cast<RT>(rotation_type);
if (new_type != viewer->core().rotation_type)
{
if (new_type == RT::ROTATION_TYPE_NO_ROTATION)
{
trackball_angle = viewer->core().trackball_angle;
orthographic = viewer->core().orthographic;
viewer->core().trackball_angle = Eigen::Quaternionf::Identity();
viewer->core().orthographic = true;
}
else if (viewer->core().rotation_type == RT::ROTATION_TYPE_NO_ROTATION)
{
viewer->core().trackball_angle = trackball_angle;
viewer->core().orthographic = orthographic;
}
viewer->core().set_rotation_type(new_type);
}
}
// Orthographic view
ImGui::Checkbox("Orthographic view", &(viewer->core().orthographic));
ImGui::PopItemWidth();
}
// Helper for setting viewport specific mesh options
auto make_checkbox = [&](const char *label, unsigned int &option)
{
return ImGui::Checkbox(label,
[&]() { return viewer->core().is_set(option); },
[&](bool value) { return viewer->core().set(option, value); }
);
};
// Draw options
if (ImGui::CollapsingHeader("Draw Options", ImGuiTreeNodeFlags_DefaultOpen))
{
if (ImGui::Checkbox("Face-based", &(viewer->data().face_based)))
{
viewer->data().dirty = MeshGL::DIRTY_ALL;
}
make_checkbox("Show texture", viewer->data().show_texture);
if (ImGui::Checkbox("Invert normals", &(viewer->data().invert_normals)))
{
viewer->data().dirty |= igl::opengl::MeshGL::DIRTY_NORMAL;
}
make_checkbox("Show overlay", viewer->data().show_overlay);
make_checkbox("Show overlay depth", viewer->data().show_overlay_depth);
ImGui::ColorEdit4("Background", viewer->core().background_color.data(),
ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_PickerHueWheel);
ImGui::ColorEdit4("Line color", viewer->data().line_color.data(),
ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_PickerHueWheel);
ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.3f);
ImGui::DragFloat("Shininess", &(viewer->data().shininess), 0.05f, 0.0f, 100.0f);
ImGui::PopItemWidth();
}
// Overlays
if (ImGui::CollapsingHeader("Overlays", ImGuiTreeNodeFlags_DefaultOpen))
{
make_checkbox("Wireframe", viewer->data().show_lines);
make_checkbox("Fill", viewer->data().show_faces);
ImGui::Checkbox("Show vertex labels", &(viewer->data().show_vertid));
ImGui::Checkbox("Show faces labels", &(viewer->data().show_faceid));
}
}
IGL_INLINE void ImGuiMenu::draw_labels_window()
{
// Text labels
ImGui::SetNextWindowPos(ImVec2(0,0), ImGuiSetCond_Always);
ImGui::SetNextWindowSize(ImGui::GetIO().DisplaySize, ImGuiSetCond_Always);
bool visible = true;
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0,0,0,0));
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0);
ImGui::Begin("ViewerLabels", &visible,
ImGuiWindowFlags_NoTitleBar
| ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoMove
| ImGuiWindowFlags_NoScrollbar
| ImGuiWindowFlags_NoScrollWithMouse
| ImGuiWindowFlags_NoCollapse
| ImGuiWindowFlags_NoSavedSettings
| ImGuiWindowFlags_NoInputs);
for (const auto & data : viewer->data_list)
{
draw_labels(data);
}
ImGui::End();
ImGui::PopStyleColor();
ImGui::PopStyleVar();
}
IGL_INLINE void ImGuiMenu::draw_labels(const igl::opengl::ViewerData &data)
{
if (data.show_vertid)
{
for (int i = 0; i < data.V.rows(); ++i)
{
draw_text(
data.V.row(i),
data.V_normals.row(i),
std::to_string(i),
data.label_color);
}
}
if (data.show_faceid)
{
for (int i = 0; i < data.F.rows(); ++i)
{
Eigen::RowVector3d p = Eigen::RowVector3d::Zero();
for (int j = 0; j < data.F.cols(); ++j)
{
p += data.V.row(data.F(i,j));
}
p /= (double) data.F.cols();
draw_text(
p,
data.F_normals.row(i),
std::to_string(i),
data.label_color);
}
}
if (data.labels_positions.rows() > 0)
{
for (int i = 0; i < data.labels_positions.rows(); ++i)
{
draw_text(
data.labels_positions.row(i),
Eigen::Vector3d(0.0,0.0,0.0),
data.labels_strings[i],
data.label_color);
}
}
}
IGL_INLINE void ImGuiMenu::draw_text(
Eigen::Vector3d pos,
Eigen::Vector3d normal,
const std::string &text,
const Eigen::Vector4f color)
{
pos += normal * 0.005f * viewer->core().object_scale;
Eigen::Vector3f coord = igl::project(Eigen::Vector3f(pos.cast<float>()),
viewer->core().view, viewer->core().proj, viewer->core().viewport);
// Draw text labels slightly bigger than normal text
ImDrawList* drawList = ImGui::GetWindowDrawList();
drawList->AddText(ImGui::GetFont(), ImGui::GetFontSize() * 1.2,
ImVec2(coord[0]/pixel_ratio_, (viewer->core().viewport[3] - coord[1])/pixel_ratio_),
ImGui::GetColorU32(ImVec4(
color(0),
color(1),
color(2),
color(3))),
&text[0], &text[0] + text.size());
}
IGL_INLINE float ImGuiMenu::pixel_ratio()
{
// Computes pixel ratio for hidpi devices
int buf_size[2];
int win_size[2];
GLFWwindow* window = glfwGetCurrentContext();
glfwGetFramebufferSize(window, &buf_size[0], &buf_size[1]);
glfwGetWindowSize(window, &win_size[0], &win_size[1]);
return (float) buf_size[0] / (float) win_size[0];
}
IGL_INLINE float ImGuiMenu::hidpi_scaling()
{
// Computes scaling factor for hidpi devices
float xscale, yscale;
GLFWwindow* window = glfwGetCurrentContext();
glfwGetWindowContentScale(window, &xscale, &yscale);
return 0.5 * (xscale + yscale);
}
} // end namespace
} // end namespace
} // end namespace
} // end namespace
|
Association of angiopoietin-like protein 3 with hepatic triglyceride lipase and lipoprotein lipase activities in human plasma Background The relationship between plasma angiopoietin-like protein 3 (ANGPTL3), and lipoprotein lipase (LPL) activity and hepatic triglyceride lipase (HTGL) activity has not been investigated in the metabolism of remnant lipoproteins (RLPs) and high-density lipoprotein (HDL) in human plasma. Methods ANGPTL3, LPL activity, HTGL activity, RLP-C and RLP-TG and small, dense LDL-cholesterol (sd LDL-C) were measured in 20 overweight and obese subjects in the fasting and postprandial states. Results Plasma TG, RLP-C, RLP-TG and sd LDL-C were inversely correlated with LPL activity both in the fasting and postprandial states, but not correlated with HTGL activity and ANGPTL3. However, plasma HDL-C was positively correlated with LPL activity both in the fasting and postprandial states, while inversely correlated with HTGL activity. ANGPTL3 was inversely correlated with HTGL activity both in the fasting and postprandial states, but not correlated with LPL activity. Conclusion HTGL plays a major role in HDL metabolism, but not RLP metabolism. These findings suggest that ANGPTL3 is strongly associated with the inhibition of HTGL activity and regulates HDL metabolism, but not associated with the inhibition of LPL activity for the metabolism of RLPs in human plasma. |
Prolonged hyperthermic seizures in rats with focal cortical dysplasia lead to hemispheric and hippocampal asymmetry Rationale: Atypical febrile seizures have been associated, in retrospective studies, with the mesial temporal lobe epilepsy. Recently, we have demonstrated that a cortical microgyrus predisposes immature rats to prolonged hyperthermic seizures (HS) and chronic epilepsy. The purpose of this study is to investigate the effects of prolonged HS on brain development and to assess the impact of seizure duration. Methods: Freeze lesions (focal microgyri) were induced in the right fronto-parietal cortex of rats on postnatal day (P)1. HS were then induced at P10 by exposure to moderately-heated dry air. To evaluate hippocampal and extrahippocampal asymmetry, right and left hemispheric, cortical, subcortical and hippocampal volumes were estimated at P22. The degree of asymmetry was estimated by calculating a ratio between the volumes of the right and left structures. To assess the role of seizure duration, we prevented the prolonged HS by administering diazepam to a subgroup of rats. Results: Hemispheric asymmetry ipsilateral to the lesion was observed in lesioned rats with HS. When their hemispheres were divided into cortical and subcortical volumes, asymmetry was only seen in the cortex. However, when the hippocampal volume was assessed independently, hippocampal asymmetry was observed. Of these rats, 29% (5/17) had severe hippocampal atrophy. Decreasing the duration of the HS did not significantly reduce the overall hemispheric asymmetry or the cortical asymmetry. However, hippocampal asymmetry was not observed in lesioned rats with shorthened HS. No hippocampal or extrahippocampal asymmetries were seen in any other control groups. Conclusion: Our findings support a link between the prolonged febrile seizure and volume abnormalities in the predisposed brain. More importantly, we demonstrate that early |
Oscillations at odds in the heart Oscillations are everywhere in biologythe cell cycle, the heart beat, circadian rhythms, fertility cycleslife could not exist without them. They arise from time delays in the feedback circuits essential for regulating biological processes. As important as oscillations are to normal physiology C o m m e n t a r y Oscillations are everywhere in biology-the cell cycle, the heart beat, circadian rhythms, fertility cycles-life could not exist without them. They arise from time delays in the feedback circuits essential for regulating biological processes. As important as oscillations are to normal physiology, however, too many oscillators can spoil the broth of life. In the heart, the master oscillator is the sinus node, to which excitation-contraction coupling and the metabolic machinery supporting cardiac energetics are both entrained. In this issue, Ganitkevich et al. describe how a classical biological oscillator, the glycolytic oscillator, can come into play during ischemia, and in doing so, compound its pathophysiological consequences. Previous studies have shown that glycolysis is capable of oscillating periodically, thought to be driven by the feedback loop in regulation of the key glycolytic enzyme phosphofructokinase by adenine nucleotides and other metabolites. Glycolytic oscillations have been most extensively characterized in yeast (Higgins, 1964;Hess and Boiteux, 1968), skeletal muscle extracts (Hess and Boiteux, 1971), and pancreatic cells (Westermark and Lansner, 2003;Silva and Yunes, 2006). Glycolytic oscillations in isolated cardiac myocytes were first described by O'Rourke et al., who showed that myocytes deprived of glucose developed oscillations in action potential duration (APD) mediated by activation of sarcolemmal ATP-sensitive K (K ATP ) channels, metabolic sensors that shorten APD to reduce energy consumption when the ATP/ADP ratio falls. Recently, Yang et al. defined the conditions promoting glycolytic oscillations in cardiac myocytes more extensively. Using chemical metabolic inhibitors, they found that when the capacity of oxidative phosphorylation and the creatine kinase (CK) system to stabilize the cellular ATP/ADP ratio becomes compromised, glycolysis is enabled to oscillate due to the feedback of adenine nucleotides on phosphofructokinase when the ATP/ADP ratio is no longer clamped by normally dominant aerobic metabolism. However, in these prior studies (O';;), metabolic Correspondence to James N. Weiss: [email protected] Abbreviations used in this paper: APD, action potential duration; CK, creatine kinase; , mitochondrial membrane potential; ROS, reactive oxygen species. oscillations were induced under physiologically artificial conditions, involving complete glucose removal or chemical metabolic inhibition. Although some of the latter conditions are relevant to acute myocardial ischemia and anoxia, they are not identical to the real thing. The significance of the Ganitkevich et al. study is their demonstration that glycolytic oscillations occur under conditions directly relevant to clinical cardiac pathophysiology. Their elegant picochamber technique allows a single isolated patch-clamped myocyte to be imaged with fluorescent dyes during severe anoxia. Because the myocyte is bathed in only a very small volume of extracellular fluid, anoxic metabolites and ions such as lactate, protons, and K accumulate progressively during anoxia. Thus, an isolated myocyte can be patch-clamped and imaged under conditions that recapitulate fairly accurately the features of genuine acute ischemia (anoxia with metabolite and ion accumulation) in intact cardiac muscle. Under normoxic conditions, mitochondria produce >95% of ATP used by the beating heart, with glycolysis and glycogenolysis generating <5%. High levels of creatine phosphate in heart cells facilitate ATP delivery evenly throughout the cytoplasm by regenerating ADP locally via CK. Adenlyate kinase, which converts two ADPs to AMP and ATP, serves a complementary role in preserving a high ATP/ADP ratio throughout the cytoplasm. However, during acute ischemia or anoxia, mitochondrial control of the ATP/ADP ratio is suppressed by lack of oxygen, and CK is progressively inactivated by reactive oxygen species (ROS) and other factors (;). Anaerobic glycolysis becomes the major source of energy production, despite an inherently limited capacity to meet the full energy needs of the beating heart. The onset of irreversible injury after 20-30 min of acute ischemia coincides with the progressive inhibition of glycolysis due to lactate accumulation and acidosis (;;;Schaefer and Ramasamy, 1997;). During anoxia with maintained coronary perfusion, removal of exogenous glucose as a substrate for glycolysis dramatically oscillations are thought to be mediated by mitochondrial ROS-induced ROS release, involving either inner membrane anion channels () or mitochondrial permeability transitions pores (). Because of the requirement for ROS generation, mitochondrial oscillations are more likely to occur during reperfusion than ischemia, when reoxygenation stimulates a burst of ROS production. However, the evidence for mitochondrial oscillations during genuine ischemia is still indirect (). In summary, when excitation-contraction-metabolism uncoupling occurs, rebellious metabolic oscillators become potentially important factors compounding ischemia reperfusion injury in the heart. The study by Ganitkevich et al. documents that one form of these metabolic oscillations, arising from glycolysis, is directly relevant to acute anoxia and ischemia in isolated cardiac myocytes. The next frontier is to determine whether such metabolic oscillations can be detected during acute ischemia in the intact heart, and if so, whether they play a role in hastening cell death. Detection of metabolic oscillations in intact tissue is technically challenging. Due to electrotonic coupling, APD in tissue represents the average of thousands of cells, so that unless the phase of the underlying cellular metabolic oscillations is synchronized in a region of tissue, APD would not appear to oscillate. Attempts to directly visualize metabolic oscillations during acute ischemia or anoxia in intact cardiac muscle using confocal imaging have so far been unrevealing (). Moreover, changes in or NADH accompanying glycolytic oscillations are expected to be small. New genetically encoded fluorescent ATP/ADP sensors (;) may be the ideal bioprobes to detect whether metabolic oscillations become at odds with the heart beat during acute ischemia/reperfusion in intact heart. If so, the relationship of such oscillations to cardioprotective signaling will become an interesting topic for study. This work was supported by NIH grants 1P01 HL078931 and R01 HL095663. Edward N. Pugh Jr. served as editor. accelerates cardiac injury (). These observations suggest that efficient coupling of glycolytic ATP production to cellular energy needs during acute ischemia and anoxia is crucial in protecting cells from irreversible injury. As long as glycolytic flux remains entrained to the heart beat, the myocyte has a chance to regulate energy balance appropriately. If glycolysis begins to oscillate independently, however, the myocyte loses its ability to match cellular energy demands to energy needs, further exacerbating energy supply-demand imbalance and potentially accelerating the onset of irreversible injury. Ganitkevich et al. also show convincing evidence that when glycolysis oscillates under these conditions, the mitochondrial network secondarily oscillates in response. As glycolytic ATP production waxes, mitochondrial F 1 -F 0 ATP synthase reverses and consumes ATP to support mitochondrial membrane potential (). Conversely, as glycolytic ATP production wanes, mitochondria are less able to maintain and partially depolarize. The metabolic oscillations affect both cellular-and tissue-level functions. At the cellular level, consequences to excitation-contraction coupling are mediated through the activation of K ATP channels, which shorten APD and depress the Ca transient when glycolytically derived ATP levels are low phase, but lengthen APD and increase Ca transient amplitude when glycolytic ATP production is in high phase (O'). The latter phase inappropriately accelerates energy requirements and may exacerbate intracellular Ca overload, a known factor promoting injury. At the tissue level, APD shortening during metabolic oscillations can lead to "metabolic sinks" that promote arrhythmias (). R E F E R E N C E S As multifunctional signaling proteins, glycolytic enzymes also influence cardioprotective signaling (). Evidence linking glycolysis to cardioprotection includes the finding that elevated extracellular glucose delays injury by preserving glycogen stores without improving overall high energy phosphate levels (), that the glycogenolytic enzyme GSK-3 is a key target protein mediating cardioprotective signaling (), and that enhanced glucose oxidation is cardioprotective (Lopaschuk and Stanley, 2006). These observations raise the intriguing possibility that by inducing excitation-contraction-metabolism uncoupling, glycolytic oscillations may promote injury during ischemia and anoxia. In addition to glycolysis, the mitochondrial network can also escape its entrainment under conditions of increased oxidative stress (;). In this setting, mitochondria become prone to periodic, cell-wide depolarization, which converts mitochondria into ATP consumers rather than producers, inducing K ATP channel activation and APD shortening. The latter |
A Segment Strategy Based on Flooding Search in Unstructured P2P Network The correlation between topology and search algorithm is less paid attention to in unstructured P2P network. In this paper, we focus on designing better search algorithm to adapt to the current network rather than to design the universal algorithm to adapt to a variety of network. Analyzing the characteristics that the flooding algorithm showing in different search stages in different network, we put forward the segment search algorithm. Through experiments we find that it has good results. In addition, we design our algorithm to be simple, as a module that can be easily applied to existing unstructured P2P systems for immediate impact. |
The family of a New Hampshire man killed in a drunken driving crash two years ago is suing the state Liquor Commission and the woman who owns the home where his friends were drinking that night.
Randy Holmes, 24, was a passenger in a friend’s car when it crashed in September 2004. The driver, Matthew Kincaid, then 20, was charged with negligent homicide and is scheduled for trial next month.
Holmes’ family accuses the state Liquor Commission of illegally selling alcohol to Kincaid. The suit also names Mildred Dore, 83, whose grandson invited the other young men to her home.
According to court records, someone at the state liquor store in Hooksett sold vodka, rum and brandy to Kincaid, which the men drank at Dore’s home. Late that night, another relative living in the house woke up Dore to tell her her grandson was having a loud party, leading to a confrontation in which Dore told the men to leave.
With Kincaid driving, the car hit a telephone pole going 53 mph in a 30 mph zone, according to court records.
Attorneys for Dore and the state Liquor Commission are fighting the lawsuit. They dispute allegations that a liquor store employee sold alcohol to Kincaid, and they disagree that Dore should be held responsible for the crash.
In a recent court filing, Dore’s lawyer argues that a 24-year-old in the group actually bought the alcohol legally and that since Dore did not invite the men to her home, she had no obligation to protect them. Dore denies that her grandson was living with her and says that he let himself into the home by climbing through a window.
Dore also said she told her grandson to leave because he was with a girl, not because there was a party going on.
Kincaid, who has since graduated from the New Hampshire Technical Institute, has been free on bail.
Bush might be at fault, after all he has a DWI on his record. |
RNA Is Closely Associated with Human Mast Cell Secretory Granules, Suggesting a Role(s) for Granules in Synthetic Processes The distribution of ribosomes in mature human mast cells, a major granulated secretory cell, does not resemble that in other secretory cells, such as pancreatic acinar cells and plasma cells. By routine ultrastructural analysis, ribosomes in human mast cells are often close to, attached to, or even appear to be within secretory granules. To document better these relationships, we used multiple electron microscopic imaging methods, based on different principles, to define RNA, ribosome, and granule relationships in mature human mast cells. These methods included EDTA regressive staining, RNase digestion, immunogold labeling of ribonucleoproteins or uridine, direct binding or binding after ultrastructural in situ hybridization of various polyuridine probes to polyadenine in mRNA, and ultrastructural autoradiographic localization of -uridine incorporated into cultured human mast cells. These different labeling methods demonstrated ribosomes, RNA, U1SnRNP (a small nuclear RNP specific for alternative splicing of mRNA), mRNA, and uridine to be associated with secretory granules in human mast cells, implicating granules in a larger synthetic role in mast cell biology. |
HECTOR BELLERIN has admitted Arsenal have a mountain to climb if they're going to win the Premier League title.
The Gunners are in third spot, 11 points behind leaders Leicester and six behind London rivals Tottenham, with eight fixtures remaining.
Though it is still mathematically possible to claim their first title since 2004, Bellerin thinks it's unlikely they can peg back their rivals.
He told Goal: "It's going to be very difficult for us to win the league.
"There are only a few games left, although there are still lots of points to play for.
"We have some difficult games, though, so we have to be realistic. It's going to be difficult for Arsenal.
"I never think that anything is impossible. If I did, it wouldn’t be worth playing.
"In football incredible things happen. And we are not going to give up on the league. We’re going to continue.
"We are disappointed about the FA Cup defeat to Watford, and the Champions League loss to Barcelona, although that was a challenge out of our reach, but we still put up a fight.
"Now we have the league left, which is a little difficult, but we have to take on the challenge. I hope we can be champions." |
<filename>src/main/java/it/polimi/ingsw/server/parse/PerformableSerializer.java<gh_stars>0
package it.polimi.ingsw.server.parse;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import it.polimi.ingsw.server.controller.*;
import java.lang.reflect.Type;
import java.util.HashMap;
/**
* PerformableSerializer class.
* Implements JsonDeserializer<Performable> interface.
*/
public class PerformableSerializer implements JsonDeserializer<Performable>{
private static final HashMap<String,Class> moveNames= new HashMap<>();
private static final String CLASSNAME="CLASSNAME";
private static final String INSTANCE="INSTANCE";
static {
moveNames.put(MoveActiveProductionExt.className, MoveActiveProductionExt.class);
moveNames.put(MoveBuyDevCardExt.className, MoveBuyDevCardExt.class);
moveNames.put(MoveChoseInitialResourcesExt.className, MoveChoseInitialResourcesExt.class);
moveNames.put(MoveChoseResourcesExt.className, MoveChoseResourcesExt.class);
moveNames.put(MoveChoseLeaderCardsExt.className, MoveChoseLeaderCardsExt.class);
moveNames.put(MoveDiscardResourcesExt.className, MoveDiscardResourcesExt.class);
moveNames.put(MoveEndTurnExt.className, MoveEndTurnExt.class);
moveNames.put(MoveLeaderExt.className, MoveLeaderExt.class);
moveNames.put(MoveTypeMarketExt.className, MoveTypeMarketExt.class);
moveNames.put(MoveWhiteConversionExt.className, MoveWhiteConversionExt.class);
}
/**
* Method that deserialize a JsonElement.
* @param json of type JsonElement: the JsonElement that has to be deserialized.
* @param type of type Type
* @param context of type JsonDeserializationContext
* @return of type Performable: the performable deserialized.
* @throws JsonParseException
*/
@Override
public Performable deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
String className = json.getAsJsonObject().get(CLASSNAME).getAsString();
Class c = moveNames.get(className);
return context.deserialize(json.getAsJsonObject().get(INSTANCE), c);
}
}
|
<filename>src/transforms/random_noise.py
import numpy as np
class RandomNoise(object):
def __init__(self):
pass
def __call__(self, img: np.ndarray) -> np.ndarray:
return img
|
<filename>ulpc/legacy_admf_interface/src/LegacyAdmfClient.cpp
/*
* Copyright (c) 2020 Sprint
*
* 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 "LegacyAdmfClient.h"
#include "LegacyAdmfInterfaceThread.h"
#include "Common.h"
LegacyAdmfClient :: LegacyAdmfClient(LegacyAdmfInterfaceThread &thread)
: ESocket::TCP::TalkerPrivate(thread)
{
LegacyAdmfInterface::log().debug("LeacyAdmfClient constructor");
}
LegacyAdmfClient :: ~LegacyAdmfClient()
{
LegacyAdmfInterface::log().debug("LegacyAdmfClient destructor");
}
Void
LegacyAdmfClient :: onConnect()
{
LegacyAdmfInterface::log().debug("LegacyAdmfClient :: onConnect()");
}
Void
LegacyAdmfClient :: onReceive()
{
unsigned char buffer[4096];
uint32_t packetLen = 0;
LegacyAdmfInterface::log().debug("LegacyAdmfClient :: onReceive()");
admf_intfc_packet_t *packet = (admf_intfc_packet_t *)buffer;
try {
while(true) {
if (bytesPending() < (Int)sizeof(admfIntfcPacket::packetLength) ||
peek((pUChar)&packetLen, sizeof(admfIntfcPacket::packetLength)) !=
sizeof(admfIntfcPacket::packetLength)) {
break;
}
if (bytesPending() < (Int)packetLen) {
break;
}
if (read(buffer,packetLen) != (Int)packetLen) {
LegacyAdmfInterface::log().debug("Error reading packet data - "
"unable to read bytes : {}", packetLen);
getThread().quit();
break;
}
if (packet->ue_entry_t.packetType == LEGACY_ADMF_ACK) {
LegacyAdmfInterface::log().info("ACK recieved from legacy admf for "
" seqId: {}", packet->ue_entry_t.seqId);
int8_t retValue = ((LegacyAdmfInterfaceThread&)getThread()).
getLegacyAdmfInterface().sendAckToAdmf(packet);
if (retValue == RETURN_SUCCESS) {
LegacyAdmfInterface::log().info("ACK sent to admf");
sendData(packet, ADMF_ACK);
} else {
LegacyAdmfInterface::log().debug("Failure while sending ack to admf.");
}
}
}
LegacyAdmfInterface::log().debug("Packet reading complete");
} catch(const std::exception &e) {
LegacyAdmfInterface::log().debug("LegacyAdmfClient Exception : {}", e.what());
}
}
Void
LegacyAdmfClient :: onClose()
{
}
Void
LegacyAdmfClient :: onError()
{
LegacyAdmfInterface::log().debug("Error in LegacyAdmfClient : "
"Socket error : {}", getError());
}
Void
LegacyAdmfClient :: sendData(admf_intfc_packet_t *packet, uint16_t packetType)
{
LegacyAdmfInterface::log().debug("LegacyAdmfClient :: sendData()");
UChar buffer[4096];
admf_intfc_packet_t *pkt = (admf_intfc_packet_t*) buffer;
std::memset(buffer, 0, sizeof(buffer));
std::memset(pkt->ue_entry_t.startTime, 0, 21);
std::memset(pkt->ue_entry_t.stopTime, 0, 21);
pkt->ue_entry_t.seqId = packet->ue_entry_t.seqId;
pkt->ue_entry_t.imsi = packet->ue_entry_t.imsi;
std::memcpy(pkt->ue_entry_t.startTime, packet->ue_entry_t.startTime, 21);
std::memcpy(pkt->ue_entry_t.stopTime, packet->ue_entry_t.stopTime, 21);
pkt->ue_entry_t.packetType = packetType;
pkt->ue_entry_t.requestType = packet->ue_entry_t.requestType;
pkt->packetLength = sizeof(admf_intfc_packet_t);
LegacyAdmfInterface::log().info("Sending packet to legacy admf for "
"seqId: {} and packetType: {} with packetLength: {}",
pkt->ue_entry_t.seqId, packetType, pkt->packetLength);
write(buffer, pkt->packetLength);
}
|
Localization of two calcium binding proteins, calbindin (28 kD) and parvalbumin (12 kD), in the vertebrate retina We used immunocytochemistry to locate two calcium binding proteins, calbindin (CaB) and parvalbumin (PV), in the retina of goldfish, frog, chick, rat, guinea pig, dog, and man. The location of CaB depended on the type of dominant photoreceptor cells in birds and mammals. In conedominant retinas such as those of the chick, CaBlike immunoreactivity was found in the cones, cone bipolars, and ganglion cells. Amacrine cells 512 m across were also labeled. In roddominant retinas, such as those of the rat, guinea pig, and dog, horizontal cells, small amacrine cells (about 6 m across), and cells in the ganglion cell layer were labeled. In the human retina, which has both cones and rods in abundance, cones, cone bipolars, ganglion cells, horizontal cells, and small and large amacrine cells were labeled. In the frog and goldfish, the level of CaBlike immunoreactivity was low. In the frog, a few cones, amacrine cells, and cells in the ganglion cell layer were labeled. No immunoreactive structures were seen in the goldfish retina. |
/* return 1 if the tcp_connections_number is not valid.
* return 0 if the tcp_connections_number is valid.
*/
static bool tcp_connections_number_not_valid(const TCP_Connections *tcp_c, int tcp_connections_number)
{
if ((unsigned int)tcp_connections_number >= tcp_c->tcp_connections_length) {
return 1;
}
if (tcp_c->tcp_connections == nullptr) {
return 1;
}
if (tcp_c->tcp_connections[tcp_connections_number].status == TCP_CONN_NONE) {
return 1;
}
return 0;
} |
Effects of the home environment on school-aged children's sleep. STUDY OBJECTIVE Examine the relationship between the sleep behavior of elementary school-aged children and characteristics of the home environment. DESIGN Cross-sectional analysis of children participating in a cohort study. SETTING Cleveland Children's Sleep and Health Study, an ethnically mixed, urban, community-based cohort. PARTICIPANTS Four hundred forty-nine children (50% girls, 46% African-American) aged 8 to 11 years. MEASUREMENTS AND RESULTS Sleep and health data were obtained from a child-completed 7-day sleep journal and caregiver-completed health and sleep questionnaire. Home-environment predictors were Middle-Childhood Home Observation for Measurement of the Environment (MC-HOME) total score and Encouragement of Maturity and Physical Environment subscale scores. Sleep outcomes were mean nightly sleep duration, night-to-night variation in sleep duration, and bedtime of 11 PM or later. Adjusted analyses showed that higher Encouragement of Maturity subscale scores were associated with longer sleep duration (P <.05) and decreased odds of a bedtime at 11 PM or later (odds ratio =.74, 95% confidence interval,.58-.95). In girls, higher Encouragement of Maturity scores were also associated with decreased nightly variation in mean sleep duration (P <.001). Increases in total MC-HOME score were associated with increased mean sleep duration among African-American children only (P <.05). CONCLUSION Collectively, results indicate that a parenting style encouraging social maturity in children is linked to healthier sleep patterns. |
1. 50 Cent and Bette Midler.
Perhaps one of the most unlikely friendships ever to have happened, 50 Cent and Bette Midler met and made friends when they worked together on the New York Restoration Project.
2. Helen Mirren and Russell Brand.
They bonded on the set of Arthur and have remained close friends ever since.
In fact, Helen spoke very highly of Russell after the film wrapped, saying, "He is the archetypal bad boy, who is really just the best, goodest boy you could possibly meet".
3. Eminem and Elton John.
They performed together at the 2001 Grammys, but they stayed in touch and remained friends.
Eminem has even revealed that he went to Elton for help and advice when he was trying to get sober. He said: ''I told him, 'Look, I'm going through a problem and I need your advice'".
4. Elton John and Chris Brown.
Proving himself to be quite the mentor for younger stars, Elton was also there for Chris Brown in the wake of his assault on Rihanna in 2009.
Chris revealed that Elton was "a good friend" when the rest of the world shunned him at the time.
5. Kim Kardashian and Mel B.
Despite the fact we can't think of a single thing these two have in common, they became close friends after Mel moved to L.A. in 2012.
In fact, Mel attended Kim's wedding to Kris Humphries and was one of just a few close celebrity pals to be invited to her baby shower when she was expecting little North West.
6. Vince Vaughn and Robert Pattinson.
Vince Vaughn and Robert Pattinson have been spotted partying together on a couple of occassions. It was even reported that Vince acted as a shoulder to cry on when Kristen Stewart admitted to cheating on Robert, and offered him advice on what to do.
7. Emma Thompson and Arnold Schwarzenegger.
They met when they filmed the movie Junior, and 20 years later are still close friends.
8. Jennifer Lawrence and Drew Barrymore.
No one knew that these two were pals until they looked overjoyed to see one another on the Golden Globes 2014 red carpet.
Jennifer even stopped posing for photos to give Drew a massive hug, and the pair stood chatting and laughing in front of photographers instead of striking a pose.
9. Harry Styles and Zach Braff.
We knew that Harry was pretty popular in showbiz circles, with some of his best mates including James Corden and Nick Grimshaw.
But it turns out he's also got friends in high places in the States too with Zach posting this snap of them enjoying dinner together on Twitter back in December.
10. Lindsay Lohan and Woody Allen.
Woody has admitted that he and Lindsay have what he calls a "social friendship", and they've been spotted numerous times enjoying dinner together.
He's spoken highly of her in the past, saying: "She's an extremely talented girl".
11. Miranda Kerr and Miley Cyrus.
They met during a photo shoot and immediately went out for dinner afterwards, with Miranda sharing this photo of her and her "gorgeous" new friend on Instagram.
12. Kylie Jenner and Selena Gomez.
Despite the five-year age difference — Selena is 21 and Kylie is 16 — the pair have been pretty inseparable over recent months, and even went to the Coachella Music and Arts Festival together.
13. Snooki and John McCain.
Whoever would've thought that Jersey Shore's Snooki would be friends with the Republican presidential nominee John McCain?
Turns out they are pals, though. After Snooki gave birth to her first child, John tweeted his congratulations to her. She responded: ''I love you John McCain."
14. Drew Barrymore and Courtney Love.
These two go way back, and Drew is even godmother to Courtney's daughter Frances Bean Cobain.
15. Mel Gibson and Britney Spears.
Mel and Britney's unlikely friendship goes back a long way. Following Britney's dramatic psychiatric hospitalisation in 2008, Mel offered her and her father his Costa Rica home for her to recuperate.
16. Keira Knightley and Sienna Miller.
They met on the set of The Edge of Love and apparently bonded over their "nerdiness". They even rented a house together in Wales during filming, so we'd imagine they know a fair few secrets about each other.
17. Lady Gaga and Julian Assange.
Lady Gaga caused a lot of controversy after deciding she wanted to meet and befriend WikiLeaks founder Julian Assange.
She visited him at the Ecuadorian Embassy in 2012 and spent five hours with him.
18. Kate Hudson and Fergie.
They may seem like an odd friendship match, but they've been pals for years and have been known to take to the red carpet together.
Fergie even attended Kate's massive celebrity Halloween party last year with husband Josh Duhamel.
19. Kate Hudson and Lea Michele.
Kate and Lea met in 2012 when Kate appeared on Glee.
However, no one really knew they'd remained close friends until Lea tragically lost her boyfriend Cory Monteith to a heroin overdose, and Kate offered up her home for Lea.
Lea explained: "I called her and said, 'I don't know where I'm going to go because my house is swarmed with reporters. She was like, 'Oh, you're going to stay at my house', like it was nothing".
She continued: "She let my family stay there, and any of my friends. She made sure that in the refrigerator were my favourite juices. I'll never really be able to thank her, truly, for what she did for me".
20. Joan Collins and Cara Delevingne.
Cara Delevingne has a lot of A-list friends, including Kate Moss and Karl Lagerfeld, but she's also close with Joan Collins.
In fact, Joan is even her godmother.
21. Cheryl Cole and Khloe Kardashian.
Cheryl Cole has long been a fan of the Kardashian family, and when she met them recently it seemed that she and Khloe made a particularly strong bond.
Cheryl shared a photo of Khloe on Instagram with the caption: "My girl!"
Khloe then returned the favour, sharing a snap of Cheryl with the caption: "Sometimes you meet people and you click instantly. Her beauty is more than skin deep... I love this lady's spirit."
22. Courteney Cox and Isla Fisher.
We all know that Jennifer Aniston is Courteney Cox's best friend, but Isla Fisher comes a close second.
They keep their friendship pretty under wraps, but apparently enjoy regular lunches — and Isla even attended Courteney's recent 49th birthday.
23. Trinny Woodall and Keanu Reeves.
Trinny met Keanu by chance in London and apparently the pair "clicked" immediately, and stayed in touch.
Shortly after her marriage broke down in 2008, Trinny found herself in L.A. and was snapped going out for dinner with her new friend and his long-term girlfriend.
24. Jim Parsons and Rihanna.
The unlikely pair met while recording vocals for an animated film and apparently bonded over their joint 'geekery'.
25. Jennifer Aniston and Chelsea Handler.
Jennifer and Chelsea have been close friends for years, although never speak publicly about their relationship.
However, they've recently been struck with rumours that Jennifer's friendship with Chelsea is driving a wedge between her and fiance Justin Theroux. Apparently he doesn't like Chelsea, and thinks she's "rude and obnoxious".
26. Snoop Dogg and David Beckham.
They met after starring in an animated short film based on A Christmas Carol and have seemingly remained friends ever since.
Becks even gave Snoop Dogg's football team a complimentary lesson, appeared on Snoop's reality show and now David even gets to hear Snoop's new music before anyone else.
27. Chris Martin and Simon Pegg.
These two are such good pals that Chris even chose Simon to be godfather to his daughter, Apple.
No doubt Simon is helping Chris through his conscious uncoupling from Gwyneth Paltrow.
28. Taylor Swift and Lena Dunham.
Girls star Lena Dunham spoke at length about how much she loved Taylor Swift and wanted to become friends with her.
Then they contacted each other via Twitter, met at an awards ceremony, and Lena's dreams came true with Taylor saying: "It became apparent that we were very similar. Very similar. I feel like I can tell her anything".
29. And finally, Dennis Rodman and Kim Jong-Un.
Basketball star Dennis Rodman made it his mission to meet the North Korean leader and became the most high-profile American to do so.
Dennis vowed eternal friendship with Kim Jong-Un after meeting him at a basketball game in Pyonhyang and called him an "awesome guy", saying that he, his father and his grandfather were all "great leaders". |
Happy Thursday!
This week’s recommendation is…
‘Accepted’!
‘Accepted’ is a not-so-famous comedy from 2006. I debated with myself a lot on whether I should recommend this or not. Despite it’s awesome feel and entertainment value, ‘Accepted’ has a lot of problems as a production. But hell with that. It might be flawed, but it’s a guilty pleasure of mine, so sue me. I actually used to re-watch this film a lot, but I haven’t seen it in a while and I might watch it again this weekend. It’s a bit strange, the subject matter is unorthodox, but that’s what makes it amazing. When it comes to plot, I love ‘Accepted’ every bit. It’s funny, it’s interesting, it’s original, and there is a very powerful message to it all (by the way, there is a scene at the end of this movie that’s one of my favorite movie scenes of all time, I don’t know why…). The characters are flawed, but nonetheless interesting and likable. The only general problem I have with ‘Accepted’ is that’s it’s narrative is a bit choppy and the tone is inconsistent. Yeah, the film is not perfect and if you watch it with a critical eye and look for every single problem with it, you won’t like it. But trust me, if you go into this movie looking to be entertained and wanting to just chill, you’ll love it. So, if you are looking for something fun and casual to watch on a Friday or Saturday evening, I highly recommend ‘Accepted’!
Have you seen this movie? What did you think of it? Share your thought in the comments section below! Don’t forget to like and share this article if you enjoyed it!
Thanks for reading,
Mickey Angelov |
<gh_stars>1-10
import tempfile
from django.conf import settings, global_settings
# Silence the warning about an insecure SECRET_KEY
global_settings.SECRET_KEY = 'SUPER_SAFE_TESTING_KEY'
settings.configure(default_settings=global_settings)
from graphite.settings import * # noqa
from django import VERSION
if VERSION < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
},
}
LOG_DIR = tempfile.mkdtemp(prefix='graphite-log-test')
URL_PREFIX = '/graphite'
|
Victim of Fatal Bike Accident Was Enrolled in CAS Chung-Wei “Victor” Yang came to Boston from Taiwan
The bicyclist who was killed Monday night in an accident involving an MBTA bus has been identified as Chung-Wei Yang (CAS’15), an international relations major, who was known as “Victor” on the Charles River Campus and on Facebook. Yang came to BU from Taiwan in January, and was a second semester student. He lived off campus.
Yang’s parents arrived in Boston Thursday afternoon, and gave permission for the media to identify their son, who was riding his bike through the busy Allston intersection of Harvard Avenue and Brighton Avenue at 6:30 p.m. when he was struck by a number 57 MBTA bus. He was pronounced dead at Beth Israel Deaconess Medical Center.
Jake Wark, a spokesperson for the Suffolk County District Attorney’s Office, says the driver of the bus has been tested for drugs and alcohol. Test results have not been released. The driver has not been charged, but has been taken out of service while the incident is investigated by police from the MBTA and the Boston Police Department. Wark says investigators are interviewing witnesses and studying surveillance video in an effort to establish the sequence of events leading to the accident.
Dean of Students Kenneth Elmore says Yang’s death is a very terrible loss. “I know that for me, at times like this, it really helps to talk to people who will listen to my concerns and anxieties,” says Elmore (SED’87). “It might be useful for some students to do the same thing.”
Counseling is available through the Dean of Students Office, from Marsh Chapel chaplains, at Student Health Services, and at the Sexual Assault Response & Prevention Center (SARP). Chaplains can be reached at 617-353-3560. SHS counselors can be reached at 617-353-3575. SARP can be reached at 617-353-7277. An SHS Behavioral Medicine provider can be reached at 617-353-3569.
Mio Shang (CAS’15), who was in a writing class with Yang, says the class may never be the same. “He was the most active guy in the class,” says Shang. “He would be the first one to speak up, and was always really funny. Our class was very united and would hang out together on the weekends. Victor invited us all to visit him at his home in Taiwan during the summer holidays.”
“He was a very respectful and cheerful student who always showed interest in the class,” says Patricio Sanhueza, a teaching fellow who taught Yang in the College of Arts & Sciences astronomy course Alien Worlds. “He was also very happy studying here at BU. It is really sad what happened to him.”
A memorial service is planned for 9:30 a.m. this Saturday, November 17, at Marsh Chapel, preceded by a visitation, from 8:30 to 9:30 a.m. in the chapel’s Thurman Room. The memorial service is open to the public, but closed to the press.
Amy Laskowski contributed to this article; she can be reached at [email protected]. |
/**
* Copyright (C) 2010 <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 org.mongodb.morphia.testmodel;
import org.mongodb.morphia.annotations.Property;
import org.mongodb.morphia.testutil.TestEntity;
/**
* @author <NAME>
*/
public class Circle extends TestEntity implements Shape {
private static final long serialVersionUID = 1L;
@Property
private double radius;
public Circle() {
}
public Circle(final double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * (radius * radius);
}
public double getRadius() {
return radius;
}
}
|
package ca.uhn.fhir.jpa.cache;
/*-
* #%L
* HAPI FHIR Search Parameters
* %%
* Copyright (C) 2014 - 2022 Smile CDR, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import ca.uhn.fhir.i18n.Msg;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.jpa.searchparam.matcher.InMemoryMatchResult;
import ca.uhn.fhir.jpa.searchparam.matcher.SearchParamMatcher;
import ca.uhn.fhir.jpa.searchparam.retry.Retrier;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
@Component
@Scope("prototype")
public class ResourceChangeListenerCache implements IResourceChangeListenerCache {
private static final Logger ourLog = LoggerFactory.getLogger(ResourceChangeListenerCache.class);
private static final int MAX_RETRIES = 60;
private static Instant ourNowForUnitTests;
@Autowired
IResourceChangeListenerCacheRefresher myResourceChangeListenerCacheRefresher;
@Autowired
SearchParamMatcher mySearchParamMatcher;
private final String myResourceName;
private final IResourceChangeListener myResourceChangeListener;
private final SearchParameterMap mySearchParameterMap;
private final ResourceVersionCache myResourceVersionCache = new ResourceVersionCache();
private final long myRemoteRefreshIntervalMs;
private boolean myInitialized = false;
private Instant myNextRefreshTime = Instant.MIN;
public ResourceChangeListenerCache(String theResourceName, IResourceChangeListener theResourceChangeListener, SearchParameterMap theSearchParameterMap, long theRemoteRefreshIntervalMs) {
myResourceName = theResourceName;
myResourceChangeListener = theResourceChangeListener;
mySearchParameterMap = SerializationUtils.clone(theSearchParameterMap);
myRemoteRefreshIntervalMs = theRemoteRefreshIntervalMs;
}
/**
* Request that the cache be refreshed at the next convenient time (in a different thread)
*/
@Override
public void requestRefresh() {
myNextRefreshTime = Instant.MIN;
}
/**
* Request that a cache be refreshed now, in the current thread
*/
@Override
public ResourceChangeResult forceRefresh() {
requestRefresh();
return refreshCacheWithRetry();
}
/**
* Refresh the cache if theResource matches our SearchParameterMap
* @param theResource
*/
public void requestRefreshIfWatching(IBaseResource theResource) {
if (matches(theResource)) {
requestRefresh();
}
}
public boolean matches(IBaseResource theResource) {
InMemoryMatchResult result = mySearchParamMatcher.match(mySearchParameterMap, theResource);
if (!result.supported()) {
// This should never happen since we enforce only in-memory SearchParamMaps at registration time
throw new IllegalStateException(Msg.code(483) + "Search Parameter Map " + mySearchParameterMap + " cannot be processed in-memory: " + result.getUnsupportedReason());
}
return result.matched();
}
@Override
public ResourceChangeResult refreshCacheIfNecessary() {
ResourceChangeResult retval = new ResourceChangeResult();
if (isTimeToRefresh()) {
retval = refreshCacheWithRetry();
}
return retval;
}
protected boolean isTimeToRefresh() {
return myNextRefreshTime.isBefore(now());
}
private static Instant now() {
if (ourNowForUnitTests != null) {
return ourNowForUnitTests;
}
return Instant.now();
}
public ResourceChangeResult refreshCacheWithRetry() {
ResourceChangeResult retval;
try {
retval = refreshCacheAndNotifyListenersWithRetry();
} finally {
myNextRefreshTime = now().plus(Duration.ofMillis(myRemoteRefreshIntervalMs));
}
return retval;
}
@VisibleForTesting
public void setResourceChangeListenerCacheRefresher(IResourceChangeListenerCacheRefresher theResourceChangeListenerCacheRefresher) {
myResourceChangeListenerCacheRefresher = theResourceChangeListenerCacheRefresher;
}
private ResourceChangeResult refreshCacheAndNotifyListenersWithRetry() {
Retrier<ResourceChangeResult> refreshCacheRetrier = new Retrier<>(() -> {
synchronized (this) {
return myResourceChangeListenerCacheRefresher.refreshCacheAndNotifyListener(this);
}
}, MAX_RETRIES);
return refreshCacheRetrier.runWithRetry();
}
@Override
public Instant getNextRefreshTime() {
return myNextRefreshTime;
}
@Override
public SearchParameterMap getSearchParameterMap() {
return mySearchParameterMap;
}
@Override
public boolean isInitialized() {
return myInitialized;
}
public ResourceChangeListenerCache setInitialized(boolean theInitialized) {
myInitialized = theInitialized;
return this;
}
@Override
public String getResourceName() {
return myResourceName;
}
public ResourceVersionCache getResourceVersionCache() {
return myResourceVersionCache;
}
public IResourceChangeListener getResourceChangeListener() {
return myResourceChangeListener;
}
/**
* @param theTime has format like "12:34:56" i.e. HH:MM:SS
*/
@VisibleForTesting
public static void setNowForUnitTests(String theTime) {
if (theTime == null) {
ourNowForUnitTests = null;
return;
}
String datetime = "2020-11-16T" + theTime + "Z";
Clock clock = Clock.fixed(Instant.parse(datetime), ZoneId.systemDefault());
ourNowForUnitTests = Instant.now(clock);
}
@VisibleForTesting
Instant getNextRefreshTimeForUnitTest() {
return myNextRefreshTime;
}
@VisibleForTesting
public void clearForUnitTest() {
requestRefresh();
myResourceVersionCache.clear();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("myResourceName", myResourceName)
.append("mySearchParameterMap", mySearchParameterMap)
.append("myInitialized", myInitialized)
.toString();
}
}
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by <NAME>
# Copyright (c) 2017 <NAME>
#
# License: MIT
#
"""This module exports the PhpCsFixer plugin class."""
import logging
import os
from SublimeLinter.lint import Linter, util
logger = logging.getLogger('SublimeLinter.plugin.php-cs-fixer')
def _find_configuration_file(file_name):
if file_name is None:
return None
if not isinstance(file_name, str):
return None
if not len(file_name) > 0:
return None
checked = []
check_dir = os.path.dirname(file_name)
candidates = ['.php-cs-fixer.php', '.php-cs-fixer.dist.php', '.php_cs', '.php_cs.dist']
while check_dir not in checked:
for candidate in candidates:
configuration_file = os.path.join(check_dir, candidate)
if os.path.isfile(configuration_file):
return configuration_file
checked.append(check_dir)
check_dir = os.path.dirname(check_dir)
return None
class PhpCsFixer(Linter):
"""Provides an interface to php-cs-fixer."""
defaults = {
'selector': 'source.php, text.html.basic'
}
regex = (
r'^\s+\d+\)\s+.+\s+\((?P<message>.+)\)[^\@]*'
r'\@\@\s+\-\d+,\d+\s+\+(?P<line>\d+),\d+\s+\@\@'
r'[^-+]+[-+]?\s+(?P<error>[^\n]*)'
)
multiline = True
tempfile_suffix = 'php'
error_stream = util.STREAM_STDOUT
def split_match(self, match):
"""Extract and return values from match."""
match, line, col, error, warning, message, near = super().split_match(match)
line = line + 3
message = "php-cs-fixer error(s) - " + message
return match, line, col, error, warning, message, near
def cmd(self):
"""Read cmd from inline settings."""
if 'cmd' in self.settings:
logger.warning('The setting `cmd` has been deprecated. '
'Use `executable` instead.')
command = [self.settings.get('cmd')]
else:
command = ['php-cs-fixer']
if 'config_file' in self.settings:
config_file = self.settings.get('config_file')
else:
config_file = _find_configuration_file(self.view.file_name())
if not config_file:
config_file = self.config_file
command.append('fix')
command.append('${temp_file}')
command.append('--dry-run')
command.append('--show-progress=none')
command.append('--stop-on-violation')
command.append('--diff')
command.append('--using-cache=no')
command.append('--no-ansi')
command.append('-vv')
command.append('--config=' + config_file)
return command
|
/* Copyright 2020-present Cornell University
*
* 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.
*/
/*
* <NAME> (<EMAIL>)
*
*/
#ifndef PSA_SWITCH_PSA_METER_H_
#define PSA_SWITCH_PSA_METER_H_
#include <bm/bm_sim/extern.h>
#include <bm/bm_sim/meters.h>
namespace bm {
namespace psa {
class PSA_Meter : public bm::ExternType {
public:
static constexpr p4object_id_t spec_id = 0xfffffffe;
BM_EXTERN_ATTRIBUTES {
BM_EXTERN_ATTRIBUTE_ADD(n_meters);
BM_EXTERN_ATTRIBUTE_ADD(type);
BM_EXTERN_ATTRIBUTE_ADD(is_direct);
BM_EXTERN_ATTRIBUTE_ADD(rate_count);
}
void init() override;
void execute(const Data &index, Data &value);
Meter &get_meter(size_t idx);
const Meter &get_meter(size_t idx) const;
Meter::MeterErrorCode set_rates(const std::vector<Meter::rate_config_t> &configs);
size_t size() const { return _meter->size(); };
private:
Data n_meters;
std::string type;
Data is_direct;
Data rate_count;
Data color;
std::unique_ptr<MeterArray> _meter;
};
} // namespace bm::psa
} // namespace bm
#endif
|
// NewNilString creates new nil string value.
func NewNilString() String {
return String{
valid: false,
value: "",
}
} |
<reponame>syfolen/sunnet
module sunnet {
/**
* 协议追踪器
* 说明:
* 1. 用于计算ping值
*/
export interface IProtocalTracker {
/**
* 请求
*/
rsp: number;
/**
* 应答
*/
rep: number;
/**
* 发送时间
*/
time: number;
}
} |
mod prefix;
mod slash;
use proc_macro::TokenStream;
use syn::spanned::Spanned as _;
// Convert None => None and Some(T) => Some(T)
fn wrap_option<T: quote::ToTokens>(literal: Option<T>) -> syn::Expr {
match literal {
Some(literal) => syn::parse_quote! { Some(#literal) },
None => syn::parse_quote! { None },
}
}
struct AllLifetimesToStatic;
impl syn::fold::Fold for AllLifetimesToStatic {
fn fold_lifetime(&mut self, _: syn::Lifetime) -> syn::Lifetime {
syn::parse_quote! { 'static }
}
}
#[derive(Debug)]
struct List<T>(Vec<T>);
impl<T: darling::FromMeta> darling::FromMeta for List<T> {
fn from_list(items: &[::syn::NestedMeta]) -> darling::Result<Self> {
items
.iter()
.map(|item| T::from_nested_meta(item))
.collect::<darling::Result<Vec<T>>>()
.map(Self)
}
}
impl<T> Default for List<T> {
fn default() -> Self {
Self(Default::default())
}
}
/// Representation of the command attribute arguments (`#[command(...)]`)
#[derive(Default, Debug, darling::FromMeta)]
#[darling(default)]
pub struct CommandArgs {
prefix_command: bool,
slash_command: bool,
context_menu_command: Option<String>,
aliases: List<String>,
invoke_on_edit: bool,
reuse_response: bool,
track_edits: bool,
broadcast_typing: bool,
explanation_fn: Option<syn::Path>,
check: Option<syn::Path>,
on_error: Option<syn::Path>,
rename: Option<String>,
discard_spare_arguments: bool,
hide_in_help: bool,
ephemeral: bool,
required_permissions: Option<syn::punctuated::Punctuated<syn::Ident, syn::Token![|]>>,
required_bot_permissions: Option<syn::punctuated::Punctuated<syn::Ident, syn::Token![|]>>,
owners_only: bool,
identifying_name: Option<String>,
category: Option<String>,
// In seconds
global_cooldown: Option<u64>,
user_cooldown: Option<u64>,
guild_cooldown: Option<u64>,
channel_cooldown: Option<u64>,
member_cooldown: Option<u64>,
}
/// Representation of the function parameter attribute arguments
#[derive(Default, Debug, darling::FromMeta)]
#[darling(default)]
struct ParamArgs {
description: Option<String>,
autocomplete: Option<syn::Path>,
channel_types: Option<List<syn::Ident>>,
min: Option<syn::Lit>,
max: Option<syn::Lit>,
lazy: bool,
flag: bool,
rest: bool,
}
/// Part of the Invocation struct. Represents a single parameter of a Discord command.
struct CommandParameter {
name: syn::Ident,
type_: syn::Type,
args: ParamArgs,
span: proc_macro2::Span,
}
/// Passed to prefix and slash command spec generators; contains info to be included in command spec
pub struct Invocation {
command_name: String,
parameters: Vec<CommandParameter>,
description: Option<String>,
explanation: Option<String>,
function: syn::ItemFn,
required_permissions: syn::Expr,
required_bot_permissions: syn::Expr,
args: CommandArgs,
}
fn extract_help_from_doc_comments(attrs: &[syn::Attribute]) -> (Option<String>, Option<String>) {
let mut doc_lines = String::new();
for attr in attrs {
if attr.path == quote::format_ident!("doc").into() {
for token in attr.tokens.clone() {
if let Ok(literal) = syn::parse2::<syn::LitStr>(token.into()) {
let literal = literal.value();
let literal = literal.strip_prefix(' ').unwrap_or(&literal);
doc_lines += literal;
doc_lines += "\n";
}
}
}
}
// Apply newline escapes
let doc_lines = doc_lines.trim().replace("\\\n", "");
if doc_lines.is_empty() {
return (None, None);
}
let mut paragraphs = doc_lines.splitn(2, "\n\n");
let inline_help = paragraphs.next().unwrap().replace("\n", " ");
let multiline_help = paragraphs.next().map(|x| x.to_owned());
(Some(inline_help), multiline_help)
}
pub fn command(
args: CommandArgs,
mut function: syn::ItemFn,
) -> Result<TokenStream, darling::Error> {
// Verify that the function is marked async. Not strictly needed, but avoids confusion
if function.sig.asyncness.is_none() {
return Err(syn::Error::new(function.sig.span(), "command function must be async").into());
}
// Verify that at least one command type was enabled
if !args.prefix_command && !args.slash_command && args.context_menu_command.is_none() {
let err_msg = "you must enable at least one of `prefix_command`, `slash_command` or \
`context_menu_command`";
return Err(syn::Error::new(proc_macro2::Span::call_site(), err_msg).into());
}
// Collect argument names/types/attributes to insert into generated function
let mut parameters = Vec::new();
for command_param in function.sig.inputs.iter_mut().skip(1) {
let pattern = match command_param {
syn::FnArg::Typed(x) => &mut *x,
syn::FnArg::Receiver(r) => {
return Err(syn::Error::new(r.span(), "self argument is invalid here").into());
}
};
let name = match &*pattern.pat {
syn::Pat::Ident(pat_ident) => &pat_ident.ident,
x => {
return Err(syn::Error::new(x.span(), "must use an identifier pattern here").into())
}
};
let attrs = pattern
.attrs
.drain(..)
.map(|attr| attr.parse_meta().map(syn::NestedMeta::Meta))
.collect::<Result<Vec<_>, _>>()?;
let attrs = <ParamArgs as darling::FromMeta>::from_list(&attrs)?;
parameters.push(CommandParameter {
name: name.clone(),
type_: (*pattern.ty).clone(),
args: attrs,
span: command_param.span(),
});
}
// Extract the command descriptions from the function doc comments
let (description, explanation) = extract_help_from_doc_comments(&function.attrs);
fn permissions_to_tokens(
perms: &Option<syn::punctuated::Punctuated<syn::Ident, syn::Token![|]>>,
) -> syn::Expr {
match perms {
Some(perms) => {
let perms = perms.iter();
syn::parse_quote! { #(poise::serenity_prelude::Permissions::#perms)|* }
}
None => syn::parse_quote! { poise::serenity_prelude::Permissions::empty() },
}
}
let required_permissions = permissions_to_tokens(&args.required_permissions);
let required_bot_permissions = permissions_to_tokens(&args.required_bot_permissions);
let inv = Invocation {
command_name: args
.rename
.clone()
.unwrap_or_else(|| function.sig.ident.to_string()),
parameters,
description,
explanation,
args,
function,
required_permissions,
required_bot_permissions,
};
Ok(TokenStream::from(generate_command(inv)?))
}
fn generate_command(mut inv: Invocation) -> Result<proc_macro2::TokenStream, darling::Error> {
let ctx_type = match inv.function.sig.inputs.first() {
Some(syn::FnArg::Typed(syn::PatType { ty, .. })) => &**ty,
_ => {
return Err(
syn::Error::new(inv.function.sig.span(), "expected a Context parameter").into(),
)
}
};
// Needed because we're not allowed to have lifetimes in the hacky use case below
let ctx_type_with_static = syn::fold::fold_type(&mut AllLifetimesToStatic, ctx_type.clone());
let prefix_action = wrap_option(match inv.args.prefix_command {
true => Some(prefix::generate_prefix_action(&inv)?),
false => None,
});
let slash_action = wrap_option(match inv.args.slash_command {
true => Some(slash::generate_slash_action(&inv)),
false => None,
});
let context_menu_action = wrap_option(match &inv.args.context_menu_command {
Some(_) => Some(slash::generate_context_menu_action(&inv)?),
None => None,
});
let identifying_name = inv
.args
.identifying_name
.as_ref()
.unwrap_or(&inv.command_name);
let command_name = &inv.command_name;
let context_menu_name = wrap_option(inv.args.context_menu_command.as_ref());
let description = wrap_option(inv.description.as_ref());
let hide_in_help = &inv.args.hide_in_help;
let category = wrap_option(inv.args.category.as_ref());
let global_cooldown = wrap_option(inv.args.global_cooldown);
let user_cooldown = wrap_option(inv.args.user_cooldown);
let guild_cooldown = wrap_option(inv.args.guild_cooldown);
let channel_cooldown = wrap_option(inv.args.channel_cooldown);
let member_cooldown = wrap_option(inv.args.member_cooldown);
let required_permissions = &inv.required_permissions;
let required_bot_permissions = &inv.required_bot_permissions;
let owners_only = inv.args.owners_only;
let explanation = match &inv.args.explanation_fn {
Some(explanation_fn) => quote::quote! { Some(#explanation_fn) },
None => match &inv.explanation {
Some(extracted_explanation) => quote::quote! { Some(|| #extracted_explanation.into()) },
None => quote::quote! { None },
},
};
// Box::pin the check and on_error callbacks in order to store them in a struct
let check = match &inv.args.check {
Some(check) => quote::quote! { Some(|ctx| Box::pin(#check(ctx))) },
None => quote::quote! { None },
};
let on_error = match &inv.args.on_error {
Some(on_error) => quote::quote! { Some(|err| Box::pin(#on_error(err))) },
None => quote::quote! { None },
};
let invoke_on_edit = inv.args.invoke_on_edit || inv.args.track_edits;
let reuse_response = inv.args.reuse_response || inv.args.track_edits;
let broadcast_typing = inv.args.broadcast_typing;
let aliases = &inv.args.aliases.0;
let parameters = slash::generate_parameters(&inv)?;
let ephemeral = inv.args.ephemeral;
let function_name = std::mem::replace(&mut inv.function.sig.ident, syn::parse_quote! { inner });
let function_visibility = &inv.function.vis;
let function = &inv.function;
Ok(quote::quote! {
#function_visibility fn #function_name() -> ::poise::Command<
<#ctx_type_with_static as poise::_GetGenerics>::U,
<#ctx_type_with_static as poise::_GetGenerics>::E,
> {
#function
::poise::Command {
prefix_action: #prefix_action,
slash_action: #slash_action,
context_menu_action: #context_menu_action,
subcommands: Vec::new(),
name: #command_name,
qualified_name: String::from(#command_name), // properly filled in later by Framework
identifying_name: String::from(#identifying_name),
category: #category,
inline_help: #description,
multiline_help: #explanation,
hide_in_help: #hide_in_help,
cooldowns: std::sync::Mutex::new(::poise::Cooldowns::new(::poise::CooldownConfig {
global: #global_cooldown.map(std::time::Duration::from_secs),
user: #user_cooldown.map(std::time::Duration::from_secs),
guild: #guild_cooldown.map(std::time::Duration::from_secs),
channel: #channel_cooldown.map(std::time::Duration::from_secs),
member: #member_cooldown.map(std::time::Duration::from_secs),
})),
reuse_response: #reuse_response,
required_permissions: #required_permissions,
required_bot_permissions: #required_bot_permissions,
owners_only: #owners_only,
check: #check,
on_error: #on_error,
parameters: vec![ #( #parameters ),* ],
aliases: &[ #( #aliases, )* ],
invoke_on_edit: #invoke_on_edit,
broadcast_typing: #broadcast_typing,
context_menu_name: #context_menu_name,
ephemeral: #ephemeral,
}
}
})
}
|
<filename>cpp/src/main.cpp
#include "unixTaskbook.hpp"
int main(int argc, char *argv[])
{
UnixTaskbook unixTaskbook(argc, argv);
unixTaskbook.run();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.