repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
Becavalier/TWVM
|
lib/include/opcodes.hh
|
<reponame>Becavalier/TWVM<filename>lib/include/opcodes.hh
// Copyright 2021 YHSPY. All rights reserved.
#ifndef LIB_INCLUDE_OPCODES_HH_
#define LIB_INCLUDE_OPCODES_HH_
#define ITERATE_ALL_OPCODE(V) \
V(Unreachable, 0x0, VALID) \
V(Nop, 0x1, VALID) \
V(Block, 0x2, VALID) \
V(Loop, 0x3, VALID) \
V(If, 0x4, VALID) \
V(Else, 0x5, VALID) \
V(_NA_0x6, 0x6, INVALID) \
V(_NA_0x7, 0x7, INVALID) \
V(_NA_0x8, 0x8, INVALID) \
V(_NA_0x9, 0x9, INVALID) \
V(_NA_0xa, 0xa, INVALID) \
V(End, 0xb, VALID) \
V(Br, 0xc, VALID) \
V(BrIf, 0xd, VALID) \
V(BrTable, 0xe, VALID) \
V(Return, 0xf, VALID) \
V(Call, 0x10, VALID) \
V(CallIndirect, 0x11, VALID) \
V(_NA_0x12, 0x12, INVALID) \
V(_NA_0x13, 0x13, INVALID) \
V(_NA_0x14, 0x14, INVALID) \
V(_NA_0x15, 0x15, INVALID) \
V(_NA_0x16, 0x16, INVALID) \
V(_NA_0x17, 0x17, INVALID) \
V(_NA_0x18, 0x18, INVALID) \
V(_NA_0x19, 0x19, INVALID) \
V(Drop, 0x1a, VALID) \
V(Select, 0x1b, VALID) \
V(_NA_0x1c, 0x1c, INVALID) \
V(_NA_0x1d, 0x1d, INVALID) \
V(_NA_0x1e, 0x1e, INVALID) \
V(_NA_0x1f, 0x1f, INVALID) \
V(LocalGet, 0x20, VALID) \
V(LocalSet, 0x21, VALID) \
V(LocalTee, 0x22, VALID) \
V(GlobalGet, 0x23, VALID) \
V(GlobalSet, 0x24, VALID) \
V(_NA_0x25, 0x25, INVALID) \
V(_NA_0x26, 0x26, INVALID) \
V(_NA_0x27, 0x27, INVALID) \
V(I32LoadMem, 0x28, VALID) \
V(I64LoadMem, 0x29, VALID) \
V(F32LoadMem, 0x2a, VALID) \
V(F64LoadMem, 0x2b, VALID) \
V(I32LoadMem8S, 0x2c, VALID) \
V(I32LoadMem8U, 0x2d, VALID) \
V(I32LoadMem16S, 0x2e, VALID) \
V(I32LoadMem16U, 0x2f, VALID) \
V(I64LoadMem8S, 0x30, VALID) \
V(I64LoadMem8U, 0x31, VALID) \
V(I64LoadMem16S, 0x32, VALID) \
V(I64LoadMem16U, 0x33, VALID) \
V(I64LoadMem32S, 0x34, VALID) \
V(I64LoadMem32U, 0x35, VALID) \
V(I32StoreMem, 0x36, VALID) \
V(I64StoreMem, 0x37, VALID) \
V(F32StoreMem, 0x38, VALID) \
V(F64StoreMem, 0x39, VALID) \
V(I32StoreMem8, 0x3a, VALID) \
V(I32StoreMem16, 0x3b, VALID) \
V(I64StoreMem8, 0x3c, VALID) \
V(I64StoreMem16, 0x3d, VALID) \
V(I64StoreMem32, 0x3e, VALID) \
V(MemorySize, 0x3f, VALID) \
V(MemoryGrow, 0x40, VALID) \
V(I32Const, 0x41, VALID) \
V(I64Const, 0x42, VALID) \
V(F32Const, 0x43, VALID) \
V(F64Const, 0x44, VALID) \
V(I32Eqz, 0x45, VALID) \
V(I32Eq, 0x46, VALID) \
V(I32Ne, 0x47, VALID) \
V(I32LtS, 0x48, VALID) \
V(I32LtU, 0x49, VALID) \
V(I32GtS, 0x4a, VALID) \
V(I32GtU, 0x4b, VALID) \
V(I32LeS, 0x4c, VALID) \
V(I32LeU, 0x4d, VALID) \
V(I32GeS, 0x4e, VALID) \
V(I32GeU, 0x4f, VALID) \
V(I64Eqz, 0x50, VALID) \
V(I64Eq, 0x51, VALID) \
V(I64Ne, 0x52, VALID) \
V(I64LtS, 0x53, VALID) \
V(I64LtU, 0x54, VALID) \
V(I64GtS, 0x55, VALID) \
V(I64GtU, 0x56, VALID) \
V(I64LeS, 0x57, VALID) \
V(I64LeU, 0x58, VALID) \
V(I64GeS, 0x59, VALID) \
V(I64GeU, 0x5a, VALID) \
V(F32Eq, 0x5b, VALID) \
V(F32Ne, 0x5c, VALID) \
V(F32Lt, 0x5d, VALID) \
V(F32Gt, 0x5e, VALID) \
V(F32Le, 0x5f, VALID) \
V(F32Ge, 0x60, VALID) \
V(F64Eq, 0x61, VALID) \
V(F64Ne, 0x62, VALID) \
V(F64Lt, 0x63, VALID) \
V(F64Gt, 0x64, VALID) \
V(F64Le, 0x65, VALID) \
V(F64Ge, 0x66, VALID) \
V(I32Clz, 0x67, VALID) \
V(I32Ctz, 0x68, VALID) \
V(I32Popcnt, 0x69, VALID) \
V(I32Add, 0x6a, VALID) \
V(I32Sub, 0x6b, VALID) \
V(I32Mul, 0x6c, VALID) \
V(I32DivS, 0x6d, VALID) \
V(I32DivU, 0x6e, VALID) \
V(I32RemS, 0x6f, VALID) \
V(I32RemU, 0x70, VALID) \
V(I32And, 0x71, VALID) \
V(I32Or, 0x72, VALID) \
V(I32Xor, 0x73, VALID) \
V(I32Shl, 0x74, VALID) \
V(I32ShrS, 0x75, VALID) \
V(I32ShrU, 0x76, VALID) \
V(I32Rotl, 0x77, VALID) \
V(I32Rotr, 0x78, VALID) \
V(I64Clz, 0x79, VALID) \
V(I64Ctz, 0x7a, VALID) \
V(I64Popcnt, 0x7b, VALID) \
V(I64Add, 0x7c, VALID) \
V(I64Sub, 0x7d, VALID) \
V(I64Mul, 0x7e, VALID) \
V(I64DivS, 0x7f, VALID) \
V(I64DivU, 0x80, VALID) \
V(I64RemS, 0x81, VALID) \
V(I64RemU, 0x82, VALID) \
V(I64And, 0x83, VALID) \
V(I64Or, 0x84, VALID) \
V(I64Xor, 0x85, VALID) \
V(I64Shl, 0x86, VALID) \
V(I64ShrS, 0x87, VALID) \
V(I64ShrU, 0x88, VALID) \
V(I64Rotl, 0x89, VALID) \
V(I64Rotr, 0x8a, VALID) \
V(F32Abs, 0x8b, VALID) \
V(F32Neg, 0x8c, VALID) \
V(F32Ceil, 0x8d, VALID) \
V(F32Floor, 0x8e, VALID) \
V(F32Trunc, 0x8f, VALID) \
V(F32NearestInt, 0x90, VALID) \
V(F32Sqrt, 0x91, VALID) \
V(F32Add, 0x92, VALID) \
V(F32Sub, 0x93, VALID) \
V(F32Mul, 0x94, VALID) \
V(F32Div, 0x95, VALID) \
V(F32Min, 0x96, VALID) \
V(F32Max, 0x97, VALID) \
V(F32CopySign, 0x98, VALID) \
V(F64Abs, 0x99, VALID) \
V(F64Neg, 0x9a, VALID) \
V(F64Ceil, 0x9b, VALID) \
V(F64Floor, 0x9c, VALID) \
V(F64Trunc, 0x9d, VALID) \
V(F64NearestInt, 0x9e, VALID) \
V(F64Sqrt, 0x9f, VALID) \
V(F64Add, 0xa0, VALID) \
V(F64Sub, 0xa1, VALID) \
V(F64Mul, 0xa2, VALID) \
V(F64Div, 0xa3, VALID) \
V(F64Min, 0xa4, VALID) \
V(F64Max, 0xa5, VALID) \
V(F64CopySign, 0xa6, VALID) \
V(I32WrapI64, 0xa7, VALID) \
V(I32TruncF32S, 0xa8, VALID) \
V(I32TruncF32U, 0xa9, VALID) \
V(I32TruncF64S, 0xaa, VALID) \
V(I32TruncF64U, 0xab, VALID) \
V(I64ExtendI32S, 0xac, VALID) \
V(I64ExtendI32U, 0xad, VALID) \
V(I64TruncF32S, 0xae, VALID) \
V(I64TruncF32U, 0xaf, VALID) \
V(I64TruncF64S, 0xb0, VALID) \
V(I64TruncF64U, 0xb1, VALID) \
V(F32SConvertI32, 0xb2, VALID) \
V(F32UConvertI32, 0xb3, VALID) \
V(F32SConvertI64, 0xb4, VALID) \
V(F32UConvertI64, 0xb5, VALID) \
V(F32DemoteF64, 0xb6, VALID) \
V(F64SConvertI32, 0xb7, VALID) \
V(F64UConvertI32, 0xb8, VALID) \
V(F64SConvertI64, 0xb9, VALID) \
V(F64UConvertI64, 0xba, VALID) \
V(F64PromoteF32, 0xbb, VALID) \
V(I32ReinterpretF32, 0xbc, VALID) \
V(I64ReinterpretF64, 0xbd, VALID) \
V(F32ReinterpretI32, 0xbe, VALID) \
V(F64ReinterpretI64, 0xbf, VALID)
#define DECLARE_NAMED_ENUM(NAME, OP, _) \
NAME = OP,
namespace TWVM {
enum class OpCodes : uint8_t {
ITERATE_ALL_OPCODE(DECLARE_NAMED_ENUM)
};
} // namespace TWVM
#endif // LIB_INCLUDE_OPCODES_HH_
|
Amaranese/mario-bros-cplusplus
|
source/Block.cpp
|
#include "Block.hpp"
#include "Coin.hpp"
#include "Flower.hpp"
#include "Globals.hpp"
#include "Item.hpp"
#include "Leaf.hpp"
#include "Mushroom.hpp"
#include "Player.hpp"
#include "Random.hpp"
#include "Shell.hpp"
#include "Sound.hpp"
#include "World.hpp"
/**
* For spawning multiple coins that scatter.
*
* @todo clean this up.
*/
class CoinSpawner : public Particle
{
public:
CoinSpawner(int coins) :
Particle(GET_ANIMATION("coin"), 0.0),
coins(coins)
{
}
private:
int coins;
void onDestroy()
{
for( int i = 0; i < coins; i++ )
{
Coin* coin = new Coin;
coin->setGravityEnabled(true);
coin->setCollisionsEnabled(true);
coin->setWidth(0.75);
coin->setXVelocity((getWorld().getRandom().nextReal() * 2.0 - 1.0) * 4.0);
coin->setCenterX(getCenterX());
coin->setBottom(getBottom());
getWorld().addSprite(coin);
}
}
};
Block::CoinParticle::CoinParticle( Player* player ) :
Particle( GET_ANIMATION("coin_particle"), COIN_PARTICLE_DURATION ),
player(player)
{
disableGravity();
disableCollisions();
setYAcceleration(COIN_PARTICLE_GRAVITY);
setYVelocity(COIN_PARTICLE_SPEED);
setMaximumYSpeed(COIN_PARTICLE_SPEED);
setAnimation("coin_particle");
}
void Block::CoinParticle::onDestroy()
{
player->scorePoints( BLOCK_COIN_POINTS, getX(), getY() );
player->gainCoins(1);
Particle* p = new Particle( getAnimation("coin_explosion"), true );
p->disableCollisions();
p->disableGravity();
p->setLayer(-1);
getWorld().addSprite( getX(), getY(), p );
}
Block::Spawner::Spawner(Sprite* sprite, int blockY) :
sprite(sprite),
blockY(blockY)
{
disableCollisions();
disableGravity();
}
Block::Spawner::~Spawner()
{
delete sprite;
}
void Block::Spawner::onPreUpdate()
{
Sprite::onPreUpdate();
// We only live for 1 second (plus the initial delay)
if( getAge() > BLOCK_SPAWN_TIME + (BLOCK_BUMP_FRAMES / GAME_FPS))
{
// Time to spawn our sprite
getWorld().addSprite(getCenterX() - sprite->getWidth() / 2.0, blockY + 1, sprite);
sprite = nullptr;
// Self destruct
kill();
}
else if( getAge() > (BLOCK_BUMP_FRAMES / GAME_FPS) )
{
// Use the same animation as what is being spawned
setAnimation(sprite->getActiveAnimation());
setYVelocity(1.0);
}
}
Block::Block(BlockType type, Sprite* contents) :
Tile(TILE_SOLID),
bumpProgress(0),
coins(0),
contents(contents),
specialContents(BLOCK_CONTENTS_NONE),
dead(false),
type(type)
{
init();
}
Block::Block(BlockType type, BlockContents contents) :
Tile(TILE_SOLID),
bumpProgress(0),
coins(0),
contents(nullptr),
specialContents(contents),
dead(false),
type(type)
{
init();
}
Block::Block(BlockType type, int coins, bool scatterCoins) :
Tile(TILE_SOLID),
bumpProgress(0),
coins(coins),
contents(nullptr),
specialContents(BLOCK_CONTENTS_NONE),
dead(false),
type(type)
{
if( scatterCoins )
{
contents = new CoinSpawner(coins);
this->coins = 0;
}
init();
}
Block::~Block()
{
delete contents;
}
void Block::bump( bool strongBump, bool fromPlayer, Player* bumper )
{
// Blocks can only be bumped when alive
if( dead )
{
return;
}
// Bump sprites that are above
const std::set<Sprite*>* sprites = getWorld().getSprites(getXInt(), getYInt() + getHeightInt());
if( sprites != nullptr )
{
for( auto sprite : *sprites )
{
// Only bump sprites that are on top of the block
if( sprite->getBottom() != getTop() )
{
continue;
}
Enemy* enemy = dynamic_cast<Enemy*>(sprite);
if( enemy != nullptr )
{
enemy->bump();
if( bumper != nullptr )
{
bumper->scorePoints(MULTIPLE_KILL_POINT_SEQUENCE[0]);
}
playSound("kick");
continue;
}
Item* item = dynamic_cast<Item*>(sprite);
if( item != nullptr )
{
Coin* coin = dynamic_cast<Coin*>(sprite);
if( coin != nullptr && fromPlayer )
{
coin->sparkle();
coin->kill();
bumper->gainCoins(1);
}
else
{
sprite->setYVelocity(BLOCK_BUMP_VELOCITY);
}
continue;
}
Player* player = dynamic_cast<Player*>(sprite);
if( player != nullptr )
{
player->setYVelocity(BLOCK_BUMP_VELOCITY);
}
}
}
if( coins > 0 )
{
coins--;
if( coins == 0 )
{
dead = true;
setAnimation(deadAnimation);
}
bumpProgress = getWorld().getFrameNumber();
Particle* coinParticle = new CoinParticle(bumper);
coinParticle->setLayer(-1);
getWorld().addSprite(getX(), getY(), coinParticle);
if( fromPlayer )
{
bumper->setYVelocity( -0.5 * std::fabs(bumper->getYVelocity()) );
}
playSound("bump");
}
else if( contents != nullptr )
{
Spawner* spawner = new Spawner(contents, getY());
spawner->setLayer(-1);
getWorld().addSprite(getX(), getY(), spawner);
contents = nullptr;
dead = true;
setAnimation(deadAnimation);
bumpProgress = getWorld().getFrameNumber();
playSound("sprout");
if( fromPlayer )
{
bumper->setYVelocity( -0.5 * std::fabs(bumper->getYVelocity()) ); ///@todo this should be an acceleration
}
}
else if( specialContents != BLOCK_CONTENTS_NONE )
{
Sprite* spriteToSpawn = nullptr;
switch( bumper->getState() )
{
case Player::SMALL:
spriteToSpawn = new Mushroom;
break;
case Player::SUPER:
default:
switch( specialContents )
{
case BLOCK_FLOWER:
spriteToSpawn = new Flower;
break;
case BLOCK_LEAF:
spriteToSpawn = new Leaf;
break;
default:
break;
}
break;
}
specialContents = BLOCK_CONTENTS_NONE;
// The following was copied from the above case
///@todo make this a function
Spawner* spawner = new Spawner(spriteToSpawn, getY());
spawner->setLayer(-1);
getWorld().addSprite(getX(), getY(), spawner);
contents = nullptr;
dead = true;
setAnimation(deadAnimation);
bumpProgress = getWorld().getFrameNumber();
playSound("sprout");
if( fromPlayer )
{
bumper->setYVelocity( -0.5 * std::fabs(bumper->getYVelocity()) ); ///@todo this should be an acceleration
}
}
else if( !strongBump || type != BLOCK_BRICK )
{
//playAnimation(bumpAnimation, mainAnimation);
bumpProgress = getWorld().getFrameNumber();
playSound("bump");
}
else
{
// Give the player points
bumper->scorePoints( BRICK_DESTROY_POINTS );
// Create brick particles
Particle* p = new Particle( getAnimation("brick_particle")/*, BRICK_PARTICLE_DURATION*/ );
p->setXVelocity(BRICK_PARTICLE_X_SPEED);
p->setYVelocity(BRICK_PARTICLE_Y_SPEED);
p->setYAcceleration(BRICK_PARTICLE_GRAVITY);
p->disableCollisions();
p->disableGravity();
getWorld().addSprite(getX(), getY(), p);
p = new Particle( getAnimation("brick_particle")/*, BRICK_PARTICLE_DURATION*/ );
p->setXVelocity(-1.0 * BRICK_PARTICLE_X_SPEED);
p->setYVelocity(BRICK_PARTICLE_Y_SPEED);
p->setYAcceleration(BRICK_PARTICLE_GRAVITY);
p->disableCollisions();
p->disableGravity();
getWorld().addSprite(getX(), getY(), p);
p = new Particle( getAnimation("brick_particle")/*, BRICK_PARTICLE_DURATION*/ );
p->setXVelocity(BRICK_PARTICLE_X_SPEED);
p->setYVelocity(BRICK_PARTICLE_Y_SPEED / 2.0);
p->setYAcceleration(BRICK_PARTICLE_GRAVITY);
p->disableCollisions();
p->disableGravity();
getWorld().addSprite(getX(), getY(), p);
p = new Particle( getAnimation("brick_particle")/*, BRICK_PARTICLE_DURATION*/ );
p->setXVelocity(-1.0 * BRICK_PARTICLE_X_SPEED);
p->setYVelocity(BRICK_PARTICLE_Y_SPEED / 2.0);
p->setYAcceleration(BRICK_PARTICLE_GRAVITY);
p->disableCollisions();
p->disableGravity();
getWorld().addSprite(getX(), getY(), p);
// Self-destruct
playSound("brick_break");
getWorld().destroyTile(this);
}
}
BlockType Block::getBlockType() const
{
return type;
}
void Block::init()
{
switch( type )
{
case BLOCK_BRICK:
mainAnimation = getAnimation("brick");
break;
case BLOCK_QUESTION:
mainAnimation = getAnimation("question_block");
break;
}
deadAnimation = getAnimation("block_dead");
setAnimation(mainAnimation);
}
void Block::onCollision(Sprite& sprite, Edge edge)
{
// Handle collisions with shells
Shell* shell = dynamic_cast<Shell*>(&sprite);
if( shell != nullptr )
{
if( (edge == EDGE_LEFT || edge == EDGE_RIGHT) && shell->getXVelocity() != 0.0 )
{
bump(true, false, shell->getPlayer());
}
return;
}
// Handle collisions with the player
Player* player = dynamic_cast<Player*>(&sprite);
if( player != nullptr )
{
if( edge == EDGE_BOTTOM && !player->isClimbingLadder() )
{
if( player->getState() != Player::SMALL )
{
bump(true, true, player);
}
else
{
bump(false, true, player);
}
}
return;
}
}
void Block::onRender()
{
// Render the bumping effect by modifying the y offset
if( bumpProgress > 0 )
{
int progress = getWorld().getFrameNumber() - bumpProgress;
if( progress + 1 >= BLOCK_BUMP_FRAMES )
{
bumpProgress = 0;
}
else
{
double offset;
if( progress < BLOCK_BUMP_FRAMES / 2 )
{
offset = (double)progress / (BLOCK_BUMP_FRAMES / 2);
}
else
{
offset = (double)(BLOCK_BUMP_FRAMES - progress) / (BLOCK_BUMP_FRAMES / 2);
}
setYOffset(offset / 2.0);
}
}
else
{
setYOffset(0.0);
}
}
|
astrapi69/greekchareditor
|
src/main/java/gr/frame/actions/ShowInfoDialogAction.java
|
<gh_stars>0
package gr.frame.actions;
import gr.frame.MainFrame;
import gr.frame.help.info.InfoJDialog;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
@SuppressWarnings("serial")
public class ShowInfoDialogAction extends AbstractAction {
private static final String INFO_TITLE = "Info";
public ShowInfoDialogAction(String name) {
super(name);
}
public void actionPerformed(ActionEvent e) {
InfoJDialog info = new InfoJDialog(MainFrame.getInstance(), INFO_TITLE);
info.setVisible(true);
}
}
|
zipated/src
|
third_party/android_tools/sdk/sources/android-25/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
|
<filename>third_party/android_tools/sdk/sources/android-25/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.statusbar.phone;
import android.app.ActivityManager;
import android.app.ActivityManagerNative;
import android.app.AlarmManager;
import android.app.AlarmManager.AlarmClockInfo;
import android.app.SynchronousUserSwitchObserver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.UserInfo;
import android.media.AudioManager;
import android.os.Handler;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings.Global;
import android.telecom.TelecomManager;
import android.util.Log;
import com.android.internal.telephony.IccCardConstants;
import com.android.internal.telephony.TelephonyIntents;
import com.android.systemui.R;
import com.android.systemui.qs.tiles.DndTile;
import com.android.systemui.qs.tiles.RotationLockTile;
import com.android.systemui.statusbar.policy.BluetoothController;
import com.android.systemui.statusbar.policy.BluetoothController.Callback;
import com.android.systemui.statusbar.policy.CastController;
import com.android.systemui.statusbar.policy.CastController.CastDevice;
import com.android.systemui.statusbar.policy.DataSaverController;
import com.android.systemui.statusbar.policy.HotspotController;
import com.android.systemui.statusbar.policy.RotationLockController;
import com.android.systemui.statusbar.policy.UserInfoController;
/**
* This class contains all of the policy about which icons are installed in the status
* bar at boot time. It goes through the normal API for icons, even though it probably
* strictly doesn't need to.
*/
public class PhoneStatusBarPolicy implements Callback, RotationLockController.RotationLockControllerCallback, DataSaverController.Listener {
private static final String TAG = "PhoneStatusBarPolicy";
private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
private final String mSlotCast;
private final String mSlotHotspot;
private final String mSlotBluetooth;
private final String mSlotTty;
private final String mSlotZen;
private final String mSlotVolume;
private final String mSlotAlarmClock;
private final String mSlotManagedProfile;
private final String mSlotRotate;
private final String mSlotHeadset;
private final String mSlotDataSaver;
private final Context mContext;
private final Handler mHandler = new Handler();
private final CastController mCast;
private final HotspotController mHotspot;
private final AlarmManager mAlarmManager;
private final UserInfoController mUserInfoController;
private final UserManager mUserManager;
private final StatusBarIconController mIconController;
private final RotationLockController mRotationLockController;
private final DataSaverController mDataSaver;
private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
// Assume it's all good unless we hear otherwise. We don't always seem
// to get broadcasts that it *is* there.
IccCardConstants.State mSimState = IccCardConstants.State.READY;
private boolean mZenVisible;
private boolean mVolumeVisible;
private boolean mCurrentUserSetup;
private int mZen;
private boolean mManagedProfileFocused = false;
private boolean mManagedProfileIconVisible = false;
private boolean mManagedProfileInQuietMode = false;
private BluetoothController mBluetooth;
public PhoneStatusBarPolicy(Context context, StatusBarIconController iconController,
CastController cast, HotspotController hotspot, UserInfoController userInfoController,
BluetoothController bluetooth, RotationLockController rotationLockController,
DataSaverController dataSaver) {
mContext = context;
mIconController = iconController;
mCast = cast;
mHotspot = hotspot;
mBluetooth = bluetooth;
mBluetooth.addStateChangedCallback(this);
mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mUserInfoController = userInfoController;
mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
mRotationLockController = rotationLockController;
mDataSaver = dataSaver;
mSlotCast = context.getString(com.android.internal.R.string.status_bar_cast);
mSlotHotspot = context.getString(com.android.internal.R.string.status_bar_hotspot);
mSlotBluetooth = context.getString(com.android.internal.R.string.status_bar_bluetooth);
mSlotTty = context.getString(com.android.internal.R.string.status_bar_tty);
mSlotZen = context.getString(com.android.internal.R.string.status_bar_zen);
mSlotVolume = context.getString(com.android.internal.R.string.status_bar_volume);
mSlotAlarmClock = context.getString(com.android.internal.R.string.status_bar_alarm_clock);
mSlotManagedProfile = context.getString(
com.android.internal.R.string.status_bar_managed_profile);
mSlotRotate = context.getString(com.android.internal.R.string.status_bar_rotate);
mSlotHeadset = context.getString(com.android.internal.R.string.status_bar_headset);
mSlotDataSaver = context.getString(com.android.internal.R.string.status_bar_data_saver);
mRotationLockController.addRotationLockControllerCallback(this);
// listen for broadcasts
IntentFilter filter = new IntentFilter();
filter.addAction(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
filter.addAction(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION);
filter.addAction(AudioManager.ACTION_HEADSET_PLUG);
filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
filter.addAction(TelecomManager.ACTION_CURRENT_TTY_MODE_CHANGED);
filter.addAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
filter.addAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
filter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
mContext.registerReceiver(mIntentReceiver, filter, null, mHandler);
// listen for user / profile change.
try {
ActivityManagerNative.getDefault().registerUserSwitchObserver(mUserSwitchListener, TAG);
} catch (RemoteException e) {
// Ignore
}
// TTY status
mIconController.setIcon(mSlotTty, R.drawable.stat_sys_tty_mode, null);
mIconController.setIconVisibility(mSlotTty, false);
// bluetooth status
updateBluetooth();
// Alarm clock
mIconController.setIcon(mSlotAlarmClock, R.drawable.stat_sys_alarm, null);
mIconController.setIconVisibility(mSlotAlarmClock, false);
// zen
mIconController.setIcon(mSlotZen, R.drawable.stat_sys_zen_important, null);
mIconController.setIconVisibility(mSlotZen, false);
// volume
mIconController.setIcon(mSlotVolume, R.drawable.stat_sys_ringer_vibrate, null);
mIconController.setIconVisibility(mSlotVolume, false);
updateVolumeZen();
// cast
mIconController.setIcon(mSlotCast, R.drawable.stat_sys_cast, null);
mIconController.setIconVisibility(mSlotCast, false);
mCast.addCallback(mCastCallback);
// hotspot
mIconController.setIcon(mSlotHotspot, R.drawable.stat_sys_hotspot,
mContext.getString(R.string.accessibility_status_bar_hotspot));
mIconController.setIconVisibility(mSlotHotspot, mHotspot.isHotspotEnabled());
mHotspot.addCallback(mHotspotCallback);
// managed profile
mIconController.setIcon(mSlotManagedProfile, R.drawable.stat_sys_managed_profile_status,
mContext.getString(R.string.accessibility_managed_profile));
mIconController.setIconVisibility(mSlotManagedProfile, mManagedProfileIconVisible);
// data saver
mIconController.setIcon(mSlotDataSaver, R.drawable.stat_sys_data_saver,
context.getString(R.string.accessibility_data_saver_on));
mIconController.setIconVisibility(mSlotDataSaver, false);
mDataSaver.addListener(this);
}
public void setStatusBarKeyguardViewManager(
StatusBarKeyguardViewManager statusBarKeyguardViewManager) {
mStatusBarKeyguardViewManager = statusBarKeyguardViewManager;
}
public void setZenMode(int zen) {
mZen = zen;
updateVolumeZen();
}
private void updateAlarm() {
final AlarmClockInfo alarm = mAlarmManager.getNextAlarmClock(UserHandle.USER_CURRENT);
final boolean hasAlarm = alarm != null && alarm.getTriggerTime() > 0;
final boolean zenNone = mZen == Global.ZEN_MODE_NO_INTERRUPTIONS;
mIconController.setIcon(mSlotAlarmClock, zenNone ? R.drawable.stat_sys_alarm_dim
: R.drawable.stat_sys_alarm, null);
mIconController.setIconVisibility(mSlotAlarmClock, mCurrentUserSetup && hasAlarm);
}
private final void updateSimState(Intent intent) {
String stateExtra = intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE);
if (IccCardConstants.INTENT_VALUE_ICC_ABSENT.equals(stateExtra)) {
mSimState = IccCardConstants.State.ABSENT;
} else if (IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR.equals(stateExtra)) {
mSimState = IccCardConstants.State.CARD_IO_ERROR;
} else if (IccCardConstants.INTENT_VALUE_ICC_CARD_RESTRICTED.equals(stateExtra)) {
mSimState = IccCardConstants.State.CARD_RESTRICTED;
} else if (IccCardConstants.INTENT_VALUE_ICC_READY.equals(stateExtra)) {
mSimState = IccCardConstants.State.READY;
} else if (IccCardConstants.INTENT_VALUE_ICC_LOCKED.equals(stateExtra)) {
final String lockedReason =
intent.getStringExtra(IccCardConstants.INTENT_KEY_LOCKED_REASON);
if (IccCardConstants.INTENT_VALUE_LOCKED_ON_PIN.equals(lockedReason)) {
mSimState = IccCardConstants.State.PIN_REQUIRED;
} else if (IccCardConstants.INTENT_VALUE_LOCKED_ON_PUK.equals(lockedReason)) {
mSimState = IccCardConstants.State.PUK_REQUIRED;
} else {
mSimState = IccCardConstants.State.NETWORK_LOCKED;
}
} else {
mSimState = IccCardConstants.State.UNKNOWN;
}
}
private final void updateVolumeZen() {
AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
boolean zenVisible = false;
int zenIconId = 0;
String zenDescription = null;
boolean volumeVisible = false;
int volumeIconId = 0;
String volumeDescription = null;
if (DndTile.isVisible(mContext) || DndTile.isCombinedIcon(mContext)) {
zenVisible = mZen != Global.ZEN_MODE_OFF;
zenIconId = mZen == Global.ZEN_MODE_NO_INTERRUPTIONS
? R.drawable.stat_sys_dnd_total_silence : R.drawable.stat_sys_dnd;
zenDescription = mContext.getString(R.string.quick_settings_dnd_label);
} else if (mZen == Global.ZEN_MODE_NO_INTERRUPTIONS) {
zenVisible = true;
zenIconId = R.drawable.stat_sys_zen_none;
zenDescription = mContext.getString(R.string.interruption_level_none);
} else if (mZen == Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS) {
zenVisible = true;
zenIconId = R.drawable.stat_sys_zen_important;
zenDescription = mContext.getString(R.string.interruption_level_priority);
}
if (DndTile.isVisible(mContext) && !DndTile.isCombinedIcon(mContext)
&& audioManager.getRingerModeInternal() == AudioManager.RINGER_MODE_SILENT) {
volumeVisible = true;
volumeIconId = R.drawable.stat_sys_ringer_silent;
volumeDescription = mContext.getString(R.string.accessibility_ringer_silent);
} else if (mZen != Global.ZEN_MODE_NO_INTERRUPTIONS && mZen != Global.ZEN_MODE_ALARMS &&
audioManager.getRingerModeInternal() == AudioManager.RINGER_MODE_VIBRATE) {
volumeVisible = true;
volumeIconId = R.drawable.stat_sys_ringer_vibrate;
volumeDescription = mContext.getString(R.string.accessibility_ringer_vibrate);
}
if (zenVisible) {
mIconController.setIcon(mSlotZen, zenIconId, zenDescription);
}
if (zenVisible != mZenVisible) {
mIconController.setIconVisibility(mSlotZen, zenVisible);
mZenVisible = zenVisible;
}
if (volumeVisible) {
mIconController.setIcon(mSlotVolume, volumeIconId, volumeDescription);
}
if (volumeVisible != mVolumeVisible) {
mIconController.setIconVisibility(mSlotVolume, volumeVisible);
mVolumeVisible = volumeVisible;
}
updateAlarm();
}
@Override
public void onBluetoothDevicesChanged() {
updateBluetooth();
}
@Override
public void onBluetoothStateChange(boolean enabled) {
updateBluetooth();
}
private final void updateBluetooth() {
int iconId = R.drawable.stat_sys_data_bluetooth;
String contentDescription =
mContext.getString(R.string.accessibility_quick_settings_bluetooth_on);
boolean bluetoothEnabled = false;
if (mBluetooth != null) {
bluetoothEnabled = mBluetooth.isBluetoothEnabled();
if (mBluetooth.isBluetoothConnected()) {
iconId = R.drawable.stat_sys_data_bluetooth_connected;
contentDescription = mContext.getString(R.string.accessibility_bluetooth_connected);
}
}
mIconController.setIcon(mSlotBluetooth, iconId, contentDescription);
mIconController.setIconVisibility(mSlotBluetooth, bluetoothEnabled);
}
private final void updateTTY(Intent intent) {
int currentTtyMode = intent.getIntExtra(TelecomManager.EXTRA_CURRENT_TTY_MODE,
TelecomManager.TTY_MODE_OFF);
boolean enabled = currentTtyMode != TelecomManager.TTY_MODE_OFF;
if (DEBUG) Log.v(TAG, "updateTTY: enabled: " + enabled);
if (enabled) {
// TTY is on
if (DEBUG) Log.v(TAG, "updateTTY: set TTY on");
mIconController.setIcon(mSlotTty, R.drawable.stat_sys_tty_mode,
mContext.getString(R.string.accessibility_tty_enabled));
mIconController.setIconVisibility(mSlotTty, true);
} else {
// TTY is off
if (DEBUG) Log.v(TAG, "updateTTY: set TTY off");
mIconController.setIconVisibility(mSlotTty, false);
}
}
private void updateCast() {
boolean isCasting = false;
for (CastDevice device : mCast.getCastDevices()) {
if (device.state == CastDevice.STATE_CONNECTING
|| device.state == CastDevice.STATE_CONNECTED) {
isCasting = true;
break;
}
}
if (DEBUG) Log.v(TAG, "updateCast: isCasting: " + isCasting);
mHandler.removeCallbacks(mRemoveCastIconRunnable);
if (isCasting) {
mIconController.setIcon(mSlotCast, R.drawable.stat_sys_cast,
mContext.getString(R.string.accessibility_casting));
mIconController.setIconVisibility(mSlotCast, true);
} else {
// don't turn off the screen-record icon for a few seconds, just to make sure the user
// has seen it
if (DEBUG) Log.v(TAG, "updateCast: hiding icon in 3 sec...");
mHandler.postDelayed(mRemoveCastIconRunnable, 3000);
}
}
private void updateQuietState() {
mManagedProfileInQuietMode = false;
int currentUserId = ActivityManager.getCurrentUser();
for (UserInfo ui : mUserManager.getEnabledProfiles(currentUserId)) {
if (ui.isManagedProfile() && ui.isQuietModeEnabled()) {
mManagedProfileInQuietMode = true;
return;
}
}
}
private void profileChanged(int userId) {
UserInfo user = null;
if (userId == UserHandle.USER_CURRENT) {
try {
user = ActivityManagerNative.getDefault().getCurrentUser();
} catch (RemoteException e) {
// Ignore
}
} else {
user = mUserManager.getUserInfo(userId);
}
mManagedProfileFocused = user != null && user.isManagedProfile();
if (DEBUG) Log.v(TAG, "profileChanged: mManagedProfileFocused: " + mManagedProfileFocused);
// Actually update the icon later when transition starts.
}
private void updateManagedProfile() {
if (DEBUG) Log.v(TAG, "updateManagedProfile: mManagedProfileFocused: "
+ mManagedProfileFocused);
final boolean showIcon;
if (mManagedProfileFocused && !mStatusBarKeyguardViewManager.isShowing()) {
showIcon = true;
mIconController.setIcon(mSlotManagedProfile,
R.drawable.stat_sys_managed_profile_status,
mContext.getString(R.string.accessibility_managed_profile));
} else if (mManagedProfileInQuietMode) {
showIcon = true;
mIconController.setIcon(mSlotManagedProfile,
R.drawable.stat_sys_managed_profile_status_off,
mContext.getString(R.string.accessibility_managed_profile));
} else {
showIcon = false;
}
if (mManagedProfileIconVisible != showIcon) {
mIconController.setIconVisibility(mSlotManagedProfile, showIcon);
mManagedProfileIconVisible = showIcon;
}
}
private final SynchronousUserSwitchObserver mUserSwitchListener =
new SynchronousUserSwitchObserver() {
@Override
public void onUserSwitching(int newUserId) throws RemoteException {
mHandler.post(new Runnable() {
@Override
public void run() {
mUserInfoController.reloadUserInfo();
}
});
}
@Override
public void onUserSwitchComplete(int newUserId) throws RemoteException {
mHandler.post(new Runnable() {
@Override
public void run() {
updateAlarm();
profileChanged(newUserId);
updateQuietState();
updateManagedProfile();
}
});
}
@Override
public void onForegroundProfileSwitch(int newProfileId) {
mHandler.post(new Runnable() {
@Override
public void run() {
profileChanged(newProfileId);
}
});
}
};
private final HotspotController.Callback mHotspotCallback = new HotspotController.Callback() {
@Override
public void onHotspotChanged(boolean enabled) {
mIconController.setIconVisibility(mSlotHotspot, enabled);
}
};
private final CastController.Callback mCastCallback = new CastController.Callback() {
@Override
public void onCastDevicesChanged() {
updateCast();
}
};
public void appTransitionStarting(long startTime, long duration) {
updateManagedProfile();
}
public void notifyKeyguardShowingChanged() {
updateManagedProfile();
}
public void setCurrentUserSetup(boolean userSetup) {
if (mCurrentUserSetup == userSetup) return;
mCurrentUserSetup = userSetup;
updateAlarm();
updateQuietState();
}
@Override
public void onRotationLockStateChanged(boolean rotationLocked, boolean affordanceVisible) {
boolean portrait = RotationLockTile.isCurrentOrientationLockPortrait(
mRotationLockController, mContext);
if (rotationLocked) {
if (portrait) {
mIconController.setIcon(mSlotRotate, R.drawable.stat_sys_rotate_portrait,
mContext.getString(R.string.accessibility_rotation_lock_on_portrait));
} else {
mIconController.setIcon(mSlotRotate, R.drawable.stat_sys_rotate_landscape,
mContext.getString(R.string.accessibility_rotation_lock_on_landscape));
}
mIconController.setIconVisibility(mSlotRotate, true);
} else {
mIconController.setIconVisibility(mSlotRotate, false);
}
}
private void updateHeadsetPlug(Intent intent) {
boolean connected = intent.getIntExtra("state", 0) != 0;
boolean hasMic = intent.getIntExtra("microphone", 0) != 0;
if (connected) {
String contentDescription = mContext.getString(hasMic
? R.string.accessibility_status_bar_headset
: R.string.accessibility_status_bar_headphones);
mIconController.setIcon(mSlotHeadset, hasMic ? R.drawable.ic_headset_mic
: R.drawable.ic_headset, contentDescription);
mIconController.setIconVisibility(mSlotHeadset, true);
} else {
mIconController.setIconVisibility(mSlotHeadset, false);
}
}
@Override
public void onDataSaverChanged(boolean isDataSaving) {
mIconController.setIconVisibility(mSlotDataSaver, isDataSaving);
}
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)) {
updateAlarm();
} else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION) ||
action.equals(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION)) {
updateVolumeZen();
} else if (action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) {
updateSimState(intent);
} else if (action.equals(TelecomManager.ACTION_CURRENT_TTY_MODE_CHANGED)) {
updateTTY(intent);
} else if (action.equals(Intent.ACTION_MANAGED_PROFILE_AVAILABLE) ||
action.equals(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE) ||
action.equals(Intent.ACTION_MANAGED_PROFILE_REMOVED)) {
updateQuietState();
updateManagedProfile();
} else if (action.equals(AudioManager.ACTION_HEADSET_PLUG)) {
updateHeadsetPlug(intent);
}
}
};
private Runnable mRemoveCastIconRunnable = new Runnable() {
@Override
public void run() {
if (DEBUG) Log.v(TAG, "updateCast: hiding icon NOW");
mIconController.setIconVisibility(mSlotCast, false);
}
};
}
|
cable5881/pmq
|
mq-ui/src/main/java/com/ppdai/infrastructure/ui/controller/CatDataController.java
|
package com.ppdai.infrastructure.ui.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ppdai.infrastructure.mq.biz.ui.dto.request.CatGetDataRequest;
import com.ppdai.infrastructure.mq.biz.ui.dto.response.CatGetDataResponse;
import com.ppdai.infrastructure.ui.service.CatDataService;
@Controller
@RequestMapping("/cat")
public class CatDataController {
@Autowired
private CatDataService catDataService;
@RequestMapping("/data")
@ResponseBody
public CatGetDataResponse getCatData(CatGetDataRequest catGetDataRequest) {
CatGetDataResponse catDataResponse = catDataService.getCatData(catGetDataRequest);
return catDataResponse;
}
}
|
meldsza/online-examination-system
|
src/axios.js
|
<gh_stars>1-10
import axios from 'axios'
export default axios.create({
baseURL: process.env.VUE_AUTH_BASE_URL || 'http://localhost:4000/auth',
timeout: 1000,
});
|
PicturElements/lib
|
pkg/vue-admin/src/plugins/routing.js
|
import {
get,
hasOwn,
isObject,
resolveVal
} from "@qtxr/utils";
export default {
use(admin) {
admin.ui.routing = {
// Route URL
currentRoute: null,
// VueAdmin route proxies
proxies: {
current: null,
previous: null
},
// Vue route objects
currentRouteObject: null,
prevRouteObject: null,
// Public title data
title: null,
titleOverrides: [],
// Public sidebar data
sidebarNav: [],
sidebarOverrides: [],
// Public breadcrumb data
breadcrumbs: [],
breadcrumbOverrides: []
};
},
useOnce: true,
connect(admin, wrapper, meta) {
// Only apply to view components
if (meta.type != "view")
return;
const dispatchChange = (to, from) => {
if (to.path == admin.ui.routing.currentRoute)
return;
admin.ui.routing.currentRoute = to.path;
admin.ui.routing.currentRouteObject = to;
admin.ui.routing.prevRouteObject = from;
admin.ui.routing.proxies.current = to.meta.route;
admin.ui.routing.proxies.previous = from.meta.route;
const args = {
type: "change",
nextRoute: to,
prevRoute: from,
currentRoute: to,
route: to.meta.route,
rootRoute: getRootRoute(to.meta.route),
admin
};
updateTitle(args);
updateSidebarNav(args);
updateBreadcrumbs(args);
};
wrapper.addWatcher("$route", dispatchChange);
wrapper.addHook("beforeMount", function() {
dispatchChange(this.$route, this.$route);
});
wrapper.addComputed("ownRoute", function() {
return getOwnRoute(this);
});
wrapper.addComputed("subroutes", function() {
return getSubroutes(this);
});
wrapper.addComputed("exactRoute", function() {
return this.$route.meta.id == this.ownRoute.meta.id;
});
wrapper.addMethod("setTitle", function(overrider, persistent) {
setOverrider(this, admin.ui.routing.titleOverrides, overrider, persistent);
updateTitle(mkUpdateArgs(admin));
});
wrapper.addMethod("setSidebar", function(overrider, persistent) {
setOverrider(this, admin.ui.routing.sidebarOverrides, overrider, persistent);
updateSidebarNav(mkUpdateArgs(admin));
});
wrapper.addMethod("setBreadcrumb", function(overrider, persistent) {
setOverrider(this, admin.ui.routing.breadcrumbOverrides, overrider, persistent);
updateBreadcrumbs(mkUpdateArgs(admin));
});
wrapper.addMethod("setRouteUi", function(overrider, persistent) {
if (typeof overrider == "string") {
overrider = {
title: overrider,
sidebar: overrider,
breadcrumb: overrider
};
} else if (!isObject(overrider))
return;
persistent = typeof overrider.persistent == "boolean" ?
overrider.persistent :
persistent;
const keys = [
["title", "setTitle"],
["sidebar", "setSidebar"],
["breadcrumb", "setBreadcrumb"]
];
for (let i = 0, l = keys.length; i < l; i++) {
if (!hasOwn(overrider, keys[i][0]))
continue;
this[keys[i][1]](overrider[keys[i][0]], persistent);
}
});
}
};
function updateTitle(args) {
const route = args.route,
accessor = route.accessor;
let overrides = args.admin.ui.routing.titleOverrides;
// One of few times where we might want to trigger
// an update when the tab isn't in focus
setTimeout(_ => {
let title = get(args.route, "view.meta.title");
for (let i = 0, l = accessor.length; i < l; i++) {
const idx = accessor[i];
if (!overrides[idx])
overrides[idx] = mkOverriderPartition();
if (i == l - 1) {
clearOverrides(overrides, idx);
if (overrides[idx].overrider !== null)
title = overrides[idx].overrider.name;
}
overrides = overrides[idx].children;
}
title = resolveVal(title, args);
if (!title)
return;
title = String(title);
document.title = title;
args.admin.ui.routing.title = title;
}, 0);
}
function updateSidebarNav(args) {
const traverse = (routes, overrides, depth, absoluteDepth) => {
if (!routes)
return [];
const outRoutes = [];
let hasActiveRoute = false;
for (let i = 0, l = routes.length; i < l; i++) {
if (!overrides[i])
overrides[i] = mkOverriderPartition();
const route = routes[i],
sidebarMeta = Object.assign(
{},
get(route, "view.meta.sidebar"),
overrides[i].overrider
),
node = {
...matchMatchedRoute(args.nextRoute, route),
path: resolveParams(route.fullPath, args.nextRoute),
activeRoute: false,
route,
depth,
absoluteDepth,
children: null,
name: resolveVal(sidebarMeta.name, args),
display: resolveVal(sidebarMeta.display, args)
},
traversalData = node.display == "skip" ?
traverse(route.children, overrides[i].children, depth, absoluteDepth + 1) :
traverse(route.children, overrides[i].children, depth + 1, absoluteDepth + 1);
if (node.active)
clearOverrides(overrides, i);
node.children = traversalData.routes;
node.activeRoute = traversalData.hasActiveRoute || (node.matched && node.active);
node.active = node.active || (node.activeRoute && !node.children.length);
hasActiveRoute = node.activeRoute || hasActiveRoute;
switch (node.display) {
case "skip": {
for (let j = 0, l2 = node.children.length; j < l2; j++)
outRoutes.push(node.children[j]);
break;
}
case "active":
if (node.activeRoute)
outRoutes.push(node);
break;
case "hidden":
case false:
break;
case "visible":
case true:
default:
outRoutes.push(node);
}
}
return {
routes: outRoutes,
hasActiveRoute
};
};
args.admin.ui.routing.sidebarNav = traverse(
[args.rootRoute],
args.admin.ui.routing.sidebarOverrides,
0,
0
).routes;
}
function updateBreadcrumbs(args) {
const breadcrumbs = args.route.breadcrumbs,
accessor = args.route.accessor,
outBreadcrumbs = [];
let overrides = args.admin.ui.routing.breadcrumbOverrides;
for (let i = 0, l = breadcrumbs.length; i < l; i++) {
const idx = accessor[i];
if (!overrides[idx])
overrides[idx] = mkOverriderPartition();
if (i == l - 1)
clearOverrides(overrides, idx);
const crumb = Object.assign(
{},
breadcrumbs[i],
overrides[idx].overrider
);
crumb.path = resolveParams(crumb.path, args.nextRoute);
crumb.display = resolveVal(crumb.display, args) || "visible";
crumb.name = resolveVal(crumb.name, args);
switch (crumb.display) {
case "hidden":
case false:
break;
case "visible":
case true:
default:
outBreadcrumbs.push(crumb);
}
overrides = overrides[idx].children;
}
args.admin.ui.routing.breadcrumbs = outBreadcrumbs;
}
// %%%%%% UTILS %%%%%%
function mkOverriderPartition() {
return {
children: [],
overrider: null
};
}
function setOverrider(vm, overrides, overrider, persistent = null, factory = null) {
const route = getOwnRoute(vm);
if (!route || !route.accessor)
return null;
if (typeof overrider == "string" || typeof overrider == "function") {
overrider = {
name: overrider
};
} else if (!isObject(overrider))
return null;
const accessor = route.accessor;
let overriderPartition = null;
for (let i = 0, l = accessor.length; i < l; i++) {
const idx = accessor[i];
if (!overrides[idx]) {
const partition = typeof factory == "function" ?
factory() :
{};
partition.children = [];
partition.overrider = null;
overrides[idx] = partition;
}
overriderPartition = overrides[idx];
overrides = overrides[idx].children;
}
if (!overriderPartition)
return null;
overriderPartition.overrider = overrider;
overrider.persistent = typeof persistent == "boolean" ?
persistent :
overrider.persistent || false;
return overriderPartition;
}
function clearOverrides(overrides, idx) {
for (let i = 0, l = overrides.length; i < l; i++) {
const child = overrides[i];
if (!child)
continue;
if (i !== idx && (!child.overrider || !child.overrider.persistent))
child.overrider = null;
clearOverrides(child.children, -1);
}
}
function matchMatchedRoute(route, node) {
const nodeId = node.meta.id,
matched = route.matched;
for (let i = 0, l = matched.length; i < l; i++) {
const id = matched[i].meta.id;
if (id == nodeId) {
return {
matched: true,
active: i == matched.length - 1
};
}
}
return {
matched: false,
active: false
};
}
function resolveParams(path, nextRoute) {
return path.replace(/:(\w+)/g, (match, key) => {
if (!hasOwn(nextRoute.params, key))
return match;
return nextRoute.params[key];
});
}
function getRootRoute(route) {
while (true) {
if (!route.parent)
return route;
route = route.parent;
}
}
function getOwnRoute(vm) {
const matched = vm.$route.matched;
for (let i = matched.length - 1; i >= 0; i--) {
const match = matched[i];
for (const k in match.instances) {
if (hasOwn(match.instances, k) && match.instances[k] == vm)
return match.meta.route;
}
}
return null;
}
function getSubroutes(vm) {
const route = getOwnRoute(vm);
if (!route)
return [];
const children = route.meta.route.children,
outChildren = [];
for (let i = 0, l = children.length; i < l; i++) {
const child = children[i],
outRoute = {
route: child
},
linkConfig = child.linkConfig,
navConfig = child.sidebarConfig,
args = {
route,
rootRoute: getRootRoute(route),
admin: vm.admin
};
outRoute.path = resolveParams(child.fullPath, vm.$route);
outRoute.name = resolveVal(linkConfig.name || navConfig.name, args);
outRoute.display = resolveVal(linkConfig.display, args) || "visible";
switch (outRoute.display) {
case "hidden":
case false:
break;
case "visible":
case true:
default:
outChildren.push(outRoute);
}
}
return outChildren;
}
function mkUpdateArgs(admin) {
const currentRoute = admin.ui.routing.currentRouteObject;
return {
type: "update",
nextRoute: currentRoute,
prevRoute: admin.ui.routing.prevRouteObject,
currentRoute,
route: currentRoute.meta.route,
rootRoute: getRootRoute(currentRoute.meta.route),
admin
};
}
|
jjzhang166/telegram-app
|
telegram/scope/templates.h
|
<filename>telegram/scope/templates.h
#pragma once
// TODO Add Telegram mascot / icon
const static std::string ERROR_TEMPLATE = R"({
"schema-version": 1,
"template": {
"category-layout": "grid",
"card-layout": "horizontal",
"card-size": "small"
},
"components": {
"title": "title",
"subtitle": "subtitle"
}
})";
const static std::string LOGIN_TEMPLATE = R"({
"schema-version": 1,
"template": {
"category-layout": "grid",
"card-size": "large"
},
"components": {
"title": "title",
"mascot": "mascot"
}
})";
const static std::string UNREAD_MESSAGES_TEMPLATE = R"({
"schema-version": 1,
"template": {
"category-layout": "grid",
"card-layout": "horizontal",
"card-size": "small",
"collapsed-rows": 1
},
"components": {
"title": "title",
"mascot" : "avatar",
"subtitle": "subtitle"
}
})";
static const std::string RECENT_MESSAGES_TEMPLATE = R"({
"schema-version": 1,
"template": {
"category-layout": "grid",
"card-layout": "horizontal",
"card-size": "small",
"collapsed-rows": 2
},
"components": {
"mascot" : "avatar",
"title": "title",
"subtitle": "subtitle"
}
})";
const static std::string MESSAGES_SEARCH_TEMPLATE = R"({
"schema-version": 1,
"template": {
"category-layout": "grid",
"card-layout": "horizontal",
"card-size": "small",
"collapsed-rows": 5
},
"components": {
"title": "title",
"mascot" : "avatar",
"subtitle": "subtitle"
}
})";
const static std::string CONTACTS_SEARCH_TEMPLATE = R"({
"schema-version": 1,
"template": {
"category-layout": "grid",
"card-layout": "horizontal",
"card-size": "small",
"collapsed-rows": 5
},
"components": {
"title": "title",
"art" : "avatar"
}
})";
const static std::string CONTATS_TEMPLATE = R"({
"schema-version": 1,
"template": {
"category-layout": "carousel",
"card-size": "small",
"overlay": true
},
"components": {
"title": "title",
"art" : "avatar"
}
})";
const static std::string PHOTO_MESSAGES_TEMPLATE = R"({
"schema-version": 1,
"template": {
"category-layout": "grid",
"card-size": "small",
"collapsed-rows": 0
},
"components": {
"art" : "mediaThumb"
}
})";
|
CBD-Forum/Genesis-crowd-funding
|
letv-crowdfund-core/src/main/java/com/fbd/core/app/crowdfunding/model/CrowdfundingOperateDataModel.java
|
package com.fbd.core.app.crowdfunding.model;
import java.util.Date;
import com.fbd.core.base.BaseModel;
public class CrowdfundingOperateDataModel extends BaseModel {
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String loanNo;
private Integer registerNumByDay;
private Integer userNumByDay;
private Double retentionByNextDay;
private Integer registerNumByMonth;
private Integer userNumByMonth;
private Double retentionByNextMonth;
private Integer payUserNum;
private Date createTime;
private Date updateTime;
private String expectedReturn;
private String tempLoanNo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getLoanNo() {
return loanNo;
}
public void setLoanNo(String loanNo) {
this.loanNo = loanNo == null ? null : loanNo.trim();
}
/**
* @return the registerNumByDay
*/
public Integer getRegisterNumByDay() {
return registerNumByDay;
}
/**
* @param registerNumByDay the registerNumByDay to set
*/
public void setRegisterNumByDay(Integer registerNumByDay) {
this.registerNumByDay = registerNumByDay;
}
/**
* @return the userNumByDay
*/
public Integer getUserNumByDay() {
return userNumByDay;
}
/**
* @param userNumByDay the userNumByDay to set
*/
public void setUserNumByDay(Integer userNumByDay) {
this.userNumByDay = userNumByDay;
}
/**
* @return the retentionByNextDay
*/
public Double getRetentionByNextDay() {
return retentionByNextDay;
}
/**
* @param retentionByNextDay the retentionByNextDay to set
*/
public void setRetentionByNextDay(Double retentionByNextDay) {
this.retentionByNextDay = retentionByNextDay;
}
/**
* @return the registerNumByMonth
*/
public Integer getRegisterNumByMonth() {
return registerNumByMonth;
}
/**
* @param registerNumByMonth the registerNumByMonth to set
*/
public void setRegisterNumByMonth(Integer registerNumByMonth) {
this.registerNumByMonth = registerNumByMonth;
}
/**
* @return the userNumByMonth
*/
public Integer getUserNumByMonth() {
return userNumByMonth;
}
/**
* @param userNumByMonth the userNumByMonth to set
*/
public void setUserNumByMonth(Integer userNumByMonth) {
this.userNumByMonth = userNumByMonth;
}
/**
* @return the retentionByNextMonth
*/
public Double getRetentionByNextMonth() {
return retentionByNextMonth;
}
/**
* @param retentionByNextMonth the retentionByNextMonth to set
*/
public void setRetentionByNextMonth(Double retentionByNextMonth) {
this.retentionByNextMonth = retentionByNextMonth;
}
/**
* @return the payUserNum
*/
public Integer getPayUserNum() {
return payUserNum;
}
/**
* @param payUserNum the payUserNum to set
*/
public void setPayUserNum(Integer payUserNum) {
this.payUserNum = payUserNum;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/**
* @return the expectedReturn
*/
public String getExpectedReturn() {
return expectedReturn;
}
/**
* @param expectedReturn the expectedReturn to set
*/
public void setExpectedReturn(String expectedReturn) {
this.expectedReturn = expectedReturn;
}
/**
* @return the tempLoanNo
*/
public String getTempLoanNo() {
return tempLoanNo;
}
/**
* @param tempLoanNo the tempLoanNo to set
*/
public void setTempLoanNo(String tempLoanNo) {
this.tempLoanNo = tempLoanNo;
}
}
|
ScalablyTyped/SlinkyTyped
|
a/arcgis-js-api/src/main/scala/typingsSlinky/arcgisJsApi/buildingGroupSublayerMod.scala
|
<filename>a/arcgis-js-api/src/main/scala/typingsSlinky/arcgisJsApi/buildingGroupSublayerMod.scala
package typingsSlinky.arcgisJsApi
import org.scalablytyped.runtime.Shortcut
import typingsSlinky.arcgisJsApi.esri.BuildingGroupSublayer
import typingsSlinky.arcgisJsApi.esri.BuildingGroupSublayerConstructor
import typingsSlinky.arcgisJsApi.esri.BuildingGroupSublayerProperties
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object buildingGroupSublayerMod extends Shortcut {
@JSImport("esri/layers/buildingSublayers/BuildingGroupSublayer", JSImport.Namespace)
@js.native
val ^ : BuildingGroupSublayerConstructor = js.native
/* This class was inferred from a value with a constructor, it was renamed because a distinct type already exists with the same name. */
@JSImport("esri/layers/buildingSublayers/BuildingGroupSublayer", JSImport.Namespace)
@js.native
class Class () extends BuildingGroupSublayer {
def this(properties: BuildingGroupSublayerProperties) = this()
}
type _To = BuildingGroupSublayerConstructor
/* This means you don't have to write `^`, but can instead just say `buildingGroupSublayerMod.foo` */
override def _to: BuildingGroupSublayerConstructor = ^
}
|
thanos/phonescript
|
phonescript/me4se/src/org/me4se/impl/gcf/ConnectionImpl_http.java
|
// ME4SE - A MicroEdition Emulation for J2SE
//
// Copyright (C) 2001 <NAME>, Oberhausen (Rhld.), Germany
//
// Contributors:
//
// STATUS: API Complete
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version. This program is
// distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
// License for more details. You should have received a copy of the
// GNU General Public License along with this program; if not, write
// to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
// Andre, this is the old version; I have shifted your version
// to src_applet in order to be able to build a "simple" version
// for execution on PJava devices.
package org.me4se.impl.gcf;
import java.io.*;
import java.util.*;
import java.net.*;
import javax.microedition.io.*;
public class ConnectionImpl_http
extends ConnectionImpl
implements HttpConnection {
public void initialise(Properties properties) {
httpProxyHost = properties.getProperty("httpProxyHost");
if (httpProxyHost != null)
httpProxyPort =
Integer.parseInt(properties.getProperty("httpProxyPort"));
}
URL url;
HttpURLConnection con;
public static String httpProxyHost = null;
public static int httpProxyPort = -1;
public void open(String url, int mode, boolean timeouts)
throws IOException {
this.url = new URL(url);
con = (HttpURLConnection) this.url.openConnection();
con.setUseCaches(false);
con.setDoOutput((mode & Connector.WRITE) != 0);
con.setDoInput((mode & Connector.READ) != 0);
con.setRequestProperty("connection", "close");
}
public long getDate() throws IOException {
return con.getDate();
}
public String getEncoding() {
return con.getContentEncoding();
}
public long getExpiration() throws IOException {
return con.getExpiration();
}
public String getFile() {
return url.getFile();
}
public String getHeaderField(String key) throws IOException {
return con.getHeaderField(key);
}
public String getHeaderField(int index) throws IOException {
return con.getHeaderField(index);
}
public int getHeaderFieldInt(String key, int def) throws IOException {
return con.getHeaderFieldInt(key, def);
}
public String getHeaderFieldKey(int index) throws IOException {
return con.getHeaderFieldKey(index);
}
public long getHeaderFieldDate(String key, long def) throws IOException {
return con.getHeaderFieldDate(key, def);
}
public String getHost() {
return url.getHost();
}
public long getLength() {
return con.getContentLength();
}
public long getLastModified() throws IOException {
return con.getLastModified();
}
public int getPort() {
return url.getPort();
}
public String getProtocol() {
return url.getProtocol();
}
public String getQuery() {
String s = url.toString();
int cut = s.indexOf('?');
return cut == -1 ? null : s.substring(cut + 1);
}
public String getRef() {
return url.getRef();
}
public int getResponseCode() throws IOException {
int code = 0;
try {
code = con.getResponseCode();
}
catch (FileNotFoundException fnfex) {
code = HttpConnection.HTTP_NOT_FOUND;
}
catch (IOException ioex) {
if (ioex.getMessage().startsWith("file not found")) {
code = HttpConnection.HTTP_NOT_FOUND;
}
else {
throw ioex;
}
}
return code;
}
public String getRequestProperty(String name) {
return con.getRequestProperty(name);
}
public String getType() {
return con.getContentType();
}
public String getURL() {
return url.toString();
}
public String getRequestMethod() {
return con.getRequestMethod();
}
public String getResponseMessage() throws IOException {
return con.getResponseMessage();
}
public void setRequestMethod(String method) throws IOException {
con.setRequestMethod(method);
}
public void setRequestProperty(String key, String value)
throws IOException {
con.setRequestProperty(key, value);
}
public InputStream openInputStream() throws IOException {
// con.getOutputStream ().flush ();
if (con.getResponseCode() >= 300)
return con.getErrorStream();
//try {
return con.getInputStream();
//}
//catch (IOException e) {
// InputStream is = con.getErrorStream ();
//if (is == null) throw e;
// return is;
// }
}
public DataInputStream openDataInputStream() throws IOException {
return new DataInputStream(openInputStream());
}
public OutputStream openOutputStream() throws IOException {
return con.getOutputStream();
}
public DataOutputStream openDataOutputStream() throws IOException {
return new DataOutputStream(openOutputStream());
}
public void close() {
con.disconnect();
//getOutputStream ().close ();
//con.getInputStream ().close ();
}
}
|
tcaram/astroquery
|
astroquery/cadc/tests/DummyJob.py
|
<filename>astroquery/cadc/tests/DummyJob.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
=============
Cadc TAP plus
=============
"""
class DummyJob(object):
def __init__(self):
self.parameters = {}
self.jobid = '123'
self.outputFile = 'file.txt'
self._phase = 'new'
self.remoteLocation = 'www.host.com/place'
self.results = 'results'
self.connHandler = None
def reset(self):
self.parameters = {}
def set_parameter(self, key, value):
self.parameters[key] = value
def _Job__responseStatus(self):
return '200'
def _Job__responseMsg(self):
return 'ok'
|
PremierLangage/platon_assets
|
apps/pl_notifications/migrations/0001_initial.py
|
<filename>apps/pl_notifications/migrations/0001_initial.py<gh_stars>0
# Generated by Django 3.2.3 on 2021-06-02 12:56
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Notification',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type', models.CharField(max_length=20)),
('data', models.JSONField(blank=True, default=dict)),
('date', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notifications_users', to=settings.AUTH_USER_MODEL)),
],
),
]
|
npocmaka/Windows-Server-2003
|
base/wow64/wow64/debug.c
|
/*++
Copyright (c) 1998 Microsoft Corporation
Module Name:
debug.c
Abstract:
Debugging/Logging helpers
Author:
11-May-1998 BarryBo
Revision History:
05-Oct-1999 SamerA <NAME>
Move logging code to wow64ext.dll
05-Dec-2001 SamerA <NAME>
Code cleanup. Remove profiling code.
--*/
#define _WOW64DLLAPI_
#include <nt.h>
#include <ntrtl.h>
#include <nturtl.h>
#include <ntverp.h>
#include <stdio.h>
#include <stdlib.h>
#include "wow64p.h"
#include "wow64log.h"
ASSERTNAME;
//
// Wow64log functions
//
PFNWOW64LOGINITIALIZE pfnWow64LogInitialize;
PFNWOW64LOGSYSTEMSERVICE pfnWow64LogSystemService;
PFNWOW64LOGMESSAGEARGLIST pfnWow64LogMessageArgList;
PFNWOW64LOGTERMINATE pfnWow64LogTerminate;
///////////////////////////////////////////////////////////////////////////////////////
//
// Generic utility routines.
//
///////////////////////////////////////////////////////////////////////////////////////
PWSTR
GetImageName(
IN PWSTR DefaultImageName
)
/*++
Routine Description:
Gets the name of this image.
Arguments:
DefaultImageName - Supplies the name to return on error.
Return Value:
Success - The image name allocated with Wow64AllocateHeap.
Failure - DefaultImageName
--*/
{
// Get the image name
PPEB Peb;
PWSTR Temp = NULL;
PUNICODE_STRING ImagePathName;
PWSTR ReturnValue;
NTSTATUS Status;
PVOID LockCookie = NULL;
Peb = NtCurrentPeb();
LdrLockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS, NULL, &LockCookie);
try {
PWCHAR Index;
ULONG NewLength;
if (!Peb->ProcessParameters) {
Temp = DefaultImageName;
leave;
}
ImagePathName = &(Peb->ProcessParameters->ImagePathName);
if (!ImagePathName->Buffer || !ImagePathName->Length) {
Temp = DefaultImageName;
leave;
}
//Strip off the path from the image name.
//Start just after the last character
Index = (PWCHAR)((PCHAR)ImagePathName->Buffer + ImagePathName->Length);
while(Index-- != ImagePathName->Buffer && *Index != '\\');
Index++;
NewLength = (ULONG)((ULONG_PTR)((PCHAR)ImagePathName->Buffer + ImagePathName->Length) - (ULONG_PTR)(Index));
Temp = Wow64AllocateHeap(NewLength+sizeof(UNICODE_NULL));
if (!Temp) {
Temp = DefaultImageName;
__leave;
}
RtlCopyMemory(Temp, Index, NewLength);
Temp[(NewLength / sizeof(WCHAR))] = L'\0';
} __finally {
LdrUnlockLoaderLock(LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS, LockCookie);
}
return Temp;
}
///////////////////////////////////////////////////////////////////////////////////////
//
// Generic IO utility routines.
//
///////////////////////////////////////////////////////////////////////////////////////
VOID
FPrintf(
IN HANDLE Handle,
IN CHAR *Format,
...
)
/*++
Routine Description:
The same as the C library function fprintf, except errors are ignored and output is to a
NT executive file handle.
Arguments:
Handle - Supplies a NT executive file handle to write to.
Format - Supplies the format specifier.
Return Value:
None. All errors are ignored.
--*/
{
va_list pArg;
CHAR Buffer[1024];
int c;
IO_STATUS_BLOCK IoStatus;
va_start(pArg, Format);
if (-1 == (c = _vsnprintf(Buffer, sizeof (Buffer), Format, pArg))) {
return;
}
NtWriteFile(Handle,
NULL,
NULL,
NULL,
&IoStatus,
Buffer,
c,
NULL,
NULL);
}
///////////////////////////////////////////////////////////////////////////////////////
//
// Logging and assert routines.
//
///////////////////////////////////////////////////////////////////////////////////////
void
LogOut(
IN UCHAR LogLevel,
IN char *pLogOut
)
/*++
Routine Description:
Generic helper routine which outputs the string to the appropriate
destination(s).
Arguments:
pLogOut - string to output
Return Value:
None.
--*/
{
//
// Send the output to the debugger, if log flag is ERRORLOG.
//
if (LogLevel == ERRORLOG)
{
DbgPrint(pLogOut);
}
}
WOW64DLLAPI
VOID
Wow64Assert(
IN CONST PSZ exp,
OPTIONAL IN CONST PSZ msg,
IN CONST PSZ mod,
IN LONG line
)
/*++
Routine Description:
Function called in the event that an assertion failed. This is always
exported from wow64.dll, so a checked thunk DLL can coexist with a retail
wow64.dll.
Arguments:
exp - text representation of the expression from the assert
msg - OPTIONAL message to display
mod - text of the source filename
line - line number within 'mod'
Return Value:
None.
--*/
{
#if DBG
if (msg) {
LOGPRINT((ERRORLOG, "WOW64 ASSERTION FAILED:\r\n %s\r\n%s\r\nFile: %s Line %d\r\n", msg, exp, mod, line));
} else {
LOGPRINT((ERRORLOG, "WOW64 ASSERTION FAILED:\r\n %s\r\nFile: %s Line %d\r\n", exp, mod, line));
}
if (NtCurrentPeb()->BeingDebugged) {
DbgBreakPoint();
}
#endif
}
void
WOW64DLLAPI
Wow64LogPrint(
UCHAR LogLevel,
char *format,
...
)
/*++
Routine Description:
WOW64 logging mechanism. If LogLevel > ModuleLogLevel then print the
message, else do nothing.
Arguments:
LogLevel - requested verbosity level
format - printf-style format string
... - printf-style args
Return Value:
None.
--*/
{
int i, Len;
va_list pArg;
char *pch;
char Buffer[1024];
//
// Call wow64log DLL if loaded
//
if (pfnWow64LogMessageArgList)
{
va_start(pArg, format);
(*pfnWow64LogMessageArgList)(LogLevel, format, pArg);
va_end(pArg);
return;
}
pch = Buffer;
Len = sizeof(Buffer) - 1;
i = _snprintf(pch, Len, "%8.8X:%8.8X ",
PtrToUlong(NtCurrentTeb()->ClientId.UniqueProcess),
PtrToUlong(NtCurrentTeb()->ClientId.UniqueThread));
ASSERT((PVOID)PtrToUlong(NtCurrentTeb()->ClientId.UniqueProcess) == NtCurrentTeb()->ClientId.UniqueProcess);
ASSERT((PVOID)PtrToUlong(NtCurrentTeb()->ClientId.UniqueThread) == NtCurrentTeb()->ClientId.UniqueThread);
if (i == -1) {
i = sizeof(Buffer) - 1;
Buffer[i] = '\0';
} else if (i < 0) {
return;
}
Len -= i;
pch += i;
va_start(pArg, format);
i = _vsnprintf(pch, Len, format, pArg);
// Force null termination in case the call fails. It may return
// sizeof(buffer) and not null-terminate!
Buffer[sizeof(Buffer)-1] = '\0';
LogOut(LogLevel, Buffer);
}
///////////////////////////////////////////////////////////////////////////////////////
//
// Startup and shutdown routines.
//
///////////////////////////////////////////////////////////////////////////////////////
NTSTATUS
Wow64pLoadLogDll(
VOID)
{
NTSTATUS NtStatus;
UNICODE_STRING Wow64LogDllName;
ANSI_STRING ProcName;
PVOID Wow64LogDllBase = NULL;
RtlInitUnicodeString(&Wow64LogDllName, L"wow64log.dll");
NtStatus = LdrLoadDll(NULL, NULL, &Wow64LogDllName, &Wow64LogDllBase);
if (NT_SUCCESS(NtStatus))
{
//
// Get the entry points
//
RtlInitAnsiString(&ProcName, "Wow64LogInitialize");
NtStatus = LdrGetProcedureAddress(Wow64LogDllBase,
&ProcName,
0,
(PVOID *) &pfnWow64LogInitialize);
if (NT_SUCCESS(NtStatus))
{
RtlInitAnsiString(&ProcName, "Wow64LogSystemService");
NtStatus = LdrGetProcedureAddress(Wow64LogDllBase,
&ProcName,
0,
(PVOID *) &pfnWow64LogSystemService);
if (!NT_SUCCESS(NtStatus))
{
goto RetStatus;
}
RtlInitAnsiString(&ProcName, "Wow64LogMessageArgList");
NtStatus = LdrGetProcedureAddress(Wow64LogDllBase,
&ProcName,
0,
(PVOID *) &pfnWow64LogMessageArgList);
if (!NT_SUCCESS(NtStatus))
{
goto RetStatus;
}
RtlInitAnsiString(&ProcName, "Wow64LogTerminate");
NtStatus = LdrGetProcedureAddress(Wow64LogDllBase,
&ProcName,
0,
(PVOID *) &pfnWow64LogTerminate);
//
// If all is well, then let's initialize
//
if (NT_SUCCESS(NtStatus))
{
NtStatus = (*pfnWow64LogInitialize)();
}
}
}
RetStatus:
if (!NT_SUCCESS(NtStatus))
{
pfnWow64LogInitialize = NULL;
pfnWow64LogSystemService = NULL;
pfnWow64LogMessageArgList = NULL;
pfnWow64LogTerminate = NULL;
if (Wow64LogDllBase)
{
LdrUnloadDll(Wow64LogDllBase);
}
}
return NtStatus;
}
VOID
InitializeDebug(
VOID
)
/*++
Routine Description:
Initializes the debug system of wow64.
Arguments:
None.
Return Value:
None.
--*/
{
Wow64pLoadLogDll();
}
VOID ShutdownDebug(
VOID
)
/*++
Routine Description:
Shutdown the debug system of wow64.
Arguments:
None.
Return Value:
None.
--*/
{
if (pfnWow64LogTerminate)
{
(*pfnWow64LogTerminate)();
}
}
|
Saikou-Bot/SaikouBotV2
|
models/userItems.js
|
<reponame>Saikou-Bot/SaikouBotV2<filename>models/userItems.js
if (!mongoose) var mongoose = require('mongoose');
const useritemsSchema = mongoose.Schema({
username: String,
userID: String,
itemName: String,
itemQuantity: Number,
itemSell: Number,
itemEmoji: String,
itemType: String,
multipurchase: Boolean,
});
module.exports = mongoose.model('userItems', useritemsSchema);
|
naojiangzhalie666/morebit-android-app
|
app/src/main/java/com/zjzy/morebit/pojo/request/base/RequestBaseTypeBean.java
|
<filename>app/src/main/java/com/zjzy/morebit/pojo/request/base/RequestBaseTypeBean.java<gh_stars>1-10
package com.zjzy.morebit.pojo.request.base;
import com.zjzy.morebit.pojo.request.RequestBaseBean;
/**
* Created by fengrs on 2019/1/9.
* 备注:
*/
public class RequestBaseTypeBean extends RequestBaseBean {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
joewang96/joewang.dev
|
src/components/menu/MenuLink.js
|
import React from 'react';
import styled, { css } from 'styled-components';
import { Link } from 'gatsby';
import { COLORS, FONTS } from '../../tokens';
import A from '../../elements/A';
import MenuContext from './MenuContext';
const LinkComponent = styled(props => {
const { active: __active, external, href, ...rest } = props;
const Component = external ? A : Link;
return <Component {...rest} href={href} />;
})`
color: ${({ to, pathname }) =>
to && pathname === to ? COLORS.WHITE : COLORS.LIGHT_GREY};
text-decoration: none;
transition: color 250ms ease-in-out;
&:hover,
&:focus {
color: ${COLORS.WHITE};
}
${({ use }) =>
use === 'case-study'
? css`
font-family: ${FONTS.SERIF};
font-size: 1.125rem;
font-style: italic;
&:not(:last-of-type) {
margin-bottom: 1.25rem;
}
`
: css`
font-family: ${FONTS.SANS};
font-size: 1.5rem;
font-weight: 600;
`};
`;
class MenuLink extends React.Component {
render() {
return (
<MenuContext.Consumer>
{value => (
<LinkComponent
{...this.props}
{...value}
tabIndex={!value.active ? -1 : null}
/>
)}
</MenuContext.Consumer>
);
}
}
export default MenuLink;
|
reffs123/PyQtDarkTheme
|
tools/test_freezing_lib/__main__.py
|
"""Module allowing for `python -m tools.test_freezing_lib`."""
import sys
from tools.test_freezing_lib.main import main
if __name__ == "__main__":
sys.exit(main())
|
aayushkapoor206/whatshot
|
node_modules/angular2/es6/prod/tools.js
|
<filename>node_modules/angular2/es6/prod/tools.js
/*
* Debugging and profiling tools for Angular 2
*/
export { enableDebugTools, disableDebugTools } from 'angular2/src/tools/tools';
//# sourceMappingURL=tools.js.map
|
tjquinno/helidon-build-tools
|
archetype/engine-v2/src/main/java/io/helidon/build/archetype/engine/v2/interpreter/ContextNodeFromDefaultValueCreator.java
|
/*
* Copyright (c) 2021 Oracle and/or its affiliates.
*
* 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 io.helidon.build.archetype.engine.v2.interpreter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Create {@code ContextNodeAST} instance using default values of the corresponding {@code InputNodeAST} node.
*/
class ContextNodeFromDefaultValueCreator extends GenericVisitorEmptyImpl<ContextNodeAST, ASTNode> {
@Override
public ContextNodeAST visit(InputEnumAST input, ASTNode arg) {
if (input.defaultValue() == null) {
return null;
}
ContextEnumAST result = new ContextEnumAST(input.path());
result.value(input.defaultValue());
return result;
}
@Override
public ContextNodeAST visit(InputListAST input, ASTNode arg) {
if (input.defaultValue() == null) {
return null;
}
ContextListAST result = new ContextListAST(input.path());
List<String> values = Stream.of(input.defaultValue().split(",")).map(String::trim).collect(Collectors.toList());
result.values().addAll(values);
return result;
}
@Override
public ContextNodeAST visit(InputBooleanAST input, ASTNode arg) {
if (input.defaultValue() == null) {
return null;
}
ContextBooleanAST result = new ContextBooleanAST(input.path());
result.bool(input.defaultValue().trim().equalsIgnoreCase("yes"));
return result;
}
@Override
public ContextNodeAST visit(InputTextAST input, ASTNode arg) {
if (input.defaultValue() == null && input.placeHolder() == null) {
return null;
}
ContextTextAST result = new ContextTextAST(input.path());
result.text(input.placeHolder() != null ? input.placeHolder() : input.defaultValue());
return result;
}
}
|
vadkasevas/BAS
|
Engine/addavexclusion.h
|
<gh_stars>100-1000
#ifndef ADDAVEXCLUSION_H
#define ADDAVEXCLUSION_H
#include "engine_global.h"
#include <QObject>
namespace BrowserAutomationStudioFramework
{
class ENGINESHARED_EXPORT AddAVExclusion : public QObject
{
Q_OBJECT
public:
explicit AddAVExclusion(QObject *parent = 0);
void Run();
};
}
#endif // ADDAVEXCLUSION_H
|
jarnoln/mitasny
|
mitasny/settings.py
|
"""
Django settings for mitasny project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
import sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
SETTINGS_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(SETTINGS_DIR)
SITE_DIR = os.path.dirname(BASE_DIR)
PROJECT_NAME = os.path.basename(SETTINGS_DIR)
# If secret_key.py does not exist, create it like this:
# python generate_secret.py > secret_key.py
try:
from .passwords import SECRET_KEY
except ImportError:
print('Password file does not exist. How to create it:')
print('python {}/generate_passwords.py {}/passwords.py'.format(PROJECT_NAME, PROJECT_NAME))
sys.exit(1)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'mitasny.com', 'www.mitasny.com', 'mitasny.luomanirva.net']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tasks',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mitasny.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mitasny.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Helsinki'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(SITE_DIR, 'static'),
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(module)s %(message)s'
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'),
},
'tasks': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
},
},
}
|
Osallek/Eu4SaveEditor
|
src/main/java/fr/osallek/eu4saveeditor/controller/converter/ProvinceStringCallBack.java
|
<gh_stars>1-10
package fr.osallek.eu4saveeditor.controller.converter;
import fr.osallek.clausewitzparser.common.ClausewitzUtils;
import fr.osallek.eu4parser.model.save.province.SaveProvince;
import javafx.util.Callback;
public class ProvinceStringCallBack implements Callback<SaveProvince, String> {
@Override
public String call(SaveProvince param) {
return ClausewitzUtils.removeQuotes(param.getName()) + " (" + param.getId() + ")";
}
}
|
Tusky/cache-dependencies
|
cache_dependencies/transaction.py
|
<filename>cache_dependencies/transaction.py<gh_stars>1-10
import time
from functools import wraps
from cache_dependencies import dependencies, interfaces, mixins, utils
from cache_dependencies.utils import Undef
class AbstractTransaction(interfaces.ITransaction):
def __init__(self, lock):
"""
:type lock: cache_dependencies.interfaces.IDependencyLock
"""
self._lock = lock
def get_session_id(self):
return utils.get_thread_id()
def evaluate(self, dependency, version):
"""
:type dependency: cache_dependencies.interfaces.IDependency
:type version: int or None
"""
return self._lock.evaluate(dependency, self, version)
@staticmethod
def _current_time():
return time.time()
class Transaction(AbstractTransaction):
def __init__(self, lock):
"""
:type lock: cache_dependencies.interfaces.IDependencyLock
"""
super(Transaction, self).__init__(lock)
self._dependencies = dict()
self._start_time = self._current_time()
self._end_time = None
def get_start_time(self):
return self._start_time
def get_end_time(self):
if self._end_time is None:
raise RuntimeError("Transaction is not finished yet!")
return self._end_time
def parent(self):
return None
def add_dependency(self, dependency, version):
"""
:type dependency: cache_dependencies.interfaces.IDependency
:type version: int or None
"""
assert isinstance(dependency, interfaces.IDependency)
if version not in self._dependencies:
self._dependencies[version] = dependencies.CompositeDependency()
self._dependencies[version].extend(dependency)
self._lock.acquire(dependency, self, version)
def finish(self):
self._end_time = self._current_time()
for version, dependency in self._dependencies.items():
self._lock.release(dependency, self, version)
def __bool__(self):
return True
class SavePoint(Transaction):
def __init__(self, lock, parent):
"""
:type lock: cache_dependencies.interfaces.IDependencyLock
:type parent: cache_dependencies.transaction.Transaction or cache_dependencies.transaction.SavePoint
"""
super(SavePoint, self).__init__(lock)
assert isinstance(parent, interfaces.ITransaction)
self._parent = parent
def get_start_time(self):
return self.parent().get_start_time()
def get_end_time(self):
return self.parent().get_end_time()
def parent(self):
return self._parent
def add_dependency(self, dependency, version):
"""
:type dependency: cache_dependencies.interfaces.IDependency
:type version: int or None
"""
assert isinstance(dependency, interfaces.IDependency)
super(SavePoint, self).add_dependency(dependency, version)
self._parent.add_dependency(dependency, version)
def finish(self):
pass
class DummyTransaction(AbstractTransaction):
def get_start_time(self):
return self._current_time()
def get_end_time(self):
return self._current_time()
def parent(self):
return None
def add_dependency(self, dependency, version):
"""
:type dependency: cache_dependencies.interfaces.IDependency
:type version: int or None
"""
assert isinstance(dependency, interfaces.IDependency)
def finish(self):
pass
def __bool__(self):
return False
class AbstractTransactionManager(interfaces.ITransactionManager):
def __call__(self, func=None):
if func is None:
return self
@wraps(func)
def _decorated(*args, **kw):
with self:
rv = func(*args, **kw)
return rv
return _decorated
def __enter__(self):
self.begin()
def __exit__(self, *args):
self.finish()
return False
class TransactionManager(AbstractTransactionManager):
def __init__(self, lock):
"""
:type lock: cache_dependencies.interfaces.IDependencyLock
"""
self._lock = lock
self._current = None
def current(self, node=Undef):
if node is Undef:
return self._current or DummyTransaction(self._lock)
self._current = node
def begin(self):
if self._current is None:
self.current(Transaction(self._lock))
else:
self.current(SavePoint(self._lock, self.current()))
return self.current()
def finish(self):
self.current().finish()
self.current(self.current().parent())
def flush(self):
while self._current:
self.finish()
class ThreadSafeTransactionManagerDecorator(mixins.ThreadSafeDecoratorMixIn, AbstractTransactionManager):
def current(self, node=Undef):
self._validate_thread_sharing()
return self._delegate.current(node)
def begin(self):
self._validate_thread_sharing()
return self._delegate.begin()
def finish(self):
self._validate_thread_sharing()
return self._delegate.finish()
def flush(self):
return self._delegate.flush()
|
ello/webapp
|
test/unit/selectors/post_test.js
|
import Immutable from 'immutable'
import * as selector from '../../../src/selectors/post'
import {
clearJSON,
json,
stub,
stubCategories,
stubPost,
stubTextRegion,
stubImageRegion,
stubEmbedRegion,
} from '../../support/stubs'
describe('post selectors', () => {
let propsPost
let state
beforeEach(() => {
stub('post', { authorId: 'statePost', token: 'token1' })
stub('post', { id: '303', authorId: '666' })
stub('post', { id: '100', authorId: '666', repostContent: [stubTextRegion()] })
stub('user', { id: '666', username: '666-username' })
stub('user', { id: '9', username: 'reposter-username' })
stubCategories()
propsPost = stub('post', {
authorId: '666',
body: [stubTextRegion(), stubImageRegion(), stubEmbedRegion()],
commentsCount: 12,
content: [stubTextRegion(), stubImageRegion(), stubEmbedRegion()],
contentWarning: 'Content Warning!',
createdAt: 'Today',
href: '/post-href',
id: '666',
links: {
repostAuthor: { id: '9' },
categories: [1, 4],
},
loved: true,
lovesCount: 10,
repostContent: [stubTextRegion()],
repostId: '667',
repostPath: '/repost-path',
reposted: true,
repostsCount: 13,
showComments: true,
showLovers: true,
showReposters: true,
summary: [stubTextRegion(), stubImageRegion()],
token: 'token<PASSWORD>',
viewsCount: 1666,
watching: true,
})
state = { authentication: Immutable.Map({ isLoggedIn: true }), json }
})
afterEach(() => {
clearJSON()
})
context('#selectPropsPostId', () => {
it('returns the correct props post id from a postId', () => {
const props = { postId: '666' }
expect(selector.selectPropsPostId(state, props)).to.equal('666')
})
it('returns the correct props post id from a post', () => {
const props = { post: propsPost }
expect(selector.selectPropsPostId(state, props)).to.equal('666')
})
})
context('#selectPropsPostIsRelated', () => {
it('returns the correct props isRelatedPost', () => {
const props = { isRelatedPost: true }
expect(selector.selectPropsPostIsRelated(state, props)).to.equal(true)
})
it('returns the correct props post id from a post', () => {
const props = {}
expect(selector.selectPropsPostIsRelated(state, props)).to.equal(false)
})
})
context('#selectPropsLocationStateFrom', () => {
it('returns the correct props isRelatedPost', () => {
const props = { location: { state: { from: 'PaginatorLink' } } }
expect(selector.selectPropsLocationStateFrom(state, props)).to.equal('PaginatorLink')
})
it('returns the correct props post id from a post', () => {
const props = {}
expect(selector.selectPropsLocationStateFrom(state, props)).to.be.null
})
})
context('#selectPosts', () => {
it('returns posts model out of json', () => {
expect(selector.selectPosts(state)).to.deep.equal(state.json.get('posts'))
})
})
context('#selectPost', () => {
it('returns a post from a postId', () => {
const props = { postId: '1' }
const post = selector.selectPost(state, props)
expect(post).to.deep.equal(state.json.get('posts').first())
})
it('returns an empty Map if postId is not found', () => {
const props = { postId: '166666' }
const post = selector.selectPost(state, props)
expect(post).to.deep.equal(Immutable.Map())
})
it('returns a post from a post.postId', () => {
const props = { post: state.json.get('posts').first() }
const post = selector.selectPost(state, props)
expect(post).to.deep.equal(state.json.get('posts').first())
})
it('returns an empty Map if post.postId is not found', () => {
const props = { post: stubPost({ id: '99999' }, false) }
const post = selector.selectPost(state, props)
expect(post).to.deep.equal(Immutable.Map())
})
it('returns a post from a token', () => {
const props = { params: { token: 'token<PASSWORD>' } }
const post = selector.selectPost(state, props)
expect(post).to.deep.equal(state.json.getIn(['posts', '666']))
})
it('returns an empty Map if token is not found', () => {
const props = { params: { token: 'token<PASSWORD>' } }
const post = selector.selectPost(state, props)
expect(post).to.deep.equal(Immutable.Map())
})
it('returns an empty Map if id and token is not found', () => {
const props = {}
const post = selector.selectPost(state, props)
expect(post).to.deep.equal(Immutable.Map())
})
it('returns an empty Map if post is not found', () => {
const props = {}
const post = selector.selectPost({ json: Immutable.Map() }, props)
expect(post).to.deep.equal(Immutable.Map())
})
})
context('#selectPostAuthorId', () => {
it('returns the post authorId', () => {
const props = { postId: '666' }
const result = selector.selectPostAuthorId(state, props)
expect(result).to.deep.equal('666')
})
})
context('#selectPostBody', () => {
it('returns the post body', () => {
const props = { postId: '666' }
const result = selector.selectPostBody(state, props)
expect(result.size).to.equal(3)
})
})
context('#selectPostCommentsCount', () => {
it('returns the post comments count', () => {
const props = { postId: '666' }
const result = selector.selectPostCommentsCount(state, props)
expect(result).to.equal(12)
})
it('ensures the comment count does not fall below 0', () => {
state.json = state.json.setIn(['posts', '666', 'commentsCount'], -1)
const props = { postId: '666' }
const result = selector.selectPostCommentsCount(state, props)
expect(result).to.equal(0)
})
})
context('#selectPostContent', () => {
it('returns the post content', () => {
const props = { postId: '666' }
const result = selector.selectPostBody(state, props)
expect(result.size).to.equal(3)
})
})
context('#selectPostContentWarning', () => {
it('returns the post content warning', () => {
const props = { postId: '666' }
const result = selector.selectPostContentWarning(state, props)
expect(result).to.equal('Content Warning!')
})
})
context('#selectPostCreatedAt', () => {
it('returns the post created at', () => {
const props = { postId: '666' }
const result = selector.selectPostCreatedAt(state, props)
expect(result).to.equal('Today')
})
})
context('#selectPostHref', () => {
it('returns the post href', () => {
const props = { postId: '666' }
const result = selector.selectPostHref(state, props)
expect(result).to.equal('/post-href')
})
})
context('#selectPostId', () => {
it('returns the post id', () => {
const props = { postId: '666' }
const result = selector.selectPostId(state, props)
expect(result).to.equal('666')
})
})
context('#selectPostIsAdultContent', () => {
it('returns the post is adult content', () => {
const props = { postId: '666' }
const result = selector.selectPostIsAdultContent(state, props)
expect(result).to.equal(false)
})
})
context('#selectPostLoved', () => {
it('returns the post is loved', () => {
const props = { postId: '666' }
const result = selector.selectPostLoved(state, props)
expect(result).to.equal(true)
})
})
context('#selectPostLovesCount', () => {
it('returns the post loves count', () => {
const props = { postId: '666' }
const result = selector.selectPostLovesCount(state, props)
expect(result).to.equal(10)
})
it('ensures the loves count does not fall below 0', () => {
state.json = state.json.setIn(['posts', '666', 'lovesCount'], -5)
const props = { postId: '666' }
const result = selector.selectPostLovesCount(state, props)
expect(result).to.equal(0)
})
})
context('#selectPostMetaAttributes', () => {
it('returns the post meta attributes', () => {
const props = { post: Immutable.Map({ id: '1' }), params: { token: 'token' } }
const attr = Immutable.fromJS({
canonicalUrl: null,
description: 'meta post description',
images: ['meta-post-image-0.jpg', 'meta-post-image-1.jpg'],
embeds: ['meta-post-embed-0.mp4', 'meta-post-embed-1.mp4'],
robots: 'index, follow',
title: 'meta post title',
url: 'https://ello.co/author/post/meta-url',
})
expect(selector.selectPostMetaAttributes(state, props)).to.deep.equal(attr)
})
})
context('#selectPostRepostContent', () => {
it('returns the post repost content', () => {
const props = { postId: '666' }
const result = selector.selectPostRepostContent(state, props)
expect(result.size).to.equal(1)
})
})
context('#selectPostRepostId', () => {
it('returns the post repost id', () => {
const props = { postId: '666' }
const result = selector.selectPostRepostId(state, props)
expect(result).to.equal('667')
})
})
context('#selectPostReposted', () => {
it('returns the post is reposted', () => {
const props = { postId: '666' }
const result = selector.selectPostReposted(state, props)
expect(result).to.equal(true)
})
})
context('#selectPostRepostsCount', () => {
it('returns the post reposted count', () => {
const props = { postId: '666' }
const result = selector.selectPostRepostsCount(state, props)
expect(result).to.equal(13)
})
it('ensures the reposts count does not fall below 0', () => {
state.json = state.json.setIn(['posts', '666', 'repostsCount'], -2)
const props = { postId: '666' }
const result = selector.selectPostRepostsCount(state, props)
expect(result).to.equal(0)
})
})
context('#selectPostShowComments', () => {
it('returns if the post shows comments', () => {
const props = { postId: '666' }
const result = selector.selectPostShowComments(state, props)
expect(result).to.equal(true)
})
})
context('#selectPostSummary', () => {
it('returns the post summary', () => {
const props = { postId: '666' }
const result = selector.selectPostSummary(state, props)
expect(result.size).to.equal(2)
})
})
context('#selectPostToken', () => {
it('returns the post token', () => {
const props = { postId: '666' }
const result = selector.selectPostToken(state, props)
expect(result).to.equal('token666')
})
})
context('#selectPostViewsCount', () => {
it('returns the post views count', () => {
const props = { postId: '666' }
const result = selector.selectPostViewsCount(state, props)
expect(result).to.equal(1666)
})
it('ensures the posts views count does not fall below 0', () => {
state.json = state.json.setIn(['posts', '666', 'viewsCount'], -6)
const props = { postId: '666' }
const result = selector.selectPostViewsCount(state, props)
expect(result).to.equal(0)
})
})
context('#selectPostViewsCountRounded', () => {
it('returns the post views count rounded', () => {
const props = { postId: '666' }
const result = selector.selectPostViewsCountRounded(state, props)
expect(result).to.equal('1.7K')
})
})
context('#selectPostWatching', () => {
it('returns the post watching property', () => {
const props = { postId: '666' }
const result = selector.selectPostWatching(state, props)
expect(result).to.equal(true)
})
})
context('#selectPostMetaDescription', () => {
it('returns the post meta description', () => {
const props = { post: Immutable.Map({ id: '1' }), params: { token: 'token' } }
expect(selector.selectPostMetaDescription(state, props)).to.equal('meta post description')
})
})
context('#selectPostMetaRobots', () => {
it('returns the post meta robot instructions', () => {
const props = { post: Immutable.Map({ id: '1' }), params: { token: 'token' } }
expect(selector.selectPostMetaRobots(state, props)).to.deep.equal('index, follow')
})
})
context('#selectPostMetaTitle', () => {
it('returns the post meta title', () => {
const props = { post: Immutable.Map({ id: '1' }), params: { token: 'token' } }
expect(selector.selectPostMetaTitle(state, props)).to.equal('meta post title')
})
})
context('#selectPostMetaUrl', () => {
it('returns the post meta url', () => {
const props = { post: Immutable.Map({ id: '1' }), params: { token: 'token' } }
expect(selector.selectPostMetaUrl(state, props)).to.equal('https://ello.co/author/post/meta-url')
})
})
context('#selectPostMetaCanonicalUrl', () => {
it('returns the post canonical url', () => {
const props = { post: Immutable.Map({ id: '1' }), params: { token: 'token' } }
expect(selector.selectPostMetaCanonicalUrl(state, props)).to.deep.equal(null)
state = { json: state.json.setIn(['posts', '1', 'metaAttributes', 'canonicalUrl'], 'meta-canonicalUrl') }
expect(selector.selectPostMetaCanonicalUrl(state, props)).to.deep.equal('meta-canonicalUrl')
})
})
context('#selectPostMetaEmbeds', () => {
it('returns the meta embeds for a post', () => {
const result = {
openGraphEmbeds: [
{ property: 'og:video', content: 'meta-post-embed-0.mp4' },
{ property: 'og:video', content: 'meta-post-embed-1.mp4' },
],
}
const props = { post: Immutable.Map({ id: '1' }), params: { token: 'token' } }
expect(selector.selectPostMetaEmbeds(state, props)).to.deep.equal(result)
})
})
context('#selectPostMetaImages', () => {
it('returns the meta images (image/embed) for a post', () => {
const result = {
openGraphImages: [
{ property: 'og:image', content: 'meta-post-image-0.jpg' },
{ property: 'og:image', content: 'meta-post-image-1.jpg' },
],
schemaImages: [
{ name: 'image', itemprop: 'image', content: 'meta-post-image-0.jpg' },
{ name: 'image', itemprop: 'image', content: 'meta-post-image-1.jpg' },
],
}
const props = { post: Immutable.Map({ id: '1' }), params: { token: 'token' } }
expect(selector.selectPostMetaImages(state, props)).to.deep.equal(result)
})
})
context('#selectPostAuthor', () => {
it('returns the post author', () => {
const props = { postId: '666' }
const result = selector.selectPostAuthor(state, props)
expect(result).to.equal(state.json.getIn(['users', '666']))
})
})
context('#selectPostAuthorUsername', () => {
it('returns the post author username', () => {
const props = { postId: '666' }
const result = selector.selectPostAuthorUsername(state, props)
expect(result).to.equal(state.json.getIn(['users', '666', 'username']))
})
})
context('#selectPostAuthorHasCommentingEnabled (true)', () => {
it('returns the post author hasCommentingEnabled flag', () => {
const props = { postId: '666' }
const result = selector.selectPostAuthorHasCommentingEnabled(state, props)
expect(result).to.equal(true)
})
it('returns the post author hasCommentingEnabled flag (false)', () => {
state.json = state.json.setIn(['users', '666', 'hasCommentingEnabled'], false)
const props = { postId: '666' }
const result = selector.selectPostAuthorHasCommentingEnabled(state, props)
expect(result).to.equal(false)
})
})
context('#selectPostRepostAuthorId', () => {
it('returns the post repost author id', () => {
const props = { postId: '666' }
const result = selector.selectPostRepostAuthorId(state, props)
expect(result).to.equal('9')
})
})
context('#selectPostRepostAuthor', () => {
it('returns the post repost author', () => {
const props = { postId: '666' }
const result = selector.selectPostRepostAuthor(state, props)
expect(result).to.equal(state.json.getIn(['users', '9']))
})
})
context('#selectPostRepostAuthorWithFallback', () => {
it('returns the post repost author', () => {
const props = { postId: '666' }
const result = selector.selectPostRepostAuthorWithFallback(state, props)
expect(result).to.equal(state.json.getIn(['users', '9']))
})
it('returns the post author as a fallback', () => {
const props = { postId: '100' }
const result = selector.selectPostRepostAuthorWithFallback(state, props)
expect(result).to.equal(state.json.getIn(['users', '666']))
})
})
context('#selectPostCategories', () => {
it('returns the post categories list', () => {
const props = { postId: '666' }
const result = selector.selectPostCategories(state, props)
expect(result).to.equal(Immutable.List([1, 4]))
})
})
context('#selectPostCategory', () => {
it('returns the first item in the post categories list', () => {
const props = { postId: '666' }
const result = selector.selectPostCategory(state, props)
expect(result).to.equal(state.json.getIn(['categories', '1']))
})
})
context('#selectPostCategoryName', () => {
it('returns the first item name in the post categories list', () => {
const props = { postId: '666' }
const result = selector.selectPostCategoryName(state, props)
expect(result).to.equal('Featured')
})
})
context('#selectPostCategorySlug', () => {
it('returns the first item slug in the post categories list', () => {
const props = { postId: '666' }
const result = selector.selectPostCategorySlug(state, props)
expect(result).to.equal('/discover/featured')
})
})
context('#selectPostDetailPath', () => {
it('returns the post detail path', () => {
const props = { postId: '666' }
const result = selector.selectPostDetailPath(state, props)
expect(result).to.equal('/666-username/post/token666')
})
})
context('#selectPostIsCommentsRequesting', () => {
it('selects the state around requesting comments for a post')
})
context('#selectPostIsEditing', () => {
it('returns the state of isEditing on the post', () => {
const props = { postId: '666' }
const result = selector.selectPostIsEditing(state, props)
expect(result).to.equal(false)
})
})
context('#selectPostIsEmpty', () => {
it('returns whether the user is emtpy (false)', () => {
const props = { postId: '666' }
const result = selector.selectPostIsEmpty(state, props)
expect(result).to.equal(false)
})
it('returns whether the user is emtpy (true)', () => {
const props = { postId: '1000' }
const result = selector.selectPostIsEmpty(state, props)
expect(result).to.equal(true)
})
})
context('#selectPostIsGridMode', () => {
it('returns the state of isGridMode on the post on post detail', () => {
state = {
json,
routing: Immutable.fromJS({
location: { pathname: '/666-username/post/token666' },
}),
gui: Immutable.fromJS({ isGridMode: true }),
}
const props = { postId: '666' }
const result = selector.selectPostIsGridMode(state, props)
expect(result).to.equal(false)
})
it('returns the state of isGridMode on the post from a profile', () => {
state = {
json,
routing: Immutable.fromJS({
location: { pathname: '/666-username/' },
}),
gui: Immutable.fromJS({ isGridMode: true }),
}
const props = { postId: '666' }
const result = selector.selectPostIsGridMode(state, props)
expect(result).to.equal(true)
})
})
context('#selectPostIsOwn', () => {
it('returns if the post is the users own', () => {
state.profile = Immutable.Map({ id: '666' })
const props = { post: propsPost }
expect(selector.selectPostIsOwn(state, props)).to.equal(true)
state.change = 1
expect(selector.selectPostIsOwn(state, props)).to.equal(true)
expect(selector.selectPostIsOwn.recomputations()).to.equal(1)
})
it('returns if the post is not the users own', () => {
state.profile = Immutable.Map({ id: 'statePost' })
const props = { post: propsPost }
expect(selector.selectPostIsOwn(state, props)).to.equal(false)
state.change = 1
expect(selector.selectPostIsOwn(state, props)).to.equal(false)
// 2 since the memoization is from the context block
expect(selector.selectPostIsOwn.recomputations()).to.equal(2)
})
})
context('#selectPostIsOwnOriginal', () => {
it('returns the state of isEditing on the post', () => {
state.profile = Immutable.Map({ id: '9' })
const props = { postId: '666' }
const result = selector.selectPostIsOwnOriginal(state, props)
expect(result).to.equal(true)
})
it('returns the state of isEditing on the post', () => {
state.profile = Immutable.Map({ id: '100' })
const props = { postId: '666' }
const result = selector.selectPostIsOwnOriginal(state, props)
expect(result).to.equal(false)
})
})
context('#selectPostIsRepost', () => {
it('returns if the post is a repost', () => {
const props = { postId: '666' }
const result = selector.selectPostIsRepost(state, props)
expect(result).to.equal(true)
})
})
context('#selectPostIsReposting', () => {
it('returns the state of isReposting on the post', () => {
const props = { postId: '666' }
const result = selector.selectPostIsReposting(state, props)
expect(result).to.equal(false)
})
})
context('#selectPostIsWatching', () => {
it('returns the state of watching on the post', () => {
const props = { postId: '666' }
const result = selector.selectPostIsWatching(state, props)
expect(result).to.equal(true)
})
})
context('#selectPostRepostAuthor', () => {
it('returns the post repost author', () => {
const props = { postId: '666' }
const result = selector.selectPostRepostAuthor(state, props)
expect(result).to.equal(state.json.getIn(['users', '9']))
})
})
context('#selectPostRepostAuthorWithFallback', () => {
it('returns the post repost author', () => {
const props = { postId: '666' }
const result = selector.selectPostRepostAuthorWithFallback(state, props)
expect(result).to.equal(state.json.getIn(['users', '9']))
})
it('returns the post author as a fallback', () => {
const props = { postId: '100' }
const result = selector.selectPostRepostAuthorWithFallback(state, props)
expect(result).to.equal(state.json.getIn(['users', '666']))
})
})
context('#selectPostShowEditor', () => {
it('returns if the post editor should be shown', () => {
const props = { postId: '666' }
const result = selector.selectPostShowEditor(state, props)
expect(result).to.equal(false)
})
it('returns if the post editor should be shown after setting isEditing', () => {
state.json = state.json.setIn(['posts', '666', 'isEditing'], true)
const props = { postId: '666' }
const result = selector.selectPostShowEditor(state, props)
expect(result).to.equal(true)
})
it('returns false if the post is related', () => {
state.json = state.json.setIn(['posts', '666', 'isEditing'], true)
const props = { postId: '666', isRelatedPost: true }
const result = selector.selectPostShowEditor(state, props)
expect(result).to.equal(false)
})
})
context('#selectPostShowCommentEditor', () => {
it('returns if the post comment editor should be shown', () => {
state = {
json,
routing: Immutable.fromJS({
location: { pathname: '/666-username/post/token666' },
}),
}
const props = { postId: '666' }
const result = selector.selectPostShowCommentEditor(state, props)
expect(result).to.equal(false)
})
it('returns if the post comment editor should be shown after setting showEditor', () => {
state.json = state.json.setIn(['posts', '666', 'isEditing'], true)
const props = { postId: '666' }
const result = selector.selectPostShowEditor(state, props)
expect(result).to.equal(true)
})
it('returns false if the post is related', () => {
state.json = state.json.setIn(['posts', '666', 'isEditing'], true)
const props = { postId: '666', isRelatedPost: true }
const result = selector.selectPostShowEditor(state, props)
expect(result).to.equal(false)
})
})
context('#selectPostDetailTabs', () => {
it('returns PostDetail tabs when there is 0 comments, 0 loves and 0 reposts', () => {
const props = { postId: '303' }
const result = selector.selectPostDetailTabs(state, props)
const expected = [
{ type: 'comments', children: 'Comments' },
]
expect(result).to.deep.equal(expected)
})
it('returns no PostDetail tabs when there is 0 comments, 0 loves and 0 reposts', () => {
const props = { postId: '303' }
state.authentication = state.authentication.set('isLoggedIn', false)
const result = selector.selectPostDetailTabs(state, props)
const expected = []
expect(result).to.deep.equal(expected)
})
it('returns the cooment tab PostDetail tabs when there is > 0 comments and we are logged out', () => {
const props = { postId: '303' }
state.json = state.json.setIn(['posts', '303', 'commentsCount'], 1)
state.authentication = state.authentication.set('isLoggedIn', false)
const result = selector.selectPostDetailTabs(state, props)
const expected = [
{ type: 'comments', children: '1 Comment' },
]
expect(result).to.deep.equal(expected)
})
it('returns PostDetail tabs when there is 1 comment, 0 loves and 0 reposts', () => {
state.json = state.json.setIn(['posts', '303', 'commentsCount'], 1)
const props = { postId: '303' }
const result = selector.selectPostDetailTabs(state, props)
const expected = [
{ type: 'comments', children: '1 Comment' },
]
expect(result).to.deep.equal(expected)
})
it('returns PostDetail tabs when there is 2 comments, 0 loves and 0 reposts', () => {
state.json = state.json.setIn(['posts', '303', 'commentsCount'], 2)
const props = { postId: '303' }
const result = selector.selectPostDetailTabs(state, props)
const expected = [
{ type: 'comments', children: '2 Comments' },
]
expect(result).to.deep.equal(expected)
})
it('returns PostDetail tabs when there is 2 comments, 1 love and 0 reposts', () => {
state.json = state.json.setIn(['posts', '303', 'commentsCount'], 2)
.setIn(['posts', '303', 'lovesCount'], 1)
const props = { postId: '303' }
const result = selector.selectPostDetailTabs(state, props)
const expected = [
{ type: 'comments', children: '2 Comments' },
{ type: 'loves', children: '1 Love' },
]
expect(result).to.deep.equal(expected)
})
it('returns PostDetail tabs when there is 2 comments, 2 loves and 0 reposts', () => {
state.json = state.json.setIn(['posts', '303', 'commentsCount'], 2)
.setIn(['posts', '303', 'lovesCount'], 2)
const props = { postId: '303' }
const result = selector.selectPostDetailTabs(state, props)
const expected = [
{ type: 'comments', children: '2 Comments' },
{ type: 'loves', children: '2 Loves' },
]
expect(result).to.deep.equal(expected)
})
it('returns PostDetail tabs when there is 2 comments, 2 loves and 1 repost', () => {
state.json = state.json.setIn(['posts', '303', 'commentsCount'], 2)
.setIn(['posts', '303', 'lovesCount'], 2)
.setIn(['posts', '303', 'repostsCount'], 1)
const props = { postId: '303' }
const result = selector.selectPostDetailTabs(state, props)
const expected = [
{ type: 'comments', children: '2 Comments' },
{ type: 'loves', children: '2 Loves' },
{ type: 'reposts', children: '1 Repost' },
]
expect(result).to.deep.equal(expected)
})
it('returns PostDetail tabs when there is 2 comments, 2 loves and 2 reposts', () => {
state.json = state.json.setIn(['posts', '303', 'commentsCount'], 2)
.setIn(['posts', '303', 'lovesCount'], 2)
.setIn(['posts', '303', 'repostsCount'], 2)
const props = { postId: '303' }
const result = selector.selectPostDetailTabs(state, props)
const expected = [
{ type: 'comments', children: '2 Comments' },
{ type: 'loves', children: '2 Loves' },
{ type: 'reposts', children: '2 Reposts' },
]
expect(result).to.deep.equal(expected)
})
it('returns PostDetail tabs when there is 0 comments, 2 loves and 1 repost', () => {
state.json = state.json.setIn(['posts', '303', 'lovesCount'], 2)
.setIn(['posts', '303', 'repostsCount'], 1)
const props = { postId: '303' }
const result = selector.selectPostDetailTabs(state, props)
const expected = [
{ type: 'comments', children: 'Comments' },
{ type: 'loves', children: '2 Loves' },
{ type: 'reposts', children: '1 Repost' },
]
expect(result).to.deep.equal(expected)
})
it('returns empty tabs when there is the author has commenting disabled, 0 comments, 0 loves and 0 reposts', () => {
const props = { postId: '303' }
state.json = state.json.setIn(['users', '666', 'hasCommentingEnabled'], false)
const result = selector.selectPostDetailTabs(state, props)
const expected = []
expect(result).to.deep.equal(expected)
})
})
})
|
moutainhigh/stuck-link
|
stuck-link-redirect/src/main/java/top/stuck/link/redirect/config/AsyncConfig.java
|
<filename>stuck-link-redirect/src/main/java/top/stuck/link/redirect/config/AsyncConfig.java<gh_stars>1-10
package top.stuck.link.redirect.config;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import top.stuck.link.core.factory.StuckThreadFactory;
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* 异步任务配置类
* Created on 2020-04-26
*
* @author Octopus
*/
@Configuration
@EnableAsync
@ConditionalOnProperty(prefix = "link.async", name = "enabled", havingValue = "true")
public class AsyncConfig implements AsyncConfigurer {
@Value("${link.async.pool-size:5}")
private Integer asyncPoolSize;
/**
* Async异步任务线程池
* @return
*/
@Bean
@Override
public Executor getAsyncExecutor() {
if (asyncPoolSize <= 0) {
throw new IllegalArgumentException("config link.async.pool-size must be greater than 0");
}
return new ConcurrentTaskExecutor(Executors.newFixedThreadPool(asyncPoolSize, new StuckThreadFactory("async")));
}
/**
* 异步任务异常处理接口实现
* @return
*/
@Bean
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SpringAsyncExceptionHandler();
}
/**
* 异步任务异常处理实现类
*/
class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler{
@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
System.out.println("异步错误");
throwable.printStackTrace();
}
}
}
|
loicgasser/ngeo
|
src/olcs/constants.js
|
<filename>src/olcs/constants.js<gh_stars>10-100
/**
* @module ngeo.olcs.constants
*/
const exports = {};
/**
* @enum {string}
* @export
*/
exports.Permalink3dParam = {
/**
* @type {string}
* @export
*/
ENABLED: '3d_enabled',
/**
* @type {string}
* @export
*/
LON: '3d_lon',
/**
* @type {string}
* @export
*/
LAT: '3d_lat',
/**
* @type {string}
* @export
*/
ELEVATION: '3d_elevation',
/**
* @type {string}
* @export
*/
HEADING: '3d_heading',
/**
* @type {string}
* @export
*/
PITCH: '3d_pitch',
/**
* @type {string}
* @export
*/
PREFIX: '3d_'
};
export default exports;
|
zealoussnow/chromium
|
chrome/browser/resources/internals/lens/lens_internals_browser_proxy.js
|
// Copyright 2021 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.
import {addSingletonGetter, sendWithPromise} from 'chrome://resources/js/cr.m.js';
/** @interface */
export class LensInternalsBrowserProxy {
/**
* Start debug mode collection for proactive.
* @return {!Promise<void>} A promise firing when the call is complete.
*/
startDebugMode() {}
/**
* Start debug mode collection for proactive.
* @return {!Promise<!Array<!Array<string>>>} A promise firing when the call
* is complete.
*/
refreshDebugData() {}
/**
* Stop debug mode collection for proactive.
* @return {!Promise<void>} A promise firing when the call is complete.
*/
stopDebugMode() {}
}
/**
* @implements {LensInternalsBrowserProxy}
*/
export class LensInternalsBrowserProxyImpl {
/** @override */
startDebugMode() {
return sendWithPromise('startDebugMode');
}
/** @override */
refreshDebugData() {
return sendWithPromise('refreshDebugData');
}
/** @override */
stopDebugMode() {
return sendWithPromise('stopDebugMode');
}
}
addSingletonGetter(LensInternalsBrowserProxyImpl);
|
marinaoliveira96/python-exercises
|
100-programming-exercises/003.py
|
<reponame>marinaoliveira96/python-exercises
# convert bytes to a string
bytes_to_convert = b"Python"
converted_str = bytes_to_convert.decode('utf-8')
|
RedBrumbler/virtuoso-codegen
|
include/OVR/OpenVR/IVRInput__GetSkeletalBoneDataCompressed.hpp
|
<reponame>RedBrumbler/virtuoso-codegen
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: OVR.OpenVR.IVRInput
#include "OVR/OpenVR/IVRInput.hpp"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: OVR::OpenVR
namespace OVR::OpenVR {
// Forward declaring type: EVRInputError
struct EVRInputError;
// Forward declaring type: EVRSkeletalTransformSpace
struct EVRSkeletalTransformSpace;
// Forward declaring type: EVRSkeletalMotionRange
struct EVRSkeletalMotionRange;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed);
DEFINE_IL2CPP_ARG_TYPE(::OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed*, "OVR.OpenVR", "IVRInput/_GetSkeletalBoneDataCompressed");
// Type namespace: OVR.OpenVR
namespace OVR::OpenVR {
// Size: 0x70
#pragma pack(push, 1)
// Autogenerated type: OVR.OpenVR.IVRInput/OVR.OpenVR._GetSkeletalBoneDataCompressed
// [TokenAttribute] Offset: FFFFFFFF
// [UnmanagedFunctionPointerAttribute] Offset: 58B98C
class IVRInput::_GetSkeletalBoneDataCompressed : public ::System::MulticastDelegate {
public:
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0x7097D8
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static IVRInput::_GetSkeletalBoneDataCompressed* New_ctor(::Il2CppObject* object, ::System::IntPtr method) {
static auto ___internal__logger = ::Logger::get().WithContext("::OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<IVRInput::_GetSkeletalBoneDataCompressed*, creationType>(object, method)));
}
// public OVR.OpenVR.EVRInputError Invoke(System.UInt64 action, OVR.OpenVR.EVRSkeletalTransformSpace eTransformSpace, OVR.OpenVR.EVRSkeletalMotionRange eMotionRange, System.IntPtr pvCompressedData, System.UInt32 unCompressedSize, ref System.UInt32 punRequiredCompressedSize, System.UInt64 ulRestrictToDevice)
// Offset: 0x7097E8
::OVR::OpenVR::EVRInputError Invoke(uint64_t action, ::OVR::OpenVR::EVRSkeletalTransformSpace eTransformSpace, ::OVR::OpenVR::EVRSkeletalMotionRange eMotionRange, ::System::IntPtr pvCompressedData, uint unCompressedSize, ByRef<uint> punRequiredCompressedSize, uint64_t ulRestrictToDevice);
// public System.IAsyncResult BeginInvoke(System.UInt64 action, OVR.OpenVR.EVRSkeletalTransformSpace eTransformSpace, OVR.OpenVR.EVRSkeletalMotionRange eMotionRange, System.IntPtr pvCompressedData, System.UInt32 unCompressedSize, ref System.UInt32 punRequiredCompressedSize, System.UInt64 ulRestrictToDevice, System.AsyncCallback callback, System.Object object)
// Offset: 0x709A94
::System::IAsyncResult* BeginInvoke(uint64_t action, ::OVR::OpenVR::EVRSkeletalTransformSpace eTransformSpace, ::OVR::OpenVR::EVRSkeletalMotionRange eMotionRange, ::System::IntPtr pvCompressedData, uint unCompressedSize, ByRef<uint> punRequiredCompressedSize, uint64_t ulRestrictToDevice, ::System::AsyncCallback* callback, ::Il2CppObject* object);
// public OVR.OpenVR.EVRInputError EndInvoke(ref System.UInt32 punRequiredCompressedSize, System.IAsyncResult result)
// Offset: 0x709BFC
::OVR::OpenVR::EVRInputError EndInvoke(ByRef<uint> punRequiredCompressedSize, ::System::IAsyncResult* result);
}; // OVR.OpenVR.IVRInput/OVR.OpenVR._GetSkeletalBoneDataCompressed
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed::Invoke
// Il2CppName: Invoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::OVR::OpenVR::EVRInputError (OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed::*)(uint64_t, ::OVR::OpenVR::EVRSkeletalTransformSpace, ::OVR::OpenVR::EVRSkeletalMotionRange, ::System::IntPtr, uint, ByRef<uint>, uint64_t)>(&OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed::Invoke)> {
static const MethodInfo* get() {
static auto* action = &::il2cpp_utils::GetClassFromName("System", "UInt64")->byval_arg;
static auto* eTransformSpace = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "EVRSkeletalTransformSpace")->byval_arg;
static auto* eMotionRange = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "EVRSkeletalMotionRange")->byval_arg;
static auto* pvCompressedData = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg;
static auto* unCompressedSize = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
static auto* punRequiredCompressedSize = &::il2cpp_utils::GetClassFromName("System", "UInt32")->this_arg;
static auto* ulRestrictToDevice = &::il2cpp_utils::GetClassFromName("System", "UInt64")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed*), "Invoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{action, eTransformSpace, eMotionRange, pvCompressedData, unCompressedSize, punRequiredCompressedSize, ulRestrictToDevice});
}
};
// Writing MetadataGetter for method: OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed::BeginInvoke
// Il2CppName: BeginInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::IAsyncResult* (OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed::*)(uint64_t, ::OVR::OpenVR::EVRSkeletalTransformSpace, ::OVR::OpenVR::EVRSkeletalMotionRange, ::System::IntPtr, uint, ByRef<uint>, uint64_t, ::System::AsyncCallback*, ::Il2CppObject*)>(&OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed::BeginInvoke)> {
static const MethodInfo* get() {
static auto* action = &::il2cpp_utils::GetClassFromName("System", "UInt64")->byval_arg;
static auto* eTransformSpace = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "EVRSkeletalTransformSpace")->byval_arg;
static auto* eMotionRange = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "EVRSkeletalMotionRange")->byval_arg;
static auto* pvCompressedData = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg;
static auto* unCompressedSize = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
static auto* punRequiredCompressedSize = &::il2cpp_utils::GetClassFromName("System", "UInt32")->this_arg;
static auto* ulRestrictToDevice = &::il2cpp_utils::GetClassFromName("System", "UInt64")->byval_arg;
static auto* callback = &::il2cpp_utils::GetClassFromName("System", "AsyncCallback")->byval_arg;
static auto* object = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed*), "BeginInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{action, eTransformSpace, eMotionRange, pvCompressedData, unCompressedSize, punRequiredCompressedSize, ulRestrictToDevice, callback, object});
}
};
// Writing MetadataGetter for method: OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed::EndInvoke
// Il2CppName: EndInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::OVR::OpenVR::EVRInputError (OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed::*)(ByRef<uint>, ::System::IAsyncResult*)>(&OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed::EndInvoke)> {
static const MethodInfo* get() {
static auto* punRequiredCompressedSize = &::il2cpp_utils::GetClassFromName("System", "UInt32")->this_arg;
static auto* result = &::il2cpp_utils::GetClassFromName("System", "IAsyncResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRInput::_GetSkeletalBoneDataCompressed*), "EndInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{punRequiredCompressedSize, result});
}
};
|
amitznati/template-editor
|
src/widgets/Gradients/widget/components/Gradients.mainView.js
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import SelectGradient from './Gradients.SelectGradient';
import EditGradient from './Gradients.EditGradient';
const useStyles = makeStyles((theme) => ({
root: {
padding: theme.spacing(2, 0)
}
}));
export default function GradientsMainView({
selectedGradient,
editGradientProps,
selectGradientProps
}) {
const classes = useStyles();
return (
<div className={classes.root}>
{selectedGradient ? (
<EditGradient {...editGradientProps} />
) : (
<SelectGradient {...selectGradientProps} />
)}
</div>
);
}
|
trusted-ws/qira
|
tracers/qemu/qemu/target-ppc/mmu_helper.c
|
/*
* PowerPC MMU, TLB, SLB and BAT emulation helpers for QEMU.
*
* Copyright (c) 2003-2007 <NAME>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#include "cpu.h"
#include "exec/helper-proto.h"
#include "sysemu/kvm.h"
#include "kvm_ppc.h"
#include "mmu-hash64.h"
#include "mmu-hash32.h"
#include "exec/cpu_ldst.h"
//#define DEBUG_MMU
//#define DEBUG_BATS
//#define DEBUG_SOFTWARE_TLB
//#define DUMP_PAGE_TABLES
//#define DEBUG_SOFTWARE_TLB
//#define FLUSH_ALL_TLBS
#ifdef DEBUG_MMU
# define LOG_MMU_STATE(cpu) log_cpu_state((cpu), 0)
#else
# define LOG_MMU_STATE(cpu) do { } while (0)
#endif
#ifdef DEBUG_SOFTWARE_TLB
# define LOG_SWTLB(...) qemu_log(__VA_ARGS__)
#else
# define LOG_SWTLB(...) do { } while (0)
#endif
#ifdef DEBUG_BATS
# define LOG_BATS(...) qemu_log(__VA_ARGS__)
#else
# define LOG_BATS(...) do { } while (0)
#endif
/*****************************************************************************/
/* PowerPC MMU emulation */
/* Context used internally during MMU translations */
typedef struct mmu_ctx_t mmu_ctx_t;
struct mmu_ctx_t {
hwaddr raddr; /* Real address */
hwaddr eaddr; /* Effective address */
int prot; /* Protection bits */
hwaddr hash[2]; /* Pagetable hash values */
target_ulong ptem; /* Virtual segment ID | API */
int key; /* Access key */
int nx; /* Non-execute area */
};
/* Common routines used by software and hardware TLBs emulation */
static inline int pte_is_valid(target_ulong pte0)
{
return pte0 & 0x80000000 ? 1 : 0;
}
static inline void pte_invalidate(target_ulong *pte0)
{
*pte0 &= ~0x80000000;
}
#define PTE_PTEM_MASK 0x7FFFFFBF
#define PTE_CHECK_MASK (TARGET_PAGE_MASK | 0x7B)
static int pp_check(int key, int pp, int nx)
{
int access;
/* Compute access rights */
access = 0;
if (key == 0) {
switch (pp) {
case 0x0:
case 0x1:
case 0x2:
access |= PAGE_WRITE;
/* No break here */
case 0x3:
access |= PAGE_READ;
break;
}
} else {
switch (pp) {
case 0x0:
access = 0;
break;
case 0x1:
case 0x3:
access = PAGE_READ;
break;
case 0x2:
access = PAGE_READ | PAGE_WRITE;
break;
}
}
if (nx == 0) {
access |= PAGE_EXEC;
}
return access;
}
static int check_prot(int prot, int rw, int access_type)
{
int ret;
if (access_type == ACCESS_CODE) {
if (prot & PAGE_EXEC) {
ret = 0;
} else {
ret = -2;
}
} else if (rw) {
if (prot & PAGE_WRITE) {
ret = 0;
} else {
ret = -2;
}
} else {
if (prot & PAGE_READ) {
ret = 0;
} else {
ret = -2;
}
}
return ret;
}
static inline int ppc6xx_tlb_pte_check(mmu_ctx_t *ctx, target_ulong pte0,
target_ulong pte1, int h, int rw, int type)
{
target_ulong ptem, mmask;
int access, ret, pteh, ptev, pp;
ret = -1;
/* Check validity and table match */
ptev = pte_is_valid(pte0);
pteh = (pte0 >> 6) & 1;
if (ptev && h == pteh) {
/* Check vsid & api */
ptem = pte0 & PTE_PTEM_MASK;
mmask = PTE_CHECK_MASK;
pp = pte1 & 0x00000003;
if (ptem == ctx->ptem) {
if (ctx->raddr != (hwaddr)-1ULL) {
/* all matches should have equal RPN, WIMG & PP */
if ((ctx->raddr & mmask) != (pte1 & mmask)) {
qemu_log("Bad RPN/WIMG/PP\n");
return -3;
}
}
/* Compute access rights */
access = pp_check(ctx->key, pp, ctx->nx);
/* Keep the matching PTE informations */
ctx->raddr = pte1;
ctx->prot = access;
ret = check_prot(ctx->prot, rw, type);
if (ret == 0) {
/* Access granted */
qemu_log_mask(CPU_LOG_MMU, "PTE access granted !\n");
} else {
/* Access right violation */
qemu_log_mask(CPU_LOG_MMU, "PTE access rejected\n");
}
}
}
return ret;
}
static int pte_update_flags(mmu_ctx_t *ctx, target_ulong *pte1p,
int ret, int rw)
{
int store = 0;
/* Update page flags */
if (!(*pte1p & 0x00000100)) {
/* Update accessed flag */
*pte1p |= 0x00000100;
store = 1;
}
if (!(*pte1p & 0x00000080)) {
if (rw == 1 && ret == 0) {
/* Update changed flag */
*pte1p |= 0x00000080;
store = 1;
} else {
/* Force page fault for first write access */
ctx->prot &= ~PAGE_WRITE;
}
}
return store;
}
/* Software driven TLB helpers */
static inline int ppc6xx_tlb_getnum(CPUPPCState *env, target_ulong eaddr,
int way, int is_code)
{
int nr;
/* Select TLB num in a way from address */
nr = (eaddr >> TARGET_PAGE_BITS) & (env->tlb_per_way - 1);
/* Select TLB way */
nr += env->tlb_per_way * way;
/* 6xx have separate TLBs for instructions and data */
if (is_code && env->id_tlbs == 1) {
nr += env->nb_tlb;
}
return nr;
}
static inline void ppc6xx_tlb_invalidate_all(CPUPPCState *env)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
ppc6xx_tlb_t *tlb;
int nr, max;
/* LOG_SWTLB("Invalidate all TLBs\n"); */
/* Invalidate all defined software TLB */
max = env->nb_tlb;
if (env->id_tlbs == 1) {
max *= 2;
}
for (nr = 0; nr < max; nr++) {
tlb = &env->tlb.tlb6[nr];
pte_invalidate(&tlb->pte0);
}
tlb_flush(CPU(cpu), 1);
}
static inline void ppc6xx_tlb_invalidate_virt2(CPUPPCState *env,
target_ulong eaddr,
int is_code, int match_epn)
{
#if !defined(FLUSH_ALL_TLBS)
CPUState *cs = CPU(ppc_env_get_cpu(env));
ppc6xx_tlb_t *tlb;
int way, nr;
/* Invalidate ITLB + DTLB, all ways */
for (way = 0; way < env->nb_ways; way++) {
nr = ppc6xx_tlb_getnum(env, eaddr, way, is_code);
tlb = &env->tlb.tlb6[nr];
if (pte_is_valid(tlb->pte0) && (match_epn == 0 || eaddr == tlb->EPN)) {
LOG_SWTLB("TLB invalidate %d/%d " TARGET_FMT_lx "\n", nr,
env->nb_tlb, eaddr);
pte_invalidate(&tlb->pte0);
tlb_flush_page(cs, tlb->EPN);
}
}
#else
/* XXX: PowerPC specification say this is valid as well */
ppc6xx_tlb_invalidate_all(env);
#endif
}
static inline void ppc6xx_tlb_invalidate_virt(CPUPPCState *env,
target_ulong eaddr, int is_code)
{
ppc6xx_tlb_invalidate_virt2(env, eaddr, is_code, 0);
}
static void ppc6xx_tlb_store(CPUPPCState *env, target_ulong EPN, int way,
int is_code, target_ulong pte0, target_ulong pte1)
{
ppc6xx_tlb_t *tlb;
int nr;
nr = ppc6xx_tlb_getnum(env, EPN, way, is_code);
tlb = &env->tlb.tlb6[nr];
LOG_SWTLB("Set TLB %d/%d EPN " TARGET_FMT_lx " PTE0 " TARGET_FMT_lx
" PTE1 " TARGET_FMT_lx "\n", nr, env->nb_tlb, EPN, pte0, pte1);
/* Invalidate any pending reference in QEMU for this virtual address */
ppc6xx_tlb_invalidate_virt2(env, EPN, is_code, 1);
tlb->pte0 = pte0;
tlb->pte1 = pte1;
tlb->EPN = EPN;
/* Store last way for LRU mechanism */
env->last_way = way;
}
static inline int ppc6xx_tlb_check(CPUPPCState *env, mmu_ctx_t *ctx,
target_ulong eaddr, int rw, int access_type)
{
ppc6xx_tlb_t *tlb;
int nr, best, way;
int ret;
best = -1;
ret = -1; /* No TLB found */
for (way = 0; way < env->nb_ways; way++) {
nr = ppc6xx_tlb_getnum(env, eaddr, way,
access_type == ACCESS_CODE ? 1 : 0);
tlb = &env->tlb.tlb6[nr];
/* This test "emulates" the PTE index match for hardware TLBs */
if ((eaddr & TARGET_PAGE_MASK) != tlb->EPN) {
LOG_SWTLB("TLB %d/%d %s [" TARGET_FMT_lx " " TARGET_FMT_lx
"] <> " TARGET_FMT_lx "\n", nr, env->nb_tlb,
pte_is_valid(tlb->pte0) ? "valid" : "inval",
tlb->EPN, tlb->EPN + TARGET_PAGE_SIZE, eaddr);
continue;
}
LOG_SWTLB("TLB %d/%d %s " TARGET_FMT_lx " <> " TARGET_FMT_lx " "
TARGET_FMT_lx " %c %c\n", nr, env->nb_tlb,
pte_is_valid(tlb->pte0) ? "valid" : "inval",
tlb->EPN, eaddr, tlb->pte1,
rw ? 'S' : 'L', access_type == ACCESS_CODE ? 'I' : 'D');
switch (ppc6xx_tlb_pte_check(ctx, tlb->pte0, tlb->pte1, 0, rw, access_type)) {
case -3:
/* TLB inconsistency */
return -1;
case -2:
/* Access violation */
ret = -2;
best = nr;
break;
case -1:
default:
/* No match */
break;
case 0:
/* access granted */
/* XXX: we should go on looping to check all TLBs consistency
* but we can speed-up the whole thing as the
* result would be undefined if TLBs are not consistent.
*/
ret = 0;
best = nr;
goto done;
}
}
if (best != -1) {
done:
LOG_SWTLB("found TLB at addr " TARGET_FMT_plx " prot=%01x ret=%d\n",
ctx->raddr & TARGET_PAGE_MASK, ctx->prot, ret);
/* Update page flags */
pte_update_flags(ctx, &env->tlb.tlb6[best].pte1, ret, rw);
}
return ret;
}
/* Perform BAT hit & translation */
static inline void bat_size_prot(CPUPPCState *env, target_ulong *blp,
int *validp, int *protp, target_ulong *BATu,
target_ulong *BATl)
{
target_ulong bl;
int pp, valid, prot;
bl = (*BATu & 0x00001FFC) << 15;
valid = 0;
prot = 0;
if (((msr_pr == 0) && (*BATu & 0x00000002)) ||
((msr_pr != 0) && (*BATu & 0x00000001))) {
valid = 1;
pp = *BATl & 0x00000003;
if (pp != 0) {
prot = PAGE_READ | PAGE_EXEC;
if (pp == 0x2) {
prot |= PAGE_WRITE;
}
}
}
*blp = bl;
*validp = valid;
*protp = prot;
}
static int get_bat_6xx_tlb(CPUPPCState *env, mmu_ctx_t *ctx,
target_ulong virtual, int rw, int type)
{
target_ulong *BATlt, *BATut, *BATu, *BATl;
target_ulong BEPIl, BEPIu, bl;
int i, valid, prot;
int ret = -1;
LOG_BATS("%s: %cBAT v " TARGET_FMT_lx "\n", __func__,
type == ACCESS_CODE ? 'I' : 'D', virtual);
switch (type) {
case ACCESS_CODE:
BATlt = env->IBAT[1];
BATut = env->IBAT[0];
break;
default:
BATlt = env->DBAT[1];
BATut = env->DBAT[0];
break;
}
for (i = 0; i < env->nb_BATs; i++) {
BATu = &BATut[i];
BATl = &BATlt[i];
BEPIu = *BATu & 0xF0000000;
BEPIl = *BATu & 0x0FFE0000;
bat_size_prot(env, &bl, &valid, &prot, BATu, BATl);
LOG_BATS("%s: %cBAT%d v " TARGET_FMT_lx " BATu " TARGET_FMT_lx
" BATl " TARGET_FMT_lx "\n", __func__,
type == ACCESS_CODE ? 'I' : 'D', i, virtual, *BATu, *BATl);
if ((virtual & 0xF0000000) == BEPIu &&
((virtual & 0x0FFE0000) & ~bl) == BEPIl) {
/* BAT matches */
if (valid != 0) {
/* Get physical address */
ctx->raddr = (*BATl & 0xF0000000) |
((virtual & 0x0FFE0000 & bl) | (*BATl & 0x0FFE0000)) |
(virtual & 0x0001F000);
/* Compute access rights */
ctx->prot = prot;
ret = check_prot(ctx->prot, rw, type);
if (ret == 0) {
LOG_BATS("BAT %d match: r " TARGET_FMT_plx " prot=%c%c\n",
i, ctx->raddr, ctx->prot & PAGE_READ ? 'R' : '-',
ctx->prot & PAGE_WRITE ? 'W' : '-');
}
break;
}
}
}
if (ret < 0) {
#if defined(DEBUG_BATS)
if (qemu_log_enabled()) {
LOG_BATS("no BAT match for " TARGET_FMT_lx ":\n", virtual);
for (i = 0; i < 4; i++) {
BATu = &BATut[i];
BATl = &BATlt[i];
BEPIu = *BATu & 0xF0000000;
BEPIl = *BATu & 0x0FFE0000;
bl = (*BATu & 0x00001FFC) << 15;
LOG_BATS("%s: %cBAT%d v " TARGET_FMT_lx " BATu " TARGET_FMT_lx
" BATl " TARGET_FMT_lx "\n\t" TARGET_FMT_lx " "
TARGET_FMT_lx " " TARGET_FMT_lx "\n",
__func__, type == ACCESS_CODE ? 'I' : 'D', i, virtual,
*BATu, *BATl, BEPIu, BEPIl, bl);
}
}
#endif
}
/* No hit */
return ret;
}
/* Perform segment based translation */
static inline int get_segment_6xx_tlb(CPUPPCState *env, mmu_ctx_t *ctx,
target_ulong eaddr, int rw, int type)
{
hwaddr hash;
target_ulong vsid;
int ds, pr, target_page_bits;
int ret;
target_ulong sr, pgidx;
pr = msr_pr;
ctx->eaddr = eaddr;
sr = env->sr[eaddr >> 28];
ctx->key = (((sr & 0x20000000) && (pr != 0)) ||
((sr & 0x40000000) && (pr == 0))) ? 1 : 0;
ds = sr & 0x80000000 ? 1 : 0;
ctx->nx = sr & 0x10000000 ? 1 : 0;
vsid = sr & 0x00FFFFFF;
target_page_bits = TARGET_PAGE_BITS;
qemu_log_mask(CPU_LOG_MMU,
"Check segment v=" TARGET_FMT_lx " %d " TARGET_FMT_lx
" nip=" TARGET_FMT_lx " lr=" TARGET_FMT_lx
" ir=%d dr=%d pr=%d %d t=%d\n",
eaddr, (int)(eaddr >> 28), sr, env->nip, env->lr, (int)msr_ir,
(int)msr_dr, pr != 0 ? 1 : 0, rw, type);
pgidx = (eaddr & ~SEGMENT_MASK_256M) >> target_page_bits;
hash = vsid ^ pgidx;
ctx->ptem = (vsid << 7) | (pgidx >> 10);
qemu_log_mask(CPU_LOG_MMU,
"pte segment: key=%d ds %d nx %d vsid " TARGET_FMT_lx "\n",
ctx->key, ds, ctx->nx, vsid);
ret = -1;
if (!ds) {
/* Check if instruction fetch is allowed, if needed */
if (type != ACCESS_CODE || ctx->nx == 0) {
/* Page address translation */
qemu_log_mask(CPU_LOG_MMU, "htab_base " TARGET_FMT_plx
" htab_mask " TARGET_FMT_plx
" hash " TARGET_FMT_plx "\n",
env->htab_base, env->htab_mask, hash);
ctx->hash[0] = hash;
ctx->hash[1] = ~hash;
/* Initialize real address with an invalid value */
ctx->raddr = (hwaddr)-1ULL;
/* Software TLB search */
ret = ppc6xx_tlb_check(env, ctx, eaddr, rw, type);
#if defined(DUMP_PAGE_TABLES)
if (qemu_log_enabled()) {
hwaddr curaddr;
uint32_t a0, a1, a2, a3;
qemu_log("Page table: " TARGET_FMT_plx " len " TARGET_FMT_plx
"\n", sdr, mask + 0x80);
for (curaddr = sdr; curaddr < (sdr + mask + 0x80);
curaddr += 16) {
a0 = ldl_phys(curaddr);
a1 = ldl_phys(curaddr + 4);
a2 = ldl_phys(curaddr + 8);
a3 = ldl_phys(curaddr + 12);
if (a0 != 0 || a1 != 0 || a2 != 0 || a3 != 0) {
qemu_log(TARGET_FMT_plx ": %08x %08x %08x %08x\n",
curaddr, a0, a1, a2, a3);
}
}
}
#endif
} else {
qemu_log_mask(CPU_LOG_MMU, "No access allowed\n");
ret = -3;
}
} else {
target_ulong sr;
qemu_log_mask(CPU_LOG_MMU, "direct store...\n");
/* Direct-store segment : absolutely *BUGGY* for now */
/* Direct-store implies a 32-bit MMU.
* Check the Segment Register's bus unit ID (BUID).
*/
sr = env->sr[eaddr >> 28];
if ((sr & 0x1FF00000) >> 20 == 0x07f) {
/* Memory-forced I/O controller interface access */
/* If T=1 and BUID=x'07F', the 601 performs a memory access
* to SR[28-31] LA[4-31], bypassing all protection mechanisms.
*/
ctx->raddr = ((sr & 0xF) << 28) | (eaddr & 0x0FFFFFFF);
ctx->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
return 0;
}
switch (type) {
case ACCESS_INT:
/* Integer load/store : only access allowed */
break;
case ACCESS_CODE:
/* No code fetch is allowed in direct-store areas */
return -4;
case ACCESS_FLOAT:
/* Floating point load/store */
return -4;
case ACCESS_RES:
/* lwarx, ldarx or srwcx. */
return -4;
case ACCESS_CACHE:
/* dcba, dcbt, dcbtst, dcbf, dcbi, dcbst, dcbz, or icbi */
/* Should make the instruction do no-op.
* As it already do no-op, it's quite easy :-)
*/
ctx->raddr = eaddr;
return 0;
case ACCESS_EXT:
/* eciwx or ecowx */
return -4;
default:
qemu_log("ERROR: instruction should not need "
"address translation\n");
return -4;
}
if ((rw == 1 || ctx->key != 1) && (rw == 0 || ctx->key != 0)) {
ctx->raddr = eaddr;
ret = 2;
} else {
ret = -2;
}
}
return ret;
}
/* Generic TLB check function for embedded PowerPC implementations */
static int ppcemb_tlb_check(CPUPPCState *env, ppcemb_tlb_t *tlb,
hwaddr *raddrp,
target_ulong address, uint32_t pid, int ext,
int i)
{
target_ulong mask;
/* Check valid flag */
if (!(tlb->prot & PAGE_VALID)) {
return -1;
}
mask = ~(tlb->size - 1);
LOG_SWTLB("%s: TLB %d address " TARGET_FMT_lx " PID %u <=> " TARGET_FMT_lx
" " TARGET_FMT_lx " %u %x\n", __func__, i, address, pid, tlb->EPN,
mask, (uint32_t)tlb->PID, tlb->prot);
/* Check PID */
if (tlb->PID != 0 && tlb->PID != pid) {
return -1;
}
/* Check effective address */
if ((address & mask) != tlb->EPN) {
return -1;
}
*raddrp = (tlb->RPN & mask) | (address & ~mask);
if (ext) {
/* Extend the physical address to 36 bits */
*raddrp |= (uint64_t)(tlb->RPN & 0xF) << 32;
}
return 0;
}
/* Generic TLB search function for PowerPC embedded implementations */
static int ppcemb_tlb_search(CPUPPCState *env, target_ulong address,
uint32_t pid)
{
ppcemb_tlb_t *tlb;
hwaddr raddr;
int i, ret;
/* Default return value is no match */
ret = -1;
for (i = 0; i < env->nb_tlb; i++) {
tlb = &env->tlb.tlbe[i];
if (ppcemb_tlb_check(env, tlb, &raddr, address, pid, 0, i) == 0) {
ret = i;
break;
}
}
return ret;
}
/* Helpers specific to PowerPC 40x implementations */
static inline void ppc4xx_tlb_invalidate_all(CPUPPCState *env)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
ppcemb_tlb_t *tlb;
int i;
for (i = 0; i < env->nb_tlb; i++) {
tlb = &env->tlb.tlbe[i];
tlb->prot &= ~PAGE_VALID;
}
tlb_flush(CPU(cpu), 1);
}
static inline void ppc4xx_tlb_invalidate_virt(CPUPPCState *env,
target_ulong eaddr, uint32_t pid)
{
#if !defined(FLUSH_ALL_TLBS)
CPUState *cs = CPU(ppc_env_get_cpu(env));
ppcemb_tlb_t *tlb;
hwaddr raddr;
target_ulong page, end;
int i;
for (i = 0; i < env->nb_tlb; i++) {
tlb = &env->tlb.tlbe[i];
if (ppcemb_tlb_check(env, tlb, &raddr, eaddr, pid, 0, i) == 0) {
end = tlb->EPN + tlb->size;
for (page = tlb->EPN; page < end; page += TARGET_PAGE_SIZE) {
tlb_flush_page(cs, page);
}
tlb->prot &= ~PAGE_VALID;
break;
}
}
#else
ppc4xx_tlb_invalidate_all(env);
#endif
}
static int mmu40x_get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
target_ulong address, int rw,
int access_type)
{
ppcemb_tlb_t *tlb;
hwaddr raddr;
int i, ret, zsel, zpr, pr;
ret = -1;
raddr = (hwaddr)-1ULL;
pr = msr_pr;
for (i = 0; i < env->nb_tlb; i++) {
tlb = &env->tlb.tlbe[i];
if (ppcemb_tlb_check(env, tlb, &raddr, address,
env->spr[SPR_40x_PID], 0, i) < 0) {
continue;
}
zsel = (tlb->attr >> 4) & 0xF;
zpr = (env->spr[SPR_40x_ZPR] >> (30 - (2 * zsel))) & 0x3;
LOG_SWTLB("%s: TLB %d zsel %d zpr %d rw %d attr %08x\n",
__func__, i, zsel, zpr, rw, tlb->attr);
/* Check execute enable bit */
switch (zpr) {
case 0x2:
if (pr != 0) {
goto check_perms;
}
/* No break here */
case 0x3:
/* All accesses granted */
ctx->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
ret = 0;
break;
case 0x0:
if (pr != 0) {
/* Raise Zone protection fault. */
env->spr[SPR_40x_ESR] = 1 << 22;
ctx->prot = 0;
ret = -2;
break;
}
/* No break here */
case 0x1:
check_perms:
/* Check from TLB entry */
ctx->prot = tlb->prot;
ret = check_prot(ctx->prot, rw, access_type);
if (ret == -2) {
env->spr[SPR_40x_ESR] = 0;
}
break;
}
if (ret >= 0) {
ctx->raddr = raddr;
LOG_SWTLB("%s: access granted " TARGET_FMT_lx " => " TARGET_FMT_plx
" %d %d\n", __func__, address, ctx->raddr, ctx->prot,
ret);
return 0;
}
}
LOG_SWTLB("%s: access refused " TARGET_FMT_lx " => " TARGET_FMT_plx
" %d %d\n", __func__, address, raddr, ctx->prot, ret);
return ret;
}
void store_40x_sler(CPUPPCState *env, uint32_t val)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
/* XXX: TO BE FIXED */
if (val != 0x00000000) {
cpu_abort(CPU(cpu), "Little-endian regions are not supported by now\n");
}
env->spr[SPR_405_SLER] = val;
}
static inline int mmubooke_check_tlb(CPUPPCState *env, ppcemb_tlb_t *tlb,
hwaddr *raddr, int *prot,
target_ulong address, int rw,
int access_type, int i)
{
int ret, prot2;
if (ppcemb_tlb_check(env, tlb, raddr, address,
env->spr[SPR_BOOKE_PID],
!env->nb_pids, i) >= 0) {
goto found_tlb;
}
if (env->spr[SPR_BOOKE_PID1] &&
ppcemb_tlb_check(env, tlb, raddr, address,
env->spr[SPR_BOOKE_PID1], 0, i) >= 0) {
goto found_tlb;
}
if (env->spr[SPR_BOOKE_PID2] &&
ppcemb_tlb_check(env, tlb, raddr, address,
env->spr[SPR_BOOKE_PID2], 0, i) >= 0) {
goto found_tlb;
}
LOG_SWTLB("%s: TLB entry not found\n", __func__);
return -1;
found_tlb:
if (msr_pr != 0) {
prot2 = tlb->prot & 0xF;
} else {
prot2 = (tlb->prot >> 4) & 0xF;
}
/* Check the address space */
if (access_type == ACCESS_CODE) {
if (msr_ir != (tlb->attr & 1)) {
LOG_SWTLB("%s: AS doesn't match\n", __func__);
return -1;
}
*prot = prot2;
if (prot2 & PAGE_EXEC) {
LOG_SWTLB("%s: good TLB!\n", __func__);
return 0;
}
LOG_SWTLB("%s: no PAGE_EXEC: %x\n", __func__, prot2);
ret = -3;
} else {
if (msr_dr != (tlb->attr & 1)) {
LOG_SWTLB("%s: AS doesn't match\n", __func__);
return -1;
}
*prot = prot2;
if ((!rw && prot2 & PAGE_READ) || (rw && (prot2 & PAGE_WRITE))) {
LOG_SWTLB("%s: found TLB!\n", __func__);
return 0;
}
LOG_SWTLB("%s: PAGE_READ/WRITE doesn't match: %x\n", __func__, prot2);
ret = -2;
}
return ret;
}
static int mmubooke_get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
target_ulong address, int rw,
int access_type)
{
ppcemb_tlb_t *tlb;
hwaddr raddr;
int i, ret;
ret = -1;
raddr = (hwaddr)-1ULL;
for (i = 0; i < env->nb_tlb; i++) {
tlb = &env->tlb.tlbe[i];
ret = mmubooke_check_tlb(env, tlb, &raddr, &ctx->prot, address, rw,
access_type, i);
if (!ret) {
break;
}
}
if (ret >= 0) {
ctx->raddr = raddr;
LOG_SWTLB("%s: access granted " TARGET_FMT_lx " => " TARGET_FMT_plx
" %d %d\n", __func__, address, ctx->raddr, ctx->prot,
ret);
} else {
LOG_SWTLB("%s: access refused " TARGET_FMT_lx " => " TARGET_FMT_plx
" %d %d\n", __func__, address, raddr, ctx->prot, ret);
}
return ret;
}
static void booke206_flush_tlb(CPUPPCState *env, int flags,
const int check_iprot)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
int tlb_size;
int i, j;
ppcmas_tlb_t *tlb = env->tlb.tlbm;
for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
if (flags & (1 << i)) {
tlb_size = booke206_tlb_size(env, i);
for (j = 0; j < tlb_size; j++) {
if (!check_iprot || !(tlb[j].mas1 & MAS1_IPROT)) {
tlb[j].mas1 &= ~MAS1_VALID;
}
}
}
tlb += booke206_tlb_size(env, i);
}
tlb_flush(CPU(cpu), 1);
}
static hwaddr booke206_tlb_to_page_size(CPUPPCState *env,
ppcmas_tlb_t *tlb)
{
int tlbm_size;
tlbm_size = (tlb->mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
return 1024ULL << tlbm_size;
}
/* TLB check function for MAS based SoftTLBs */
static int ppcmas_tlb_check(CPUPPCState *env, ppcmas_tlb_t *tlb,
hwaddr *raddrp, target_ulong address,
uint32_t pid)
{
hwaddr mask;
uint32_t tlb_pid;
if (!msr_cm) {
/* In 32bit mode we can only address 32bit EAs */
address = (uint32_t)address;
}
/* Check valid flag */
if (!(tlb->mas1 & MAS1_VALID)) {
return -1;
}
mask = ~(booke206_tlb_to_page_size(env, tlb) - 1);
LOG_SWTLB("%s: TLB ADDR=0x" TARGET_FMT_lx " PID=0x%x MAS1=0x%x MAS2=0x%"
PRIx64 " mask=0x" TARGET_FMT_lx " MAS7_3=0x%" PRIx64 " MAS8=%x\n",
__func__, address, pid, tlb->mas1, tlb->mas2, mask, tlb->mas7_3,
tlb->mas8);
/* Check PID */
tlb_pid = (tlb->mas1 & MAS1_TID_MASK) >> MAS1_TID_SHIFT;
if (tlb_pid != 0 && tlb_pid != pid) {
return -1;
}
/* Check effective address */
if ((address & mask) != (tlb->mas2 & MAS2_EPN_MASK)) {
return -1;
}
if (raddrp) {
*raddrp = (tlb->mas7_3 & mask) | (address & ~mask);
}
return 0;
}
static int mmubooke206_check_tlb(CPUPPCState *env, ppcmas_tlb_t *tlb,
hwaddr *raddr, int *prot,
target_ulong address, int rw,
int access_type)
{
int ret;
int prot2 = 0;
if (ppcmas_tlb_check(env, tlb, raddr, address,
env->spr[SPR_BOOKE_PID]) >= 0) {
goto found_tlb;
}
if (env->spr[SPR_BOOKE_PID1] &&
ppcmas_tlb_check(env, tlb, raddr, address,
env->spr[SPR_BOOKE_PID1]) >= 0) {
goto found_tlb;
}
if (env->spr[SPR_BOOKE_PID2] &&
ppcmas_tlb_check(env, tlb, raddr, address,
env->spr[SPR_BOOKE_PID2]) >= 0) {
goto found_tlb;
}
LOG_SWTLB("%s: TLB entry not found\n", __func__);
return -1;
found_tlb:
if (msr_pr != 0) {
if (tlb->mas7_3 & MAS3_UR) {
prot2 |= PAGE_READ;
}
if (tlb->mas7_3 & MAS3_UW) {
prot2 |= PAGE_WRITE;
}
if (tlb->mas7_3 & MAS3_UX) {
prot2 |= PAGE_EXEC;
}
} else {
if (tlb->mas7_3 & MAS3_SR) {
prot2 |= PAGE_READ;
}
if (tlb->mas7_3 & MAS3_SW) {
prot2 |= PAGE_WRITE;
}
if (tlb->mas7_3 & MAS3_SX) {
prot2 |= PAGE_EXEC;
}
}
/* Check the address space and permissions */
if (access_type == ACCESS_CODE) {
if (msr_ir != ((tlb->mas1 & MAS1_TS) >> MAS1_TS_SHIFT)) {
LOG_SWTLB("%s: AS doesn't match\n", __func__);
return -1;
}
*prot = prot2;
if (prot2 & PAGE_EXEC) {
LOG_SWTLB("%s: good TLB!\n", __func__);
return 0;
}
LOG_SWTLB("%s: no PAGE_EXEC: %x\n", __func__, prot2);
ret = -3;
} else {
if (msr_dr != ((tlb->mas1 & MAS1_TS) >> MAS1_TS_SHIFT)) {
LOG_SWTLB("%s: AS doesn't match\n", __func__);
return -1;
}
*prot = prot2;
if ((!rw && prot2 & PAGE_READ) || (rw && (prot2 & PAGE_WRITE))) {
LOG_SWTLB("%s: found TLB!\n", __func__);
return 0;
}
LOG_SWTLB("%s: PAGE_READ/WRITE doesn't match: %x\n", __func__, prot2);
ret = -2;
}
return ret;
}
static int mmubooke206_get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
target_ulong address, int rw,
int access_type)
{
ppcmas_tlb_t *tlb;
hwaddr raddr;
int i, j, ret;
ret = -1;
raddr = (hwaddr)-1ULL;
for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
int ways = booke206_tlb_ways(env, i);
for (j = 0; j < ways; j++) {
tlb = booke206_get_tlbm(env, i, address, j);
if (!tlb) {
continue;
}
ret = mmubooke206_check_tlb(env, tlb, &raddr, &ctx->prot, address,
rw, access_type);
if (ret != -1) {
goto found_tlb;
}
}
}
found_tlb:
if (ret >= 0) {
ctx->raddr = raddr;
LOG_SWTLB("%s: access granted " TARGET_FMT_lx " => " TARGET_FMT_plx
" %d %d\n", __func__, address, ctx->raddr, ctx->prot,
ret);
} else {
LOG_SWTLB("%s: access refused " TARGET_FMT_lx " => " TARGET_FMT_plx
" %d %d\n", __func__, address, raddr, ctx->prot, ret);
}
return ret;
}
static const char *book3e_tsize_to_str[32] = {
"1K", "2K", "4K", "8K", "16K", "32K", "64K", "128K", "256K", "512K",
"1M", "2M", "4M", "8M", "16M", "32M", "64M", "128M", "256M", "512M",
"1G", "2G", "4G", "8G", "16G", "32G", "64G", "128G", "256G", "512G",
"1T", "2T"
};
static void mmubooke_dump_mmu(FILE *f, fprintf_function cpu_fprintf,
CPUPPCState *env)
{
ppcemb_tlb_t *entry;
int i;
if (kvm_enabled() && !env->kvm_sw_tlb) {
cpu_fprintf(f, "Cannot access KVM TLB\n");
return;
}
cpu_fprintf(f, "\nTLB:\n");
cpu_fprintf(f, "Effective Physical Size PID Prot "
"Attr\n");
entry = &env->tlb.tlbe[0];
for (i = 0; i < env->nb_tlb; i++, entry++) {
hwaddr ea, pa;
target_ulong mask;
uint64_t size = (uint64_t)entry->size;
char size_buf[20];
/* Check valid flag */
if (!(entry->prot & PAGE_VALID)) {
continue;
}
mask = ~(entry->size - 1);
ea = entry->EPN & mask;
pa = entry->RPN & mask;
/* Extend the physical address to 36 bits */
pa |= (hwaddr)(entry->RPN & 0xF) << 32;
size /= 1024;
if (size >= 1024) {
snprintf(size_buf, sizeof(size_buf), "%3" PRId64 "M", size / 1024);
} else {
snprintf(size_buf, sizeof(size_buf), "%3" PRId64 "k", size);
}
cpu_fprintf(f, "0x%016" PRIx64 " 0x%016" PRIx64 " %s %-5u %08x %08x\n",
(uint64_t)ea, (uint64_t)pa, size_buf, (uint32_t)entry->PID,
entry->prot, entry->attr);
}
}
static void mmubooke206_dump_one_tlb(FILE *f, fprintf_function cpu_fprintf,
CPUPPCState *env, int tlbn, int offset,
int tlbsize)
{
ppcmas_tlb_t *entry;
int i;
cpu_fprintf(f, "\nTLB%d:\n", tlbn);
cpu_fprintf(f, "Effective Physical Size TID TS SRWX"
" URWX WIMGE U0123\n");
entry = &env->tlb.tlbm[offset];
for (i = 0; i < tlbsize; i++, entry++) {
hwaddr ea, pa, size;
int tsize;
if (!(entry->mas1 & MAS1_VALID)) {
continue;
}
tsize = (entry->mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
size = 1024ULL << tsize;
ea = entry->mas2 & ~(size - 1);
pa = entry->mas7_3 & ~(size - 1);
cpu_fprintf(f, "0x%016" PRIx64 " 0x%016" PRIx64 " %4s %-5u %1u S%c%c%c"
"U%c%c%c %c%c%c%c%c U%c%c%c%c\n",
(uint64_t)ea, (uint64_t)pa,
book3e_tsize_to_str[tsize],
(entry->mas1 & MAS1_TID_MASK) >> MAS1_TID_SHIFT,
(entry->mas1 & MAS1_TS) >> MAS1_TS_SHIFT,
entry->mas7_3 & MAS3_SR ? 'R' : '-',
entry->mas7_3 & MAS3_SW ? 'W' : '-',
entry->mas7_3 & MAS3_SX ? 'X' : '-',
entry->mas7_3 & MAS3_UR ? 'R' : '-',
entry->mas7_3 & MAS3_UW ? 'W' : '-',
entry->mas7_3 & MAS3_UX ? 'X' : '-',
entry->mas2 & MAS2_W ? 'W' : '-',
entry->mas2 & MAS2_I ? 'I' : '-',
entry->mas2 & MAS2_M ? 'M' : '-',
entry->mas2 & MAS2_G ? 'G' : '-',
entry->mas2 & MAS2_E ? 'E' : '-',
entry->mas7_3 & MAS3_U0 ? '0' : '-',
entry->mas7_3 & MAS3_U1 ? '1' : '-',
entry->mas7_3 & MAS3_U2 ? '2' : '-',
entry->mas7_3 & MAS3_U3 ? '3' : '-');
}
}
static void mmubooke206_dump_mmu(FILE *f, fprintf_function cpu_fprintf,
CPUPPCState *env)
{
int offset = 0;
int i;
if (kvm_enabled() && !env->kvm_sw_tlb) {
cpu_fprintf(f, "Cannot access KVM TLB\n");
return;
}
for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
int size = booke206_tlb_size(env, i);
if (size == 0) {
continue;
}
mmubooke206_dump_one_tlb(f, cpu_fprintf, env, i, offset, size);
offset += size;
}
}
static void mmu6xx_dump_BATs(FILE *f, fprintf_function cpu_fprintf,
CPUPPCState *env, int type)
{
target_ulong *BATlt, *BATut, *BATu, *BATl;
target_ulong BEPIl, BEPIu, bl;
int i;
switch (type) {
case ACCESS_CODE:
BATlt = env->IBAT[1];
BATut = env->IBAT[0];
break;
default:
BATlt = env->DBAT[1];
BATut = env->DBAT[0];
break;
}
for (i = 0; i < env->nb_BATs; i++) {
BATu = &BATut[i];
BATl = &BATlt[i];
BEPIu = *BATu & 0xF0000000;
BEPIl = *BATu & 0x0FFE0000;
bl = (*BATu & 0x00001FFC) << 15;
cpu_fprintf(f, "%s BAT%d BATu " TARGET_FMT_lx
" BATl " TARGET_FMT_lx "\n\t" TARGET_FMT_lx " "
TARGET_FMT_lx " " TARGET_FMT_lx "\n",
type == ACCESS_CODE ? "code" : "data", i,
*BATu, *BATl, BEPIu, BEPIl, bl);
}
}
static void mmu6xx_dump_mmu(FILE *f, fprintf_function cpu_fprintf,
CPUPPCState *env)
{
ppc6xx_tlb_t *tlb;
target_ulong sr;
int type, way, entry, i;
cpu_fprintf(f, "HTAB base = 0x%"HWADDR_PRIx"\n", env->htab_base);
cpu_fprintf(f, "HTAB mask = 0x%"HWADDR_PRIx"\n", env->htab_mask);
cpu_fprintf(f, "\nSegment registers:\n");
for (i = 0; i < 32; i++) {
sr = env->sr[i];
if (sr & 0x80000000) {
cpu_fprintf(f, "%02d T=%d Ks=%d Kp=%d BUID=0x%03x "
"CNTLR_SPEC=0x%05x\n", i,
sr & 0x80000000 ? 1 : 0, sr & 0x40000000 ? 1 : 0,
sr & 0x20000000 ? 1 : 0, (uint32_t)((sr >> 20) & 0x1FF),
(uint32_t)(sr & 0xFFFFF));
} else {
cpu_fprintf(f, "%02d T=%d Ks=%d Kp=%d N=%d VSID=0x%06x\n", i,
sr & 0x80000000 ? 1 : 0, sr & 0x40000000 ? 1 : 0,
sr & 0x20000000 ? 1 : 0, sr & 0x10000000 ? 1 : 0,
(uint32_t)(sr & 0x00FFFFFF));
}
}
cpu_fprintf(f, "\nBATs:\n");
mmu6xx_dump_BATs(f, cpu_fprintf, env, ACCESS_INT);
mmu6xx_dump_BATs(f, cpu_fprintf, env, ACCESS_CODE);
if (env->id_tlbs != 1) {
cpu_fprintf(f, "ERROR: 6xx MMU should have separated TLB"
" for code and data\n");
}
cpu_fprintf(f, "\nTLBs [EPN EPN + SIZE]\n");
for (type = 0; type < 2; type++) {
for (way = 0; way < env->nb_ways; way++) {
for (entry = env->nb_tlb * type + env->tlb_per_way * way;
entry < (env->nb_tlb * type + env->tlb_per_way * (way + 1));
entry++) {
tlb = &env->tlb.tlb6[entry];
cpu_fprintf(f, "%s TLB %02d/%02d way:%d %s ["
TARGET_FMT_lx " " TARGET_FMT_lx "]\n",
type ? "code" : "data", entry % env->nb_tlb,
env->nb_tlb, way,
pte_is_valid(tlb->pte0) ? "valid" : "inval",
tlb->EPN, tlb->EPN + TARGET_PAGE_SIZE);
}
}
}
}
void dump_mmu(FILE *f, fprintf_function cpu_fprintf, CPUPPCState *env)
{
switch (env->mmu_model) {
case POWERPC_MMU_BOOKE:
mmubooke_dump_mmu(f, cpu_fprintf, env);
break;
case POWERPC_MMU_BOOKE206:
mmubooke206_dump_mmu(f, cpu_fprintf, env);
break;
case POWERPC_MMU_SOFT_6xx:
case POWERPC_MMU_SOFT_74xx:
mmu6xx_dump_mmu(f, cpu_fprintf, env);
break;
#if defined(TARGET_PPC64)
case POWERPC_MMU_64B:
case POWERPC_MMU_2_03:
case POWERPC_MMU_2_06:
case POWERPC_MMU_2_06a:
case POWERPC_MMU_2_07:
case POWERPC_MMU_2_07a:
dump_slb(f, cpu_fprintf, env);
break;
#endif
default:
qemu_log_mask(LOG_UNIMP, "%s: unimplemented\n", __func__);
}
}
static inline int check_physical(CPUPPCState *env, mmu_ctx_t *ctx,
target_ulong eaddr, int rw)
{
int in_plb, ret;
ctx->raddr = eaddr;
ctx->prot = PAGE_READ | PAGE_EXEC;
ret = 0;
switch (env->mmu_model) {
case POWERPC_MMU_SOFT_6xx:
case POWERPC_MMU_SOFT_74xx:
case POWERPC_MMU_SOFT_4xx:
case POWERPC_MMU_REAL:
case POWERPC_MMU_BOOKE:
ctx->prot |= PAGE_WRITE;
break;
case POWERPC_MMU_SOFT_4xx_Z:
if (unlikely(msr_pe != 0)) {
/* 403 family add some particular protections,
* using PBL/PBU registers for accesses with no translation.
*/
in_plb =
/* Check PLB validity */
(env->pb[0] < env->pb[1] &&
/* and address in plb area */
eaddr >= env->pb[0] && eaddr < env->pb[1]) ||
(env->pb[2] < env->pb[3] &&
eaddr >= env->pb[2] && eaddr < env->pb[3]) ? 1 : 0;
if (in_plb ^ msr_px) {
/* Access in protected area */
if (rw == 1) {
/* Access is not allowed */
ret = -2;
}
} else {
/* Read-write access is allowed */
ctx->prot |= PAGE_WRITE;
}
}
break;
default:
/* Caller's checks mean we should never get here for other models */
abort();
return -1;
}
return ret;
}
static int get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
target_ulong eaddr, int rw, int access_type)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
int ret = -1;
bool real_mode = (access_type == ACCESS_CODE && msr_ir == 0)
|| (access_type != ACCESS_CODE && msr_dr == 0);
#if 0
qemu_log("%s\n", __func__);
#endif
switch (env->mmu_model) {
case POWERPC_MMU_SOFT_6xx:
case POWERPC_MMU_SOFT_74xx:
if (real_mode) {
ret = check_physical(env, ctx, eaddr, rw);
} else {
/* Try to find a BAT */
if (env->nb_BATs != 0) {
ret = get_bat_6xx_tlb(env, ctx, eaddr, rw, access_type);
}
if (ret < 0) {
/* We didn't match any BAT entry or don't have BATs */
ret = get_segment_6xx_tlb(env, ctx, eaddr, rw, access_type);
}
}
break;
case POWERPC_MMU_SOFT_4xx:
case POWERPC_MMU_SOFT_4xx_Z:
if (real_mode) {
ret = check_physical(env, ctx, eaddr, rw);
} else {
ret = mmu40x_get_physical_address(env, ctx, eaddr,
rw, access_type);
}
break;
case POWERPC_MMU_BOOKE:
ret = mmubooke_get_physical_address(env, ctx, eaddr,
rw, access_type);
break;
case POWERPC_MMU_BOOKE206:
ret = mmubooke206_get_physical_address(env, ctx, eaddr, rw,
access_type);
break;
case POWERPC_MMU_MPC8xx:
/* XXX: TODO */
cpu_abort(CPU(cpu), "MPC8xx MMU model is not implemented\n");
break;
case POWERPC_MMU_REAL:
if (real_mode) {
ret = check_physical(env, ctx, eaddr, rw);
} else {
cpu_abort(CPU(cpu), "PowerPC in real mode do not do any translation\n");
}
return -1;
default:
cpu_abort(CPU(cpu), "Unknown or invalid MMU model\n");
return -1;
}
#if 0
qemu_log("%s address " TARGET_FMT_lx " => %d " TARGET_FMT_plx "\n",
__func__, eaddr, ret, ctx->raddr);
#endif
return ret;
}
hwaddr ppc_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
{
PowerPCCPU *cpu = POWERPC_CPU(cs);
CPUPPCState *env = &cpu->env;
mmu_ctx_t ctx;
switch (env->mmu_model) {
#if defined(TARGET_PPC64)
case POWERPC_MMU_64B:
case POWERPC_MMU_2_03:
case POWERPC_MMU_2_06:
case POWERPC_MMU_2_06a:
case POWERPC_MMU_2_07:
case POWERPC_MMU_2_07a:
return ppc_hash64_get_phys_page_debug(env, addr);
#endif
case POWERPC_MMU_32B:
case POWERPC_MMU_601:
return ppc_hash32_get_phys_page_debug(env, addr);
default:
;
}
if (unlikely(get_physical_address(env, &ctx, addr, 0, ACCESS_INT) != 0)) {
/* Some MMUs have separate TLBs for code and data. If we only try an
* ACCESS_INT, we may not be able to read instructions mapped by code
* TLBs, so we also try a ACCESS_CODE.
*/
if (unlikely(get_physical_address(env, &ctx, addr, 0,
ACCESS_CODE) != 0)) {
return -1;
}
}
return ctx.raddr & TARGET_PAGE_MASK;
}
static void booke206_update_mas_tlb_miss(CPUPPCState *env, target_ulong address,
int rw)
{
env->spr[SPR_BOOKE_MAS0] = env->spr[SPR_BOOKE_MAS4] & MAS4_TLBSELD_MASK;
env->spr[SPR_BOOKE_MAS1] = env->spr[SPR_BOOKE_MAS4] & MAS4_TSIZED_MASK;
env->spr[SPR_BOOKE_MAS2] = env->spr[SPR_BOOKE_MAS4] & MAS4_WIMGED_MASK;
env->spr[SPR_BOOKE_MAS3] = 0;
env->spr[SPR_BOOKE_MAS6] = 0;
env->spr[SPR_BOOKE_MAS7] = 0;
/* AS */
if (((rw == 2) && msr_ir) || ((rw != 2) && msr_dr)) {
env->spr[SPR_BOOKE_MAS1] |= MAS1_TS;
env->spr[SPR_BOOKE_MAS6] |= MAS6_SAS;
}
env->spr[SPR_BOOKE_MAS1] |= MAS1_VALID;
env->spr[SPR_BOOKE_MAS2] |= address & MAS2_EPN_MASK;
switch (env->spr[SPR_BOOKE_MAS4] & MAS4_TIDSELD_PIDZ) {
case MAS4_TIDSELD_PID0:
env->spr[SPR_BOOKE_MAS1] |= env->spr[SPR_BOOKE_PID] << MAS1_TID_SHIFT;
break;
case MAS4_TIDSELD_PID1:
env->spr[SPR_BOOKE_MAS1] |= env->spr[SPR_BOOKE_PID1] << MAS1_TID_SHIFT;
break;
case MAS4_TIDSELD_PID2:
env->spr[SPR_BOOKE_MAS1] |= env->spr[SPR_BOOKE_PID2] << MAS1_TID_SHIFT;
break;
}
env->spr[SPR_BOOKE_MAS6] |= env->spr[SPR_BOOKE_PID] << 16;
/* next victim logic */
env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_ESEL_SHIFT;
env->last_way++;
env->last_way &= booke206_tlb_ways(env, 0) - 1;
env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_NV_SHIFT;
}
/* Perform address translation */
static int cpu_ppc_handle_mmu_fault(CPUPPCState *env, target_ulong address,
int rw, int mmu_idx)
{
CPUState *cs = CPU(ppc_env_get_cpu(env));
mmu_ctx_t ctx;
int access_type;
int ret = 0;
if (rw == 2) {
/* code access */
rw = 0;
access_type = ACCESS_CODE;
} else {
/* data access */
access_type = env->access_type;
}
ret = get_physical_address(env, &ctx, address, rw, access_type);
if (ret == 0) {
tlb_set_page(cs, address & TARGET_PAGE_MASK,
ctx.raddr & TARGET_PAGE_MASK, ctx.prot,
mmu_idx, TARGET_PAGE_SIZE);
ret = 0;
} else if (ret < 0) {
LOG_MMU_STATE(cs);
if (access_type == ACCESS_CODE) {
switch (ret) {
case -1:
/* No matches in page tables or TLB */
switch (env->mmu_model) {
case POWERPC_MMU_SOFT_6xx:
cs->exception_index = POWERPC_EXCP_IFTLB;
env->error_code = 1 << 18;
env->spr[SPR_IMISS] = address;
env->spr[SPR_ICMP] = 0x80000000 | ctx.ptem;
goto tlb_miss;
case POWERPC_MMU_SOFT_74xx:
cs->exception_index = POWERPC_EXCP_IFTLB;
goto tlb_miss_74xx;
case POWERPC_MMU_SOFT_4xx:
case POWERPC_MMU_SOFT_4xx_Z:
cs->exception_index = POWERPC_EXCP_ITLB;
env->error_code = 0;
env->spr[SPR_40x_DEAR] = address;
env->spr[SPR_40x_ESR] = 0x00000000;
break;
case POWERPC_MMU_BOOKE206:
booke206_update_mas_tlb_miss(env, address, rw);
/* fall through */
case POWERPC_MMU_BOOKE:
cs->exception_index = POWERPC_EXCP_ITLB;
env->error_code = 0;
env->spr[SPR_BOOKE_DEAR] = address;
return -1;
case POWERPC_MMU_MPC8xx:
/* XXX: TODO */
cpu_abort(cs, "MPC8xx MMU model is not implemented\n");
break;
case POWERPC_MMU_REAL:
cpu_abort(cs, "PowerPC in real mode should never raise "
"any MMU exceptions\n");
return -1;
default:
cpu_abort(cs, "Unknown or invalid MMU model\n");
return -1;
}
break;
case -2:
/* Access rights violation */
cs->exception_index = POWERPC_EXCP_ISI;
env->error_code = 0x08000000;
break;
case -3:
/* No execute protection violation */
if ((env->mmu_model == POWERPC_MMU_BOOKE) ||
(env->mmu_model == POWERPC_MMU_BOOKE206)) {
env->spr[SPR_BOOKE_ESR] = 0x00000000;
}
cs->exception_index = POWERPC_EXCP_ISI;
env->error_code = 0x10000000;
break;
case -4:
/* Direct store exception */
/* No code fetch is allowed in direct-store areas */
cs->exception_index = POWERPC_EXCP_ISI;
env->error_code = 0x10000000;
break;
}
} else {
switch (ret) {
case -1:
/* No matches in page tables or TLB */
switch (env->mmu_model) {
case POWERPC_MMU_SOFT_6xx:
if (rw == 1) {
cs->exception_index = POWERPC_EXCP_DSTLB;
env->error_code = 1 << 16;
} else {
cs->exception_index = POWERPC_EXCP_DLTLB;
env->error_code = 0;
}
env->spr[SPR_DMISS] = address;
env->spr[SPR_DCMP] = 0x80000000 | ctx.ptem;
tlb_miss:
env->error_code |= ctx.key << 19;
env->spr[SPR_HASH1] = env->htab_base +
get_pteg_offset32(env, ctx.hash[0]);
env->spr[SPR_HASH2] = env->htab_base +
get_pteg_offset32(env, ctx.hash[1]);
break;
case POWERPC_MMU_SOFT_74xx:
if (rw == 1) {
cs->exception_index = POWERPC_EXCP_DSTLB;
} else {
cs->exception_index = POWERPC_EXCP_DLTLB;
}
tlb_miss_74xx:
/* Implement LRU algorithm */
env->error_code = ctx.key << 19;
env->spr[SPR_TLBMISS] = (address & ~((target_ulong)0x3)) |
((env->last_way + 1) & (env->nb_ways - 1));
env->spr[SPR_PTEHI] = 0x80000000 | ctx.ptem;
break;
case POWERPC_MMU_SOFT_4xx:
case POWERPC_MMU_SOFT_4xx_Z:
cs->exception_index = POWERPC_EXCP_DTLB;
env->error_code = 0;
env->spr[SPR_40x_DEAR] = address;
if (rw) {
env->spr[SPR_40x_ESR] = 0x00800000;
} else {
env->spr[SPR_40x_ESR] = 0x00000000;
}
break;
case POWERPC_MMU_MPC8xx:
/* XXX: TODO */
cpu_abort(cs, "MPC8xx MMU model is not implemented\n");
break;
case POWERPC_MMU_BOOKE206:
booke206_update_mas_tlb_miss(env, address, rw);
/* fall through */
case POWERPC_MMU_BOOKE:
cs->exception_index = POWERPC_EXCP_DTLB;
env->error_code = 0;
env->spr[SPR_BOOKE_DEAR] = address;
env->spr[SPR_BOOKE_ESR] = rw ? ESR_ST : 0;
return -1;
case POWERPC_MMU_REAL:
cpu_abort(cs, "PowerPC in real mode should never raise "
"any MMU exceptions\n");
return -1;
default:
cpu_abort(cs, "Unknown or invalid MMU model\n");
return -1;
}
break;
case -2:
/* Access rights violation */
cs->exception_index = POWERPC_EXCP_DSI;
env->error_code = 0;
if (env->mmu_model == POWERPC_MMU_SOFT_4xx
|| env->mmu_model == POWERPC_MMU_SOFT_4xx_Z) {
env->spr[SPR_40x_DEAR] = address;
if (rw) {
env->spr[SPR_40x_ESR] |= 0x00800000;
}
} else if ((env->mmu_model == POWERPC_MMU_BOOKE) ||
(env->mmu_model == POWERPC_MMU_BOOKE206)) {
env->spr[SPR_BOOKE_DEAR] = address;
env->spr[SPR_BOOKE_ESR] = rw ? ESR_ST : 0;
} else {
env->spr[SPR_DAR] = address;
if (rw == 1) {
env->spr[SPR_DSISR] = 0x0A000000;
} else {
env->spr[SPR_DSISR] = 0x08000000;
}
}
break;
case -4:
/* Direct store exception */
switch (access_type) {
case ACCESS_FLOAT:
/* Floating point load/store */
cs->exception_index = POWERPC_EXCP_ALIGN;
env->error_code = POWERPC_EXCP_ALIGN_FP;
env->spr[SPR_DAR] = address;
break;
case ACCESS_RES:
/* lwarx, ldarx or stwcx. */
cs->exception_index = POWERPC_EXCP_DSI;
env->error_code = 0;
env->spr[SPR_DAR] = address;
if (rw == 1) {
env->spr[SPR_DSISR] = 0x06000000;
} else {
env->spr[SPR_DSISR] = 0x04000000;
}
break;
case ACCESS_EXT:
/* eciwx or ecowx */
cs->exception_index = POWERPC_EXCP_DSI;
env->error_code = 0;
env->spr[SPR_DAR] = address;
if (rw == 1) {
env->spr[SPR_DSISR] = 0x06100000;
} else {
env->spr[SPR_DSISR] = 0x04100000;
}
break;
default:
printf("DSI: invalid exception (%d)\n", ret);
cs->exception_index = POWERPC_EXCP_PROGRAM;
env->error_code =
POWERPC_EXCP_INVAL | POWERPC_EXCP_INVAL_INVAL;
env->spr[SPR_DAR] = address;
break;
}
break;
}
}
#if 0
printf("%s: set exception to %d %02x\n", __func__,
cs->exception, env->error_code);
#endif
ret = 1;
}
return ret;
}
/*****************************************************************************/
/* BATs management */
#if !defined(FLUSH_ALL_TLBS)
static inline void do_invalidate_BAT(CPUPPCState *env, target_ulong BATu,
target_ulong mask)
{
CPUState *cs = CPU(ppc_env_get_cpu(env));
target_ulong base, end, page;
base = BATu & ~0x0001FFFF;
end = base + mask + 0x00020000;
LOG_BATS("Flush BAT from " TARGET_FMT_lx " to " TARGET_FMT_lx " ("
TARGET_FMT_lx ")\n", base, end, mask);
for (page = base; page != end; page += TARGET_PAGE_SIZE) {
tlb_flush_page(cs, page);
}
LOG_BATS("Flush done\n");
}
#endif
static inline void dump_store_bat(CPUPPCState *env, char ID, int ul, int nr,
target_ulong value)
{
LOG_BATS("Set %cBAT%d%c to " TARGET_FMT_lx " (" TARGET_FMT_lx ")\n", ID,
nr, ul == 0 ? 'u' : 'l', value, env->nip);
}
void helper_store_ibatu(CPUPPCState *env, uint32_t nr, target_ulong value)
{
target_ulong mask;
dump_store_bat(env, 'I', 0, nr, value);
if (env->IBAT[0][nr] != value) {
mask = (value << 15) & 0x0FFE0000UL;
#if !defined(FLUSH_ALL_TLBS)
do_invalidate_BAT(env, env->IBAT[0][nr], mask);
#endif
/* When storing valid upper BAT, mask BEPI and BRPN
* and invalidate all TLBs covered by this BAT
*/
mask = (value << 15) & 0x0FFE0000UL;
env->IBAT[0][nr] = (value & 0x00001FFFUL) |
(value & ~0x0001FFFFUL & ~mask);
env->IBAT[1][nr] = (env->IBAT[1][nr] & 0x0000007B) |
(env->IBAT[1][nr] & ~0x0001FFFF & ~mask);
#if !defined(FLUSH_ALL_TLBS)
do_invalidate_BAT(env, env->IBAT[0][nr], mask);
#else
tlb_flush(env, 1);
#endif
}
}
void helper_store_ibatl(CPUPPCState *env, uint32_t nr, target_ulong value)
{
dump_store_bat(env, 'I', 1, nr, value);
env->IBAT[1][nr] = value;
}
void helper_store_dbatu(CPUPPCState *env, uint32_t nr, target_ulong value)
{
target_ulong mask;
dump_store_bat(env, 'D', 0, nr, value);
if (env->DBAT[0][nr] != value) {
/* When storing valid upper BAT, mask BEPI and BRPN
* and invalidate all TLBs covered by this BAT
*/
mask = (value << 15) & 0x0FFE0000UL;
#if !defined(FLUSH_ALL_TLBS)
do_invalidate_BAT(env, env->DBAT[0][nr], mask);
#endif
mask = (value << 15) & 0x0FFE0000UL;
env->DBAT[0][nr] = (value & 0x00001FFFUL) |
(value & ~0x0001FFFFUL & ~mask);
env->DBAT[1][nr] = (env->DBAT[1][nr] & 0x0000007B) |
(env->DBAT[1][nr] & ~0x0001FFFF & ~mask);
#if !defined(FLUSH_ALL_TLBS)
do_invalidate_BAT(env, env->DBAT[0][nr], mask);
#else
tlb_flush(env, 1);
#endif
}
}
void helper_store_dbatl(CPUPPCState *env, uint32_t nr, target_ulong value)
{
dump_store_bat(env, 'D', 1, nr, value);
env->DBAT[1][nr] = value;
}
void helper_store_601_batu(CPUPPCState *env, uint32_t nr, target_ulong value)
{
target_ulong mask;
#if defined(FLUSH_ALL_TLBS)
int do_inval;
#endif
dump_store_bat(env, 'I', 0, nr, value);
if (env->IBAT[0][nr] != value) {
#if defined(FLUSH_ALL_TLBS)
do_inval = 0;
#endif
mask = (env->IBAT[1][nr] << 17) & 0x0FFE0000UL;
if (env->IBAT[1][nr] & 0x40) {
/* Invalidate BAT only if it is valid */
#if !defined(FLUSH_ALL_TLBS)
do_invalidate_BAT(env, env->IBAT[0][nr], mask);
#else
do_inval = 1;
#endif
}
/* When storing valid upper BAT, mask BEPI and BRPN
* and invalidate all TLBs covered by this BAT
*/
env->IBAT[0][nr] = (value & 0x00001FFFUL) |
(value & ~0x0001FFFFUL & ~mask);
env->DBAT[0][nr] = env->IBAT[0][nr];
if (env->IBAT[1][nr] & 0x40) {
#if !defined(FLUSH_ALL_TLBS)
do_invalidate_BAT(env, env->IBAT[0][nr], mask);
#else
do_inval = 1;
#endif
}
#if defined(FLUSH_ALL_TLBS)
if (do_inval) {
tlb_flush(env, 1);
}
#endif
}
}
void helper_store_601_batl(CPUPPCState *env, uint32_t nr, target_ulong value)
{
#if !defined(FLUSH_ALL_TLBS)
target_ulong mask;
#else
int do_inval;
#endif
dump_store_bat(env, 'I', 1, nr, value);
if (env->IBAT[1][nr] != value) {
#if defined(FLUSH_ALL_TLBS)
do_inval = 0;
#endif
if (env->IBAT[1][nr] & 0x40) {
#if !defined(FLUSH_ALL_TLBS)
mask = (env->IBAT[1][nr] << 17) & 0x0FFE0000UL;
do_invalidate_BAT(env, env->IBAT[0][nr], mask);
#else
do_inval = 1;
#endif
}
if (value & 0x40) {
#if !defined(FLUSH_ALL_TLBS)
mask = (value << 17) & 0x0FFE0000UL;
do_invalidate_BAT(env, env->IBAT[0][nr], mask);
#else
do_inval = 1;
#endif
}
env->IBAT[1][nr] = value;
env->DBAT[1][nr] = value;
#if defined(FLUSH_ALL_TLBS)
if (do_inval) {
tlb_flush(env, 1);
}
#endif
}
}
/*****************************************************************************/
/* TLB management */
void ppc_tlb_invalidate_all(CPUPPCState *env)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
switch (env->mmu_model) {
case POWERPC_MMU_SOFT_6xx:
case POWERPC_MMU_SOFT_74xx:
ppc6xx_tlb_invalidate_all(env);
break;
case POWERPC_MMU_SOFT_4xx:
case POWERPC_MMU_SOFT_4xx_Z:
ppc4xx_tlb_invalidate_all(env);
break;
case POWERPC_MMU_REAL:
cpu_abort(CPU(cpu), "No TLB for PowerPC 4xx in real mode\n");
break;
case POWERPC_MMU_MPC8xx:
/* XXX: TODO */
cpu_abort(CPU(cpu), "MPC8xx MMU model is not implemented\n");
break;
case POWERPC_MMU_BOOKE:
tlb_flush(CPU(cpu), 1);
break;
case POWERPC_MMU_BOOKE206:
booke206_flush_tlb(env, -1, 0);
break;
case POWERPC_MMU_32B:
case POWERPC_MMU_601:
#if defined(TARGET_PPC64)
case POWERPC_MMU_64B:
case POWERPC_MMU_2_03:
case POWERPC_MMU_2_06:
case POWERPC_MMU_2_06a:
case POWERPC_MMU_2_07:
case POWERPC_MMU_2_07a:
#endif /* defined(TARGET_PPC64) */
tlb_flush(CPU(cpu), 1);
break;
default:
/* XXX: TODO */
cpu_abort(CPU(cpu), "Unknown MMU model\n");
break;
}
}
void ppc_tlb_invalidate_one(CPUPPCState *env, target_ulong addr)
{
#if !defined(FLUSH_ALL_TLBS)
PowerPCCPU *cpu = ppc_env_get_cpu(env);
CPUState *cs;
addr &= TARGET_PAGE_MASK;
switch (env->mmu_model) {
case POWERPC_MMU_SOFT_6xx:
case POWERPC_MMU_SOFT_74xx:
ppc6xx_tlb_invalidate_virt(env, addr, 0);
if (env->id_tlbs == 1) {
ppc6xx_tlb_invalidate_virt(env, addr, 1);
}
break;
case POWERPC_MMU_SOFT_4xx:
case POWERPC_MMU_SOFT_4xx_Z:
ppc4xx_tlb_invalidate_virt(env, addr, env->spr[SPR_40x_PID]);
break;
case POWERPC_MMU_REAL:
cpu_abort(CPU(cpu), "No TLB for PowerPC 4xx in real mode\n");
break;
case POWERPC_MMU_MPC8xx:
/* XXX: TODO */
cpu_abort(CPU(cpu), "MPC8xx MMU model is not implemented\n");
break;
case POWERPC_MMU_BOOKE:
/* XXX: TODO */
cpu_abort(CPU(cpu), "BookE MMU model is not implemented\n");
break;
case POWERPC_MMU_BOOKE206:
/* XXX: TODO */
cpu_abort(CPU(cpu), "BookE 2.06 MMU model is not implemented\n");
break;
case POWERPC_MMU_32B:
case POWERPC_MMU_601:
/* tlbie invalidate TLBs for all segments */
addr &= ~((target_ulong)-1ULL << 28);
cs = CPU(cpu);
/* XXX: this case should be optimized,
* giving a mask to tlb_flush_page
*/
tlb_flush_page(cs, addr | (0x0 << 28));
tlb_flush_page(cs, addr | (0x1 << 28));
tlb_flush_page(cs, addr | (0x2 << 28));
tlb_flush_page(cs, addr | (0x3 << 28));
tlb_flush_page(cs, addr | (0x4 << 28));
tlb_flush_page(cs, addr | (0x5 << 28));
tlb_flush_page(cs, addr | (0x6 << 28));
tlb_flush_page(cs, addr | (0x7 << 28));
tlb_flush_page(cs, addr | (0x8 << 28));
tlb_flush_page(cs, addr | (0x9 << 28));
tlb_flush_page(cs, addr | (0xA << 28));
tlb_flush_page(cs, addr | (0xB << 28));
tlb_flush_page(cs, addr | (0xC << 28));
tlb_flush_page(cs, addr | (0xD << 28));
tlb_flush_page(cs, addr | (0xE << 28));
tlb_flush_page(cs, addr | (0xF << 28));
break;
#if defined(TARGET_PPC64)
case POWERPC_MMU_64B:
case POWERPC_MMU_2_03:
case POWERPC_MMU_2_06:
case POWERPC_MMU_2_06a:
case POWERPC_MMU_2_07:
case POWERPC_MMU_2_07a:
/* tlbie invalidate TLBs for all segments */
/* XXX: given the fact that there are too many segments to invalidate,
* and we still don't have a tlb_flush_mask(env, n, mask) in QEMU,
* we just invalidate all TLBs
*/
tlb_flush(CPU(cpu), 1);
break;
#endif /* defined(TARGET_PPC64) */
default:
/* XXX: TODO */
cpu_abort(CPU(cpu), "Unknown MMU model\n");
break;
}
#else
ppc_tlb_invalidate_all(env);
#endif
}
/*****************************************************************************/
/* Special registers manipulation */
void ppc_store_sdr1(CPUPPCState *env, target_ulong value)
{
qemu_log_mask(CPU_LOG_MMU, "%s: " TARGET_FMT_lx "\n", __func__, value);
assert(!env->external_htab);
env->spr[SPR_SDR1] = value;
#if defined(TARGET_PPC64)
if (env->mmu_model & POWERPC_MMU_64) {
target_ulong htabsize = value & SDR_64_HTABSIZE;
if (htabsize > 28) {
fprintf(stderr, "Invalid HTABSIZE 0x" TARGET_FMT_lx
" stored in SDR1\n", htabsize);
htabsize = 28;
}
env->htab_mask = (1ULL << (htabsize + 18 - 7)) - 1;
env->htab_base = value & SDR_64_HTABORG;
} else
#endif /* defined(TARGET_PPC64) */
{
/* FIXME: Should check for valid HTABMASK values */
env->htab_mask = ((value & SDR_32_HTABMASK) << 16) | 0xFFFF;
env->htab_base = value & SDR_32_HTABORG;
}
}
/* Segment registers load and store */
target_ulong helper_load_sr(CPUPPCState *env, target_ulong sr_num)
{
#if defined(TARGET_PPC64)
if (env->mmu_model & POWERPC_MMU_64) {
/* XXX */
return 0;
}
#endif
return env->sr[sr_num];
}
void helper_store_sr(CPUPPCState *env, target_ulong srnum, target_ulong value)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
qemu_log_mask(CPU_LOG_MMU,
"%s: reg=%d " TARGET_FMT_lx " " TARGET_FMT_lx "\n", __func__,
(int)srnum, value, env->sr[srnum]);
#if defined(TARGET_PPC64)
if (env->mmu_model & POWERPC_MMU_64) {
uint64_t rb = 0, rs = 0;
/* ESID = srnum */
rb |= ((uint32_t)srnum & 0xf) << 28;
/* Set the valid bit */
rb |= SLB_ESID_V;
/* Index = ESID */
rb |= (uint32_t)srnum;
/* VSID = VSID */
rs |= (value & 0xfffffff) << 12;
/* flags = flags */
rs |= ((value >> 27) & 0xf) << 8;
ppc_store_slb(env, rb, rs);
} else
#endif
if (env->sr[srnum] != value) {
env->sr[srnum] = value;
/* Invalidating 256MB of virtual memory in 4kB pages is way longer than
flusing the whole TLB. */
#if !defined(FLUSH_ALL_TLBS) && 0
{
target_ulong page, end;
/* Invalidate 256 MB of virtual memory */
page = (16 << 20) * srnum;
end = page + (16 << 20);
for (; page != end; page += TARGET_PAGE_SIZE) {
tlb_flush_page(CPU(cpu), page);
}
}
#else
tlb_flush(CPU(cpu), 1);
#endif
}
}
/* TLB management */
void helper_tlbia(CPUPPCState *env)
{
ppc_tlb_invalidate_all(env);
}
void helper_tlbie(CPUPPCState *env, target_ulong addr)
{
ppc_tlb_invalidate_one(env, addr);
}
/* Software driven TLBs management */
/* PowerPC 602/603 software TLB load instructions helpers */
static void do_6xx_tlb(CPUPPCState *env, target_ulong new_EPN, int is_code)
{
target_ulong RPN, CMP, EPN;
int way;
RPN = env->spr[SPR_RPA];
if (is_code) {
CMP = env->spr[SPR_ICMP];
EPN = env->spr[SPR_IMISS];
} else {
CMP = env->spr[SPR_DCMP];
EPN = env->spr[SPR_DMISS];
}
way = (env->spr[SPR_SRR1] >> 17) & 1;
(void)EPN; /* avoid a compiler warning */
LOG_SWTLB("%s: EPN " TARGET_FMT_lx " " TARGET_FMT_lx " PTE0 " TARGET_FMT_lx
" PTE1 " TARGET_FMT_lx " way %d\n", __func__, new_EPN, EPN, CMP,
RPN, way);
/* Store this TLB */
ppc6xx_tlb_store(env, (uint32_t)(new_EPN & TARGET_PAGE_MASK),
way, is_code, CMP, RPN);
}
void helper_6xx_tlbd(CPUPPCState *env, target_ulong EPN)
{
do_6xx_tlb(env, EPN, 0);
}
void helper_6xx_tlbi(CPUPPCState *env, target_ulong EPN)
{
do_6xx_tlb(env, EPN, 1);
}
/* PowerPC 74xx software TLB load instructions helpers */
static void do_74xx_tlb(CPUPPCState *env, target_ulong new_EPN, int is_code)
{
target_ulong RPN, CMP, EPN;
int way;
RPN = env->spr[SPR_PTELO];
CMP = env->spr[SPR_PTEHI];
EPN = env->spr[SPR_TLBMISS] & ~0x3;
way = env->spr[SPR_TLBMISS] & 0x3;
(void)EPN; /* avoid a compiler warning */
LOG_SWTLB("%s: EPN " TARGET_FMT_lx " " TARGET_FMT_lx " PTE0 " TARGET_FMT_lx
" PTE1 " TARGET_FMT_lx " way %d\n", __func__, new_EPN, EPN, CMP,
RPN, way);
/* Store this TLB */
ppc6xx_tlb_store(env, (uint32_t)(new_EPN & TARGET_PAGE_MASK),
way, is_code, CMP, RPN);
}
void helper_74xx_tlbd(CPUPPCState *env, target_ulong EPN)
{
do_74xx_tlb(env, EPN, 0);
}
void helper_74xx_tlbi(CPUPPCState *env, target_ulong EPN)
{
do_74xx_tlb(env, EPN, 1);
}
/*****************************************************************************/
/* PowerPC 601 specific instructions (POWER bridge) */
target_ulong helper_rac(CPUPPCState *env, target_ulong addr)
{
mmu_ctx_t ctx;
int nb_BATs;
target_ulong ret = 0;
/* We don't have to generate many instances of this instruction,
* as rac is supervisor only.
*/
/* XXX: FIX THIS: Pretend we have no BAT */
nb_BATs = env->nb_BATs;
env->nb_BATs = 0;
if (get_physical_address(env, &ctx, addr, 0, ACCESS_INT) == 0) {
ret = ctx.raddr;
}
env->nb_BATs = nb_BATs;
return ret;
}
static inline target_ulong booke_tlb_to_page_size(int size)
{
return 1024 << (2 * size);
}
static inline int booke_page_size_to_tlb(target_ulong page_size)
{
int size;
switch (page_size) {
case 0x00000400UL:
size = 0x0;
break;
case 0x00001000UL:
size = 0x1;
break;
case 0x00004000UL:
size = 0x2;
break;
case 0x00010000UL:
size = 0x3;
break;
case 0x00040000UL:
size = 0x4;
break;
case 0x00100000UL:
size = 0x5;
break;
case 0x00400000UL:
size = 0x6;
break;
case 0x01000000UL:
size = 0x7;
break;
case 0x04000000UL:
size = 0x8;
break;
case 0x10000000UL:
size = 0x9;
break;
case 0x40000000UL:
size = 0xA;
break;
#if defined(TARGET_PPC64)
case 0x000100000000ULL:
size = 0xB;
break;
case 0x000400000000ULL:
size = 0xC;
break;
case 0x001000000000ULL:
size = 0xD;
break;
case 0x004000000000ULL:
size = 0xE;
break;
case 0x010000000000ULL:
size = 0xF;
break;
#endif
default:
size = -1;
break;
}
return size;
}
/* Helpers for 4xx TLB management */
#define PPC4XX_TLB_ENTRY_MASK 0x0000003f /* Mask for 64 TLB entries */
#define PPC4XX_TLBHI_V 0x00000040
#define PPC4XX_TLBHI_E 0x00000020
#define PPC4XX_TLBHI_SIZE_MIN 0
#define PPC4XX_TLBHI_SIZE_MAX 7
#define PPC4XX_TLBHI_SIZE_DEFAULT 1
#define PPC4XX_TLBHI_SIZE_SHIFT 7
#define PPC4XX_TLBHI_SIZE_MASK 0x00000007
#define PPC4XX_TLBLO_EX 0x00000200
#define PPC4XX_TLBLO_WR 0x00000100
#define PPC4XX_TLBLO_ATTR_MASK 0x000000FF
#define PPC4XX_TLBLO_RPN_MASK 0xFFFFFC00
target_ulong helper_4xx_tlbre_hi(CPUPPCState *env, target_ulong entry)
{
ppcemb_tlb_t *tlb;
target_ulong ret;
int size;
entry &= PPC4XX_TLB_ENTRY_MASK;
tlb = &env->tlb.tlbe[entry];
ret = tlb->EPN;
if (tlb->prot & PAGE_VALID) {
ret |= PPC4XX_TLBHI_V;
}
size = booke_page_size_to_tlb(tlb->size);
if (size < PPC4XX_TLBHI_SIZE_MIN || size > PPC4XX_TLBHI_SIZE_MAX) {
size = PPC4XX_TLBHI_SIZE_DEFAULT;
}
ret |= size << PPC4XX_TLBHI_SIZE_SHIFT;
env->spr[SPR_40x_PID] = tlb->PID;
return ret;
}
target_ulong helper_4xx_tlbre_lo(CPUPPCState *env, target_ulong entry)
{
ppcemb_tlb_t *tlb;
target_ulong ret;
entry &= PPC4XX_TLB_ENTRY_MASK;
tlb = &env->tlb.tlbe[entry];
ret = tlb->RPN;
if (tlb->prot & PAGE_EXEC) {
ret |= PPC4XX_TLBLO_EX;
}
if (tlb->prot & PAGE_WRITE) {
ret |= PPC4XX_TLBLO_WR;
}
return ret;
}
void helper_4xx_tlbwe_hi(CPUPPCState *env, target_ulong entry,
target_ulong val)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
CPUState *cs = CPU(cpu);
ppcemb_tlb_t *tlb;
target_ulong page, end;
LOG_SWTLB("%s entry %d val " TARGET_FMT_lx "\n", __func__, (int)entry,
val);
entry &= PPC4XX_TLB_ENTRY_MASK;
tlb = &env->tlb.tlbe[entry];
/* Invalidate previous TLB (if it's valid) */
if (tlb->prot & PAGE_VALID) {
end = tlb->EPN + tlb->size;
LOG_SWTLB("%s: invalidate old TLB %d start " TARGET_FMT_lx " end "
TARGET_FMT_lx "\n", __func__, (int)entry, tlb->EPN, end);
for (page = tlb->EPN; page < end; page += TARGET_PAGE_SIZE) {
tlb_flush_page(cs, page);
}
}
tlb->size = booke_tlb_to_page_size((val >> PPC4XX_TLBHI_SIZE_SHIFT)
& PPC4XX_TLBHI_SIZE_MASK);
/* We cannot handle TLB size < TARGET_PAGE_SIZE.
* If this ever occurs, one should use the ppcemb target instead
* of the ppc or ppc64 one
*/
if ((val & PPC4XX_TLBHI_V) && tlb->size < TARGET_PAGE_SIZE) {
cpu_abort(cs, "TLB size " TARGET_FMT_lu " < %u "
"are not supported (%d)\n",
tlb->size, TARGET_PAGE_SIZE, (int)((val >> 7) & 0x7));
}
tlb->EPN = val & ~(tlb->size - 1);
if (val & PPC4XX_TLBHI_V) {
tlb->prot |= PAGE_VALID;
if (val & PPC4XX_TLBHI_E) {
/* XXX: TO BE FIXED */
cpu_abort(cs,
"Little-endian TLB entries are not supported by now\n");
}
} else {
tlb->prot &= ~PAGE_VALID;
}
tlb->PID = env->spr[SPR_40x_PID]; /* PID */
LOG_SWTLB("%s: set up TLB %d RPN " TARGET_FMT_plx " EPN " TARGET_FMT_lx
" size " TARGET_FMT_lx " prot %c%c%c%c PID %d\n", __func__,
(int)entry, tlb->RPN, tlb->EPN, tlb->size,
tlb->prot & PAGE_READ ? 'r' : '-',
tlb->prot & PAGE_WRITE ? 'w' : '-',
tlb->prot & PAGE_EXEC ? 'x' : '-',
tlb->prot & PAGE_VALID ? 'v' : '-', (int)tlb->PID);
/* Invalidate new TLB (if valid) */
if (tlb->prot & PAGE_VALID) {
end = tlb->EPN + tlb->size;
LOG_SWTLB("%s: invalidate TLB %d start " TARGET_FMT_lx " end "
TARGET_FMT_lx "\n", __func__, (int)entry, tlb->EPN, end);
for (page = tlb->EPN; page < end; page += TARGET_PAGE_SIZE) {
tlb_flush_page(cs, page);
}
}
}
void helper_4xx_tlbwe_lo(CPUPPCState *env, target_ulong entry,
target_ulong val)
{
ppcemb_tlb_t *tlb;
LOG_SWTLB("%s entry %i val " TARGET_FMT_lx "\n", __func__, (int)entry,
val);
entry &= PPC4XX_TLB_ENTRY_MASK;
tlb = &env->tlb.tlbe[entry];
tlb->attr = val & PPC4XX_TLBLO_ATTR_MASK;
tlb->RPN = val & PPC4XX_TLBLO_RPN_MASK;
tlb->prot = PAGE_READ;
if (val & PPC4XX_TLBLO_EX) {
tlb->prot |= PAGE_EXEC;
}
if (val & PPC4XX_TLBLO_WR) {
tlb->prot |= PAGE_WRITE;
}
LOG_SWTLB("%s: set up TLB %d RPN " TARGET_FMT_plx " EPN " TARGET_FMT_lx
" size " TARGET_FMT_lx " prot %c%c%c%c PID %d\n", __func__,
(int)entry, tlb->RPN, tlb->EPN, tlb->size,
tlb->prot & PAGE_READ ? 'r' : '-',
tlb->prot & PAGE_WRITE ? 'w' : '-',
tlb->prot & PAGE_EXEC ? 'x' : '-',
tlb->prot & PAGE_VALID ? 'v' : '-', (int)tlb->PID);
}
target_ulong helper_4xx_tlbsx(CPUPPCState *env, target_ulong address)
{
return ppcemb_tlb_search(env, address, env->spr[SPR_40x_PID]);
}
/* PowerPC 440 TLB management */
void helper_440_tlbwe(CPUPPCState *env, uint32_t word, target_ulong entry,
target_ulong value)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
ppcemb_tlb_t *tlb;
target_ulong EPN, RPN, size;
int do_flush_tlbs;
LOG_SWTLB("%s word %d entry %d value " TARGET_FMT_lx "\n",
__func__, word, (int)entry, value);
do_flush_tlbs = 0;
entry &= 0x3F;
tlb = &env->tlb.tlbe[entry];
switch (word) {
default:
/* Just here to please gcc */
case 0:
EPN = value & 0xFFFFFC00;
if ((tlb->prot & PAGE_VALID) && EPN != tlb->EPN) {
do_flush_tlbs = 1;
}
tlb->EPN = EPN;
size = booke_tlb_to_page_size((value >> 4) & 0xF);
if ((tlb->prot & PAGE_VALID) && tlb->size < size) {
do_flush_tlbs = 1;
}
tlb->size = size;
tlb->attr &= ~0x1;
tlb->attr |= (value >> 8) & 1;
if (value & 0x200) {
tlb->prot |= PAGE_VALID;
} else {
if (tlb->prot & PAGE_VALID) {
tlb->prot &= ~PAGE_VALID;
do_flush_tlbs = 1;
}
}
tlb->PID = env->spr[SPR_440_MMUCR] & 0x000000FF;
if (do_flush_tlbs) {
tlb_flush(CPU(cpu), 1);
}
break;
case 1:
RPN = value & 0xFFFFFC0F;
if ((tlb->prot & PAGE_VALID) && tlb->RPN != RPN) {
tlb_flush(CPU(cpu), 1);
}
tlb->RPN = RPN;
break;
case 2:
tlb->attr = (tlb->attr & 0x1) | (value & 0x0000FF00);
tlb->prot = tlb->prot & PAGE_VALID;
if (value & 0x1) {
tlb->prot |= PAGE_READ << 4;
}
if (value & 0x2) {
tlb->prot |= PAGE_WRITE << 4;
}
if (value & 0x4) {
tlb->prot |= PAGE_EXEC << 4;
}
if (value & 0x8) {
tlb->prot |= PAGE_READ;
}
if (value & 0x10) {
tlb->prot |= PAGE_WRITE;
}
if (value & 0x20) {
tlb->prot |= PAGE_EXEC;
}
break;
}
}
target_ulong helper_440_tlbre(CPUPPCState *env, uint32_t word,
target_ulong entry)
{
ppcemb_tlb_t *tlb;
target_ulong ret;
int size;
entry &= 0x3F;
tlb = &env->tlb.tlbe[entry];
switch (word) {
default:
/* Just here to please gcc */
case 0:
ret = tlb->EPN;
size = booke_page_size_to_tlb(tlb->size);
if (size < 0 || size > 0xF) {
size = 1;
}
ret |= size << 4;
if (tlb->attr & 0x1) {
ret |= 0x100;
}
if (tlb->prot & PAGE_VALID) {
ret |= 0x200;
}
env->spr[SPR_440_MMUCR] &= ~0x000000FF;
env->spr[SPR_440_MMUCR] |= tlb->PID;
break;
case 1:
ret = tlb->RPN;
break;
case 2:
ret = tlb->attr & ~0x1;
if (tlb->prot & (PAGE_READ << 4)) {
ret |= 0x1;
}
if (tlb->prot & (PAGE_WRITE << 4)) {
ret |= 0x2;
}
if (tlb->prot & (PAGE_EXEC << 4)) {
ret |= 0x4;
}
if (tlb->prot & PAGE_READ) {
ret |= 0x8;
}
if (tlb->prot & PAGE_WRITE) {
ret |= 0x10;
}
if (tlb->prot & PAGE_EXEC) {
ret |= 0x20;
}
break;
}
return ret;
}
target_ulong helper_440_tlbsx(CPUPPCState *env, target_ulong address)
{
return ppcemb_tlb_search(env, address, env->spr[SPR_440_MMUCR] & 0xFF);
}
/* PowerPC BookE 2.06 TLB management */
static ppcmas_tlb_t *booke206_cur_tlb(CPUPPCState *env)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
uint32_t tlbncfg = 0;
int esel = (env->spr[SPR_BOOKE_MAS0] & MAS0_ESEL_MASK) >> MAS0_ESEL_SHIFT;
int ea = (env->spr[SPR_BOOKE_MAS2] & MAS2_EPN_MASK);
int tlb;
tlb = (env->spr[SPR_BOOKE_MAS0] & MAS0_TLBSEL_MASK) >> MAS0_TLBSEL_SHIFT;
tlbncfg = env->spr[SPR_BOOKE_TLB0CFG + tlb];
if ((tlbncfg & TLBnCFG_HES) && (env->spr[SPR_BOOKE_MAS0] & MAS0_HES)) {
cpu_abort(CPU(cpu), "we don't support HES yet\n");
}
return booke206_get_tlbm(env, tlb, ea, esel);
}
void helper_booke_setpid(CPUPPCState *env, uint32_t pidn, target_ulong pid)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
env->spr[pidn] = pid;
/* changing PIDs mean we're in a different address space now */
tlb_flush(CPU(cpu), 1);
}
void helper_booke206_tlbwe(CPUPPCState *env)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
uint32_t tlbncfg, tlbn;
ppcmas_tlb_t *tlb;
uint32_t size_tlb, size_ps;
target_ulong mask;
switch (env->spr[SPR_BOOKE_MAS0] & MAS0_WQ_MASK) {
case MAS0_WQ_ALWAYS:
/* good to go, write that entry */
break;
case MAS0_WQ_COND:
/* XXX check if reserved */
if (0) {
return;
}
break;
case MAS0_WQ_CLR_RSRV:
/* XXX clear entry */
return;
default:
/* no idea what to do */
return;
}
if (((env->spr[SPR_BOOKE_MAS0] & MAS0_ATSEL) == MAS0_ATSEL_LRAT) &&
!msr_gs) {
/* XXX we don't support direct LRAT setting yet */
fprintf(stderr, "cpu: don't support LRAT setting yet\n");
return;
}
tlbn = (env->spr[SPR_BOOKE_MAS0] & MAS0_TLBSEL_MASK) >> MAS0_TLBSEL_SHIFT;
tlbncfg = env->spr[SPR_BOOKE_TLB0CFG + tlbn];
tlb = booke206_cur_tlb(env);
if (!tlb) {
helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
POWERPC_EXCP_INVAL |
POWERPC_EXCP_INVAL_INVAL);
}
/* check that we support the targeted size */
size_tlb = (env->spr[SPR_BOOKE_MAS1] & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
size_ps = booke206_tlbnps(env, tlbn);
if ((env->spr[SPR_BOOKE_MAS1] & MAS1_VALID) && (tlbncfg & TLBnCFG_AVAIL) &&
!(size_ps & (1 << size_tlb))) {
helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
POWERPC_EXCP_INVAL |
POWERPC_EXCP_INVAL_INVAL);
}
if (msr_gs) {
cpu_abort(CPU(cpu), "missing HV implementation\n");
}
tlb->mas7_3 = ((uint64_t)env->spr[SPR_BOOKE_MAS7] << 32) |
env->spr[SPR_BOOKE_MAS3];
tlb->mas1 = env->spr[SPR_BOOKE_MAS1];
/* MAV 1.0 only */
if (!(tlbncfg & TLBnCFG_AVAIL)) {
/* force !AVAIL TLB entries to correct page size */
tlb->mas1 &= ~MAS1_TSIZE_MASK;
/* XXX can be configured in MMUCSR0 */
tlb->mas1 |= (tlbncfg & TLBnCFG_MINSIZE) >> 12;
}
/* Make a mask from TLB size to discard invalid bits in EPN field */
mask = ~(booke206_tlb_to_page_size(env, tlb) - 1);
/* Add a mask for page attributes */
mask |= MAS2_ACM | MAS2_VLE | MAS2_W | MAS2_I | MAS2_M | MAS2_G | MAS2_E;
if (!msr_cm) {
/* Executing a tlbwe instruction in 32-bit mode will set
* bits 0:31 of the TLB EPN field to zero.
*/
mask &= 0xffffffff;
}
tlb->mas2 = env->spr[SPR_BOOKE_MAS2] & mask;
if (!(tlbncfg & TLBnCFG_IPROT)) {
/* no IPROT supported by TLB */
tlb->mas1 &= ~MAS1_IPROT;
}
if (booke206_tlb_to_page_size(env, tlb) == TARGET_PAGE_SIZE) {
tlb_flush_page(CPU(cpu), tlb->mas2 & MAS2_EPN_MASK);
} else {
tlb_flush(CPU(cpu), 1);
}
}
static inline void booke206_tlb_to_mas(CPUPPCState *env, ppcmas_tlb_t *tlb)
{
int tlbn = booke206_tlbm_to_tlbn(env, tlb);
int way = booke206_tlbm_to_way(env, tlb);
env->spr[SPR_BOOKE_MAS0] = tlbn << MAS0_TLBSEL_SHIFT;
env->spr[SPR_BOOKE_MAS0] |= way << MAS0_ESEL_SHIFT;
env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_NV_SHIFT;
env->spr[SPR_BOOKE_MAS1] = tlb->mas1;
env->spr[SPR_BOOKE_MAS2] = tlb->mas2;
env->spr[SPR_BOOKE_MAS3] = tlb->mas7_3;
env->spr[SPR_BOOKE_MAS7] = tlb->mas7_3 >> 32;
}
void helper_booke206_tlbre(CPUPPCState *env)
{
ppcmas_tlb_t *tlb = NULL;
tlb = booke206_cur_tlb(env);
if (!tlb) {
env->spr[SPR_BOOKE_MAS1] = 0;
} else {
booke206_tlb_to_mas(env, tlb);
}
}
void helper_booke206_tlbsx(CPUPPCState *env, target_ulong address)
{
ppcmas_tlb_t *tlb = NULL;
int i, j;
hwaddr raddr;
uint32_t spid, sas;
spid = (env->spr[SPR_BOOKE_MAS6] & MAS6_SPID_MASK) >> MAS6_SPID_SHIFT;
sas = env->spr[SPR_BOOKE_MAS6] & MAS6_SAS;
for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
int ways = booke206_tlb_ways(env, i);
for (j = 0; j < ways; j++) {
tlb = booke206_get_tlbm(env, i, address, j);
if (!tlb) {
continue;
}
if (ppcmas_tlb_check(env, tlb, &raddr, address, spid)) {
continue;
}
if (sas != ((tlb->mas1 & MAS1_TS) >> MAS1_TS_SHIFT)) {
continue;
}
booke206_tlb_to_mas(env, tlb);
return;
}
}
/* no entry found, fill with defaults */
env->spr[SPR_BOOKE_MAS0] = env->spr[SPR_BOOKE_MAS4] & MAS4_TLBSELD_MASK;
env->spr[SPR_BOOKE_MAS1] = env->spr[SPR_BOOKE_MAS4] & MAS4_TSIZED_MASK;
env->spr[SPR_BOOKE_MAS2] = env->spr[SPR_BOOKE_MAS4] & MAS4_WIMGED_MASK;
env->spr[SPR_BOOKE_MAS3] = 0;
env->spr[SPR_BOOKE_MAS7] = 0;
if (env->spr[SPR_BOOKE_MAS6] & MAS6_SAS) {
env->spr[SPR_BOOKE_MAS1] |= MAS1_TS;
}
env->spr[SPR_BOOKE_MAS1] |= (env->spr[SPR_BOOKE_MAS6] >> 16)
<< MAS1_TID_SHIFT;
/* next victim logic */
env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_ESEL_SHIFT;
env->last_way++;
env->last_way &= booke206_tlb_ways(env, 0) - 1;
env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_NV_SHIFT;
}
static inline void booke206_invalidate_ea_tlb(CPUPPCState *env, int tlbn,
uint32_t ea)
{
int i;
int ways = booke206_tlb_ways(env, tlbn);
target_ulong mask;
for (i = 0; i < ways; i++) {
ppcmas_tlb_t *tlb = booke206_get_tlbm(env, tlbn, ea, i);
if (!tlb) {
continue;
}
mask = ~(booke206_tlb_to_page_size(env, tlb) - 1);
if (((tlb->mas2 & MAS2_EPN_MASK) == (ea & mask)) &&
!(tlb->mas1 & MAS1_IPROT)) {
tlb->mas1 &= ~MAS1_VALID;
}
}
}
void helper_booke206_tlbivax(CPUPPCState *env, target_ulong address)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
if (address & 0x4) {
/* flush all entries */
if (address & 0x8) {
/* flush all of TLB1 */
booke206_flush_tlb(env, BOOKE206_FLUSH_TLB1, 1);
} else {
/* flush all of TLB0 */
booke206_flush_tlb(env, BOOKE206_FLUSH_TLB0, 0);
}
return;
}
if (address & 0x8) {
/* flush TLB1 entries */
booke206_invalidate_ea_tlb(env, 1, address);
tlb_flush(CPU(cpu), 1);
} else {
/* flush TLB0 entries */
booke206_invalidate_ea_tlb(env, 0, address);
tlb_flush_page(CPU(cpu), address & MAS2_EPN_MASK);
}
}
void helper_booke206_tlbilx0(CPUPPCState *env, target_ulong address)
{
/* XXX missing LPID handling */
booke206_flush_tlb(env, -1, 1);
}
void helper_booke206_tlbilx1(CPUPPCState *env, target_ulong address)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
int i, j;
int tid = (env->spr[SPR_BOOKE_MAS6] & MAS6_SPID);
ppcmas_tlb_t *tlb = env->tlb.tlbm;
int tlb_size;
/* XXX missing LPID handling */
for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
tlb_size = booke206_tlb_size(env, i);
for (j = 0; j < tlb_size; j++) {
if (!(tlb[j].mas1 & MAS1_IPROT) &&
((tlb[j].mas1 & MAS1_TID_MASK) == tid)) {
tlb[j].mas1 &= ~MAS1_VALID;
}
}
tlb += booke206_tlb_size(env, i);
}
tlb_flush(CPU(cpu), 1);
}
void helper_booke206_tlbilx3(CPUPPCState *env, target_ulong address)
{
PowerPCCPU *cpu = ppc_env_get_cpu(env);
int i, j;
ppcmas_tlb_t *tlb;
int tid = (env->spr[SPR_BOOKE_MAS6] & MAS6_SPID);
int pid = tid >> MAS6_SPID_SHIFT;
int sgs = env->spr[SPR_BOOKE_MAS5] & MAS5_SGS;
int ind = (env->spr[SPR_BOOKE_MAS6] & MAS6_SIND) ? MAS1_IND : 0;
/* XXX check for unsupported isize and raise an invalid opcode then */
int size = env->spr[SPR_BOOKE_MAS6] & MAS6_ISIZE_MASK;
/* XXX implement MAV2 handling */
bool mav2 = false;
/* XXX missing LPID handling */
/* flush by pid and ea */
for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
int ways = booke206_tlb_ways(env, i);
for (j = 0; j < ways; j++) {
tlb = booke206_get_tlbm(env, i, address, j);
if (!tlb) {
continue;
}
if ((ppcmas_tlb_check(env, tlb, NULL, address, pid) != 0) ||
(tlb->mas1 & MAS1_IPROT) ||
((tlb->mas1 & MAS1_IND) != ind) ||
((tlb->mas8 & MAS8_TGS) != sgs)) {
continue;
}
if (mav2 && ((tlb->mas1 & MAS1_TSIZE_MASK) != size)) {
/* XXX only check when MMUCFG[TWC] || TLBnCFG[HES] */
continue;
}
/* XXX e500mc doesn't match SAS, but other cores might */
tlb->mas1 &= ~MAS1_VALID;
}
}
tlb_flush(CPU(cpu), 1);
}
void helper_booke206_tlbflush(CPUPPCState *env, target_ulong type)
{
int flags = 0;
if (type & 2) {
flags |= BOOKE206_FLUSH_TLB1;
}
if (type & 4) {
flags |= BOOKE206_FLUSH_TLB0;
}
booke206_flush_tlb(env, flags, 1);
}
/*****************************************************************************/
/* try to fill the TLB and return an exception if error. If retaddr is
NULL, it means that the function was called in C code (i.e. not
from generated code or from helper.c) */
/* XXX: fix it to restore all registers */
void tlb_fill(CPUState *cs, target_ulong addr, int is_write, int mmu_idx,
uintptr_t retaddr)
{
PowerPCCPU *cpu = POWERPC_CPU(cs);
PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cs);
CPUPPCState *env = &cpu->env;
int ret;
if (pcc->handle_mmu_fault) {
ret = pcc->handle_mmu_fault(cpu, addr, is_write, mmu_idx);
} else {
ret = cpu_ppc_handle_mmu_fault(env, addr, is_write, mmu_idx);
}
if (unlikely(ret != 0)) {
if (likely(retaddr)) {
/* now we have a real cpu fault */
cpu_restore_state(cs, retaddr);
}
helper_raise_exception_err(env, cs->exception_index, env->error_code);
}
}
|
rla/old-code
|
2011/infdot-serializer/src/main/java/com/infdot/serialize/binary/serializer/ArraySerializer.java
|
package com.infdot.serialize.binary.serializer;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* {@link Serializer} implementation for arrays.
*
* @author <NAME>
*
* @param <T> type of array element.
*/
public class ArraySerializer<T> extends Serializer<T[]> {
private Serializer<T> elementSerializer;
public ArraySerializer(Serializer<T> elementSerializer) {
this.elementSerializer = elementSerializer;
}
@Override
public void write(T[] instance, DataOutput out) throws IOException {
out.writeInt(instance.length);
for (T o : instance) {
elementSerializer.write(o, out);
}
}
@Override
public T[] read(DataInput in) throws IOException {
int length = in.readInt();
@SuppressWarnings("unchecked")
T[] array = (T[]) new Object[length];
for (int i = 0; i < length; i++) {
array[i] = elementSerializer.read(in);
}
return array;
}
/**
* Helper method for cleaner API usage.
*/
public static <T> ArraySerializer<T> of(Serializer<T> elementSerializer) {
return new ArraySerializer<T>(elementSerializer);
}
}
|
SaadMeftah/c-example-code
|
infinite_buffer.c
|
/*******************************************************************************
*
* Program: Infinite buffer
*
* Description: An example of an "infinite input buffer" in C.
*
* YouTube Lesson: https://www.youtube.com/watch?v=qwM_c3gF2lw
*
* Author: <NAME> @ https://portfoliocourses.com
*
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define BUFFER_SIZE 5
int main(void)
{
// A traditional input buffer with a fixed length.
// But what if we don't know the size of the input in advance? We could
// either make a very large buffer to accommodate large inputs, or we could
// use dynamic memory allocation and realloc to increase the size of our
// buffer (see below).
/*
int buffer[BUFFER_SIZE];
for (int i = 0; i < BUFFER_SIZE; i++)
{
printf("Enter: ");
scanf("%d", &buffer[i]);
}
// compute the average, print out the data in the buffer
int total = 0;
for (int i = 0; i < BUFFER_SIZE; i++)
{
printf("buffer[%d]=%d\n", i, buffer[i]);
total += buffer[i];
}
printf("Average: %d\n", total / BUFFER_SIZE);
*/
// Infinite buffer will grow as required to store an unknown amount of input!
// Of course the buffer is not truly "infinite" as eventually our computer
// will run out of memory, but we'll call it infinite because it's more fun.
// start with a small buffer size of 2 and allocate space for it on the heap
int size = 2;
int *buffer = malloc(sizeof(int) * size);
// accept input indefinitely from the user (i.e. input of unknown length)
int input = 0;
int num_data = 0;
while (true)
{
// if the number of data inputs equals the size of the buffer, use realloc
// to increase the size of the buffer (double it each time)
if (num_data == size)
{
size *= 2;
buffer = realloc(buffer, sizeof(int) * size);
printf("Buffer size: %d\n", size);
}
// ask the user for input, store it in the buffer or break if time to quit
printf("Enter (-1 to quit): ");
scanf("%d", &input);
if (input == -1) break;
else buffer[num_data] = input;
// num_data keeps track of how much actual data is in the buffer
num_data++;
}
// compute the average, output the data in the buffer
int total = 0;
for (int i = 0; i < num_data; i++)
{
printf("buffer[%d]=%d\n", i, buffer[i]);
total += buffer[i];
}
printf("Average: %d\n", total / num_data);
// notice how the buffer size increases depending on how many numbers we
// input, with num_data keeping track of the actual amount of data in the
// buffer
printf("Num data: %d\n", num_data);
printf("Buffer size: %d\n", size);
return 0;
}
|
Brightspace/d2l-outcomes-overall-achievement
|
lang/es.js
|
<reponame>Brightspace/d2l-outcomes-overall-achievement
export default {
"anonymousUser": "Usuario anónimo",
"ascending": "Ascendente",
"bigTrendAttemptsScreenReaderString": "{numAttempts, plural, =1 {Intento {attemptNames}} other {Intentos {attemptNames} y {lastAttemptName}}}",
"cancelBtn": "Cancelar",
"close": "Cerrar",
"commaSeparator": ",",
"descending": "Descendente",
"evidence": "Evidencia",
"firstName": "Nombre",
"firstUseAlertSettingPageMessage": "Vea los detalles del método o cambie el método de cálculo en Configuración",
"firstUseAlertToastMessage": "La vista de maestría se calcula automáticamente con el método \"{calculationMethod}\"",
"firstUseAlertToastMessageNone": "La vista de maestría no se calcula automáticamente",
"goToNextPage": "Ir a la página siguiente de la tabla.",
"goToPreviousPage": "Ir a la página anterior de la tabla.",
"goToUserAchievementSummaryPage": "Presione Espacio o Intro para abrir la página de resumen de logros de {name}.",
"headingDate": "Fecha",
"headingEvidence": "Nombre de la evidencia",
"headingLoa": "Nivel de logro",
"headingTotalAssessments": "Evaluaciones totales: {num}",
"indexedAttempt": "Intento {num}",
"labelOverallAchievement": "Logro general",
"lastName": "Apellido",
"learnerHasNoData": "{username} no tiene datos de logros generales.",
"learnerSortButtonDescription": "Seleccione para ordenar las filas de la tabla por usuario {newSortKey} {newSortDirection}. El orden de clasificación actual es por {currentSortKey} {currentSortDirection}.",
"levelNamePercentLabel": "{name}: {percentage}.",
"loadingOverallAchievement": "Cargando logro general.",
"manualOverride": "anulación manual",
"masteryViewTableDescription": "Tabla Vista de maestría: Esta tabla muestra los logros generales de todos los resultados del curso para cada estudiante. Los resultados con actividades alineadas se muestran como encabezados de columna con estadísticas de desglose por clase.",
"masteryViewTableEmptyError": "Los logros generales de los resultados no se pueden cargar. Actualice la página para volver a intentarlo o comuníquese con el administrador si el error persiste.",
"masteryViewUserOutcomeScreenReaderText": "{assessmentInfo}. Presione Espacio o Intro para abrir la página de evaluación.",
"miniTrendScreenReaderText": "Se evaluó {numAssessed} {numAssessed, plural, =1 {time} other {times}}: {levelNames}",
"name": "Nombre",
"newPageSelectLiveText": "Página {pageNum} de {totalPages} seleccionada.",
"newPageSizeLiveText": "Se muestran {pageSize} filas por página.",
"noAlignedOutcomes": "Para utilizar la Vista de maestría, comience alineando {outcome, select, competencies {competencias} expectations {expectativas} objectives {objetivos} outcomes {resultados} standards {estándares} other {estándares}} a las actividades del curso en la página de edición de la actividad.",
"noEnrolledLearners": "No hay estudiantes inscritos en el curso.",
"noScaleInstructor": "Con el fin de ver el progreso del estudiante para lograr este {outcome, select, competencies {competencia} expectations {expectativas} objectives {objetivos} outcomes {resultados} standards {estándares} other {estándares}}, cree y seleccione una escala de logros.",
"noScaleStudent": "No se ha establecido ninguna escala para medir el logro de {outcome, select, competencies {competencias} expectations {expectativas} objectives {objetivos} outcomes {resultados} standards {estándares} other {estándares}}.",
"notAssessed": "Sin evaluación",
"notEvaluated": "No evaluado",
"notPublished": "No publicado",
"outcomeInfo": "{name}. {description}",
"outOfDate": "Sin actualización",
"page": "Página:",
"pageSelectOptionText": "{currentPage} de {pageCount}",
"pageSizeSelectOptionText": "{pageSize} por página",
"percentLabel": "{percentage}%",
"periodSeparator": ".",
"published": "Publicada",
"releaseAllBtn": "Publicar todo",
"releaseAllTxt": "¿Publicar los logros generales de todos los estudiantes en el curso?",
"retractAllBtn": "Retirar todo",
"retractAllTxt": "¿Retirar los logros generales de todos los estudiantes en el curso?",
"searchResults": "{numResults} Buscar {numResults, plural, =1 {Resultado} other {Resultados}}",
"searchUsersLabel": "Buscar usuarios",
"searchUsersPlaceholder": "Buscar por usuarios…",
"selectLearnersPerPage": "Seleccione cuántas filas desea mostrar en cada página de la tabla.",
"selectTablePage": "Seleccione una página específica en la tabla.",
"toastReleased": "Logros generales publicados de todos los estudiantes",
"toastRetracted": "Logros generales retirados de todos los estudiantes",
"tooltipUserOutcomeAssessments": "Se evalúan {numAssessed} de {numTotal} actividades",
"trend": "Tendencia",
"untitled": "Sin título",
"viewCourseIntentList": "Ver la lista de metas en la herramienta {outcome, select, competencies {Competencias} expectations {Expectativas} objectives {Objetivos} outcomes {Resultados} standards {Estándares} other {Estándares}}"
};
|
RocMarshal/fevernova
|
src/main/java/com/github/fevernova/task/rdb/JobParser.java
|
package com.github.fevernova.task.rdb;
import com.alibaba.fastjson.JSON;
import com.github.fevernova.framework.common.context.GlobalContext;
import com.github.fevernova.framework.common.context.TaskContext;
import com.github.fevernova.framework.common.data.Data;
import com.github.fevernova.framework.component.channel.ChannelProxy;
import com.github.fevernova.framework.component.parser.AbstractParser;
import com.github.fevernova.task.rdb.data.ListData;
import lombok.extern.slf4j.Slf4j;
@Slf4j(topic = "fevernova-data")
public class JobParser extends AbstractParser<Long, ListData> {
public JobParser(GlobalContext globalContext, TaskContext taskContext, int index, int inputsNum, ChannelProxy channelProxy) {
super(globalContext, taskContext, index, inputsNum, channelProxy);
}
@Override protected void handleEvent(Data event) {
ListData oldData = (ListData) event;
if (log.isDebugEnabled()) {
log.debug(JSON.toJSONString(oldData));
}
ListData newData = feedOne(oldData.getKey() == null ? 0L : oldData.getKey());
newData.getValues().addAll(oldData.getValues());
push();
}
}
|
Waginator/mycv
|
src/main/java/com/wagner/mycv/web/dto/request/TechnologySkillRequestDto.java
|
package com.wagner.mycv.web.dto.request;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Getter
@Setter
@Builder
public class TechnologySkillRequestDto {
@NotBlank
private String category;
@NotNull
private List<String> skillNames;
public Map<String, Object> toMap() {
Map<String, Object> map = new HashMap<>();
map.put("category", category);
map.put("skillNames", skillNames);
return map;
}
}
|
ShawnZhong/SplitFS
|
kernel/linux-4.13/include/trace/events/alarmtimer.h
|
#undef TRACE_SYSTEM
#define TRACE_SYSTEM alarmtimer
#if !defined(_TRACE_ALARMTIMER_H) || defined(TRACE_HEADER_MULTI_READ)
#define _TRACE_ALARMTIMER_H
#include <linux/alarmtimer.h>
#include <linux/rtc.h>
#include <linux/tracepoint.h>
TRACE_DEFINE_ENUM(ALARM_REALTIME);
TRACE_DEFINE_ENUM(ALARM_BOOTTIME);
TRACE_DEFINE_ENUM(ALARM_REALTIME_FREEZER);
TRACE_DEFINE_ENUM(ALARM_BOOTTIME_FREEZER);
#define show_alarm_type(type) __print_flags(type, " | ", \
{ 1 << ALARM_REALTIME, "REALTIME" }, \
{ 1 << ALARM_BOOTTIME, "BOOTTIME" }, \
{ 1 << ALARM_REALTIME_FREEZER, "REALTIME Freezer" }, \
{ 1 << ALARM_BOOTTIME_FREEZER, "BOOTTIME Freezer" })
TRACE_EVENT(alarmtimer_suspend,
TP_PROTO(ktime_t expires, int flag),
TP_ARGS(expires, flag),
TP_STRUCT__entry(
__field(s64, expires)
__field(unsigned char, alarm_type)
),
TP_fast_assign(
__entry->expires = expires;
__entry->alarm_type = flag;
),
TP_printk("alarmtimer type:%s expires:%llu",
show_alarm_type((1 << __entry->alarm_type)),
__entry->expires
)
);
DECLARE_EVENT_CLASS(alarm_class,
TP_PROTO(struct alarm *alarm, ktime_t now),
TP_ARGS(alarm, now),
TP_STRUCT__entry(
__field(void *, alarm)
__field(unsigned char, alarm_type)
__field(s64, expires)
__field(s64, now)
),
TP_fast_assign(
__entry->alarm = alarm;
__entry->alarm_type = alarm->type;
__entry->expires = alarm->node.expires;
__entry->now = now;
),
TP_printk("alarmtimer:%p type:%s expires:%llu now:%llu",
__entry->alarm,
show_alarm_type((1 << __entry->alarm_type)),
__entry->expires,
__entry->now
)
);
DEFINE_EVENT(alarm_class, alarmtimer_fired,
TP_PROTO(struct alarm *alarm, ktime_t now),
TP_ARGS(alarm, now)
);
DEFINE_EVENT(alarm_class, alarmtimer_start,
TP_PROTO(struct alarm *alarm, ktime_t now),
TP_ARGS(alarm, now)
);
DEFINE_EVENT(alarm_class, alarmtimer_cancel,
TP_PROTO(struct alarm *alarm, ktime_t now),
TP_ARGS(alarm, now)
);
#endif /* _TRACE_ALARMTIMER_H */
/* This part must be outside protection */
#include <trace/define_trace.h>
|
erhard-lab/gedi
|
GediCenteredDiskIntervalTreeStorage/src/executables/BedIndex.java
|
<gh_stars>10-100
/**
*
* Copyright 2017 <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 executables;
import gedi.app.Config;
import gedi.centeredDiskIntervalTree.CenteredDiskIntervalTree;
import gedi.centeredDiskIntervalTree.CenteredDiskIntervalTreeStorage;
import gedi.core.data.annotation.ScoreNameAnnotation;
import gedi.core.data.annotation.Transcript;
import gedi.core.data.reads.AlignedReadsData;
import gedi.core.data.reads.ContrastMapping;
import gedi.core.data.reads.DefaultAlignedReadsData;
import gedi.core.processing.old.CombinedGenomicRegionProcessor;
import gedi.core.processing.old.FillStorageProcessor;
import gedi.core.processing.old.GenomicRegionProcessor;
import gedi.core.processing.old.OverlapMode;
import gedi.core.processing.old.sources.GeneProcessorSource;
import gedi.core.reference.ReferenceSequenceConversion;
import gedi.core.region.GenomicRegionStorage;
import gedi.core.region.MutableReferenceGenomicRegion;
import gedi.core.region.intervalTree.MemoryIntervalTreeStorage;
import gedi.core.sequence.FastaIndexSequenceProvider;
import gedi.core.sequence.SequenceProvider;
import gedi.util.ArrayUtils;
import gedi.util.FileUtils;
import gedi.util.ParseUtils;
import gedi.util.StringUtils;
import gedi.util.datastructure.collections.longcollections.LongArrayList;
import gedi.util.io.text.HeaderLine;
import gedi.util.io.text.LineIterator;
import gedi.util.io.text.LineOrientedFile;
import gedi.util.io.text.fasta.index.FastaIndexFile;
import gedi.util.io.text.tsv.formats.BedEntry;
import gedi.util.io.text.tsv.formats.GtfFileReader;
import gedi.util.mutable.MutableLong;
import gedi.util.mutable.MutableTriple;
import gedi.util.mutable.MutableTuple;
import gedi.util.nashorn.JSFunction;
import gedi.util.userInteraction.progress.ConsoleProgress;
import gedi.util.userInteraction.progress.Progress;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.function.BiConsumer;
import java.util.function.Function;
public class BedIndex {
public static void main(String[] args) {
try {
start(args);
} catch (UsageException e) {
usage("An error occurred: "+e.getMessage());
if (ArrayUtils.find(args, "-D")>=0)
e.printStackTrace();
} catch (Exception e) {
System.err.println("An error occurred: "+e.getMessage());
if (ArrayUtils.find(args, "-D")>=0)
e.printStackTrace();
}
}
private static class UsageException extends Exception {
public UsageException(String msg) {
super(msg);
}
}
private static String checkParam(String[] args, int index) throws UsageException {
if (index>=args.length || args[index].startsWith("-")) throw new UsageException("Missing argument for "+args[index-1]);
return args[index];
}
private static int checkIntParam(String[] args, int index) throws UsageException {
String re = checkParam(args, index);
if (!StringUtils.isInt(re)) throw new UsageException("Must be an integer: "+args[index-1]);
return Integer.parseInt(args[index]);
}
private static double checkDoubleParam(String[] args, int index) throws UsageException {
String re = checkParam(args, index);
if (!StringUtils.isNumeric(re)) throw new UsageException("Must be a double: "+args[index-1]);
return Double.parseDouble(args[index]);
}
public static void start(String[] args) throws Exception {
boolean progress = false;
String input = null;
boolean silent = false;
int i;
for (i=0; i<args.length; i++) {
if (args[i].equals("-h")) {
usage(null);
return;
}
else if (args[i].equals("-p")) {
progress=true;
}
else if (args[i].equals("-S")) {
silent=true;
}
else if (args[i].equals("-D")){}
else if (!args[i].startsWith("-"))
break;
else throw new UsageException("Unknown parameter: "+args[i]);
}
if (i==args.length-1)
input = args[i++];
if (i!=args.length) throw new UsageException("Unknown parameter "+args[i]);
if (input==null) throw new UsageException("No input file!");
LineIterator lit = new LineOrientedFile(input).lineIterator();
MutableReferenceGenomicRegion<BedEntry> rgr = new MutableReferenceGenomicRegion<BedEntry>();
MutableReferenceGenomicRegion<ScoreNameAnnotation> rgr2 = new MutableReferenceGenomicRegion<ScoreNameAnnotation>();
MemoryIntervalTreeStorage<ScoreNameAnnotation> tmp = new MemoryIntervalTreeStorage<ScoreNameAnnotation>(ScoreNameAnnotation.class);
Progress pro = progress?new ConsoleProgress(System.err):null;
if (progress) pro.init();
while (lit.hasNext()) {
String[] f = StringUtils.split(lit.next(), '\t');
BedEntry.parseValues(f).getReferenceGenomicRegion(rgr);
ScoreNameAnnotation data = new ScoreNameAnnotation(rgr.getData().getName(), rgr.getData().getDoubleScore());
if (rgr.getReference()==null) {
if (!silent)
System.out.println("Cannot parse location for "+StringUtils.concat("\t", f));
}
else {
tmp.add(rgr.getReference(), rgr.getRegion(), data, (a,b)->{
System.err.println("Multiregions: \n"+a+"\n"+b);
return b;
});
}
if (progress) pro.incrementProgress();
}
new CenteredDiskIntervalTreeStorage<ScoreNameAnnotation>(StringUtils.removeFooter(input, ".bed")+".cit", ScoreNameAnnotation.class).fill(tmp);
if (progress) pro.finish();
}
private static void usage(String message) {
System.err.println();
if (message!=null){
System.err.println(message);
System.err.println();
}
System.err.println("BedIndex <Options> <input>");
System.err.println();
System.err.println("Options:");
System.err.println(" -S\t\t\tSilent mode");
System.err.println(" -p\t\t\tShow progress");
System.err.println(" -h\t\t\tShow this message");
System.err.println(" -D\t\t\tOutput debugging information");
System.err.println();
}
}
|
LigthWarrior/frontend-course-2020
|
homeworks/nataliia.koval_NataliyaKoval/2-DOM/chat.js
|
const input = document.querySelector('[data-text]');
const button = document.querySelector('[data-send-message]');
const dialogWindow = document.querySelector('.dialog-window');
function createMessage(event) {
event.preventDefault();
if (input.value.trim().length > 0) {
const message = document.createElement('p');
message.innerText = input.value;
message.classList.add('new-message');
dialogWindow.appendChild(message);
input.value = '';
}
}
button.addEventListener('click', createMessage);
const typing = document.querySelector('.typing');
function sayTyping() {
typing.innerText = 'Typing...';
}
input.addEventListener('keyup', sayTyping);
const debounce = (func, wait) => {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
const stopSayTyping = debounce(() => {
typing.innerText = '';
}, 1000);
input.addEventListener('keyup', stopSayTyping);
|
xu753x/free5GRAN
|
lib/asn1c/nr_rrc/PDCCH-ConfigSIB1.c
|
/*
* Copyright 2020-2021 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "NR-RRC-Definitions"
* `asn1c -gen-PER -fcompound-names -findirect-choice -no-gen-example`
*/
#include "PDCCH-ConfigSIB1.h"
asn_TYPE_member_t asn_MBR_PDCCH_ConfigSIB1_1[] = {
{ ATF_NOFLAGS, 0, offsetof(struct PDCCH_ConfigSIB1, controlResourceSetZero),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_ControlResourceSetZero,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"controlResourceSetZero"
},
{ ATF_NOFLAGS, 0, offsetof(struct PDCCH_ConfigSIB1, searchSpaceZero),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_SearchSpaceZero,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"searchSpaceZero"
},
};
static const ber_tlv_tag_t asn_DEF_PDCCH_ConfigSIB1_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static const asn_TYPE_tag2member_t asn_MAP_PDCCH_ConfigSIB1_tag2el_1[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* controlResourceSetZero */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* searchSpaceZero */
};
asn_SEQUENCE_specifics_t asn_SPC_PDCCH_ConfigSIB1_specs_1 = {
sizeof(struct PDCCH_ConfigSIB1),
offsetof(struct PDCCH_ConfigSIB1, _asn_ctx),
asn_MAP_PDCCH_ConfigSIB1_tag2el_1,
2, /* Count of tags in the map */
0, 0, 0, /* Optional elements (not needed) */
-1, /* First extension addition */
};
asn_TYPE_descriptor_t asn_DEF_PDCCH_ConfigSIB1 = {
"PDCCH-ConfigSIB1",
"PDCCH-ConfigSIB1",
&asn_OP_SEQUENCE,
asn_DEF_PDCCH_ConfigSIB1_tags_1,
sizeof(asn_DEF_PDCCH_ConfigSIB1_tags_1)
/sizeof(asn_DEF_PDCCH_ConfigSIB1_tags_1[0]), /* 1 */
asn_DEF_PDCCH_ConfigSIB1_tags_1, /* Same as above */
sizeof(asn_DEF_PDCCH_ConfigSIB1_tags_1)
/sizeof(asn_DEF_PDCCH_ConfigSIB1_tags_1[0]), /* 1 */
{ 0, 0, SEQUENCE_constraint },
asn_MBR_PDCCH_ConfigSIB1_1,
2, /* Elements count */
&asn_SPC_PDCCH_ConfigSIB1_specs_1 /* Additional specs */
};
|
bragabriel/Beecrowd
|
Javascript/Uri1144_SequenciaLogica.js
|
<reponame>bragabriel/Beecrowd
var input = require("fs").readFileSync("stdin", "utf8");
var lines = input.split(' ');
var a = parseInt(lines.shift());
for(var b=1; b<=a; b++){
c = b * b;
var d = b * b * b;
console.log(b, c, d);
var e = c + 1;
var f = d + 1;
console.log(b, e, f);
}
|
rbieniek/BGP4J
|
lib/common-config/src/main/java/org/bgp4j/config/nodes/impl/RouteConfigurationImpl.java
|
<gh_stars>1-10
/**
*
*/
package org.bgp4j.config.nodes.impl;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.bgp4j.config.nodes.PathAttributeConfiguration;
import org.bgp4j.config.nodes.RouteConfiguration;
import org.bgp4j.net.NetworkLayerReachabilityInformation;
/**
* @author rainer
*
*/
public class RouteConfigurationImpl implements RouteConfiguration {
private NetworkLayerReachabilityInformation nlri;
private PathAttributeConfiguration pathAttributes;
public RouteConfigurationImpl() {}
public RouteConfigurationImpl(NetworkLayerReachabilityInformation nlri, PathAttributeConfiguration pathAttributes) {
this.nlri = nlri;
this.pathAttributes = pathAttributes;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(RouteConfiguration o) {
return (new CompareToBuilder())
.append(getNlri(), o.getNlri())
.append(getPathAttributes(), o.getPathAttributes())
.toComparison();
}
/* (non-Javadoc)
* @see org.bgp4.config.nodes.RouteConfiguration#getNlri()
*/
@Override
public NetworkLayerReachabilityInformation getNlri() {
return this.nlri;
}
/* (non-Javadoc)
* @see org.bgp4.config.nodes.RouteConfiguration#getPathAttributes()
*/
@Override
public PathAttributeConfiguration getPathAttributes() {
return this.pathAttributes;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return (new HashCodeBuilder())
.append(getNlri())
.append(getPathAttributes())
.toHashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if(!(obj instanceof RouteConfiguration))
return false;
RouteConfiguration o = (RouteConfiguration)obj;
return (new EqualsBuilder())
.append(getNlri(), o.getNlri())
.append(getPathAttributes(), o.getPathAttributes())
.isEquals();
}
/**
* @param nlri the nlri to set
*/
void setNlri(NetworkLayerReachabilityInformation nlri) {
this.nlri = nlri;
}
/**
* @param pathAttributes the pathAttributes to set
*/
void setPathAttributes(PathAttributeConfiguration pathAttributes) {
this.pathAttributes = pathAttributes;
}
}
|
fhwang/sync_machine
|
lib/rails/generators/templates/sync.rb
|
<filename>lib/rails/generators/templates/sync.rb
module <%= class_name %>
extend SyncMachine
subject :<%= subject %>
end
|
sdmg15/GoodDAPP
|
src/components/common/view/JaggedEdge.js
|
<gh_stars>10-100
// @flow
import React, { useMemo, useState } from 'react'
import { View } from 'react-native'
import { withStyles } from '../../../lib/styles'
// To match web version
const TILES = 27
const useJaggedEdge = (width, tileSize, styles) =>
useMemo(() => {
const tileDiagonal = Math.sqrt(2) * tileSize
const marginLeft = tileDiagonal - tileSize
const marginTop = -tileDiagonal / 2 // negative margin for vertical alignment
// Create array of tiles (triangles)
const tileItems = Array.from({ length: TILES }, (e, i) => {
const leftMargin = i === 0 ? marginLeft / 2 : marginLeft
return (
<View key={`tile-${i}`} style={[styles.tile, { width: tileSize, height: tileSize, marginLeft: leftMargin }]} />
)
})
return { marginTop, tileItems, tileDiagonal }
}, [width, tileSize, styles])
const JaggedEdge = ({ styles, theme }) => {
const [width, setWidth] = useState(0)
// calculate container's width
const onLayout = ({ nativeEvent }) => setWidth(nativeEvent.layout.width)
// size of the triangles
const tileSize = useMemo(() => width / ((TILES - 0.5) * Math.sqrt(2)), [width])
const { marginTop, tileItems, tileDiagonal } = useJaggedEdge(width, tileSize, styles)
return (
<View onLayout={onLayout} style={[{ marginTop, height: tileDiagonal }, styles.container]}>
{tileItems}
</View>
)
}
const getStylesFromProps = ({ theme }) => ({
container: {
flexDirection: 'row',
alignItems: 'center',
overflow: 'hidden',
width: '100%',
},
tile: {
backgroundColor: theme.modals.backgroundColor,
transform: [{ rotate: '45deg' }],
},
})
export default withStyles(getStylesFromProps)(JaggedEdge)
|
pierotofy/rosettadrone
|
app/src/main/cpp/gstreamer-1.0/armv7/include/gstreamer-1.0/gst/gstpromise.h
|
<reponame>pierotofy/rosettadrone
/* GStreamer
* Copyright (C) 2017 <NAME> <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef __GST_PROMISE_H__
#define __GST_PROMISE_H__
#include <gst/gst.h>
G_BEGIN_DECLS
GST_API
GType gst_promise_get_type(void);
#define GST_TYPE_PROMISE (gst_promise_get_type())
#define GST_PROMISE(obj) ((GstPromise *) obj)
typedef struct _GstPromise GstPromise;
/**
* GstPromiseResult:
* @GST_PROMISE_RESULT_PENDING: Initial state. Waiting for transition to any
* other state.
* @GST_PROMISE_RESULT_INTERRUPTED: Interrupted by the consumer as it doesn't
* want the value anymore.
* @GST_PROMISE_RESULT_REPLIED: A producer marked a reply
* @GST_PROMISE_RESULT_EXPIRED: The promise expired (the carrying object
* lost all refs) and the promise will never be fulfilled.
*
* The result of a #GstPromise
*
* Since: 1.14
*/
typedef enum
{
GST_PROMISE_RESULT_PENDING,
GST_PROMISE_RESULT_INTERRUPTED,
GST_PROMISE_RESULT_REPLIED,
GST_PROMISE_RESULT_EXPIRED,
} GstPromiseResult;
/**
* GstPromiseChangeFunc:
* @promise: a #GstPromise
* @user_data: (closure): user data
*
* Since: 1.14
*/
typedef void (*GstPromiseChangeFunc) (GstPromise * promise, gpointer user_data);
/**
* GstPromise:
* @parent: parent #GstMiniObject
*
* Since: 1.14
*/
struct _GstPromise
{
GstMiniObject parent;
};
GST_API
GstPromise * gst_promise_new (void);
GST_API
GstPromise * gst_promise_new_with_change_func (GstPromiseChangeFunc func,
gpointer user_data,
GDestroyNotify notify);
GST_API
GstPromiseResult gst_promise_wait (GstPromise * promise);
GST_API
void gst_promise_reply (GstPromise * promise,
GstStructure * s);
GST_API
void gst_promise_interrupt (GstPromise * promise);
GST_API
void gst_promise_expire (GstPromise * promise);
GST_API
const GstStructure * gst_promise_get_reply (GstPromise * promise);
/**
* gst_promise_ref:
* @promise: a #GstPromise.
*
* Increases the refcount of the given @promise by one.
*
* Returns: (transfer full): @promise
*
* Since: 1.14
*/
static inline GstPromise *
gst_promise_ref (GstPromise * promise)
{
return (GstPromise *) gst_mini_object_ref (GST_MINI_OBJECT_CAST (promise));
}
/**
* gst_promise_unref:
* @promise: (transfer full): a #GstPromise.
*
* Decreases the refcount of the promise. If the refcount reaches 0, the
* promise will be freed.
*
* Since: 1.14
*/
static inline void
gst_promise_unref (GstPromise * promise)
{
gst_mini_object_unref (GST_MINI_OBJECT_CAST (promise));
}
G_END_DECLS
#endif /* __GST_PROMISE_H__ */
|
FranicevicNikola/OOP
|
FER/Lectures-master/Exercises/Homework-03/src/main/java/hr/fer/oop/homework_03/e03/Main.java
|
<reponame>FranicevicNikola/OOP
package hr.fer.oop.homework_03.e03;
public class Main {
public static void main(String[] args) {
FoodType foodType = new FoodType("banana", 4, 93, 3);
System.out.println(foodType.toString());
}
}
|
1st/jenkins
|
test/src/test/java/hudson/views/ListViewColumnTest.java
|
<filename>test/src/test/java/hudson/views/ListViewColumnTest.java
package hudson.views;
import hudson.model.ListView;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
/**
* @author <NAME>
*/
public class ListViewColumnTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void createView() throws Exception {
j.jenkins.addView(new ListView("test"));
j.submit(j.createWebClient().goTo("view/test/configure").getFormByName("viewConfig"));
}
}
|
onezens/QQTweak
|
qqtw/qqheaders7.2/NearbyInterestTagViewDelegate-Protocol.h
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "NSObject.h"
@class ITTagInfo, NearbyInterestTagView;
@protocol NearbyInterestTagViewDelegate <NSObject>
- (void)didSelectedInterestTagView:(NearbyInterestTagView *)arg1 tagInfo:(ITTagInfo *)arg2;
@end
|
bmampaey/SDA
|
metadata/resources/gaia_dem.py
|
<reponame>bmampaey/SDA<filename>metadata/resources/gaia_dem.py
# Generated by command write_metadata_files version 1
from metadata.models import GaiaDem
from .base_metadata import BaseMetadataResource
__all__ = ['GaiaDemResource']
class GaiaDemResource(BaseMetadataResource):
'''RESTful resource for model GaiaDem'''
class Meta(BaseMetadataResource.Meta):
abstract = False
queryset = GaiaDem.objects.all()
resource_name = 'metadata_gaia_dem'
|
DeedleFake/p9
|
proto/client.go
|
package proto
import (
"context"
"io"
"log"
"net"
"sync/atomic"
"time"
"github.com/DeedleFake/p9/internal/debug"
)
// Client provides functionality for sending requests to and receiving
// responses from a server for a given protocol. It automatically
// handles message tags, properly blocking until a matching tag
// response has been received.
type Client struct {
done chan struct{}
cancel func()
p Proto
c net.Conn
nextTag chan uint16
sentMsg chan clientMsg
recvMsg chan clientMsg
cancelMsg chan uint16
msize uint32
}
// NewClient initializes a client that communicates using c. The
// Client will close c when the Client is closed.
func NewClient(p Proto, c net.Conn) *Client {
ctx, cancel := context.WithCancel(context.Background())
client := &Client{
done: make(chan struct{}),
cancel: cancel,
p: p,
c: c,
nextTag: make(chan uint16),
sentMsg: make(chan clientMsg),
recvMsg: make(chan clientMsg),
cancelMsg: make(chan uint16),
msize: 1024,
}
go client.reader(ctx)
go client.coord(ctx)
return client
}
// Dial is a convenience function that dials and creates a client in
// the same step.
func Dial(p Proto, network, addr string) (*Client, error) {
c, err := net.Dial(network, addr)
if err != nil {
return nil, err
}
return NewClient(p, c), nil
}
// Close cleans up resources created by the client as well as closing
// the underlying connection.
func (c *Client) Close() error {
c.cancel()
return c.c.Close()
}
// reader reads messages from the connection, sending them to the
// coordinator to be sent to waiting Send calls.
func (c *Client) reader(ctx context.Context) {
for {
err := c.c.SetReadDeadline(time.Now().Add(10 * time.Second))
if err != nil {
if ctx.Err() != nil {
return
}
log.Printf("Failed to set conn deadline: %v", err)
return
}
msg, tag, err := c.p.Receive(c.c, c.Msize())
if err != nil {
if (ctx.Err() != nil) || (err == io.EOF) {
return
}
continue
}
select {
case <-ctx.Done():
return
case c.recvMsg <- clientMsg{
tag: tag,
recv: msg,
}:
}
}
}
// coord coordinates between Send calls and the reader.
func (c *Client) coord(ctx context.Context) {
defer close(c.done)
var nextTag uint16
tags := make(map[uint16]chan interface{})
for {
select {
case <-ctx.Done():
return
case cm := <-c.sentMsg:
tags[cm.tag] = cm.ret
case cm := <-c.recvMsg:
rcm, ok := tags[cm.tag]
if !ok {
continue
}
rcm <- cm.recv
delete(tags, cm.tag)
case tag := <-c.cancelMsg:
delete(tags, tag)
case c.nextTag <- nextTag:
for {
nextTag++
if _, ok := tags[nextTag]; !ok {
break
}
}
}
}
}
// Msize returns the maxiumum size of a message. This does not perform
// any communication with the server.
func (c *Client) Msize() uint32 {
return atomic.LoadUint32(&c.msize)
}
// SetMsize sets the maximum size of a message. This does not perform
// any communication with the server.
func (c *Client) SetMsize(size uint32) {
atomic.StoreUint32(&c.msize, size)
}
// Send sends a message to the server, blocking until a response has
// been received. It is safe to place multiple Send calls
// concurrently, and each will return when the response to that
// request has been received.
func (c *Client) Send(msg interface{}) (interface{}, error) {
debug.Log("client -> %#v\n", msg)
tag := NoTag
if _, ok := msg.(P9NoTag); !ok {
select {
case <-c.done:
return nil, ErrClientClosed
case tag = <-c.nextTag:
}
}
ret := make(chan interface{}, 1)
select {
case <-c.done:
return nil, ErrClientClosed
case c.sentMsg <- clientMsg{
tag: tag,
ret: ret,
}:
}
err := c.p.Send(c.c, tag, msg)
if err != nil {
select {
case <-c.done:
case c.cancelMsg <- tag:
}
return nil, err
}
select {
case <-c.done:
return nil, ErrClientClosed
case rsp := <-ret:
debug.Log("client <- %#v\n", rsp)
if err, ok := rsp.(error); ok {
return nil, err
}
return rsp, nil
}
}
// Sometimes I think that some type of tuples would be nice...
type clientMsg struct {
tag uint16
recv interface{}
ret chan interface{}
}
// P9NoTag is implemented by any types that should not use tags for
// communicating. In 9P, for example, this is true of the Tversion
// message type, as it must be the first thing sent and no further
// communication can happen before an Rversion is sent in response.
type P9NoTag interface {
P9NoTag()
}
|
Neology92/dobrybruk-website
|
src/components/PopUp/PopUp.js
|
<reponame>Neology92/dobrybruk-website<gh_stars>0
import styled from 'styled-components';
const Modal = styled.div`
display: none;
${({ theme }) => theme.media.above.xl} {
display: ${({ isOpen }) => (isOpen ? 'block' : 'none')};
height: 80vh;
width: calc(80vh * 1.7);
background: ${({ theme, isGreen }) =>
isGreen ? theme.color.darkGreen : theme.color.darkGrey};
position: fixed;
top: 15%;
left: calc(10vw * 1.7);
z-index: 9999999;
}
`;
export default Modal;
|
bvarner/javashare
|
src/main/java/org/beShare/event/ChatMessageListener.java
|
<filename>src/main/java/org/beShare/event/ChatMessageListener.java
package org.beShare.event;
import org.beShare.data.ChatMessage;
import org.beShare.gui.ChatPoster;
/**
ChatMessageListener - Defines the interface for classes wishing to listen
for new ChatMessage events.
Last Update: 2-28-2002
@author <NAME>
@version 1.0
*/
public interface ChatMessageListener{
public void chatMessage(ChatMessage cm);
public void addChatPoster(ChatPoster p);
public void removeChatPoster(ChatPoster p);
}
|
magneticchen/NRSF
|
NoService/services/NoCluster/plugin/virtualization/index.js
|
<reponame>magneticchen/NRSF
// NoService/NoService/rumtime/plugins/virtualization/index.js
// Description:
// "virtualization" use cluster API to virtualize model, filesystem etc.
// Copyright 2018-2019 NOOXY. All Rights Reserved.
module.exports.Filesystem = require('./filesystem');
module.exports.Model = require('./model');
|
Mohammad-Elsharkawy/CompetitiveProgramming
|
codeforces/1433/D.cpp
|
<reponame>Mohammad-Elsharkawy/CompetitiveProgramming
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=200005;
int arr[300005];
bool done[300005];
set<int>s1;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;cin>>t;
while(t--){
s1.clear();
memset(done,0,sizeof done);
int n;cin>>n;
for(int i=1;i<=n;i++){
cin>>arr[i];
s1.insert(arr[i]);
}
if(s1.size()==1){
cout<<"NO\n";
continue;
}else{
cout<<"YES\n";
int a=arr[1];
done[1]=1;
int g=-1;
for(int i=2;i<=n;i++){
if(arr[i]!=a){
cout<<1<<" "<<i<<endl;
done[i]=1;
g=i;
}
}
for(int i=2;i<=n;i++){
if(done[i]==0){
cout<<g<<" "<<i<<endl;
done[i]=1;
}
}
}
}
return 0;
}
|
psryland/rylogic_code
|
projects/lost_at_sea/src/world/skybox.h
|
//************************************
// Lost at Sea
// Copyright (c) Rylogic Ltd 2011
//************************************
#pragma once
#include "lost_at_sea/src/forward.h"
#include "lost_at_sea/src/event.h"
namespace las
{
struct Skybox
:pr::events::IRecv<Evt_AddToViewport>
{
#define PR_RDR_INST(x)\
x(pr::rdr::ModelPtr ,m_model ,EInstComp::ModelPtr)\
x(pr::m4x4 ,m_i2w ,EInstComp::I2WTransform)
PR_RDR_DEFINE_INSTANCE(Instance, PR_RDR_INST);
#undef PR_RDR_INST
Instance m_inst; // The skybox instance
pr::rdr::Texture2DPtr m_tex; // A texture for the skybox
Skybox(pr::Renderer& rdr, string const& texpath);
void OnEvent(las::Evt_AddToViewport const& e);
};
}
|
iuskye/SREWorks
|
paas/appmanager/tesla-appmanager-spring/src/main/java/com/alibaba/tesla/appmanager/spring/config/SchedulingConfigurerConfiguration.java
|
<filename>paas/appmanager/tesla-appmanager-spring/src/main/java/com/alibaba/tesla/appmanager/spring/config/SchedulingConfigurerConfiguration.java
package com.alibaba.tesla.appmanager.spring.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
/**
* Scheduler Pool Settings
*
* @author yaox<EMAIL>
*/
@Configuration
public class SchedulingConfigurerConfiguration implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(100);
taskScheduler.initialize();
taskRegistrar.setTaskScheduler(taskScheduler);
}
}
|
Tagar/dremio-oss
|
dac/ui/src/pages/ExplorePage/components/ExploreDragArea-spec.js
|
<gh_stars>0
/*
* Copyright (C) 2017-2018 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { shallow } from 'enzyme';
import DragTarget from 'components/DragComponents/DragTarget';
import ExploreDragArea from './ExploreDragArea';
describe('ExploreDragArea', () => {
let minimalProps;
let commonProps;
beforeEach(() => {
minimalProps = {
handleDrop: sinon.spy(),
getColumnsForDragArea: sinon.spy(),
dragType: 'test',
emptyDragAreaText: 'DragTarget TEXT',
isDragged: false
};
commonProps = {
...minimalProps,
children: [<div>foo</div>]
};
});
it('should render with minimal props without exploding', () => {
const wrapper = shallow(<ExploreDragArea {...minimalProps} />);
expect(wrapper).to.have.length(1);
});
it('should render emptyDragAreaText if no children', () => {
const wrapper = shallow(<ExploreDragArea {...minimalProps} />);
expect(wrapper.find('.empty-text').text()).to.eql(minimalProps.emptyDragAreaText);
});
it('should not render emptyDragAreaText if there are children', () => {
const wrapper = shallow(<ExploreDragArea {...commonProps} />);
expect(wrapper.find('.empty-text')).to.have.length(0);
});
it('should render DragTarget component', () => {
const wrapper = shallow(<ExploreDragArea {...commonProps} />);
expect(wrapper.find(DragTarget)).to.have.length(1);
});
});
|
amur-host/node
|
it/src/test/scala/com/amurplatform/it/sync/matcher/OrderExclusionTestSuite.scala
|
<filename>it/src/test/scala/com/amurplatform/it/sync/matcher/OrderExclusionTestSuite.scala
package com.amurplatform.it.sync.matcher
import com.typesafe.config.{Config, ConfigFactory}
import com.amurplatform.it._
import com.amurplatform.it.api.SyncHttpApi._
import com.amurplatform.it.api.SyncMatcherHttpApi._
import com.amurplatform.it.transactions.NodesFromDocker
import com.amurplatform.it.util._
import com.amurplatform.state.ByteStr
import com.amurplatform.transaction.assets.exchange.{AssetPair, Order, OrderType}
import org.scalatest.{BeforeAndAfterAll, CancelAfterFailure, FreeSpec, Matchers}
import scala.concurrent.duration._
import scala.util.Random
class OrderExclusionTestSuite
extends FreeSpec
with Matchers
with BeforeAndAfterAll
with CancelAfterFailure
with ReportingTestName
with NodesFromDocker {
import OrderExclusionTestSuite._
override protected def nodeConfigs: Seq[Config] = Configs
private def matcherNode = nodes.head
private def aliceNode = nodes(1)
"check order execution" - {
// Alice issues new asset
val aliceAsset =
aliceNode.issue(aliceNode.address, "AliceCoin", "AliceCoin for matcher's tests", AssetQuantity, 0, reissuable = false, 100000000L).id
nodes.waitForHeightAriseAndTxPresent(aliceAsset)
val aliceAmurPair = AssetPair(ByteStr.decodeBase58(aliceAsset).toOption, None)
// check assets's balances
aliceNode.assertAssetBalance(aliceNode.address, aliceAsset, AssetQuantity)
aliceNode.assertAssetBalance(matcherNode.address, aliceAsset, 0)
"sell order could be placed and status it's correct" in {
// Alice places sell order
val aliceOrder = matcherNode
.placeOrder(aliceNode, aliceAmurPair, OrderType.SELL, 2.amur * Order.PriceConstant, 500, 2: Byte, 70.seconds)
aliceOrder.status shouldBe "OrderAccepted"
val orderId = aliceOrder.message.id
// Alice checks that the order in order book
matcherNode.orderStatus(orderId, aliceAmurPair).status shouldBe "Accepted"
matcherNode.fullOrderHistory(aliceNode).head.status shouldBe "Accepted"
// Alice check that order is correct
val orders = matcherNode.orderBook(aliceAmurPair)
orders.asks.head.amount shouldBe 500
orders.asks.head.price shouldBe 2.amur * Order.PriceConstant
// sell order should be in the aliceNode orderbook
matcherNode.fullOrderHistory(aliceNode).head.status shouldBe "Accepted"
//wait for expiration of order
matcherNode.waitOrderStatus(aliceAmurPair, orderId, "Cancelled", 2.minutes)
matcherNode.fullOrderHistory(aliceNode).head.status shouldBe "Cancelled"
}
}
}
object OrderExclusionTestSuite {
val ForbiddenAssetId = "FdbnAsset"
import NodeConfigs.Default
private val matcherConfig = ConfigFactory.parseString(s"""
|amur {
| matcher {
| enable = yes
| account = <KEY>
| bind-address = "0.0.0.0"
| order-match-tx-fee = 300000
| blacklisted-assets = [$ForbiddenAssetId]
| order-cleanup-interval = 20s
| }
| rest-api {
| enable = yes
| api-key-hash = <KEY>
| }
| miner.enable=no
|}""".stripMargin)
private val nonGeneratingPeersConfig = ConfigFactory.parseString(
"""amur {
| matcher.order-cleanup-interval = 30s
| miner.enable=no
|}""".stripMargin
)
val AssetQuantity: Long = 1000
val MatcherFee: Long = 300000
val TransactionFee: Long = 300000
// val Amur: Long = 100000000L
private val Configs: Seq[Config] = {
val notMatchingNodes = Random.shuffle(Default.init).take(3)
Seq(matcherConfig.withFallback(Default.last), notMatchingNodes.head) ++
notMatchingNodes.tail.map(nonGeneratingPeersConfig.withFallback)
}
}
|
jxg01713/zstack
|
header/src/main/java/org/zstack/header/vm/VmInstantiateResourceException.java
|
<filename>header/src/main/java/org/zstack/header/vm/VmInstantiateResourceException.java
package org.zstack.header.vm;
import org.zstack.header.errorcode.ErrorCode;
public class VmInstantiateResourceException extends Exception {
private ErrorCode errorCode;
public ErrorCode getErrorCode() {
return errorCode;
}
public void setErrorCode(ErrorCode errorCode) {
this.errorCode = errorCode;
}
}
|
nydevel/qirk
|
qirk-parent/qirk-main-parent/qirk-services-api/src/main/java/org/wrkr/clb/services/dto/project/task/TaskLinkDTO.java
|
<reponame>nydevel/qirk
package org.wrkr.clb.services.dto.project.task;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TaskLinkDTO {
@JsonProperty(value = "task1")
@NotNull(message = "task1 in TaskLinkDTO must not be null")
public Long task1Id;
@JsonProperty(value = "task2")
@NotNull(message = "task2 in TaskLinkDTO must not be null")
public Long task2Id;
}
|
cbbathaglini/orange-talents-05-template-mercado-livre
|
src/main/java/br/com/mercadolivre/dto/request/ProdutoDTORequest.java
|
<gh_stars>0
package br.com.mercadolivre.dto.request;
import br.com.mercadolivre.model.*;
import br.com.mercadolivre.repository.CategoriaRepository;
import br.com.mercadolivre.repository.ProdutoRepository;
import br.com.mercadolivre.repository.UsuarioRepository;
import br.com.mercadolivre.validates.ExistsId;
import io.jsonwebtoken.lang.Assert;
import org.hibernate.validator.constraints.Length;
import javax.persistence.CascadeType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class ProdutoDTORequest {
@NotBlank
private String nome;
@NotNull @Positive
private BigDecimal preco;
@NotNull @PositiveOrZero
private Integer quantidade;
@NotBlank @Length(max = 1000)
private String descricao;
@Size(min = 3)
private List<CaracteristicasProdutoDTORequest> caracteristicasProdutoDTORequestList = new ArrayList<>(); // um produto pode ter várias características
@NotNull
@ExistsId(domainClass = Categoria.class, fieldName = "id")
private Long idCategoria;
public ProdutoDTORequest() {
}
public List<CaracteristicasProdutoDTORequest> getCaracteristicas() {
return caracteristicasProdutoDTORequestList;
}
public void setCaracteristicas(List<CaracteristicasProdutoDTORequest> caracteristicas) {
this.caracteristicasProdutoDTORequestList = caracteristicas;
}
public ProdutoDTORequest(String nome, BigDecimal preco, Integer quantidade,
String descricao, List<CaracteristicasProdutoDTORequest>
caracteristicasProdutoDTORequestList, Long idCategoria) {
this.nome = nome;
this.preco = preco;
this.quantidade = quantidade;
this.descricao = descricao;
this.caracteristicasProdutoDTORequestList.addAll(caracteristicasProdutoDTORequestList);
this.idCategoria = idCategoria;
}
public Produto converter(CategoriaRepository categoriaRepository, Usuario usuario) {
Optional<Categoria> categoriaOp = categoriaRepository.findById(this.idCategoria);// acha a categoria a partir do id
if(categoriaOp.isPresent()) {
return new Produto(nome, preco, quantidade, descricao, caracteristicasProdutoDTORequestList, categoriaOp.get(),usuario);
}
return null;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public BigDecimal getPreco() {
return preco;
}
public void setPreco(BigDecimal preco) {
this.preco = preco;
}
public Integer getQuantidade() {
return quantidade;
}
public void setQuantidade(Integer quantidade) {
this.quantidade = quantidade;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public List<CaracteristicasProdutoDTORequest> getCaracteristicasProdutoDTORequestList() {
return caracteristicasProdutoDTORequestList;
}
public void setCaracteristicasProdutoDTORequestList(List<CaracteristicasProdutoDTORequest> caracteristicasProdutoDTORequestList) {
this.caracteristicasProdutoDTORequestList = caracteristicasProdutoDTORequestList;
}
public Long getIdCategoria() {
return idCategoria;
}
public void setIdCategoria(Long idCategoria) {
this.idCategoria = idCategoria;
}
@Override
public String toString() {
return "ProdutoDTORequest{" +
"nome='" + nome + '\'' +
", preco=" + preco +
", quantidade=" + quantidade +
", descricao='" + descricao + '\'' +
", caracteristicasProdutoDTORequestList=" + caracteristicasProdutoDTORequestList +
", idCategoria=" + idCategoria +
'}';
}
}
|
mengkeer/xbsz-iOS
|
xbsz/xbsz/Common/Utils/FMDBUtil.h
|
//
// FMDBUtil.h
// xbsz
//
// Created by lotus on 2017/4/25.
// Copyright © 2017年 lotus. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ExerciseMode.h"
@interface FMDBUtil : NSObject
+ (instancetype)instance;
#pragma mark - 所有模式公共接口
+ (ExerciseType)indexToExerciseType:(NSInteger)index;
//根据题库类型转换为对应的table name
+ (NSString *)exerciseTypeToExerciseName:(ExerciseType )type;
//获取题库题目总数
+ (NSInteger)getQuestionsTotalByType:(ExerciseType )type;
//根据是否是错题获取题目总数
+ (NSInteger)getQuestionsTotalByType:(ExerciseType )type isWrong:(BOOL)isWrong;
//根据是否是单选获取题目总数
+ (NSInteger)getQuestionsTotalByType:(ExerciseType )type isSingle:(BOOL)isSingle;
//根据单选多选 是否是错题获取题目总数
+ (NSInteger)getQuestionsTotalByType:(ExerciseType )type isSingle:(BOOL)isSingle isWrong:(BOOL)isWrong;
//获取章节索引
+ (NSArray *)getChapterIndex:(ExerciseType)type isSingle:(BOOL)isSingle;
+ (NSArray *)getChapterIndex:(ExerciseType)type isSingle:(BOOL)isSingle isWrong:(BOOL)isWrong;
//获取每章的题目数构成的数组
+ (NSArray *)getChapterNums:(ExerciseType)type isSingle:(BOOL)isSingle;
+ (NSArray *)getChapterNums:(ExerciseType)type isSingle:(BOOL)isSingle isWrong:(BOOL)isWrong;
//根据type 是否单选 章节数获取具体的章节题目数
+ (NSArray *)getQuestions:(ExerciseType)type isSingle:(BOOL)isSingle chapterIndex:(NSInteger)index;
+ (NSArray *)getQuestions:(ExerciseType)type isSingle:(BOOL)isSingle isWrong:(NSInteger)isWrong chapterIndex:(NSInteger)index;
//根据option字符窜分离出来 各个选项
+ (NSArray *)getOptionsByString:(NSString *)optionStr type:(NSInteger)type;
//获取纯净的题干内容 去除前面的题号索引
+ (NSString *)getPureTitle:(NSString *)title;
+ (NSString *)indexConvertToSymbol:(NSInteger)index;
#pragma mark - 搜索模式接口
//根据关键字获取查询结果 最多显示前20条数据
+ (NSMutableArray *)getSearchResultsBySearchText:(NSString *)text type:(ExerciseType)type;
+ (BOOL)isSingleRightAnswer:(NSInteger)index answer:(NSString *)answer; //单选
+ (BOOL)isMutiRightAnswer:(NSString *)selectedIndexs answer:(NSString *)answer;
#pragma mark - 错题集接口
+ (void)setQuestionFlag:(ExerciseType)type quesionID:(NSInteger)quesionID isWrong:(BOOL)isWrong;
#pragma mark - 考试模式接口
//随机获取模拟考试题目数据
+ (NSArray *)getExamQuestionsByType:(ExerciseType)type;
+ (void)closeDB;
@end
|
gkumar111/elasticsearch
|
modules/mapper-extras/src/main/java/org/elasticsearch/index/query/VectorDVAtomicFieldData.java
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.query;
import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.index.fielddata.AtomicFieldData;
import org.elasticsearch.index.fielddata.ScriptDocValues;
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
final class VectorDVAtomicFieldData implements AtomicFieldData {
private final LeafReader reader;
private final String field;
private final boolean isDense;
VectorDVAtomicFieldData(LeafReader reader, String field, boolean isDense) {
this.reader = reader;
this.field = field;
this.isDense = isDense;
}
@Override
public long ramBytesUsed() {
return 0; // not exposed by Lucene
}
@Override
public Collection<Accountable> getChildResources() {
return Collections.emptyList();
}
@Override
public SortedBinaryDocValues getBytesValues() {
throw new UnsupportedOperationException("String representation of doc values for vector fields is not supported");
}
@Override
public ScriptDocValues<BytesRef> getScriptValues() {
try {
final BinaryDocValues values = DocValues.getBinary(reader, field);
if (isDense) {
return new VectorScriptDocValues.DenseVectorScriptDocValues(values);
} else {
return new VectorScriptDocValues.SparseVectorScriptDocValues(values);
}
} catch (IOException e) {
throw new IllegalStateException("Cannot load doc values for vector field!", e);
}
}
@Override
public void close() {
// no-op
}
}
|
fangjiaxiaobai/learn
|
13-design-pattern/chapter03-proxy/src/demo1_staticProxy/IUserDao.java
|
<reponame>fangjiaxiaobai/learn
package demo1_staticProxy;
/**
* @author <EMAIL>
* @date 2018/3/5
*/
public interface IUserDao {
default void save(){
System.out.println("this is save method in demo1_staticProxy.IUserDao");
}
}
|
xutao6936/archYBT
|
src/main/java/com/topcheer/ybt/filter/LoginFilter.java
|
package com.topcheer.ybt.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.topcheer.ybt.system.entity.TopUserinfo;
/**
* @ClassName: LoginFilter
* @Description: 登录filter
* @author XUTAO
* @date 2016-6-17 上午09:21:14
*
*/
public class LoginFilter implements Filter {
private static Logger log = LoggerFactory.getLogger(LoginFilter.class);
private static String allowUrl;
/**
* Default constructor.
*/
public LoginFilter() {
}
/**
* @see Filter#destroy()
*/
public void destroy() {
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
String URI = request.getRequestURI();
if (validateUrl(URI)) {
chain.doFilter(request, response);
} else {
TopUserinfo userinfo = (TopUserinfo) request.getSession().getAttribute("userinfo");
if (null == userinfo) {
log.info("用户未登录");
response.sendRedirect(request.getContextPath() + "/login.jsp");
// request.getRequestDispatcher(request.getContextPath() + "/login.jsp").forward(request, response);
// response.setHeader("Cache-Control", "no-store");
// response.setDateHeader("Expires", 0);
// response.setHeader("Pragma", "no-cache");
return;
} else {
log.info("登录账户为{}", userinfo.getLoginAccount());
chain.doFilter(request, response);
}
}
}
private static boolean validateUrl(String URI) {
if (URI.indexOf(allowUrl) != -1) {
return true;
}
return false;
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
allowUrl = fConfig.getInitParameter("allowUrl");
}
}
|
thirtyfiveparts/live
|
repos/live/packages/app-templates/full-stack-graphql-react-2/web/test/e2e/cypress/support/index.js
|
import './commands'
// Run before all tests.
before(() => {
setupFromGetRequest()
//setupFromScripts()
})
// Runs a script to reset the database.
function setupFromScripts() {
//const backendPath = Cypress.env('BACKEND_PATH')
console.log(__dirname)
// TODO(vjpr): Fix!
const backendPath =
'/Users/Vaughan/dev-mono/thirtyfive/repos/live/packages/app-templates/full-stack-graphql-react/node-backend'
const cmd = `cd ${backendPath} && bin/cli.js db:reset`
cy.exec(cmd, {failOnNonZeroExit: false}).then(res => {
//cy.log(res.stdout)
})
}
// Make a request to a private API in the backend to reset the database.
// This means we don't have to spin up the entire app just to reset the database.
function setupFromGetRequest() {
cy.request('POST', 'api/debug-reset')
}
|
slilichenko/dataflow-sample-applications
|
retail/retail-java-applications/data-engineering-dept/business-logic/src/test/java/com/google/dataflow/sample/retail/businesslogic/core/utils/test/clickstream/ValidateAndCorrectClickStreamEventsTests.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.dataflow.sample.retail.businesslogic.core.utils.test.clickstream;
import com.google.common.collect.ImmutableList;
import com.google.dataflow.sample.retail.businesslogic.core.transforms.DeadLetterSink.SinkType;
import com.google.dataflow.sample.retail.businesslogic.core.transforms.clickstream.ValidateAndCorrectCSEvt;
import com.google.dataflow.sample.retail.dataobjects.ClickStream.ClickStreamEvent;
import com.google.dataflow.sample.retail.dataobjects.Ecommerce;
import com.google.dataflow.sample.retail.dataobjects.Item;
import org.apache.beam.sdk.schemas.NoSuchSchemaException;
import org.apache.beam.sdk.schemas.SchemaCoder;
import org.apache.beam.sdk.schemas.transforms.Convert;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.testing.TestStream;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TimestampedValue;
import org.joda.time.Instant;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ValidateAndCorrectCSEvt}. TODO Remove Convert to / from left over code. */
@RunWith(JUnit4.class)
public class ValidateAndCorrectClickStreamEventsTests {
private static final Long TIME = Instant.parse("2000-01-01T00:00:00").getMillis();
private static final TimestampedValue<ClickStreamEvent> CLEAN_DATA =
TimestampedValue.of(
ClickStreamEvent.builder()
.setEventTime("2000-01-01 00:00:00")
.setUid(1L)
.setClientId("1")
.setPage("pageRef")
.setPagePrevious("pageTarget")
.setEvent("event")
.build(),
Instant.ofEpochMilli(TIME));
private static final ClickStreamEvent BAD_DATE_FORMAT =
ClickStreamEvent.builder()
.setEventTime("2000-XX-01 00:00:00")
.setClientId("1")
.setPage("pageRef")
.setPagePrevious("pageTarget")
.setEvent("event")
.setUid(1L)
.build();
private static final ClickStreamEvent DATE_IN_FUTURE =
ClickStreamEvent.builder()
.setEventTime("2000-01-02 00:00:00")
.setUid(1L)
.setClientId("1")
.setPage("pageRef")
.setPagePrevious("pageTarget")
.setEvent("event")
.setUid(1L)
.build();
private static final ClickStreamEvent MISSING_ITEM_INFO =
ClickStreamEvent.builder()
.setEventTime("2000-01-01 00:00:00")
.setClientId("1")
.setPage("pageRef")
.setPagePrevious("pageTarget")
.setEvent("add_to_cart")
.setEcommerce(
Ecommerce.builder()
.setItems(ImmutableList.of(Item.builder().setPrice(1F).setItemId("1").build()))
.build())
.build();
private static final ClickStreamEvent CLEAN_DATE_TIMESTAMP =
ClickStreamEvent.builder()
.setEventTime("2000-XX-01 00:00:00")
.setUid(1L)
.setClientId("1")
.setPage("pageRef")
.setPagePrevious("pageTarget")
.setEvent("event")
.build();
private static final ClickStreamEvent MISSING_ITEM_INFO_BAD_DATE =
ClickStreamEvent.builder()
.setEventTime("2000-0X-01 00:00:00")
.setClientId("1")
.setPage("pageRef")
.setPagePrevious("pageTarget")
.setEvent("add_to_cart")
.setEcommerce(
Ecommerce.builder()
.setItems(ImmutableList.of(Item.builder().setPrice(1F).setItemId("1").build()))
.build())
.build();
@Rule public transient TestPipeline pipeline = TestPipeline.create();
@Test
public void testCleanValidation() {
PCollection<ClickStreamEvent> result =
pipeline
.apply(Create.timestamped(CLEAN_DATA))
.apply("From", Convert.toRows())
.apply(new ValidateAndCorrectCSEvt(SinkType.LOG))
.apply(Convert.fromRows(ClickStreamEvent.class));
PAssert.that(result)
.containsInAnyOrder(CLEAN_DATA.getValue().toBuilder().setTimestamp(TIME).build());
pipeline.run();
}
@Test
public void testBadDateFormat() throws NoSuchSchemaException {
SchemaCoder<ClickStreamEvent> schema =
pipeline.getSchemaRegistry().getSchemaCoder(ClickStreamEvent.class);
TestStream<ClickStreamEvent> ts =
TestStream.create(schema)
.advanceWatermarkTo(Instant.ofEpochMilli(TIME))
.addElements(BAD_DATE_FORMAT)
.advanceWatermarkToInfinity();
PCollection<ClickStreamEvent> result =
pipeline
.apply(ts)
.apply("From", Convert.toRows())
.apply(new ValidateAndCorrectCSEvt(SinkType.LOG))
.apply(Convert.fromRows(ClickStreamEvent.class));
PAssert.that(result)
.containsInAnyOrder(CLEAN_DATE_TIMESTAMP.toBuilder().setTimestamp(TIME).build());
pipeline.run();
}
@Test
public void testDateInFuture() throws NoSuchSchemaException {
SchemaCoder<ClickStreamEvent> schema =
pipeline.getSchemaRegistry().getSchemaCoder(ClickStreamEvent.class);
TestStream<ClickStreamEvent> ts =
TestStream.create(schema)
.advanceWatermarkTo(Instant.ofEpochMilli(TIME))
.addElements(DATE_IN_FUTURE)
.advanceWatermarkToInfinity();
PCollection<ClickStreamEvent> result =
pipeline
.apply(ts)
.apply("From", Convert.toRows())
.apply(new ValidateAndCorrectCSEvt(SinkType.LOG))
.apply(Convert.fromRows(ClickStreamEvent.class));
PAssert.that(result).containsInAnyOrder(DATE_IN_FUTURE.toBuilder().setTimestamp(TIME).build());
pipeline.run();
}
@Test
public void testMissingItems() throws NoSuchSchemaException {
SchemaCoder<ClickStreamEvent> schema =
pipeline.getSchemaRegistry().getSchemaCoder(ClickStreamEvent.class);
TestStream<ClickStreamEvent> ts =
TestStream.create(schema)
.advanceWatermarkTo(Instant.ofEpochMilli(TIME))
.addElements(MISSING_ITEM_INFO)
.advanceWatermarkToInfinity();
PCollection<ClickStreamEvent> result =
pipeline
.apply(ts)
.apply("From", Convert.toRows())
.apply(new ValidateAndCorrectCSEvt(SinkType.LOG))
.apply(Convert.fromRows(ClickStreamEvent.class));
PAssert.that(result)
.containsInAnyOrder(
MISSING_ITEM_INFO
.toBuilder()
.setTimestamp(TIME)
.setEcommerce(
Ecommerce.builder()
.setItems(
ImmutableList.of(
Item.builder()
.setPrice(1F)
.setItemId("1")
.setItemName("foo_name")
.setItemBrand("item_brand")
.setItemCat01("foo_category")
.build()))
.build())
.build());
pipeline.run();
}
@Test
public void testBadDateFormatAndMissingItems() throws NoSuchSchemaException {
SchemaCoder<ClickStreamEvent> schema =
pipeline.getSchemaRegistry().getSchemaCoder(ClickStreamEvent.class);
TestStream<ClickStreamEvent> ts =
TestStream.create(schema)
.advanceWatermarkTo(Instant.ofEpochMilli(TIME))
.addElements(MISSING_ITEM_INFO_BAD_DATE)
.advanceWatermarkToInfinity();
PCollection<ClickStreamEvent> result =
pipeline
.apply(ts)
.apply("From", Convert.toRows())
.apply(new ValidateAndCorrectCSEvt(SinkType.LOG))
.apply(Convert.fromRows(ClickStreamEvent.class));
PAssert.that(result)
.containsInAnyOrder(
MISSING_ITEM_INFO_BAD_DATE
.toBuilder()
.setEcommerce(
Ecommerce.builder()
.setItems(
ImmutableList.of(
Item.builder()
.setPrice(1F)
.setItemId("1")
.setItemName("foo_name")
.setItemBrand("item_brand")
.setItemCat01("foo_category")
.build()))
.build())
.setTimestamp(TIME)
.build());
pipeline.run();
}
}
|
aerinkayne/website
|
Tutorials/Processing/11_video/sketch_11_9_BlobTrackingIDs_js/blob.js
|
// <NAME>
// http://codingtra.in
// http://patreon.com/codingtrain
// Code for: https://youtu.be/r0lvsMPGEoY
class Blob {
constructor(x, y) {
this.minx = x;
this.miny = y;
this.maxx = x;
this.maxy = y;
this.taken = false;
this.id = 0;
}
show() {
stroke(0);
fill(255, 100);
strokeWeight(2);
rectMode(CORNERS);
rect(this.minx, this.miny, this.maxx, this.maxy);
textAlign(CENTER);
textSize(64);
fill(0);
text(this.id, this.minx + (this.maxx - this.minx) * 0.5, this.maxy - 10);
}
add(x, y) {
this.minx = min(this.minx, x);
this.miny = min(this.miny, y);
this.maxx = max(this.maxx, x);
this.maxy = max(this.maxy, y);
}
become(other) {
this.minx = other.minx;
this.maxx = other.maxx;
this.miny = other.miny;
this.maxy = other.maxy;
}
size() {
return (this.maxx - this.minx) * (this.maxy - this.miny);
}
getCenter() {
const x = (this.maxx - this.minx) * 0.5 + this.minx;
const y = (this.maxy - this.miny) * 0.5 + this.miny;
return createVector(x, y);
}
isNear(x, y) {
const cx = max(min(x, this.maxx), this.minx);
const cy = max(min(y, this.maxy), this.miny);
const d = distSq(cx, cy, x, y);
if (d < distThreshold * distThreshold) {
return true;
} else {
return false;
}
}
}
|
Hearthstonepp/Hearthstonepp
|
Sources/Rosetta/PlayMode/Tasks/PlayerTasks/EndTurnTask.cpp
|
<filename>Sources/Rosetta/PlayMode/Tasks/PlayerTasks/EndTurnTask.cpp
// This code is based on Sabberstone project.
// Copyright (c) 2017-2021 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2017-2021 <NAME>
#include <Rosetta/PlayMode/Games/Game.hpp>
#include <Rosetta/PlayMode/Managers/GameManager.hpp>
#include <Rosetta/PlayMode/Models/Player.hpp>
#include <Rosetta/PlayMode/Tasks/PlayerTasks/EndTurnTask.hpp>
namespace RosettaStone::PlayMode::PlayerTasks
{
TaskStatus EndTurnTask::Impl(Player* player)
{
auto game = player->game;
game->nextStep = Step::MAIN_END;
GameManager::ProcessNextStep(*game, game->nextStep);
return TaskStatus::COMPLETE;
}
std::unique_ptr<ITask> EndTurnTask::CloneImpl()
{
return std::make_unique<EndTurnTask>();
}
} // namespace RosettaStone::PlayMode::PlayerTasks
|
sshockwave/Online-Judge-Solutions
|
EZOJ/Contests/1317/A.cpp
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <cctype>
#include <vector>
using namespace std;
typedef long long lint;
#define cout cerr
#define ni (next_num<int>())
#define nl (next_num<lint>())
template<class T>inline T next_num(){
T i=0;char c;
while(!isdigit(c=getchar())&&c!='-');
bool flag=c=='-';
flag?(c=getchar()):0;
while(i=i*10-'0'+c,isdigit(c=getchar()));
return flag?-i:i;
}
template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){
if(b<a){a=b;}
}
template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){
if(a<b){a=b;}
}
const int N=1500010;
void solve(lint a[],int n){
if(n==1){
return;
}
int half=n>>1;
lint s0=a[half-1],s1=a[n-1]-s0;
for(int i=0;i<half;i++){
a[i]=(a[i+half]+a[i]-s1)>>1;
a[i+half]-=a[i];
}
solve(a,half),solve(a+half,half);
}
lint a[N];
int main(){
#ifndef ONLINE_JUDGE
freopen("spy.in","r",stdin);
freopen("spy.out","w",stdout);
#endif
int n=ni;
for(int i=0;i<n;i++){
a[i]=nl;
}
solve(a,n);
for(int i=0;i<n;i++){
printf("%lld ",a[i]);
}
putchar('\n');
}
|
wm-c/ICS4U1
|
Graphic/src/main/java/graphics/RenderHell/objects/terrain/TerrainMaster.java
|
<filename>Graphic/src/main/java/graphics/RenderHell/objects/terrain/TerrainMaster.java
package graphics.RenderHell.objects.terrain;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.ArrayList;
import graphics.RenderHell.collision.CollisionController;
import graphics.RenderHell.interfaces.Drawable;
import graphics.RenderHell.interfaces.Logicable;
import graphics.RenderHell.utils.Vector;
public class TerrainMaster implements Logicable, Drawable {
// creates instances
private static TerrainMaster mInstance = null;
// arraylist for walls
private static ArrayList<Wall> terrain;
// gets instance of terrain master
public static TerrainMaster getInstance() {
if (mInstance == null) {
mInstance = new TerrainMaster();
}
return mInstance;
}
// Creates arraylist adds wall base walls
private TerrainMaster() {
terrain = new ArrayList<>();
addTerrain(new Wall(-50, -50, 1500 + 15, 50));
addTerrain(new Wall(-50, 550, 1000 + 15, 50));
addTerrain(new Wall(-50, 0, 50, 550 + 15));
addTerrain(new Wall(950, 550, 50, 550 + 15));
addTerrain(new Wall(950, 1100, 500 + 15, 50));
addTerrain(new Wall(1450, -50, 50, 1200));
}
// adds terrain and registers it with the collision controller
private void addTerrain(Wall newTerrain) {
terrain.add(newTerrain);
CollisionController.getInstance().addHittable(newTerrain);
}
// updates all walls
@Override
public void update(Vector playerVector) {
for (Wall wall : terrain) {
wall.update(playerVector);
}
}
// draws all walls
@Override
public void draw(Graphics2D g2d) {
for (Wall wall : terrain) {
wall.draw(g2d);
}
}
// returns a list of terrain
public ArrayList<Wall> getTerrain(){
return terrain;
}
}
|
JustPretender/botan
|
src/lib/prov/pkcs11/p11_x509.cpp
|
<gh_stars>1-10
/*
* PKCS#11 X.509
* (C) 2016 <NAME>, Sirrix AG
* (C) 2016 <NAME>, Sirrix AG
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/p11_x509.h>
#if defined(BOTAN_HAS_X509_CERTIFICATES)
namespace Botan::PKCS11 {
X509_CertificateProperties::X509_CertificateProperties(const std::vector<uint8_t>& subject, const std::vector<uint8_t>& value)
: CertificateProperties(CertificateType::X509), m_subject(subject), m_value(value)
{
add_binary(AttributeType::Subject, m_subject);
add_binary(AttributeType::Value, m_value);
}
PKCS11_X509_Certificate::PKCS11_X509_Certificate(Session& session, ObjectHandle handle)
: Object(session, handle), X509_Certificate(unlock(get_attribute_value(AttributeType::Value)))
{
}
PKCS11_X509_Certificate::PKCS11_X509_Certificate(Session& session, const X509_CertificateProperties& props)
: Object(session, props), X509_Certificate(props.value())
{
}
}
#endif
|
soulgoast/blog-repository
|
source_code/src/goodman/javax/naming/ldap/SortKey.java
|
/*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package goodman.javax.naming.ldap;
import goodman.javax.naming.ldap.SortControl;
/**
* A sort key and its associated sort parameters.
* This class implements a sort key which is used by the LDAPv3
* Control for server-side sorting of search results as defined in
* <a href="http://www.ietf.org/rfc/rfc2891.txt">RFC 2891</a>.
*
* @since 1.5
* @see SortControl
* @author <NAME>
*/
public class SortKey {
/*
* The ID of the attribute to sort by.
*/
private String attrID;
/*
* The sort order. Ascending order, by default.
*/
private boolean reverseOrder = false;
/*
* The ID of the matching rule to use for ordering attribute values.
*/
private String matchingRuleID = null;
/**
* Creates the default sort key for an attribute. Entries will be sorted
* according to the specified attribute in ascending order using the
* ordering matching rule defined for use with that attribute.
*
* @param attrID The non-null ID of the attribute to be used as a sort
* key.
*/
public SortKey(String attrID) {
this.attrID = attrID;
}
/**
* Creates a sort key for an attribute. Entries will be sorted according to
* the specified attribute in the specified sort order and using the
* specified matching rule, if supplied.
*
* @param attrID The non-null ID of the attribute to be used as
* a sort key.
* @param ascendingOrder If true then entries are arranged in ascending
* order. Otherwise there are arranged in
* descending order.
* @param matchingRuleID The possibly null ID of the matching rule to
* use to order the attribute values. If not
* specified then the ordering matching rule
* defined for the sort key attribute is used.
*/
public SortKey(String attrID, boolean ascendingOrder,
String matchingRuleID) {
this.attrID = attrID;
reverseOrder = (! ascendingOrder);
this.matchingRuleID = matchingRuleID;
}
/**
* Retrieves the attribute ID of the sort key.
*
* @return The non-null Attribute ID of the sort key.
*/
public String getAttributeID() {
return attrID;
}
/**
* Determines the sort order.
*
* @return true if the sort order is ascending, false if descending.
*/
public boolean isAscending() {
return (! reverseOrder);
}
/**
* Retrieves the matching rule ID used to order the attribute values.
*
* @return The possibly null matching rule ID. If null then the
* ordering matching rule defined for the sort key attribute
* is used.
*/
public String getMatchingRuleID() {
return matchingRuleID;
}
}
|
lathroplabs/CodeLaboratoryAddin
|
node_modules/office-ui-fabric-react/lib/components/pickers/TagPicker/TagPicker.js
|
import { __assign, __extends } from "tslib";
import * as React from 'react';
import { styled, initializeComponentRef } from '../../../Utilities';
import { BasePicker } from '../BasePicker';
import { getStyles } from '../BasePicker.styles';
import { TagItem } from './TagItem';
import { TagItemSuggestion } from './TagItemSuggestion';
/**
* {@docCategory TagPicker}
*/
var TagPickerBase = /** @class */ (function (_super) {
__extends(TagPickerBase, _super);
function TagPickerBase(props) {
var _this = _super.call(this, props) || this;
initializeComponentRef(_this);
return _this;
}
TagPickerBase.defaultProps = {
onRenderItem: function (props) { return React.createElement(TagItem, __assign({}, props), props.item.name); },
onRenderSuggestionsItem: function (props) { return React.createElement(TagItemSuggestion, null, props.name); },
};
return TagPickerBase;
}(BasePicker));
export { TagPickerBase };
export var TagPicker = styled(TagPickerBase, getStyles, undefined, {
scope: 'TagPicker',
});
//# sourceMappingURL=TagPicker.js.map
|
SINTEF/Thermopack
|
addon/pycThermopack/pyctp/ljs_bh.py
|
# Support for python2
from __future__ import print_function
# Import ctypes
from ctypes import *
# Importing Numpy (math, arrays, etc...)
import numpy as np
# Import platform to detect OS
from sys import platform, exit
# Import os utils
from os import path
# Import thermo
from . import thermo
c_len_type = thermo.c_len_type
class ljs_bh(thermo.thermopack):
"""
Interface to LJS-BH
"""
def __init__(self):
"""
Initialize cubic specific function pointers
"""
# Load dll/so
super(ljs_bh, self).__init__()
# Options methods
self.s_ljs_bh_model_control = getattr(self.tp, self.get_export_name("lj_splined", "ljs_bh_model_control"))
# Init methods
self.s_eoslibinit_init_ljs_bh = getattr(self.tp, self.get_export_name("eoslibinit", "init_ljs"))
self.s_ljs_bh_get_pure_params = getattr(self.tp, self.get_export_name("lj_splined", "ljs_bh_get_pure_params"))
self.s_ljs_bh_set_pure_params = getattr(self.tp, self.get_export_name("lj_splined", "ljs_bh_set_pure_params"))
# LJS-BH specific methods
self.s_calc_ai_reduced_ljs_ex = getattr(self.tp, self.get_export_name("lj_splined", "calc_ai_reduced_ljs_ex"))
self.s_ljs_bh_get_bh_diameter_div_sigma = getattr(self.tp, self.get_export_name("lj_splined", "ljs_bh_get_bh_diameter_div_sigma"))
#################################
# Init
#################################
def init(self, parameter_reference="Default"):
"""Initialize Lennard-Jomes splined model based on Barker-Henderson perturbation theory
Args:
parameter_reference (str, optional): Which parameters to use?. Defaults to "Default".
"""
self.activate()
model = "BH"
model_string_c = c_char_p(model.encode('ascii'))
model_string_len = c_len_type(len(model))
ref_string_c = c_char_p(parameter_reference.encode('ascii'))
ref_string_len = c_len_type(len(parameter_reference))
self.s_eoslibinit_init_ljs_bh.argtypes = [c_char_p,
c_char_p,
c_len_type,
c_len_type]
self.s_eoslibinit_init_ljs_bh.restype = None
self.s_eoslibinit_init_ljs_bh(model_string_c,
ref_string_c,
model_string_len,
ref_string_len)
self.nc = 1
def get_sigma_eps(self):
"""Get particle size and well depth
Returns:
sigma (float): Particle diameter (m)
eps_depth_divk (float): Well depth divided by Boltzmann constant (K)
"""
self.activate()
sigma_c = c_double(0.0)
eps_depth_divk_c = c_double(0.0)
self.s_ljs_bh_get_pure_params.argtypes = [POINTER(c_double),
POINTER(c_double)]
self.s_ljs_bh_get_pure_params.restype = None
self.s_ljs_bh_get_pure_params(byref(sigma_c),
byref(eps_depth_divk_c))
return sigma_c.value, eps_depth_divk_c.value
def set_sigma_eps(self, sigma, eps_depth_divk):
"""Set particle size and well depth
Args:
sigma (float): Particle diameter (m)
eps_depth_divk (float): Well depth divided by Boltzmann constant (K)
"""
self.activate()
sigma_c = c_double(sigma)
eps_depth_divk_c = c_double(eps_depth_divk)
self.s_ljs_bh_set_pure_params.argtypes = [POINTER(c_double),
POINTER(c_double)]
self.s_ljs_bh_set_pure_params.restype = None
self.s_ljs_bh_set_pure_params(byref(sigma_c),
byref(eps_depth_divk_c))
#################################
# Model options
#################################
def model_control(self,
use_Lafitte_a3=False,
enable_chi_correction=True,
enable_hs=True,
enable_a1=True,
enable_a2=True,
enable_a3=True):
"""Model control. Enable/disable model terms.
Args:
use_Lafitte_a3 (bool): Enable/disable use of Lafitte model for a3 dispersion term. Defaults to False.
enable_chi_correction (bool): Enable/disable use of chi correction for a2 dispersion term. Defaults to True.
enable_hs (bool): Enable/disable hard-sphere term. Defaults to True.
enable_a1 (bool): Enable/disable use of a1 dispersion term. Defaults to True.
enable_a2 (bool): Enable/disable use of a2 dispersion term. Defaults to True.
enable_a3 (bool): Enable/disable use of a3 dispersion term. Defaults to True.
"""
self.activate()
use_Lafitte_a3_c = c_int(use_Lafitte_a3)
enable_chi_correction_c = c_int(enable_chi_correction)
enable_hs_c = c_int(enable_hs)
enable_a1_c = c_int(enable_a1)
enable_a2_c = c_int(enable_a2)
enable_a3_c = c_int(enable_a3)
self.s_ljs_bh_model_control.argtypes = [POINTER(c_int),
POINTER(c_int),
POINTER(c_int),
POINTER(c_int),
POINTER(c_int),
POINTER(c_int)]
self.s_ljs_bh_model_control.restype = None
self.s_ljs_bh_model_control(byref(use_Lafitte_a3_c),
byref(enable_chi_correction_c),
byref(enable_hs_c),
byref(enable_a1_c),
byref(enable_a2_c),
byref(enable_a3_c))
#################################
# LJS-BH specific methods
#################################
def get_pert_a(self,
T_star,
rho_star):
"""Get perturbation terms.
Args:
T_star (float): Reduced temperature.
rho_star (float): Reduced density.
Returns:
a1 (float): a1 dispersion term divided by epsilon.
a2 (float): a2 dispersion term divided by epsilon squared.
a3 (float): a3 dispersion term divided by epsilon cube.
"""
T_c = c_double(T_star)
rho_star_c = c_double(rho_star)
a1_c = c_double(0.0)
a2_c = c_double(0.0)
a3_c = c_double(0.0)
self.s_calc_ai_reduced_ljs_ex.argtypes = [POINTER(c_double),
POINTER(c_double),
POINTER(c_double),
POINTER(c_double),
POINTER(c_double)]
self.s_calc_ai_reduced_ljs_ex.restype = None
self.s_calc_ai_reduced_ljs_ex(byref(T_c),
byref(rho_star_c),
byref(a1_c),
byref(a2_c),
byref(a3_c))
return a1_c.value, a2_c.value, a3_c.value
def get_bh_diameter_div_sigma(self, T_star):
"""Get Barker-Henderson diameter.
Args:
T_star (float): Reduced temperature (-).
Returns:
d_bh (float): Barker-Henderson diameter divided by sigma (-).
"""
T_star_c = c_double(T_star)
d_bh_c = c_double(0.0)
self.s_ljs_bh_get_bh_diameter_div_sigma.argtypes = [POINTER(c_double),
POINTER(c_double)]
self.s_ljs_bh_get_bh_diameter_div_sigma.restype = None
self.s_ljs_bh_get_bh_diameter_div_sigma(byref(T_star_c),
byref(d_bh_c))
return d_bh_c.value
|
zz860926/sejs
|
example/designPattern/00-callback/02-promise/mainAwait.js
|
const web = require('./web')
async function main (url) {
try {
let text = await web.get(url)
console.log(text)
} catch (error) {
console.log('error:' + error)
}
}
main(process.argv[2])
|
7ossamamahmoud/Problem-Solving-Answers
|
Answers of Sheet#1 of Assuit University/L - The Brothers.cpp
|
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
string F1, S1, F2, S2;
cin >> F1 >> S1 >> F2 >> S2;
if (S1 == S2)
cout << "ARE Brothers";
else
cout << "NOT";
return 0;
}
|
frankgh/cassandra
|
test/distributed/org/apache/cassandra/distributed/test/DataResurrectionCheckTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.distributed.test;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
import org.apache.cassandra.config.CassandraRelevantProperties;
import org.apache.cassandra.config.StartupChecksOptions;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.IInvokableInstance;
import org.apache.cassandra.distributed.api.IIsolatedExecutor;
import org.apache.cassandra.exceptions.StartupException;
import org.apache.cassandra.io.util.File;
import org.apache.cassandra.service.DataResurrectionCheck;
import org.apache.cassandra.service.DataResurrectionCheck.Heartbeat;
import org.apache.cassandra.service.StartupChecks.StartupCheckType;
import org.apache.cassandra.utils.Clock.Global;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.cassandra.config.StartupChecksOptions.ENABLED_PROPERTY;
import static org.apache.cassandra.distributed.Cluster.build;
import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL;
import static org.apache.cassandra.service.DataResurrectionCheck.DEFAULT_HEARTBEAT_FILE;
import static org.apache.cassandra.service.DataResurrectionCheck.EXCLUDED_KEYSPACES_CONFIG_PROPERTY;
import static org.apache.cassandra.service.DataResurrectionCheck.EXCLUDED_TABLES_CONFIG_PROPERTY;
import static org.apache.cassandra.service.StartupChecks.StartupCheckType.check_data_resurrection;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class DataResurrectionCheckTest extends TestBaseImpl
{
@Test
public void testDataResurrectionCheck() throws Exception
{
try
{
// set it to 1 hour so check will be not updated after it is written, for test purposes
System.setProperty(CassandraRelevantProperties.CHECK_DATA_RESURRECTION_HEARTBEAT_PERIOD.getKey(), "3600000");
// start the node with the check enabled, it will just pass fine as there are not any user tables yet
// and system tables are young enough
try (Cluster cluster = build().withNodes(1)
.withDataDirCount(3) // we will expect heartbeat to be in the first data dir
.withConfig(config -> config.with(NATIVE_PROTOCOL)
.set("startup_checks",
getStartupChecksConfig(ENABLED_PROPERTY, "true")))
.start())
{
IInvokableInstance instance = cluster.get(1);
checkHeartbeat(instance);
for (String ks : new String[]{ "ks1", "ks2", "ks3" })
{
cluster.schemaChange("CREATE KEYSPACE " + ks + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};");
cluster.schemaChange(format("CREATE TABLE %s.tb1 (pk text PRIMARY KEY) WITH gc_grace_seconds = 10", ks));
cluster.schemaChange(format("CREATE TABLE %s.tb2 (pk text PRIMARY KEY)", ks));
}
AtomicReference<Throwable> throwable = new AtomicReference<>();
// periodically execute check on a running instance and wait until the exception is thrown on all keyspaces
// wait for all violations by Awaitility as due to nature how tables were created,
// they will not expire on their gc_grace_period exactly at the same time
await().timeout(1, MINUTES)
.pollInterval(5, SECONDS)
.until(() -> {
Throwable t = executeChecksOnInstance(instance);
if (t == null)
return false;
String message = t.getMessage();
if (!message.contains("ks1") || !message.contains("ks2") || !message.contains("ks3"))
{
return false;
}
throwable.set(t);
return true;
});
assertThat(throwable.get().getMessage(), containsString("Invalid tables"));
// returned tables in output are not in any particular order
// it is how they are returned from system tables
assertThat(throwable.get().getMessage(), containsString("ks1.tb1"));
assertThat(throwable.get().getMessage(), containsString("ks2.tb1"));
assertThat(throwable.get().getMessage(), containsString("ks3.tb1"));
// exclude failing keyspaces which already expired on their gc_grace_seconds, so we will pass the check
assertNull(executeChecksOnInstance(instance, EXCLUDED_KEYSPACES_CONFIG_PROPERTY, "ks1,ks2,ks3"));
// exclude failing tables which already expired on their gc_grace_seconds, so we will pass the check
assertNull(executeChecksOnInstance(instance, EXCLUDED_TABLES_CONFIG_PROPERTY, "ks1.tb1,ks2.tb1,ks3.tb1"));
// exclude failing tables, but not all of them,
// so check detects only one table violates the check
Throwable t = executeChecksOnInstance(instance, EXCLUDED_TABLES_CONFIG_PROPERTY, "ks1.tb1,ks2.tb1");
assertNotNull(t);
assertThat(t.getMessage(), containsString("Invalid tables: ks3.tb1"));
// shadow table exclusion with keyspace exclusion, we have not excluded ks3.tb1, but we excluded whole ks3
assertNull(executeChecksOnInstance(instance,
EXCLUDED_TABLES_CONFIG_PROPERTY, "ks1.tb1,ks2.tb1",
EXCLUDED_KEYSPACES_CONFIG_PROPERTY, "ks3"));
}
}
finally
{
System.clearProperty(CassandraRelevantProperties.CHECK_DATA_RESURRECTION_HEARTBEAT_PERIOD.getKey());
}
}
private Throwable executeChecksOnInstance(IInvokableInstance instance, final String... config)
{
assert config.length % 2 == 0;
return instance.callsOnInstance((IIsolatedExecutor.SerializableCallable<Throwable>) () ->
{
try
{
DataResurrectionCheck check = new DataResurrectionCheck();
StartupChecksOptions startupChecksOptions = new StartupChecksOptions();
startupChecksOptions.enable(check_data_resurrection);
for (int i = 0; i < config.length - 1; i = i + 2)
startupChecksOptions.set(check_data_resurrection, config[i], config[i + 1]);
check.execute(startupChecksOptions);
return null;
}
catch (StartupException e)
{
return e;
}
}).call();
}
private Map<StartupCheckType, Map<String, Object>> getStartupChecksConfig(String... configs)
{
return new EnumMap<StartupCheckType, Map<String, Object>>(StartupCheckType.class)
{{
put(check_data_resurrection,
new HashMap<String, Object>()
{{
for (int i = 0; i < configs.length - 1; i = i + 2)
put(configs[i], configs[i + 1]);
}});
}};
}
private void checkHeartbeat(IInvokableInstance instance) throws Exception
{
File heartbeatFile = new File(((String[]) instance.config().get("data_file_directories"))[0],
DEFAULT_HEARTBEAT_FILE);
assertTrue(heartbeatFile.exists());
Heartbeat heartbeat = Heartbeat.deserializeFromJsonFile(heartbeatFile);
assertNotNull(heartbeat.lastHeartbeat);
assertTrue(heartbeat.lastHeartbeat.toEpochMilli() < Global.currentTimeMillis());
}
}
|
ehabhelmy/jedaah_attractions
|
app/src/main/java/com/spade/ja/ui/Home/profile/liked_events/LikedEventsContract.java
|
<filename>app/src/main/java/com/spade/ja/ui/Home/profile/liked_events/LikedEventsContract.java
package com.spade.ja.ui.Home.profile.liked_events;
import com.spade.ja.ui.Base.listener.BaseView;
import com.spade.ja.ui.Base.listener.ErrorView;
import com.spade.ja.ui.Base.listener.ProgressView;
import com.spade.ja.ui.Home.explore.pojo.Event;
import com.spade.ja.usecase.Unsubscribable;
import java.util.List;
/**
* Created by Romisaa on 12/17/2017.
*/
public class LikedEventsContract {
interface View extends BaseView, ErrorView, ProgressView {
void setupAllEvents(List<Event> events);
void showNoEvents();
}
interface Presenter extends Unsubscribable {
void like(int id);
void showEventInner(int id);
}
}
|
bcs4313/WebCheckers-Project-Archived
|
src/main/java/com/webcheckers/model/RuleSystem/InitJumpRule.java
|
<filename>src/main/java/com/webcheckers/model/RuleSystem/InitJumpRule.java
package com.webcheckers.model.RuleSystem;
import com.webcheckers.model.GameBoard;
public class InitJumpRule extends Rule {
// handler for all basic rules
private final RuleMaster master;
// if not null, force ONLY a check at this position
private final int[] forceCheck;
// Defined pieces to analyze
private final GameBoard.cells attackerKing;
private final GameBoard.cells attackerBasic;
private final GameBoard.cells victimKing;
private final GameBoard.cells victimBasic;
/**
* Enhanced Rule Constructor
* @param master parent root of this Rule
* @param teamTarget whose turn is it currently? (used for orientation)
* @param forceCheck array [y, x] that if not null forces this rule to ONLY check here
*/
public InitJumpRule(RuleMaster master, GameBoard.activeColors teamTarget, int[] forceCheck) {
super(master);
this.master = master;
this.forceCheck = forceCheck;
if(teamTarget == GameBoard.activeColors.WHITE)
{
attackerKing = GameBoard.cells.WK;
attackerBasic = GameBoard.cells.W;
victimKing = GameBoard.cells.RK;
victimBasic = GameBoard.cells.R;
}
else
{
attackerKing = GameBoard.cells.RK;
attackerBasic = GameBoard.cells.R;
victimKing = GameBoard.cells.WK;
victimBasic = GameBoard.cells.W;
}
}
/**
* Checks whether or not a jump CAN be performed,
* start of a turn.
* @param b_before board state to analyze
* @param b_after special case, should be NULL
* @return true if jump must be performed, false otherwise
*/
@Override
public boolean isTriggered(GameBoard.cells[][] b_before, GameBoard.cells[][] b_after) {
GameBoard.cells[][] b_input;
// flip board if its white's turn
if(master.getTurn() == GameBoard.activeColors.WHITE)
{
System.out.println("flipped board");
b_input = flipBoard(b_before);
}
else
{
b_input = b_before;
}
if(forceCheck == null) {
System.out.println("MULTICHECK");
// we must check every possible situation on the board
// (only for the team in question though)
for (int y = 0; y < b_input.length; y++) // note that jumps in certain parts of
{
for (int x = 0; x < b_input[y].length; x++) {
GameBoard.cells cell = b_input[y][x];
if (cell == attackerKing || cell == attackerBasic) {
System.out.println("Potential Attacker identified: " + cell.toString());
System.out.println("At y: " + y + " x: " + x);
if (hasTarget(b_input, y, x)) {
System.out.println("Returning true...");
return true;
}
}
}
}
}
else
{
System.out.println("SINGLECHECK");
int y = forceCheck[0];
int x = forceCheck[1];
System.out.println("looking at y: " + y + "x: " + x);
GameBoard.cells cell = b_input[y][x];
if (cell == attackerKing || cell == attackerBasic) {
System.out.println("Potential Attacker identified: " + cell.toString());
System.out.println("At y: " + y + " x: " + x);
if (hasTarget(b_input, y, x)) {
System.out.println("Returning true...");
return true;
}
}
else
{
System.out.println("??? = " + cell.toString());
}
}
return false;
}
/**
* Checks to see if a checker has something to jump over
* at its location.
* @return Is there an opposing checker to jump over?
*/
public boolean hasTarget(GameBoard.cells[][] b_before, int y, int x)
{
GameBoard.cells cell = b_before[y][x];
// targets that anything can capture
GameBoard.cells target1 = b_before[Math.max(y - 1, 0)][Math.min(x + 1, 7)];
GameBoard.cells target2 = b_before[Math.max(y - 1, 0)][Math.max(x - 1, 0)];
// targets that only kings can capture
GameBoard.cells target3 = b_before[Math.min(y + 1, 7)][Math.min(x + 1, 7)];
GameBoard.cells target4 = b_before[Math.min(y + 1, 7)][Math.max(x - 1, 0)];
System.out.println("t1: " + target1.toString());
System.out.println("t2: " + target2.toString());
System.out.println("t3: " + target3.toString());
System.out.println("t4: " + target4.toString());
System.out.println("S0");
// basic checks
if(target1 == victimBasic || target1 == victimKing)
{
System.out.println("Scope1");
if(b_before[Math.max(y - 2, 0)][Math.min(x + 2, 7)] == GameBoard.cells.E)
{
return true;
}
}
if(target2 == victimBasic || target2 == victimKing)
{
System.out.println("Scope2");
if(b_before[Math.max(y - 2, 0)][Math.max(x - 2, 0)] == GameBoard.cells.E)
{
return true;
}
}
// king checks
if(target3 == victimBasic || target3 == victimKing)
{
if(cell == attackerKing)
{
System.out.println("Scope3");
if(b_before[Math.min(y + 2, 7)][Math.min(x + 2, 7)] == GameBoard.cells.E)
{
return true;
}
}
}
if(target4 == victimBasic || target4 == victimKing)
{
if(cell == attackerKing)
{
System.out.println("Scope4");
if(b_before[Math.min(y + 2, 7)][Math.max(x - 2, 0)] == GameBoard.cells.E)
{
return true;
}
}
}
System.out.println("S1");
return false;
}
// the return value of isTriggered is not used, so nothing should occur
@Override
public void action() {
// not applicable
}
}
|
richarddd/ably-js
|
spec/browser/connection.test.js
|
'use strict';
define(['ably', 'shared_helper'], function(Ably, helper) {
var exports = {},
_exports = {},
closeAndFinish = helper.closeAndFinish,
monitorConnection = helper.monitorConnection,
simulateDroppedConnection = helper.simulateDroppedConnection,
transportPreferenceName = 'ably-transport-preference';
function supportedBrowser(test) {
if(document.body.ononline === undefined) {
console.log('Online events not supported; skipping connection.test.js');
return false;
}
if(!window.WebSocket || !window.localStorage) {
console.log('Websockets or local storage not supported; skipping connection.test.js');
return false;
}
// IE doesn't support creating your own events with new
try {
var testEvent = new Event('foo');
} catch(e) {
console.log('On IE; skipping connection.test.js');
return false;
}
return true;
}
function eraseSession(name) {
window.sessionStorage && window.sessionStorage.removeItem(name);
}
exports.setup_realtime = function(test) {
test.expect(1);
helper.setupApp(function(err) {
if(err) {
test.ok(false, helper.displayError(err));
} else {
test.ok(true, 'app set up');
}
test.done();
});
/* Ensure session is clean for persistance tests */
eraseSession('ably-connection-recovery');
};
exports.device_going_offline_causes_disconnected_state = function(test) {
var realtime = helper.AblyRealtime(),
connection = realtime.connection,
offlineEvent = new Event('offline', {'bubbles': true});
test.expect(3);
monitorConnection(test, realtime);
connection.once('connected', function() {
var connectedAt = new Date().getTime()
connection.once('disconnected', function() {
var disconnectedAt = new Date().getTime();
test.ok(disconnectedAt - connectedAt < 1500, 'Offline event caused connection to move to the disconnected state');
connection.once('connecting', function() {
var reconnectingAt = new Date().getTime();
test.ok(reconnectingAt - disconnectedAt < 1500, 'Client automatically reattempts connection without waiting for disconnect timeout, even if the state is still offline');
connection.once('connected', function() {
test.ok(true, 'Successfully reconnected');
closeAndFinish(test, realtime);
})
});
})
// simulate offline event, expect connection moves to disconnected state and waits to retry connection
document.dispatchEvent(offlineEvent);
});
};
exports.device_going_online_causes_disconnected_connection_to_reconnect_immediately = function(test) {
/* Give up trying to connect fairly quickly */
var realtime = helper.AblyRealtime({realtimeRequestTimeout: 1000}),
connection = realtime.connection,
onlineEvent = new Event('online', {'bubbles': true});
test.expect(3);
monitorConnection(test, realtime);
// simulate the internet being failed by stubbing out tryATransport to foil
// the initial connection. (No immediate reconnect attempt since it was never
// connected in the first place)
var oldTransport = connection.connectionManager.tryATransport;
connection.connectionManager.tryATransport = function(){};
connection.once('disconnected', function() {
var disconnectedAt = new Date();
test.ok(connection.state == 'disconnected', 'Connection should still be disconnected before we trigger it to connect');
connection.once('connecting', function() {
test.ok(new Date() - disconnectedAt < 1500, 'Online event should have caused the connection to enter the connecting state without waiting for disconnect timeout');
connection.once('connected', function() {
test.ok(true, 'Successfully reconnected');
closeAndFinish(test, realtime);
})
});
// restore the 'internet' and simulate an online event
connection.connectionManager.tryATransport= oldTransport;
document.dispatchEvent(onlineEvent);
});
};
exports.device_going_online_causes_suspended_connection_to_reconnect_immediately = function(test) {
/* move to suspended state after 2s of being disconnected */
var realtime = helper.AblyRealtime({ disconnectedRetryTimeout: 500, realtimeRequestTimeout: 500, connectionStateTtl: 2000 }),
connection = realtime.connection,
onlineEvent = new Event('online', {'bubbles': true});
// Easiest way to have all transports attempt fail it to stub out tryATransport
connection.connectionManager.tryATransport = function(){};
test.expect(2);
connection.on('failed', function () {
test.ok(false, 'connection to server failed');
closeAndFinish(test, realtime);
});
connection.once('suspended', function() {
var suspendedAt = new Date();
test.ok(connection.state == 'suspended', 'Connection should still be suspended before we trigger it to connect');
connection.once('connecting', function() {
test.ok(new Date() - suspendedAt < 1500, 'Online event should have caused the connection to enter the connecting state without waiting for suspended timeout');
closeAndFinish(test, realtime);
});
// simulate online event
document.dispatchEvent(onlineEvent);
});
};
/* uses internal realtime knowledge of the format of the connection key to
* check if a connection key is the result of a successful recovery of another */
function sameConnection(keyA, keyB) {
return keyA.split('-')[0] === keyB.split('-')[0];
}
exports.page_refresh_with_recovery = function(test) {
var realtimeOpts = { recover: function(lastConnectionDetails, cb) { cb(true); } },
realtime = helper.AblyRealtime(realtimeOpts),
refreshEvent = new Event('beforeunload', {'bubbles': true});
test.expect(2);
monitorConnection(test, realtime);
realtime.connection.once('connected', function() {
var connectionKey = realtime.connection.key;
document.dispatchEvent(refreshEvent);
test.equal(realtime.connection.state, 'connected', 'check connection state initially unaffected by page refresh');
simulateDroppedConnection(realtime);
var newRealtime = helper.AblyRealtime(realtimeOpts);
newRealtime.connection.once('connected', function() {
test.ok(sameConnection(connectionKey, newRealtime.connection.key), 'Check new realtime recovered the connection from the cookie');
closeAndFinish(test, [realtime, newRealtime]);
});
});
};
exports.page_refresh_persist_with_denied_recovery = function(test) {
var realtimeOpts = { recover: function(lastConnectionDetails, cb) { cb(false); } };
var realtime = helper.AblyRealtime(realtimeOpts),
refreshEvent = new Event('beforeunload', {'bubbles': true});
test.expect(2);
monitorConnection(test, realtime);
realtime.connection.once('connected', function() {
var connectionKey = realtime.connection.key;
document.dispatchEvent(refreshEvent);
test.equal(realtime.connection.state, 'connected', 'check connection state initially unaffected by page refresh');
simulateDroppedConnection(realtime);
var newRealtime = helper.AblyRealtime(realtimeOpts);
newRealtime.connection.once('connected', function() {
test.ok(!sameConnection(connectionKey, newRealtime.connection.key), 'Check new realtime created a new connection');
closeAndFinish(test, [realtime, newRealtime]);
});
monitorConnection(test, newRealtime);
});
};
exports.page_refresh_with_close_on_unload = function(test) {
var realtime = helper.AblyRealtime({ closeOnUnload: true }),
refreshEvent = new Event('beforeunload', {'bubbles': true});
test.expect(1);
monitorConnection(test, realtime);
realtime.connection.once('connected', function() {
var connectionKey = realtime.connection.key;
document.dispatchEvent(refreshEvent);
var state = realtime.connection.state;
test.ok(state == 'closing' || state == 'closed', 'check page refresh triggered a close');
test.done();
});
};
exports.page_refresh_with_manual_recovery = function(test) {
var realtime = helper.AblyRealtime({ closeOnUnload: false }),
refreshEvent = new Event('beforeunload', {'bubbles': true});
test.expect(2);
monitorConnection(test, realtime);
realtime.connection.once('connected', function() {
var connectionKey = realtime.connection.key,
recoveryKey = realtime.connection.recoveryKey;
document.dispatchEvent(refreshEvent);
test.equal(realtime.connection.state, 'connected', 'check connection state initially unaffected by page refresh');
simulateDroppedConnection(realtime);
var newRealtime = helper.AblyRealtime({ recover: recoveryKey });
newRealtime.connection.once('connected', function() {
test.ok(sameConnection(connectionKey, newRealtime.connection.key), 'Check new realtime recovered the old');
closeAndFinish(test, [realtime, newRealtime]);
});
});
};
exports.persist_preferred_transport = function(test) {
test.expect(1);
var realtime = helper.AblyRealtime();
realtime.connection.connectionManager.on(function(transport) {
if(this.event === 'transport.active' && transport.shortName === 'web_socket') {
test.equal(window.localStorage.getItem(transportPreferenceName), JSON.stringify({value: 'web_socket'}));
closeAndFinish(test, realtime);
}
});
monitorConnection(test, realtime);
};
exports.use_persisted_transport0 = function(test) {
test.expect(1);
var transportPreferenceName = 'ably-transport-preference';
window.localStorage.setItem(transportPreferenceName, JSON.stringify({value: 'web_socket'}));
var realtime = helper.AblyRealtime();
realtime.connection.connectionManager.on(function(transport) {
if(this.event === 'transport.active') {
test.equal(transport.shortName, 'web_socket');
closeAndFinish(test, realtime);
}
});
monitorConnection(test, realtime);
};
exports.use_persisted_transport1 = function(test) {
test.expect(1);
window.localStorage.setItem(transportPreferenceName, JSON.stringify({value: 'xhr_streaming'}));
var realtime = helper.AblyRealtime();
realtime.connection.connectionManager.on(function(transport) {
if(this.event === 'transport.active') {
test.equal(transport.shortName, 'xhr_streaming');
closeAndFinish(test, realtime);
}
});
monitorConnection(test, realtime);
};
exports.browser_transports = function(test) {
test.expect(2);
var realtime = helper.AblyRealtime();
test.equal(realtime.connection.connectionManager.baseTransport, 'xhr_polling');
test.deepEqual(realtime.connection.connectionManager.upgradeTransports, ['xhr_streaming', 'web_socket']);
closeAndFinish(test, realtime);
}
return module.exports = supportedBrowser() ? helper.withTimeout(exports) : {};
});
|
priyankamalviya/reactmaterialuisample
|
src/components/BasicExamples/PropsExample.js
|
import React, { Component, PropTypes } from 'react';
export default class PropsExample extends Component{
constructor(props) {
super(props)
};
render(){
const {intl} = this.props;
return (
<div>
<h3>Props Example</h3>
<p>This example demonstartes how to use a react component with props.</p>
<p>Because we use redux the state is immutable. To get a state value we use redux connect.</p>
<p>And the prop that we us in this componente is intl where we get the locale value:</p>
<h4>{intl.locale}</h4>
<p>If you change the language in the settings the value abow would also change.</p>
</div>
);
}
};
PropsExample.propTypes = {
intl: PropTypes.object.isRequired,
}
|
siebenfarben/webdriverio
|
test/spec/functional/endAll.js
|
const WebdriverIO = require('../../../')
describe('endAll', () => {
it('should delete multiple sessions', async function () {
// at the beginning there is only one session
(await this.client.sessions()).value.should.have.length(1)
// create two new session
const testDriverA = WebdriverIO.remote({
desiredCapabilities: {
browserName: 'phantomjs'
}
})
await testDriverA.init()
const testDriverB = WebdriverIO.remote({
desiredCapabilities: {
browserName: 'phantomjs'
}
})
await testDriverB.init();
// now we should have two sessions
(await this.client.sessions()).value.should.have.length(3)
// end all sessions
await testDriverB.endAll();
// now there should be only one session again
(await this.client.sessions()).value.should.have.length(0)
})
after(async function () {
// reinitialise the session
this.client.requestHandler.sessionID = null
await this.client.init()
})
})
|
alexavila150/luciddb
|
fennel/calculator/RegisterReference.cpp
|
/*
// Licensed to DynamoBI Corporation (DynamoBI) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. DynamoBI licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
*/
#include "fennel/common/CommonPreamble.h"
#include "fennel/calculator/RegisterReference.h"
#include "fennel/calculator/Calculator.h"
#include "boost/format.hpp"
using boost::format;
FENNEL_BEGIN_CPPFILE("$Id$");
RegisterSetBinding::~RegisterSetBinding()
{
if (ownTheBase) {
delete base;
}
delete[] datumAddr;
}
RegisterSetBinding::RegisterSetBinding(TupleData* base, bool ownIt)
: ownTheBase(ownIt), base(base)
{
assert(base);
ncols = base->size();
datumAddr = new PConstBuffer[ncols];
for (int i = 0; i < ncols; i++) {
const TupleDatum& baseCol = (*base)[i];
datumAddr[i] = baseCol.pData;
}
}
// Rebind to new Tuple as base. Make sure old base and newBase have the same
// size.
void RegisterSetBinding::rebind(
TupleData* newBase, bool ownIt)
{
assert(newBase);
assert(ncols == newBase->size());
if (ownTheBase) {
// previous base owned by me.
delete base;
}
base = newBase;
ownTheBase = ownIt;
ncols = base->size();
for (int i = 0; i < ncols; i++) {
const TupleDatum& baseCol = (*base)[i];
datumAddr[i] = baseCol.pData;
}
}
RegisterSetBinding::RegisterSetBinding(
TupleData* base,
const TupleData* shadow,
bool ownIt)
: ownTheBase(ownIt),
base(base)
{
assert(base);
ncols = base->size();
assert(shadow->size() == ncols);
datumAddr = new PConstBuffer[ncols];
for (int i = 0; i < ncols; i++) {
const TupleDatum& baseCol = (*base)[i];
const TupleDatum& shadowCol = (*shadow)[i];
datumAddr[i] = shadowCol.pData;
// check that SHADOW coincides with BASE
if (baseCol.pData) {
assert(baseCol.pData == shadowCol.pData);
} else {
assert(shadowCol.pData);
}
}
}
// Rebind to new Tuple as base. Make sure old base and newBase have the same
// size.
void RegisterSetBinding::rebind(
TupleData* newBase, const TupleData* shadow, bool ownIt)
{
assert(newBase);
assert(ncols == newBase->size());
if (ownTheBase) {
// previous base owned by me.
delete base;
}
base = newBase;
ownTheBase = ownIt;
ncols = base->size();
assert(shadow->size() == ncols);
for (int i = 0; i < ncols; i++) {
const TupleDatum& baseCol = (*base)[i];
const TupleDatum& shadowCol = (*shadow)[i];
datumAddr[i] = shadowCol.pData;
// check that SHADOW coincides with BASE
if (baseCol.pData) {
assert(baseCol.pData == shadowCol.pData);
} else {
assert(shadowCol.pData);
}
}
}
void
RegisterReference::setCalc(Calculator* calcP) {
mRegisterSetP = calcP->mRegisterSetBinding;
mRegisterSetDescP = calcP->mRegisterSetDescriptor;
mResetP = &(calcP->mRegisterReset);
mPDynamicParamManager = calcP->getDynamicParamManager();
if (mSetIndex == EOutput && calcP->mOutputRegisterByReference) {
//! See Calculator#outputRegisterByReference()
mProp |= (EPropByRefOnly | EPropReadOnly);
}
}
void
RegisterReference::cachePointer() {
if (mProp & (EPropCachePointer | EPropPtrReset)) {
TupleDatum *bind = getBinding();
mPData = const_cast<PBuffer>(bind->pData);
mCbData = bind->cbData;
// Next 3 lines clarify complex 4th line:
// TupleDescriptor* tupleDescP = mRegisterSetDescP[mSetIndex];
// TupleAttributeDescriptor* attrP = &((*tupleDescP)[mIndex]);
// mCbStorage = attrP->cbStorage;
mCbStorage = ((*(mRegisterSetDescP[mSetIndex]))[mIndex]).cbStorage;
mCachePtrModified = false;
}
}
void
RegisterReference::setDefaultProperties()
{
switch (mSetIndex) {
case ELiteral:
mProp = KLiteralSetDefault;
break;
case EInput:
mProp = KInputSetDefault;
break;
case EOutput:
mProp = KOutputSetDefault;
break;
case ELocal:
mProp = KLocalSetDefault;
break;
case EStatus:
mProp = KStatusSetDefault;
break;
default:
mProp = EPropNone;
}
}
string
RegisterReference::toString() const
{
return boost::io::str(format("[S%d I%lu]") % mSetIndex % mIndex);
}
FENNEL_END_CPPFILE("$Id$");
// End RegisterReference.cpp
|
httplab/roadie
|
spec/lib/roadie/test_provider_spec.rb
|
<filename>spec/lib/roadie/test_provider_spec.rb
# frozen_string_literal: true
require 'spec_helper'
require 'roadie/rspec'
describe TestProvider do
subject(:provider) { TestProvider.new }
it_behaves_like "roadie asset provider", valid_name: "existing.css", invalid_name: "invalid.css" do
subject { TestProvider.new "existing.css" => "" }
end
it "finds styles from a predefined hash" do
provider = TestProvider.new({
"foo.css" => "a { color: red; }",
"bar.css" => "body { color: green; }",
})
expect(provider.find_stylesheet("foo.css").to_s).not_to include("body")
expect(provider.find_stylesheet("bar.css").to_s).to include("body")
expect(provider.find_stylesheet("baz.css")).to be_nil
end
it "can have a default for missing entries" do
provider = TestProvider.new({
"foo.css" => "a { color: red; }",
:default => "body { color: green; }",
})
expect(provider.find_stylesheet("foo.css").to_s).not_to include("body")
expect(provider.find_stylesheet("bar.css").to_s).to include("body")
end
end
|
iopsthecloud/aspiratv
|
matcher/matcher.go
|
package matcher
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
"github.com/simulot/aspiratv/metadata/nfo"
)
// MatchRequest holds criterions for selecting show
type MatchRequest struct {
Provider string
// Fields for matching
Show string
Title string
// ShowID string // Future use
// TitleID string // Future use
// Pitch string // Future use
// Playlist string // Playlist search is implemented in providers.
MaxAgedDays int // Retrive media younger than MaxAgedDays when not zero
// Fields for managing download
Type nfo.ShowType // Determine the type of show for file layout and naming
Destination string // Download base destination code defined in config
ShowRootPath string `json:"ShowPath"` // Show/Movie path. Bypass destinations. For expisodes, actual season will append to the path
SeasonPathTemplate TemplateString // Template for season path, can be empty to skip season in path. When missing uses default naming
ShowNameTemplate TemplateString // Template for the name of mp4 file, can't be empty. When missing, uses default naming
RetentionDays int // Media retention time, when not zero the system will delete old files
TitleFilter Filter // ShowTitle or Episode title must match this regexp to be downloaded
TitleExclude Filter // ShowTitle and Episode title must not match this regexp to be downloaded
KeepBonus bool // When trie bonuses and trailer are retrieved
Force bool // True to force medias
}
func (m MatchRequest) Validate(destinations map[string]string) error {
if m.Show == "" {
return errors.New("Missing show name")
}
if m.Provider == "" {
return errors.New("Missing provider")
}
if m.ShowRootPath == "" && m.Destination == "" {
return errors.New("Missing show path or destination")
}
if m.ShowRootPath != "" {
p := os.ExpandEnv(m.ShowRootPath)
p, err := filepath.Abs(p)
if err != nil {
return err
}
err = os.MkdirAll(p, 0755)
if err != nil {
return err
}
m.ShowRootPath = p
}
return nil
}
func (m MatchRequest) IsTitleMatch(title string) bool {
if m.TitleExclude.Regexp != nil {
if m.TitleExclude.Regexp.MatchString(title) {
return false
}
}
if m.TitleFilter.Regexp != nil {
if m.TitleFilter.Regexp.MatchString(title) {
return true
}
}
title = strings.ToUpper(strings.TrimSpace(title))
return strings.Contains(title, m.Title)
}
// Filter is a wrapper for regexp
// Implement JSON and Value interfaces
type Filter struct {
*regexp.Regexp
}
//MarshalJSON returns a string from regexp and place it in the JSON stream
func (t Filter) MarshalJSON() ([]byte, error) {
return []byte(`"` + t.String() + `"`), nil
}
// UnmarshalJSON takes the string from the stream and compile the regexp
func (t *Filter) UnmarshalJSON(b []byte) error {
if b[0] == '"' {
b = b[1 : len(b)-1]
}
t.Regexp = nil
if len(b) > 0 {
return t.Set(string(b))
}
return nil
}
// Set value
func (t *Filter) Set(s string) error {
re, err := regexp.Compile(s)
if err != nil {
return err
}
t.Regexp = re
return nil
}
func (t Filter) String() string {
if t.Regexp != nil {
return t.Regexp.String()
}
return ""
}
// Type used in command line
func (Filter) Type() string { return "regexp-filter" }
type TemplateString struct {
S string
T *template.Template
}
func (t TemplateString) String() string {
return t.S
}
func (t TemplateString) Type() string {
return "name-template"
}
func (t *TemplateString) Set(s string) error {
var err error
t.T, err = template.New("").Parse(s)
if err != nil {
return err
}
t.S = s
return nil
}
//MarshalJSON returns a string from regexp and place it in the JSON stream
func (t TemplateString) MarshalJSON() ([]byte, error) {
return []byte(`"` + t.S + `"`), nil
}
// UnmarshalJSON takes the string from the stream and compile the template
func (t *TemplateString) UnmarshalJSON(b []byte) error {
var err error
// if b[0] == '"' {
// b = b[1 : len(b)-1]
// }
err = json.Unmarshal(b, &t.S)
if err != nil {
return err
}
t.T, err = template.New("").Parse(t.S)
if err != nil {
return err
}
return nil
}
// Accepted check if ShowTitle or episode Title matches the filter
func (m *MatchRequest) Accepted(n *nfo.MediaInfo) bool {
if m.TitleExclude.Regexp != nil {
if m.TitleExclude.Regexp.MatchString(n.Showtitle) {
return false
}
if m.TitleExclude.Regexp.MatchString(n.Title) {
return false
}
}
if m.TitleFilter.Regexp != nil {
if m.TitleFilter.Regexp.MatchString(n.Showtitle) {
return true
}
if m.TitleFilter.Regexp.MatchString(n.Title) {
return true
}
return false
}
return true
}
|
Pandinosaurus/geojs
|
src/version.js
|
<gh_stars>100-1000
/* global GEO_VERSION */
/**
* The current geojs version.
*
* @alias geo.version
* @constant
* @type {string}
*/
module.exports = GEO_VERSION;
|
zhaomingjun/svg-path-commander
|
src/math/polygonLength.js
|
import distanceSquareRoot from './distanceSquareRoot';
/**
* d3-polygon-length
* https://github.com/d3/d3-polygon
*
* Returns the perimeter of a polygon.
*
* @param {number[][]} polygon an array of coordinates
* @returns {number} the polygon length
*/
export default function polygonLength(polygon) {
return polygon.reduce((length, point, i) => {
if (i) {
// @ts-ignore
return length + distanceSquareRoot(polygon[i - 1], point);
}
return 0;
}, 0);
}
|
rafaelmartins/blogc
|
tests/blogc/check_sysinfo.c
|
<reponame>rafaelmartins/blogc
/*
* blogc: A blog compiler.
* Copyright (C) 2014-2019 <NAME> <<EMAIL>>
*
* This program can be distributed under the terms of the BSD License.
* See the file LICENSE.
*/
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "../../src/common/error.h"
#include "../../src/common/utils.h"
#include "../../src/blogc/sysinfo.h"
#ifdef HAVE_SYSINFO_DATETIME
#include <time.h>
#endif
#ifdef HAVE_SYSINFO_HOSTNAME
int
__wrap_gethostname(char *name, size_t len)
{
assert_int_equal(len, 1024);
const char *f = mock_type(const char*);
if (f != NULL)
strcpy(name, f);
return mock_type(int);
}
#endif
char*
__wrap_getenv(const char *name)
{
return mock_type(char*);
}
#ifdef HAVE_SYSINFO_DATETIME
time_t
__wrap_time(time_t *tloc)
{
*tloc = mock_type(time_t);
return *tloc;
}
static struct tm tm = {
.tm_sec = 1,
.tm_min = 2,
.tm_hour = 3,
.tm_mday = 4,
.tm_mon = 5,
.tm_year = 6,
.tm_wday = 6,
.tm_yday = 7,
.tm_isdst = 0,
};
struct tm*
__wrap_gmtime(const time_t *timep)
{
if (*timep == 2)
return NULL;
return &tm;
}
#endif
char*
__wrap_bc_file_get_contents(const char *path, bool utf8, size_t *len, bc_error_t **err)
{
assert_string_equal(path, "/proc/1/cgroup");
assert_false(utf8);
char *rv = mock_type(char*);
*len = strlen(rv);
return rv;
}
static void
test_sysinfo_get_hostname(void **state)
{
will_return(__wrap_gethostname, NULL);
will_return(__wrap_gethostname, -1);
char *f = blogc_sysinfo_get_hostname();
assert_null(f);
will_return(__wrap_gethostname, "bola");
will_return(__wrap_gethostname, 0);
f = blogc_sysinfo_get_hostname();
assert_non_null(f);
assert_string_equal(f, "bola");
free(f);
}
static void
test_sysinfo_inject_hostname(void **state)
{
bc_trie_t *t = bc_trie_new(free);
will_return(__wrap_gethostname, NULL);
will_return(__wrap_gethostname, -1);
blogc_sysinfo_inject_hostname(t);
assert_int_equal(bc_trie_size(t), 0);
will_return(__wrap_gethostname, "bola");
will_return(__wrap_gethostname, 0);
blogc_sysinfo_inject_hostname(t);
assert_int_equal(bc_trie_size(t), 1);
assert_string_equal(bc_trie_lookup(t, "BLOGC_SYSINFO_HOSTNAME"), "bola");
bc_trie_free(t);
}
static void
test_sysinfo_get_username(void **state)
{
will_return(__wrap_getenv, NULL);
char *f = blogc_sysinfo_get_username();
assert_null(f);
will_return(__wrap_getenv, "bola");
f = blogc_sysinfo_get_username();
assert_non_null(f);
assert_string_equal(f, "bola");
free(f);
}
static void
test_sysinfo_inject_username(void **state)
{
bc_trie_t *t = bc_trie_new(free);
will_return(__wrap_getenv, NULL);
blogc_sysinfo_inject_username(t);
assert_int_equal(bc_trie_size(t), 0);
will_return(__wrap_getenv, "bola");
blogc_sysinfo_inject_username(t);
assert_int_equal(bc_trie_size(t), 1);
assert_string_equal(bc_trie_lookup(t, "BLOGC_SYSINFO_USERNAME"), "bola");
bc_trie_free(t);
}
static void
test_sysinfo_get_datetime(void **state)
{
will_return(__wrap_time, -1);
char *f = blogc_sysinfo_get_datetime();
assert_null(f);
will_return(__wrap_time, 2);
f = blogc_sysinfo_get_datetime();
assert_null(f);
will_return(__wrap_time, 1);
f = blogc_sysinfo_get_datetime();
assert_non_null(f);
assert_string_equal(f, "1906-06-04 03:02:01");
free(f);
}
static void
test_sysinfo_inject_datetime(void **state)
{
bc_trie_t *t = bc_trie_new(free);
will_return(__wrap_time, -1);
blogc_sysinfo_inject_datetime(t);
assert_int_equal(bc_trie_size(t), 0);
will_return(__wrap_time, 2);
blogc_sysinfo_inject_datetime(t);
assert_int_equal(bc_trie_size(t), 0);
will_return(__wrap_time, 1);
blogc_sysinfo_inject_datetime(t);
assert_int_equal(bc_trie_size(t), 1);
assert_string_equal(bc_trie_lookup(t, "BLOGC_SYSINFO_DATETIME"), "1906-06-04 03:02:01");
bc_trie_free(t);
}
static void
test_sysinfo_get_inside_docker(void **state)
{
// the "positive" case was already tested in check_funcvars. this is done
// this way because this function caches the results in a global variable.
will_return(__wrap_bc_file_get_contents, bc_strdup("bola"));
assert_false(blogc_sysinfo_get_inside_docker());
}
// the blogc_sysinfo_inject_inside_docker() function was already indirectly
// tested in check_funcvars.c
int
main(void)
{
const struct CMUnitTest tests[] = {
#ifdef HAVE_SYSINFO_HOSTNAME
cmocka_unit_test(test_sysinfo_get_hostname),
cmocka_unit_test(test_sysinfo_inject_hostname),
#endif
cmocka_unit_test(test_sysinfo_get_username),
cmocka_unit_test(test_sysinfo_inject_username),
#ifdef HAVE_SYSINFO_DATETIME
cmocka_unit_test(test_sysinfo_get_datetime),
cmocka_unit_test(test_sysinfo_inject_datetime),
#endif
cmocka_unit_test(test_sysinfo_get_inside_docker),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
|
RobbiNespu/hyperboria
|
nexus/actions/vote.py
|
<filename>nexus/actions/vote.py
import aiopg
from library.aiopostgres.pool_holder import AioPostgresPoolHolder
from nexus.models.proto.operation_pb2 import \
DocumentOperation as DocumentOperationPb
from pypika import (
PostgreSQLQuery,
Table,
)
from .base import BaseAction
class SendDocumentOperationVotePbToGoldenPostgresAction(BaseAction):
votes_table = Table('votes')
def __init__(self, database):
super().__init__()
self.pool_holder = AioPostgresPoolHolder(
fn=aiopg.create_pool,
dsn=f'dbname={database["database"]} '
f'user={database["username"]} '
f'password={database["password"]} '
f'host={database["host"]}',
timeout=30,
pool_recycle=60,
maxsize=2,
)
self.waits.append(self.pool_holder)
def generate_insert_sql(self, document_id: int, value: int, voter_id: int):
query = PostgreSQLQuery.into(self.votes_table).columns(
'document_id',
'value',
'voter_id',
).insert(
document_id,
value,
voter_id,
)
query = query.on_conflict('document_id', 'voter_id').do_update('value', value)
return query.get_sql()
async def do(self, document_operation_pb: DocumentOperationPb) -> DocumentOperationPb:
vote_pb = document_operation_pb.vote
sql = self.generate_insert_sql(
document_id=vote_pb.document_id,
value=vote_pb.value,
voter_id=vote_pb.voter_id,
)
await self.pool_holder.execute(sql)
return vote_pb
|
arushgupta/rails-sample-app
|
app/admin/user.rb
|
<gh_stars>0
ActiveAdmin.register User do
menu parent: "Settings"
before_filter :skip_sidebar!, only: :index
permit_params :first_name, :last_name, :email, :is_active
controller do
def show
@page_title = "User"
end
end
index do
selectable_column
id_column
column :first_name
column :last_name
column :email
column :is_active
actions
end
form do |f|
f.inputs 'User Details' do
f.input :first_name
f.input :last_name
f.input :email
f.input :is_active
end
f.actions
end
end
|
aardvarck/rism
|
app/models/right/subject_types.rb
|
# frozen_string_literl: true
module Right::SubjectTypes
SUBJECT_TYPES = {
'Organization' => I18n.t('activerecord.models.organization.one'),
'OrganizationKind' => I18n.t('activerecord.models.organization_kind.one'),
'User' => I18n.t('activerecord.models.user.one'),
'Department' => I18n.t('activerecord.models.department.one'),
'Agreement' => I18n.t('activerecord.models.agreement.one'),
'AgreementKind' => I18n.t('activerecord.models.agreement_kind.one'),
'Article' => I18n.t('activerecord.models.article.one'),
'ArticlesFolder' => I18n.t('activerecord.models.articles_folder.one'),
'Incident' => I18n.t('activerecord.models.incident.one'),
'Investigation' => I18n.t('activerecord.models.investigation.one'),
'InvestigationKind' => I18n.t('activerecord.models.investigation_kind.one'),
'Feed' => I18n.t('activerecord.models.feed.one'),
'Indicator' => I18n.t('activerecord.models.indicator.one'),
'IndicatorContext' => I18n.t('activerecord.models.indicator_context.one'),
'Enrichment' => I18n.t('activerecord.models.enrichment.one'),
'Host' => I18n.t('activerecord.models.host.one'),
'HostService' => I18n.t('activerecord.models.host_service.one'),
'HostServiceStatus' => I18n.t('activerecord.models.host_service_status.one'),
'ScanOption' => I18n.t('activerecord.models.scan_option.one'),
'ScanJob' => I18n.t('activerecord.models.scan_job.one'),
'ScanJobLog' => I18n.t('activerecord.models.scan_job_log.one'),
'ScanJobsHost' => I18n.t('activerecord.models.scan_jobs_host.one'),
'ScanResult' => I18n.t('activerecord.models.scan_result.one'),
'Schedule' => I18n.t('activerecord.models.schedule.one'),
'ScheduledJobs' => I18n.t('activerecord.models.scheduled_jobs.one'),
'Agent' => I18n.t('activerecord.models.agent.one'),
'RaAgentApi' => I18n.t('labels.ra_agent_api'),
'Vulnerability' => I18n.t('activerecord.models.vulnerability.one'),
'VulnerabilityKind' => I18n.t('activerecord.models.vulnerability_kind.one'),
'VulnerabilityBulletin' => I18n.t('activerecord.models.vulnerability_bulletin.one'),
'VulnerabilityBulletinKind' => I18n.t('activerecord.models.vulnerability_bulletin_kind.one'),
'VulnerabilityBulletinMember' => I18n.t('activerecord.models.vulnerability_bulletin_member.one'),
'VulnerabilityBulletinStatus' => I18n.t('activerecord.models.vulnerability_bulletin_status.one'),
'DeliveryList' => I18n.t('activerecord.models.delivery_list.one'),
'DeliverySubject' => I18n.t('activerecord.models.delivery_subject.one'),
'DeliveryRecipient' => I18n.t('activerecord.models.delivery_recipient.one'),
'Subscription' => I18n.t('activerecord.models.subscription.one'),
'Publication' => I18n.t('activerecord.models.publication.one'),
'ProcessingLog' => I18n.t('activerecord.models.processing_log.one'),
'NotificationsLog' => I18n.t('activerecord.models.notifications_log.one'),
'SearchFilter' => I18n.t('activerecord.models.search_filter.one'),
'AttachedFile' => I18n.t('activerecord.models.attached_file.one'),
'Tag' => I18n.t('activerecord.models.tag.one'),
'TagKind' => I18n.t('activerecord.models.tag_kind.one'),
'TagMember' => I18n.t('activerecord.models.tag_member.one'),
'Link' => I18n.t('activerecord.models.link.one'),
'LinkKind' => I18n.t('activerecord.models.link_kind.one'),
'RecordTemplate' => I18n.t('activerecord.models.record_template.one'),
'Versions' => I18n.t('labels.version.versions'),
'Reports' => I18n.t('labels.reports'),
'CustomReportsFolder' => I18n.t('activerecord.models.custom_reports_folder.one'),
'CustomReport' => I18n.t('activerecord.models.custom_report.one'),
'CustomReportsResult' => I18n.t('activerecord.models.custom_reports_result.one'),
'Charts' => I18n.t('navigations.charts'),
'Dashboards' => I18n.t('navigations.dashboards'),
'ReadableLog' => I18n.t('activerecord.models.readable_log.one')
}.freeze
end
|
kkurt/the-hand
|
src/test/scala/com/gilt/thehand/UtilSpec.scala
|
<filename>src/test/scala/com/gilt/thehand/UtilSpec.scala<gh_stars>0
package com.gilt.thehand
import org.scalatest.FlatSpec
import org.scalatest.Matchers
class UtilSpec extends FlatSpec with Matchers {
"Util.nestedSplit" should "work for a simple split" in {
Util.nestedSplit("1,2,3,4") shouldBe Seq("1", "2", "3", "4")
}
it should "do a simple split with a non-standard delimiter" in {
Util.nestedSplit("1|2,3|4", '|') shouldBe Seq("1", "2,3", "4")
}
it should "do a nested split" in {
Util.nestedSplit("1,(2,3),(4,(5,(6,7)))") shouldBe Seq("1", "(2,3)", "(4,(5,(6,7)))")
}
it should "do a nested split with a non-standard delimiter" in {
Util.nestedSplit("1,(2|3)|(4|(5|(6|7)))", '|') shouldBe Seq("1,(2|3)", "(4|(5|(6|7)))")
}
it should "do a nested split with a non-standard opening delimiter" in {
Util.nestedSplit("1,{2,3),{(4,{5,{6,7)),)", openDelimiter = '{') shouldBe Seq("1", "{2,3)", "{(4,{5,{6,7)),)")
}
it should "do a nested split with a non-standard closing delimiter" in {
Util.nestedSplit("1,(2,3},(4,(5,(6,7)},}}", closeDelimiter = '}') shouldBe Seq("1", "(2,3}", "(4,(5,(6,7)},}}")
}
it should "do a nested split with all non-standard delimiters" in {
Util.nestedSplit("1,{(2|3|}|{4|{5|{6|7}}}", '|', '{', '}') shouldBe Seq("1,{(2|3|}", "{4|{5|{6|7}}}")
}
}
|
snapmeds/snapmeds
|
SnapMeds/src/com/dosage/TimePickerFragment.java
|
package com.dosage;
import java.util.Calendar;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.format.DateFormat;
public class TimePickerFragment extends DialogFragment {
private TimePickerDialog.OnTimeSetListener callback;
public void setOnTimeSetListener(TimePickerDialog.OnTimeSetListener callback) {
this.callback = callback;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), callback, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
}
|
nxtreaming/yt-dlp
|
yt_dlp/extractor/aenetworks.py
|
<filename>yt_dlp/extractor/aenetworks.py
from .theplatform import ThePlatformIE
from ..utils import (
ExtractorError,
GeoRestrictedError,
int_or_none,
update_url_query,
urlencode_postdata,
)
class AENetworksBaseIE(ThePlatformIE):
_BASE_URL_REGEX = r'''(?x)https?://
(?:(?:www|play|watch)\.)?
(?P<domain>
(?:history(?:vault)?|aetv|mylifetime|lifetimemovieclub)\.com|
fyi\.tv
)/'''
_THEPLATFORM_KEY = '43jXaGRQud'
_THEPLATFORM_SECRET = '<KEY>'
_DOMAIN_MAP = {
'history.com': ('HISTORY', 'history'),
'aetv.com': ('AETV', 'aetv'),
'mylifetime.com': ('LIFETIME', 'lifetime'),
'lifetimemovieclub.com': ('LIFETIMEMOVIECLUB', 'lmc'),
'fyi.tv': ('FYI', 'fyi'),
'historyvault.com': (None, 'historyvault'),
'biography.com': (None, 'biography'),
}
def _extract_aen_smil(self, smil_url, video_id, auth=None):
query = {'mbr': 'true'}
if auth:
query['auth'] = auth
TP_SMIL_QUERY = [{
'assetTypes': 'high_video_ak',
'switch': 'hls_high_ak'
}, {
'assetTypes': 'high_video_s3'
}, {
'assetTypes': 'high_video_s3',
'switch': 'hls_high_fastly',
}]
formats = []
subtitles = {}
last_e = None
for q in TP_SMIL_QUERY:
q.update(query)
m_url = update_url_query(smil_url, q)
m_url = self._sign_url(m_url, self._THEPLATFORM_KEY, self._THEPLATFORM_SECRET)
try:
tp_formats, tp_subtitles = self._extract_theplatform_smil(
m_url, video_id, 'Downloading %s SMIL data' % (q.get('switch') or q['assetTypes']))
except ExtractorError as e:
if isinstance(e, GeoRestrictedError):
raise
last_e = e
continue
formats.extend(tp_formats)
subtitles = self._merge_subtitles(subtitles, tp_subtitles)
if last_e and not formats:
raise last_e
self._sort_formats(formats)
return {
'id': video_id,
'formats': formats,
'subtitles': subtitles,
}
def _extract_aetn_info(self, domain, filter_key, filter_value, url):
requestor_id, brand = self._DOMAIN_MAP[domain]
result = self._download_json(
'https://feeds.video.aetnd.com/api/v2/%s/videos' % brand,
filter_value, query={'filter[%s]' % filter_key: filter_value})['results'][0]
title = result['title']
video_id = result['id']
media_url = result['publicUrl']
theplatform_metadata = self._download_theplatform_metadata(self._search_regex(
r'https?://link\.theplatform\.com/s/([^?]+)', media_url, 'theplatform_path'), video_id)
info = self._parse_theplatform_metadata(theplatform_metadata)
auth = None
if theplatform_metadata.get('AETN$isBehindWall'):
resource = self._get_mvpd_resource(
requestor_id, theplatform_metadata['title'],
theplatform_metadata.get('AETN$PPL_pplProgramId') or theplatform_metadata.get('AETN$PPL_pplProgramId_OLD'),
theplatform_metadata['ratings'][0]['rating'])
auth = self._extract_mvpd_auth(
url, video_id, requestor_id, resource)
info.update(self._extract_aen_smil(media_url, video_id, auth))
info.update({
'title': title,
'series': result.get('seriesName'),
'season_number': int_or_none(result.get('tvSeasonNumber')),
'episode_number': int_or_none(result.get('tvSeasonEpisodeNumber')),
})
return info
class AENetworksIE(AENetworksBaseIE):
IE_NAME = 'aenetworks'
IE_DESC = 'A+E Networks: A&E, Lifetime, History.com, FYI Network and History Vault'
_VALID_URL = AENetworksBaseIE._BASE_URL_REGEX + r'''(?P<id>
shows/[^/]+/season-\d+/episode-\d+|
(?:
(?:movie|special)s/[^/]+|
(?:shows/[^/]+/)?videos
)/[^/?#&]+
)'''
_TESTS = [{
'url': 'http://www.history.com/shows/mountain-men/season-1/episode-1',
'info_dict': {
'id': '22253814',
'ext': 'mp4',
'title': 'Winter is Coming',
'description': 'md5:641f424b7a19d8e24f26dea22cf59d74',
'timestamp': 1338306241,
'upload_date': '20120529',
'uploader': 'AENE-NEW',
},
'params': {
# m3u8 download
'skip_download': True,
},
'add_ie': ['ThePlatform'],
'skip': 'This video is only available for users of participating TV providers.',
}, {
'url': 'http://www.aetv.com/shows/duck-dynasty/season-9/episode-1',
'info_dict': {
'id': '600587331957',
'ext': 'mp4',
'title': 'Inlawful Entry',
'description': 'md5:57c12115a2b384d883fe64ca50529e08',
'timestamp': 1452634428,
'upload_date': '20160112',
'uploader': 'AENE-NEW',
},
'params': {
# m3u8 download
'skip_download': True,
},
'add_ie': ['ThePlatform'],
}, {
'url': 'http://www.fyi.tv/shows/tiny-house-nation/season-1/episode-8',
'only_matching': True
}, {
'url': 'http://www.mylifetime.com/shows/project-runway-junior/season-1/episode-6',
'only_matching': True
}, {
'url': 'http://www.mylifetime.com/movies/center-stage-on-pointe/full-movie',
'only_matching': True
}, {
'url': 'https://watch.lifetimemovieclub.com/movies/10-year-reunion/full-movie',
'only_matching': True
}, {
'url': 'http://www.history.com/specials/sniper-into-the-kill-zone/full-special',
'only_matching': True
}, {
'url': 'https://www.aetv.com/specials/hunting-jonbenets-killer-the-untold-story/preview-hunting-jonbenets-killer-the-untold-story',
'only_matching': True
}, {
'url': 'http://www.history.com/videos/history-of-valentines-day',
'only_matching': True
}, {
'url': 'https://play.aetv.com/shows/duck-dynasty/videos/best-of-duck-dynasty-getting-quack-in-shape',
'only_matching': True
}]
def _real_extract(self, url):
domain, canonical = self._match_valid_url(url).groups()
return self._extract_aetn_info(domain, 'canonical', '/' + canonical, url)
class AENetworksListBaseIE(AENetworksBaseIE):
def _call_api(self, resource, slug, brand, fields):
return self._download_json(
'https://yoga.appsvcs.aetnd.com/graphql',
slug, query={'brand': brand}, data=urlencode_postdata({
'query': '''{
%s(slug: "%s") {
%s
}
}''' % (resource, slug, fields),
}))['data'][resource]
def _real_extract(self, url):
domain, slug = self._match_valid_url(url).groups()
_, brand = self._DOMAIN_MAP[domain]
playlist = self._call_api(self._RESOURCE, slug, brand, self._FIELDS)
base_url = 'http://watch.%s' % domain
entries = []
for item in (playlist.get(self._ITEMS_KEY) or []):
doc = self._get_doc(item)
canonical = doc.get('canonical')
if not canonical:
continue
entries.append(self.url_result(
base_url + canonical, AENetworksIE.ie_key(), doc.get('id')))
description = None
if self._PLAYLIST_DESCRIPTION_KEY:
description = playlist.get(self._PLAYLIST_DESCRIPTION_KEY)
return self.playlist_result(
entries, playlist.get('id'),
playlist.get(self._PLAYLIST_TITLE_KEY), description)
class AENetworksCollectionIE(AENetworksListBaseIE):
IE_NAME = 'aenetworks:collection'
_VALID_URL = AENetworksBaseIE._BASE_URL_REGEX + r'(?:[^/]+/)*(?:list|collections)/(?P<id>[^/?#&]+)/?(?:[?#&]|$)'
_TESTS = [{
'url': 'https://watch.historyvault.com/list/america-the-story-of-us',
'info_dict': {
'id': '282',
'title': 'America The Story of Us',
},
'playlist_mincount': 12,
}, {
'url': 'https://watch.historyvault.com/shows/america-the-story-of-us-2/season-1/list/america-the-story-of-us',
'only_matching': True
}, {
'url': 'https://www.historyvault.com/collections/mysteryquest',
'only_matching': True
}]
_RESOURCE = 'list'
_ITEMS_KEY = 'items'
_PLAYLIST_TITLE_KEY = 'display_title'
_PLAYLIST_DESCRIPTION_KEY = None
_FIELDS = '''id
display_title
items {
... on ListVideoItem {
doc {
canonical
id
}
}
}'''
def _get_doc(self, item):
return item.get('doc') or {}
class AENetworksShowIE(AENetworksListBaseIE):
IE_NAME = 'aenetworks:show'
_VALID_URL = AENetworksBaseIE._BASE_URL_REGEX + r'shows/(?P<id>[^/?#&]+)/?(?:[?#&]|$)'
_TESTS = [{
'url': 'http://www.history.com/shows/ancient-aliens',
'info_dict': {
'id': 'SERIES1574',
'title': 'Ancient Aliens',
'description': 'md5:3f6d74daf2672ff3ae29ed732e37ea7f',
},
'playlist_mincount': 150,
}]
_RESOURCE = 'series'
_ITEMS_KEY = 'episodes'
_PLAYLIST_TITLE_KEY = 'title'
_PLAYLIST_DESCRIPTION_KEY = 'description'
_FIELDS = '''description
id
title
episodes {
canonical
id
}'''
def _get_doc(self, item):
return item
class HistoryTopicIE(AENetworksBaseIE):
IE_NAME = 'history:topic'
IE_DESC = 'History.com Topic'
_VALID_URL = r'https?://(?:www\.)?history\.com/topics/[^/]+/(?P<id>[\w+-]+?)-video'
_TESTS = [{
'url': 'https://www.history.com/topics/valentines-day/history-of-valentines-day-video',
'info_dict': {
'id': '40700995724',
'ext': 'mp4',
'title': "History of Valentine’s Day",
'description': 'md5:7b57ea4829b391995b405fa60bd7b5f7',
'timestamp': 1375819729,
'upload_date': '20130806',
'uploader': 'AENE-NEW',
},
'params': {
# m3u8 download
'skip_download': True,
},
'add_ie': ['ThePlatform'],
}]
def _real_extract(self, url):
display_id = self._match_id(url)
return self.url_result(
'http://www.history.com/videos/' + display_id,
AENetworksIE.ie_key())
class HistoryPlayerIE(AENetworksBaseIE):
IE_NAME = 'history:player'
_VALID_URL = r'https?://(?:www\.)?(?P<domain>(?:history|biography)\.com)/player/(?P<id>\d+)'
_TESTS = []
def _real_extract(self, url):
domain, video_id = self._match_valid_url(url).groups()
return self._extract_aetn_info(domain, 'id', video_id, url)
class BiographyIE(AENetworksBaseIE):
_VALID_URL = r'https?://(?:www\.)?biography\.com/video/(?P<id>[^/?#&]+)'
_TESTS = [{
'url': 'https://www.biography.com/video/vincent-van-gogh-full-episode-2075049808',
'info_dict': {
'id': '30322987',
'ext': 'mp4',
'title': 'Vincent Van Gogh - Full Episode',
'description': 'A full biography about the most influential 20th century painter, <NAME>.',
'timestamp': 1311970571,
'upload_date': '20110729',
'uploader': 'AENE-NEW',
},
'params': {
# m3u8 download
'skip_download': True,
},
'add_ie': ['ThePlatform'],
}]
def _real_extract(self, url):
display_id = self._match_id(url)
webpage = self._download_webpage(url, display_id)
player_url = self._search_regex(
r'<phoenix-iframe[^>]+src="(%s)' % HistoryPlayerIE._VALID_URL,
webpage, 'player URL')
return self.url_result(player_url, HistoryPlayerIE.ie_key())
|
visor-tax/plaid-go
|
plaid/model_email.go
|
/*
* The Plaid API
*
* The Plaid REST API. Please see https://plaid.com/docs/api for more details.
*
* API version: 2020-09-14_1.54.0
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package plaid
import (
"encoding/json"
)
// Email An object representing an email address
type Email struct {
// The email address.
Data string `json:"data"`
// When `true`, identifies the email address as the primary email on an account.
Primary bool `json:"primary"`
// The type of email account as described by the financial institution.
Type string `json:"type"`
AdditionalProperties map[string]interface{}
}
type _Email Email
// NewEmail instantiates a new Email object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewEmail(data string, primary bool, type_ string) *Email {
this := Email{}
this.Data = data
this.Primary = primary
this.Type = type_
return &this
}
// NewEmailWithDefaults instantiates a new Email object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewEmailWithDefaults() *Email {
this := Email{}
return &this
}
// GetData returns the Data field value
func (o *Email) GetData() string {
if o == nil {
var ret string
return ret
}
return o.Data
}
// GetDataOk returns a tuple with the Data field value
// and a boolean to check if the value has been set.
func (o *Email) GetDataOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Data, true
}
// SetData sets field value
func (o *Email) SetData(v string) {
o.Data = v
}
// GetPrimary returns the Primary field value
func (o *Email) GetPrimary() bool {
if o == nil {
var ret bool
return ret
}
return o.Primary
}
// GetPrimaryOk returns a tuple with the Primary field value
// and a boolean to check if the value has been set.
func (o *Email) GetPrimaryOk() (*bool, bool) {
if o == nil {
return nil, false
}
return &o.Primary, true
}
// SetPrimary sets field value
func (o *Email) SetPrimary(v bool) {
o.Primary = v
}
// GetType returns the Type field value
func (o *Email) GetType() string {
if o == nil {
var ret string
return ret
}
return o.Type
}
// GetTypeOk returns a tuple with the Type field value
// and a boolean to check if the value has been set.
func (o *Email) GetTypeOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Type, true
}
// SetType sets field value
func (o *Email) SetType(v string) {
o.Type = v
}
func (o Email) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if true {
toSerialize["data"] = o.Data
}
if true {
toSerialize["primary"] = o.Primary
}
if true {
toSerialize["type"] = o.Type
}
for key, value := range o.AdditionalProperties {
toSerialize[key] = value
}
return json.Marshal(toSerialize)
}
func (o *Email) UnmarshalJSON(bytes []byte) (err error) {
varEmail := _Email{}
if err = json.Unmarshal(bytes, &varEmail); err == nil {
*o = Email(varEmail)
}
additionalProperties := make(map[string]interface{})
if err = json.Unmarshal(bytes, &additionalProperties); err == nil {
delete(additionalProperties, "data")
delete(additionalProperties, "primary")
delete(additionalProperties, "type")
o.AdditionalProperties = additionalProperties
}
return err
}
type NullableEmail struct {
value *Email
isSet bool
}
func (v NullableEmail) Get() *Email {
return v.value
}
func (v *NullableEmail) Set(val *Email) {
v.value = val
v.isSet = true
}
func (v NullableEmail) IsSet() bool {
return v.isSet
}
func (v *NullableEmail) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableEmail(val *Email) *NullableEmail {
return &NullableEmail{value: val, isSet: true}
}
func (v NullableEmail) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableEmail) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
}
|
LeandroTk/Algorithms
|
competitive_programming/programming_contests/hacker_rank/cpp/introduction/library_fine.cpp
|
#include <iostream>
using namespace std;
int main() {
int day1, day2, month1, month2, year1, year2;
cin >> day1 >> month1 >> year1;
cin >> day2 >> month2 >> year2;
if (year1 == year2) {
if (month1 == month2) {
if (day1 <= day2)
cout << 0 << endl;
else
cout << 15 * (day1 - day2) << endl;
} else if (month1 > month2) {
cout << 500 * (month1 - month2) << endl;
} else {
cout << 0 << endl;
}
} else if (year1 > year2) {
cout << 10000 * (year1 - year2) << endl;
} else {
cout << 0 << endl;
}
return 0;
}
|
red-machine-games/goblin-base-server
|
test/runningCloudFunctionFromCloudFunctions-contract/cloudFunctions/cloudFunction42.js
|
if(args){
let give = await run('cloudFunction42', false);
give.lack = lock.check();
FunctionResponse({ give });
} else {
FunctionResponse({ exile: lock.check() })
}
|
luoyusoft/luoyublog-backend
|
src/main/java/com/jinhx/blog/controller/system/SysParamController.java
|
<filename>src/main/java/com/jinhx/blog/controller/system/SysParamController.java
package com.jinhx.blog.controller.system;
import com.jinhx.blog.common.aop.annotation.SuperAdmin;
import com.jinhx.blog.common.util.MyAssert;
import com.jinhx.blog.common.validator.ValidatorUtils;
import com.jinhx.blog.common.validator.group.InsertGroup;
import com.jinhx.blog.common.validator.group.UpdateGroup;
import com.jinhx.blog.entity.base.PageData;
import com.jinhx.blog.entity.base.Response;
import com.jinhx.blog.entity.system.SysParam;
import com.jinhx.blog.service.system.SysParamService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* SysParamController
*
* @author jinhx
* @since 2018-10-08
*/
@RestController
public class SysParamController {
@Autowired
private SysParamService sysParamService;
/**
* 分页查询系统参数列表
*
* @param page page
* @param limit limit
* @param menuUrl menuUrl
* @param type type
* @return 系统参数列表
*/
@GetMapping("/manage/sysparams/page")
@RequiresPermissions("sysparam:list")
public Response<PageData<SysParam>> selectSysParamsByPage(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit,
@RequestParam(value = "menuUrl", required = false) String menuUrl,
@RequestParam(value = "type", required = false) String type){
return Response.success(sysParamService.selectSysParamsByPage(page, limit, menuUrl, type));
}
/**
* 查询所有参数列表
*
* @return 参数列表
*/
@GetMapping("/manage/sysparams/all")
public Response<List<SysParam>> selectAllSysParams(){
return Response.success(sysParamService.selectAllSysParams());
}
/**
* 根据sysParamId查询参数
*
* @param sysParamId sysParamId
* @return 参数
*/
@GetMapping("/manage/sysparam/{sysParamId}")
@RequiresPermissions("sysparam:detail")
public Response<SysParam> selectSysParamById(@PathVariable Long sysParamId){
return Response.success(sysParamService.selectSysParamById(sysParamId));
}
/**
* 新增参数
*
* @param sysParam sysParam
* @return 新增结果
*/
@PostMapping("/manage/sysparam")
@RequiresPermissions("sysparam:insert")
public Response<Void> insertSysParam(@RequestBody SysParam sysParam){
ValidatorUtils.validateEntity(sysParam, InsertGroup.class);
sysParamService.insertSysParam(sysParam);
return Response.success();
}
/**
* 根据sysParamId更新参数
*
* @param sysParam sysParam
* @return 更新结果
*/
@SuperAdmin()
@PutMapping("/manage/sysparam")
@RequiresPermissions("sysparam:update")
public Response<Void> updateSysParamById(@RequestBody SysParam sysParam){
ValidatorUtils.validateEntity(sysParam, UpdateGroup.class);
sysParamService.updateSysParamById(sysParam);
return Response.success();
}
/**
* 批量根据sysParamId删除参数
*
* @param sysParamIds sysParamIds
* @return 删除结果
*/
@SuperAdmin()
@DeleteMapping("/manage/sysparams")
@RequiresPermissions("sysparam:delete")
public Response<Void> deleteSysParamsById(@RequestBody List<Long> sysParamIds){
MyAssert.sizeBetween(sysParamIds, 1, 100, "sysParamIds");
sysParamService.deleteSysParamsById(sysParamIds);
return Response.success();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.