hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
06bd2c4d8706da507d86e20d7ff476e3a8c2770f | 17,208 | cpp | C++ | editor/gui/src/glWidget.cpp | lizardkinger/blacksun | 0119948726d2a057c13d208044c7664a8348a1ea | [
"Linux-OpenIB"
] | null | null | null | editor/gui/src/glWidget.cpp | lizardkinger/blacksun | 0119948726d2a057c13d208044c7664a8348a1ea | [
"Linux-OpenIB"
] | null | null | null | editor/gui/src/glWidget.cpp | lizardkinger/blacksun | 0119948726d2a057c13d208044c7664a8348a1ea | [
"Linux-OpenIB"
] | null | null | null | /***************************************************************************
* Copyright (C) 2006 by The Hunter *
* hunter@localhost *
* *
* 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. *
***************************************************************************/
#include "./../include/glWidget.h"
#include "./../include/mainwindow.h"
#include "./../../scenegraph/include/SceneManager.h"
#include "./../../scenegraph/include/SceneAction2D.h"
using namespace BSScene;
using namespace BSRenderer;
namespace BSGui
{
GLWidget::GLWidget(QWidget *parent, bool bOrtho, FillMode fm,
OrthogonalType orthoType)
: BSRenderWidget(parent, bOrtho, fm, orthoType), showRubberBand(false),
showMoveLine(false), showScaleLine(false), showRotateArc(false), overpaintingColor(QColor(0,0,0))
{
actionMaximizeMe = new QAction("Maximized", this);
actionMaximizeMe->setCheckable(true);
insertAction(1, actionMaximizeMe);
enableOverpainting();
connect(actionMaximizeMe, SIGNAL(toggled(bool)), this, SLOT(setMaximized(bool)));
}
void GLWidget::setMaximized(bool status)
{
emit maximizeMe(this, status);
}
/*void GLWidget::mousePositionChanged(QPoint pos)
{
QPointF p;
if(settings.viewMode != VIEWMODE_Perspective)
{
p = calcRenderPosition(pos);
}
MainWindow::getInstance()->getStatusBarPosLabel()->setText("X: " + QString::number(p.x(), 'f', 4) + " Y: " + QString::number(p.y(), 'f', 4));
}*/
void GLWidget::mousePressEvent(QMouseEvent* event)
{
SceneManager *sm = SceneManager::getInstance();
BSRenderWidget::mousePressEvent(event);
int currentMouseProperty = getMouseProperty(event);
lastMouseMoveProperty = currentMouseProperty;
if(event->buttons() != Qt::NoButton)
{
if(currentMouseProperty == MouseSettings::SelectedAction)
{
if(settings.viewMode == VIEWMODE_Orthogonal)
{
rubberBandOrigin = event->pos();
rubberBandDestination = event->pos();
showRubberBand = true;
if(sm->getActionMode() == BSScene::SCENEACTION_Move)
{
moveLineOrigin = snapToGrid(event->pos());
moveLineDestination = snapToGrid(event->pos());
showMoveLine = true;
}
if(sm->getActionMode() == BSScene::SCENEACTION_Rotate)
{
moveLineOrigin = snapToGrid(event->pos());
moveLineDestination = snapToGrid(event->pos());
showRotateArc = true;
}
if(sm->getActionMode() == BSScene::SCENEACTION_Scale)
{
moveLineOrigin = snapToGrid(event->pos());
moveLineDestination = snapToGrid(event->pos());
showScaleLine = true;
}
}
}
else if((currentMouseProperty == MouseSettings::AddToSelection ||
currentMouseProperty == MouseSettings::RemoveFromSelection)
&& sm->getActionMode() == BSScene::SCENEACTION_Selection)
{
rubberBandOrigin = event->pos();
rubberBandDestination = event->pos();
showRubberBand = true;
}
}
}
void GLWidget::mouseMoveEvent(QMouseEvent* event)
{
SceneManager *sm = SceneManager::getInstance();
if(event->buttons() != Qt::NoButton)
{
int currentMouseProperty = getMouseProperty(event);
lastMouseMoveProperty = currentMouseProperty;
if(currentMouseProperty == MouseSettings::SelectedAction)
{
switch(sm->getActionMode())
{
case BSScene::SCENEACTION_Creation:
{
break;
}
case BSScene::SCENEACTION_Rotate:
case BSScene::SCENEACTION_Move:
case BSScene::SCENEACTION_Scale:
{
moveLineDestination = snapToGrid(event->pos());
break;
}
default:
{
if(settings.viewMode == VIEWMODE_Orthogonal)
{
if(settings.viewMode == VIEWMODE_Orthogonal)
{
rubberBandDestination = event->pos();
}
}
}
}
}
else if((currentMouseProperty == MouseSettings::AddToSelection ||
currentMouseProperty == MouseSettings::RemoveFromSelection)
&& sm->getActionMode() == BSScene::SCENEACTION_Selection)
{
rubberBandDestination = event->pos();
}
}
BSRenderWidget::mouseMoveEvent(event);
}
SceneAction2D GLWidget::buildSceneAction2D(Qt::MouseButton button,
SceneAction2D_SelectionType selectionType,
QPoint eventPos)
{
SceneManager *sm = SceneManager::getInstance();
QPointF startPos;
QPointF endPos;
SceneAction2D sa;
if(sm->getActionMode() == BSScene::SCENEACTION_Selection)
{
startPos = calcRenderPosition(rubberBandOrigin);
endPos = calcRenderPosition(eventPos);
}
else
{
startPos = calcRenderPosition(snapToGrid(rubberBandOrigin));
endPos = calcRenderPosition(snapToGrid(eventPos));
}
SceneAxis current_axis;
switch(getOrthoType())
{
case ORTHO_Front:
case ORTHO_Back:
current_axis = AXIS_z;
break;
case ORTHO_Left:
case ORTHO_Right:
current_axis = AXIS_x;
break;
case ORTHO_Top:
case ORTHO_Bottom:
current_axis = AXIS_y;
break;
}
sa.topleft = startPos;
sa.bottomright = endPos;
sa.mouseButton = button;
sa.axis = current_axis;
sa.axis = current_axis;
sa.selType = selectionType;
switch(sm->getActionMode())
{
case BSScene::SCENEACTION_Rotate:
{
sa.rotateValue = rotateAngle;
}
break;
case BSScene::SCENEACTION_Scale:
{
double svX, svY, svZ;
svX = svY = svZ = 0.0;
switch(getOrthoType())
{
case ORTHO_Front:
case ORTHO_Back:
svX = (moveLineDestination.x() - moveLineOrigin.x()) / 100.0;
svY = (moveLineDestination.y() - moveLineOrigin.y()) / 100.0;
break;
case ORTHO_Left:
case ORTHO_Right:
svZ = (moveLineDestination.x() - moveLineOrigin.x()) / 100.0;
svY = (moveLineDestination.y() - moveLineOrigin.y()) / 100.0;
break;
case ORTHO_Top:
case ORTHO_Bottom:
svX = (moveLineDestination.x() - moveLineOrigin.x()) / 100.0;
svZ = (moveLineOrigin.y() - moveLineDestination.y() ) / 100.0;
break;
}
sa.scaleValueX = 1 + svX;
sa.scaleValueY = 1 + svY;
sa.scaleValueZ = 1 + svZ;
/* qDebug() << "sa.scaleValueX: " << sa.scaleValueX;
qDebug() << "sa.scaleValueY: " << sa.scaleValueY;
qDebug() << "sa.scaleValueZ: " << sa.scaleValueZ;*/
}
break;
default: break;
}
return sa;
}
void GLWidget::mouseReleaseEvent(QMouseEvent* event)
{
SceneManager *sm = SceneManager::getInstance();
BSRenderWidget::mouseReleaseEvent(event);
showRubberBand = false;
showMoveLine = false;
showRotateArc = false;
showScaleLine = false;
if(lastMouseMoveProperty == MouseSettings::SelectedAction)
{
if(settings.viewMode != VIEWMODE_Perspective)
{
sm->action2D(buildSceneAction2D(event->button(), SCENETYPE_Select, event->pos()));
}
}
else if(lastMouseMoveProperty == MouseSettings::AddToSelection
&& sm->getActionMode() == BSScene::SCENEACTION_Selection)
{
if(settings.viewMode != VIEWMODE_Perspective)
{
sm->action2D(buildSceneAction2D(event->button(), SCENETYPE_AddToSelection, event->pos()));
}
}
else if(lastMouseMoveProperty == MouseSettings::RemoveFromSelection
&& sm->getActionMode() == BSScene::SCENEACTION_Selection)
{
if(settings.viewMode != VIEWMODE_Perspective)
{
sm->action2D(buildSceneAction2D(event->button(), SCENETYPE_RemoveFromSelection, event->pos()));
}
}
update();
}
QPoint GLWidget::getNearestGridPosition(QPoint pos) const
{
vector<QPoint> gridPoints;
//r->getGridIntersectionPoints(gridPoints);
if(settings.viewMode == VIEWMODE_Orthogonal)
{
m_pCamOrthogonal->getGridIntersectionPoints(gridPoints);
QPoint nearestPoint;
nearestPoint = gridPoints.at(0);
QLine beginDestination(pos, nearestPoint);
int nearestDistance = beginDestination.dx() * beginDestination.dx() +
beginDestination.dy() * beginDestination.dy();
for(unsigned int i = 1 ; i < gridPoints.size() ; i++)
{
QLine newDestination(pos, gridPoints.at(i));
int newDistance = newDestination.dx() * newDestination.dx() +
newDestination.dy() * newDestination.dy();
if(newDistance < nearestDistance)
{
nearestPoint = gridPoints.at(i);
nearestDistance = newDistance;
}
}
return nearestPoint;
}
return pos;
}
QPoint GLWidget::snapToGrid(QPoint point)
{
if(MainWindow::getInstance()->getSnapToGridBox()->isChecked())
{
return getNearestGridPosition(point);
}
return point;
}
void GLWidget::enterEvent(QEvent* event)
{
setMouseTracking(true);
}
void GLWidget::leaveEvent(QEvent* event)
{
setMouseTracking(false);
emit mouseMovedRenderPosition(QPointF(0,0));
}
void GLWidget::initializeGL()
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
BSRenderWidget::initializeGL();
glPopAttrib();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
void GLWidget::paintEvent(QPaintEvent* event)
{
SceneManager *sm =SceneManager::getInstance();
const double fSmoothness = 1.5;
QPainter painter;
painter.begin(this);
// QPen myPen;
painter.setPen(Qt::SolidLine);
//myPen.setWidth(2);
painter.setPen(overpaintingColor);
//myPen.setColor(overpaintingColor);
//painter.setPen(myPen);
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
initRenderer();
resetViewport();
renderNow();
glPopAttrib();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
if(showRubberBand)
{
painter.save();
QColor rectColor(selectionBoxColor);
painter.setPen(rectColor);
painter.drawRect(QRect(rubberBandOrigin, rubberBandDestination));
rectColor.setAlpha(50);
painter.fillRect(QRect(rubberBandOrigin, rubberBandDestination), rectColor);
painter.restore();
}
if(showMoveLine || showScaleLine)
{
painter.drawLine(moveLineOrigin, moveLineDestination);
}
if(showRotateArc)
{
Aabb aabb = sm->getSelBuffer().getBoundary();
Vector center = aabb.getCentre();
//qDebug() << "AABB-Center: " << aabb.getCentre().x << ", " << aabb.getCentre().y << ", " << aabb.getCentre().z;
QPointF pointScene;
switch(getOrthoType())
{
case ORTHO_Front:
case ORTHO_Back:
pointScene = QPointF(center.x,center.y);
break;
case ORTHO_Left:
case ORTHO_Right:
pointScene = QPointF(center.z,center.y);
break;
case ORTHO_Top:
case ORTHO_Bottom:
pointScene = QPointF(center.x,center.z);
break;
}
QPoint pointG = calcGUIPosition(pointScene);
qreal x= pointG.x();
qreal y= pointG.y();
qreal w= width() / 4.0;
qreal h= height() / 4.0;
QRectF rectangle(x - w/2 ,y - h/2, w,h);
double lineX = moveLineDestination.x() - moveLineOrigin.x();
rotateAngle = lineX * fSmoothness;
if(rotateAngle > 360)
rotateAngle = 360;
else if(rotateAngle < -360)
rotateAngle = -360;
int startAngle = 0 * 16;
int spanAngle = static_cast<int>(rotateAngle * 16);
spanAngle = (-1 * spanAngle);
painter.drawPie(rectangle,startAngle,spanAngle);
sm->checkForRedraw(true);
}
QString stringToShow;
if(settings.viewMode == VIEWMODE_Orthogonal)
{
if(m_pCamOrthogonal->getOrthogonalType() == ORTHO_Left)
{
stringToShow = "Left View";
}
if(m_pCamOrthogonal->getOrthogonalType() == ORTHO_Top)
{
stringToShow = "Top View";
}
if(m_pCamOrthogonal->getOrthogonalType() == ORTHO_Front)
{
stringToShow = "Front View";
}
}
else
{
stringToShow = "3D View";
}
painter.drawText(QPoint(10,20), stringToShow);
/*
vector<QPoint> gridPoints;
m_pCamOrthogonal->getGridIntersectionPoints(gridPoints);
for(unsigned int i = 1 ; i < gridPoints.size() ; i++)
{
painter.drawPoint(gridPoints.at(i));
}
*/
painter.end();
}
}
| 34.693548 | 144 | 0.487622 |
09478640c4307e7b7c1a8b72405acf8c2da25487 | 503 | lua | Lua | tests/overall.lua | tomasguisasola/dado | b40b271a26a4d6c03fa0d85a7da933aff323fc83 | [
"MIT"
] | 1 | 2021-01-26T08:07:39.000Z | 2021-01-26T08:07:39.000Z | tests/overall.lua | tomasguisasola/dado | b40b271a26a4d6c03fa0d85a7da933aff323fc83 | [
"MIT"
] | null | null | null | tests/overall.lua | tomasguisasola/dado | b40b271a26a4d6c03fa0d85a7da933aff323fc83 | [
"MIT"
] | 2 | 2020-06-19T15:47:12.000Z | 2021-01-26T08:07:41.000Z | #!/usr/local/bin/lua
local path = arg[0]:sub (1, arg[0]:find"/overall")
if arg[0]:find"/overall" == nil then
path = ""
end
io.write("Testing ")
local dado = require"dado"
io.write(dado._VERSION)
io.write(" in ")
io.write(_VERSION)
io.write("\n")
io.write("table.extra ...")
assert(loadfile(path.."ttable.extra.lua"))()
io.write("sql ...")
assert(loadfile(path.."tsql.lua"))()
io.write("dado ...")
assert(loadfile(path.."tdado.lua"))(...)
io.write("dbobj ...")
assert(loadfile(path.."tdbobj.lua"))()
| 21.869565 | 50 | 0.640159 |
f174889d39617faa63852c7df50018686ea6d72a | 752 | asm | Assembly | oeis/028/A028196.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/028/A028196.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/028/A028196.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A028196: Expansion of 1/((1-5x)(1-9x)(1-10x)(1-11x)).
; Submitted by Christian Krause
; 1,35,776,13930,221151,3240825,44906926,597218720,7698198101,96837355615,1194615734676,14505367659510,173840151316651,2060770407338405,24205227062904026,282088240414000300,3265447176464616801,37582206965366853195,430364865022642734976,4906658791808049905090,55727054103551935698551,630781861205204615163985,7118658865468264878107526,80125773038129111705837880,899768233021619366408721901,10082913129359582045419534775,112781207516561207514542461676,1259415750517174947197391462670
mov $1,1
mov $2,$0
mov $3,$0
lpb $2
mov $0,$3
sub $2,1
sub $0,$2
seq $0,20982 ; Expansion of 1/((1-9*x)*(1-10*x)*(1-11*x)).
sub $0,$1
mul $1,6
add $1,$0
lpe
mov $0,$1
| 41.777778 | 481 | 0.797872 |
62ab50558c15e7a83be89c59ac6128100195caa7 | 213 | sql | SQL | src/cli/bundled/sql/PageSavedFilter.sql | maiha/facebook.cr | d2c58423fdc82cee93fbc794a51465dc0e78747e | [
"MIT"
] | 9 | 2019-08-29T14:42:35.000Z | 2022-02-08T19:30:53.000Z | src/cli/bundled/sql/PageSavedFilter.sql | maiha/facebook.cr | d2c58423fdc82cee93fbc794a51465dc0e78747e | [
"MIT"
] | 3 | 2019-09-22T07:22:46.000Z | 2021-07-30T18:58:59.000Z | src/cli/bundled/sql/PageSavedFilter.sql | maiha/facebook.cr | d2c58423fdc82cee93fbc794a51465dc0e78747e | [
"MIT"
] | null | null | null | CREATE TABLE page_saved_filter (
id String,
display_name Nullable(String),
page_id Nullable(String),
section Nullable(String),
time_created Nullable(Int64),
time_updated Nullable(Int64)
)
ENGINE = Log
| 21.3 | 32 | 0.765258 |
e8691fa5c06890a8982742572c5551ed0deaee91 | 11,332 | cc | C++ | dii_player/dii_rtmp/avcodec.cc | PixPark/DiiPlayer | 7cc6beed5dec886204a95781d4b6f8142e7227b9 | [
"MIT"
] | 1 | 2022-03-25T17:06:49.000Z | 2022-03-25T17:06:49.000Z | dii_player/dii_rtmp/avcodec.cc | PixPark/DiiPlayer | 7cc6beed5dec886204a95781d4b6f8142e7227b9 | [
"MIT"
] | null | null | null | dii_player/dii_rtmp/avcodec.cc | PixPark/DiiPlayer | 7cc6beed5dec886204a95781d4b6f8142e7227b9 | [
"MIT"
] | 1 | 2022-03-25T17:06:51.000Z | 2022-03-25T17:06:51.000Z | /*
* Copyright (c) 2016 The rtmp_live_kit project authors. All Rights Reserved.
*
* Please visit https://https://github.com/PixPark/DiiPlayer for detail.
*
* The GNU General Public License is a free, copyleft license for
* software and other kinds of works.
*
* The licenses for most software and other practical works are designed
* to take away your freedom to share and change the works. By contrast,
* the GNU General Public License is intended to guarantee your freedom to
* share and change all versions of a program--to make sure it remains free
* software for all its users. We, the Free Software Foundation, use the
* GNU General Public License for most of our software; it applies also to
* any other work released this way by its authors. You can apply it to
* your programs, too.
* See the GNU LICENSE file for more info.
*/
#include "avcodec.h"
#include "webrtc/media/base/videoframe.h"
#include "webrtc/modules/video_coding/codecs/h264/include/h264.h"
static const size_t kEventMaxWaitTimeMs = 100;
static const size_t kMaxDataSizeSamples = 3840;
namespace dii_media_kit {
class AudioPcm{
public:
AudioPcm(const void* audioSamples, size_t nSamples,
size_t nChannels, uint32_t samplesPerSec) :audio_samples_(NULL){
audio_samples_ = new char[nSamples*sizeof(int16_t)*nChannels];
memcpy(audio_samples_, audioSamples, nSamples*sizeof(int16_t)*nChannels);
sample_per_channel = nSamples;
channels_ = nChannels;
samples_hz_ = samplesPerSec;
}
virtual ~AudioPcm(void){
if (audio_samples_) {
delete (char *)audio_samples_;
audio_samples_ = NULL;
}
}
void* audio_samples_;
int sample_per_channel;
int channels_;
uint32_t samples_hz_;
};
A_AACEncoder::A_AACEncoder(AVCodecCallback&callback)
: callback_(callback)
, encoder_(nullptr)
, muted_(false)
, encoded_(false)
, audio_record_sample_hz_(44100)
, audio_record_channels_(2)
{
if (!running_) {
running_ = true;
}
}
A_AACEncoder::~A_AACEncoder(void)
{
if (running_) {
running_ = false;
}
if (NULL != encoder_)
{
/*Close FAAC engine*/
aac_encoder_close(encoder_);
encoder_ = NULL;
}
dii_rtc::CritScope cs(&buffer_critsect_);
while (audio_buffer_.size() > 0) {
AudioPcm* pcm = (AudioPcm*)audio_buffer_.front();
audio_buffer_.pop_front();
delete pcm;
}
}
bool A_AACEncoder::Init(int num_channels, int sample_rate, int pcm_bit_size)
{
if(encoder_)
return false;
audio_record_sample_hz_ = sample_rate;
audio_record_channels_ = num_channels;
encoder_ = aac_encoder_open(num_channels, sample_rate, pcm_bit_size, false);
return true;
}
void A_AACEncoder::StartEncoder()
{
dii_rtc::CritScope cs(&buffer_critsect_);
while (audio_buffer_.size() > 0) {
AudioPcm* pcm = (AudioPcm*)audio_buffer_.front();
audio_buffer_.pop_front();
delete pcm;
}
encoded_ = true;
}
void A_AACEncoder::StopEncoder()
{
dii_rtc::CritScope cs(&buffer_critsect_);
encoded_ = false;
while (audio_buffer_.size() > 0) {
AudioPcm* pcm = (AudioPcm*)audio_buffer_.front();
audio_buffer_.pop_front();
delete pcm;
}
}
int A_AACEncoder::Encode(const void* audioSamples, const size_t nSamples, const size_t nBytesPerSample,
const size_t nChannels, const uint32_t samplesPerSec, const uint32_t totalDelayMS)
{
int status = 0;
if(encoder_)
{
unsigned int outlen = 0;
uint32_t curtime = dii_rtc::Time();
uint8_t encoded[1024];
if(muted_)
{// mute audio
memset((uint8_t*)audioSamples, 0, nSamples*nBytesPerSample*nChannels);
}
status = aac_encoder_encode_frame(encoder_, (uint8_t*)audioSamples, nSamples*nBytesPerSample*nChannels, encoded, &outlen);
if(outlen > 0)
{
//ALOGE("Encode aac len:%d", outlen);
callback_.OnEncodeDataCallback(true, encoded, outlen, curtime);
}
}
return status;
}
void A_AACEncoder::OnData(const Data& audio)
{
dii_rtc::CritScope cs(&buffer_critsect_);
if(encoded_) {
if (audio_record_sample_hz_ != audio.sample_rate || audio.channels != audio_record_channels_) {
int16_t temp_output[kMaxDataSizeSamples];
int samples_per_channel_int = resampler_record_.Resample10Msec((int16_t*)audio.data, audio.sample_rate * audio.channels,
audio_record_sample_hz_ * audio_record_channels_, 1, kMaxDataSizeSamples, temp_output);
Encode(temp_output, audio_record_sample_hz_ / 100, 2, audio_record_channels_, audio_record_sample_hz_, 0);
}
else {
Encode((int16_t*)audio.data, audio.samples_per_channel, 2, audio_record_channels_, audio_record_sample_hz_, 0);
}
}
}
//===================================================
//* V_H264Encoder
V_H264Encoder::V_H264Encoder(AVCodecCallback&callback)
: callback_(callback)
, need_keyframe_(true)
, running_(false)
, encoded_(false)
, video_bitrate_(768)
, delay_ms_(0)
, adjust_v_bitrate_(0)
, render_buffers_(new VideoRenderFrames(0))
, video_encoder_factory_(NULL)
, encoder_(NULL)
{
h264_.codecType = kVideoCodecH264;
h264_.mode = kRealtimeVideo;
h264_.startBitrate = video_bitrate_;
h264_.targetBitrate = video_bitrate_;
h264_.maxBitrate = 1024;
h264_.maxFramerate = 20;
h264_.width = 640;
h264_.height = 480;
h264_.codecSpecific.H264.profile = kProfileBase;
h264_.codecSpecific.H264.frameDroppingOn = true;
h264_.codecSpecific.H264.keyFrameInterval = h264_.maxFramerate * 3; // 3s
h264_.codecSpecific.H264.spsData = nullptr;
h264_.codecSpecific.H264.spsLen = 0;
h264_.codecSpecific.H264.ppsData = nullptr;
h264_.codecSpecific.H264.ppsLen = 0;
adjust_v_bitrate_ = video_bitrate_;
if (!running_) {
running_ = true;
// dii_rtc::Thread::SetName("apollo_rtmp_live_avc_codec_thread", this);
dii_rtc::Thread::Start();
}
}
V_H264Encoder::~V_H264Encoder(void)
{
if (running_) {
running_ = false;
dii_rtc::Thread::Stop();
}
{
dii_rtc::CritScope cs_buffer(&buffer_critsect_);
render_buffers_.reset();
}
if(encoder_)
{
encoder_->Release();
delete encoder_;
encoder_ = NULL;
}
}
void V_H264Encoder::Init(cricket::WebRtcVideoEncoderFactory* video_encoder_factory)
{
video_encoder_factory_ = video_encoder_factory;
}
void V_H264Encoder::SetParameter(int width, int height, int fps, int bitrate)
{
h264_.startBitrate = bitrate;
h264_.targetBitrate = bitrate;
h264_.maxBitrate = bitrate;
h264_.maxFramerate = fps;
h264_.width = width;
h264_.height = height;
}
void V_H264Encoder::SetRates(int bitrate)
{
video_bitrate_ = bitrate;
h264_.startBitrate = bitrate;
h264_.targetBitrate = bitrate;
h264_.maxBitrate = bitrate;
if(encoder_ != NULL)
{
encoder_->SetRates(bitrate, h264_.maxFramerate);
}
}
void V_H264Encoder::SetAutoAdjustBit(bool enabled)
{
if (enabled) {
adjust_v_bitrate_ = video_bitrate_;
}
}
void V_H264Encoder::SetNetDelay(int delayMs)
{
if(delayMs >= 0 && delayMs < 3000)
{
if(delay_ms_ != 0 && delayMs <=1000){
delay_ms_ = 0;
SetRates(adjust_v_bitrate_);
}
}
else if(delayMs >= 3000 && delayMs < 5000)
{
if(delay_ms_ == 0)
{
delay_ms_ = 3000;
SetRates(adjust_v_bitrate_*3/4);
}
else if(delay_ms_ >= 5000) {
if(delayMs <= 4000)
{
delay_ms_ = 3000;
SetRates(adjust_v_bitrate_*3/4);
}
}
}
else if(delayMs >= 5000 && delayMs < 10000)
{
if(delay_ms_ <= 3000)
{
delay_ms_ = 5000;
SetRates(adjust_v_bitrate_/2);
}
else if(delay_ms_ >= 10000) {
if(delayMs <= 7000)
{
delay_ms_ = 5000;
SetRates(adjust_v_bitrate_/2);
// Fps Up
}
}
}
else if(delayMs >= 10000)
{
if(delay_ms_ <= 5000)
{
delay_ms_ = 10000;
SetRates(adjust_v_bitrate_/3);
// Fps down
}
}
}
void V_H264Encoder::CreateVideoEncoder()
{
VideoEncoder* extern_encoder = NULL;
if(video_encoder_factory_ != NULL)
{
extern_encoder = video_encoder_factory_->CreateVideoEncoder(kVideoCodecH264);
}
if(extern_encoder != NULL)
{// Try to use encoder use H/W
if(extern_encoder->InitEncode(&h264_, 1, 0) == WEBRTC_VIDEO_CODEC_OK)
{
encoder_ = extern_encoder;
}
else
{
delete extern_encoder;
}
}
if(encoder_ == NULL)
{// Use software codec
encoder_ = dii_media_kit::H264Encoder::Create();
if(encoder_->InitEncode(&h264_, 1, 0) != WEBRTC_VIDEO_CODEC_OK)
{
assert(false);
}
}
encoder_->RegisterEncodeCompleteCallback(this);
}
void V_H264Encoder::StartEncoder()
{
dii_rtc::CritScope cs_buffer(&buffer_critsect_);
//render_buffers_->ReleaseAllFrames();
need_keyframe_ = true;
encoded_ = true;
}
void V_H264Encoder::StopEncoder()
{
dii_rtc::CritScope cs_buffer(&buffer_critsect_);
//render_buffers_->ReleaseAllFrames();
encoded_ = false;
}
void V_H264Encoder::RequestKeyFrame()
{
need_keyframe_ = true;
}
//* For Thread
void V_H264Encoder::Run()
{
while(running_)
{
int64_t cur_time = dii_rtc::TimeMillis();
// Get a new frame to render and the time for the frame after this one.
dii_rtc::Optional<VideoFrame> frame_to_render;
uint32_t wait_time = 0;
{
dii_rtc::CritScope cs(&buffer_critsect_);
frame_to_render = render_buffers_->FrameToRender();
wait_time = render_buffers_->TimeToNextFrameRelease();
}
if (frame_to_render) {
if(h264_.width != frame_to_render->width() || h264_.height != frame_to_render->height())
{
h264_.width = frame_to_render->width();
h264_.height = frame_to_render->height();
if(encoder_)
{
encoder_->Release();
encoder_ = NULL;
}
}
if(encoder_ == NULL)
{
CreateVideoEncoder();
}
CodecSpecificInfo codec_info;
std::vector<FrameType> next_frame_types(1, kVideoFrameDelta);
if(need_keyframe_) {
need_keyframe_ = false;
next_frame_types[0] = kVideoFrameKey;
}
if(encoder_)
{
int ret = encoder_->Encode(*frame_to_render, &codec_info, &next_frame_types);
if(ret != 0)
{
//printf("Encode ret :%d", ret);
}
}
}
// Set timer for next frame to render.
if (wait_time > kEventMaxWaitTimeMs) {
wait_time = kEventMaxWaitTimeMs;
}
// Reduce encode time
uint64_t slapTime = dii_rtc::TimeMillis() - cur_time;
if (wait_time >= slapTime)
wait_time -= slapTime;
else
wait_time = 1;
if(wait_time > 0)
{
//ALOGE("WaitTime: %d", wait_time);
dii_rtc::Thread::SleepMs(wait_time);
}
}
}
void V_H264Encoder::OnFrame(const cricket::VideoFrame& frame)
{
dii_rtc::CritScope csB(&buffer_critsect_);
if (encoded_) {
dii_media_kit::VideoFrame video_frame(frame.video_frame_buffer(), 0, dii_rtc::TimeMillis() + 150, frame.rotation());
if (!video_frame.IsZeroSize()) {
if (render_buffers_->AddFrame(video_frame) == 1) {
// OK
}
}
}
}
int32_t V_H264Encoder::Encoded(const EncodedImage& encoded_image,
const CodecSpecificInfo* codec_specific_info,
const RTPFragmentationHeader* fragmentation)
{
callback_.OnEncodeDataCallback(false, encoded_image._buffer, encoded_image._length, dii_rtc::Time());
return 0;
}
} // namespace dii_media_kit
| 25.872146 | 124 | 0.679139 |
04813268b5dedf16ba721e7ea752c69ec47d33e2 | 3,040 | java | Java | jmx/src/main/java/com/lafaspot/jmetrics/common/MetricClassComposite.java | kevinliuyifeng/jmetrics | 34ca80fd4393be556abb5f6589c154c9502cfce4 | [
"Apache-2.0"
] | 3 | 2015-11-05T23:21:55.000Z | 2021-11-16T22:30:42.000Z | jmx/src/main/java/com/lafaspot/jmetrics/common/MetricClassComposite.java | kevinliuyifeng/jmetrics | 34ca80fd4393be556abb5f6589c154c9502cfce4 | [
"Apache-2.0"
] | 10 | 2017-08-07T20:29:34.000Z | 2019-05-03T18:08:19.000Z | jmx/src/main/java/com/lafaspot/jmetrics/common/MetricClassComposite.java | kevinliuyifeng/jmetrics | 34ca80fd4393be556abb5f6589c154c9502cfce4 | [
"Apache-2.0"
] | 20 | 2015-11-05T00:24:45.000Z | 2019-07-30T22:40:31.000Z | /*
* Copyright [yyyy] [name of copyright owner]
*
* ====================================================================
* 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.lafaspot.jmetrics.common;
import java.lang.reflect.Method;
import java.util.List;
import javax.annotation.Nonnull;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
/**
* CompositeType for monitor class.
*
* @author KevinL
*
*/
public class MetricClassComposite {
/** All the methods that has metric annotation. */
@Nonnull
private final String[] methodNames;
/** Class CompositeType. */
private final CompositeType metricClassCompositeType;
/** Method description. */
private static final String METHOD_DESCRIPTION = "Method: ";
/**
* Constructor.
*
* @param className used to Construct type
* @param metricClassName MetricClass name store in CompositeData type Description
* @param methods contains metric annotation
* @param methodCompositeType method CompositeType
* @throws OpenDataException Create class compositeType fail
*/
public MetricClassComposite(@Nonnull final String className, @Nonnull final String metricClassName, @Nonnull final List<Method> methods,
@Nonnull final MetricMethodComposite methodCompositeType) throws OpenDataException {
final int size = methods.size();
methodNames = new String[size];
final String[] methodDescriptions = new String[size];
@SuppressWarnings("rawtypes")
final OpenType[] methodTypes = new OpenType[size];
for (int i = 0; i < size; i++) {
final Method method = methods.get(i);
methodNames[i] = method.getName();
methodDescriptions[i] = METHOD_DESCRIPTION + methodNames[i];
methodTypes[i] = methodCompositeType.getCompositeType();
}
metricClassCompositeType = new CompositeType(className, metricClassName, methodNames, methodDescriptions, methodTypes);
}
/**
* Get the method names as key.
* @return method array of one monitor
*/
protected String[] getMethodNames() {
return methodNames;
}
/**
* Get class compositeType.
* @return the class CompositeType
*/
protected CompositeType getCompositeType() {
return metricClassCompositeType;
}
} | 36.190476 | 140 | 0.665461 |
c9feb5f6ef118e1bc085631820c3df7c64010e6f | 323 | swift | Swift | Mobile/iOS/Hunter/Hunter/App/Flows/Guest/iOSGuestFactory.swift | UTN-FRBA-Mobile/Hunter | 9531a0a1d263fc0af1c168e55e3d4b2a2f32d1d1 | [
"MIT"
] | null | null | null | Mobile/iOS/Hunter/Hunter/App/Flows/Guest/iOSGuestFactory.swift | UTN-FRBA-Mobile/Hunter | 9531a0a1d263fc0af1c168e55e3d4b2a2f32d1d1 | [
"MIT"
] | 2 | 2020-09-25T21:04:33.000Z | 2020-11-01T23:24:50.000Z | Mobile/iOS/Hunter/Hunter/App/Flows/Guest/iOSGuestFactory.swift | UTN-FRBA-Mobile/Hunter | 9531a0a1d263fc0af1c168e55e3d4b2a2f32d1d1 | [
"MIT"
] | null | null | null | import UIKit
struct iOSGuestFactory: GuestFactory {
let presenter: GuestPresenter
func guestController() -> UIViewController {
let controller = GuestViewController()
_ = controller.view
controller.buttonStack.addArrangedSubviews(presenter.actionsButton())
return controller
}
}
| 26.916667 | 77 | 0.712074 |
a1955d18bf8f9819a924e305a1719c31d9017d8e | 744 | tab | SQL | wordLists/wikt/wn-wikt-sna.tab | vatbub/auto-hotkey-noun-replacer | 467c34292c1cc6465cb2d4003a91021b763b22d7 | [
"Apache-2.0"
] | null | null | null | wordLists/wikt/wn-wikt-sna.tab | vatbub/auto-hotkey-noun-replacer | 467c34292c1cc6465cb2d4003a91021b763b22d7 | [
"Apache-2.0"
] | null | null | null | wordLists/wikt/wn-wikt-sna.tab | vatbub/auto-hotkey-noun-replacer | 467c34292c1cc6465cb2d4003a91021b763b22d7 | [
"Apache-2.0"
] | null | null | null | # Wiktionary sna http://wiktionary.org/ CC BY-SA
00017222-n sna:lemma mbesa
01613294-n sna:lemma gondo
01693783-n sna:lemma rwavhi
02084071-n sna:lemma imbwá
02206856-n sna:lemma nyuchi
02274259-n sna:lemma shavishavi
02403454-n sna:lemma mhóu
03249569-n sna:lemma ngoma
04401088-n sna:lemma runhare
05526384-n sna:lemma mboro
07815588-n sna:lemma mhiripiri
07847198-n sna:lemma ruwomba
07859284-n sna:lemma shuga
09896685-n sna:lemma muvezi
10787470-n sna:lemma vakadzi
13882961-n sna:lemma gonyaina tsazamativi
15156187-n sna:lemma nezuro
15163797-n sna:lemma Svondo
15163979-n sna:lemma Muvhuro
15164233-n sna:lemma Chitatu
15164354-n sna:lemma China
15164463-n sna:lemma Chishanu
15164570-n sna:lemma Chitanhatu
15166462-n sna:lemma maneru
| 28.615385 | 48 | 0.819892 |
d416ddc79833cebff96d5b4b4a38a9111267be84 | 2,255 | swift | Swift | Trips/views/components/IntegratedStepper.swift | katzrkool/trips | 0b0e206daa58ecbac4fa8bfee23026bebf00b76f | [
"MIT"
] | 4 | 2020-07-04T18:46:39.000Z | 2021-01-16T16:30:04.000Z | Trips/views/components/IntegratedStepper.swift | katzrkool/trips | 0b0e206daa58ecbac4fa8bfee23026bebf00b76f | [
"MIT"
] | 101 | 2019-11-27T05:59:19.000Z | 2021-04-29T22:58:45.000Z | Trips/views/components/IntegratedStepper.swift | lkellar/trips | 0b0e206daa58ecbac4fa8bfee23026bebf00b76f | [
"MIT"
] | null | null | null | //
// IntegratedStepper.swift
// Trips
//
// Created by Lucas Kellar on 2020-04-06.
// Copyright © 2020 Lucas Kellar. All rights reserved.
//
import SwiftUI
struct IntegratedStepper: View {
@Binding var quantity: Int
var upperLimit: Int
var lowerLimit: Int
@Environment(\.colorScheme) var colorScheme
var body: some View {
HStack {
Text("Quantity")
Spacer()
ZStack {
RoundedRectangle(cornerRadius: 7.92)
.fill((colorScheme == .dark ? Color(UIColor(red:0.24, green:0.24, blue:0.26, alpha:1.00)) : Color(UIColor(red:0.93, green:0.93, blue:0.94, alpha:1.00))))
.frame(width: 120, height: 35)
HStack {
Image(systemName: "minus")
.frame(height: 30)
.contentShape(Rectangle())
.onTapGesture {
if quantity > lowerLimit {
quantity -= 1
}
}
Spacer()
.frame(width: 10)
Text("|")
.foregroundColor(colorScheme == .dark ? Color(UIColor(red:0.29, green:0.29, blue:0.31, alpha:1.00)) : Color(UIColor(red:0.87, green:0.87, blue:0.88, alpha:1.00)))
Spacer()
.frame(width: 10)
Text("\(quantity)")
Spacer()
.frame(width: 10)
Text("|")
.foregroundColor(colorScheme == .dark ? Color(UIColor(red:0.29, green:0.29, blue:0.31, alpha:1.00)) : Color(UIColor(red:0.87, green:0.87, blue:0.88, alpha:1.00)))
Spacer()
.frame(width: 10)
Image(systemName: "plus")
.onTapGesture {
if quantity < upperLimit {
quantity += 1
}
}
}
}
}
}
}
struct IntegratedStepper_Previews: PreviewProvider {
static var previews: some View {
NoPreview()
}
}
| 34.166667 | 186 | 0.43592 |
4107bb09a501f634f3d9223415f1033399f1a997 | 484 | dart | Dart | pkg/front_end/test/patching/data/const_constructors/patch.dart | jtlapp/sdk | 0bca6aaf106b1d2752df8134d745743d52b6a78b | [
"BSD-3-Clause"
] | 2 | 2019-11-06T13:44:11.000Z | 2019-11-17T06:49:40.000Z | pkg/front_end/test/patching/data/const_constructors/patch.dart | jtlapp/sdk | 0bca6aaf106b1d2752df8134d745743d52b6a78b | [
"BSD-3-Clause"
] | 1 | 2021-01-21T14:45:59.000Z | 2021-01-21T14:45:59.000Z | pkg/front_end/test/patching/data/const_constructors/patch.dart | jtlapp/sdk | 0bca6aaf106b1d2752df8134d745743d52b6a78b | [
"BSD-3-Clause"
] | 3 | 2020-02-13T02:08:04.000Z | 2020-08-09T07:49:55.000Z | // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// ignore: import_internal_library
import 'dart:_internal';
@patch
class PatchedClass {
final int _field;
/*member: PatchedClass.:
initializers=[FieldInitializer(_field),SuperInitializer],
*/
@patch
const PatchedClass({int field}) : _field = field;
}
| 26.888889 | 77 | 0.733471 |
179c4421f25beeec20ea088427cf9fe730c3e675 | 5,067 | cs | C# | sdk/src/Services/PersonalizeEvents/Generated/Model/Event.cs | SammyEnigma/aws-sdk-net | 69988d8bbdea614b5088a33d92248806a10cdc7a | [
"Apache-2.0"
] | 2 | 2022-02-24T09:39:37.000Z | 2022-02-24T11:20:07.000Z | sdk/src/Services/PersonalizeEvents/Generated/Model/Event.cs | SammyEnigma/aws-sdk-net | 69988d8bbdea614b5088a33d92248806a10cdc7a | [
"Apache-2.0"
] | null | null | null | sdk/src/Services/PersonalizeEvents/Generated/Model/Event.cs | SammyEnigma/aws-sdk-net | 69988d8bbdea614b5088a33d92248806a10cdc7a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the personalize-events-2018-03-22.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.PersonalizeEvents.Model
{
/// <summary>
/// Represents user interaction event information sent using the <code>PutEvents</code>
/// API.
/// </summary>
public partial class Event
{
private string _eventId;
private string _eventType;
private string _properties;
private DateTime? _sentAt;
/// <summary>
/// Gets and sets the property EventId.
/// <para>
/// An ID associated with the event. If an event ID is not provided, Amazon Personalize
/// generates a unique ID for the event. An event ID is not used as an input to the model.
/// Amazon Personalize uses the event ID to distinquish unique events. Any subsequent
/// events after the first with the same event ID are not used in model training.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=256)]
public string EventId
{
get { return this._eventId; }
set { this._eventId = value; }
}
// Check to see if EventId property is set
internal bool IsSetEventId()
{
return this._eventId != null;
}
/// <summary>
/// Gets and sets the property EventType.
/// <para>
/// The type of event. This property corresponds to the <code>EVENT_TYPE</code> field
/// of the Interactions schema.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=256)]
public string EventType
{
get { return this._eventType; }
set { this._eventType = value; }
}
// Check to see if EventType property is set
internal bool IsSetEventType()
{
return this._eventType != null;
}
/// <summary>
/// Gets and sets the property Properties.
/// <para>
/// A string map of event-specific data that you might choose to record. For example,
/// if a user rates a movie on your site, you might send the movie ID and rating, and
/// the number of movie ratings made by the user.
/// </para>
///
/// <para>
/// Each item in the map consists of a key-value pair. For example,
/// </para>
///
/// <para>
/// <code>{"itemId": "movie1"}</code>
/// </para>
///
/// <para>
/// <code>{"itemId": "movie2", "eventValue": "4.5"}</code>
/// </para>
///
/// <para>
/// <code>{"itemId": "movie3", "eventValue": "3", "numberOfRatings": "12"}</code>
/// </para>
///
/// <para>
/// The keys use camel case names that match the fields in the Interactions schema. The
/// <code>itemId</code> and <code>eventValue</code> keys correspond to the <code>ITEM_ID</code>
/// and <code>EVENT_VALUE</code> fields. In the above example, the <code>eventType</code>
/// might be 'MovieRating' with <code>eventValue</code> being the rating. The <code>numberOfRatings</code>
/// would match the 'NUMBER_OF_RATINGS' field defined in the Interactions schema.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=1024)]
public string Properties
{
get { return this._properties; }
set { this._properties = value; }
}
// Check to see if Properties property is set
internal bool IsSetProperties()
{
return this._properties != null;
}
/// <summary>
/// Gets and sets the property SentAt.
/// <para>
/// The timestamp on the client side when the event occurred.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public DateTime SentAt
{
get { return this._sentAt.GetValueOrDefault(); }
set { this._sentAt = value; }
}
// Check to see if SentAt property is set
internal bool IsSetSentAt()
{
return this._sentAt.HasValue;
}
}
} | 34.006711 | 116 | 0.577659 |
16243ac1b295b488a30c7a1ceffe819903e26ef8 | 278 | h | C | YLCleaner/Xcode-RuntimeHeaders/Xcode3UI/Xcode3VariantFileReference-IDENavigableItemSupport.h | liyong03/YLCleaner | 7453187a884c8e783bda1af82cbbb51655ec41c6 | [
"MIT"
] | 1 | 2019-02-15T02:16:35.000Z | 2019-02-15T02:16:35.000Z | YLCleaner/Xcode-RuntimeHeaders/Xcode3UI/Xcode3VariantFileReference-IDENavigableItemSupport.h | liyong03/YLCleaner | 7453187a884c8e783bda1af82cbbb51655ec41c6 | [
"MIT"
] | null | null | null | YLCleaner/Xcode-RuntimeHeaders/Xcode3UI/Xcode3VariantFileReference-IDENavigableItemSupport.h | liyong03/YLCleaner | 7453187a884c8e783bda1af82cbbb51655ec41c6 | [
"MIT"
] | null | null | null | /*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "Xcode3VariantFileReference.h"
@interface Xcode3VariantFileReference (IDENavigableItemSupport)
- (id)navigableItem_name;
@end
| 21.384615 | 83 | 0.719424 |
a3093a45ed78cba591236912e9bca84b27f87b48 | 1,723 | ps1 | PowerShell | Config/Core-Functionality.ps1 | paulmarsy/Console | 9bb25382f4580fa68aa1f0424541842e08b4e330 | [
"MIT"
] | 3 | 2015-05-28T07:05:50.000Z | 2016-03-29T10:15:34.000Z | Config/Core-Functionality.ps1 | paulmarsy/Console | 9bb25382f4580fa68aa1f0424541842e08b4e330 | [
"MIT"
] | 1 | 2020-04-16T03:42:30.000Z | 2020-04-16T03:42:30.000Z | Config/Core-Functionality.ps1 | paulmarsy/Console | 9bb25382f4580fa68aa1f0424541842e08b4e330 | [
"MIT"
] | null | null | null | param(
$InstallPath = (Get-Item -Path Env:\CustomConsolesInstallPath | % Value)
)
# Constants
$PowerShellConsoleConstants = & (Join-Path $InstallPath "Config\Constants.ps1")
# Module Initialization
$private:ModuleInitializationRoot = Join-Path $InstallPath "Custom Consoles\PowerShell\ModuleInitialization"
@(
"2 - Configure Environment\Configure PATH Extensions.ps1"
) | % { & (Join-Path $private:ModuleInitializationRoot $_) }
# Functions
$private:FunctionExportsRoot = Join-Path $InstallPath "Custom Consoles\PowerShell\Exports\Functions"
@(
"Working Directory Helpers\User Scripts\_Internal\_Import-UserScripts.ps1"
"Working Directory Helpers\User Scripts\_Internal\_Promote-NewUserObjects.ps1"
"Working Directory Helpers\User Scripts\_Internal\_Remove-ExistingUserScripts.ps1"
"Working Directory Helpers\User Scripts\Import-UserScripts.ps1"
"PowerShell Utilities\New-DynamicParam.ps1"
"PowerShell Utilities\Test-PowerShellScriptSyntax.ps1"
"PowerShell Utilities\Test-PowerShellScript.ps1"
"PowerShell Utilities\Test-PowerShellDirectory.ps1"
"Windows\ConvertTo-DirectoryJunction.ps1"
"Invoke-Ternary.ps1"
"Test-Null.ps1"
) | % { . (Join-Path $private:FunctionExportsRoot $_) }
# Aliases
$private:AliasExportsRoot = Join-Path $InstallPath "Custom Consoles\PowerShell\Exports\Aliases"
@(
"0x003F+0x003A"
"Is"
) | % {
$alias = $_
if ($alias.StartsWith("0x")) {
$alias = [string]::Concat(($alias | % Split '+' | % { [char][int]($_) }))
}
$command = Get-Content -Path (Join-Path $private:AliasExportsRoot ("{0}.alias" -f $_)) | Select-Object -First 1
Set-Alias -Name $alias -Value $command -Force -Scope Script
} | 41.02381 | 113 | 0.719095 |
f5945e1251d296b1f762b201e0aa2927affeead6 | 5,393 | cpp | C++ | src/cetech/editor/private/log_view.cpp | ValtoForks/cetech | 03347c5ec34e8827024ae4ddd911bd0f804a85b0 | [
"CC0-1.0"
] | null | null | null | src/cetech/editor/private/log_view.cpp | ValtoForks/cetech | 03347c5ec34e8827024ae4ddd911bd0f804a85b0 | [
"CC0-1.0"
] | null | null | null | src/cetech/editor/private/log_view.cpp | ValtoForks/cetech | 03347c5ec34e8827024ae4ddd911bd0f804a85b0 | [
"CC0-1.0"
] | null | null | null | #include <stdio.h>
#include <cetech/debugui/debugui.h>
#include <cetech/editor/editor.h>
#include <celib/log.h>
#include <cetech/editor/log_view.h>
#include <cetech/debugui/private/ocornut-imgui/imgui.h>
#include <celib/array.inl>
#include <celib/ebus.h>
#include <cetech/debugui/icons_font_awesome.h>
#include "celib/hashlib.h"
#include "celib/memory.h"
#include "celib/api_system.h"
#include "celib/module.h"
#include <cetech/editor/dock.h>
#define WINDOW_NAME "Log view"
#define LOG_FORMAT "[%d|%s] -> %s"
#define LOG_ARGS worker_id, where, msg
struct log_item {
enum ce_log_level level;
int offset;
};
#define _G log_view_global
static struct _G {
log_item *log_items;
char *line_buffer;
ImGuiTextFilter filter;
int level_counters[5];
uint8_t level_mask;
bool visible;
ce_alloc *allocator;
} _G;
static int _levels[] = {LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DBG};
static ImVec4 _level_to_color[][4] = {
[LOG_INFO] = {{1.0f, 1.0f, 1.0f, 1.0f},
{0.5f, 0.5f, 0.5f, 1.0f}},
[LOG_WARNING] = {{1.0f, 1.0f, 0.0f, 1.0f},
{0.5f, 0.5f, 0.0f, 1.0f}},
[LOG_ERROR] = {{1.0f, 0.0f, 0.0f, 1.0f},
{0.5f, 0.0f, 0.0f, 1.0f}},
[LOG_DBG] = {{0.0f, 1.0f, 0.0f, 1.0f},
{0.0f, 0.5f, 0.0f, 1.0f}},
};
static const char *_level_to_label[4] = {
[LOG_INFO] = "I (%d)",
[LOG_WARNING] = "W (%d)",
[LOG_ERROR] = "E (%d)",
[LOG_DBG] = "D (%d)",
};
static void log_handler(enum ce_log_level level,
time_t time,
char worker_id,
const char *where,
const char *msg,
void *data) {
if (!_G.allocator) {
return;
}
++_G.level_counters[level];
int offset = ce_array_size(_G.line_buffer);
log_item item = {
.level = level,
.offset = offset
};
char buffer[1024];
int len = snprintf(buffer, CE_ARRAY_LEN(buffer), LOG_FORMAT, LOG_ARGS);
ce_array_push(_G.log_items, item, _G.allocator);
ce_array_push_n(_G.line_buffer, buffer, len + 1, _G.allocator);
}
static void ui_filter() {
_G.filter.Draw(ICON_FA_SEARCH);
}
static void ui_level_mask() {
char buffer[64];
for (int i = 0; i < CE_ARRAY_LEN(_levels); ++i) {
int level = _levels[i];
snprintf(buffer, CE_ARRAY_LEN(buffer),
_level_to_label[level], _G.level_counters[level]);
bool active = (_G.level_mask & (1 << level)) > 0;
ImGui::PushStyleColor(ImGuiCol_CheckMark, _level_to_color[level][0]);
ImGui::PushStyleColor(ImGuiCol_Text, _level_to_color[level][0]);
ImGui::PushStyleColor(ImGuiCol_FrameBg, _level_to_color[level][1]);
if (i > 0) {
ct_debugui_a0->SameLine(0, -1);
}
if (ct_debugui_a0->RadioButton(buffer, active)) {
if (!active) {
_G.level_mask |= (1 << level);
} else {
_G.level_mask &= ~(1 << level);
}
}
ImGui::PopStyleColor(3);
}
}
static void ui_log_items() {
ImGui::BeginChild("log_view_scrolling_region",
ImVec2(0, -ImGui::GetTextLineHeightWithSpacing()),
false, ImGuiWindowFlags_HorizontalScrollbar);
const int size = ce_array_size(_G.log_items);
for (int i = size - 1; i >= 0; --i) {
log_item *item = &_G.log_items[i];
const char *line = &_G.line_buffer[item->offset];
if (!_G.filter.PassFilter(line)) {
continue;
}
if (!(_G.level_mask & (1 << item->level))) {
continue;
}
int len = strlen(line);
ImGui::PushStyleColor(ImGuiCol_Text, _level_to_color[item->level][0]);
ct_debugui_a0->TextUnformatted(line, line + len);
ImGui::PopStyleColor();
}
ImGui::EndChild();
}
static void on_debugui(uint64_t dock) {
ui_filter();
ui_level_mask();
ui_log_items();
}
static const char *dock_title(uint64_t dock) {
return WINDOW_NAME;
}
static const char *name(uint64_t dock) {
return "log_view";
}
static uint64_t cdb_type() {
return LOG_VIEW;
};
static struct ct_dock_i0 ct_dock_i0 = {
.cdb_type = cdb_type,
.display_title = dock_title,
.draw_ui = on_debugui,
.name = name,
};
static void _init(struct ce_api_a0 *api) {
_G = {
.visible = true,
.level_mask = (uint8_t) ~0,
.allocator = ce_memory_a0->system,
};
ce_log_a0->register_handler(log_handler, NULL);
ce_api_a0->register_api(DOCK_INTERFACE_NAME, &ct_dock_i0);
ct_dock_a0->create_dock(LOG_VIEW, true);
}
static void _shutdown() {
ce_array_free(_G.log_items, _G.allocator);
ce_array_free(_G.line_buffer, _G.allocator);
_G = {};
}
CE_MODULE_DEF(
log_view,
{
CE_INIT_API(api, ce_memory_a0);
CE_INIT_API(api, ce_id_a0);
CE_INIT_API(api, ct_debugui_a0);
CE_INIT_API(api, ce_log_a0);
CE_INIT_API(api, ce_ebus_a0);
},
{
CE_UNUSED(reload);
_init(api);
},
{
CE_UNUSED(reload);
CE_UNUSED(api);
_shutdown();
}
) | 25.200935 | 78 | 0.566104 |
2dc78cbdf0a74623c1e50023ec72d0f0879a8f00 | 1,325 | swift | Swift | YILUtilKit/Swift_Category/String+Object.swift | yiliazhang/ComplicatedUIAndMutiRequestDemo | 439574fadc2eee6afc2ceb49732144f615473f08 | [
"MIT"
] | 4 | 2018-03-15T03:43:56.000Z | 2020-05-19T05:25:16.000Z | YILUtilKit/Swift_Category/String+Object.swift | yiliazhang/ComplicatedUIAndMutiRequestDemo | 439574fadc2eee6afc2ceb49732144f615473f08 | [
"MIT"
] | null | null | null | YILUtilKit/Swift_Category/String+Object.swift | yiliazhang/ComplicatedUIAndMutiRequestDemo | 439574fadc2eee6afc2ceb49732144f615473f08 | [
"MIT"
] | null | null | null | //
// String+Object.swift
// MOSP
//
// Created by apple on 2017/11/11.
//
import Foundation
import UIKit
extension String {
func toObject<T: Codable>(_ param: T) -> T? {
do {
let data = (self as AnyObject).data(using: String.Encoding.utf8.rawValue)
let obj = try JSONDecoder().decode(T.self, from: data!)
return obj
} catch {
print("解析出错啦:\(error)")
return nil
}
}
/// 类文件字符串转换为ViewController
///
/// - Parameter childControllerName: VC的字符串
/// - Returns: ViewController
func swiftClass() -> NSObject? {
// 1.获取命名空间
// 通过字典的键来取值,如果键名不存在,那么取出来的值有可能就为没值.所以通过字典取出的值的类型为AnyObject?
guard let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {
print("命名空间不存在")
return nil
}
// 2.通过命名空间和类名转换成类
// let cls : AnyClass? = NSClassFromString((clsName as! String) + "." + self)
let cls : AnyClass? = NSClassFromString(self)
// swift 中通过Class创建一个对象,必须告诉系统Class的类型
guard let clsType = cls as? NSObject.Type else {
print("无法转换成UIViewController")
return nil
}
// 3.通过Class创建对象
let childController = clsType.init()
return childController
}
}
| 28.191489 | 95 | 0.578113 |
e90ef31bd7a26001fb5fba2661af096442707701 | 29,242 | cpp | C++ | Source/CNTKv2LibraryDll/Common.cpp | vschs007/CNTK | 894d9e1a5d65d30cd33803c06a988844bb87fcb7 | [
"RSA-MD"
] | 5 | 2017-08-28T08:27:18.000Z | 2021-04-20T21:12:52.000Z | Source/CNTKv2LibraryDll/Common.cpp | vschs007/CNTK | 894d9e1a5d65d30cd33803c06a988844bb87fcb7 | [
"RSA-MD"
] | null | null | null | Source/CNTKv2LibraryDll/Common.cpp | vschs007/CNTK | 894d9e1a5d65d30cd33803c06a988844bb87fcb7 | [
"RSA-MD"
] | 3 | 2019-08-23T11:42:14.000Z | 2022-01-06T08:41:32.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#include "stdafx.h"
#include "CNTKLibrary.h"
#include "Utils.h"
#include "BestGpu.h"
#include <mutex>
#include <memory>
#include <algorithm>
#include <CPUMatrix.h> // For CPUMatrix::SetNumThreads
#include <thread>
#include "GPUMatrix.h"
#include "Globals.h"
#include "PerformanceProfiler.h"
#include "MPIWrapper.h"
#include "Basics.h"
#include "ProgressTracing.h"
#include "buildinfo.h"
#include "Constants.h"
extern bool g_shareNodeValueMatrices;
using namespace Microsoft::MSR::CNTK;
namespace CNTK
{
namespace Internal
{
static std::atomic_ullong s_nextUniqueId = ATOMIC_VAR_INIT(0);
size_t NewUniqueId()
{
return s_nextUniqueId++;
}
static std::atomic_ullong s_currentRandomSeed = ATOMIC_VAR_INIT(0);
// This is used to generate a default seed for stateful nodes (dropout, and both
// flavors of random sample). As a result, in distributed environment, each worker
// ends up having a different seed.
size_t GenerateRandomSeed()
{
static size_t numWorkers = 1, rank = 0;
static bool initialized = false;
if (MPIWrapper::GetTotalNumberOfMPINodes() != 0 && !initialized)
{
DistributedCommunicatorPtr communicator = MPICommunicator();
numWorkers = communicator->Workers().size();
rank = communicator->CurrentWorker().m_globalRank;
if (numWorkers < 1)
numWorkers = 1;
}
initialized = true;
return (numWorkers * s_currentRandomSeed++) + rank;
}
std::atomic<bool> s_reverseTensorShapesInErrorMessages(false);
void EnableReversingTensorShapesInErrorMessages()
{
s_reverseTensorShapesInErrorMessages.store(true);
}
bool IsReversingTensorShapesInErrorMessagesEnabled()
{
return s_reverseTensorShapesInErrorMessages.load();
}
std::atomic<bool> s_alwaysAllowSettingDefaultDevice(false);
void AlwaysAllowSettingDefaultDevice()
{
s_alwaysAllowSettingDefaultDevice.store(true);
}
bool IsSettingDefaultDeviceAlwaysAllowed()
{
return s_alwaysAllowSettingDefaultDevice.load();
}
std::atomic<bool> s_allowRenamingFunctions(false);
void AllowRenamingFunctions()
{
s_allowRenamingFunctions.store(true);
}
bool IsRenamingFunctionsAllowed()
{
return s_allowRenamingFunctions.load();
}
std::atomic<bool> s_disableAutomaticUnpackingOfPackedValues(false);
void SetAutomaticUnpackingOfPackedValues(bool disable)
{
s_disableAutomaticUnpackingOfPackedValues.store(disable);
}
bool IsAutomaticUnpackingOfPackedValuesDisabled()
{
return s_disableAutomaticUnpackingOfPackedValues.load();
}
void EnableForwardValuesSharing()
{
Microsoft::MSR::CNTK::Globals::SetShareNodeValueMatrices(/* enable = */ true);
}
void DisableForwardValuesSharing()
{
Microsoft::MSR::CNTK::Globals::SetShareNodeValueMatrices(/* enable = */ false);
}
void EnableGradientAccumulationOptimization()
{
Microsoft::MSR::CNTK::Globals::SetGradientAccumulationOptimization(/* enable = */ true);
}
void DisableGradientAccumulationOptimization()
{
Microsoft::MSR::CNTK::Globals::SetGradientAccumulationOptimization(/* enable = */ false);
}
void StartProfiler(const wstring& profilerDir, bool profilerSyncGpu, size_t profilerBufferSize)
{
std::wstring logSuffix = L"";
auto mpi = Microsoft::MSR::CNTK::MPIWrapper::GetInstance();
if (mpi)
{
logSuffix = std::to_wstring(mpi->CurrentNodeRank());
}
Microsoft::MSR::CNTK::ProfilerInit(
profilerDir,
profilerBufferSize,
logSuffix,
profilerSyncGpu);
}
void EnableProfiler()
{
Microsoft::MSR::CNTK::ProfilerEnable(true);
}
void DisableProfiler()
{
Microsoft::MSR::CNTK::ProfilerEnable(false);
}
void StopProfiler()
{
Microsoft::MSR::CNTK::ProfilerClose();
}
bool AreEquivalent(const Variable& var1, const Variable& var2, bool allowParameterAndConstantsEquivalence)
{
bool areDynamicAxesCompatible = (var1.DynamicAxes().size() == var2.DynamicAxes().size());
auto numAxes = var1.DynamicAxes().size();
for (size_t i = 0; areDynamicAxesCompatible && (i < numAxes); ++i)
areDynamicAxesCompatible = (var1.DynamicAxes()[i].IsOrdered() == var2.DynamicAxes()[i].IsOrdered());
bool areVarKindsCompatible = (var1.Kind() == var2.Kind()) && (var1.NeedsGradient() == var2.NeedsGradient());
if (!areVarKindsCompatible && allowParameterAndConstantsEquivalence)
{
areVarKindsCompatible = (var1.IsParameter() && var2.IsConstant()) || (var2.IsParameter() && var1.IsConstant());
}
return (areVarKindsCompatible &&
(var1.GetDataType() == var2.GetDataType()) &&
(var1.IsSparse() == var2.IsSparse()) &&
(var1.Name() == var2.Name()) &&
areDynamicAxesCompatible &&
((var1.Shape() == var2.Shape()) || (AsTensorShape(var1.Shape()) == AsTensorShape(var2.Shape()))));
}
bool AreEquivalent(const FunctionPtr& f1, const FunctionPtr& f2, std::unordered_set<std::wstring>& uids)
{
if (f1 == f2)
{
return true;
}
if (uids.find(f1->Uid()) != uids.end())
{
return true;
}
else
{
uids.insert(f1->Uid());
}
if (f1->Name() != f2->Name())
{
return false;
}
if (f1->Attributes() != f2->Attributes())
{
return false;
}
auto outputs1 = f1->Outputs();
auto outputs2 = f2->Outputs();
if (outputs1.size() != outputs2.size())
{
return false;
}
for (int i = 0; i < outputs1.size(); ++i)
{
if (!AreEquivalent(outputs1[i], outputs2[i]))
{
return false;
}
}
auto inputs1 = f1->Inputs();
auto inputs2 = f2->Inputs();
if (inputs1.size() != inputs2.size())
{
return false;
}
for (int i = 0; i < inputs1.size(); ++i)
{
if (!AreEquivalent(inputs1[i], inputs2[i]))
{
return false;
}
if (inputs1[i].IsOutput() && !AreEquivalent(inputs1[i].Owner(), inputs2[i].Owner(), uids))
{
return false;
}
}
return true;
}
bool AreEquivalent(const FunctionPtr& f1, const FunctionPtr& f2)
{
std::unordered_set<std::wstring> uids;
return AreEquivalent(f1, f2, uids);
}
template <typename ElementType>
bool AreEqual(const ElementType* data1, const ElementType* data2, size_t numElements, double relativeTolerance, double absoluteTolerance)
{
for (size_t i = 0; i < numElements; ++i)
{
auto firstValue = data1[i];
auto secondValue = data2[i];
ElementType allowedTolerance = (std::max<ElementType>)((ElementType)absoluteTolerance, std::abs(((ElementType)relativeTolerance) * firstValue));
if (std::abs(firstValue - secondValue) > allowedTolerance)
return false;
}
return true;
}
template <typename ElementType>
std::pair<ElementType*, NDArrayViewPtr> GetCPUDataPtr(const NDArrayView& view)
{
auto deviceType = view.Device().Type();
if (deviceType == DeviceKind::CPU)
return{ const_cast<ElementType*>(view.DataBuffer<ElementType>()), nullptr };
if (deviceType == DeviceKind::GPU)
{
auto tempCPUDataView = view.DeepClone(DeviceDescriptor::CPUDevice());
return{ tempCPUDataView->WritableDataBuffer<ElementType>(), tempCPUDataView };
}
LogicError("Invalid device type (%u).", (unsigned int)deviceType);
}
template <typename ElementType>
bool AreEqual(const NDArrayView& view1, const NDArrayView& view2, double relativeTolerance, double absoluteTolerance)
{
if (std::addressof(view1) == std::addressof(view2))
{
return true;
}
if (view1.GetDataType() != view2.GetDataType() ||
view1.Shape() != view2.Shape())
{
return false;
}
CNTK::NDArrayViewPtr temp1CpuDataView, temp2CpuDataView;
ElementType* data1;
ElementType* data2;
std::tie(data1, temp1CpuDataView) = GetCPUDataPtr<ElementType>(view1);
std::tie(data2, temp2CpuDataView) = GetCPUDataPtr<ElementType>(view2);
size_t numElements = view1.Shape().TotalSize();
return AreEqual(data1, data2, numElements, relativeTolerance, absoluteTolerance);
}
bool AreEqual(const NDArrayView& view1, const NDArrayView& view2, double relativeTolerance, double absoluteTolerance)
{
if (view1.GetDataType() == DataType::Float)
return AreEqual<float>(view1, view2, relativeTolerance, absoluteTolerance);
if (view1.GetDataType() == DataType::Double)
return AreEqual<double>(view1, view2, relativeTolerance, absoluteTolerance);
LogicError("AreEqual(NDArrayView): Unknown DataType.");
}
std::pair<const MaskKind*, NDMaskPtr> GetCPUDataPtr(const NDMask& mask)
{
if (mask.Device() == DeviceDescriptor::CPUDevice())
return{ mask.DataBuffer(), nullptr };
else
{
auto tempCPUMask = mask.DeepClone(DeviceDescriptor::CPUDevice());
return{ tempCPUMask->DataBuffer(), tempCPUMask };
}
}
bool AreEqual(const NDMask& mask1, const NDMask& mask2)
{
if (mask1.Shape() != mask2.Shape())
return false;
NDMaskPtr tempCPUMask1, tempCPUMask2;
const MaskKind* mask1Data = nullptr;
const MaskKind* mask2Data = nullptr;
std::tie(mask1Data, tempCPUMask1) = GetCPUDataPtr(mask1);
std::tie(mask2Data, tempCPUMask2) = GetCPUDataPtr(mask2);
size_t numElements = mask1.Shape().TotalSize();
for (size_t i = 0; i < numElements; ++i)
{
if (mask1Data[i] != mask2Data[i])
return false;
}
return true;
}
template <typename ElementType>
bool AreEqual(const ::CNTK::Value& value1, const ::CNTK::Value& value2, double relativeTolerance, double absoluteTolerance)
{
if (std::addressof(value1) == std::addressof(value2))
return true;
// If neither of the values have mask, we just compare the Data
if (!value1.Mask() && !value2.Mask())
return AreEqual(*value1.Data(), *value2.Data(), relativeTolerance, absoluteTolerance);
// Both or neither should have masks
if ((!value1.Mask() && value2.Mask()) || (!value2.Mask() && value1.Mask()) || !AreEqual(*value1.Mask(), *value2.Mask()))
return false;
if ((value1.GetDataType() != value2.GetDataType()) || (value1.Shape() != value2.Shape()))
return false;
NDMaskPtr tempCPUMask;
const MaskKind* maskData;
std::tie(maskData, tempCPUMask) = GetCPUDataPtr(*value1.Mask());
CNTK::NDArrayViewPtr temp1CpuDataView, temp2CpuDataView;
ElementType* data1;
ElementType* data2;
std::tie(data1, temp1CpuDataView) = GetCPUDataPtr<ElementType>(*value1.Data());
std::tie(data2, temp2CpuDataView) = GetCPUDataPtr<ElementType>(*value2.Data());
auto numMaskElements = value1.Mask()->Shape().TotalSize();
auto numElementsPerMaskUnit = value1.Shape().TotalSize() / numMaskElements;
for (size_t i = 0; i < numMaskElements; ++i)
{
if (maskData[i] != MaskKind::Invalid)
{
if (!AreEqual(data1 + (i * numElementsPerMaskUnit), data2 + (i * numElementsPerMaskUnit), numElementsPerMaskUnit, relativeTolerance, absoluteTolerance))
return false;
}
}
return true;
}
bool AreEqual(const ::CNTK::Value& value1, const ::CNTK::Value& value2, double relativeTolerance, double absoluteTolerance)
{
if (value1.GetDataType() == DataType::Float)
return AreEqual<float>(value1, value2, relativeTolerance, absoluteTolerance);
if (value1.GetDataType() == DataType::Double)
return AreEqual<double>(value1, value2, relativeTolerance, absoluteTolerance);
LogicError("AreEqual(Value): Unknown DataType.");
}
std::atomic<int> s_computationNetworkTraceLevel(0);
void SetComputationNetworkTraceLevel(int traceLevel)
{
s_computationNetworkTraceLevel.store(traceLevel);
}
int GetComputationNetworkTraceLevel()
{
return s_computationNetworkTraceLevel.load();
}
std::atomic<bool> s_computationNetworkTrackGapNans(false);
void SetComputationNetworkTrackGapNans(bool enable)
{
s_computationNetworkTrackGapNans.store(enable);
}
bool GetComputationNetworkTrackGapNans()
{
return s_computationNetworkTrackGapNans.load();
}
void SetGPUMemoryAllocationTraceLevel(int traceLevel)
{
Microsoft::MSR::CNTK::TracingGPUMemoryAllocator::SetTraceLevel(traceLevel);
}
void SetMathLibTraceLevel(int traceLevel)
{
Microsoft::MSR::CNTK::SetMathLibTraceLevel(traceLevel);
}
void ForceDeterministicAlgorithms()
{
Microsoft::MSR::CNTK::Globals::ForceDeterministicAlgorithms();
}
bool ShouldForceDeterministicAlgorithms()
{
return Microsoft::MSR::CNTK::Globals::ShouldForceDeterministicAlgorithms();
}
void EnableSynchronousGPUKernelExecution()
{
SyncGuard::EnableSync();
}
bool IsSynchronousGPUKernelExecutionEnabled()
{
return SyncGuard::IsSyncEnabled();
}
static std::atomic<bool> s_threadsAreSet(false);
bool MaxNumCPUThreadsSet()
{
return s_threadsAreSet;
}
size_t DefaultPackThresholdSizeInBytes()
{
return DEFAULT_PACK_THRESHOLD_SIZE_IN_BYTES;
}
}
std::atomic<TraceLevel> s_traceLevel(TraceLevel::Warning);
void SetTraceLevel(TraceLevel value)
{
using namespace Internal;
auto previousValue = s_traceLevel.exchange(value);
if (previousValue == value)
return;
if (value == TraceLevel::Info)
{
// V1 does not have an intermediate trace level,
// the logging is either disabled (trace level = 0)
// or enabled (trace level != 0);
SetComputationNetworkTraceLevel(int(value));
SetMathLibTraceLevel(int(value));
}
else if (previousValue == TraceLevel::Info)
{
SetComputationNetworkTraceLevel(0);
SetMathLibTraceLevel(0);
}
}
TraceLevel GetTraceLevel()
{
return s_traceLevel.load();
}
/*static*/ const NDShape NDShape::Unknown(1, SentinelDimValueForUnknownShape);
/*static*/ std::mutex DeviceDescriptor::s_mutex;
/*static*/ bool DeviceDescriptor::s_defaultDeviceFrozen(false);
/*static*/ std::unique_ptr<DeviceDescriptor> DeviceDescriptor::s_defaultDevice(nullptr);
/*static*/ std::vector<DeviceDescriptor> DeviceDescriptor::s_excludedDevices;
/*static*/ std::vector<DeviceDescriptor> DeviceDescriptor::s_allDevices;
/*static*/ std::vector<GPUProperties> DeviceDescriptor::s_gpuProperties;
static std::once_flag s_initAllDevicesFlag;
/*static*/ void DeviceDescriptor::Reset()
{
DeviceDescriptor::s_defaultDevice.reset(nullptr);
DeviceDescriptor::s_defaultDeviceFrozen = false;
DeviceDescriptor::s_excludedDevices.clear();
}
bool DeviceDescriptor::IsLocked() const
{
return Microsoft::MSR::CNTK::IsLocked(AsCNTKImplDeviceId(*this));
}
/*static*/ DeviceDescriptor DeviceDescriptor::UseDefaultDevice()
{
std::unique_lock<std::mutex> lock(s_mutex);
if (!s_defaultDeviceFrozen && s_defaultDevice == nullptr)
{
vector<int> excludedIds;
for (auto device : s_excludedDevices)
{
excludedIds.push_back(AsCNTKImplDeviceId(device));
}
auto id = Microsoft::MSR::CNTK::GetBestDevice(excludedIds);
auto selectedDevice = id >= 0 ? DeviceDescriptor::GPUDevice(id) : DeviceDescriptor::CPUDevice();
s_defaultDevice.reset(new DeviceDescriptor(selectedDevice));
}
s_defaultDeviceFrozen = true;
return *s_defaultDevice;
}
/*static*/ bool DeviceDescriptor::TrySetDefaultDevice(const DeviceDescriptor& newDefaultDevice, bool acquireDeviceLock)
{
std::unique_lock<std::mutex> lock(s_mutex);
if (s_defaultDevice != nullptr && newDefaultDevice == *s_defaultDevice)
return !acquireDeviceLock || Microsoft::MSR::CNTK::TryLock(AsCNTKImplDeviceId(newDefaultDevice));
// As a testing backdoor we allow changing the default device even after being "used/frozen"
if (!Internal::IsSettingDefaultDeviceAlwaysAllowed() && s_defaultDeviceFrozen)
// TODO: alternatively, print a warning and return false.
{
RuntimeError("Process wide default device cannot be changed since it has been frozen by being implicitly used "
"as the default device in a CNTK API call; Current default = %S, New default = %S.",
s_defaultDevice->AsString().c_str(), newDefaultDevice.AsString().c_str());
}
if (std::find(s_excludedDevices.begin(), s_excludedDevices.end(), newDefaultDevice) != s_excludedDevices.end())
return false;
if (acquireDeviceLock && !Microsoft::MSR::CNTK::TryLock(AsCNTKImplDeviceId(newDefaultDevice)))
return false;
s_defaultDevice.reset(new DeviceDescriptor(newDefaultDevice));
if (!acquireDeviceLock)
Microsoft::MSR::CNTK::ReleaseLock();
return true;
}
/*static*/ void DeviceDescriptor::SetExcludedDevices(const std::vector<DeviceDescriptor>& excluded)
{
std::unique_lock<std::mutex> lock(s_mutex);
s_excludedDevices = excluded;
}
/*static*/ const std::vector<DeviceDescriptor>& DeviceDescriptor::AllDevices()
{
using namespace Microsoft::MSR::CNTK;
std::call_once(s_initAllDevicesFlag, [&]
{
#ifndef CPUONLY
auto allGpusData = GetAllGpusData();
for (const auto& gpuData : allGpusData)
{
if (gpuData.validity == GpuValidity::Valid)
{
s_allDevices.push_back(DeviceDescriptor((unsigned int) gpuData.deviceId, DeviceKind::GPU));
s_gpuProperties.push_back(
{
(unsigned int)gpuData.deviceId,
gpuData.versionMajor,
gpuData.versionMinor,
gpuData.cudaCores,
gpuData.name,
gpuData.totalMemory,
});
}
}
#endif
s_allDevices.push_back(DeviceDescriptor::CPUDevice());
});
return s_allDevices;
}
/*static*/ DeviceDescriptor DeviceDescriptor::GPUDevice(unsigned int deviceId)
{
const auto& allDevices = AllDevices();
if (std::none_of(allDevices.begin(), allDevices.end(),
[deviceId](const DeviceDescriptor& device){ return device.Type() == DeviceKind::GPU && device.Id() == deviceId; }))
{
InvalidArgument("Specified GPU device id (%u) is invalid.", deviceId);
}
return { deviceId, DeviceKind::GPU };
}
/*static*/ const GPUProperties& DeviceDescriptor::GetGPUProperties(const DeviceDescriptor& device)
{
if (device.Type() == DeviceKind::CPU)
InvalidArgument("GPU properties cannot be obtained for a CPU device.");
// Now, make sure that the device vectores are initialized.
const auto& allDevices = AllDevices();
UNUSED(allDevices);
auto result = std::find_if(s_gpuProperties.begin(), s_gpuProperties.end(),
[&device](const GPUProperties& props) { return device.Id() == props.deviceId; });
if (result == s_gpuProperties.end())
InvalidArgument("Could not find properties for the specified GPU device (id=%u).", device.Id());
return *result;
}
/*static*/ const std::wstring Axis::StaticAxisNamePrefix = L"staticAxisIdx=";
/*static*/ const int Axis::SentinelStaticAxisIndexValueForDynamicAxes = std::numeric_limits<int>::max();
/*static*/ const int Axis::SentinelStaticAxisIndexValueForAllStaticAxes = std::numeric_limits<int>::max() - 1;
/*static*/ const int Axis::SentinelStaticAxisIndexValueForUnknownAxes = std::numeric_limits<int>::max() - 2;
/*static*/ const int Axis::SentinelEndStaticAxisIndexValue = std::numeric_limits<int>::max() - 3;
/*static*/ const int Axis::SentinelStaticAxisIndexValueForAllAxes = std::numeric_limits<int>::max() - 4;
/*static*/ Axis::UniqueDynamicAxesNames Axis::s_uniqueDynamicAxisNames;
bool Axis::UniqueDynamicAxesNames::RegisterAxisName(const std::wstring& axisName)
{
std::unique_lock<std::mutex> lock(m_mutex);
return m_allKnownDynamicAxisNames.insert(axisName).second;
}
const std::wstring& Axis::UniqueDynamicAxesNames::NewUniqueDynamicAxisName(const std::wstring& axisNamePrefix)
{
std::unique_lock<std::mutex> lock(m_mutex);
if (m_allKnownDynamicAxisNames.find(axisNamePrefix) == m_allKnownDynamicAxisNames.end())
{
m_allKnownDynamicAxisNames.insert(axisNamePrefix);
return axisNamePrefix;
}
for (size_t i = 1;; i++)
{
auto newDynamicAxisName = axisNamePrefix + std::to_wstring(i);
if (m_allKnownDynamicAxisNames.find(newDynamicAxisName) == m_allKnownDynamicAxisNames.end())
{
m_allKnownDynamicAxisNames.insert(newDynamicAxisName);
return *m_allKnownDynamicAxisNames.find(newDynamicAxisName);
}
}
}
static std::shared_ptr<std::vector<Axis>> s_defaultInputVariableDynamicAxes, s_unknownDynamicAxes;
static std::once_flag s_initDefaultInputVariableDynamicAxesFlag, s_initUnknownDynamicAxesFlag;
/*static*/ const std::vector<Axis>& Axis::DefaultInputVariableDynamicAxes()
{
std::call_once(s_initDefaultInputVariableDynamicAxesFlag, []
{
s_defaultInputVariableDynamicAxes.reset(new std::vector<Axis>({ Axis::DefaultDynamicAxis(), Axis::DefaultBatchAxis() }));
});
return *s_defaultInputVariableDynamicAxes;
}
/*static*/ const std::vector<Axis>& Axis::UnknownDynamicAxes()
{
std::call_once(s_initUnknownDynamicAxesFlag, []
{
s_unknownDynamicAxes.reset(new std::vector<Axis>({ Axis(SentinelStaticAxisIndexValueForUnknownAxes) }));
});
return *s_unknownDynamicAxes;
}
/*static*/ const Axis& Axis::DefaultDynamicAxis()
{
static const Axis s_defaultDynamicAxis(L"defaultDynamicAxis");
return s_defaultDynamicAxis;
}
/*static*/ const Axis& Axis::OperandSequenceAxis()
{
static const Axis s_operandSequenceAxis(L"__operandSequenceAxis");
return s_operandSequenceAxis;
}
/*static*/ const Axis& Axis::DefaultBatchAxis()
{
static const Axis s_defaultBatchAxis(L"defaultBatchAxis", false);
return s_defaultBatchAxis;
}
/*static*/ const Axis& Axis::AllStaticAxes()
{
static const Axis s_allStaticAxes(SentinelStaticAxisIndexValueForAllStaticAxes);
return s_allStaticAxes;
}
/*static*/ const Axis& Axis::AllAxes()
{
static const Axis s_allAxes(SentinelStaticAxisIndexValueForAllAxes);
return s_allAxes;
}
void Axis::RegisterAxisName(const std::wstring& axisName)
{
s_uniqueDynamicAxisNames.RegisterAxisName(axisName);
}
std::wstring Axis::AsString() const
{
std::wstringstream wss;
wss << "Axis('";
wss << m_name;
wss << "')";
return wss.str();
}
void SetMaxNumCPUThreads(size_t numCPUThreads)
{
Internal::s_threadsAreSet = true;
Microsoft::MSR::CNTK::CPUMatrix<float>::SetNumThreads((int)numCPUThreads);
}
size_t GetMaxNumCPUThreads()
{
return Microsoft::MSR::CNTK::CPUMatrix<float>::GetMaxNumThreads();
}
static std::atomic<bool> s_defaultUnitGainValue(true);
bool DefaultUnitGainValue()
{
return s_defaultUnitGainValue;
}
void SetDefaultUnitGainValue(bool value)
{
s_defaultUnitGainValue.store(value);
}
static std::atomic<bool> s_defaultUseMeanGradient(false);
bool DefaultUseMeanGradientValue()
{
return s_defaultUseMeanGradient;
}
void SetDefaultUseMeanGradientValue(bool value)
{
s_defaultUseMeanGradient.store(value);
}
template <class E>
__declspec_noreturn void ThrowFormatted(const char* format, ...)
{
va_list args;
va_start(args, format);
Microsoft::MSR::CNTK::ThrowFormattedVA<E>(format, args);
va_end(args);
}
void PrintBuiltInfo()
{
LOGPRINTF(stderr, "-------------------------------------------------------------------\n");
LOGPRINTF(stderr, "Build info: \n\n");
LOGPRINTF(stderr, "\t\tBuilt time: %s %s\n", __DATE__, __TIME__);
LOGPRINTF(stderr, "\t\tLast modified date: %s\n", __TIMESTAMP__);
#ifdef _BUILDTYPE_
LOGPRINTF(stderr, "\t\tBuild type: %s\n", _BUILDTYPE_);
#endif
#ifdef _BUILDTARGET_
LOGPRINTF(stderr, "\t\tBuild target: %s\n", _BUILDTARGET_);
#endif
#ifdef _WITH_1BITSGD_
LOGPRINTF(stderr, "\t\tWith 1bit-SGD: %s\n", _WITH_1BITSGD_);
#endif
#ifdef _WITH_ASGD_
LOGPRINTF(stderr, "\t\tWith ASGD: %s\n", _WITH_ASGD_);
#endif
#ifdef _MATHLIB_
LOGPRINTF(stderr, "\t\tMath lib: %s\n", _MATHLIB_);
#endif
#ifdef _CUDA_PATH_
LOGPRINTF(stderr, "\t\tCUDA_PATH: %s\n", _CUDA_PATH_);
#endif
#ifdef _CUB_PATH_
LOGPRINTF(stderr, "\t\tCUB_PATH: %s\n", _CUB_PATH_);
#endif
#ifdef _CUDNN_PATH_
LOGPRINTF(stderr, "\t\tCUDNN_PATH: %s\n", _CUDNN_PATH_);
#endif
#ifdef _GIT_EXIST
LOGPRINTF(stderr, "\t\tBuild Branch: %s\n", _BUILDBRANCH_);
LOGPRINTF(stderr, "\t\tBuild SHA1: %s\n", _BUILDSHA1_);
#endif
#ifdef _BUILDER_
LOGPRINTF(stderr, "\t\tBuilt by %s on %s\n", _BUILDER_, _BUILDMACHINE_);
#endif
#ifdef _BUILDPATH_
LOGPRINTF(stderr, "\t\tBuild Path: %s\n", _BUILDPATH_);
#endif
#ifdef _MPI_NAME_
LOGPRINTF(stderr, "\t\tMPI distribution: %s\n", _MPI_NAME_);
#endif
#ifdef _MPI_VERSION_
LOGPRINTF(stderr, "\t\tMPI version: %s\n", _MPI_VERSION_);
#endif
LOGPRINTF(stderr, "-------------------------------------------------------------------\n");
}
template CNTK_API __declspec_noreturn void ThrowFormatted<std::runtime_error>(const char* format, ...);
template CNTK_API __declspec_noreturn void ThrowFormatted<std::logic_error>(const char* format, ...);
template CNTK_API __declspec_noreturn void ThrowFormatted<std::invalid_argument>(const char* format, ...);
}
| 34.853397 | 172 | 0.59907 |
fbda5edf75873401ec67ee53a26df398d814b2f6 | 1,015 | java | Java | service/service-oss/src/main/java/com/aiden/oss/utils/ConstantPropertiesUtils.java | AidenDan/education-parent | d35629990d76371f575354a8240877d4fe398397 | [
"Apache-2.0"
] | 1 | 2021-01-29T15:29:44.000Z | 2021-01-29T15:29:44.000Z | service/service-oss/src/main/java/com/aiden/oss/utils/ConstantPropertiesUtils.java | AidenDan/education-parent | d35629990d76371f575354a8240877d4fe398397 | [
"Apache-2.0"
] | null | null | null | service/service-oss/src/main/java/com/aiden/oss/utils/ConstantPropertiesUtils.java | AidenDan/education-parent | d35629990d76371f575354a8240877d4fe398397 | [
"Apache-2.0"
] | null | null | null | package com.aiden.oss.utils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author Aiden
* @version 1.0
* @description
* @date 2021-1-30 12:35:48
*/
@Component
public class ConstantPropertiesUtils implements InitializingBean {
public static String oss_endPoint;
public static String oss_keyId;
public static String oss_keySecret;
public static String oss_bucketName;
@Value("${aliyun.oss.file.endpoint}")
private String endPoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
@Override
public void afterPropertiesSet() throws Exception {
oss_endPoint = endPoint;
oss_keyId = keyId;
oss_keySecret = keySecret;
oss_bucketName = bucketName;
}
}
| 26.710526 | 66 | 0.714286 |
b1e93a89a13e0ad38b7272f362dbf6f6050f3021 | 2,849 | swift | Swift | Loady/Classes/Animations/LoadyTopLineAnimation.swift | FedeGens/loady | 8eb8c74a46eaf0657162bd4e6b4d4e1da31c0207 | [
"MIT"
] | 848 | 2019-02-04T08:55:17.000Z | 2022-03-12T13:07:06.000Z | Loady/Classes/Animations/LoadyTopLineAnimation.swift | FedeGens/loady | 8eb8c74a46eaf0657162bd4e6b4d4e1da31c0207 | [
"MIT"
] | 10 | 2019-02-08T04:22:28.000Z | 2020-10-21T14:35:30.000Z | Loady/Classes/Animations/LoadyTopLineAnimation.swift | FedeGens/loady | 8eb8c74a46eaf0657162bd4e6b4d4e1da31c0207 | [
"MIT"
] | 55 | 2019-02-04T08:55:18.000Z | 2022-03-09T15:24:45.000Z | //
// LoadyTopLineAnimation.swift
// loady
//
// Created by Farshad Jahanmanesh on 11/6/19.
// Copyright © 2019 farshadJahanmanesh. All rights reserved.
//
import UIKit
public extension LoadyAnimationType {
static func topLine()->LoadyTopLineAnimation{
return LoadyTopLineAnimation()
}
}
public class LoadyTopLineAnimation {
public static var animationTypeKey: LoadyAnimationType.Key = .init(rawValue: "indicator")
lazy var activiyIndicator : LoadyActivityIndicator = { UIActivityIndicatorView() }()
private unowned var loady: Loadiable!
var loadingLayer: CAShapeLayer?
private var loading: Bool = false
///line loading
private func createTopLineLoading(){
//create our loading layer and line path
let loadingLayer = CAShapeLayer();
let path = UIBezierPath();
//height of the line
let lineHeight : CGFloat = 2.0;
//center the layer in our view and set the bounds
loadingLayer.position = CGPoint(x:self.loady.frame.size.width / 2,y: -1);
loadingLayer.bounds = CGRect(x:0,y: 0, width: self.loady.frame.size.width, height: lineHeight);
//draw our line
path.move(to: CGPoint(x:0,y: -1))
path.addLine(to: CGPoint(x:loadingLayer.bounds.size.width/2.4,y: -1))
//set the path layer, and costumizing it
loadingLayer.path = path.cgPath;
loadingLayer.strokeColor = self.loady.loadingColor.cgColor;
loadingLayer.strokeEnd = 1;
loadingLayer.lineWidth = lineHeight;
loadingLayer.lineCap = CAShapeLayerLineCap(rawValue: "round");
loadingLayer.contentsScale = UIScreen.main.scale;
loadingLayer.accessibilityHint = "button_topline_loading";
loadingLayer.opacity = 0
//add the new layer
self.loady.addSublayer(loadingLayer);
//animated path
let animatedPath = UIBezierPath()
animatedPath.move(to: CGPoint(x:loadingLayer.bounds.size.width / 1.2,y: -1))
animatedPath.addLine(to: CGPoint(x:loadingLayer.bounds.size.width,y: -1))
let animateOpacity = LoadyCore.createBasicAnimation(keypath: "opacity", from: 0, to: 1,duration : 0.6)
animateOpacity.isRemovedOnCompletion = false
animateOpacity.fillMode = .forwards
//create our animation and add it to the layer, animate indictor from left to right
let animation = LoadyCore.createBasicAnimation(keypath: "path", from: path.cgPath, to: animatedPath.cgPath)
animation.autoreverses = true;
animation.repeatCount = 100;
animation.isRemovedOnCompletion = false
loadingLayer.add(animation,forKey:nil);
loadingLayer.add(animateOpacity,forKey:nil);
self.loadingLayer = loadingLayer
}
}
extension LoadyTopLineAnimation: LoadyAnimation {
public func inject(loady: Loadiable) {
self.loady = loady
}
public func isLoading() -> Bool {
return loading
}
public func run() {
loading = true
createTopLineLoading()
}
public func stop() {
loading = false
self.loadingLayer?.removeFromSuperlayer()
}
}
| 31.655556 | 109 | 0.744472 |
e551253ef76003889ea9e85896fe28b540ef186d | 1,158 | swift | Swift | ScrollStackKitDemo/Views/CollectionView/VerticalCollectionViewDelegate.swift | Marcodeg/ScrollStackKit | 598ff0235f0336ed33f11e2e4c966a8a26e88948 | [
"MIT"
] | 2 | 2021-10-11T08:52:26.000Z | 2021-10-11T08:58:25.000Z | ScrollStackKitDemo/Views/CollectionView/VerticalCollectionViewDelegate.swift | Marcodeg/ScrollStackKit | 598ff0235f0336ed33f11e2e4c966a8a26e88948 | [
"MIT"
] | null | null | null | ScrollStackKitDemo/Views/CollectionView/VerticalCollectionViewDelegate.swift | Marcodeg/ScrollStackKit | 598ff0235f0336ed33f11e2e4c966a8a26e88948 | [
"MIT"
] | null | null | null | //
// VerticalCollectionViewDelegate.swift
// ScrollStackKitDemo
//
// Created by Marco Del Giudice on 08/10/21.
//
import UIKit
class VerticalCollectionViewDelegate: NSObject, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
private let itemsPerRow: CGFloat = 1
private let sectionInsets = UIEdgeInsets(top: 8, left: 24, bottom: 16, right: 24)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInsets
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let paddingSpace = sectionInsets.left * 2
let widthPerItem = (UIScreen.main.bounds.width - paddingSpace) / itemsPerRow
return CGSize(width: widthPerItem, height: 200)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return sectionInsets.left
}
}
| 38.6 | 170 | 0.75475 |
75fa4c1334f789ff9fdd6824def8e28fdec92dad | 9,632 | php | PHP | resources/views/star/order_detail.blade.php | wangdeyi27/Honglema | 5d2016601a7b524d5f6bda207fc8a3020c1e07b7 | [
"MIT"
] | 1 | 2018-12-26T10:11:31.000Z | 2018-12-26T10:11:31.000Z | resources/views/star/order_detail.blade.php | EricWang427/honglema | 5d2016601a7b524d5f6bda207fc8a3020c1e07b7 | [
"MIT"
] | null | null | null | resources/views/star/order_detail.blade.php | EricWang427/honglema | 5d2016601a7b524d5f6bda207fc8a3020c1e07b7 | [
"MIT"
] | null | null | null | @extends('star.star_layouts')
@section('title', "红了吗(试用版)")
@section('body')
@section('page-main')
<header class="bar bar-nav">
<a class="button button-link button-nav pull-left back" href="javascript:history.go(-1)">
<span class="icon icon-left"></span>
返回
</a>
<h1 class="title">订单详情</h1>
</header>
<div class="content" style="margin-bottom: 5rem">
<div class="list-block" style="margin-top:0; margin-bottom:0;">
<ul>
<li>
<div valign="bottom" class="card-header color-white no-border no-padding" style="height:6rem">
<img class='card-cover' style="height:100%" src="{{$data['activity']->picture}}" alt="">
</div>
</li>
</ul>
<ul>
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title" style="font-size:80%;">{{ $data['activity']->title}}</div>
<div id="f_merchant_name" class="item-after" style="font-size:80%;">¥ {{$data['price']}}</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label" style="font-size:80%;">活动时间</div>
<div class="item-input" style="font-size:80%; color:#666666">
<p>{{$data['activity']->time_within}}</p>
</div>
</div>
</div>
<div class="item-content">
<div class="item-inner">
<div class="item-title label" style="font-size:80%;">活动要求</div>
<div class="item-input" style="font-size:80%; color:#666666">
<p>{{$data['activity']->claim}}</p>
</div>
</div>
</div>
@if($data['order']->status==1)
<div class="item-content">
<div class="item-inner">
<div class="item-title label" style="font-size:80%;">抢单场次</div>
<div class="item-input" style="font-size:80%; color:#666666">
<p>{{$data['order']->expectation_num}}</p>
</div>
</div>
</div>
@endif
@if($data['order']->status==2)
<div class="item-content">
<div class="item-inner">
<div class="item-title label" style="font-size:80%;">分配场次</div>
<div class="item-input" style="font-size:80%; color:#666666">
<p>{{$data['task']->show_num}}</p>
</div>
</div>
</div>
@endif
</li>
</ul>
</div>
<div class="list-block" style="margin-bottom: 0px;margin-top:1rem">
<ul>
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title" style="font-size:80%;">商品信息</div>
</div>
</div>
</li>
</ul>
</div>
<div class="list-block" style="margin:0px ">
<ul>
@foreach ($commodities as $commodity)
<li>
<a href="<?php echo (strpos($commodity->url,'http') === 0) ? $commodity->url : 'http://'.$commodity->url; ?>" style="">
<div class="item-content">
<div class="item-inner">
<div class="item-title" style="font-size:80%;">{{$commodity->name}}</div>
</div>
</div>
</a>
</li>
@endforeach
</ul>
</div>
@if($data['order']->status==2)
<div class="list-block" style="margin-top: 0px;margin-bottom: 2rem" >
<ul>
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title" style="font-size:80%;">物流信息</div>
</div>
<div class="item-after">
<div class="item-title" style="font-size:80%;">
@if($data['task']->is_shipping==0) 无需邮寄样品
@elseif($data['order']->status==2&&$data['task']->status>=2&&$data['task']->is_shipping>=1)
{{$data['task']->express_company}}
{{$data['task']->express_num}}
@endif
</div>
</div>
</div>
</li>
</ul>
</div>
@endif
@if($data['order']->status==2&&$data['task']->status>=4)
<div class="list-block" style="margin-top: 0px;margin-bottom: 5rem" >
<ul>
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title" style="font-size:80%;">商家评论</div>
</div>
<div class="item-after">
<div class="item-title" style="font-size:80%;">
@if($data['order']->status==2&&$data['task']->status==2)
{{$data['task']->evaluation}}
@endif
</div>
</div>
</div>
</li>
</ul>
</div>
@endif
</div>
<div class="list-block" style="background-color:#cccccc;position:fixed; width:100%; bottom:2.5rem; margin-bottom:0; overflow:visible;">
<div class="item-content">
<div class="item-inner">
@if($data['order']->status==1&&$data['isAvailable']==true)
<div class="item-title" style="font-size:80%;">正在审核抢单 </div>
<div class="item-after">
<a href="#" onclick="$.cancelOrder({{$data['order']->order_id}})" class="button button-dark" style="border:0; background-color:#ee5555; color:white;">取消申请</a></div>
@elseif($data['order']->status==2&&$data['task']->status==1)
<div class="item-title" style="font-size:80%;">等待商家发货 </div>
@elseif($data['order']->status==2&&$data['task']->status==2&&$data['task']->is_shipping==1)
<div class="item-title" style="font-size:80%;">商家已发货 </div>
<div class="item-after">
<a href="javascript:ship_confirm({{$data['task']->task_id}})" class="button button-dark" style="border:0; background-color:#ee5555; color:white;">确认收货</a></div>
@elseif($data['order']->status==2&&$data['task']->status==2&&$data['task']->is_shipping==2)
<div class="item-title" style="font-size:80%;">已收货 </div>
<div class="item-after">
<a href="task_result?task_id={{$data['task']->task_id}}" class="button button-dark" style="border:0; background-color:#ee5555; color:white;">提交结果</a>
<a href="javascript:finish_task({{$data['task']->task_id}})" class="button button-dark" style="border:0; background-color:#ee5555; color:white;">完成任务</a>
</div>
@elseif($data['order']->status==2&&$data['task']->status==2&&$data['task']->is_shipping==0)
<div class="item-title" style="font-size:80%;">无样品,任务进行中 </div>
<div class="item-after">
<a href="task_result?task_id={{$data['task']->task_id}}" class="button button-dark" style="border:0; background-color:#ee5555; color:white;">提交结果</a>
<a href="javascript:finish_task({{$data['task']->task_id}})" class="button button-dark" style="border:0; background-color:#ee5555; color:white;">完成任务</a>
</div>
@elseif($data['order']->status==2&&$data['task']->status==3)
<div class="item-title" style="font-size:80%;">任务已完成,等待商家评论 </div>
@elseif($data['order']->status==2&&$data['task']->status==4)
<div class="item-title" style="font-size:80%;">商家已完成评价,任务结束 </div>
@elseif($data['order']->status==0)
<div class="item-title" style="font-size:80%;">抢单已取消,任务结束 </div>
@elseif($data['order']->status==1&&$data['isAvailable']==false)
<div class="item-title" style="font-size:80%;">该活动已被抢光 </div>
@endif
</div> </div> </div>
@include("star.star_footer")
@overwrite
@include('partial/jquery_mobile_page', ["page_id" => "main"])
| 51.784946 | 188 | 0.417255 |
8041d55786c64c685986045db8bc82f0029d616e | 457 | java | Java | src/main/java/com/fakecompany/personmonolith/model/ImageRepository.java | antipatron/person-monolith | 5d8f0f9b04e377010c307c018b9d6436c8865930 | [
"MIT"
] | null | null | null | src/main/java/com/fakecompany/personmonolith/model/ImageRepository.java | antipatron/person-monolith | 5d8f0f9b04e377010c307c018b9d6436c8865930 | [
"MIT"
] | null | null | null | src/main/java/com/fakecompany/personmonolith/model/ImageRepository.java | antipatron/person-monolith | 5d8f0f9b04e377010c307c018b9d6436c8865930 | [
"MIT"
] | null | null | null | package com.fakecompany.personmonolith.model;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.Optional;
@EnableMongoRepositories
public interface ImageRepository extends MongoRepository<Image, String> {
Optional<Image> findByPersonId(Integer personId);
Optional<Image> findByPersonIdAndId(Integer personId, String id);
}
| 25.388889 | 82 | 0.829322 |
e56f21c0506ae0495f1f7069b1bc058887d8742c | 4,544 | asm | Assembly | deps/gmp.js/mpn/powerpc32/vmx/copyd.asm | 6un9-h0-Dan/cobaul | 11115a7a77924d6e1642f847c613efb25f217e56 | [
"MIT"
] | 184 | 2020-04-15T14:28:37.000Z | 2020-09-22T15:57:55.000Z | deps/gmp.js/mpn/powerpc32/vmx/copyd.asm | 6un9-h0-Dan/cobaul | 11115a7a77924d6e1642f847c613efb25f217e56 | [
"MIT"
] | 3 | 2020-09-22T05:09:36.000Z | 2020-09-22T11:56:00.000Z | deps/gmp.js/mpn/powerpc32/vmx/copyd.asm | 6un9-h0-Dan/cobaul | 11115a7a77924d6e1642f847c613efb25f217e56 | [
"MIT"
] | 5 | 2020-04-21T19:50:23.000Z | 2020-09-22T10:58:02.000Z | dnl PowerPC-32/VMX and PowerPC-64/VMX mpn_copyd.
dnl Copyright 2006 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of the GNU Lesser General Public License as published
dnl by the Free Software Foundation; either version 3 of the License, or (at
dnl your option) any later version.
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
dnl License for more details.
dnl You should have received a copy of the GNU Lesser General Public License
dnl along with the GNU MP Library. If not, see http://www.gnu.org/licenses/.
include(`../config.m4')
C 16-byte coaligned unaligned
C cycles/limb cycles/limb
C 7400,7410 (G4): 0.5 0.64
C 744x,745x (G4+): 0.75 0.82
C 970 (G5): 0.78 1.02 (64-bit limbs)
C STATUS
C * Works for all sizes and alignments.
C TODO
C * Optimize unaligned case. Some basic tests with 2-way and 4-way unrolling
C indicate that we can reach 0.56 c/l for 7400, 0.75 c/l for 745x, and 0.80
C c/l for 970.
C * Consider using VMX instructions also for head and tail, by using some
C read-modify-write tricks.
C * The VMX code is used from the smallest sizes it handles, but measurements
C show a large speed bump at the cutoff points. Small copying (perhaps
C using some read-modify-write technique) should be optimized.
C * Make a mpn_com based on this code.
define(`GMP_LIMB_BYTES', eval(GMP_LIMB_BITS/8))
define(`LIMBS_PER_VR', eval(16/GMP_LIMB_BYTES))
define(`LIMBS_PER_2VR', eval(32/GMP_LIMB_BYTES))
ifelse(GMP_LIMB_BITS,32,`
define(`LIMB32',` $1')
define(`LIMB64',`')
',`
define(`LIMB32',`')
define(`LIMB64',` $1')
')
C INPUT PARAMETERS
define(`rp', `r3')
define(`up', `r4')
define(`n', `r5')
define(`us', `v4')
ASM_START()
PROLOGUE(mpn_copyd)
LIMB32(`slwi. r0, n, 2 ')
LIMB64(`sldi. r0, n, 3 ')
add rp, rp, r0
add up, up, r0
LIMB32(`cmpi cr7, n, 11 ')
LIMB64(`cmpdi cr7, n, 5 ')
bge cr7, L(big)
beqlr cr0
C Handle small cases with plain operations
mtctr n
L(topS):
LIMB32(`lwz r0, -4(up) ')
LIMB64(`ld r0, -8(up) ')
addi up, up, -GMP_LIMB_BYTES
LIMB32(`stw r0, -4(rp) ')
LIMB64(`std r0, -8(rp) ')
addi rp, rp, -GMP_LIMB_BYTES
bdnz L(topS)
blr
C Handle large cases with VMX operations
L(big):
addi rp, rp, -16
addi up, up, -16
mfspr r12, 256
oris r0, r12, 0xf800 C Set VRSAVE bit 0-4
mtspr 256, r0
LIMB32(`rlwinm. r7, rp, 30,30,31') C (rp >> 2) mod 4
LIMB64(`rlwinm. r7, rp, 29,31,31') C (rp >> 3) mod 2
beq L(rp_aligned)
subf n, r7, n
L(top0):
LIMB32(`lwz r0, 12(up) ')
LIMB64(`ld r0, 8(up) ')
addi up, up, -GMP_LIMB_BYTES
LIMB32(`addic. r7, r7, -1 ')
LIMB32(`stw r0, 12(rp) ')
LIMB64(`std r0, 8(rp) ')
addi rp, rp, -GMP_LIMB_BYTES
LIMB32(`bne L(top0) ')
L(rp_aligned):
LIMB32(`rlwinm. r0, up, 30,30,31') C (up >> 2) mod 4
LIMB64(`rlwinm. r0, up, 29,31,31') C (up >> 3) mod 2
LIMB64(`srdi r7, n, 2 ') C loop count corresponding to n
LIMB32(`srwi r7, n, 3 ') C loop count corresponding to n
mtctr r7 C copy n to count register
li r10, -16
beq L(up_aligned)
lvsl us, 0, up
addi up, up, 16
LIMB32(`andi. r0, n, 0x4 ')
LIMB64(`andi. r0, n, 0x2 ')
beq L(1)
lvx v0, 0, up
lvx v2, r10, up
vperm v3, v2, v0, us
stvx v3, 0, rp
addi up, up, -32
addi rp, rp, -16
b L(lpu)
L(1): lvx v2, 0, up
addi up, up, -16
b L(lpu)
ALIGN(32)
L(lpu): lvx v0, 0, up
vperm v3, v0, v2, us
stvx v3, 0, rp
lvx v2, r10, up
addi up, up, -32
vperm v3, v2, v0, us
stvx v3, r10, rp
addi rp, rp, -32
bdnz L(lpu)
b L(tail)
L(up_aligned):
LIMB32(`andi. r0, n, 0x4 ')
LIMB64(`andi. r0, n, 0x2 ')
beq L(lpa)
lvx v0, 0, up
stvx v0, 0, rp
addi up, up, -16
addi rp, rp, -16
b L(lpa)
ALIGN(32)
L(lpa): lvx v0, 0, up
lvx v1, r10, up
addi up, up, -32
nop
stvx v0, 0, rp
stvx v1, r10, rp
addi rp, rp, -32
bdnz L(lpa)
L(tail):
LIMB32(`rlwinm. r7, n, 0,30,31 ') C r7 = n mod 4
LIMB64(`rlwinm. r7, n, 0,31,31 ') C r7 = n mod 2
beq L(ret)
LIMB32(`li r10, 12 ')
L(top2):
LIMB32(`lwzx r0, r10, up ')
LIMB64(`ld r0, 8(up) ')
LIMB32(`addic. r7, r7, -1 ')
LIMB32(`stwx r0, r10, rp ')
LIMB64(`std r0, 8(rp) ')
LIMB32(`addi r10, r10, -GMP_LIMB_BYTES')
LIMB32(`bne L(top2) ')
L(ret): mtspr 256, r12
blr
EPILOGUE()
| 23.544041 | 79 | 0.643486 |
b626c567bd646951729f3c58e8b9c9f553fdf2e3 | 304 | rb | Ruby | app/controllers/user_statuses_controller.rb | ping414ms/walk881 | 42c77ab6e93c7c857ad951a8607f80ebc2f61e2c | [
"MIT"
] | null | null | null | app/controllers/user_statuses_controller.rb | ping414ms/walk881 | 42c77ab6e93c7c857ad951a8607f80ebc2f61e2c | [
"MIT"
] | null | null | null | app/controllers/user_statuses_controller.rb | ping414ms/walk881 | 42c77ab6e93c7c857ad951a8607f80ebc2f61e2c | [
"MIT"
] | null | null | null | class UserStatusesController < ApplicationController
def index
reverse_mode = params[:reverse_mode].to_s.to_i == UserSetting::REVERSE_MODE ? UserSetting::REVERSE_MODE : UserSetting::NORMAL_MODE
current_statuses = UserStatus.all_data(reverse_mode)
render :json => current_statuses
end
end
| 38 | 134 | 0.789474 |
806c7033e13e0d941159e887947ccc05a79c3097 | 5,854 | java | Java | src/test/java/seedu/weeblingo/commons/util/RegexUtilTest.java | xyzhang00/tp | 4183c4b7fd2a5ed37b9ba9c826bd8fda07ca94f6 | [
"MIT"
] | null | null | null | src/test/java/seedu/weeblingo/commons/util/RegexUtilTest.java | xyzhang00/tp | 4183c4b7fd2a5ed37b9ba9c826bd8fda07ca94f6 | [
"MIT"
] | 143 | 2021-02-17T15:55:19.000Z | 2021-04-11T18:01:55.000Z | src/test/java/seedu/weeblingo/commons/util/RegexUtilTest.java | xyzhang00/tp | 4183c4b7fd2a5ed37b9ba9c826bd8fda07ca94f6 | [
"MIT"
] | 4 | 2021-02-15T11:46:02.000Z | 2021-02-21T09:29:57.000Z | package seedu.weeblingo.commons.util;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* Automated testing for seedu.weeblingo.commons.util.RegexUtil.
*/
public class RegexUtilTest {
// -------------------------------- REGEX_JAP_WORD --------------------------------
/**
* Valid Jap words: only contains hiragana, katakana, and kanji
*/
@Test
public void regexJapWordValid() {
// regex to be used for testing
String regex = RegexUtil.REGEX_JAP_WORD;
// normal hiragana
assertTrue("あ".matches(regex));
assertTrue("が".matches(regex));
assertTrue("っ".matches(regex));
assertTrue("ぴ".matches(regex));
assertTrue("きゅ".matches(regex));
// normal katakana
assertTrue("ア".matches(regex));
assertTrue("ザ".matches(regex));
assertTrue("ア".matches(regex));
assertTrue("ッ".matches(regex));
assertTrue("キュ".matches(regex));
// normal kanji
assertTrue("留学生".matches(regex));
assertTrue("私".matches(regex));
assertTrue("金魚".matches(regex));
assertTrue("天気".matches(regex));
// simple combinations
assertTrue("散りぬるを".matches(regex));
assertTrue("ツネナラムウヰノオクヤマ".matches(regex));
assertTrue("浅き夢見じ酔ひもせず".matches(regex));
}
/**
* Invalid Jap words: contains space, punctuation, latin and numeric characters
*/
@Test
public void regexJapWordInvalid() {
// regex to be used for testing
String regex = RegexUtil.REGEX_JAP_WORD;
// empty string / strings without content
assertFalse("".matches(regex));
assertFalse(" ".matches(regex));
// strings with trailing white spaces
assertFalse(" 天気".matches(regex));
assertFalse("天気 ".matches(regex));
// strings containing punctuations
assertFalse("天気。".matches(regex));
assertFalse("天気、".matches(regex));
assertFalse("、天気".matches(regex));
// strings containing numeric values
assertFalse("123天気".matches(regex));
assertFalse("天123気weather".matches(regex));
assertFalse("123.123天気".matches(regex));
// strings containing German/Latin characters
assertFalse("latin天気".matches(regex));
assertFalse("天気latin".matches(regex));
assertFalse("天気Ä".matches(regex));
assertFalse("weather".matches(regex));
// strings containing miscellaneous non-sense characters
assertFalse("&*()(&**天気".matches(regex));
assertFalse("天気^&(^&&(^ ".matches(regex));
}
// ---------------- Tests for REGEX_JAP_SENTENCE --------------------------------------
/**
* Valid Jap sentences: only contains hiragana, katakana, kanji, english letters, numbers punctuations and symbols.
*/
@Test
public void regexJapSentenceValid() {
// regex to be used for testing
String regex = RegexUtil.REGEX_JAP_SENTENCE;
assertTrue("猫になりたい。".matches(regex));
assertTrue("私は ただ、勉強したくないだけです。".matches(regex));
assertTrue("CS2103Tははははは".matches(regex));
assertTrue("収入は1000.25円。".matches(regex));
assertTrue("12345あいうえお".matches(regex));
assertTrue("ジンボはリンゴを食べる。".matches(regex));
assertTrue("。。。".matches(regex));
}
// ---------------- Tests for REGEX_JAP_SENTENCE --------------------------------------
/**
* Invalid Jap sentences: empty sentences, contain non-english & non-japanese & non-chinese characters
*/
@Test
public void regexJapSentenceInvalid() {
// regex to be used for testing
String regex = RegexUtil.REGEX_JAP_SENTENCE;
assertFalse("".matches(regex));
assertFalse(" ".matches(regex));
assertFalse(" 収入は1000.25円。".matches(regex));
assertFalse("Glück".matches(regex));
assertFalse("Adiós".matches(regex));
assertFalse("아니요".matches(regex));
}
// ---------------- Tests for REGEX_ENG_WORD --------------------------------------
/**
* Both valid and invalid cases tests are here.
*/
@Test
public void regexEngWords() {
// regex to be used for testing
String regex = RegexUtil.REGEX_ENG_WORDS;
assertTrue("a".matches(regex));
assertTrue("A".matches(regex));
assertTrue("Yes".matches(regex));
assertTrue("two words".matches(regex));
assertFalse("".matches(regex));
assertFalse(" ".matches(regex));
assertFalse("No.".matches(regex));
assertFalse("1word".matches(regex));
assertFalse("Adiós".matches(regex));
assertFalse("아니요".matches(regex));
}
// ---------------- Tests for REGEX_ENG_SENTENCE --------------------------------------
/**
* Both valid and invalid cases tests are here.
*/
@Test
public void regexEngSentence() {
// regex to be used for testing
String regex = RegexUtil.REGEX_ENG_SENTENCE;
assertTrue("a".matches(regex));
assertTrue("A".matches(regex));
assertTrue("Yes".matches(regex));
assertTrue("True.".matches(regex));
assertTrue("Haha means happiness.".matches(regex));
assertTrue("1 means one.".matches(regex));
assertTrue("......".matches(regex));
assertTrue("I ate dinner.".matches(regex));
assertTrue("We all agreed; it was a magnificent evening.".matches(regex));
assertTrue("Oh, how I'd love to go!".matches(regex));
assertFalse("".matches(regex));
assertFalse(" ".matches(regex));
assertFalse("这不对!".matches(regex));
assertFalse("Adiós".matches(regex));
assertFalse("아니요".matches(regex));
}
}
| 34.435294 | 119 | 0.589341 |
4ad35859683d9b86e09f9719aa9cf39def483d42 | 1,532 | swift | Swift | Example/Backpack/TableNavigationData.swift | tomjaroli/backpack-ios | 97220e98a90e84e0b905d75207d176dc3bcc76d7 | [
"Apache-2.0"
] | null | null | null | Example/Backpack/TableNavigationData.swift | tomjaroli/backpack-ios | 97220e98a90e84e0b905d75207d176dc3bcc76d7 | [
"Apache-2.0"
] | 14 | 2022-03-17T09:58:25.000Z | 2022-03-30T10:43:22.000Z | Example/Backpack/TableNavigationData.swift | tomjaroli/backpack-ios | 97220e98a90e84e0b905d75207d176dc3bcc76d7 | [
"Apache-2.0"
] | null | null | null | /*
* Backpack - Skyscanner's Design System
*
* Copyright 2018 Skyscanner Ltd
*
* 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.
*/
public struct Section<T> {
let name: String?
let rows: [Row<T>]
}
public struct Row<T> {
let name: String
let value: T
}
/**
* Converts a list of group items into a list of sections if they have subitems
*
* parameter items: The items to organise into one or more sections.
* returns: A list of sections.
*/
public func sectionify(items: [Item]) -> [Section<Item>] {
let groups: [(String, [Item])] = items.compactMap({ group in
group.subItems().map({
(group.name, $0)
})
})
let ungroupedItems: [Item] = items.filter({ $0.isStory() })
var value = groups.map({group in
Section(name: group.0, rows: group.1.map({ Row(name: $0.name, value: $0) }))
})
if ungroupedItems.count > 0 {
value.append(Section(name: nil, rows: ungroupedItems.map({ Row(name: $0.name, value: $0) })))
}
return value
}
| 28.37037 | 101 | 0.657963 |
26d69d962d97ff6f8f9cc480089bf305caa9042a | 1,519 | dart | Dart | lib/src/annotations.dart | champeauxr/needle | 78a3e0f56bd6193cc866545c324736a560a39735 | [
"MIT"
] | 2 | 2020-07-05T02:52:59.000Z | 2020-07-11T15:17:09.000Z | lib/src/annotations.dart | champeauxr/needle | 78a3e0f56bd6193cc866545c324736a560a39735 | [
"MIT"
] | null | null | null | lib/src/annotations.dart | champeauxr/needle | 78a3e0f56bd6193cc866545c324736a560a39735 | [
"MIT"
] | null | null | null | /// The annotation `@Named()` marks a constructor parameter as resolving
/// to a named instance of an object.
///
/// For example, the `cache` parameter in the following constructor:
/// ```
///class BarDataStore {
/// BarDataStore(@Named('Bar') this.cache, this.size);
///
/// final ObjectCache cache;
/// final int size;
///}
///```
///
/// would be resolved to the object produced by the following registration:
/// ```
/// builder.registerType<ObjectCache>().singleInstance().withName('Bar');
/// ```
class Named {
const Named(this.name);
final String name;
}
/// The annotation `@reflect` marks a type for reflection code generation.
const reflect = Reflect();
/// The annotation `@Reflect()` marks a type for reflection code generation.
class Reflect {
const Reflect();
}
/// The annotation `@ReflectInclude()` marks a factory class and specifies
/// additional types that should be reflected.
///
/// Usage:
/// ```
/// @ReflectInclude(RepositoryModelImpl)
///@ReflectInclude(ObjectCache)
///@factory
///class MyFactory extends ClassFactory with $MyFactory {}
/// ```
class ReflectInclude {
const ReflectInclude(this.type);
final Type type;
}
/// The annotation `@needle` marks a class as a Needle ScopeBuilder that
/// build_runner will populate with mirrors of the reflected classes.
const needle = Needle();
/// The annotation `@Needle()` marks a class as a Needle ScopeBuilder that
/// build_runner will populate with mirrors of the reflected classes.
class Needle {
const Needle();
}
| 26.649123 | 76 | 0.700461 |
982957cf7bd28c0a08b127fe0517acedca07ec7b | 183 | sql | SQL | db/migrations/000004_indexes.up.sql | SmilyOrg/photofield | 76f5cdaf12e4eb999607482814ab4883279ab112 | [
"MIT"
] | 20 | 2021-11-05T07:50:12.000Z | 2022-03-10T18:06:26.000Z | db/migrations/000004_indexes.up.sql | SmilyOrg/photofield | 76f5cdaf12e4eb999607482814ab4883279ab112 | [
"MIT"
] | 3 | 2021-11-07T12:49:17.000Z | 2021-11-22T08:09:01.000Z | db/migrations/000004_indexes.up.sql | SmilyOrg/photofield | 76f5cdaf12e4eb999607482814ab4883279ab112 | [
"MIT"
] | 1 | 2021-12-01T21:33:32.000Z | 2021-12-01T21:33:32.000Z | CREATE INDEX list_paths_idx
ON infos (
created_at COLLATE NOCASE,
path COLLATE NOCASE,
width,
height,
color
);
CREATE INDEX sorted_path_idx ON infos (path COLLATE NOCASE);
| 16.636364 | 60 | 0.754098 |
2e38a1114c31bada754c58142ecddd130260c9ab | 675 | lua | Lua | addons/ArcCW/lua/arccw/server/sv_year.lua | lechu2375/GM-DayZ | 35beb8cc80bc1673f45be8385b56c654fb066e8d | [
"MIT"
] | 4 | 2021-12-01T15:57:30.000Z | 2022-01-28T11:10:24.000Z | addons/ArcCW/lua/arccw/server/sv_year.lua | lechu2375/GM-DayZ | 35beb8cc80bc1673f45be8385b56c654fb066e8d | [
"MIT"
] | null | null | null | addons/ArcCW/lua/arccw/server/sv_year.lua | lechu2375/GM-DayZ | 35beb8cc80bc1673f45be8385b56c654fb066e8d | [
"MIT"
] | 3 | 2021-08-20T15:19:34.000Z | 2021-12-07T00:34:33.000Z | hook.Add( "PlayerGiveSWEP", "ArcCW_YearLimiter", function( ply, class, swep )
local wep = weapons.Get(class)
if !ArcCW:WithinYearLimit(wep) then
ply:ChatPrint( wep.PrintName .. " is outside the year limit!")
return false
end
end )
function ArcCW:WithinYearLimit(wep)
if !wep then return true end
if !wep.ArcCW then return true end
if !GetConVar("arccw_limityear_enable"):GetBool() then return true end
local year = GetConVar("arccw_limityear"):GetInt()
if !wep.Trivia_Year then return true end
if !isnumber(wep.Trivia_Year) then return true end
if wep.Trivia_Year > year then return false end
return true
end | 28.125 | 77 | 0.700741 |
4a416f725d74fcdcd5085af02606b7775d0c0c86 | 5,056 | cs | C# | GraphLib/GraphLib/QuadTree/PointQuadTree.cs | DMokhnatkin/GraphLib | 428a2a8b77ae6b870c0cc1e9d7a322aa62716547 | [
"Apache-2.0"
] | null | null | null | GraphLib/GraphLib/QuadTree/PointQuadTree.cs | DMokhnatkin/GraphLib | 428a2a8b77ae6b870c0cc1e9d7a322aa62716547 | [
"Apache-2.0"
] | null | null | null | GraphLib/GraphLib/QuadTree/PointQuadTree.cs | DMokhnatkin/GraphLib | 428a2a8b77ae6b870c0cc1e9d7a322aa62716547 | [
"Apache-2.0"
] | null | null | null | using System.Collections.Generic;
namespace Graph.QuadTree
{
public class PointQuadTree<TValue> : ICollection<TValue> where TValue : IQuadObject
{
QuadTreeNode<TValue> tree;
public Rectangle Bound { get { return tree.Bound; } }
/// <param name="bound">Bound to initialize</param>
public PointQuadTree(Rectangle bound)
{
tree = new QuadTreeNode<TValue>(bound);
}
public PointQuadTree()
{
tree = new QuadTreeNode<TValue>(new Rectangle(1, 1, -1, -1));
}
/// <summary>
/// Return all object which are in bound
/// </summary>
public List<TValue> QueryRange(Rectangle bound)
{
return tree.QueryRange(bound);
}
/// <summary>
/// Add item to tree
/// </summary>
public void Add(TValue item)
{
if (!tree.Bound.ContainsPoint(item.X, item.Y))
{
// Point is in left top corner
// Or point is upper
if (item.X < Bound.MaxX &&
item.Y > Bound.MaxY)
{
Rectangle _newBound = new Rectangle(
Bound.MinX - Bound.Width,
Bound.MaxY + Bound.Height,
Bound.MaxX,
Bound.MinY);
QuadTreeNode<TValue> _newNode = new QuadTreeNode<TValue>(_newBound);
_newNode.Subdivide();
_newNode.rightDown = tree;
tree = _newNode;
}
// Point is in right top corner
// Or point is to the right
if (item.X > Bound.MaxX &&
item.Y > Bound.MinY)
{
Rectangle _newBound = new Rectangle(
Bound.MinX,
Bound.MaxY + Bound.Height,
Bound.MaxX + Bound.Width,
Bound.MinY);
QuadTreeNode<TValue> _newNode = new QuadTreeNode<TValue>(_newBound);
_newNode.Subdivide();
_newNode.leftDown = tree;
tree = _newNode;
}
// Point is in left down corner
// Or point is to the left
if (item.X < Bound.MinX &&
item.Y < Bound.MaxY)
{
Rectangle _newBound = new Rectangle(
Bound.MinX - Bound.Width,
Bound.MinY - Bound.Height,
Bound.MaxX,
Bound.MaxY);
QuadTreeNode<TValue> _newNode = new QuadTreeNode<TValue>(_newBound);
_newNode.Subdivide();
_newNode.rightTop = tree;
tree = _newNode;
}
// Point is right down corner
// Or point is lower
if (item.X > Bound.MinX &&
item.Y < Bound.MinY)
{
Rectangle _newBound = new Rectangle(
Bound.MinX,
Bound.MaxY,
Bound.MaxX + Bound.Width,
Bound.MinY - Bound.Height);
QuadTreeNode<TValue> _newNode = new QuadTreeNode<TValue>(_newBound);
_newNode.Subdivide();
_newNode.leftTop = tree;
tree = _newNode;
}
Add(item);
return;
}
tree.Insert(item);
Count++;
}
/// <summary>
/// Delete all items from tree
/// </summary>
public void Clear()
{
tree = new QuadTreeNode<TValue>(tree.Bound);
Count = 0;
}
/// <summary>
/// Does this colellection contains item
/// </summary>
public bool Contains(TValue item)
{
return tree.QueryRange(tree.Bound).Contains(item);
}
public void CopyTo(TValue[] array, int arrayIndex)
{
tree.QueryRange(tree.Bound).CopyTo(array, arrayIndex);
}
public int Count
{
get;
private set;
}
public bool IsReadOnly
{
get { throw new System.NotImplementedException(); }
}
public bool Remove(TValue item)
{
return tree.Remove(item);
}
public IEnumerator<TValue> GetEnumerator()
{
return tree.QueryRange(tree.Bound).GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new System.NotImplementedException();
}
}
}
| 32.203822 | 89 | 0.437896 |
47255406f5545ad15b254939ace1767c0b1035ee | 407 | lua | Lua | tests/.data/statement/table.lua | awh6al/lua-format | 33e55b176ffd7f94f2a1a021504081b9d1b85b16 | [
"Apache-2.0"
] | 490 | 2018-10-30T02:40:38.000Z | 2022-03-29T22:16:41.000Z | tests/.data/statement/table.lua | awh6al/lua-format | 33e55b176ffd7f94f2a1a021504081b9d1b85b16 | [
"Apache-2.0"
] | 185 | 2018-12-13T09:16:57.000Z | 2022-03-31T23:57:44.000Z | tests/.data/statement/table.lua | awh6al/lua-format | 33e55b176ffd7f94f2a1a021504081b9d1b85b16 | [
"Apache-2.0"
] | 102 | 2018-12-22T02:08:34.000Z | 2022-03-30T18:11:05.000Z | key = "some key"
q = {
a="1",
b=1;
-- line break
c=function() return 1 end,
d={
[1] = {};
[2] = {};
[key] = (function() return {1,2,3} end)()
}
}
function a(...)
local t = {...}
for k,v in ipairs(t) do
print(k,v)
end
end
a(1,2,3)
q[ [=[key1]=] ] = "value1"
q[ [[key2]] ] = "value2"
q['\'"key3"'] = "value3"
q["\"key4\""] = "value4" | 15.074074 | 49 | 0.395577 |
2f380b329fbea9da733318e6e7b596d071927ca7 | 1,446 | java | Java | app/src/main/java/com/schneewittchen/rosandroid/utility/WidgetDiffCallback.java | michaelastein/ROS-Mobile-Android | 6b2ab8448af4edef41225c126cfbe384cff33e35 | [
"MIT",
"Unlicense"
] | 283 | 2020-07-12T11:13:16.000Z | 2022-03-31T06:50:31.000Z | app/src/main/java/com/schneewittchen/rosandroid/utility/WidgetDiffCallback.java | michaelastein/ROS-Mobile-Android | 6b2ab8448af4edef41225c126cfbe384cff33e35 | [
"MIT",
"Unlicense"
] | 70 | 2020-05-26T07:55:29.000Z | 2022-03-30T19:15:28.000Z | app/src/main/java/com/schneewittchen/rosandroid/utility/WidgetDiffCallback.java | michaelastein/ROS-Mobile-Android | 6b2ab8448af4edef41225c126cfbe384cff33e35 | [
"MIT",
"Unlicense"
] | 88 | 2020-07-12T10:42:16.000Z | 2022-03-29T15:50:14.000Z | package com.schneewittchen.rosandroid.utility;
import androidx.recyclerview.widget.DiffUtil;
import com.schneewittchen.rosandroid.model.entities.widgets.BaseEntity;
import java.util.List;
/**
* TODO: Description
*
* @author Nico Studt
* @version 1.0.1
* @created on 05.02.20
* @updated on 24.09.20
* @modified by Nico Studt
*/
public class WidgetDiffCallback extends DiffUtil.Callback{
public static String TAG = WidgetDiffCallback.class.getSimpleName();
List<BaseEntity> oldWidgets;
List<BaseEntity> newWidgets;
public WidgetDiffCallback(List<BaseEntity> newWidgets, List<BaseEntity> oldWidgets) {
this.newWidgets = newWidgets;
this.oldWidgets = oldWidgets;
}
@Override
public int getOldListSize() {
return oldWidgets.size();
}
@Override
public int getNewListSize() {
return newWidgets.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
BaseEntity oldWidget = oldWidgets.get(oldItemPosition);
BaseEntity newWidget = newWidgets.get(newItemPosition);
return oldWidget.id == newWidget.id;
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
BaseEntity oldWidget = oldWidgets.get(oldItemPosition);
BaseEntity newWidget = newWidgets.get(newItemPosition);
return oldWidget.equals(newWidget);
}
}
| 24.1 | 89 | 0.707469 |
bfc03f61fdf781bfc9bb32d6edd9a50680f66623 | 4,680 | ps1 | PowerShell | Samples/build.ps1 | chandramouleswaran/PSharp | 79e689a4c76aa227646ed6183a721fc04eb2c0d8 | [
"MIT"
] | null | null | null | Samples/build.ps1 | chandramouleswaran/PSharp | 79e689a4c76aa227646ed6183a721fc04eb2c0d8 | [
"MIT"
] | null | null | null | Samples/build.ps1 | chandramouleswaran/PSharp | 79e689a4c76aa227646ed6183a721fc04eb2c0d8 | [
"MIT"
] | null | null | null | param(
[string]$dotnet="dotnet",
[string]$msbuild="msbuild",
[ValidateSet("net46")]
[string]$framework="net46",
[ValidateSet("Debug","Release")]
[string]$configuration="Release",
[bool]$restore=$true,
[bool]$build=$true,
[bool]$publish=$true,
[switch]$show
)
# Restores the packages for the specified sample.
function Restore-SamplePackages([String]$sample)
{
Write-Comment -prefix "....." -text "Restoring packages for '$samples_dir\$sample'" -color "white"
$command = "restore $samples_dir\$sample"
$error_message = "Failed to restore packages for '$samples_dir\$sample'"
Invoke-ToolCommand -tool $dotnet -command $command -error_message $error_message -show_output $show.IsPresent
}
# # Builds the specified sample using the specified configuration.
# function New-Sample([String]$sample, [String]$configuration)
# {
# Write-Comment -prefix "..." -text "Building '$samples_dir\$sample' using the '$configuration' configuration" -color "white"
# $command = "build $samples_dir\$sample -f $framework -c $configuration"
# $error_message = "Failed to build '$samples_dir\$sample'"
# Invoke-ToolCommand -tool $dotnet -command $command -error_message $error_message -show_output $show.IsPresent
# }
# Builds the specified sample using the specified configuration.
function New-Sample([String]$sample, [String]$configuration)
{
Write-Comment -prefix "..." -text "Building '$samples_dir\$sample' using the '$configuration' configuration" -color "white"
$command = "$samples_dir\$sample /p:Configuration=$configuration"
$error_message = "Failed to build '$samples_dir\$sample'"
Invoke-ToolCommand -tool $msbuild -command $command -error_message $error_message -show_output $show.IsPresent
}
# Paths to the various directories.
$psharp_binaries = $PSScriptRoot + '\..\bin\' + $framework
$samples_dir = $PSScriptRoot
# Available samples.
$samples = "BoundedAsync\BoundedAsync.PSharpLanguage\BoundedAsync.PSharpLanguage.csproj",
"BoundedAsync\BoundedAsync.PSharpLibrary\BoundedAsync.PSharpLibrary.csproj",
"CacheCoherence\CacheCoherence.PSharpLanguage\CacheCoherence.PSharpLanguage.csproj",
"CacheCoherence\CacheCoherence.PSharpLibrary\CacheCoherence.PSharpLibrary.csproj",
"ChainReplication\ChainReplication.PSharpLibrary\ChainReplication.PSharpLibrary.csproj",
"Chord\Chord.PSharpLibrary\Chord.PSharpLibrary.csproj",
"FailureDetector\FailureDetector.PSharpLanguage\FailureDetector.PSharpLanguage.csproj",
"FailureDetector\FailureDetector.PSharpLibrary\FailureDetector.PSharpLibrary.csproj",
"MultiPaxos\MultiPaxos.PSharpLanguage\MultiPaxos.PSharpLanguage.csproj",
"MultiPaxos\MultiPaxos.PSharpLibrary\MultiPaxos.PSharpLibrary.csproj",
"PingPong\PingPong.CustomLogging\PingPong.CustomLogging.csproj",
"PingPong\PingPong.MixedMode\PingPong.MixedMode.csproj",
"PingPong\PingPong.PSharpLanguage\PingPong.PSharpLanguage.csproj",
"PingPong\PingPong.PSharpLanguage.AsyncAwait\PingPong.PSharpLanguage.AsyncAwait.csproj",
"PingPong\PingPong.PSharpLibrary\PingPong.PSharpLibrary.csproj",
"PingPong\PingPong.PSharpLibrary.AsyncAwait\PingPong.PSharpLibrary.AsyncAwait.csproj",
"Raft\Raft.PSharpLanguage\Raft.PSharpLanguage.csproj",
"Raft\Raft.PSharpLibrary\Raft.PSharpLibrary.csproj",
"ReplicatingStorage\ReplicatingStorage.PSharpLanguage\ReplicatingStorage.PSharpLanguage.csproj",
"ReplicatingStorage\ReplicatingStorage.PSharpLibrary\ReplicatingStorage.PSharpLibrary.csproj",
"TwoPhaseCommit\TwoPhaseCommit.PSharpLibrary\TwoPhaseCommit.PSharpLibrary.csproj",
"Timers\TimerSample\TimerSample.csproj"
Import-Module $PSScriptRoot\..\Scripts\common.psm1
Write-Comment -prefix "." -text "Building P# samples using the '$framework' framework" -color "yellow"
# Checks if P# is built for the specified framework.
Write-Comment -prefix "..." -text "Checking if P# is built using the '$framework' framework" -color "white"
if (-not (Test-Path $psharp_binaries))
{
Write-Error "P# is not built using the '$framework' framework. Please build and try again."
exit
}
if ($restore -eq $true)
{
Write-Comment -prefix "..." -text "Restoring packages (might take several minutes)" -color "white"
foreach ($project in $samples)
{
# Restores the packages for the sample.
Restore-SamplePackages -sample $project
}
}
if ($build -eq $true)
{
foreach ($project in $samples)
{
# Builds the sample for the specified configuration.
New-Sample -sample $project -configuration $configuration
}
}
Write-Comment -prefix "." -text "Successfully built all samples" -color "green"
| 46.8 | 129 | 0.751282 |
39f4da423c08bfb66fde1ba187f84878d666c927 | 2,014 | dart | Dart | lib/model/theme_item.g.dart | fluttertutorialin/mikan_flutter | 9afff976e36f04377a685968c3e9b553e3a249b0 | [
"Apache-2.0"
] | 2 | 2021-05-30T13:17:28.000Z | 2022-01-12T01:48:20.000Z | lib/model/theme_item.g.dart | fluttertutorialin/mikan_flutter | 9afff976e36f04377a685968c3e9b553e3a249b0 | [
"Apache-2.0"
] | null | null | null | lib/model/theme_item.g.dart | fluttertutorialin/mikan_flutter | 9afff976e36f04377a685968c3e9b553e3a249b0 | [
"Apache-2.0"
] | 1 | 2021-05-30T13:17:37.000Z | 2021-05-30T13:17:37.000Z | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'theme_item.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class ThemeItemAdapter extends TypeAdapter<ThemeItem> {
@override
final int typeId = 1;
@override
ThemeItem read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return ThemeItem()
..id = fields[0] as int
..canDelete = fields[1] as bool
..autoMode = fields[2] as bool
..isDark = fields[4] as bool
..primaryColor = fields[5] as int
..accentColor = fields[6] as int
..lightBackgroundColor = fields[7] as int
..darkBackgroundColor = fields[8] as int
..lightScaffoldBackgroundColor = fields[9] as int
..darkScaffoldBackgroundColor = fields[10] as int
..fontFamily = fields[11] as String?;
}
@override
void write(BinaryWriter writer, ThemeItem obj) {
writer
..writeByte(11)
..writeByte(0)
..write(obj.id)
..writeByte(1)
..write(obj.canDelete)
..writeByte(2)
..write(obj.autoMode)
..writeByte(4)
..write(obj.isDark)
..writeByte(5)
..write(obj.primaryColor)
..writeByte(6)
..write(obj.accentColor)
..writeByte(7)
..write(obj.lightBackgroundColor)
..writeByte(8)
..write(obj.darkBackgroundColor)
..writeByte(9)
..write(obj.lightScaffoldBackgroundColor)
..writeByte(10)
..write(obj.darkScaffoldBackgroundColor)
..writeByte(11)
..write(obj.fontFamily);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is ThemeItemAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
| 28.366197 | 77 | 0.5715 |
0f087d5e54cb1bd1c7509242ce4caed9ecd8cf46 | 126 | cpp | C++ | section3/video5/test.cpp | PacktPublishing/Hands-On-WebAssembly-for-C-Programmers | e10f26636d2a864c9cbebc6d7e813a4d1c617253 | [
"MIT"
] | 19 | 2020-04-10T08:40:56.000Z | 2021-12-27T21:46:48.000Z | section3/video5/test.cpp | ostvld/Hands-On-WebAssembly-for-C-Programmers | e10f26636d2a864c9cbebc6d7e813a4d1c617253 | [
"MIT"
] | null | null | null | section3/video5/test.cpp | ostvld/Hands-On-WebAssembly-for-C-Programmers | e10f26636d2a864c9cbebc6d7e813a4d1c617253 | [
"MIT"
] | 9 | 2020-10-13T08:41:38.000Z | 2022-01-23T20:20:45.000Z | #include <iostream>
extern "C" int add(int a, int b){
std::cout << a << " " << b << " " << a + b << "\n";
return a + b;
}
| 18 | 53 | 0.444444 |
90683122bb84cde79e92c24929d9dbb7c996d0bc | 1,378 | py | Python | datastructures/dynamicarray/DynamicArray.py | venkatacrc/Algorithms | 0c64280f3bc2b5c0563eebf162c448ce0ca646a5 | [
"MIT"
] | null | null | null | datastructures/dynamicarray/DynamicArray.py | venkatacrc/Algorithms | 0c64280f3bc2b5c0563eebf162c448ce0ca646a5 | [
"MIT"
] | null | null | null | datastructures/dynamicarray/DynamicArray.py | venkatacrc/Algorithms | 0c64280f3bc2b5c0563eebf162c448ce0ca646a5 | [
"MIT"
] | null | null | null | class DynamicArray(object):
def __init__(self, capacity=0):
self.capacity = capacity
if not capacity:
self.arr = None
self.len = 0
else:
self.len = 0
self.arr = []
def size(self):
return self.len
def isEmpty(self):
return self.len == 0
def get(self, index):
if index >= self.len or index < 0:
raise ValueError("Index out of range in get")
return self.arr[index]
def set(self, index, elem):
if index >= self.len or index < 0:
raise ValueError("Index out of range in set")
self.arr[index] = elem
def clear(self):
self.arr = []
self.len = 0
def add(self, elem):
if self.len+1 >= self.capacity:
self.capacity *= 2
self.arr.append(elem)
def removeAt(self, rm_index):
if rm_index >= self.len or rm_index < 0:
raise ValueError("Remove Index out of range in removeAt")
data = self.arr.pop(rm_index)
self.len -= 1
return data
def remove(self, value):
self.arr.remove(value)
def indexOf(self, value):
for i in range(self.len):
if self.arr[i] == value:
return i
return -1
def contains(self, value):
return self.indexOf(value) != -1
def __str__ (self):
s = "["
for i in range(self.len-1):
s += str(self.arr[i])
s += ", "
s += str(self.arr[self.len -1]
s += "]"
| 20.567164 | 63 | 0.576197 |
75063ff563eed2e0534670bca51da4bf0dce557d | 763 | h | C | qpcol/searchprovider/youporn/youporn.h | quntax/qpcol | 290e2f0639eaee12fe6190070b3e2c38a8fd1ea7 | [
"BSD-3-Clause"
] | null | null | null | qpcol/searchprovider/youporn/youporn.h | quntax/qpcol | 290e2f0639eaee12fe6190070b3e2c38a8fd1ea7 | [
"BSD-3-Clause"
] | null | null | null | qpcol/searchprovider/youporn/youporn.h | quntax/qpcol | 290e2f0639eaee12fe6190070b3e2c38a8fd1ea7 | [
"BSD-3-Clause"
] | null | null | null | #ifndef YOUPORN_H
#define YOUPORN_H
#include <QtCore>
#include <QtGui>
#include <QtWebKit>
#include "searchprovider.h"
class Youporn : public SearchProvider
{
Q_OBJECT
Q_INTERFACES(SearchProviderInterface)
public:
Youporn();
QWebElementCollection parse();
void extract(const QWebElement &);
QString video(const QString &);
bool hasNext();
bool hasPrevious();
void next();
void previous();
QString baseUrl();
QString searchBaseUrl();
QString name();
signals:
void gotHtml();
protected:
// void loadPage(const QString &);
QByteArray html;
QHttpDownload *downloader;
QEventLoop loop;
protected slots:
void addHtml(QByteArray);
void setHtml(QByteArray);
};
#endif // YOUPORN_H
| 16.586957 | 41 | 0.68152 |
2f04e90283da07389a505e128e28e396c9943039 | 3,960 | java | Java | larky/src/main/java/com/verygood/security/larky/modules/testing/AssertionsModule.java | OmegaPointZero/starlarky | 5a21a5a0f2a776add19ad56d5e22ea6df270d865 | [
"Apache-2.0"
] | 12 | 2020-11-20T00:01:24.000Z | 2022-02-03T12:48:11.000Z | larky/src/main/java/com/verygood/security/larky/modules/testing/AssertionsModule.java | OmegaPointZero/starlarky | 5a21a5a0f2a776add19ad56d5e22ea6df270d865 | [
"Apache-2.0"
] | 92 | 2020-10-15T15:59:07.000Z | 2022-03-31T16:37:24.000Z | larky/src/main/java/com/verygood/security/larky/modules/testing/AssertionsModule.java | OmegaPointZero/starlarky | 5a21a5a0f2a776add19ad56d5e22ea6df270d865 | [
"Apache-2.0"
] | 23 | 2020-10-27T07:51:32.000Z | 2022-02-03T12:48:13.000Z | package com.verygood.security.larky.modules.testing;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.annotations.FormatMethod;
import com.google.re2j.Pattern;
import com.google.re2j.PatternSyntaxException;
import java.util.Objects;
import com.verygood.security.larky.modules.utils.Reporter;
import net.starlark.java.annot.Param;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkCallable;
import net.starlark.java.eval.StarlarkThread;
import net.starlark.java.eval.StarlarkValue;
@StarlarkBuiltin(
name = "assertions",
category = "BUILTIN",
doc = "This module implements a ")
public class AssertionsModule implements StarlarkValue {
public static final AssertionsModule INSTANCE = new AssertionsModule();
@StarlarkMethod(
name = "assert_",
documented = false,
parameters = {
@Param(name = "cond"),
@Param(name = "msg", defaultValue = "'assertion failed'"),
},
useStarlarkThread = true)
public Object assertStarlark(Object cond, String msg, StarlarkThread thread)
throws EvalException {
if (!Starlark.truth(cond)) {
Objects.requireNonNull(thread.getThreadLocal(Reporter.class))
.reportError(thread, "assert_: " + msg);
}
return Starlark.NONE;
}
@StarlarkMethod(
name = "assert_eq",
documented = false,
parameters = {
@Param(name = "x"),
@Param(name = "y"),
},
useStarlarkThread = true)
public Object assertEq(Object x, Object y, StarlarkThread thread) throws EvalException {
if (!x.equals(y)) {
String msg = String.format("assert_eq: %s != %s", Starlark.repr(x), Starlark.repr(y));
Objects.requireNonNull(thread.getThreadLocal(Reporter.class)).reportError(thread, msg);
}
return Starlark.NONE;
}
@StarlarkMethod(
name = "assert_fails",
doc = "assert_fails asserts that evaluation of f() fails with the specified error",
parameters = {
@Param(name = "f", doc = "the Starlark function to call"),
@Param(
name = "wantError",
doc = "a regular expression matching the expected error message"),
},
useStarlarkThread = true)
public Object assertFails(StarlarkCallable f, String wantError, StarlarkThread thread)
throws EvalException, InterruptedException {
Pattern pattern;
try {
pattern = Pattern.compile(wantError);
} catch (PatternSyntaxException unused) {
throw Starlark.errorf("invalid regexp: %s", wantError);
}
String errorMsg;
try {
Starlark.call(thread, f, ImmutableList.of(), ImmutableMap.of());
errorMsg = String.format("evaluation succeeded unexpectedly (want error matching %s)", wantError);
} catch (Starlark.UncheckedEvalException ex) {
// Verify error matches UncheckedEvalException message (which has a nested cause).
String msg = ex.getCause().getMessage();
if (pattern.matcher(msg).find()) {
return Starlark.NONE;
}
errorMsg = String.format("regular expression (%s) did not match error (%s)", pattern, msg);
} catch(EvalException ex) {
// Verify error matches expectation.
String msg = ex.getMessage();
if (pattern.matcher(msg).find()) {
return Starlark.NONE;
}
errorMsg = String.format("regular expression (%s) did not match error (%s)", pattern, msg);
}
reportErrorf(thread, "%s", errorMsg);
throw Starlark.errorf("%s", errorMsg);
}
@FormatMethod
private static void reportErrorf(StarlarkThread thread, String format, Object... args) {
Objects.requireNonNull(thread.getThreadLocal(Reporter.class))
.reportError(thread, String.format(format, args));
}
}
| 34.736842 | 104 | 0.682071 |
ddfd8d416712d2bf84123e284493e80b929b1922 | 20,708 | php | PHP | application/views/approvals_old1.php | unique211/erp-wadhwa | 386a641a5f551712f90cfd240daeda5fe839e553 | [
"MIT"
] | null | null | null | application/views/approvals_old1.php | unique211/erp-wadhwa | 386a641a5f551712f90cfd240daeda5fe839e553 | [
"MIT"
] | null | null | null | application/views/approvals_old1.php | unique211/erp-wadhwa | 386a641a5f551712f90cfd240daeda5fe839e553 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$title = '';
$title1 = '';
if(isset($title_name)){
$title = $title_name;
$title1 = $title_name1;
}
?>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $title; ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<style>
// .tab-pane{
// height:600px;
// overflow-y:scroll;
// overflow-x:hidden;
// }
.tabfont{
font-weight:1000;
color:#180905;
}
.navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 15px;
}
.navbar a:hover {
background: #ddd;
color: black;
}
.project_info-heading {
font-size:30px;
background-color:#ddd;
}
</style>
<?php include "includes/headerlink.php"; ?>
<!--<link href="<?php echo base_url(); ?>assets/multiselect/multiselect.css" rel="stylesheet" > -->
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/multiselect/bootstrap-multiselect.css" type="text/css">
</head>
<body class="overflow-hidden" >
<!-- Overlay Div -->
<div id="overlay" class="transparent"></div>
<div id="wrapper" class="preload">
<?php include "includes/header.php"; ?>
<?php include "includes/sidebar.php"; ?>
<div id="main-container">
<!-- <div id="breadcrumb">
<ul class="breadcrumb">
<li><i class="fa fa-home"></i><a href="index.html"> Home</a></li>
<li class="active"><?php //echo $title1 ?></li>
</ul>
</div><!-- /breadcrumb-->
<div class="padding-md">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<b>Approval Memo List</b>
<button type="button" id="formopen" class="btn btn-primary btn-xs pull-right btnhideshow"><i class="fa fa-plus"></i> Add New</button>
</div>
<div class="panel-tab clearfix formhideshow navbar">
<ul class="tab-bar">
<li class="tabfont active"><a href="#project_info-heading" data-toggle="tab"><i class="fa fa-address-card fa-lg"></i> Project Information</a></li>
<li class="tabfont"><a href="#document_tab" data-toggle="tab"><i class="fa fa-address-card fa-lg"></i> Documents</a></li>
</ul>
</div>
<div class="panel-body formhideshow">
<div class="tab-content">
<!----------------------------------------------- project_info tab start ------------------------------------->
<!----project information--->
<div class="tab-pane fade active in tab-pane" id="project_info-heading">
<div style="margin-top:0px;border-bottom:2px solid;width:100%;">
<b>Project Information</b>
</div>
<br>
<form id="approval_form" name="approval_form" ></form>
<div class="row" >
<div class="form-group">
<div class="col-lg-4" >
<label for="" class="control-label">Approval Request No.</label>
<input type="text" form="approval_form" class="form-control input-sm" id="request_no" name="request_no" required >
</div>
<div class="col-lg-4" >
<label for="" class="control-label">Dated</label>
<input type="text" form="approval_form" class="form-control input-sm" id="dated" name="dated" required>
</div>
<div class="col-lg-4" >
<label for="" class="control-label">Status</label>
<select form="approval_form" class="form-control input-sm project_name" id="area_name" name="area_name" required>
<option value="Draft">Draft</option>
<option value="Approved">Approved</option>
<option value="Submitted">Submitted</option>
<option value="Resubmitted">Resubmitted</option>
<option value="Rejected">Rejected</option>
</select>
</div>
</div>
</div>
<br>
<div class="row" >
<div class="form-group">
<div class="col-lg-2" >
<label for="" class="control-label" >Project Name</label>
</div>
<div class="col-lg-4">
<select form="approval_form" class="form-control input-sm project_name" id="project_name" name="project_name" required>
</select>
</div>
<div class="col-lg-2" >
<label for="" class="control-label">Company Name</label>
</div>
<div class="col-lg-4">
<input type="text" form="approval_form" class="form-control input-sm" id="company_name" name="company_name" required>
</div>
</div>
</div>
<br>
<div class="row" >
<div class="form-group">
<div class="col-lg-2" >
<label for="" class="control-label" >Phase</label>
</div>
<div class="col-lg-4">
<select form="approval_form" class="form-control input-sm phase" id="Phase" name="Phase" required>
</select>
</div>
<div class="col-lg-2" >
<label for="" class="control-label">Company GST</label>
</div>
<div class="col-lg-4">
<input type="text" form="approval_form" class="form-control input-sm" id="company_gst" name="company_gst" required>
</div>
</div>
</div>
<br>
<div class="row" >
<div class="form-group">
<div class="col-lg-3" >
<label for="" class="control-label" >Building/Area</label>
<select form="approval_form" class="form-control input-sm project_name" id="area_name" name="area_name" required>
</select>
</div>
<div class="col-lg-3">
<label for="" class="control-label" >Vendor Category</label>
<select form="approval_form" class="form-control input-sm project_name" id="area_name" name="area_name" required>
</select>
</div>
<div class="col-lg-6">
<label for="" class="control-label">Work Type</label>
<select form="approval_form" class="form-control input-sm project_name" id="area_name" name="area_name" required>
<option selected disabled >Select</option>
<option value="Architect" >Architect</option>
<option value="Engineering_Consultant" >Engineering Consultant</option>
<option value="Contracts" >Contracts</option>
<option value="MEP_Contracts" >MEP Contracts</option>
<option value="Material">Material</option>
</select>
</div>
</div>
</div>
<br>
<div style="margin-top:0px;border-bottom:2px solid;width:100%;">
<b>Work Information</b>
</div>
<br>
<div class="tab-pane fade active in tab-pane" id="work-info-heading">
<form id="work_form" name="work_form" ></form>
<div class="row" >
<div class="form-group">
<div class="col-lg-2" >
<label for="" class="control-label">Type of Contract</label>
</div>
<div class="col-lg-4">
<select form="work_form" class="form-control input-sm project_name" id="area_name" name="area_name" required>
<option selected disabled >Select</option>
<option value="Work_order" >Work Order</option>
<option value="Ammendment_work_order" >Ammendment work Order</option>
<option value="Purchase_Order" >Purchase Order</option>
<option value="Ammendment_Purchase_Order" >Ammendment Purchase Order</option>
</select>
</div>
<div class="col-lg-3" >
<label for="" class="control-label" >Vendor Name</label>
</div>
<div class="col-lg-3">
<select form="work_form" class="form-control input-sm architect_name" id="architect_name" name="architect_name" required>
</select>
</div>
</div>
</div>
<br><!----end row-->
<div class="row" >
<div class="form-group">
<div class="col-lg-4" >
<label for="" class="control-label" >Work order/PO Number</label>
</div>
<div class="col-lg-2">
<select form="work_form" class="form-control input-sm po_number" id="po_number" name="po_number" required>
</select>
</div>
<div class="col-lg-4" >
<label for="" class="control-label">ERP Work order/PO Number</label>
</div>
<div class="col-lg-2">
<input type="text" form="work_form" class="form-control input-sm" id="erp_order" name="erp_order" required>
</div>
</div>
</div>
<br><!--end row-->
<div class="row" >
<div class="form-group">
<div class="col-lg-2" >
<label for="" class="control-label" >Description of Work</label>
</div>
<div class="col-lg-6">
<textarea form="work_form" class="form-control" rows="3" id="headoffice_address" name="headoffice_address" required></textarea>
</div>
<div class="col-lg-2" >
<label for="" class="control-label">Requirement of Vendor on Board By</label>
</div>
<div class="col-lg-2">
<input type="text" form="work_form" class="form-control input-sm" id="requirement_board" name="requirement_board" required>
</div>
</div>
</div>
</div>
<br><!----end row--->
<div class="row">
<div class="form-group">
<div class="col-lg-12">
<a href="#initiation_model" role="button" data-toggle="modal" id="model_link" class="btn btn-primary btn-xs pull-right btn-small fnmodel_link"><i class="fa fa-plus"></i> Add</a>
</div>
</div>
</div>
<br><!--end row-->
<div class="modal fade" id="initiation_model">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="pull-left" style="margin-top:20px;">Add Document</h4>
<button type="button" class="close pull-right" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<form id="approval_form" method="post">
<div class="modal-body">
<div class="col-lg-12" >
<br>
<div class="form-group">
<label class="control-label">Type of Document</label>
<select class="form-control input-sm type_document" id="type_document" name="type_document" required>
<option selected disabled >Select</option>
<option value="Tender_Drawings" >Tender Drawings</option>
<option value="Bill_of_Quantity" >Bill of Quantity</option>
<option value="Technical_Specifications" >Technical Specifications</option>
<option value="Report" >Report</option>
<option value="Quotations" >Quotations</option>
<option value="Comparative_Statement" >Comparative Statement</option>
<option value="ERP_Material_Indent" >ERP Material Indent</option>
<option value="Others" >Others</option>
</select>
</div><!-- /form-group -->
</div>
<div class="col-lg-12" >
<div class="form-group">
<label class="control-label">Description</label>
<textarea form="work_form" class="form-control" rows="3" id="headoffice_address" name="headoffice_address" required></textarea>
</div><!-- /form-group -->
</div>
<div class="col-lg-12" >
<div class="form-group">
<label class="control-label">File Name</label>
<input type="file" class="form-control input-sm" id="attachreg_certy" name="attachreg_certy" required="">
</div><!-- /form-group -->
</div>
</div>
<div class="modal-footer">
<input type="hidden" id="financial_save_update" value="">
<input type="hidden" id="financial_row_id" value="0">
<button type="button" class="btn btn-sm btn-danger" data-dismiss="modal" aria-hidden="true">Close</button>
<button type="submit" class="btn btn-sm btn-success" aria-hidden="true">Save</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div class="row">
<div class="form-group">
<div class="col-lg-12">
<div class="table-responsive">
<table id="file_info" class="table table-striped">
<thead>
<tr>
<th>Type of Document</th>
<th>Description</th>
<th>File Name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="file_info">
<td>Final BOQ</td>
<td>Edit</td>
<td>Delete</td>
</tbody>
</table>
</div>
</div>
</div>
</div>
<br><!--end row-->
<div class="row">
<div class="form-group">
<div class="col-lg-12">
<button type="button" form="button_form" class="btn btn-sm btn-success btn-sm pull-left" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button style="margin-left:5px;" type="button" class="btn btn-sm btn-info pull-right savebtn" id="save_button">Save</button>
<button style="margin-left:5px;" type="submit" class="btn btn-sm btn-info pull-right submitbtn" id="submit_button">Submit for Approval</button>
<button style="margin-left:5px;" type="button" class="btn btn-sm btn-info pull-right approvbtn" id="approve_button">Approve</button>
<button type="button" class="btn btn-sm btn-info pull-right rejectbtn" id="reject_button">Reject</button>
</div>
</div>
</div>
</div><!---project_info-heading---->
<!--------------------------------------------------- project_info tab end ------------------------------------------------------------------->
<!----------------------------------------------------------document start------------------------------------------->
<div class="tab-pane fade" id="document_tab">
<div style="margin-top:0px;border-bottom:2px solid;width:100%;">
<b>Documents</b>
</div>
<br>
<div class="row">
<div class="form-group">
<div class="col-lg-12">
<a href="#document_model" role="button" data-toggle="modal" id="model_link" class="btn btn-primary btn-xs pull-right btn-small fnmodel_link"><i class="fa fa-plus"></i> Add</a>
</div>
</div>
</div><!----end row--->
<div class="modal fade" id="document_model">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="pull-left" style="margin-top:20px;">Add Document</h4>
<button type="button" class="close pull-right" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<form id="approval_form" method="post">
<div class="modal-body">
<div class="col-lg-12" >
<br>
<div class="form-group">
<label class="control-label">Type of Document</label>
<select class="form-control input-sm type_document" id="type_document" name="type_document" required>
<option selected disabled >Select</option>
<option value="Tender_Drawings" >Tender Drawings</option>
<option value="Bill_of_Quantity" >Bill of Quantity</option>
<option value="Technical_Specifications" >Technical Specifications</option>
<option value="Report" >Report</option>
<option value="Quotations" >Quotations</option>
<option value="Comparative_Statement" >Comparative Statement</option>
<option value="ERP_Material_Indent" >ERP Material Indent</option>
<option value="Others" >Others</option>
</select>
</div><!-- /form-group -->
</div>
<div class="col-lg-12" >
<div class="form-group">
<label class="control-label">Description</label>
<textarea form="work_form" class="form-control" rows="3" id="headoffice_address" name="headoffice_address" required></textarea>
</div><!-- /form-group -->
</div>
<div class="col-lg-12" >
<div class="form-group">
<label class="control-label">File Name</label>
<input type="file" class="form-control input-sm" id="attachreg_certy" name="attachreg_certy" required="">
</div><!-- /form-group -->
</div>
</div>
<div class="modal-footer">
<input type="hidden" id="financial_save_update" value="">
<input type="hidden" id="financial_row_id" value="0">
<button type="button" class="btn btn-sm btn-danger" data-dismiss="modal" aria-hidden="true">Close</button>
<button type="submit" class="btn btn-sm btn-success" aria-hidden="true">Save</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div class="row">
<div class="form-group">
<div class="col-lg-12">
<div class="table-responsive">
<table id="file_info" class="table table-striped">
<thead>
<tr>
<th>Type of Document</th>
<th>Description</th>
<th>File Name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="file_info">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!------------------------------------------document end-------------------------------------------------------->
</div>
</div>
</div><!-- /panel -->
</div><!-- /.col -->
</div>
</br>
<div class="col-lg-12 tablehideshow">
<div class="table-responsive" id="table_master"></div>
</div>
</div><!-- /.padding-md -->
</div><!-- /main-container -->
<!-- Footer
================================================== -->
<?php include "includes/footer.php"; ?>
<!-- /wrapper -->
<a href="" id="scroll-to-top" class="hidden-print"><i class="fa fa-chevron-up"></i></a>
</div><!-- /wrapper -->
<!-- Logout confirmation -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript">var baseurl = "<?php print base_url(); ?>";</script>
<?php include "includes/footerlink.php"; ?>
<!-- <script src="<?php echo base_url(); ?>assets/multiselect/multiselect.js"></script> -->
<script type="text/javascript" src="<?php echo base_url(); ?>assets/multiselect/bootstrap-multiselect.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/AjaxFileUpload.js"></script>
</body>
</html>
| 39.594646 | 190 | 0.508596 |
b6bff575d2d4f94c9a57747c341f74a762d91f66 | 584 | kt | Kotlin | scarlet-websocket-mockwebserver/src/main/java/com/tinder/scarlet/websocket/mockwebserver/MockWebServerOkHttpWebSocketConnectionEstablisher.kt | akndmr/Scarlet | 227b493776ae99f0efadc366a9c8bfacff95eb88 | [
"BSD-3-Clause"
] | 2,904 | 2018-06-14T18:35:50.000Z | 2022-03-31T22:40:12.000Z | scarlet-websocket-mockwebserver/src/main/java/com/tinder/scarlet/websocket/mockwebserver/MockWebServerOkHttpWebSocketConnectionEstablisher.kt | akndmr/Scarlet | 227b493776ae99f0efadc366a9c8bfacff95eb88 | [
"BSD-3-Clause"
] | 172 | 2018-06-14T23:15:00.000Z | 2022-03-22T07:02:27.000Z | scarlet-websocket-mockwebserver/src/main/java/com/tinder/scarlet/websocket/mockwebserver/MockWebServerOkHttpWebSocketConnectionEstablisher.kt | akndmr/Scarlet | 227b493776ae99f0efadc366a9c8bfacff95eb88 | [
"BSD-3-Clause"
] | 251 | 2018-06-14T23:09:26.000Z | 2022-03-20T09:52:40.000Z | /*
* © 2018 Match Group, LLC.
*/
package com.tinder.scarlet.websocket.mockwebserver
import com.tinder.scarlet.websocket.okhttp.OkHttpWebSocket
import okhttp3.WebSocketListener
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
class MockWebServerOkHttpWebSocketConnectionEstablisher(
private val mockWebServer: MockWebServer
) : OkHttpWebSocket.ConnectionEstablisher {
override fun establishConnection(webSocketListener: WebSocketListener) {
mockWebServer.enqueue(MockResponse().withWebSocketUpgrade(webSocketListener))
}
}
| 29.2 | 85 | 0.821918 |
f53406ca374750be8129fcbfc3b894fd82d78ce4 | 2,011 | cpp | C++ | src/xci/widgets/Icon.cpp | rbrich/xcik | 4eab7d1dfc8b0bc269137e28af076be943c15041 | [
"Apache-2.0"
] | 11 | 2019-08-21T12:48:45.000Z | 2022-01-21T01:49:01.000Z | src/xci/widgets/Icon.cpp | rbrich/xcik | 4eab7d1dfc8b0bc269137e28af076be943c15041 | [
"Apache-2.0"
] | 3 | 2019-10-20T19:10:41.000Z | 2021-02-11T10:32:40.000Z | src/xci/widgets/Icon.cpp | rbrich/xcik | 4eab7d1dfc8b0bc269137e28af076be943c15041 | [
"Apache-2.0"
] | 1 | 2020-10-09T20:08:17.000Z | 2020-10-09T20:08:17.000Z | // Icon.cpp created on 2018-04-10 as part of xcikit project
// https://github.com/rbrich/xcikit
//
// Copyright 2018, 2019 Radek Brich
// Licensed under the Apache License, Version 2.0 (see LICENSE file)
#include "Icon.h"
#include <xci/core/string.h>
namespace xci::widgets {
using xci::core::to_utf8;
using namespace xci::graphics;
using namespace xci::text;
void Icon::set_icon(IconId icon_id)
{
m_icon_id = icon_id;
m_needs_refresh = true;
}
void Icon::set_text(const std::string& text)
{
m_text = text;
m_needs_refresh = true;
}
void Icon::set_font_size(float size)
{
m_layout.set_default_font_size(size);
m_needs_refresh = true;
}
void Icon::set_icon_color(graphics::Color color)
{
m_icon_color = color;
}
void Icon::set_color(graphics::Color color)
{
m_layout.set_default_color(color);
m_needs_refresh = true;
}
void Icon::resize(View& view)
{
view.finish_draw();
if (m_needs_refresh) {
// Refresh
m_layout.clear();
m_layout.set_font(&theme().icon_font());
m_layout.begin_span("icon");
m_layout.set_offset({0_vp, 0.125f * m_layout.default_style().size()});
m_layout.add_word(to_utf8(theme().icon_codepoint(m_icon_id)));
m_layout.end_span("icon");
m_layout.reset_offset();
m_layout.set_font(&theme().font());
m_layout.add_space();
m_layout.add_word(m_text);
m_layout.typeset(view);
m_needs_refresh = false;
}
m_layout.update(view);
auto rect = m_layout.bbox();
set_size(rect.size());
set_baseline(-rect.y);
}
void Icon::update(View& view, State state)
{
view.finish_draw();
m_layout.get_span("icon")->adjust_style([this, &state](Style& s) {
s.set_color(state.focused ? theme().color(ColorId::Focus) : m_icon_color);
});
m_layout.update(view);
}
void Icon::draw(View& view)
{
auto rect = m_layout.bbox();
m_layout.draw(view, position() - rect.top_left());
}
} // namespace xci::widgets
| 21.393617 | 82 | 0.657882 |
bb2e4aaea1a8c37b61ee31c6caaebd5729714110 | 9,370 | html | HTML | doc/VMT/tools/ASCII2KML.html | moffat/VMT | 5246150a20a670cb045587fedf6628dfad8365a5 | [
"BSD-3-Clause"
] | null | null | null | doc/VMT/tools/ASCII2KML.html | moffat/VMT | 5246150a20a670cb045587fedf6628dfad8365a5 | [
"BSD-3-Clause"
] | null | null | null | doc/VMT/tools/ASCII2KML.html | moffat/VMT | 5246150a20a670cb045587fedf6628dfad8365a5 | [
"BSD-3-Clause"
] | null | null | null | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>Description of ASCII2KML</title>
<meta name="keywords" content="ASCII2KML">
<meta name="description" content="WinRiver ASCII to Google Earth KML">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="generator" content="m2html © 2005 Guillaume Flandin">
<meta name="robots" content="index, follow">
<link type="text/css" rel="stylesheet" href="../../m2html.css">
<script type="text/javascript">
if (top.frames.length == 0) { top.location = "../../index.html"; };
</script>
</head>
<body>
<a name="_top"></a>
<!-- ../menu.html VMT --><!-- menu.html tools -->
<h1>ASCII2KML
</h1>
<h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2>
<div class="box"><strong>WinRiver ASCII to Google Earth KML</strong></div>
<h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2>
<div class="box"><strong>function [log_text,zPathName,zFileName] = ASCII2KML(inpath,infile) </strong></div>
<h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2>
<div class="fragment"><pre class="comment"> WinRiver ASCII to Google Earth KML</pre></div>
<!-- crossreference -->
<h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2>
This function calls:
<ul style="list-style-image:url(../../matlabicon.gif)">
</ul>
This function is called by:
<ul style="list-style-image:url(../../matlabicon.gif)">
<li><a href="ASCII2KML_GUI.html" class="code" title="function varargout = ASCII2KML_GUI(varargin)">ASCII2KML_GUI</a> ASCII2KML_GUI M-file for ASCII2KML_GUI.fig</li></ul>
<!-- crossreference -->
<h2><a name="_subfunctions"></a>SUBFUNCTIONS <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2>
<ul style="list-style-image:url(../../matlabicon.gif)">
<li><a href="#_sub1" class="code">function pwr_kml(name,latlon)</a></li></ul>
<h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2>
<div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function [log_text,zPathName,zFileName] = ASCII2KML(inpath,infile)</a>
0002 <span class="comment">% WinRiver ASCII to Google Earth KML</span>
0003
0004 <span class="comment">% This program reads in an ASCII file or files generated from WinRiver</span>
0005 <span class="comment">% Classic ASCII output and outputs the GPS position into a KML file which</span>
0006 <span class="comment">% can be displayed in Google Earth.</span>
0007 <span class="comment">%</span>
0008 <span class="comment">%(adapted from code by J. Czuba)</span>
0009
0010 <span class="comment">% P.R. Jackson 9/4/09</span>
0011 <span class="comment">% Last Modified: Frank L. Engel, 6/4/2014</span>
0012
0013 <span class="comment">%% Read and Convert the Data</span>
0014
0015 <span class="comment">% Determine Files to Process</span>
0016 <span class="comment">% Prompt user for directory containing files</span>
0017 current_file = fullfile(inpath,infile);
0018 [zFileName,zPathName] = uigetfile({<span class="string">'*_ASC.TXT'</span>,<span class="string">'ASCII (*_ASC.TXT)'</span>}, <span class="keyword">...</span>
0019 <span class="string">'Convert WRII ASCII output file(s) to KML: Select the ASCII Output Files'</span>, <span class="keyword">...</span>
0020 current_file, <span class="keyword">...</span>
0021 <span class="string">'MultiSelect'</span>,<span class="string">'on'</span>);
0022 <span class="keyword">if</span> ~ischar(zFileName) && ~iscell(zFileName) <span class="comment">% User hit cancel, get out quick</span>
0023 log_text = {};
0024 zPathName = inpath;
0025 zFileName = infile;
0026 <span class="keyword">return</span>
0027 <span class="keyword">end</span>
0028
0029 <span class="comment">% Determine number of files to be processed</span>
0030 <span class="keyword">if</span> isa(zFileName,<span class="string">'cell'</span>)
0031 z=size(zFileName,2);
0032 zFileName=sort(zFileName);
0033 <span class="keyword">else</span>
0034 z=1;
0035 zFileName={zFileName}
0036 <span class="keyword">end</span>
0037 <span class="comment">%msgbox('Loading Data...Please Be Patient','Conversion Status','help','replace');</span>
0038 <span class="comment">% Read in Selected Files</span>
0039 <span class="comment">% % Initialize row counter</span>
0040 <span class="comment">% j=0;</span>
0041 <span class="comment">% st=['A'; 'B'; 'C'; 'D'; 'E'; 'F'];</span>
0042 <span class="comment">% Begin master loop</span>
0043 log_text = {<span class="keyword">...</span>
0044 <span class="string">'Writing KML Files to directory:'</span>;
0045 zPathName};
0046 wbh = waitbar(0,<span class="string">'Writing KML Files...Please Be Patient'</span>);
0047 <span class="keyword">for</span> zi=1:z
0048 <span class="comment">% Open txt data file</span>
0049 <span class="keyword">if</span> isa(zFileName,<span class="string">'cell'</span>)
0050 fileName=strcat(zPathName,filesep,zFileName(zi));
0051 fileName=char(fileName);
0052 <span class="keyword">else</span>
0053 fileName=strcat(zPathName,zFileName);
0054 <span class="keyword">end</span>
0055
0056 <span class="comment">% screenData 0 leaves bad data as -32768, 1 converts to NaN</span>
0057 screenData=1;
0058
0059 <span class="comment">% tfile reads the data from an RDI ASCII output file and puts the</span>
0060 <span class="comment">% data in a Matlab data structure with major groups of:</span>
0061 <span class="comment">% Sup - supporing data</span>
0062 <span class="comment">% Wat - water data</span>
0063 <span class="comment">% Nav - navigation data including GPS.</span>
0064 <span class="comment">% Sensor - Sensor data</span>
0065 <span class="comment">% Q - discharge related data</span>
0066 ignoreBS = 0;
0067 [A(zi)]=tfile(fileName,screenData,ignoreBS);
0068 <span class="comment">%Extract only Lat lon data</span>
0069 latlon(:,1)=A(zi).Nav.lat_deg(:,:);
0070 latlon(:,2)=A(zi).Nav.long_deg(:,:);
0071
0072 <span class="comment">%Rescreen data to remove missing data (30000 value)</span>
0073 indx1 = find(abs(latlon(:,1)) > 90);
0074 indx2 = find(abs(latlon(:,2)) > 180);
0075 latlon(indx1,1)=NaN;
0076 latlon(indx2,2)=NaN;
0077
0078 indx3 = find(~isnan(latlon(:,1)) & ~isnan(latlon(:,2)));
0079 latlon = latlon(indx3,:);
0080
0081 clear A
0082
0083 <span class="comment">% Determine the file name</span>
0084 idx=strfind(fileName,<span class="string">'.'</span>);
0085 namecut = fileName(1:idx(end)-5);
0086
0087 <span class="comment">% Write latitude and longitude into a KML file</span>
0088 <span class="comment">%msgbox('Writing KML Files...','Conversion Status','help','replace');</span>
0089 <a href="#_sub1" class="code" title="subfunction pwr_kml(name,latlon)">pwr_kml</a>(namecut,latlon);
0090
0091 clear latlon idx namecut
0092 waitbar(zi/z); <span class="comment">%update the waitbar</span>
0093 <span class="keyword">end</span>
0094 delete(wbh) <span class="comment">%remove the waitbar</span>
0095 msgbox(<span class="string">'Conversion Complete'</span>,<span class="string">'Conversion Status'</span>,<span class="string">'help'</span>,<span class="string">'replace'</span>);
0096
0097 <span class="comment">% % Save the paths</span>
0098 <span class="comment">% if exist('LastDir.mat') == 2</span>
0099 <span class="comment">% save('LastDir.mat','ascii2kmlpath','-append')</span>
0100 <span class="comment">% else</span>
0101 <span class="comment">% save('LastDir.mat','ascii2kmlpath')</span>
0102 <span class="comment">% end</span>
0103
0104 <span class="comment">%%</span>
0105 <a name="_sub1" href="#_subfunctions" class="code">function pwr_kml(name,latlon)</a>
0106 <span class="comment">%makes a kml file for use in google earth</span>
0107 <span class="comment">%input: name of track, one matrix containing latitude and longitude</span>
0108 <span class="comment">%usage: pwr_kml('track5',latlon)</span>
0109
0110 header=[<span class="string">'<kml xmlns="http://earth.google.com/kml/2.0"><Placemark><description>"'</span> name <span class="string">'"</description><LineString><tessellate>1</tessellate><coordinates>'</span>];
0111 footer=<span class="string">'</coordinates></LineString></Placemark></kml>'</span>;
0112
0113 fid = fopen([name <span class="string">'ShipTrack.kml'</span>], <span class="string">'wt'</span>);
0114 d=flipud(rot90(fliplr(latlon)));
0115 fprintf(fid, <span class="string">'%s \n'</span>,header);
0116 fprintf(fid, <span class="string">'%.6f,%.6f,0.0 \n'</span>, d);
0117 fprintf(fid, <span class="string">'%s'</span>, footer);
0118 fclose(fid);
0119</pre></div>
<hr><address>Generated on Mon 08-Jun-2015 10:37:11 by <strong><a href="http://www.artefact.tk/software/matlab/m2html/" target="_parent">m2html</a></strong> © 2005</address>
</body>
</html> | 56.107784 | 285 | 0.673426 |
ea80c4b87b172a91e83c305478681a5ca80f9a56 | 1,146 | sql | SQL | sql/_31_cherry/issue_22161_CTE_extensions/_04_replace/cases/multiple_001.sql | zionyun/cubrid-testcases | ed8a07b096d721b9b42eb843fab326c63d143d77 | [
"BSD-3-Clause"
] | 9 | 2016-03-24T09:51:52.000Z | 2022-03-23T10:49:47.000Z | sql/_31_cherry/issue_22161_CTE_extensions/_04_replace/cases/multiple_001.sql | zionyun/cubrid-testcases | ed8a07b096d721b9b42eb843fab326c63d143d77 | [
"BSD-3-Clause"
] | 173 | 2016-04-13T01:16:54.000Z | 2022-03-16T07:50:58.000Z | sql/_31_cherry/issue_22161_CTE_extensions/_04_replace/cases/multiple_001.sql | zionyun/cubrid-testcases | ed8a07b096d721b9b42eb843fab326c63d143d77 | [
"BSD-3-Clause"
] | 38 | 2016-03-24T17:10:31.000Z | 2021-10-30T22:55:45.000Z | drop table if exists t;
create table t as
WITH recursive cte1 AS(
SELECT 1 AS id
union all
select id*2 as [id] from cte1 where id<=1024
),
cte2 AS(
SELECT 1 AS id
union all
select id+1 as [id] from cte2 where id<=10240 and (3*id)=(select id from cte1 order by 1 desc limit 1)
),
cte3 as (
select 1 AS id
union all
select id+1 as [id] from cte3 where id<=10240 and (6*id)=(select id from cte2 order by 1 desc limit 1)
)
SELECT *
FROM cte1
UNION ALL
SELECT *
FROM cte2
UNION ALL
SELECT *
FROM cte1 order by 1;
insert into t
WITH recursive cte1 AS(
SELECT 1 AS id
union all
select id*2 from cte1 where id<=1024
),
cte2 AS(
SELECT 1 AS id
union all
select id+1 from cte2 where id<=10240 and (3*id)=(select id from cte1 order by 1 desc limit 1)
),
cte3 as (
select 1 AS id
union all
select id+1 from cte3 where id<=10240 and (6*id)=(select id from cte2 order by 1 desc limit 1)
)
SELECT *
FROM cte1
UNION ALL
SELECT *
FROM cte2
UNION ALL
SELECT *
FROM cte1 order by 1;
select distinct id from t order by id;
select id,count(id) from t group by id order by id;
drop table if exists t;
| 20.464286 | 104 | 0.681501 |
c7d25f03ae1e1783e5ec104f7faa6f21d027d2ca | 47 | sql | SQL | test/run-time/input/expr-library/function/string/format/basic.sql | AnyhowStep/typed-orm | 2edc76e84101f1cedc508c6d8d266112413fa654 | [
"MIT"
] | 9 | 2019-01-20T23:35:51.000Z | 2020-03-30T02:13:25.000Z | test/run-time/input/expr-library/function/string/format/basic.sql | AnyhowStep/typed-orm | 2edc76e84101f1cedc508c6d8d266112413fa654 | [
"MIT"
] | 7 | 2019-05-29T16:05:16.000Z | 2021-05-07T11:21:09.000Z | test/run-time/input/expr-library/function/string/format/basic.sql | AnyhowStep/typed-orm | 2edc76e84101f1cedc508c6d8d266112413fa654 | [
"MIT"
] | null | null | null | SELECT
FORMAT(3.141, 2) AS `__aliased--value` | 23.5 | 40 | 0.702128 |
751b435ccca596062069d70cf2cfa485d9454ce8 | 9,052 | cs | C# | src/Smolev/SpellChecker/SpellChecker/Form1.Designer.cs | sms-a/Internship2019 | 1f82259d9d59fe8e84737dfd95bb195700db47b8 | [
"MIT"
] | null | null | null | src/Smolev/SpellChecker/SpellChecker/Form1.Designer.cs | sms-a/Internship2019 | 1f82259d9d59fe8e84737dfd95bb195700db47b8 | [
"MIT"
] | null | null | null | src/Smolev/SpellChecker/SpellChecker/Form1.Designer.cs | sms-a/Internship2019 | 1f82259d9d59fe8e84737dfd95bb195700db47b8 | [
"MIT"
] | 2 | 2019-07-01T16:42:26.000Z | 2019-07-02T10:38:00.000Z | namespace SpellChecker
{
partial class Form1
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором форм Windows
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.sourceText = new System.Windows.Forms.TextBox();
this.checkedText = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.открытьToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.сохранитьToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.помощьToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.оПрограммеToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.checkButton = new System.Windows.Forms.Button();
this.labelError = new System.Windows.Forms.Label();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// sourceText
//
this.sourceText.Location = new System.Drawing.Point(12, 50);
this.sourceText.Multiline = true;
this.sourceText.Name = "sourceText";
this.sourceText.Size = new System.Drawing.Size(472, 114);
this.sourceText.TabIndex = 0;
//
// checkedText
//
this.checkedText.Location = new System.Drawing.Point(12, 216);
this.checkedText.Multiline = true;
this.checkedText.Name = "checkedText";
this.checkedText.ReadOnly = true;
this.checkedText.Size = new System.Drawing.Size(472, 114);
this.checkedText.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(9, 34);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(379, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Исходный текст (формат по заданию: \"словарь === проверяемый текст\"";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(9, 200);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(113, 13);
this.label2.TabIndex = 3;
this.label2.Text = "Результат проверки:";
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem,
this.помощьToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(496, 24);
this.menuStrip1.TabIndex = 4;
this.menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.открытьToolStripMenuItem,
this.сохранитьToolStripMenuItem});
this.файлToolStripMenuItem.Name = "файлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.файлToolStripMenuItem.Text = "Файл";
//
// открытьToolStripMenuItem
//
this.открытьToolStripMenuItem.Name = "открытьToolStripMenuItem";
this.открытьToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.открытьToolStripMenuItem.Size = new System.Drawing.Size(193, 22);
this.открытьToolStripMenuItem.Text = "Открыть...";
this.открытьToolStripMenuItem.Click += new System.EventHandler(this.открытьToolStripMenuItem_Click);
//
// сохранитьToolStripMenuItem
//
this.сохранитьToolStripMenuItem.Name = "сохранитьToolStripMenuItem";
this.сохранитьToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.сохранитьToolStripMenuItem.Size = new System.Drawing.Size(193, 22);
this.сохранитьToolStripMenuItem.Text = "Сохранить как";
this.сохранитьToolStripMenuItem.Click += new System.EventHandler(this.сохранитьToolStripMenuItem_Click);
//
// помощьToolStripMenuItem
//
this.помощьToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.оПрограммеToolStripMenuItem});
this.помощьToolStripMenuItem.Name = "помощьToolStripMenuItem";
this.помощьToolStripMenuItem.Size = new System.Drawing.Size(68, 20);
this.помощьToolStripMenuItem.Text = "Помощь";
//
// оПрограммеToolStripMenuItem
//
this.оПрограммеToolStripMenuItem.Name = "оПрограммеToolStripMenuItem";
this.оПрограммеToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.оПрограммеToolStripMenuItem.Text = "О программе";
this.оПрограммеToolStripMenuItem.Click += new System.EventHandler(this.оПрограммеToolStripMenuItem_Click);
//
// checkButton
//
this.checkButton.Location = new System.Drawing.Point(405, 170);
this.checkButton.Name = "checkButton";
this.checkButton.Size = new System.Drawing.Size(79, 23);
this.checkButton.TabIndex = 5;
this.checkButton.Text = "Проверить";
this.checkButton.UseVisualStyleBackColor = true;
this.checkButton.Click += new System.EventHandler(this.checkButton_Click);
//
// labelError
//
this.labelError.AutoSize = true;
this.labelError.ForeColor = System.Drawing.Color.DarkRed;
this.labelError.Location = new System.Drawing.Point(9, 170);
this.labelError.Name = "labelError";
this.labelError.Size = new System.Drawing.Size(0, 13);
this.labelError.TabIndex = 6;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(496, 346);
this.Controls.Add(this.labelError);
this.Controls.Add(this.checkButton);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.checkedText);
this.Controls.Add(this.sourceText);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "SpellChecker";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox sourceText;
private System.Windows.Forms.TextBox checkedText;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem файлToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem открытьToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem сохранитьToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem помощьToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem оПрограммеToolStripMenuItem;
private System.Windows.Forms.Button checkButton;
private System.Windows.Forms.Label labelError;
}
}
| 47.642105 | 156 | 0.615113 |
28f1bbc2703a2d1caf7a65d701c95be73694c45c | 1,097 | cpp | C++ | ds3runtime/hooks/play_animation_hook.cpp | tremwil/DS3RuntimeScripting | 50508bbf9295f87c459722ea3bea015c85a36de5 | [
"MIT"
] | 8 | 2021-06-05T21:59:53.000Z | 2022-02-03T10:00:09.000Z | ds3runtime/hooks/play_animation_hook.cpp | tremwil/DS3RuntimeScripting | 50508bbf9295f87c459722ea3bea015c85a36de5 | [
"MIT"
] | null | null | null | ds3runtime/hooks/play_animation_hook.cpp | tremwil/DS3RuntimeScripting | 50508bbf9295f87c459722ea3bea015c85a36de5 | [
"MIT"
] | 5 | 2021-05-17T19:49:29.000Z | 2022-02-26T11:00:29.000Z | /*
* DS3RuntimeScripting
* Contributers: Amir
*/
#pragma once
#include "pch.h"
#include "play_animation_hook.h"
#include "ds3runtime/ds3runtime.h"
#include "ds3runtime/player_ins.h"
#include <ds3runtime/databaseaddress.h>
namespace ds3runtime {
PlayAnimationHook::PlayAnimationHook()
: Hook(0x140D84870, (uintptr_t)onPlayAnimation, {})
{
instance = this;
}
void PlayAnimationHook::onPlayAnimation(uintptr_t hkbCharacter, int32_t* animationId)
{
int32_t filteredId = *animationId;
for (auto filter : instance->filters) {
filteredId = filter.second(hkbCharacter, filteredId);
if (filteredId == 0) return;
}
//spdlog::debug("Animation played: {}", *animationId);
*animationId = filteredId;
void (*originalFunction)(...);
*(uintptr_t*)&originalFunction = *instance->original;
originalFunction(hkbCharacter, animationId);
}
void PlayAnimationHook::installFilter(std::string key, AnimationFilter function)
{
filters[key] = function;
}
void PlayAnimationHook::uninstallFilter(std::string key)
{
filters.erase(key);
}
PlayAnimationHook* PlayAnimationHook::instance = nullptr;
} | 22.387755 | 85 | 0.753874 |
7f68606da7b9eb0a277c40d3a2b0343b6cdc3a5d | 168 | html | HTML | example.html | tratchat/Sha256 | fbd3285c8ee860480c57324ca7cd7f457d15ef2e | [
"MIT"
] | null | null | null | example.html | tratchat/Sha256 | fbd3285c8ee860480c57324ca7cd7f457d15ef2e | [
"MIT"
] | null | null | null | example.html | tratchat/Sha256 | fbd3285c8ee860480c57324ca7cd7f457d15ef2e | [
"MIT"
] | null | null | null | <script src="https://cdn.trat.chat/sha256.min.js"></script>
<script>
document.write(Sha256.hash('abc'))
// Writes the SHA256 of abc into your browser window.
</script>
| 28 | 59 | 0.720238 |
be7003578f8d8974d5e7c6ca38e8b558ecddfea3 | 449 | sql | SQL | db/postgres/API/get_current_game_board.sql | PavelLebed20/chess_classic | 72f7d08cadae8db9c65d61411bcdc8c79bfa04c3 | [
"Apache-2.0"
] | 1 | 2019-06-04T11:08:55.000Z | 2019-06-04T11:08:55.000Z | db/postgres/API/get_current_game_board.sql | PavelLebed20/chess_classic | 72f7d08cadae8db9c65d61411bcdc8c79bfa04c3 | [
"Apache-2.0"
] | 115 | 2019-03-02T08:02:50.000Z | 2019-06-02T16:28:00.000Z | db/postgres/API/get_current_game_board.sql | PavelLebed20/chess_classic | 72f7d08cadae8db9c65d61411bcdc8c79bfa04c3 | [
"Apache-2.0"
] | null | null | null | CREATE OR REPLACE FUNCTION chess.get_current_game_board_state(
p_user_id integer) RETURNS table(board varchar, side bit) AS $$
DECLARE
BEGIN
RETURN QUERY SELECT cast(chess.game.board as varchar), chess.game.next_move_player
FROM chess.game WHERE
(chess.game.user_id1 = p_user_id or chess.game.user_id2 = p_user_id) and
chess.game.is_playing = 1::BIT LIMIT 1;
END;
$$ LANGUAGE 'plpgsql'; | 37.416667 | 92 | 0.685969 |
d4b24c01258b9a6ed58fa2c64ed316bc34f98e1c | 607 | asm | Assembly | programs/oeis/260/A260708.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/260/A260708.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/260/A260708.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A260708: a(2n) = n*(2*n+1), a(2n+7) = a(2n+1) + 12*n + 28, with a(1)=1, a(3)=6, a(5)=16.
; 0,1,3,6,10,16,21,29,36,46,55,68,78,93,105,122,136,156,171,193,210,234,253,280,300,329,351,382,406,440,465,501,528,566,595,636,666,709,741,786,820,868,903,953,990,1042,1081,1136,1176,1233,1275,1334,1378,1440,1485,1549,1596,1662,1711,1780,1830,1901,1953,2026,2080,2156,2211,2289,2346,2426,2485,2568,2628,2713,2775,2862,2926,3016,3081,3173,3240,3334,3403,3500,3570,3669,3741,3842,3916,4020,4095,4201,4278,4386,4465,4576,4656,4769,4851,4966
sub $0,1
mov $1,$0
div $0,2
add $1,2
add $0,$1
mul $1,$0
div $1,3
mov $0,$1
| 50.583333 | 438 | 0.688633 |
04e47568dd9ddf90408cacb7453139bc80f1cab8 | 506 | java | Java | piano-hero/core/src/main/java/com/novoda/pianohero/SimplePitchNotationFormatter.java | jgtaylor123/novoda_spikes | 7bdebb58318d09a6ff5645694b0b7d9f7f6a1dff | [
"Apache-2.0"
] | 568 | 2015-02-12T17:35:42.000Z | 2022-03-20T19:54:00.000Z | piano-hero/core/src/main/java/com/novoda/pianohero/SimplePitchNotationFormatter.java | jgtaylor123/novoda_spikes | 7bdebb58318d09a6ff5645694b0b7d9f7f6a1dff | [
"Apache-2.0"
] | 237 | 2015-04-04T04:02:42.000Z | 2021-11-11T09:06:17.000Z | piano-hero/core/src/main/java/com/novoda/pianohero/SimplePitchNotationFormatter.java | jgtaylor123/novoda_spikes | 7bdebb58318d09a6ff5645694b0b7d9f7f6a1dff | [
"Apache-2.0"
] | 161 | 2015-07-20T03:49:25.000Z | 2022-02-09T03:58:11.000Z | package com.novoda.pianohero;
import java.util.Arrays;
import java.util.List;
public class SimplePitchNotationFormatter {
private static final int NOTES_IN_OCTAVE = 12;
private static final List<String> ORDERED_NOTES = Arrays.asList("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B");
public String format(Note note) {
if(note == Note.NONE) {
return "";
}
int i = note.midi() % NOTES_IN_OCTAVE;
return ORDERED_NOTES.get(i);
}
}
| 26.631579 | 133 | 0.594862 |
c561e39fa5a3184e0d1927be3459a9e1aaf08e02 | 2,060 | hpp | C++ | BookReader/BookAtomBinary.hpp | msdmazarei/cpp-msd-freetype | ae4c79512ea6c9fba686235e9dd2dd03bd791a6f | [
"BSD-2-Clause"
] | null | null | null | BookReader/BookAtomBinary.hpp | msdmazarei/cpp-msd-freetype | ae4c79512ea6c9fba686235e9dd2dd03bd791a6f | [
"BSD-2-Clause"
] | null | null | null | BookReader/BookAtomBinary.hpp | msdmazarei/cpp-msd-freetype | ae4c79512ea6c9fba686235e9dd2dd03bd791a6f | [
"BSD-2-Clause"
] | null | null | null | #ifndef _H_MSD_BOOKATOMBinary_
#define _H_MSD_BOOKATOMBinary_
#include "BookAtom.hpp"
#include "clearTypeClass/cleartype.hpp"
#include "decomposable/decomposable.hpp"
#include "defs/typedefs.hpp"
enum BookAtomBinaryType {
BookAtomBinaryTypes_PDF = 1,
BookAtomBinaryTypes_EPUB = 2,
BookAtomBinaryTypes_XPS = 3
};
class BookAtomBinary : public BookAtom, public Decomposable<BYTE> {
protected:
WORD type;
DWORD bytesLength;
BYTE *buffer;
public:
BookAtomBinary(DWORD bytesLength, BYTE *buf, WORD type)
: BookAtom(BookAtomType_Binary), bytesLength(bytesLength), buffer(buf),
type(type){};
ClassName getType() override { return ClassName_BookAtomBinary; }
bool is_screen_renderable() override{return true;};
bool is_render_decomposable() override{return false;};
Vector<BYTE> decompose() override { throw 1; };
BYTE *getBuffer() { return buffer; }
DWORD getBufferLength() { return bytesLength; }
BookAtom *clone() override {
BookAtom *rtn = new BookAtomBinary(bytesLength, buffer, type);
return rtn;
}
BookAtom *deserialize_from_bin(DWORD len, BYTE *buf) override { throw 1; }
List<BYTE> *serialize_binary() override{throw 1;};
};
class BookAtomPDF : public BookAtomBinary {
public:
BookAtomPDF(DWORD bytesLength, BYTE *buf)
: BookAtomBinary(bytesLength, buf, (WORD)BookAtomBinaryTypes_PDF) {
atom_type=BookAtomType_PDF;
}
ClassName getType() override { return ClassName_BookAtomPDF; }
};
class BookAtomXPS : public BookAtomBinary {
public:
BookAtomXPS(DWORD bytesLength, BYTE *buf)
: BookAtomBinary(bytesLength, buf, (WORD)BookAtomBinaryTypes_XPS) {
atom_type=BookAtomType_XPS;
}
ClassName getType() override { return ClassName_BookAtomXPS; }
};
class BookAtomEPUB : public BookAtomBinary {
public:
BookAtomEPUB(DWORD bytesLength, BYTE *buf)
: BookAtomBinary(bytesLength, buf, (WORD)BookAtomBinaryTypes_EPUB) {
atom_type=BookAtomType_EPUB;
}
ClassName getType() override { return ClassName_BookAtomEPUB; }
};
#endif | 32.698413 | 77 | 0.734951 |
04a3153841d18fd524512d859e1142b288c8dead | 505 | java | Java | src/main/java/com/lajospolya/spotifyapiwrapper/response/Artists.java | LajosPolya/Spotify-API-Wrapper | 53cda176c4bff8b7e2a13f6bb3cbfa3d3c9d6ac9 | [
"MIT"
] | 1 | 2020-04-15T23:21:23.000Z | 2020-04-15T23:21:23.000Z | src/main/java/com/lajospolya/spotifyapiwrapper/response/Artists.java | LajosPolya/Spotify-API-Wrapper | 53cda176c4bff8b7e2a13f6bb3cbfa3d3c9d6ac9 | [
"MIT"
] | 1 | 2020-04-02T02:17:44.000Z | 2020-04-03T19:49:51.000Z | src/main/java/com/lajospolya/spotifyapiwrapper/response/Artists.java | LajosPolya/Spotify-API-Wrapper | 53cda176c4bff8b7e2a13f6bb3cbfa3d3c9d6ac9 | [
"MIT"
] | null | null | null | package com.lajospolya.spotifyapiwrapper.response;
import java.util.List;
/**
* @author Lajos Polya
* Represent the response of GetArtist, and GetArtistsRelatedArtists as described at
* https://developer.spotify.com/documentation/web-api/reference-beta/
*/
public class Artists
{
List<Artist> artists;
public List<Artist> getArtists()
{
return artists;
}
public void setArtists(List<Artist> artists)
{
this.artists = artists;
}
}
| 21.041667 | 85 | 0.663366 |
754b884bbdb550dffae02b90fbbb5c269948e34c | 2,794 | c | C | usr/src/cmd/lp/lib/msgs/mread.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/lp/lib/msgs/mread.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/lp/lib/msgs/mread.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/* Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T */
/* All Rights Reserved */
#ident "%Z%%M% %I% %E% SMI" /* SVr4.0 1.6 */
/* LINTLIBRARY */
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <stropts.h>
#include "lp.h"
#include "msgs.h"
extern int Lp_prio_msg;
/*
** Function: int mread( MESG *, char *, int)
** Args: message descriptor
** message buffer (var)
** buffer size
** Return: The size of the message in message buffer.
** or -1 on error. Possible errnos are:
** EINVAL Bad value for md or msgbuf.
** E2BIG Not enough space for message.
** EPIPE Far end dropped the connection.
** ENOMSG No valid message available on fifo.
**
** mread examines message descriptor and either calls read3_2
** to read 3.2 HPI messages or getmsg(2) to read 4.0 HPI messages.
** If a message is read, it is returned in message buffer.
*/
#if defined(__STDC__)
int mread ( MESG * md, char * msgbuf, int size )
#else
int mread ( md, msgbuf, size )
MESG *md;
char *msgbuf;
int size;
#endif
{
int flag = 0;
char buff [MSGMAX];
struct strbuf dat;
struct strbuf ctl;
if (md == NULL || msgbuf == NULL)
{
errno = EINVAL;
return(-1);
}
switch(md->type)
{
case MD_CHILD:
case MD_STREAM:
case MD_BOUND:
if (size <= 0)
{
errno = E2BIG;
return(-1);
}
dat.buf = msgbuf;
dat.maxlen = size;
dat.len = 0;
ctl.buf = buff;
ctl.maxlen = sizeof (buff);
ctl.len = 0;
flag = Lp_prio_msg;
Lp_prio_msg = 0; /* clean this up so there are no surprises */
if (Getmsg(md, &ctl, &dat, &flag) < 0)
{
if (errno == EBADF)
errno = EPIPE;
return(-1);
}
if (dat.len == 0)
{
(void) Close(md->readfd);
return(0);
}
break;
case MD_USR_FIFO:
case MD_SYS_FIFO:
if (size < CONTROL_LEN)
{
errno = E2BIG;
return(-1);
}
if (read3_2(md, msgbuf, size) < 0)
return(-1);
break;
}
return((int)msize(msgbuf));
}
| 22.352 | 70 | 0.645311 |
1a7c5f0f38bb4be0fb22ee919032e585cfeda423 | 612 | asm | Assembly | libsrc/oz/ozgfx/ozputch.asm | dex4er/deb-z88dk | 9ee4f23444fa6f6043462332a1bff7ae20a8504b | [
"ClArtistic"
] | 1 | 2018-09-04T23:07:24.000Z | 2018-09-04T23:07:24.000Z | libsrc/oz/ozgfx/ozputch.asm | dex4er/deb-z88dk | 9ee4f23444fa6f6043462332a1bff7ae20a8504b | [
"ClArtistic"
] | null | null | null | libsrc/oz/ozgfx/ozputch.asm | dex4er/deb-z88dk | 9ee4f23444fa6f6043462332a1bff7ae20a8504b | [
"ClArtistic"
] | null | null | null | ;
; Sharp OZ family functions
;
; ported from the OZ-7xx SDK by by Alexander R. Pruss
; by Stefano Bodrato - Oct. 2003
;
;
; gfx functions
;
; int ozputch (int x, int y, char c);
;
; ------
; $Id: ozputch.asm,v 1.1 2003/10/21 17:15:20 stefano Exp $
;
XLIB ozputch
LIB ozputs
ozputchbuf:
defb 0 ; Char to be printed
defb 0 ; string terminator
ozputch:
;ld hl,6
ld hl,2
add hl,sp
ld a,(hl)
ld (ozputchbuf),a
ld bc,ozputchbuf
ld (hl),c
inc hl
ld (hl),b
jp ozputs
| 17.485714 | 59 | 0.504902 |
4a86d48d4b11897a2304e865099dba22db27880b | 787 | html | HTML | exercicios/ex022/fundo002.html | NathaliStell/html-css | 30ee907befbb6c02baa6099ef2c55c143dd23afa | [
"MIT"
] | null | null | null | exercicios/ex022/fundo002.html | NathaliStell/html-css | 30ee907befbb6c02baa6099ef2c55c143dd23afa | [
"MIT"
] | null | null | null | exercicios/ex022/fundo002.html | NathaliStell/html-css | 30ee907befbb6c02baa6099ef2c55c143dd23afa | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Personalização dos fundos</title>
<style>
body {
background-image: url('https://gustavoguanabara.github.io/html-css/imagens/mascote.png'); background-size: 100px 100px;
background-repeat: no-repeat;
/* essas propriedades ajudam a definir se seu background image vai se repetir ou não e de que forma isso vai acontecer.
background-repeat: repeat-y (y de ordenadas, vertical)
ou
background-repeat: repeat-x (x de abscissas, horizontal)*/
}
</style>
</head>
<body>
</body>
</html> | 37.47619 | 131 | 0.636595 |
4aa47de55cff3cf35d8e7719bf5def82a16fb720 | 1,704 | html | HTML | schroeder/index.html | loicseguin/lab | 14e0c5f622d39efb8e969a3dc25dd0b1103bd828 | [
"MIT"
] | 1 | 2020-06-04T02:39:25.000Z | 2020-06-04T02:39:25.000Z | schroeder/index.html | loicseguin/lab | 14e0c5f622d39efb8e969a3dc25dd0b1103bd828 | [
"MIT"
] | null | null | null | schroeder/index.html | loicseguin/lab | 14e0c5f622d39efb8e969a3dc25dd0b1103bd828 | [
"MIT"
] | null | null | null | <!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Newton's Cannon</title>
<link rel="stylesheet" href="newton.css">
</head>
<body>
<h1>Newton's Cannon</h1>
<div class="figure" style="width: 500px; height: 500px;">
<img src="newtondrawing.jpg" width="500" height="500"
alt="Netwon's illustration of the cannon" />
<canvas id="trailcanvas" width="500" height="500">
Canvas not supported, please use an up to date modern web browser.
</canvas>
<canvas id="thecanvas" width="500" height="500">
Canvas not supported, please use an up to date modern web browser.
</canvas>
</div>
<div class="centered">
<!--<input type="button" value="Fire!" onclick="fireProjectile();" />-->
<a class="customButton" href="javascript:void(0)"
onclick="fireProjectile();" ontouchstart="">Fire!</a>
<a class="customButton" href="javascript:void(0)"
onclick="clearFigure();" ontouchstart="">Clear!</a>
<input id="speedslider" type="range"
min="0" max="8000" step="100" value="3000"
oninput="showSpeed();" onchange="showSpeed();" />
Initial speed = <span id="speedreadout">3000</span> m/s
</div>
<p>This simulation is based on Isaac Newton's famous thought experiment and
illustration of firing a projectile from a high mountaintop at various
speeds as described in <a
href="http://books.google.com/books?id=DXE9AAAAcAAJ">A Treatise of the
System of the World</a>.</p>
<script src="newton.js"></script>
</body>
</html>
| 32.769231 | 80 | 0.607394 |
d71b375b0b0d7923bd4339d1bcf3ef95e0db0336 | 1,756 | lua | Lua | gamemodes/ix_cotz/schema/items/technician/sh_tooloil1.lua | kristofferth/cotz | 7d76c0214fbe8bbda6a8996697154d0feaf50f44 | [
"MIT"
] | 3 | 2021-12-15T12:49:33.000Z | 2022-01-15T16:15:40.000Z | gamemodes/ix_cotz/schema/items/technician/sh_tooloil1.lua | kristofferth/cotz | 7d76c0214fbe8bbda6a8996697154d0feaf50f44 | [
"MIT"
] | 1 | 2022-02-10T19:12:08.000Z | 2022-02-10T19:36:02.000Z | gamemodes/ix_cotz/schema/items/technician/sh_tooloil1.lua | kristofferth/cotz | 7d76c0214fbe8bbda6a8996697154d0feaf50f44 | [
"MIT"
] | 3 | 2021-12-07T00:34:43.000Z | 2021-12-23T15:37:44.000Z | ITEM.name = "Cleaning Solvent"
ITEM.desc = "Used by technicians to restore the durability of tools."
ITEM.model = "models/lostsignalproject/items/repair/gun_oil_ru_d.mdl"
ITEM.width = 1
ITEM.height = 1
ITEM.price = "5000"
ITEM.flag = "A"
ITEM.toolValue = 2
ITEM.functions.repair = {
name = "Repair Tools",
icon = "icon16/stalker/repair.png",
isMulti = true,
multiOptions = function(item, client)
local targets = {}
local char = client:GetCharacter()
if (char) then
local inv = char:GetInventory()
if (inv) then
local items = inv:GetItems()
for k, v in pairs(items) do
if v.isTool and v:GetData("quantity", 0) < 100 then
table.insert(targets, {
name = L("Repair "..v.name.." with "..math.Clamp(v:GetData("quantity",0), 0 , 100).." percent durability to "..math.Clamp(v:GetData("quantity",0)+(item.toolValue*v.toolMult), 0, 100).." percent durability"),
data = {v:GetID()},
})
else
continue
end
end
end
end
return targets
end,
OnCanRun = function(item)
return (!IsValid(item.entity))
end,
OnRun = function(item, data)
local client = item.player
local char = client:GetCharacter()
local inv = char:GetInventory()
local items = inv:GetItems()
local target = data[1]
for k, invItem in pairs(items) do
if (data[1]) then
if (invItem:GetID() == data[1]) then
target = invItem
break
end
else
client:Notify("No tool selected.")
return false
end
end
target:SetData("quantity", math.Clamp(target:GetData("quantity",100) + (item.toolValue*target.toolMult), 0, 100))
client:Notify(target.name.." successfully repaired.")
item.player:EmitSound("stalkersound/inv_attach_addon.mp3")
return true
end,
} | 25.085714 | 214 | 0.654897 |
6ebb4acdbad8b1f6a627d98f5c4392f11ef0ec0e | 920 | kt | Kotlin | app/src/main/java/com/hongwei/android_lab/lab/rx3/Rx3Test.kt | hongwei-bai/android-lab | c3fc0d4b4145f1ff537b7e4cbbceec8a831b3093 | [
"MIT"
] | null | null | null | app/src/main/java/com/hongwei/android_lab/lab/rx3/Rx3Test.kt | hongwei-bai/android-lab | c3fc0d4b4145f1ff537b7e4cbbceec8a831b3093 | [
"MIT"
] | null | null | null | app/src/main/java/com/hongwei/android_lab/lab/rx3/Rx3Test.kt | hongwei-bai/android-lab | c3fc0d4b4145f1ff537b7e4cbbceec8a831b3093 | [
"MIT"
] | null | null | null | package com.hongwei.android_lab.lab.rx3
import android.util.Log
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.schedulers.Schedulers
class Rx3Test {
fun testMergeCompletables() {
val c1 = Completable.create {
Log.d("bbbb", "c1 start...")
Thread.sleep(2000)
Log.d("bbbb", "c1 finish")
}.subscribeOn(Schedulers.io())
val c2 = Completable.create {
Log.d("bbbb", "c2 start...")
Thread.sleep(3000)
Log.d("bbbb", "c2 finish")
}.subscribeOn(Schedulers.io())
// c1.mergeWith(c2).subscribe {
// Log.d("bbbb", "concatWith finish")
// }
val decisionId: String? = null//"123"
c1.run {
decisionId?.let {
mergeWith(c2)
} ?: this
}.subscribe {
Log.d("bbbb", "concatWith finish")
}
}
} | 27.878788 | 49 | 0.53587 |
0376881ded469765a404dcf6bb65c886222bfcac | 1,071 | swift | Swift | MathTraining/ResultViewController.swift | Juliennu/MathQuiz | 837c14c1f3a6d684d0e557f444e34c8f6164ced8 | [
"MIT"
] | null | null | null | MathTraining/ResultViewController.swift | Juliennu/MathQuiz | 837c14c1f3a6d684d0e557f444e34c8f6164ced8 | [
"MIT"
] | null | null | null | MathTraining/ResultViewController.swift | Juliennu/MathQuiz | 837c14c1f3a6d684d0e557f444e34c8f6164ced8 | [
"MIT"
] | null | null | null | //
// ResultViewController.swift
// MathTraining
//
// Created by Juri Ohto on 2021/03/08.
//
import UIKit
class ResultViewController: UIViewController {
var result = 0.0
@IBOutlet var resultLabel: UILabel!
@IBOutlet var messageLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
resultLabel.text = "\(round(result))%"
if result < 50 {
messageLabel.text = "Please Try Again!"
}else if result < 80 {
messageLabel.text = "Nice!"
}else {
messageLabel.text = "You are GREAT!!"
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 22.3125 | 106 | 0.590103 |
bf832d0b264cef51de678350a8c92d48c858a2d3 | 1,000 | sql | SQL | src/main/schema.sql | canmogol/project-webflux | 9f93c3d79e6ecf2e8697bc2dedf4b9fb11823ce8 | [
"MIT"
] | null | null | null | src/main/schema.sql | canmogol/project-webflux | 9f93c3d79e6ecf2e8697bc2dedf4b9fb11823ce8 | [
"MIT"
] | null | null | null | src/main/schema.sql | canmogol/project-webflux | 9f93c3d79e6ecf2e8697bc2dedf4b9fb11823ce8 | [
"MIT"
] | null | null | null |
CREATE OR REPLACE FUNCTION public.notify_event()
RETURNS trigger
LANGUAGE plpgsql
as
$function$
DECLARE
payload JSON;
BEGIN
-- raise warning 'book_notification before row_to_json id: % author: %', NEW.id, NEW.author;
payload = json_build_object('new', row_to_json(NEW), 'old', row_to_json(OLD), 'operation', TG_OP);
-- raise warning 'book_notification after row_to_json payload: %', payload::text;
PERFORM pg_notify('book_notification', payload::text);
-- raise warning 'book_notification after pg_notify payload: %', payload::text;
RETURN NULL;
END;
$function$;
DROP table public.book;
CREATE TABLE IF NOT EXISTS public.book
(
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL
);
DROP TRIGGER IF EXISTS notify_book ON public.book;
CREATE TRIGGER notify_book
AFTER INSERT OR UPDATE OR DELETE
ON public.book
FOR EACH ROW
EXECUTE PROCEDURE notify_event();
ALTER TABLE public.book ENABLE ALWAYS TRIGGER notify_book;
| 26.315789 | 102 | 0.727 |
11cb227d9a4386f42fe929ffba86773194b5e9a2 | 2,926 | rs | Rust | azure-functions/src/util.rs | rylev/azure-functions-rs | 7bc1e1d977da8bca669e7d802d401c689448e852 | [
"MIT"
] | null | null | null | azure-functions/src/util.rs | rylev/azure-functions-rs | 7bc1e1d977da8bca669e7d802d401c689448e852 | [
"MIT"
] | null | null | null | azure-functions/src/util.rs | rylev/azure-functions-rs | 7bc1e1d977da8bca669e7d802d401c689448e852 | [
"MIT"
] | null | null | null | use crate::rpc::protocol;
use serde::de::IntoDeserializer;
use serde::Deserialize;
use serde_json::from_str;
use std::str::{from_utf8, FromStr};
pub fn convert_from<T>(data: &'a protocol::TypedData) -> Option<T>
where
T: FromStr + Deserialize<'a>,
{
if data.has_string() {
return data.get_string().parse::<T>().ok();
}
if data.has_json() {
return from_str(data.get_json()).ok();
}
if data.has_bytes() {
if let Ok(s) = from_utf8(data.get_bytes()) {
return s.parse::<T>().ok();
}
return None;
}
if data.has_stream() {
if let Ok(s) = from_utf8(data.get_stream()) {
return s.parse::<T>().ok();
}
return None;
}
if data.has_int() {
let deserializer: ::serde::de::value::I64Deserializer<::serde_json::error::Error> =
data.get_int().into_deserializer();
return T::deserialize(deserializer).ok();
}
if data.has_double() {
let deserializer: ::serde::de::value::F64Deserializer<::serde_json::error::Error> =
data.get_double().into_deserializer();
return T::deserialize(deserializer).ok();
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_converts_from_string_data() {
const DATA: &'static str = "test";
let mut data = protocol::TypedData::new();
data.set_string(DATA.to_string());
let s: String = convert_from(&data).unwrap();
assert_eq!(s, DATA);
}
#[test]
fn it_converts_from_json_data() {
let mut data = protocol::TypedData::new();
data.set_json(r#""hello world""#.to_string());
let s: String = convert_from(&data).unwrap();
assert_eq!(s, "hello world");
}
#[test]
fn it_converts_from_bytes_data() {
let mut data = protocol::TypedData::new();
data.set_bytes(vec![
0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77, 0x6F, 0x72, 0x6C, 0x64,
]);
let s: String = convert_from(&data).unwrap();
assert_eq!(s, "hello world");
}
#[test]
fn it_converts_from_stream_data() {
let mut data = protocol::TypedData::new();
data.set_stream(vec![
0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77, 0x6F, 0x72, 0x6C, 0x64,
]);
let s: String = convert_from(&data).unwrap();
assert_eq!(s, "hello world");
}
#[test]
fn it_converts_from_int_data() {
const DATA: i64 = 42;
let mut data = protocol::TypedData::new();
data.set_int(DATA);
let d: i64 = convert_from(&data).unwrap();
assert_eq!(d, DATA);
}
#[test]
fn it_converts_from_double_data() {
const DATA: f64 = 42.24;
let mut data = protocol::TypedData::new();
data.set_double(DATA);
let d: f64 = convert_from(&data).unwrap();
assert_eq!(d, DATA);
}
}
| 25.008547 | 91 | 0.561859 |
c7db9ab40ecfafa2942cbfa086b208e36734d6e2 | 135 | py | Python | 11_class_initialization/twelth_class.py | utkarshsaraf19/python-object-oriented-programming | f36d7b72567a3dc5c21da7653e0db6274a3f5516 | [
"CC0-1.0"
] | null | null | null | 11_class_initialization/twelth_class.py | utkarshsaraf19/python-object-oriented-programming | f36d7b72567a3dc5c21da7653e0db6274a3f5516 | [
"CC0-1.0"
] | null | null | null | 11_class_initialization/twelth_class.py | utkarshsaraf19/python-object-oriented-programming | f36d7b72567a3dc5c21da7653e0db6274a3f5516 | [
"CC0-1.0"
] | null | null | null | class RequiredClass:
pass
def main():
required = RequiredClass()
print(required)
if __name__ == '__main__':
main()
| 11.25 | 30 | 0.62963 |
12b648dc5ff4863988ab7db8389abe7c09ef7b7d | 3,536 | swift | Swift | HouseOfToday/HouseOfToday/Home/Picture/TableViewFooter.swift | changSic/iOSHouseOfToday | 96505967a66f84b1e755fa9385c98d27aa4a49a6 | [
"MIT"
] | 9 | 2019-08-20T05:48:41.000Z | 2019-08-30T08:47:26.000Z | HouseOfToday/HouseOfToday/Home/Picture/TableViewFooter.swift | Chang-Geun-Ryu/iOSHouseOfToday | c234b9334497c05f37fb7b70463ef34d32ab1ab9 | [
"MIT"
] | 3 | 2019-07-09T11:35:02.000Z | 2019-07-28T13:13:57.000Z | HouseOfToday/HouseOfToday/Home/Picture/TableViewFooter.swift | Chang-Geun-Ryu/iOSHouseOfToday | c234b9334497c05f37fb7b70463ef34d32ab1ab9 | [
"MIT"
] | 4 | 2019-07-06T07:08:48.000Z | 2019-07-16T09:57:14.000Z | //
// TableViewFooter.swift
// HouseOfToday
//
// Created by Daisy on 06/08/2019.
// Copyright © 2019 CHANGGUEN YU. All rights reserved.
//
import UIKit
class TableViewFooter: UITableViewHeaderFooterView {
static var height = UIScreen.main.bounds.height/20
private lazy var heartButton: UIButton = {
let button = UIButton(type: .custom)
button.setTitle("1", for: .normal)
button.setTitleColor(.darkGray, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
button.setImage(UIImage(named: "picHeart"), for: .normal)
button.setImage(UIImage(named: "fullPicHeart"), for: .selected)
// button.addTarget(self, action: #selector(didTapHeartButton(_:)), for: .touchUpInside)
addSubview(button)
return button
}()
private lazy var scrapButton: UIButton = {
let button = UIButton(type: .custom)
button.setTitle("1", for: .normal)
button.setTitleColor(.darkGray, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
button.setImage(UIImage(named: "picBookMark"), for: .normal)
button.setImage(UIImage(named: "fullPicBookMark"), for: .selected)
// button.addTarget(self, action: #selector(didTapScrapButton(_:)), for: .touchUpInside)
// button.isUserInteractionEnabled = true
addSubview(button)
return button
}()
private lazy var commentButton: UIButton = {
let button = UIButton(type: .custom)
button.setTitle("1", for: .normal)
button.setImage(UIImage(named: "picComment"), for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
button.setTitleColor(.darkGray, for: .normal)
// button.addTarget(self, action: #selector(didTapCommentButton(_:)), for: .touchUpInside)
addSubview(button)
return button
}()
private lazy var sharingButton: UIButton = {
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "picShare"), for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
button.setTitleColor(.darkGray, for: .normal)
// button.addTarget(self, action: #selector(didTapSharingButton(_:)), for: .touchUpInside)
addSubview(button)
return button
}()
private lazy var socialButtonStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [ self.heartButton,
self.scrapButton,
self.commentButton,
self.sharingButton]
)
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .fillEqually
stackView.spacing = 10
addSubview(stackView)
return stackView
}()
override init(reuseIdentifier: String?) {
super .init(reuseIdentifier: reuseIdentifier)
configureLabel()
backgroundColor = .clear
// backgroundColor?.withAlphaComponent(50)
contentView.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.3)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
backgroundColor = .clear
// backgroundColor?.withAlphaComponent(50)
contentView.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.3)
}
private func configureLabel() {
socialButtonStackView.snp.makeConstraints { make in
make.edges.equalToSuperview()
make.width.equalToSuperview().multipliedBy(0.9)
}
}
}
| 34 | 97 | 0.668835 |
05bf7ac09ffeddf62fff9e3db653482319fd08d1 | 354 | sql | SQL | Algo and DSA/LeetCode-Solutions-master/MySQL/new-users-daily-count.sql | Sourav692/FAANG-Interview-Preparation | f523e5c94d582328b3edc449ea16ac6ab28cdc81 | [
"Unlicense"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | Algo and DSA/LeetCode-Solutions-master/MySQL/new-users-daily-count.sql | Sourav692/FAANG-Interview-Preparation | f523e5c94d582328b3edc449ea16ac6ab28cdc81 | [
"Unlicense"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | Algo and DSA/LeetCode-Solutions-master/MySQL/new-users-daily-count.sql | Sourav692/FAANG-Interview-Preparation | f523e5c94d582328b3edc449ea16ac6ab28cdc81 | [
"Unlicense"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | # Time: O(n)
# Space: O(n)
SELECT login_date,
Count(user_id) AS user_count
FROM (SELECT user_id,
Min(activity_date) AS login_date
FROM traffic
WHERE activity = 'login'
GROUP BY user_id
ORDER BY NULL) p
WHERE Datediff('2019-06-30', login_date) <= 90
GROUP BY login_date
ORDER BY NULL
| 23.6 | 48 | 0.60452 |
4fe4ef30eabea44aa5c6877c2d007fdd1436f520 | 3,439 | lua | Lua | yatm_reactors/nodes/fuel_rod.lua | IceDragon200/mt-yatm | 7452f2905e1f4121dc9d244d18a23e76b11ebe5d | [
"Apache-2.0"
] | 3 | 2019-03-15T03:17:36.000Z | 2020-02-19T19:50:49.000Z | yatm_reactors/nodes/fuel_rod.lua | IceDragon200/mt-yatm | 7452f2905e1f4121dc9d244d18a23e76b11ebe5d | [
"Apache-2.0"
] | 24 | 2019-12-02T06:01:04.000Z | 2021-04-08T04:09:27.000Z | yatm_reactors/nodes/fuel_rod.lua | IceDragon200/mt-yatm | 7452f2905e1f4121dc9d244d18a23e76b11ebe5d | [
"Apache-2.0"
] | null | null | null | local cluster_reactor = assert(yatm.cluster.reactor)
local function fuel_rod_refresh_infotext(pos, node)
local meta = minetest.get_meta(pos)
local infotext =
cluster_reactor:get_node_infotext(pos)
meta:set_string("infotext", infotext)
end
local fuel_rod_open_reactor_device = {
kind = "fuel_rod",
groups = {
fuel_rod_casing = 1,
fuel_rod_open = 1,
device = 1,
},
default_state = "off",
states = {
conflict = "yatm_reactors:fuel_rod_case_open",
error = "yatm_reactors:fuel_rod_case_open",
off = "yatm_reactors:fuel_rod_case_open",
on = "yatm_reactors:fuel_rod_case_open",
}
}
yatm_reactors.register_reactor_node("yatm_reactors:fuel_rod_case_open", {
description = "Fuel Rod Case (Unoccupied)",
groups = {
cracky = 1
},
drop = fuel_rod_open_reactor_device.states.off,
tiles = {
"yatm_reactor_fuel_rod_case.open.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png^[transformFX",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
},
paramtype = "none",
paramtype2 = "facedir",
reactor_device = fuel_rod_open_reactor_device,
refresh_infotext = fuel_rod_refresh_infotext,
})
local function update_fuel_rod(pos, node, state, dtime)
-- todo consume fuel rod
end
for _, variant in ipairs({"uranium", "plutonium", "radium", "redranium"}) do
local fuel_rod_reactor_device = {
kind = "machine",
groups = {
fuel_rod = 1,
["fuel_rod_" .. variant] = 1,
device = 1,
},
default_state = "off",
states = {
conflict = "yatm_reactors:fuel_rod_case_" .. variant .. "_error",
error = "yatm_reactors:fuel_rod_case_" .. variant .. "_error",
off = "yatm_reactors:fuel_rod_case_" .. variant .. "_off",
on = "yatm_reactors:fuel_rod_case_" .. variant .. "_on",
}
}
fuel_rod_reactor_device.update_fuel_rod = update_fuel_rod
yatm_reactors.register_stateful_reactor_node({
basename = "yatm_reactors:fuel_rod_case_" .. variant,
description = "Reactor Fuel Rod (" .. variant .. ")",
groups = {
cracky = 1,
nuclear_fuel_rod = 1,
["nuclear_fuel_rod_" .. variant] = 1,
},
nuclear_fuel_rod_type = variant,
drop = fuel_rod_reactor_device.states.off,
tiles = {
"yatm_reactor_fuel_rod_case.closed." .. variant .. ".png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png^[transformFX",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
},
paramtype = "none",
paramtype2 = "facedir",
reactor_device = fuel_rod_reactor_device,
refresh_infotext = fuel_rod_refresh_infotext,
}, {
error = {
tiles = {
"yatm_reactor_fuel_rod_case.closed." .. variant .. ".png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png^[transformFX",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
},
},
on = {
tiles = {
"yatm_reactor_fuel_rod_case.closed." .. variant .. ".png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png^[transformFX",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
},
},
})
end
| 25.474074 | 76 | 0.66153 |
1a8057410fceb8df74bce6f850b9ec3b1442d755 | 689 | lua | Lua | demo/spiFlash/lmath.lua | openLuat/Luat_Lua_Air724U | b45ba7b57ae4387c36b4243fcdd23a7da494980b | [
"MIT"
] | 1 | 2021-04-06T01:46:53.000Z | 2021-04-06T01:46:53.000Z | demo/spiFlash/lmath.lua | airystar/lua_air724U | c19bbef7219d0aab4761f4ff77af2b100491e8cb | [
"MIT"
] | null | null | null | demo/spiFlash/lmath.lua | airystar/lua_air724U | c19bbef7219d0aab4761f4ff77af2b100491e8cb | [
"MIT"
] | 1 | 2021-07-01T11:46:53.000Z | 2021-07-01T11:46:53.000Z | -- luat math lib
require "bit"
module(..., package.seeall)
local seed = tonumber(tostring(os.time()):reverse():sub(1, 7)) + rtos.tick()
function randomseed(val)
seed = val
end
function random(min, max)
local next = seed
next = next * 1103515245
next = next + 12345
local result = (next / 65536) % 2048
next = next * 1103515245
next = next + 12345
result = result * 2 ^ 10
result = bit.bxor(result, (next / 65536) % 1024)
next = next * 1103515245
next = next + 12345
result = result * 2 ^ 10
result = bit.bxor(result, (next / 65536) % 1024)
seed = next
return min + (result % (max - min))
end
| 22.225806 | 77 | 0.577649 |
4ad64be7bfa5ad2b2f0d4b9e794888d8a63b16bf | 1,013 | cs | C# | Cross/Models/VisionAttribute.cs | angelobelchior/IntelligentApp | f813151259d5c883002f981fff136991974ba691 | [
"MIT"
] | 7 | 2018-01-15T15:37:58.000Z | 2022-02-24T18:11:56.000Z | Cross/Models/VisionAttribute.cs | angelobelchior/IntelligentApp | f813151259d5c883002f981fff136991974ba691 | [
"MIT"
] | 1 | 2018-01-15T10:59:41.000Z | 2018-01-22T09:01:26.000Z | Cross/Models/VisionAttribute.cs | angelobelchior/IntelligentApp | f813151259d5c883002f981fff136991974ba691 | [
"MIT"
] | 2 | 2018-03-10T13:13:57.000Z | 2018-07-03T14:00:53.000Z | namespace IntelligentApp.Models
{
public class VisionAttribute
{
public string ElementeName { get; set; }
public string Text { get; set; }
public string Detail { get; set; }
public VisionAttribute() { }
public VisionAttribute(string text)
: this(string.Empty, text)
{
}
public VisionAttribute(string elementName, string text)
{
this.ElementeName = elementName;
this.Text = text;
}
public VisionAttribute(string elementName, string text, string detail)
: this(elementName, text)
=> this.Detail = detail;
public VisionAttribute(string elementName, string text, float score)
: this(elementName, text)
=> this.Detail = score.ToString("0.##");
public VisionAttribute(string elementName, string text, double score)
: this(elementName, text)
=> this.Detail = score.ToString("0.##");
}
}
| 28.138889 | 78 | 0.579467 |
bd1f17e4dade55542d7b9b3d7780a06dcf46398e | 553 | lua | Lua | lua/apprentice/plugins/netrw.lua | adisen99/couleur-nvim | 92d1e12bd98ff601328ae748534e7fd46017d900 | [
"MIT"
] | 15 | 2021-09-09T08:57:24.000Z | 2022-03-29T07:00:35.000Z | lua/apprentice/plugins/netrw.lua | adisen99/couleur-nvim | 92d1e12bd98ff601328ae748534e7fd46017d900 | [
"MIT"
] | null | null | null | lua/apprentice/plugins/netrw.lua | adisen99/couleur-nvim | 92d1e12bd98ff601328ae748534e7fd46017d900 | [
"MIT"
] | 2 | 2021-12-27T20:37:05.000Z | 2022-03-04T00:08:33.000Z | -- netrw highlights
local lush = require("lush")
local base = require("apprentice.base")
local M = {}
M = lush(function()
return {
-- netrw
netrwDir {base.ApprenticeAqua},
netrwClassify {base.ApprenticeAqua},
netrwLink {base.ApprenticeGray},
netrwSymLink {base.ApprenticeFg1},
netrwExe {base.ApprenticeYellow},
netrwComment {base.ApprenticeGray},
netrwList {base.ApprenticeBlue},
netrwHelpCmd {base.ApprenticeAqua},
netrwCmdSep {base.ApprenticeFg3},
netrwVersion {base.ApprenticeGreen},
}
end)
return M
| 23.041667 | 40 | 0.708861 |
5f9a4a57b858c8db69f8c9afe38e43f6603af2aa | 1,450 | h | C | core/vice-3.3/src/arch/gtk3/joy-win32.h | paulscottrobson/cxp-computer | b43f47d5e8232d3229c6522c9a02d53c1edd3a4d | [
"MIT"
] | 1 | 2020-02-03T16:46:40.000Z | 2020-02-03T16:46:40.000Z | third_party/vice-3.3/src/arch/gtk3/joy-win32.h | xlar54/bmc64 | c73f91babaf9e9f75b5073c773bb50e8a8e43505 | [
"Apache-2.0"
] | 4 | 2019-06-18T14:45:35.000Z | 2019-06-22T17:18:22.000Z | third_party/vice-3.3/src/arch/gtk3/joy-win32.h | xlar54/bmc64 | c73f91babaf9e9f75b5073c773bb50e8a8e43505 | [
"Apache-2.0"
] | 1 | 2021-05-14T11:13:44.000Z | 2021-05-14T11:13:44.000Z | /** \file joy-win32.h
* \brief Joystick support for Windows - header
*
* \author Ettore Perazzoli <ettore@comm2000.it>
*/
/*
* This file is part of VICE, the Versatile Commodore Emulator.
* See README for copyright notice.
*
* 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.
*
*/
#ifndef VICE_JOY_WIN32_H
#define VICE_JOY_WIN32_H
typedef int joystick_device_t;
/* standard devices */
#define JOYDEV_NONE 0
#define JOYDEV_NUMPAD 1
#define JOYDEV_KEYSET1 2
#define JOYDEV_KEYSET2 3
/* extra devices */
#define JOYDEV_HW1 4
#define JOYDEV_HW2 5
int joystick_close(void);
void joystick_update(void);
int joystick_uses_direct_input(void);
void joystick_ui_reset_device_list(void);
const char *joystick_ui_get_next_device_name(int *id);
#endif
| 28.431373 | 72 | 0.742759 |
1eff9f8528b7e9768cdb3ed3d44bf7c0cc5276cb | 666 | swift | Swift | Tests/MongoKittenTests/MobileTests.swift | coaoac/MongoKitten | 7cb8c355a8ddc6f93d95bfcb6e4ae650338f9e38 | [
"MIT"
] | null | null | null | Tests/MongoKittenTests/MobileTests.swift | coaoac/MongoKitten | 7cb8c355a8ddc6f93d95bfcb6e4ae650338f9e38 | [
"MIT"
] | null | null | null | Tests/MongoKittenTests/MobileTests.swift | coaoac/MongoKitten | 7cb8c355a8ddc6f93d95bfcb6e4ae650338f9e38 | [
"MIT"
] | null | null | null | import MongoKitten
import NIO
import XCTest
let loop = MultiThreadedEventLoopGroup(numberOfThreads: 1)
class CRUDTests : XCTestCase {
let settings = try! ConnectionSettings("mongodb://localhost:27017")
var db: MongoCluster!
override func setUp() {
db = try! MongoCluster.connect(on: loop, settings: settings).wait()
}
func testListDatabases() throws {
let databases = try db.listDatabases().wait()
XCTAssertTrue(databases.contains { $0.name == "admin" })
for db in databases {
XCTAssertNoThrow(try db.listCollections().wait())
}
}
func testInsert() {
}
}
| 23.785714 | 75 | 0.630631 |
70ac24c029942c09ce746dc963abbfd0da64a252 | 4,461 | cs | C# | src/Stunts/Stunts.Sdk/Processors/VisualBasicStunt.cs | akrisiun/winforms | 4ab9923a1e5ffb213295b099fb87d3f5b7e2d4af | [
"MIT"
] | 1 | 2020-06-16T22:26:37.000Z | 2020-06-16T22:26:37.000Z | src/Stunts/Stunts.Sdk/Processors/VisualBasicStunt.cs | akrisiun/winforms | 4ab9923a1e5ffb213295b099fb87d3f5b7e2d4af | [
"MIT"
] | null | null | null | src/Stunts/Stunts.Sdk/Processors/VisualBasicStunt.cs | akrisiun/winforms | 4ab9923a1e5ffb213295b099fb87d3f5b7e2d4af | [
"MIT"
] | null | null | null | using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.CodeAnalysis.VisualBasic.Syntax;
using static Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory;
namespace Stunts.Processors
{
/// <summary>
/// Adds the <see cref="IStunt"/> interface implementation.
/// </summary>
public class VisualBasicStunt : IDocumentProcessor
{
/// <summary>
/// Applies to <see cref="LanguageNames.VisualBasic"/> only.
/// </summary>
public string[] Languages { get; } = new[] { LanguageNames.VisualBasic };
/// <summary>
/// Runs in the final phase of codegen, <see cref="ProcessorPhase.Fixup"/>.
/// </summary>
public ProcessorPhase Phase => ProcessorPhase.Fixup;
/// <summary>
/// Adds the <see cref="IStunt"/> interface implementation to the document.
/// </summary>
public async Task<Document> ProcessAsync(Document document, CancellationToken cancellationToken = default)
{
var syntax = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
syntax = new VisualBasicStuntVisitor(SyntaxGenerator.GetGenerator(document)).Visit(syntax);
return document.WithSyntaxRoot(syntax);
}
class VisualBasicStuntVisitor : VisualBasicSyntaxRewriter
{
SyntaxGenerator generator;
public VisualBasicStuntVisitor(SyntaxGenerator generator) => this.generator = generator;
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
if (!node.Options.Any(opt => !opt.ChildTokens().Any(t => t.Kind() == SyntaxKind.StrictKeyword)))
node = node.AddOptions(OptionStatement(Token(SyntaxKind.StrictKeyword), Token(SyntaxKind.OnKeyword)));
return base.VisitCompilationUnit(node);
}
public override SyntaxNode VisitClassBlock(ClassBlockSyntax node)
{
var result = base.VisitClassBlock(node);
if (!generator.GetBaseAndInterfaceTypes(result).Any(x =>
x.ToString() == nameof(IStunt) ||
x.ToString() == typeof(IStunt).FullName))
{
// Only add the base type if it isn't already there
result = generator.AddInterfaceType(
result,
generator.IdentifierName(nameof(IStunt)));
}
if (!generator.GetMembers(result).Any(x => generator.GetName(x) == nameof(IStunt.Behaviors)))
{
var property = (PropertyBlockSyntax)generator.PropertyDeclaration(
nameof(IStunt.Behaviors),
GenericName("ObservableCollection", TypeArgumentList(IdentifierName(nameof(IStuntBehavior)))),
modifiers: DeclarationModifiers.ReadOnly,
getAccessorStatements: new[]
{
generator.ReturnStatement(
generator.MemberAccessExpression(
IdentifierName("pipeline"),
nameof(BehaviorPipeline.Behaviors)))
});
property = property.WithPropertyStatement(
property.PropertyStatement.WithImplementsClause(
ImplementsClause(QualifiedName(IdentifierName(nameof(IStunt)), IdentifierName(nameof(IStunt.Behaviors))))));
result = generator.InsertMembers(result, 0, property);
}
if (!generator.GetMembers(result).Any(x => generator.GetName(x) == "pipeline"))
{
var field = generator.FieldDeclaration(
"pipeline",
generator.IdentifierName(nameof(BehaviorPipeline)),
modifiers: DeclarationModifiers.ReadOnly,
initializer: generator.ObjectCreationExpression(generator.IdentifierName(nameof(BehaviorPipeline))));
result = generator.InsertMembers(result, 0, field);
}
return result;
}
}
}
} | 43.31068 | 136 | 0.579915 |
906801dff67423d7bd800399f03f7aa9ea123aab | 1,566 | py | Python | pypomo.py | wandbrandon/pypom | 2433cb3905e9aae10dedb16850c99219f729f09e | [
"MIT"
] | null | null | null | pypomo.py | wandbrandon/pypom | 2433cb3905e9aae10dedb16850c99219f729f09e | [
"MIT"
] | null | null | null | pypomo.py | wandbrandon/pypom | 2433cb3905e9aae10dedb16850c99219f729f09e | [
"MIT"
] | null | null | null | import click
import time
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
Notify.init("Pypom")
#countdown code
def countdown(t):
t = t*60
while t:
mins, secs = divmod(t, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
t -= 1
#click methodology
@click.command()
@click.option('-wt', default=25, help='Work time in minutes')
@click.option('-rt', default=5, help='Rest time in minutes')
@click.option('-lrt', default=15, help='Long rest time in minutes')
@click.option('-c', default=1, help='Cycle amount')
def timer(wt, rt, lrt, c):
noti = Notify.Notification.new("")
noti.set_urgency(0)
ctemp = c
while c:
noti.update("cycle start")
noti.show()
countdown(wt)
noti.update("break")
noti.show()
countdown(rt)
noti.update("work")
noti.show()
countdown(wt)
noti.update("break")
noti.show()
countdown(rt)
noti.update("work")
noti.show()
countdown(wt)
noti.update("long break")
noti.show()
countdown(lrt)
noti.update("cycle complete")
noti.show()
c = c - 1
sum = wt+wt+wt+rt+rt+lrt
total = sum*ctemp
if ctemp == 1:
print("finished {0} cycle for a total of {1} minutes".format(ctemp,total))
else:
print("finished {0} cycles for a total of {1} minutes".format(ctemp,total))
if __name__ == '__main__':
timer()
Notify.uninit()
| 26.1 | 83 | 0.579183 |
99702e2d632a41b82e0af42e6b5ec845ccfd5b5a | 348 | h | C | JoJoEngine/WinHierarchy.h | joeyGumer/JoJoEngine | 15289b1f87e5c79a51ff04a703977abf9dd84886 | [
"MIT"
] | null | null | null | JoJoEngine/WinHierarchy.h | joeyGumer/JoJoEngine | 15289b1f87e5c79a51ff04a703977abf9dd84886 | [
"MIT"
] | null | null | null | JoJoEngine/WinHierarchy.h | joeyGumer/JoJoEngine | 15289b1f87e5c79a51ff04a703977abf9dd84886 | [
"MIT"
] | null | null | null | #ifndef _WINHIERARCHY_H_
#define _WINHIERARCHY_H_
#include "EditorWindow.h"
#include "Globals.h"
class GameObject;
class WinHierarchy : public EditorWindow
{
public:
WinHierarchy();
~WinHierarchy();
void Start();
void Update();
void CleanUp();
private:
void ShowGO(GameObject* go);
private:
uint go_id = 0;
char label[100];
};
#endif | 12.888889 | 40 | 0.724138 |
771249a95f14e7854abdd2f213b8cfd335ad78dc | 546 | sql | SQL | sample/sample-greatest-and-least.sql | nminoru/pg_plan_tree_dot | 13eff984a59ccfeb332685e870195885db02a8e3 | [
"BSD-3-Clause"
] | 9 | 2016-09-14T06:49:50.000Z | 2021-12-17T08:41:56.000Z | sample/sample-greatest-and-least.sql | nminoru/pg_plan_tree_dot | 13eff984a59ccfeb332685e870195885db02a8e3 | [
"BSD-3-Clause"
] | 2 | 2016-09-14T07:03:30.000Z | 2017-06-03T11:00:02.000Z | sample/sample-greatest-and-least.sql | nminoru/pg_plan_tree_dot | 13eff984a59ccfeb332685e870195885db02a8e3 | [
"BSD-3-Clause"
] | 3 | 2017-08-02T23:41:04.000Z | 2021-12-17T08:58:04.000Z | CREATE EXTENSION IF NOT EXISTS pg_plan_tree_dot;
DROP TABLE IF EXISTS test;
CREATE TABLE test (id1 INTEGER, id2 INTEGER, id3 INTEGER, id4 INTEGER, id5 INTEGER);
INSERT INTO test VALUES (10, 20, 30, 40, 50);
-- SELECT greatest(id1, id2, id3, id4, id5) FROM test;
-- SELECT least(id1, id2, id3, id4, id5) FROM test;
SELECT generate_plan_tree_dot('SELECT greatest(id1, id2, id3, id4, id5) FROM test', 'sample-greatest.dot');
SELECT generate_plan_tree_dot('SELECT least(id1, id2, id3, id4, id5) FROM test', 'sample-least.dot');
DROP TABLE test;
| 36.4 | 107 | 0.732601 |
c53f52dcdc44f6b883bcd58de37f434619707dc4 | 353 | lua | Lua | MMOCoreORB/bin/scripts/object/tangible/loot/loot_schematic/gen_medium_window_s01_house_loot_schem.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/bin/scripts/object/tangible/loot/loot_schematic/gen_medium_window_s01_house_loot_schem.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/bin/scripts/object/tangible/loot/loot_schematic/gen_medium_window_s01_house_loot_schem.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | object_tangible_loot_loot_schematic_gen_medium_window_s01_house_loot_schem = object_tangible_loot_loot_schematic_shared_gen_medium_window_s01_house_loot_schem:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_loot_schematic_gen_medium_window_s01_house_loot_schem, "object/tangible/loot/loot_schematic/gen_medium_window_s01_house_loot_schem.iff")
| 88.25 | 185 | 0.937677 |
bbd06fc1f705dc18d57a55f56ae7427633334603 | 823 | lua | Lua | crafting/currency.lua | AntumMT/mod-antum_overrides | 1ca8f05316e78afe76cda51e50b93e3ff9d4f683 | [
"MIT"
] | null | null | null | crafting/currency.lua | AntumMT/mod-antum_overrides | 1ca8f05316e78afe76cda51e50b93e3ff9d4f683 | [
"MIT"
] | null | null | null | crafting/currency.lua | AntumMT/mod-antum_overrides | 1ca8f05316e78afe76cda51e50b93e3ff9d4f683 | [
"MIT"
] | null | null | null | --[[ LICENSE HEADER
MIT Licensing
Copyright © 2017 Jordan Irwin (AntumDeluge)
See: LICENSE.txt
]]
if antum.dependsSatisfied({'default', 'currency'}) then
core.register_craft({
output = 'default:paper',
recipe = {
{'currency:minegeld', 'currency:minegeld'},
{'currency:minegeld', 'currency:minegeld'},
},
})
core.register_craft({
output = 'default:paper',
recipe = {
{'currency:minegeld_5', 'currency:minegeld_5'},
{'currency:minegeld_5', 'currency:minegeld_5'},
},
})
core.register_craft({
output = 'default:paper',
recipe = {
{'currency:minegeld_10', 'currency:minegeld_10'},
{'currency:minegeld_10', 'currency:minegeld_10'},
},
})
core.register_craft({
output = 'default:paper 10',
type = 'shapeless',
recipe = {'currency:minegeld_bundle'},
})
end
| 19.595238 | 55 | 0.651276 |
abf1762941581c927a797950aa419ff4c08d0476 | 106 | cpp | C++ | exercise06/6.13.cpp | Yang-33/OpenDataStructuresSolution | 32bebde04ac8a33b81f715705559f9d934830d1b | [
"MIT"
] | 3 | 2019-10-06T08:39:07.000Z | 2020-03-25T15:42:08.000Z | exercise06/6.13.cpp | Yang-33/OpenDataStructuresSolution | 32bebde04ac8a33b81f715705559f9d934830d1b | [
"MIT"
] | null | null | null | exercise06/6.13.cpp | Yang-33/OpenDataStructuresSolution | 32bebde04ac8a33b81f715705559f9d934830d1b | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
// 4
// / \
// / \
// 1 6
int main() {
}
| 8.153846 | 23 | 0.40566 |
0517f400fa9a449b81d2ef1daff71cb81d951f49 | 190 | rb | Ruby | db/migrate/20150210144621_add_step_definitions_to_builds.rb | Byclosure/webcat-project | 46059310383b5a4cb6ed548a6302eaf9b57f6c41 | [
"MIT-0"
] | 4 | 2015-03-26T20:40:30.000Z | 2019-02-09T00:58:12.000Z | db/migrate/20150210144621_add_step_definitions_to_builds.rb | Byclosure/webcat-project | 46059310383b5a4cb6ed548a6302eaf9b57f6c41 | [
"MIT-0"
] | null | null | null | db/migrate/20150210144621_add_step_definitions_to_builds.rb | Byclosure/webcat-project | 46059310383b5a4cb6ed548a6302eaf9b57f6c41 | [
"MIT-0"
] | 2 | 2015-03-19T16:48:38.000Z | 2020-11-04T05:54:29.000Z | class AddStepDefinitionsToBuilds < ActiveRecord::Migration
def up
add_column :builds, :step_definitions, :text
end
def down
remove_column :builds, :step_definitions
end
end
| 19 | 58 | 0.757895 |
91cebaa26e03f4cf106654ae46350a094a356391 | 432 | dart | Dart | query/lib/query/block/insert_fields_from_query_block.dart | viplmad/game_collection | 34649c36b27d7e6269cb022b27dd27b2638ebfdf | [
"MIT"
] | null | null | null | query/lib/query/block/insert_fields_from_query_block.dart | viplmad/game_collection | 34649c36b27d7e6269cb022b27dd27b2638ebfdf | [
"MIT"
] | null | null | null | query/lib/query/block/insert_fields_from_query_block.dart | viplmad/game_collection | 34649c36b27d7e6269cb022b27dd27b2638ebfdf | [
"MIT"
] | null | null | null | import '../query.dart' show Query;
import 'block.dart' show Block;
/// (INSERT INTO) ... setField ... (SELECT ... FROM ...)
class InsertFieldsFromQueryBlock extends Block {
InsertFieldsFromQueryBlock() :
this.fields = <String>[],
super();
List<String> fields;
Query? query;
void setFromQuery(Iterable<String> fields, Query query) {
this.fields = fields.toList(growable: false);
this.query = query;
}
}
| 22.736842 | 59 | 0.664352 |
11cc7105b2bbd57098c0ed45e2b6b71a137f696d | 17,709 | html | HTML | coverage/2021-01-31/feel-evaluator/src/bifs/named.rs.func.html | dmntk/dmntk.measure | dfcffd3018b7c3d74bc15f985ce528c6b8fd2f4a | [
"Apache-2.0",
"MIT"
] | 1 | 2022-01-27T14:49:05.000Z | 2022-01-27T14:49:05.000Z | coverage/2021-01-31/feel-evaluator/src/bifs/named.rs.func.html | dmntk/dmntk.measure | dfcffd3018b7c3d74bc15f985ce528c6b8fd2f4a | [
"Apache-2.0",
"MIT"
] | null | null | null | coverage/2021-01-31/feel-evaluator/src/bifs/named.rs.func.html | dmntk/dmntk.measure | dfcffd3018b7c3d74bc15f985ce528c6b8fd2f4a | [
"Apache-2.0",
"MIT"
] | null | null | null | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LCOV - Decision Model and Notation Toolkit - feel-evaluator/src/bifs/named.rs - functions</title>
<link rel="stylesheet" type="text/css" href="../../../gcov.css">
</head>
<body>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="title">LCOV - code coverage report</td></tr>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
<tr>
<td width="100%">
<table cellpadding=1 border=0 width="100%">
<tr>
<td width="10%" class="headerItem">Current view:</td>
<td width="35%" class="headerValue"><a href="../../../index.html">top level</a> - <a href="index.html">feel-evaluator/src/bifs</a> - named.rs<span style="font-size: 80%;"> (<a href="named.rs.gcov.html">source</a> / functions)</span></td>
<td width="5%"></td>
<td width="15%"></td>
<td width="10%" class="headerCovTableHead">Hit</td>
<td width="10%" class="headerCovTableHead">Total</td>
<td width="15%" class="headerCovTableHead">Coverage</td>
</tr>
<tr>
<td class="headerItem">Test:</td>
<td class="headerValue">Decision Model and Notation Toolkit</td>
<td></td>
<td class="headerItem">Lines:</td>
<td class="headerCovTableEntry">422</td>
<td class="headerCovTableEntry">486</td>
<td class="headerCovTableEntryMed">86.8 %</td>
</tr>
<tr>
<td class="headerItem">Date:</td>
<td class="headerValue">2022-01-31 09:31:12</td>
<td></td>
<td class="headerItem">Functions:</td>
<td class="headerCovTableEntry">59</td>
<td class="headerCovTableEntry">75</td>
<td class="headerCovTableEntryMed">78.7 %</td>
</tr>
<tr><td><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
</td>
</tr>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
<center>
<table width="60%" cellpadding=1 cellspacing=1 border=0>
<tr><td><br></td></tr>
<tr>
<td width="80%" class="tableHead">Function Name <span class="tableHeadSort"><img src="../../../glass.png" width=10 height=14 alt="Sort by function name" title="Sort by function name" border=0></span></td>
<td width="20%" class="tableHead">Hit count <span class="tableHeadSort"><a href="named.rs.func-sort-c.html"><img src="../../../updown.png" width=10 height=14 alt="Sort by hit count" title="Sort by hit count" border=0></a></span></td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#167">dmntk_feel_evaluator::bifs::named::bif_abs</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#175">dmntk_feel_evaluator::bifs::named::bif_after</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#187">dmntk_feel_evaluator::bifs::named::bif_all</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#195">dmntk_feel_evaluator::bifs::named::bif_any</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#204">dmntk_feel_evaluator::bifs::named::bif_append</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#208">dmntk_feel_evaluator::bifs::named::bif_before</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#220">dmntk_feel_evaluator::bifs::named::bif_ceiling</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#229">dmntk_feel_evaluator::bifs::named::bif_coincides</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#240">dmntk_feel_evaluator::bifs::named::bif_concatenate</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#244">dmntk_feel_evaluator::bifs::named::bif_contains</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#256">dmntk_feel_evaluator::bifs::named::bif_count</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#264">dmntk_feel_evaluator::bifs::named::bif_date</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#278">dmntk_feel_evaluator::bifs::named::bif_date_and_time</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#290">dmntk_feel_evaluator::bifs::named::bif_day_of_week</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#294">dmntk_feel_evaluator::bifs::named::bif_day_of_year</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#298">dmntk_feel_evaluator::bifs::named::bif_decimal</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#310">dmntk_feel_evaluator::bifs::named::bif_distinct_values</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#318">dmntk_feel_evaluator::bifs::named::bif_duration</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#326">dmntk_feel_evaluator::bifs::named::bif_during</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#330">dmntk_feel_evaluator::bifs::named::bif_ends_with</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#342">dmntk_feel_evaluator::bifs::named::bif_even</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#350">dmntk_feel_evaluator::bifs::named::bif_exp</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#358">dmntk_feel_evaluator::bifs::named::bif_finished_by</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#362">dmntk_feel_evaluator::bifs::named::bif_finishes</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#366">dmntk_feel_evaluator::bifs::named::bif_flatten</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#374">dmntk_feel_evaluator::bifs::named::bif_floor</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#382">dmntk_feel_evaluator::bifs::named::bif_get_entries</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#390">dmntk_feel_evaluator::bifs::named::bif_get_value</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#402">dmntk_feel_evaluator::bifs::named::bif_includes</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#406">dmntk_feel_evaluator::bifs::named::bif_index_of</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#418">dmntk_feel_evaluator::bifs::named::bif_insert_before</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#434">dmntk_feel_evaluator::bifs::named::bif_is</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#438">dmntk_feel_evaluator::bifs::named::bif_list_contains</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#450">dmntk_feel_evaluator::bifs::named::bif_log</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#458">dmntk_feel_evaluator::bifs::named::bif_lower_case</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#466">dmntk_feel_evaluator::bifs::named::bif_matches</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#482">dmntk_feel_evaluator::bifs::named::bif_max</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#490">dmntk_feel_evaluator::bifs::named::bif_mean</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#502">dmntk_feel_evaluator::bifs::named::bif_median</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#498">dmntk_feel_evaluator::bifs::named::bif_meets</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#510">dmntk_feel_evaluator::bifs::named::bif_met_by</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#514">dmntk_feel_evaluator::bifs::named::bif_min</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#538">dmntk_feel_evaluator::bifs::named::bif_mode</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#522">dmntk_feel_evaluator::bifs::named::bif_modulo</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#534">dmntk_feel_evaluator::bifs::named::bif_month_of_year</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#546">dmntk_feel_evaluator::bifs::named::bif_not</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#554">dmntk_feel_evaluator::bifs::named::bif_number</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#570">dmntk_feel_evaluator::bifs::named::bif_odd</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#578">dmntk_feel_evaluator::bifs::named::bif_overlaps_after</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#582">dmntk_feel_evaluator::bifs::named::bif_overlaps_before</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#586">dmntk_feel_evaluator::bifs::named::bif_product</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#590">dmntk_feel_evaluator::bifs::named::bif_remove</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#602">dmntk_feel_evaluator::bifs::named::bif_replace</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#623">dmntk_feel_evaluator::bifs::named::bif_reverse</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#632">dmntk_feel_evaluator::bifs::named::bif_sort</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#645">dmntk_feel_evaluator::bifs::named::bif_split</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#657">dmntk_feel_evaluator::bifs::named::bif_sqrt</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#665">dmntk_feel_evaluator::bifs::named::bif_started_by</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#669">dmntk_feel_evaluator::bifs::named::bif_starts</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#673">dmntk_feel_evaluator::bifs::named::bif_starts_with</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#685">dmntk_feel_evaluator::bifs::named::bif_stddev</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#693">dmntk_feel_evaluator::bifs::named::bif_string</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#701">dmntk_feel_evaluator::bifs::named::bif_string_length</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#709">dmntk_feel_evaluator::bifs::named::bif_sublist</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#725">dmntk_feel_evaluator::bifs::named::bif_substring</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#741">dmntk_feel_evaluator::bifs::named::bif_substring_after</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#753">dmntk_feel_evaluator::bifs::named::bif_substring_before</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#765">dmntk_feel_evaluator::bifs::named::bif_sum</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#773">dmntk_feel_evaluator::bifs::named::bif_time</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#791">dmntk_feel_evaluator::bifs::named::bif_union</a></td>
<td class="coverFnHi">1</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#795">dmntk_feel_evaluator::bifs::named::bif_upper_case</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#803">dmntk_feel_evaluator::bifs::named::bif_week_of_year</a></td>
<td class="coverFnLo">0</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#807">dmntk_feel_evaluator::bifs::named::bif_years_and_months_duration</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#89">dmntk_feel_evaluator::bifs::named::evaluate_bif</a></td>
<td class="coverFnHi">2</td>
</tr>
<tr>
<td class="coverFn"><a href="named.rs.gcov.html#821">dmntk_feel_evaluator::bifs::named::get_param</a></td>
<td class="coverFnHi">2</td>
</tr>
</table>
<br>
</center>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
<tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php" target="_parent">LCOV version 1.14</a></td></tr>
</table>
<br>
</body>
</html>
| 47.477212 | 249 | 0.541702 |
fb928ee4fbb4cc907dfb1c3f46ab90356057a46a | 5,255 | java | Java | flash/src/flash/display/DisplayObjectContainer.java | dyorgio/playn | 1c17d5549f8c3829acf12388f683d6a5b205b600 | [
"Apache-2.0"
] | null | null | null | flash/src/flash/display/DisplayObjectContainer.java | dyorgio/playn | 1c17d5549f8c3829acf12388f683d6a5b205b600 | [
"Apache-2.0"
] | null | null | null | flash/src/flash/display/DisplayObjectContainer.java | dyorgio/playn | 1c17d5549f8c3829acf12388f683d6a5b205b600 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package flash.display;
import com.google.gwt.core.client.JsArray;
import flash.geom.Point;
/**
* Implementation of <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObjectContainer.html">
* flash.display.DisplayObjectContainer</a>
*/
public class DisplayObjectContainer extends InteractiveObject {
protected DisplayObjectContainer() {}
/**
* Determines whether or not the children of the object are mouse enabled.
* @return
*/
final public native boolean isMouseChildren() /*-{
return this.mouseChildren;
}-*/;
final public native void setMouseChildren(boolean enabled) /*-{
this.mouseChildren = enabled;;
}-*/;
final public native void setTabChildren(boolean enabled) /*-{
this.tabChildren = enabled;
}-*/;
/**
* Returns the number of children of this object.
* @return
*/
final public native int getNumChildren() /*-{
return this.numChildren;
}-*/;
/**
* Determines whether the children of the object are tab enabled.
* @return
*/
final public native boolean isTabChildren() /*-{
return this.tabChildren;
}-*/;
/**
* Adds a child DisplayObject instance to this DisplayObjectContainer instance.
*/
final public native DisplayObject addChild(DisplayObject child) /*-{
return this.addChild(child);
}-*/;
/**
* Adds a child DisplayObject instance to this DisplayObjectContainer instance.
*/
final public native DisplayObject addChildAt(DisplayObject child, int index) /*-{
return this.addChildAt(child, index);
}-*/;
/**
* Indicates whether the security restrictions would cause any display objects
* to be omitted from the list returned by calling the
* DisplayObjectContainer.getObjectsUnderPoint() method with the specified
* point point.
* @param point
* @return
*/
final public native boolean areInaccessibleObjectsUnderPoint(Point point) /*-{
return this.areInaccessibleObjectsUnderPoint(point);
}-*/;
/**
* Determines whether the specified display object is a child of the
* DisplayObjectContainer instance or the instance itself.
* @param child
* @return
*/
final public native boolean contains(DisplayObject child) /*-{
return this.contains(child);
}-*/;
/**
* Returns the child display object instance that exists at the specified index.
* @param index
* @return
*/
final public native DisplayObject getChildAt(int index) /*-{
return this.getChildAt(index);
}-*/;
/**
* Returns the child display object that exists with the specified name.
* @param name
* @return
*/
final public native DisplayObject getChildByName(String name) /*-{
return this.getChildByName(name);
}-*/;
/**
* Returns the index position of a child DisplayObject instance.
* @param child
* @return
*/
final public native int getChildIndex(DisplayObject child) /*-{
return this.getChildIndex(child);
}-*/;
/**
* Returns an array of objects that lie under the specified point and are
* children (or grandchildren, and so on) of this DisplayObjectContainer instance.
* @param point
* @return
*/
final public native JsArray<DisplayObject> getObjectsUnderPoint(Point point) /*-{
return this.getObjectsUnderPoint(point);
}-*/;
/**
* Removes the specified child DisplayObject instance from the child list of the DisplayObjectContainer instance.
* @param child
* @return
*/
final public native DisplayObject removeChild(DisplayObject child) /*-{
return this.removeChild(child);
}-*/;
/**
* Removes a child DisplayObject from the specified index position in the
* child list of the DisplayObjectContainer.
* @param index
* @return
*/
final public native DisplayObject removeChildAt(int index) /*-{
return this.removeChildAt(index);
}-*/;
/**
* Changes the position of an existing child in the display object container.
* @param child
* @param index
*/
final public native void setChildIndex(DisplayObject child, int index) /*-{
this.setChildIndex(child, index);
}-*/;
/**
* Swaps the z-order (front-to-back order) of the two specified child objects.
*/
final public native void swapChildren(DisplayObject child1, DisplayObject child2) /*-{
this.swapChildren(child1, child2);
}-*/;
/**
* Swaps the z-order (front-to-back order) of the child objects at the two
* specified index positions in the child list.
* @param index1
* @param index2
*/
final public native void swapChildrenAt(int index1, int index2) /*-{
this.swapChildrenAt(child1, child2);
}-*/;
}
| 28.405405 | 131 | 0.695147 |
638c6b907480610e359081c2695eadcea94b2047 | 751 | lua | Lua | make.lua | ArcanoxDragon/lua-language-server | 0805d50df822422bcee2b5bf6bfe9067f1a9063a | [
"MIT"
] | null | null | null | make.lua | ArcanoxDragon/lua-language-server | 0805d50df822422bcee2b5bf6bfe9067f1a9063a | [
"MIT"
] | null | null | null | make.lua | ArcanoxDragon/lua-language-server | 0805d50df822422bcee2b5bf6bfe9067f1a9063a | [
"MIT"
] | null | null | null | local lm = require 'luamake'
lm.EXE = "lua"
lm.EXE_RESOURCE = "../../make/lua-language-server.rc"
lm:import "3rd/bee.lua/make.lua"
lm:lua_dll 'lpeglabel' {
rootdir = '3rd',
sources = 'lpeglabel/*.c',
visibility = 'default',
defines = {
'MAXRECLEVEL=1000',
},
}
lm:build 'install' {
'$luamake', 'lua', 'make/install.lua', lm.builddir,
deps = {
'lua',
'lpeglabel',
'bee',
}
}
local fs = require 'bee.filesystem'
local pf = require 'bee.platform'
local exe = pf.OS == 'Windows' and ".exe" or ""
lm:build 'unittest' {
fs.path 'bin' / pf.OS / ('lua-language-server' .. exe), 'test.lua', '-E',
pool = "console",
deps = {
'install',
}
}
lm:default 'unittest'
| 20.297297 | 77 | 0.552597 |
3bb8ea773ea5290ddb1021e4503b2e9946aff491 | 810 | html | HTML | src/app/layout/color-stack/color-stack.component.html | shuizhongxiong/colorbox | a1a6054be9f6ca1a85ccb180b965a7da81db1943 | [
"MIT"
] | 5 | 2019-08-27T18:00:40.000Z | 2021-10-21T13:45:43.000Z | src/app/layout/color-stack/color-stack.component.html | shuizhongxiong/colorbox | a1a6054be9f6ca1a85ccb180b965a7da81db1943 | [
"MIT"
] | null | null | null | src/app/layout/color-stack/color-stack.component.html | shuizhongxiong/colorbox | a1a6054be9f6ca1a85ccb180b965a7da81db1943 | [
"MIT"
] | null | null | null | <div class="app-color-stack">
<div class="stack-header clearfloat">
<p class="float-left header-title">文字测试</p>
<p class="float-right header-subtitle">请注意文字阅读清晰度</p>
</div>
<div class="stack-main">
<div class="stack-block" *ngFor="let data of result"
[style.backgroundColor]="data.hex" clipboard [payload]="data.hex" [isNeedTooltip]="true">
<div class="block-label" [style.color]="data.displayColor">{{data.label}}
</div>
<div class="block-lock">
<i *ngIf="data.lock" nz-icon type="lock" theme="outline"></i>
</div>
<div class="block-black">{{data.contrastBlack}}b</div>
<div class="block-white">{{data.contrastWhite}}w</div>
<div class="block-hex" [style.color]="data.displayColor">{{data.hex}}
</div>
</div>
</div>
</div>
| 38.571429 | 95 | 0.619753 |
bc2d3ae42a53573a95687fe01ab3814cf0f362ff | 1,869 | swift | Swift | LCWaterfallLayout/LCWaterfallLayout/ViewController.swift | Userliuchong/LCwaterfallLayout-swift | 3077fd81b1ea7f8ab138d273d2b6923c9f9648ac | [
"MIT"
] | 16 | 2017-03-14T10:33:46.000Z | 2017-07-03T04:37:21.000Z | LCWaterfallLayout/LCWaterfallLayout/ViewController.swift | Userliuchong/LCwaterfallLayout-swift | 3077fd81b1ea7f8ab138d273d2b6923c9f9648ac | [
"MIT"
] | null | null | null | LCWaterfallLayout/LCWaterfallLayout/ViewController.swift | Userliuchong/LCwaterfallLayout-swift | 3077fd81b1ea7f8ab138d273d2b6923c9f9648ac | [
"MIT"
] | null | null | null | //
// ViewController.swift
// LCWaterfallLayout
//
// Created by 刘崇 on 17/3/13.
// Copyright © 2017年 liuchong. All rights reserved.
//
import UIKit
class ViewController: UIViewController,LCWaterfallLayoutDelegate,UICollectionViewDelegate,UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let lceat = LCWaterfallLayout()
lceat.waterdelegate = self
lceat.setColumnSpacing(columnspacing: 10, rowspacing: 10, sectionInset: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5))
//实现网格
let collection = UICollectionView(frame: self.view.bounds, collectionViewLayout: lceat)
collection.delegate = self
collection.dataSource = self
self.view.addSubview(collection)
//注册单元格
collection.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "MyCell")
}
//
func lcwaterfallLayout(waterfallLayout: LCWaterfallLayout, itemwidth: CGFloat, atindexpath: NSIndexPath) -> CGFloat {
return CGFloat(arc4random_uniform(150))/CGFloat(70) * itemwidth
}
//行数
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 60;
}
//
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let collectionC = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)
collectionC.backgroundColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
return collectionC;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 38.142857 | 131 | 0.7084 |
5bf0d2e77c0ce370b5d55c2465560cfea370bf24 | 22,035 | cs | C# | Excel.Gallery/Gallery.cs | govert/ImageMso | d50208c2d77e3b6dfdcc4f580e2ed12673fa833a | [
"Zlib"
] | 1 | 2021-11-02T05:53:15.000Z | 2021-11-02T05:53:15.000Z | Excel.Gallery/Gallery.cs | govert/ImageMso | d50208c2d77e3b6dfdcc4f580e2ed12673fa833a | [
"Zlib"
] | null | null | null | Excel.Gallery/Gallery.cs | govert/ImageMso | d50208c2d77e3b6dfdcc4f580e2ed12673fa833a | [
"Zlib"
] | 1 | 2021-03-16T10:42:35.000Z | 2021-03-16T10:42:35.000Z | //------------------------------------------------------------------------------
// <copyright file="Gallery.cs" company="Alton X Lam">
// Copyright © 2013 Alton Lam
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
// Alton X Lam
// https://www.facebook.com/AltonXL
// https://www.codeplex.com/site/users/view/AltonXL
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.IconLib;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ExcelDna.Integration;
using ExcelDna.Integration.CustomUI;
namespace ImageMso.Excel
{
///<summary>Image gallery of unqiue ImageMso icons gathered by a composite of multiple sources.</summary>
public partial class Gallery : Form, IExcelAddIn
{
///<summary>ComVisible class for Ribbon call back and event handling methods.</summary>
[ComVisible(true)]
public class Ribbon : ExcelRibbon
{
public void OnLoad(IRibbonUI ribbonUI)
{
}
///<summary>Handles the ribbon control button OnClick Event. Activates the existing gallery or builds a new gallery.</summary>
public void OnAction(IRibbonControl control)
{
if (Gallery.Default == null || Gallery.Default.IsDisposed) (Gallery.Default = new Gallery()).Show();
else Gallery.Default.Activate();
}
}
///<summary>Underlines the hotkey letter for tool strip menu items.</summary>
private class HotkeyMenuStripRenderer : ToolStripProfessionalRenderer
{
public HotkeyMenuStripRenderer() : base() { }
public HotkeyMenuStripRenderer(ProfessionalColorTable table) : base(table) { }
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
e.TextFormat &= ~TextFormatFlags.HidePrefix;
base.OnRenderItemText(e);
}
}
///<summary>Default instance for static referencing.</summary>
public static Gallery Default { get; private set; }
private Images imageMso = Images.Default;
private KeyEventArgs key = null; // Holds the key state between KeyDown and KeyUp events.
private string size = string.Empty; // Holds the image size between GotFocus and LostFocus events.
private string pattern = string.Empty; // Holds the filter pattern between GotFocus and LostFocus events.
/// <summary>Initializes a new instance of the ImageMso.Gallery class.</summary>
public Gallery()
{
InitializeComponent();
GalleryMenu.Renderer = new HotkeyMenuStripRenderer();
if (Default == null) Default = this;
Icons.SmallImageList = new ImageList();
Icons.LargeImageList = new ImageList();
Icons.SmallImageList.ImageSize = new Size(16, 16);
Icons.LargeImageList.ImageSize = new Size(32, 32);
Icons.SmallImageList.ColorDepth = ColorDepth.Depth32Bit;
Icons.LargeImageList.ColorDepth = ColorDepth.Depth32Bit;
var names = new string[imageMso.Names.Count];
imageMso.Names.CopyTo(names, 0);
Icons.BeginUpdate();
var smallImages = Array.ConvertAll(names, name => imageMso[name, 16, 16]).Where(img => img != null).ToArray();
var largeImages = Array.ConvertAll(names, name => imageMso[name, 32, 32]).Where(img => img != null).ToArray();
Icons.SmallImageList.Images.AddRange(smallImages);
Icons.LargeImageList.Images.AddRange(largeImages);
Icons.Items.AddRange(Array.ConvertAll(names, name => new ListViewItem(name, Array.IndexOf(names, name))));
Icons.EndUpdate();
Small.Checked = Icons.View == View.List;
Large.Checked = Icons.View == View.LargeIcon;
using (var image = imageMso["DesignAccentsGallery", 32, 32] ?? imageMso["GroupSmartArtQuickStyles", 32, 32])
if (image != null) Icon = Icon.FromHandle(image.GetHicon());
ViewSize.Image = imageMso["ListView", 16, 16];
Large.Image = imageMso["LargeIcons", 16, 16] ?? imageMso["SmartArtLargerShape", 16, 16];
Small.Image = imageMso["SmallIcons", 16, 16] ?? imageMso["SmartArtSmallerShape", 16, 16];
Filter.Image = imageMso["FiltersMenu", 16, 16];
Clear.Image = imageMso["FilterClearAllFilters", 16, 16];
CopyPicture.Image = imageMso["CopyPicture", 16, 16];
CopyText.Image = imageMso["Copy", 16, 16];
SelectAll.Image = imageMso["SelectAll", 16, 16];
Dimensions.Image = imageMso["PicturePropertiesSize", 16, 16] ?? imageMso["SizeAndPositionWindow", 16, 16];
SaveAs.Image = imageMso["PictureFormatDialog", 16, 16];
Save.Image = imageMso["FileSave", 16, 16];
Bmp.Image = imageMso["SaveAsBmp", 16, 16];
Gif.Image = imageMso["SaveAsGif", 16, 16];
Jpg.Image = imageMso["SaveAsJpg", 16, 16];
Png.Image = imageMso["SaveAsPng", 16, 16];
Tif.Image = imageMso["SaveAsTiff", 16, 16];
Ico.Image = imageMso["InsertImageHtmlTag", 16, 16];
Background.Image = imageMso["FontColorCycle", 16, 16];
ExportAs.Image = imageMso["SlideShowResolutionGallery", 16, 16];
Export.Image = imageMso["ArrangeBySize", 16, 16];
Support.Image = imageMso["Help", 16, 16];
Information.Image = imageMso["Info", 16, 16];
Background.Text = string.Format(Background.Text, Palette.Color.Name);
}
///<summary>Runs when the Excel Add-In is attached. Renders the gallery and brings the form into focus.</summary>
public void AutoOpen()
{
Application.EnableVisualStyles();
this.Show();
this.Activate();
}
///<summary>Runs when the Excel Add-In is detached. Cleans up resources no longer being used.</summary>
public void AutoClose()
{
}
private void Gallery_Disposed(object sender, System.EventArgs e)
{
DestroyIcon(Icon.Handle);
}
private void Gallery_KeyDown(object sender, KeyEventArgs e)
{
key = e;
}
private void Gallery_KeyUp(object sender, KeyEventArgs e)
{
if (key != null && key.Alt)
{
GalleryMenu.Show(RectangleToScreen(Icons.ClientRectangle).Left,
RectangleToScreen(Icons.ClientRectangle).Top);
e.SuppressKeyPress = true;
}
key = e;
}
private void Icons_ItemDrag(object sender, ItemDragEventArgs e)
{ // The MemoryStream containing the image must cycle through the clipboard to Drag & Drop correctly.
// Mysteriously, the direct approach loses the alpha channel (background transparency) or will not drop.
CopyPicture_Click(sender, e);
Icons.DoDragDrop(Clipboard.GetDataObject(), DragDropEffects.All);
}
private void Icons_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
CopyPicture.Enabled = Icons.FocusedItem.Selected;
CopyText.Enabled = Icons.SelectedItems.Count > 0;
Export.Enabled = Icons.SelectedItems.Count > 0;
Save.Enabled = Icons.SelectedItems.Count > 0;
}
private void ViewSize_Check(object sender, EventArgs e)
{
if (sender == Large && Icons.View != View.LargeIcon)
{
Icons.View = View.LargeIcon;
Copy32px.PerformClick();
}
if (sender == Small && Icons.View != View.List)
{
Icons.View = View.List;
Copy16px.PerformClick();
}
Large.Checked = Icons.View == View.LargeIcon;
Small.Checked = Icons.View == View.List;
}
private void SetFilters_GotFocus(object sender, EventArgs e)
{
pattern = SetFilters.Text;
}
private void SetFilters_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter) SetFilters_LostFocus(sender, e);
}
private void SetFilters_LostFocus(object sender, EventArgs e)
{
SetFilters.Text = SetFilters.Text.Trim();
if (!SetFilters.AutoCompleteCustomSource.Contains(SetFilters.Text))
SetFilters.AutoCompleteCustomSource.Add(SetFilters.Text);
if (SetFilters.Text != pattern)
{
pattern = SetFilters.Text;
Clear.Enabled = SetFilters.Text.Length > 0;
Filter.Checked = SetFilters.Text.Length > 0;
// Comma separated array of keyword groups which are in turn space separated arrays of keywords.
var filter = Array.ConvertAll(pattern.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries),
search => search.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
var names = new string[imageMso.Names.Count];
imageMso.Names.CopyTo(names, 0);
Icons.BeginUpdate();
Icons.Items.Clear();
// Find all names where there exists a keyword group in the filter such that the name contains
// all the keywords in the group, convert all names found to listview items and add as a range.
if (filter.Length > 0) Icons.Items.AddRange(Array.ConvertAll(Array.FindAll(names,
name => Array.Exists(filter, group => Array.TrueForAll(group,
keyword => name.ToLowerInvariant().Contains(keyword.ToLowerInvariant().Trim())))),
name => new ListViewItem(name, Array.IndexOf(names, name))));
else Icons.Items.AddRange(Array.ConvertAll(names, name => new ListViewItem(name, Array.IndexOf(names, name))));
if (Icons.Items.Count > 0) Icons.FocusedItem = Icons.Items[0];
Icons.EndUpdate();
}
}
private void Clear_Click(object sender, EventArgs e)
{
if (Filter.Checked)
{
SetFilters.Clear();
SetFilters_LostFocus(sender, e);
}
}
private void CopyPicture_Click(object sender, EventArgs e)
{
short[] dims = Parse(Pixels.Text.ToLowerInvariant().Trim());
using (var image = imageMso[Icons.FocusedItem.Text, dims[0], dims[1]])
// Clipboard.SetImage(image); // Loses alpha channel (background transparency). Convert to MemoryStream instead.
using (var stream = new MemoryStream())
{
image.Save(stream, ImageFormat.Png);
Clipboard.SetData("PNG", stream);
}
}
private void CopyText_Click(object sender, EventArgs e)
{
var items = new ListViewItem[Icons.SelectedItems.Count];
Icons.SelectedItems.CopyTo(items, 0);
string value = string.Join(Environment.NewLine, Array.ConvertAll(items, item => item.Text)).Trim();
if (!string.IsNullOrEmpty(value)) Clipboard.SetText(value);
}
private void SelectAll_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in Icons.Items) item.Selected = true;
}
private void Dimensions_Check(object sender, EventArgs e)
{
Pixels.Text = ((ToolStripMenuItem)sender).Text.Replace("&", string.Empty);
foreach (ToolStripItem item in Dimensions.DropDownItems) if (item is ToolStripMenuItem)
((ToolStripMenuItem)item).Checked = item == sender;
}
private void Pixels_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ToolStripItem item in Dimensions.DropDownItems) if (item is ToolStripMenuItem)
((ToolStripMenuItem)item).Checked = Pixels.Text == ((ToolStripMenuItem)item).Text.Replace("&", string.Empty);
}
private void Pixels_GotFocus(object sender, EventArgs e)
{
size = Pixels.Text;
}
private void Pixels_LostFocus(object sender, EventArgs e)
{
if (Regex.IsMatch(Pixels.Text.ToLowerInvariant().Trim(), @"^\d{2,3}\s*(x)?\s*(\d{2,3})?$"))
{
var dimensions = Parse(Pixels.Text.ToLowerInvariant().Trim());
if (Array.TrueForAll(dimensions, dimension => dimension >= 16 && dimension <= 128) &&
Array.TrueForAll(dimensions, dimension => dimension == dimensions[0]))
if (dimensions.Length == 1) size = dimensions[0] + " x " + dimensions[0];
else if (dimensions.Length == 2) size = dimensions[0] + " x " + dimensions[1];
}
Pixels.Text = size;
Pixels_SelectedIndexChanged(sender, e);
}
private void Pixels_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter) Pixels_LostFocus(sender, e);
}
private void Export_Click(object sender, EventArgs e)
{
if (Icons.SelectedItems.Count > 0 && SaveTo.ShowDialog() == DialogResult.OK)
{ // Collect all checked items from the Export menu and parse into an array of width x length sizes.
var sizes = Array.ConvertAll(Choices(ExportAs.DropDownItems),
item => Parse(item.Text.Replace("&", string.Empty).ToLowerInvariant().Trim()));
foreach (ListViewItem selection in Icons.SelectedItems)
{
SingleIcon icon = (new MultiIcon()).Add(selection.Text);
foreach (var size in sizes) icon.Add(imageMso[selection.Text, size[0], size[1]]);
icon.Save(Path.Combine(SaveTo.SelectedPath, string.Format("{0}.{1}", selection.Text, "ico")));
DestroyIcon(icon.Icon.Handle);
}
MessageBox.Show("Export Complete.", "Export", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void Size_Check(object sender, EventArgs e)
{
((ToolStripMenuItem)sender).Checked ^= true;
}
private void Save_Click(object sender, EventArgs e)
{
if (Icons.SelectedItems.Count > 0 && SaveTo.ShowDialog() == DialogResult.OK)
{ // Collect all checked items from the Save menu and parse into an array of image formats.
var formats = Array.ConvertAll(Choices(SaveAs.DropDownItems), item => Format(item.Name));
var size = Parse(Pixels.Text.ToLowerInvariant().Trim());
foreach (ListViewItem selection in Icons.SelectedItems)
using (var image = imageMso[selection.Text, size[0], size[1]])
using (var canvas = new Bitmap(size[0], size[1]))
using (var drawing = Graphics.FromImage(canvas))
{ // Image is drawn on a colored opaque canvas for formats that do not support transparency.
drawing.Clear(Palette.Color);
drawing.DrawImage(image, 0, 0);
foreach (ImageFormat format in formats)
{
string filename = Path.Combine(SaveTo.SelectedPath,
string.Format("{0}.{1}", selection.Text, Extension(format)));
if (format == ImageFormat.Icon)
{ // image.Save(filename, format); // Loses color depth. Use IconLib instead.
SingleIcon icon = (new MultiIcon()).Add(selection.Text);
icon.Add(image);
icon.Save(filename);
DestroyIcon(icon.Icon.Handle);
}
else if (format == ImageFormat.Bmp || format == ImageFormat.Gif || format == ImageFormat.Jpeg)
canvas.Save(filename, format); // These formats do not support alpha channel transparency.
else image.Save(filename, format);
}
}
MessageBox.Show("Save Complete.", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void Format_Check(object sender, EventArgs e)
{
((ToolStripMenuItem)sender).Checked ^= true;
}
private void Background_Click(object sender, EventArgs e)
{
string text = Background.Text.Replace(Palette.Color.Name, "{0}");
Palette.ShowDialog();
Background.Text = string.Format(text, Palette.Color.Name);
}
private void Support_Click(object sender, EventArgs e)
{
if (MessageBox.Show("This action will launch the web browser and open the support website.", "Help",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) Process.Start(imageMso.Help);
}
private void Information_Click(object sender, EventArgs e)
{
(new About()).ShowDialog();
}
///<summary>Collect all checked items from a <see cref="System.Windows.Forms.ToolStripItemCollection"/>
///and into a <see cref="System.Windows.Forms.ToolStripMenuItem"/> array.</summary>
///<param name="items"><see cref="System.Windows.Forms.ToolStripItemCollection"/></param>
///<returns><see cref="System.Array"/> of <see cref="System.Windows.Forms.ToolStripMenuItem"/></returns>
private static ToolStripItem[] Choices(ToolStripItemCollection items)
{
var choices = new ToolStripItem[items.Count];
items.CopyTo(choices, 0);
return Array.FindAll(choices, item => item is ToolStripMenuItem && ((ToolStripMenuItem)item).Checked);
}
///<summary>Translates the <see cref="System.Drawing.Imaging.ImageFormat"/>
///constant into a 3 or 4 letter image file extension.</summary>
///<param name="format"><see cref="System.Drawing.Imaging.ImageFormat"/> constant.</param>
///<returns>3 or 4 letter <see cref="System.String"/> file extension.</returns>
private string Extension(ImageFormat format)
{
switch (format.ToString())
{
case "Bmp": return "bmp";
case "Emf": return "emf";
case "Gif": return "gif";
case "Icon": return "ico";
case "Jpeg": return "jpg";
case "Exif": return "exif";
case "Png": return "png";
case "Tiff": return "tif";
case "Wmf": return "wmf";
default: return string.Empty;
}
}
///<summary>Translates the 3 or 4 letter image file extension into a
///<see cref="System.Drawing.Imaging.ImageFormat"/> constant.</summary>
///<param name="extension">3 or 4 letter <see cref="System.String"/> file extension.</param>
///<returns><see cref="System.Drawing.Imaging.ImageFormat"/> constant.</returns>
private ImageFormat Format(string extension)
{
switch (extension.ToLowerInvariant())
{
case "bmp": return ImageFormat.Bmp;
case "emf": return ImageFormat.Emf;
case "gif": return ImageFormat.Gif;
case "ico": return ImageFormat.Icon;
case "jpeg": return ImageFormat.Jpeg;
case "jpg": return ImageFormat.Jpeg;
case "exif": return ImageFormat.Exif;
case "png": return ImageFormat.Png;
case "tif": return ImageFormat.Tiff;
case "tiff": return ImageFormat.Tiff;
case "wmf": return ImageFormat.Wmf;
default: return null;
}
}
///<summary>Parses n dimension sizes from a <see cref="System.String"/> in the form
///"D1 x D2 x … x Dn" to a <see cref="System.Array"/> of <see cref="System.Int16" />.</summary>
///<param name="pixels"><see cref="System.String"/> in the form "D1 x D2 x … x Dn".</param>
///<returns><see cref="System.Array"/> of <see cref="System.Int16" /> in the form
///{ D1, D2, … , Dn }</returns>
private short[] Parse(string pixels)
{
return Array.ConvertAll(pixels.Split("x".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries), s => Int16.Parse(s.Trim()));
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private extern static bool DestroyIcon(IntPtr handle);
}
} | 47.489224 | 138 | 0.587474 |
53c9ddff9c41e276495057213da12e392e8d8487 | 4,200 | java | Java | src/fabric/trade-finance/application/buyer/java/src/main/java/org/example/ClientApp.java | fichtip/DLT-LoC | e8013a27f2696d3580ec50bfb4f77ca7ce976db0 | [
"Apache-2.0"
] | null | null | null | src/fabric/trade-finance/application/buyer/java/src/main/java/org/example/ClientApp.java | fichtip/DLT-LoC | e8013a27f2696d3580ec50bfb4f77ca7ce976db0 | [
"Apache-2.0"
] | null | null | null | src/fabric/trade-finance/application/buyer/java/src/main/java/org/example/ClientApp.java | fichtip/DLT-LoC | e8013a27f2696d3580ec50bfb4f77ca7ce976db0 | [
"Apache-2.0"
] | null | null | null | package org.example;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.GatewayException;
import org.hyperledger.fabric.gateway.Network;
import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallets;
public class ClientApp {
private static final String CONTRACT = "CONTRACT_NAME";
private static final String CHANNEL = "CHANNEL_NAME";
public static void main(final String[] args) {
final Gateway.Builder builder = Gateway.createBuilder();
String contractName = "trade-finance";
String channelName = "mychannel";
// get the name of the contract, in case it is overridden
final Map<String, String> envvar = System.getenv();
if (envvar.containsKey(CONTRACT)) {
contractName = envvar.get(CONTRACT);
}
if (envvar.containsKey(CHANNEL)) {
channelName = envvar.get(CHANNEL);
}
try {
// A wallet stores a collection of identities
final Path walletPath = Paths.get(".", "wallet");
final Wallet wallet = Wallets.newFileSystemWallet(walletPath);
System.out.println("Read wallet info from: " + walletPath);
final String userName = "user1";
final Path connectionProfile = Paths.get("..", "..", "..", "..", "test-network", "organizations",
"peerOrganizations", "buyer.example.com", "connection-buyer.yaml");
// Set connection options on the gateway builder
builder.identity(wallet, userName).networkConfig(connectionProfile).discovery(false);
// Connect to gateway using application specified parameters
try (Gateway gateway = builder.connect()) {
// get the network and contract
final Network network = gateway.getNetwork(channelName);
final Contract contract = network.getContract(contractName);
byte[] result;
result = contract.evaluateTransaction("queryAllOrders");
System.out.println("List of all orders:");
System.out.println(new String(result));
System.out.println("------------------------------------");
result = contract.evaluateTransaction("queryAllOrders");
System.out.println("Result of 1st transaction:");
System.out.println(new String(result));
System.out.println("------------------------------------");
contract.submitTransaction("cancelOrder", "1");
System.out.println("Cancelled order 1");
result = contract.evaluateTransaction("queryOrder", "1");
System.out.println(new String(result));
System.out.println("------------------------------------");
contract.submitTransaction("confirmOrder", "2");
System.out.println("Confirmed order 2");
result = contract.evaluateTransaction("queryOrder", "2");
System.out.println(new String(result));
System.out.println("------------------------------------");
System.out.println("Check if delivery date of order 3 has passed");
result = contract.submitTransaction("deliveryDatePassed", "3");
System.out.println(new String(result));
result = contract.evaluateTransaction("queryOrder", "3");
System.out.println(new String(result));
System.out.println("------------------------------------");
System.out.println("Wait until order with id 2 is set to state SHIPPED");
result = contract.evaluateTransaction("queryOrder", "2");
Order order = Order.deserialize(result);
System.out.println(Order.deserialize(result));
while (order.getState() != Order.State.SHIPPED) {
System.out.println("order 2 state is:" + order.getState());
Thread.sleep(5000);
result = contract.evaluateTransaction("queryOrder", "2");
order = Order.deserialize(result);
}
contract.submitTransaction("signArrival", "2");
System.out.println("Signed arrival of order 2");
result = contract.evaluateTransaction("queryOrder", "2");
System.out.println(new String(result));
System.out.println("------------------------------------");
}
} catch (GatewayException | IOException | TimeoutException | InterruptedException e) {
e.printStackTrace();
System.exit(-1);
}
}
}
| 38.181818 | 100 | 0.677619 |
f052b9fc28af42e699049bdfe2b0ac01d467c316 | 187 | py | Python | user_details/give_default.py | Shreyanshsachan/College-Predictor | 87068aa1d1a889ced586ff155bc2b5d9a78340f7 | [
"MIT"
] | null | null | null | user_details/give_default.py | Shreyanshsachan/College-Predictor | 87068aa1d1a889ced586ff155bc2b5d9a78340f7 | [
"MIT"
] | null | null | null | user_details/give_default.py | Shreyanshsachan/College-Predictor | 87068aa1d1a889ced586ff155bc2b5d9a78340f7 | [
"MIT"
] | null | null | null | preference_list_of_user=[]
def give(def_list):
Def=def_list
global preference_list_of_user
preference_list_of_user=Def
return Def
def give_to_model():
return preference_list_of_user | 20.777778 | 31 | 0.84492 |
a17ce30b4bf8c98bfc969e1faaaa844ee1d3f69d | 2,826 | h | C | Applications/Setup/BuddyMesaEnrollmentController.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | 12 | 2019-06-02T02:42:41.000Z | 2021-04-13T07:22:20.000Z | Applications/Setup/BuddyMesaEnrollmentController.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | null | null | null | Applications/Setup/BuddyMesaEnrollmentController.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | 3 | 2019-06-11T02:46:10.000Z | 2019-12-21T14:58:16.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "UIViewController.h"
#import "BFFFlowItem.h"
#import "BiometricKitUIEnrollResultDelegate.h"
@class BiometricKitIdentity, BiometricKitUIEnrollViewController, NSString, UIBarButtonItem;
@interface BuddyMesaEnrollmentController : UIViewController <BFFFlowItem, BiometricKitUIEnrollResultDelegate>
{
UIBarButtonItem *_cancelLeftNavigationItem; // 8 = 0x8
_Bool _enrollComplete; // 16 = 0x10
id <BFFFlowItemDelegate> _delegate; // 24 = 0x18
BiometricKitUIEnrollViewController *_enrollController; // 32 = 0x20
UIBarButtonItem *_previousLeftNavigationItem; // 40 = 0x28
BiometricKitIdentity *_identity; // 48 = 0x30
}
+ (id)cloudConfigSkipKey; // IMP=0x0000000100031950
+ (_Bool)controllerNeedsToRun; // IMP=0x0000000100031740
@property(retain, nonatomic) BiometricKitIdentity *identity; // @synthesize identity=_identity;
@property(retain, nonatomic) UIBarButtonItem *previousLeftNavigationItem; // @synthesize previousLeftNavigationItem=_previousLeftNavigationItem;
@property(retain, nonatomic) BiometricKitUIEnrollViewController *enrollController; // @synthesize enrollController=_enrollController;
@property(nonatomic) __weak id <BFFFlowItemDelegate> delegate; // @synthesize delegate=_delegate;
- (void).cxx_destruct; // IMP=0x0000000100032ba8
- (void)generateAuthToken; // IMP=0x0000000100032a00
- (void)viewDidLayoutSubviews; // IMP=0x0000000100032930
- (struct CGRect)frameForEnrollmentController; // IMP=0x0000000100032854
- (void)enrollResult:(int)arg1 identity:(id)arg2; // IMP=0x000000010003249c
- (void)completeMesaController; // IMP=0x00000001000322f8
- (void)resetLeftNavigationItem; // IMP=0x00000001000321dc
- (id)cancelLeftNavigationItem; // IMP=0x000000010003216c
- (void)deleteIdentity; // IMP=0x00000001000320c8
- (void)restartEnrollment; // IMP=0x0000000100031f78
- (void)endEnrollment; // IMP=0x0000000100031ec0
- (void)beginEnrollment; // IMP=0x0000000100031c08
- (void)viewDidDisappear:(_Bool)arg1; // IMP=0x0000000100031bb8
- (void)viewWillAppear:(_Bool)arg1; // IMP=0x0000000100031b4c
- (void)didResignActive:(id)arg1; // IMP=0x0000000100031b04
- (void)didBecomeActive:(id)arg1; // IMP=0x0000000100031ae4
- (void)controllerWasPopped; // IMP=0x0000000100031a94
- (_Bool)shouldAllowStartOver; // IMP=0x0000000100031a8c
- (_Bool)isEphemeral; // IMP=0x0000000100031a6c
- (_Bool)controllerAllowsNavigatingBack; // IMP=0x0000000100031a54
- (id)init; // IMP=0x0000000100031960
- (void)dealloc; // IMP=0x00000001000316ac
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 46.327869 | 144 | 0.789101 |
a32bdc97cd603df3eb6c693f7f75a41b0c068047 | 3,071 | swift | Swift | MapboxNavigation/FeedbackCollectionViewCell.swift | Jonathan-Navagis/mapbox-navigation-ios | 93ac76909c9970c238fb0c8f4aa3fae5680985c0 | [
"MIT"
] | null | null | null | MapboxNavigation/FeedbackCollectionViewCell.swift | Jonathan-Navagis/mapbox-navigation-ios | 93ac76909c9970c238fb0c8f4aa3fae5680985c0 | [
"MIT"
] | null | null | null | MapboxNavigation/FeedbackCollectionViewCell.swift | Jonathan-Navagis/mapbox-navigation-ios | 93ac76909c9970c238fb0c8f4aa3fae5680985c0 | [
"MIT"
] | null | null | null | import Foundation
import UIKit
class FeedbackCollectionViewCell: UICollectionViewCell {
static let defaultIdentifier = "MapboxFeedbackCell"
struct Constants {
static let circleSize: CGSize = 70.0
static let imageSize: CGSize = 36.0
static let padding: CGFloat = 8
static let titleFont: UIFont = .systemFont(ofSize: 18.0)
}
lazy var circleView: UIView = .forAutoLayout()
lazy var imageView: UIImageView = .forAutoLayout()
lazy var titleLabel: UILabel = {
let title: UILabel = .forAutoLayout()
title.numberOfLines = 2
title.textAlignment = .center
title.font = Constants.titleFont
return title
}()
public var circleColor: UIColor = .black {
didSet {
circleView.backgroundColor = circleColor
}
}
var originalTransform: CGAffineTransform?
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
setupViews()
setupConstraints()
circleColor = .black
}
override var isHighlighted: Bool {
didSet {
if originalTransform == nil {
originalTransform = self.imageView.transform
}
UIView.defaultSpringAnimation(0.3, animations: {
if self.isHighlighted {
self.imageView.transform = self.imageView.transform.scaledBy(x: 0.85, y: 0.85)
} else {
guard let originalTransform = self.originalTransform else { return }
self.imageView.transform = originalTransform
}
}, completion: nil)
}
}
func setupViews() {
addSubview(circleView)
addSubview(imageView)
addSubview(titleLabel)
circleView.layer.cornerRadius = Constants.circleSize.height / 2
}
func setupConstraints() {
circleView.topAnchor.constraint(equalTo: topAnchor).isActive = true
circleView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
circleView.heightAnchor.constraint(equalToConstant: Constants.circleSize.height).isActive = true
circleView.widthAnchor.constraint(equalToConstant: Constants.circleSize.width).isActive = true
imageView.centerYAnchor.constraint(equalTo: circleView.centerYAnchor).isActive = true
imageView.centerXAnchor.constraint(equalTo: circleView.centerXAnchor).isActive = true
imageView.heightAnchor.constraint(equalToConstant: Constants.imageSize.height).isActive = true
imageView.widthAnchor.constraint(equalToConstant: Constants.imageSize.width).isActive = true
titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
titleLabel.topAnchor.constraint(equalTo: circleView.bottomAnchor, constant: Constants.padding).isActive = true
}
}
| 34.505618 | 118 | 0.644741 |
83ebb4321f855e4a9eddb97ca12cd93114843300 | 271 | java | Java | elasticsearch-helper-boot-starter/src/main/java/org/pippi/elasticsearch/helper/spring/package-info.java | Johendeng/elasticsearch-helper | 362907acfd75aa8225406be8b472879fdbca32e7 | [
"Apache-2.0"
] | 3 | 2021-09-30T17:53:31.000Z | 2021-11-25T08:37:44.000Z | elasticsearch-helper-boot-starter/src/main/java/org/pippi/elasticsearch/helper/spring/package-info.java | Johendeng/elasticsearch-helper | 362907acfd75aa8225406be8b472879fdbca32e7 | [
"Apache-2.0"
] | null | null | null | elasticsearch-helper-boot-starter/src/main/java/org/pippi/elasticsearch/helper/spring/package-info.java | Johendeng/elasticsearch-helper | 362907acfd75aa8225406be8b472879fdbca32e7 | [
"Apache-2.0"
] | null | null | null | /**
* package-info
*
* author johenTeng
* date 2021/9/17
*/
package org.pippi.elasticsearch.helper.spring;
// load the elasticsearch-helper into SpringApplicationContext
// when user's context user spring-cloud-data-elasticsearch, supplier adapter for user | 27.1 | 86 | 0.741697 |
484bb4ddc2bcf0853427d09ae99472906078ecf7 | 502 | sql | SQL | script/table/gear.sql | UKGANG/IST-659 | cb0f2381dca85b13bbd38a2dc9c9e6fe02044850 | [
"MIT"
] | null | null | null | script/table/gear.sql | UKGANG/IST-659 | cb0f2381dca85b13bbd38a2dc9c9e6fe02044850 | [
"MIT"
] | null | null | null | script/table/gear.sql | UKGANG/IST-659 | cb0f2381dca85b13bbd38a2dc9c9e6fe02044850 | [
"MIT"
] | null | null | null | IF NOT EXISTS(SELECT TOP 1 1 FROM sys.tables WHERE name='gear' AND SCHEMA_NAME(schema_id)='dbo')
BEGIN
CREATE TABLE dbo.gear
(
gear_id BIGINT NOT NULL IDENTITY,
gear_type_id BIGINT NOT NULL,
use_frequency_count INT NOT NULL,
brand NVARCHAR(255)
)
PRINT 'CREATE TABLE dbo.gear'
ALTER TABLE dbo.[gear]
ADD CONSTRAINT pk_gear PRIMARY KEY CLUSTERED (gear_id)
PRINT 'CREATE primary key pk_gear on table [dbo].[gear]'
END
| 26.421053 | 96 | 0.649402 |
44d1f65bcb6bb3f9ded8b7999d672f6b889d3d87 | 4,803 | asm | Assembly | C_and_Assembly/Gcd/Gcd.asm | woobear/School_projects | 40933c0ae90cdabfd364ab0b8e5ae48414d8c347 | [
"MIT"
] | null | null | null | C_and_Assembly/Gcd/Gcd.asm | woobear/School_projects | 40933c0ae90cdabfd364ab0b8e5ae48414d8c347 | [
"MIT"
] | null | null | null | C_and_Assembly/Gcd/Gcd.asm | woobear/School_projects | 40933c0ae90cdabfd364ab0b8e5ae48414d8c347 | [
"MIT"
] | null | null | null | ;Robert Wooner
;Final Project
;CS 261
; main and puts functions were given to us by Dr. Dick Lang
section .data
pmpt: db "Enter positive integer: "
plen: equ $-pmpt
outpt: db "Greatest common divisor: "
outlen: equ $-outpt
error: db "These are bad Numbers"
erlen: equ $-error
newln: db 10
section .bss
inbuff: resd 20
remain: resd 1
section .text
global _start
global getInt
global readNumber
global gcd
global makeDecimal
; *****************
;puts(string address, char count)
; *****************
puts:
push ebp
mov ebp, esp
push eax
push ebx
push ecx
push edx
mov ecx, [ebp+8]
mov edx, [ebp+12]
mov eax, 4
mov ebx, 1
int 80H
pop edx
pop ecx
pop ebx
pop eax
mov esp, ebp
pop ebp
ret
; **************
; gcd()
; **************
gcd:
push ebp
mov ebp, esp
push ecx
push edx
mov ecx, [ebp+8] ; this is n
mov edx, [ebp+12] ; this is m
jmp gcdStart
gcdStart:
cld
cmp ecx, edx
ja one
jb two
mov eax, ecx
jmp Base
one:
sub ecx, edx ;n-m
push edx
push ecx
call gcd ;restart
add esp, 8
jmp Base
two:
sub edx, ecx ;m-n
push edx
push ecx
call gcd ;restart
add esp, 8
jmp Base
Base:
pop edx
pop ecx
pop ebx
mov esp, ebp
pop ebp
ret
; **************
; readNumber()
; **************
readNumber:
push ebp
mov ebp, esp
push ebx
push ecx
push edx
mov eax, 4 ;writes
mov ebx, 1
mov ecx, pmpt
mov edx, plen
int 80H
mov eax, 3 ;reads
mov ebx, 0
mov ecx, inbuff
mov edx, 21
int 80H
push inbuff ;pushes input
call getInt ; calls getInt on the input
add esp, 4
pop edx
pop ecx
pop ebx
mov esp, ebp
pop ebp
ret
; **************************
; getInt(char* string)
; **************************
getInt:
push ebp
mov ebp, esp
push ebx
push ecx
push edx
push esi
push edi
mov ebx, 1
mov edx, 0
mov esi, [ebp+8]
mov edi, [ebp+8]
firstLoop:
mov al, byte [esi] ; counts how many digits there are in the string
cmp al, 10
je calc ; jumps to calc if its the end
inc esi
jmp firstLoop ;jumps back til the end of the string
calc:
dec esi ;counts backwards for the amount of numbers in the sting
movzx eax, byte [esi] ;moves the byte into eax while filling the rest with zeros
cmp esi, edi ; compares to see if its the first position
jb Last
cmp al, 32 ; sees if its a space
je Last
cmp al, 48 ;sees if its less than '0'
jl errorM
cmp al, 57 ;sees if its greater '9'
jg errorM
sub al, '0'
imul eax, ebx
add edx, eax
imul ebx, 10
jmp calc
errorM:
mov eax, 4 ;writes error message
mov ebx, 1
mov ecx, error
mov edx, erlen
int 80H
mov eax, 4 ;writes new line
mov ebx, 1
mov ecx, newln
mov edx, 10
int 80H
add esp, 8
mov eax, 1
mov ebx, 0
int 80H
Last:
mov eax, edx
pop edi
pop esi
pop ecx
pop ebx
mov esp, ebp
pop ebp
ret
; **************************
; MakeDecimal(unsigned int)
; **************************
makeDecimal:
push ebp
mov ebp, esp
push eax
push edx
push ecx
mov ecx, 10 ; moves 10 into eax
mov eax, [ebp+8] ;moves the unsigned int into edx
mov edx, 0 ;sets edx to 0
div dword ecx ; divides ecx by eax
cmp eax, 0 ;compares eax (qotient with zero
ja recurse ;if greater then zero jump to recurse function
jmp End
End:
add edx, '0' ; adds '0' to edx (remainder)
mov [remain], edx
push dword 1 ;push room for on the stack
push dword remain ;push the number on the stack
call puts ;call put which writes the number
add esp, 8 ;clear the stack
pop ecx
pop edx
pop eax
mov esp, ebp
pop ebp
ret
recurse:
push eax
call makeDecimal
pop eax
jmp End
; **************
; main program
; **************
_start:
call readNumber
mov esi, eax
call readNumber
push eax
push esi
call gcd
add esp, 8
push dword outlen
push dword outpt
call puts
push eax
call makeDecimal
add esp, 4
push dword 1
push dword newln
call puts
add esp, 8
mov eax, 1
mov ebx, 0
int 80H
| 17.723247 | 85 | 0.511347 |
aff3a354b7774ddbf8f63f694e3b2ca81b4b2d44 | 2,358 | html | HTML | manuscript/page-1650/body.html | marvindanig/the-complete-herbal | f40cade6bd6553a90da7b8ff8b0a3068575870df | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | manuscript/page-1650/body.html | marvindanig/the-complete-herbal | f40cade6bd6553a90da7b8ff8b0a3068575870df | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | manuscript/page-1650/body.html | marvindanig/the-complete-herbal | f40cade6bd6553a90da7b8ff8b0a3068575870df | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | <div class="leaf flex"><div class="inner justify"><p class="no-indent ">model, (because he gives the whole <em>simple</em> which must needs consist of divers qualities, because the creation is made up of and consists by an harmony of contraries there is (I say this faculty in all purges of that nature, that they contain in them a substance which is inimical both to the stomach and bowels, and some are of opinion this doth good, namely, provokes nature the more to expulsion; the reason might be good if the foundation of it were so, for by this reason nature herself should purge, not the medicine, and a physician should help nature in her business and not hinder her. But to forbear being critical, this substance which I told you was inimical to the stomach, must be corrected in every purge. ) )</p><p><em>CULPEPER’S LAST LEGACIES.</em></p><img class="overlay center" width = "0%" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/wAALCAAKAI8BAREA/8QAGwAAAQUBAQAAAAAAAAAAAAAABgABAgQFBwP/xAAyEAABAwIFAwIEBAcAAAAAAAABAgMEBREABgcSIRMxQSJRCBUXcTKBkaEUI0JhgsHw/9oACAEBAAA/AO853rebaPMhjK+T0ZiiuNL6yhU2oimlgjaLLHIPPIv+VuQatZ/1XZjBqFpQGZZG4OLqzclsAd7pRt59vV+uBv6n6zt1OOiRpwwiMr1LIjvrshPK/WlSrHbew2kk9go+nFzNeq2pNMqlRixNO1yGWggsvsx5r7ZukFXr6KN/JPhNu3Nr453U/iA1SaYBkZahQLK4X8qfF/7etwj/AHgTmfEDn18jq1kR1D0LaZpscceTuWlRB8drY8Hdcc0SXX1Sq7XEqUUOMrZcjIDa0ngqQGQFJ90gpB83x0BOtepMnTBuaxQpCZCprUePXkR0BuTuUobCypJBJKSkqRwDYcG1/LPGs2qMjNUuiwIlOyg5GUVJZnOR2nFIvtF3ZJDawTyCgC45FwCcLKutOqVPrcGFUItLzcZAUf4WnPx3n1D33RSoIt7qTa1/uNp/WbUZvK2ZZiMsyA2xWZMRdRDaH/lLSQklotJtvU2CT1FkIJsDftgAquveYE9T5RmmvrXYEKlwYQS4sWPKEp9CSfAUePJxmR/iJ1HaQnqVxl5QNyHIDABH+KR9vzwRUb4g9Tpj6E0+FHqqlIUemmlqV3PcdNVzt7D97nBIzrBraEA/Twuk87zQ5vPt2WBgtoOpGslQaCl6YtqJF/5i1RP2dVfBQjOeqQ/HpKk8AenMcYc+e4P/AHvgkyTX84VaqPsZoyOcvQw0XESfm7Mveu6QG9iACOCo3Ptbzg2xBz+n7jEvAw/jFeSpQ6ViRdYBscSVyCDyD4OMiRluhzHw9Mo1Mfe773Yra1fqRjTjstJihtLaA2lRISEiwO697ffnEJ9Og1SIiPUocaYwFJWG5DSXEhQ7GxBFx74lTqdCpcUx6ZDjQ2NxX047SW07j3NgALnFsdsZicvUVDm9NIpyV3vuEZAPv3ti/wBJtKUBKEgJNwAO32xNH4RhYWHw2P/Z" url = "https://raw.githubusercontent.com/marvindanig/the-complete-herbal/master/assets/images/i_deco.jpg" /><h5 class=" "><Em>select Medicinal Aphorisms And Receipts, For Many Diseases Our Frail Natures Are Incident</h5></div> </div> | 2,358 | 2,358 | 0.871077 |
861f883bb74490e8c789977d597148f6a90a3941 | 3,682 | java | Java | core/src/main/java/com/cloud/example/login/SsoWebLoginHelper.java | wand007/cloud-example | f657b8c16e42da57059c88807aa936561d365e84 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/com/cloud/example/login/SsoWebLoginHelper.java | wand007/cloud-example | f657b8c16e42da57059c88807aa936561d365e84 | [
"Apache-2.0"
] | 5 | 2022-01-15T04:33:44.000Z | 2022-03-10T07:54:14.000Z | core/src/main/java/com/cloud/example/login/SsoWebLoginHelper.java | wand007/cloud-example | f657b8c16e42da57059c88807aa936561d365e84 | [
"Apache-2.0"
] | 1 | 2021-02-23T08:55:01.000Z | 2021-02-23T08:55:01.000Z | package com.cloud.example.login;
import com.cloud.example.config.SsoConfig;
import com.cloud.example.domain.sso.SsoUser;
import com.cloud.example.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author xuxueli 2018-04-03
*/
@Component
public class SsoWebLoginHelper {
@Autowired
SsoLoginStore ssoLoginStore;
@Autowired
SsoTokenLoginHelper ssoTokenLoginHelper;
/**
* make client sessionId
*
* @param ssoUser
* @return
*/
public String makeSessionId(SsoUser ssoUser) {
String sessionId = ssoUser.getUserId().concat("_").concat(ssoUser.getVersion());
return sessionId;
}
/**
* client login
*
* @param response
* @param sessionId
* @param ifRemember true: cookie not expire, false: expire when browser close (server cookie)
* @param ssoUser
*/
public void login(HttpServletResponse response,
String sessionId,
SsoUser ssoUser,
boolean ifRemember) {
String storeKey = SsoSessionIdHelper.parseStoreKey(sessionId);
if (storeKey == null) {
throw new RuntimeException("parseStoreKey Fail, sessionId:" + sessionId);
}
ssoLoginStore.put(storeKey, ssoUser);
CookieUtil.set(response, SsoConfig.SSO_SESSIONID, sessionId, ifRemember);
}
/**
* client logout
*
* @param request
* @param response
*/
public void logout(HttpServletRequest request,
HttpServletResponse response) {
String cookieSessionId = CookieUtil.getValue(request, SsoConfig.SSO_SESSIONID);
if (cookieSessionId == null) {
return;
}
String storeKey = SsoSessionIdHelper.parseStoreKey(cookieSessionId);
if (storeKey != null) {
ssoLoginStore.remove(storeKey);
}
CookieUtil.remove(request, response, SsoConfig.SSO_SESSIONID);
}
/**
* login check
*
* @param request
* @param response
* @return
*/
public SsoUser loginCheck(HttpServletRequest request, HttpServletResponse response) {
String cookieSessionId = CookieUtil.getValue(request, SsoConfig.SSO_SESSIONID);
// cookie user
SsoUser ssoUser = ssoTokenLoginHelper.loginCheck(cookieSessionId);
if (ssoUser != null) {
return ssoUser;
}
// redirect user
// remove old cookie
this.removeSessionIdByCookie(request, response);
// set new cookie
String paramSessionId = request.getParameter(SsoConfig.SSO_SESSIONID);
ssoUser = ssoTokenLoginHelper.loginCheck(paramSessionId);
if (ssoUser != null) {
CookieUtil.set(response, SsoConfig.SSO_SESSIONID, paramSessionId, false); // expire when browser close (client cookie)
return ssoUser;
}
return null;
}
/**
* client logout, cookie only
*
* @param request
* @param response
*/
public void removeSessionIdByCookie(HttpServletRequest request, HttpServletResponse response) {
CookieUtil.remove(request, response, SsoConfig.SSO_SESSIONID);
}
/**
* get sessionid by cookie
*
* @param request
* @return
*/
public String getSessionIdByCookie(HttpServletRequest request) {
String cookieSessionId = CookieUtil.getValue(request, SsoConfig.SSO_SESSIONID);
return cookieSessionId;
}
}
| 27.073529 | 133 | 0.641771 |
4a53d1793b18e503656734098fc03fa08f3915cb | 5,135 | cs | C# | Adapters/HttpListenerResponseAdapter.cs | alkampfergit/WebDAVSharp.Server | e34268c424a178349a84f901874d5364d8fa3f79 | [
"MIT"
] | 5 | 2017-10-01T01:04:26.000Z | 2021-11-01T09:16:19.000Z | Adapters/HttpListenerResponseAdapter.cs | alkampfergit/WebDAVSharp.Server | e34268c424a178349a84f901874d5364d8fa3f79 | [
"MIT"
] | 3 | 2017-02-08T07:19:55.000Z | 2017-02-20T16:18:08.000Z | Adapters/HttpListenerResponseAdapter.cs | alkampfergit/WebDAVSharp.Server | e34268c424a178349a84f901874d5364d8fa3f79 | [
"MIT"
] | 7 | 2016-08-29T16:56:47.000Z | 2021-09-07T09:39:31.000Z | using System;
using System.IO;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
namespace WebDAVSharp.Server.Adapters
{
/// <summary>
/// This
/// <see cref="IHttpListenerResponse" /> implementation wraps around a
/// <see cref="HttpListenerResponse" /> instance.
/// </summary>
internal sealed class HttpListenerResponseAdapter : IHttpListenerResponse
{
#region Private Variables
private readonly HttpListenerResponse _response;
#endregion
#region Properties
/// <summary>
/// Gets the internal instance that was adapted for WebDAV#.
/// </summary>
/// <value>
/// The adapted instance.
/// </value>
public HttpListenerResponse AdaptedInstance
{
get
{
return _response;
}
}
/// <summary>
/// Gets or sets the HTTP status code to be returned to the client.
/// </summary>
public int StatusCode
{
get
{
return _response.StatusCode;
}
set
{
_response.StatusCode = value;
}
}
/// <summary>
/// Gets or sets a text description of the HTTP <see cref="StatusCode">status code</see> returned to the client.
/// </summary>
public string StatusDescription
{
get
{
return _response.StatusDescription;
}
set
{
_response.StatusDescription = value ?? string.Empty;
}
}
/// <summary>
/// Gets a <see cref="Stream" /> object to which a response can be written.
/// </summary>
public Stream OutputStream
{
get
{
return _response.OutputStream;
}
}
/// <summary>
/// Gets or sets the <see cref="Encoding" /> for this response's <see cref="OutputStream" />.
/// </summary>
public Encoding ContentEncoding
{
get
{
return _response.ContentEncoding;
}
set
{
_response.ContentEncoding = value;
}
}
/// <summary>
/// Gets or sets the number of bytes in the body data included in the response.
/// </summary>
public long ContentLength64
{
get
{
return _response.ContentLength64;
}
set
{
_response.ContentLength64 = value;
}
}
#endregion
#region Public Functions
/// <summary>
/// Initializes a new instance of the <see cref="HttpListenerResponseAdapter" /> class.
/// </summary>
/// <param name="response">The <see cref="HttpListenerResponse" /> to adapt for WebDAV#.</param>
/// <exception cref="System.ArgumentNullException">Response</exception>
/// <exception cref="ArgumentNullException"><paramref name="response" /> is <c>null</c>.</exception>
public HttpListenerResponseAdapter(HttpListenerResponse response)
{
if (response == null)
throw new ArgumentNullException("response");
_response = response;
}
/// <summary>
/// Sends the response to the client and releases the resources held by the adapted
/// <see cref="HttpListenerResponse" /> instance.
/// </summary>
public void Close()
{
_response.Close();
}
/// <summary>
/// Appends a value to the specified HTTP header to be sent with the response.
/// </summary>
/// <param name="name">The name of the HTTP header to append the <paramref name="value" /> to.</param>
/// <param name="value">The value to append to the <paramref name="name" /> header.</param>
public void AppendHeader(string name, string value)
{
_response.AppendHeader(name, value);
}
public void SetEtag(String etag)
{
_response.Headers.Add("ETag", etag);
}
public void SetLastModified(DateTime date)
{
_response.Headers.Add("Last-Modified", GetLastModifiedFromDate(date));
}
public static String GetLastModifiedFromDate(DateTime date)
{
return date.ToUniversalTime().ToString("ddd, dd MMM yyyy hh:mm:ss G\\MT", System.Globalization.CultureInfo.InvariantCulture);
}
public string DumpHeaders()
{
StringBuilder headers = new StringBuilder();
headers.AppendFormat("STATUS CODE: {0}\r\n", _response.StatusCode);
foreach (String header in _response.Headers)
{
headers.AppendFormat("{0}: {1}\r\n", header, _response.Headers[header]);
}
return headers.ToString();
}
#endregion
}
} | 28.848315 | 138 | 0.528335 |
238963d6ae53d55dbdadc59ceaddd4884b7e4296 | 4,896 | swift | Swift | Sources/SmokeHTTP1/SmokeHTTP1Server.swift | pbthif/smoke-framework | 8b8cab2c459612b3be3e5331fa6ea371a8aab0ff | [
"Apache-2.0"
] | 1,289 | 2018-10-03T21:50:32.000Z | 2022-03-30T23:59:29.000Z | Sources/SmokeHTTP1/SmokeHTTP1Server.swift | pbthif/smoke-framework | 8b8cab2c459612b3be3e5331fa6ea371a8aab0ff | [
"Apache-2.0"
] | 27 | 2018-10-04T19:14:01.000Z | 2021-11-29T17:45:21.000Z | Sources/SmokeHTTP1/SmokeHTTP1Server.swift | pbthif/smoke-framework | 8b8cab2c459612b3be3e5331fa6ea371a8aab0ff | [
"Apache-2.0"
] | 44 | 2018-10-04T15:40:20.000Z | 2021-12-06T01:27:05.000Z | // Copyright 2018-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file 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.
//
// SmokeHTTP1Server.swift
// SmokeHTTP1
//
import Foundation
import NIO
public struct ServerDefaults {
static let defaultHost = "0.0.0.0"
public static let defaultPort = 8080
}
public enum SmokeHTTP1ServerError: Error {
case shutdownAttemptOnUnstartedServer
}
/**
A basic non-blocking HTTP server that handles a request with an
optional body and returns a response with an optional body.
This implementation wraps an `StandardSmokeHTTP1Server` instance internally, type erasing the generic parameters and
presenting the same external methods as SmokeFramework 1.x.
*/
public class SmokeHTTP1Server {
/**
Enumeration specifying how the event loop is provided for a channel established by this client.
*/
public enum EventLoopProvider {
/// The client will create a new EventLoopGroup to be used for channels created from
/// this client. The EventLoopGroup will be closed when this client is closed.
case spawnNewThreads
/// The client will use the provided EventLoopGroup for channels created from
/// this client. This EventLoopGroup will not be closed when this client is closed.
case use(EventLoopGroup)
}
/**
Enumeration specifying if the server should be shutdown on any signals received.
*/
public enum ShutdownOnSignal {
// do not shut down the server on any signals
case none
// shutdown the server if a SIGINT is received
case sigint
// shutdown the server if a SIGTERM is received
case sigterm
}
private let startHandler: () throws -> ()
private let shutdownHandler: () throws -> ()
private let waitUntilShutdownHandler: () throws -> ()
private let waitUntilShutdownAndThenHandler: (_ onShutdown: @escaping () -> Void) throws -> ()
private let onShutdownHandler: (_ onShutdown: @escaping () -> Void) throws -> ()
public init<HTTP1RequestHandlerType: HTTP1RequestHandler>(
wrappedServer: StandardSmokeHTTP1Server<HTTP1RequestHandlerType>) {
self.startHandler = {
try wrappedServer.start()
}
self.shutdownHandler = {
try wrappedServer.shutdown()
}
self.waitUntilShutdownHandler = {
try wrappedServer.waitUntilShutdown()
}
self.waitUntilShutdownAndThenHandler = { onShutdown in
try wrappedServer.waitUntilShutdownAndThen(onShutdown: onShutdown)
}
self.onShutdownHandler = { onShutdown in
try wrappedServer.onShutdown(onShutdown: onShutdown)
}
}
/**
Starts the server on the provided port. Function returns
when the server is started. The server will continue running until
either shutdown() is called or the surrounding application is being terminated.
*/
public func start() throws {
try self.startHandler()
}
/**
Initiates the process of shutting down the server.
*/
public func shutdown() throws {
try self.shutdownHandler()
}
/**
Blocks until the server has been shutdown and all completion handlers
have been executed.
*/
public func waitUntilShutdown() throws {
try self.waitUntilShutdownHandler()
}
/**
Blocks until the server has been shutdown and all completion handlers
have been executed. The provided closure will be added to the list of
completion handlers to be executed on shutdown. If the server is already
shutdown, the provided closure will be immediately executed.
- Parameters:
- onShutdown: the closure to be executed after the server has been
fully shutdown.
*/
public func waitUntilShutdownAndThen(onShutdown: @escaping () -> Void) throws {
try self.waitUntilShutdownAndThenHandler(onShutdown)
}
/**
Provides a closure to be executed after the server has been fully shutdown.
- Parameters:
- onShutdown: the closure to be executed after the server has been
fully shutdown.
*/
public func onShutdown(onShutdown: @escaping () -> Void) throws {
try self.onShutdownHandler(onShutdown)
}
}
| 34.723404 | 117 | 0.671773 |
75ff9d734e7c204bda8c07d6d2b0e7c5abb98d5b | 14,488 | java | Java | src/main/java/org/apache/hadoop/ozone/examples/OzoneRpc.java | SincereXIA/ozonerpc2 | 229a0f8df2c06dfb1785ef9b573de4ed38d5d46e | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/hadoop/ozone/examples/OzoneRpc.java | SincereXIA/ozonerpc2 | 229a0f8df2c06dfb1785ef9b573de4ed38d5d46e | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/hadoop/ozone/examples/OzoneRpc.java | SincereXIA/ozonerpc2 | 229a0f8df2c06dfb1785ef9b573de4ed38d5d46e | [
"Apache-2.0"
] | 1 | 2021-12-30T07:32:50.000Z | 2021-12-30T07:32:50.000Z | /*
* 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.hadoop.ozone.examples;
import com.beust.jcommander.JCommander;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.hadoop.hdds.client.ReplicationConfig;
import org.apache.hadoop.hdds.client.ReplicationFactor;
import org.apache.hadoop.hdds.client.ReplicationType;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.ozone.client.ObjectStore;
import org.apache.hadoop.ozone.client.OzoneBucket;
import org.apache.hadoop.ozone.client.OzoneClient;
import org.apache.hadoop.ozone.client.OzoneClientFactory;
import org.apache.hadoop.ozone.client.OzoneVolume;
import org.apache.hadoop.ozone.client.io.OzoneDataStreamOutput;
import org.apache.hadoop.ozone.client.io.OzoneOutputStream;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* A mini demo program that access Ozone Volume/Bucket/Key via Ozone RPC
* with minimal dependency on classpath/configuration stuff.
* It has been tested with secure, non-secure, HA and non-HA Ozone clusters.
*/
public class OzoneRpc {
private static boolean disableChecksum = false;
private static long numFiles;
private static int chunkSize;
private static long fileSizeInBytes = 128000000;
private static long bufferSizeInBytes = 4000000;
private static String[] storageDir = new String[]{"/data/ratis/", "/data1/ratis/", "/data2/ratis/", "/data3/ratis/",
"/data4/ratis/", "/data5/ratis/", "/data6/ratis/", "/data7/ratis/", "/data8/ratis/", "/data9/ratis/",
"/data10/ratis/", "/data11/ratis/"};
private static void createDirs() throws IOException {
for (String dir : storageDir) {
Files.createDirectory(new File(dir).toPath());
}
}
public static String getPath(String fileName) {
int hash = fileName.hashCode() % storageDir.length;
return new File(storageDir[Math.abs(hash)], fileName).getAbsolutePath();
}
protected static void dropCache() throws InterruptedException, IOException {
String[] cmds = {"/bin/sh","-c","sync; echo 3 > /proc/sys/vm/drop_caches"};
Process pro = Runtime.getRuntime().exec(cmds);
pro.waitFor();
final long safeTime = 5 * 1000L; // sleep extra 5 seconds.
final long filesPerDisk = (numFiles - 1) / storageDir.length + 1;
final long diskSpeed = 100 * 1000 * 1000 / 1000; // 100 MB / 1000ms
final long msPerFile = (fileSizeInBytes - 1) / diskSpeed + 1;
final long msSleep = filesPerDisk * msPerFile + safeTime;
System.out.println("sleeping " + msSleep + "ms to wait for disk write");
Thread.sleep(filesPerDisk * msPerFile); // wait disk buffer write-back
}
private static CompletableFuture<Long> writeFileAsync(String path, ExecutorService executor) {
final CompletableFuture<Long> future = new CompletableFuture<>();
CompletableFuture.supplyAsync(() -> {
try {
future.complete(
writeFileFast(path, fileSizeInBytes));
//writeFile(path, fileSizeInBytes, bufferSizeInBytes, new Random().nextInt(127) + 1));
} catch (IOException e) {
future.completeExceptionally(e);
} catch (InterruptedException e) {
future.completeExceptionally(e);
}
return future;
}, executor);
return future;
}
protected static List<String> generateFiles(ExecutorService executor) {
UUID uuid = UUID.randomUUID();
List<String> paths = new ArrayList<>();
List<CompletableFuture<Long>> futures = new ArrayList<>();
for (int i = 0; i < numFiles; i ++) {
String path = getPath("file-" + uuid + "-" + i);
paths.add(path);
futures.add(writeFileAsync(path, executor));
}
for (int i = 0; i < futures.size(); i ++) {
long size = futures.get(i).join();
if (size != fileSizeInBytes) {
System.err.println("Error: path:" + paths.get(i) + " write:" + size +
" mismatch expected size:" + fileSizeInBytes);
}
}
return paths;
}
protected static long writeFileFast(String path, long fileSize) throws InterruptedException, IOException {
long mbytes = (fileSize >> 20) + 1;
String[] cmd = {"/bin/bash", "-c", "dd if=<(openssl enc -aes-256-ctr -pass pass:\"$(dd if=/dev/urandom bs=128 count=1 2>/dev/null | base64)\" -nosalt < /dev/zero) of=" + path + " bs=1M count=" + mbytes + " iflag=fullblock"};
Process ps = Runtime.getRuntime().exec(cmd);
ps.waitFor();
String[] cmd2 = {"/usr/bin/truncate", "--size=" + fileSize, "path"};
Process ps2 = Runtime.getRuntime().exec(cmd2);
ps2.waitFor();
return fileSize;
}
protected static long writeFile(String path, long fileSize, long bufferSize, int random) throws IOException {
RandomAccessFile raf = null;
long offset = 0;
try {
raf = new RandomAccessFile(path, "rw");
while (offset < fileSize) {
final long remaining = fileSize - offset;
final long chunkSize = Math.min(remaining, bufferSize);
byte[] buffer = new byte[(int)chunkSize];
for (int i = 0; i < chunkSize; i ++) {
buffer[i]= (byte) (i % random);
}
raf.write(buffer);
offset += chunkSize;
}
} finally {
if (raf != null) {
raf.close();
}
}
return offset;
}
private static Map<String, CompletableFuture<Boolean>> writeByHeapByteBuffer(
List<String> paths, List<OzoneOutputStream> outs, ExecutorService executor) {
Map<String, CompletableFuture<Boolean>> fileMap = new HashMap<>();
for(int i = 0; i < paths.size(); i ++) {
String path = paths.get(i);
OzoneOutputStream out = outs.get(i);
final CompletableFuture<Boolean> future = new CompletableFuture<>();
CompletableFuture.supplyAsync(() -> {
File file = new File(path);
try (FileInputStream fis = new FileInputStream(file)) {
int bytesToRead = (int)bufferSizeInBytes;
byte[] buffer = new byte[bytesToRead];
long offset = 0L;
while(fis.read(buffer, 0, bytesToRead) > 0) {
out.write(buffer);
offset += bytesToRead;
bytesToRead = (int) Math.min(fileSizeInBytes - offset, bufferSizeInBytes);
if (bytesToRead > 0) {
buffer = new byte[bytesToRead];
}
}
out.close();
future.complete(true);
} catch (Throwable e) {
future.complete(false);
}
return future;
}, executor);
fileMap.put(path, future);
}
return fileMap;
}
private static Map<String, CompletableFuture<Boolean>> writeByFileRegion(
List<String> paths, List<OzoneDataStreamOutput> outs, ExecutorService executor) {
Map<String, CompletableFuture<Boolean>> fileMap = new HashMap<>();
for(int i = 0; i < paths.size(); i ++) {
String path = paths.get(i);
OzoneDataStreamOutput out = outs.get(i);
final CompletableFuture<Boolean> future = new CompletableFuture<>();
CompletableFuture.supplyAsync(() -> {
File file = new File(path);
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(file);
FileChannel channel = fileInputStream.getChannel();
long size = channel.size();
MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, size);
out.write(mappedByteBuffer);
out.close();
future.complete(true);
} catch (Throwable e) {
future.complete(false);
}
return future;
}, executor);
fileMap.put(path, future);
}
return fileMap;
}
private static Map<String, CompletableFuture<Boolean>> writeByMappedByteBuffer(
List<String> paths, List<OzoneDataStreamOutput> outs, ExecutorService executor) {
Map<String, CompletableFuture<Boolean>> fileMap = new HashMap<>();
for(int i = 0; i < paths.size(); i ++) {
String path = paths.get(i);
OzoneDataStreamOutput out = outs.get(i);
final CompletableFuture<Boolean> future = new CompletableFuture<>();
CompletableFuture.supplyAsync(() -> {
File file = new File(path);
try (RandomAccessFile raf = new RandomAccessFile(file, "r");) {
FileChannel ch = raf.getChannel();
long len = raf.length();
long off = 0;
while (len > 0) {
long writeLen = Math.min(len, chunkSize);
ByteBuffer bb = ch.map(FileChannel.MapMode.READ_ONLY, off, writeLen);
out.write(bb);
off += writeLen;
len -= writeLen;
}
out.close();
future.complete(true);
} catch (Throwable e) {
future.complete(false);
}
return future;
}, executor);
fileMap.put(path, future);
}
return fileMap;
}
static OzoneClient getOzoneClient(boolean secure) throws IOException {
OzoneConfiguration conf = new OzoneConfiguration();
// TODO: If you don't have OM HA configured, change the following as appropriate.
conf.set("ozone.om.address", "9.29.173.57:9862");
if (disableChecksum)
conf.set("ozone.client.checksum.type", "NONE");
return OzoneClientFactory.getRpcClient(conf);
}
public static void main(String[] args) throws Exception {
CommandArgs commandArgs = new CommandArgs();
JCommander.newBuilder().addObject(commandArgs).build().parse(args);
System.out.println("Ozone Rpc Demo Begin.");
OzoneClient ozoneClient = null;
LaunchSync launchSync = new LaunchSync(55666, commandArgs.groups);
launchSync.start();
try {
String testVolumeName = commandArgs.volume;
String testBucketName = commandArgs.bucket;
numFiles = commandArgs.fileNum;
chunkSize = commandArgs.chunkSize;
fileSizeInBytes = commandArgs.fileSize;
disableChecksum = commandArgs.disableChecksum;
System.out.println("numFiles:" + numFiles);
System.out.println("chunkSize:" + chunkSize);
System.out.println("fileSize:" + fileSizeInBytes);
System.out.println("checksum:" + (disableChecksum ? "NONE" : "DEFAULT"));
createDirs();
final ExecutorService executor = Executors.newFixedThreadPool(1000);
final boolean streamApi = (chunkSize != 0);
final boolean byByteBuffer = (chunkSize > 0);
if (streamApi) {
System.out.println("=== using " + (byByteBuffer ? "ByteBuffer" : "FileRegion") + " stream api ===");
} else {
System.out.println("=== using async api ===");
}
List<String> paths = generateFiles(executor);
dropCache();
// Get an Ozone RPC Client.
ozoneClient = getOzoneClient(false);
// An Ozone ObjectStore instance is the entry point to access Ozone.
ObjectStore store = ozoneClient.getObjectStore();
// Create volume with random name.
store.createVolume(testVolumeName);
OzoneVolume volume = store.getVolume(testVolumeName);
System.out.println("Volume " + testVolumeName + " created.");
// Create bucket with random name.
volume.createBucket(testBucketName);
OzoneBucket bucket = volume.getBucket(testBucketName);
System.out.println("Bucket " + testBucketName + " created.");
ReplicationConfig config =
ReplicationConfig.fromTypeAndFactor(ReplicationType.RATIS, ReplicationFactor.THREE);
List<OzoneDataStreamOutput> streamOuts = new ArrayList<>();
List<OzoneOutputStream> asyncOuts = new ArrayList<>();
if (streamApi) {
for (int i = 0; i < paths.size(); i++) {
OzoneDataStreamOutput out = bucket.createStreamKey("ozonekey_" + i, 128000000,
config, new HashMap<>());
streamOuts.add(out);
}
} else {
for (int i = 0; i < paths.size(); i++) {
OzoneOutputStream out = bucket.createKey("ozonekey_" + i, 128000000,
config, new HashMap<>());
asyncOuts.add(out);
}
}
// wait for sync signal
launchSync.sendReady();
System.out.println("=== Wait All Client Ready ===");
System.out.println("...");
launchSync.waitAllReady();
System.out.println("=== All Ready! Start Test ===");
long start = System.currentTimeMillis();
// Write key with random name.
Map<String, CompletableFuture<Boolean>> map;
if (streamApi) {
map = byByteBuffer ? writeByMappedByteBuffer(paths, streamOuts, executor)
: writeByFileRegion(paths, streamOuts, executor);
} else {
map = writeByHeapByteBuffer(paths, asyncOuts, executor);
}
for (String path : map.keySet()) {
CompletableFuture<Boolean> future = map.get(path);
if (!future.join().booleanValue()) {
System.err.println("Error: path:" + path + " write fail");
}
}
long end = System.currentTimeMillis();
System.err.println("cost:" + (end - start) + " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
} catch (Exception e) {
System.err.println(e);
} finally {
// Ensure Ozone client resource is safely closed at the end.
if (ozoneClient != null) {
ozoneClient.close();
}
}
System.out.println("Ozone Rpc Demo End.");
System.exit(0);
}
private static String getRandomString(int len) {
return RandomStringUtils.randomAlphanumeric(len).toLowerCase();
}
}
| 37.340206 | 228 | 0.649365 |
b91739a6363242a17f397a17d2e9c09e601af806 | 428 | h | C | include/SpringBoard/CSOrientationUpdateControlling-Protocol.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | 3 | 2020-06-20T02:53:25.000Z | 2020-11-07T08:39:13.000Z | include/SpringBoard/CSOrientationUpdateControlling-Protocol.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | null | null | null | include/SpringBoard/CSOrientationUpdateControlling-Protocol.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | 1 | 2020-07-26T02:16:06.000Z | 2020-07-26T02:16:06.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 22 2020 01:47:48).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
@class NSString;
@protocol CSOrientationUpdateControlling <NSObject>
- (void)noteInterfaceOrientationChanged:(long long)arg1 duration:(double)arg2 logMessage:(NSString *)arg3;
- (void)cancelOrientationUpdateDeferral;
- (void)deferOrientationUpdatesWithReason:(NSString *)arg1;
@end
| 26.75 | 106 | 0.757009 |
23d34825638a76ff4212d12c01b10aa8b165d50a | 1,772 | lua | Lua | mta-resources/[Gamemode]/mtatr_3dsound/3dSoundAPI/c.lua | umithyo/MTA-TR | d5121f4671a82dc0593a867795eb988a9cb06da4 | [
"MIT"
] | 2 | 2019-10-02T16:03:16.000Z | 2020-05-13T20:29:58.000Z | mta-resources/[Gamemode]/mtatr_3dsound/3dSoundAPI/c.lua | umithyo/MTA-TR | d5121f4671a82dc0593a867795eb988a9cb06da4 | [
"MIT"
] | 8 | 2021-06-17T21:09:17.000Z | 2021-06-27T06:08:52.000Z | mta-resources/[Gamemode]/mtatr_3dsound/3dSoundAPI/c.lua | umithyo/mta-tr | d5121f4671a82dc0593a867795eb988a9cb06da4 | [
"MIT"
] | null | null | null | addEvent("core:onServerRequest3DSound", true);
function create3DSound ( ... )
local x, y, z, path, owner, looped, distance, dim, int = unpack(arg);
local clientSound3D = playSound3D (path, x, y, z, looped);
addEventHandler("onClientSoundStopped", clientSound3D,
function()
clientSound3D:destroy();
end
)
setSoundMaxDistance(clientSound3D, (distance or 50));
local dim, int = dim or 0, int or 0;
clientSound3D:setDimension(dim);
clientSound3D:setInterior(int);
if (owner and isElement(owner) ) then
attachElements(clientSound3D, owner);
local function destroyCreatedSound ()
if (isElement(clientSound3D) ) then
clientSound3D:destroy();
end
end
if getElementType(owner) == "player" then
addEventHandler("onClientPlayerQuit", owner, destroyCreatedSound);
addEventHandler("onClientElementDestroy", clientSound3D,
function()
removeEventHandler("onClientPlayerQuit", owner, destroyCreatedSound);
end
);
else
addEventHandler("onClientElementDestroy", owner, destroyCreatedSound);
addEventHandler("onClientElementDestroy", clientSound3D,
function()
removeEventHandler("onClientElementDestroy", owner, destroyCreatedSound);
end
);
end
end
end
addEventHandler("core:onServerRequest3DSound", root, create3DSound);
function createShared3DSound (x, y, z, path, owner, looped, distance, dim, int)
triggerServerEvent("core:onClientRequestGlobal3DSound", (owner or localPlayer), x, y, z, path, owner, looped, distance, dim, int) ;
end
function create3DOwnerSound (path, owner, looped, distance, dim, int)
triggerServerEvent("core:onClientRequestGlobal3DSound", (owner or localPlayer), 0, 0, 0, path, owner, looped, distance, dim, int) ;
end | 36.163265 | 133 | 0.722348 |
e00fb36c7c274f8b43ddb4dff444598e7f4757fc | 2,453 | dart | Dart | lib/ui/lainnya/tentang.dart | irzaip/trampillv2 | f89035d7d65cda737d5262406f6d61712b4f0bc1 | [
"MIT"
] | null | null | null | lib/ui/lainnya/tentang.dart | irzaip/trampillv2 | f89035d7d65cda737d5262406f6d61712b4f0bc1 | [
"MIT"
] | 1 | 2021-10-17T02:14:49.000Z | 2021-10-17T02:14:49.000Z | lib/ui/lainnya/tentang.dart | irzaip/trampillv2 | f89035d7d65cda737d5262406f6d61712b4f0bc1 | [
"MIT"
] | null | null | null | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:trampillv2/values/assets.dart';
class TentangScreen extends StatelessWidget {
TentangScreen({Key? key}) : super(key: key);
static const String routeName = '/tentang';
final String _markdownData = """
# SIAPA KAMI?
Kami berangkat dari sebuah komunitas pembelajaran kecerdasan buatan INDOSOAI, komunitas kami berusaha untuk memajukan pendidikan di Indonesia dengan bantuan tools-tools moderen seperti apps, dan AI.
bergabunglah di komunitas kami di:
## https://docs.google.com/forms/d/e/1FAIpQLSeqj1oG-nU2Vp1gsOjf9BTFZ1LXU_K2Uz0IoRTv4ckeGonIbw/viewform
""";
String url =
'https://docs.google.com/forms/d/e/1FAIpQLSeqj1oG-nU2Vp1gsOjf9BTFZ1LXU_K2Uz0IoRTv4ckeGonIbw/viewform';
@override
Widget build(BuildContext context) {
final controller = ScrollController();
return Scaffold(
backgroundColor: Colors.indigo,
appBar: AppBar(
backgroundColor: Colors.blue,
title: const Text('Tentang kami'),
),
body: Container(
color: Colors.white,
child: SafeArea(
child: ListView(
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Image.asset(
imageIndosoai,
fit: BoxFit.fitWidth,
),
ElevatedButton(
onPressed: () {
_launchURL();
},
child: const Text("KLIK DISINI UNTUK BERGABUNG")),
SizedBox(
height: 300,
child: Markdown(
controller: controller,
selectable: true,
data: _markdownData,
imageDirectory: 'https://raw.githubusercontent.com',
),
),
],
),
],
),
),
),
);
}
}
_launchURL() async {
const url =
'https://docs.google.com/forms/d/e/1FAIpQLSeqj1oG-nU2Vp1gsOjf9BTFZ1LXU_K2Uz0IoRTv4ckeGonIbw/viewform';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
| 31.050633 | 198 | 0.579698 |
0f0874578d6b4dfb4f45b7a9fc8daacc942a4d63 | 775 | hpp | C++ | adjacent_find_with_pred/adjacent_find_with_pred.hpp | colorhistory/cplusplus-general-programming | 3ece924a2ab34711a55a45bc41e2b74384956204 | [
"MIT"
] | 1 | 2019-09-28T09:40:08.000Z | 2019-09-28T09:40:08.000Z | adjacent_find_with_pred/adjacent_find_with_pred.hpp | colorhistory/cplusplus-general-programming | 3ece924a2ab34711a55a45bc41e2b74384956204 | [
"MIT"
] | null | null | null | adjacent_find_with_pred/adjacent_find_with_pred.hpp | colorhistory/cplusplus-general-programming | 3ece924a2ab34711a55a45bc41e2b74384956204 | [
"MIT"
] | null | null | null | #ifndef ADJACENT_FIND_WITH_PRED_HPP
#define ADJACENT_FIND_WITH_PRED_HPP
namespace GP {
////////////////////////////////////////////////////////////
/// \brief adjacent_find
/// \param first
/// \param last
/// \param pred
/// \return
///
template <class ForwardIterator, class BinaryPredicate>
constexpr ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate pred) {
if (first != last) {
ForwardIterator i = first;
while (++i != last) {
if (pred(*first, *i)) {
return first;
}
first = i;
}
}
return last;
}
} // namespace GP
#endif // ADJACENT_FIND_WITH_PRED_HPP
| 25 | 112 | 0.510968 |