text
stringlengths 27
775k
|
|---|
SpringApplication.getOrCreateEnvironment
创建 environment
AbstractApplicationContext.prepareBeanFactory
注册environment bean
idea配置java系统属性 ——> VM Options ——> -Duser.city.name=中文 。属性前面加上-D
javax.validation.constraints.NotEmpty.message
搜索属性的值 Ctrl+Shift+F ——> Scope ——> Project and Libraries
扩展Environment最好放在SpringApplication.refreshContext()方法执行前
|
module View where
import Data.Proxy (Proxy(..))
import qualified Miso
import Miso.Html
import Miso.String (ms)
import Routes (Route)
import qualified Routes
import Servant.API ((:<|>)(..))
import Types
viewApp :: App -> Miso.View Msg
viewApp appModel =
case appModel of
Initializing _initModel -> div_ [] [text "Initializing.."]
FailedToInitialize _initModel err -> div_ [] [text ("Failed to initialize: " <> err)]
Ready model -> div_ [] [routeToPage model]
routeToPage :: Model -> Miso.View Msg
routeToPage model = either (const notFoundPage) id page
where
page = Miso.runRoute (Proxy @Route) handlers (.currentURI) model
handlers = topPage :<|> listPage :<|> editPage
topPage :: Model -> View Msg
topPage = listPage
listPage :: Model -> View Msg
listPage _model =
div_
[]
[ button_ [onClick $ ChangeURI $ Routes.editLink "test"] [text "Go to edit"]
]
editPage :: RepoId -> Model -> View Msg
editPage _query model =
div_
[]
[ button_ [onClick AddOne] [text "+"],
text . ms $ model.counter,
button_ [onClick SubtractOne] [text "-"]
]
notFoundPage :: View action
notFoundPage = errorPage "Not found"
errorPage :: MisoString -> View action
errorPage err =
div_
[]
[ text err
]
|
namespace Predavac_URIS.Models
{
public class KorisnikInfoVO
{
public string Username { get; set; }
public string Email { get; set; }
public string Ime { get; set; }
public string Prezime { get; set; }
}
}
|
import { OPEN_PROJECT,
NEW_PROJECT,
DEFAULT_PAGE,
COMPILE_PROJECT, LOGIN_PAGE} from "./type/open"
export function openProjectPage(val) {
return {
type: OPEN_PROJECT,
payload: {
open: val,
whatPage: "open"
}
}
}
export function openNewProjectPage(val) {
return {
type: NEW_PROJECT,
payload: {
new: val,
whatpage: "new"
}
}
}
export function openCompilePage(val) {
return {
type: COMPILE_PROJECT,
payload: {
compile: val,
whatpage: "compile"
}
}
}
export function openLoginPage(val) {
return {
type: LOGIN_PAGE,
payload: {
login: val,
whatpage: "login"
}
}
}
export function defaultPage(val) {
return {
type: DEFAULT_PAGE,
payload: {
open: false,
login: false,
new: false,
compile: false,
whatpage: "default"
}
}
}
|
#!/usr/bin/env bash
# ----------------------------------------------------------------------------
#
# Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
# WSO2 Inc. 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.
#
# ----------------------------------------------------------------------------
# This script depends on curl and unzip, so make sure they are already installed.
set -o xtrace
echo "This is a Dummy Deployment creation scripts to deploy a standalone WSO2 Identity server"
echo "Here the test infrastructure is your local machine. Working dir: " `pwd`
#if you do not have a account, please create a account at https://wso2.com/
DEPLOYMENT_EP_FILE_NAME=deployment_eps
#echo "Downloading the IS 5.4.0 distribution"
#curl -k https://product-dist.wso2.com/products/identity-server/5.4.0/wso2is-5.4.0.zip --user $WSO2_USER:$WSO2_PASSWORD -o is.zip
echo "unzip the IS distribution"
if [ ! -f wso2is-5.4.0.zip ]; then
>&2 echo "wso2is-5.4.0.zip file does not exist at: " `pwd`
exit 1
fi
unzip -q -o wso2is-5.4.0.zip
echo -n "Starting the IS server"
bash ./wso2is-5.4.0/bin/wso2server.sh start
x=0;
retry_count=60;
echo "Wait for the server start up"
while ! nc -z localhost 9763; do
sleep 2 # wait for 2 second before check again
echo -n "."
if [ $x = $retry_count ]; then
echo "Identity server never started."
exit 1
fi
x=$((x+1))
done
echo "Successfully started the server!!"
echo "Generating the deployment_ep file with the endpoints"
echo "https://localhost:9443/carbon" > $DEPLOYMENT_EP_FILE_NAME
echo "Deployment has finished, test execution will commence next"
|
# frozen_string_literal: true
RgGen.define_simple_feature(:register_block, :vhdl_top) do
vhdl do
build do
input :clock, { name: 'i_clk' }
input :reset, { name: 'i_rst_n' }
signal :register_valid
signal :register_access, {
width: 2
}
signal :register_address, {
width: address_width
}
signal :register_write_data, {
width: bus_width
}
signal :register_strobe, {
width: bus_width / 8
}
signal :register_active, {
array_size: [total_registers]
}
signal :register_ready, {
array_size: [total_registers]
}
signal :register_status, {
width: 2, array_size: [total_registers]
}
signal :register_read_data, {
width: bus_width, array_size: [total_registers]
}
signal :register_value, {
width: value_width, array_size: [total_registers]
}
end
write_file '<%= register_block.name %>.vhd' do |file|
file.body { process_template }
end
private
def total_registers
register_block.files_and_registers.sum(&:count)
end
def address_width
register_block.local_address_width
end
def bus_width
configuration.bus_width
end
def value_width
register_block.registers.map(&:width).max
end
def generic_declarations
register_block
.declarations[:generic]
.yield_self(&method(:add_terminator))
end
def port_declarations
register_block
.declarations[:port]
.yield_self(&method(:sort_port_declarations))
.yield_self(&method(:add_terminator))
end
def signal_declarations
register_block.declarations[:signal]
end
def architecture_body_code
code_block(2) do |code|
register_block.generate_code(code, :register_block, :top_down)
register_block.generate_code(code, :register_file, :top_down, 1)
end
end
def sort_port_declarations(declarations)
declarations
.partition(&method(:clock_or_reset?))
.flatten
end
def clock_or_reset?(declaration)
[clock.to_s, reset.to_s]
.any? { |port_name| declaration.include?(port_name) }
end
def add_terminator(declarations)
declarations.map.with_index do |declaration, i|
(i == declarations.size - 1) && declaration ||
declaration + semicolon
end
end
end
end
|
#! /usr/bin/perl -w
use strict;
use CGI;
use JSON::XS;
use HTML::Template;
use Data::Dumper;
use File::Path;
use CoGe::Accessory::Web;
use CoGeX;
no warnings 'redefine';
use vars qw($P $PAGE_NAME $PAGE_TITLE $USER $coge %FUNCTION $FORM $LINK);
$PAGE_TITLE = 'Sources';
$PAGE_NAME = "$PAGE_TITLE.pl";
$FORM = new CGI;
( $coge, $USER, $P, $LINK ) = CoGe::Accessory::Web->init(
cgi => $FORM,
page_title => $PAGE_TITLE
);
%FUNCTION = (
create_source => \&create_source,
delete_source => \&delete_source,
get_sources => \&get_sources,
edit_source_info => \&edit_source_info,
update_source_info => \&update_source_info
);
CoGe::Accessory::Web->dispatch( $FORM, \%FUNCTION, \&gen_html );
sub create_source {
my %opts = @_;
return 0 unless $USER->is_admin;
return "No specified name!" unless $opts{name};
# Check if one already exists with same name
my $source =
$coge->resultset('DataSource')->find( { name => $opts{name} } );
return "A data source with the same name already exists" if ($source);
my $link = $opts{link};
$link =~ s/^\s+//;
$link = 'http://' . $link if ( not $link =~ /^(\w+)\:\/\// );
# Create the new data source
$coge->resultset('DataSource')->create(
{
name => $opts{name},
description => $opts{desc},
link => $link
}
);
return 1;
}
sub delete_source {
my %opts = @_;
return 0 unless $USER->is_admin;
my $dsid = $opts{dsid};
return "Must have valid data source id\n" unless ($dsid);
# Delete the data source
my $ds = $coge->resultset('DataSource')->find($dsid);
$ds->delete;
return 1;
}
sub get_sources {
#my %opts = @_;
my @sources;
foreach my $source ( sort { $a->name cmp $b->name }
$coge->resultset('DataSource')->all() )
{
push @sources,
{
NAME => $source->name . ' (id' . $source->id . ')',
DESC => ( $source->description ? $source->description : undef ),
LINK => (
$source->link
? '<a href="'
. $source->link
. '" target=_blank>'
. $source->link . '</a>'
: undef
),
BUTTONS => $USER->is_admin,
EDIT_BUTTON =>
"<span class='link ui-icon ui-icon-gear' onclick=\"edit_source_info({dsid: '"
. $source->id
. "'});\"></span>",
DELETE_BUTTON =>
"<span class='link ui-icon ui-icon-trash' onclick=\"delete_source({dsid: '"
. $source->id
. "'});\"></span>"
};
}
my $template =
HTML::Template->new( filename => $P->{TMPLDIR} . 'Sources.tmpl' );
$template->param( SOURCE_TABLE => 1 );
$template->param( SOURCE_LOOP => \@sources );
$template->param( BUTTONS => $USER->is_admin );
return $template->output;
}
sub edit_source_info {
my %opts = @_;
return 0 unless $USER->is_admin;
my $dsid = $opts{dsid};
return 0 unless $dsid;
my $ds = $coge->resultset('DataSource')->find($dsid);
my $desc = ( $ds->description ? $ds->description : '' );
my $template =
HTML::Template->new( filename => $P->{TMPLDIR} . 'Sources.tmpl' );
$template->param( EDIT_SOURCE_INFO => 1 );
$template->param( DSID => $dsid );
$template->param( NAME => $ds->name );
$template->param( DESC => $desc );
$template->param( LINK => $ds->link );
my %data;
$data{title} = 'Edit Source Info';
$data{name} = $ds->name;
$data{desc} = $desc;
$data{link} = $ds->link;
$data{output} = $template->output;
return encode_json( \%data );
}
sub update_source_info {
my %opts = @_;
return 0 unless $USER->is_admin;
my $dsid = $opts{dsid};
return 0 unless $dsid;
my $name = $opts{name};
return 0 unless $name;
my $desc = $opts{desc};
my $link = $opts{link};
my $ds = $coge->resultset('DataSource')->find($dsid);
$ds->name($name);
$ds->description($desc) if $desc;
$ds->link($link) if ($link);
$ds->update;
return 1;
}
sub gen_html {
my $html;
my $template =
HTML::Template->new( filename => $P->{TMPLDIR} . 'generic_page.tmpl' );
$template->param( USER => $USER->display_name || '' );
$template->param( TITLE => qq{Sources},
PAGE_TITLE => qq{Sources},
PAGE_LINK => $LINK,
HOME => $P->{SERVER},
HELP => 'Sources',
WIKI_URL => $P->{WIKI_URL} || '' );
$template->param( LOGON => 1 ) unless $USER->user_name eq "public";
$template->param( BODY => gen_body() );
$template->param( ADMIN_ONLY => $USER->is_admin );
$template->param( CAS_URL => $P->{CAS_URL} || '' );
$html .= $template->output;
}
sub gen_body {
my $template =
HTML::Template->new( filename => $P->{TMPLDIR} . 'Sources.tmpl' );
$template->param( PAGE_NAME => $FORM->url );
$template->param( MAIN => 1 );
$template->param( SOURCE_INFO => get_sources() );
$template->param( BUTTONS => $USER->is_admin );
$template->param( ADMIN_AREA => $USER->is_admin );
return $template->output;
}
|
namespace Quantic.Web
{
public class HeaderMissingException : System.Exception
{
public HeaderMissingException(string message)
: base(message)
{
}
}
}
|
# Learning Git and Version Control
This repo is mainly for my learning of Git & GitHub
## Pure files without Git Initialized
1. Git Initialize
```
$ git init
```
2. Add files
  a. To add all the files under the folder
```
$ git add .
```
  b. To add a / some files under the folder, e.g., just add README.md
```
$ git add README.md
```
3. Commit
```
$ git commit -m "Update Files"
```
4. Connect remote repo, for example, I connect EEG-DL repo
```
$ git remote add origin https://github.com/SuperBruceJia/EEG-DL.git
```
5. Pull the original files from the repo
```
$ git pull origin master
```
6. Push the new files to the repo (by force)
```
$ git push origin master -f
```
## Cloned repo and update files
1. Add files
  a. To add all the files under the folder
```
$ git add .
```
  b. To add a / some files under the folder, e.g., just add README.md
```
$ git add README.md
```
2. Commit
```
$ git commit -m "Update Files"
```
3. Push the new files to the repo
```
$ git push
```
or
```
$ git push origin HEAD:master
```
or
```
$ git push --set-upstream origin master
```
## Commit Logs
```
$ git log -all -graph --decorate
```
## Commit File Difference
```
$ git diff file_name
```
## Check
```
$ git checkout -vv file_name
```
or
```
$ git checkout -vv branch_name
```
## Merge Branches
```
$ git merge branch_name
```
If Merge Conflicts happened, we can manually make difficult branches' codes right, and use
```
$ git merge --continue
```
## Remote
```
$ git remote add <name> <url>
```
## Reference
[Version Control (Git)](https://missing.csail.mit.edu/2020/version-control/)
## License
MIT License
|
#include "../src/imagecalendar.h"
#include "imagecalendarplugin.h"
#include <QtPlugin>
ImageCalendarPlugin::ImageCalendarPlugin(QObject *parent)
: QObject(parent)
{
m_initialized = false;
}
void ImageCalendarPlugin::initialize(QDesignerFormEditorInterface * /* core */)
{
if (m_initialized)
return;
// Add extension registrations, etc. here
m_initialized = true;
}
bool ImageCalendarPlugin::isInitialized() const
{
return m_initialized;
}
QWidget *ImageCalendarPlugin::createWidget(QWidget *parent)
{
return new ImageCalendar(parent);
}
QString ImageCalendarPlugin::name() const
{
return QLatin1String("ImageCalendar");
}
QString ImageCalendarPlugin::group() const
{
return QLatin1String("Quc Widgets");
}
QIcon ImageCalendarPlugin::icon() const
{
return QIcon(QLatin1String(":/ico/imagecalendar.png"));
}
QString ImageCalendarPlugin::toolTip() const
{
return QLatin1String("");
}
QString ImageCalendarPlugin::whatsThis() const
{
return QLatin1String("");
}
bool ImageCalendarPlugin::isContainer() const
{
return false;
}
QString ImageCalendarPlugin::domXml() const
{
return QLatin1String("<widget class=\"ImageCalendar\" name=\"imageCalendar\">\n</widget>\n");
}
QString ImageCalendarPlugin::includeFile() const
{
return QLatin1String("imagecalendar.h");
}
|
cask 'webkit-build-archive' do
version :latest
sha256 :no_check
url do
require 'open-uri'
base_url = 'https://webkit.org/build-archives/'
macos_release = if MacOS.version == :sierra
%r{href="([^"]+mac\-sierra[^"]+.zip)"}
else
%r{href="([^"]+mac\-highsierra[^"]+.zip)"}
end
file = open(base_url).read.scan(macos_release).flatten.first
file.to_s
end
name 'WebKit Build Archive'
homepage 'https://webkit.org/build-archives/'
depends_on macos: [
:sierra,
:high_sierra,
]
# shim script (https://github.com/caskroom/homebrew-cask/issues/18809)
shimscript = "#{staged_path}/webkit.wrapper.sh"
binary shimscript, target: 'webkit'
preflight do
IO.write shimscript, <<~EOS
#!/bin/bash
cd "$(dirname "$(readlink -n "${0}")")" && \
'#{staged_path}/run-webkit-archive' "${@}"
EOS
end
end
|
using FluentValidation.TestHelper;
using NUnit.Framework;
using System;
using ygo.application.Commands.AddBanlist;
using ygo.tests.core;
namespace ygo.application.unit.tests.ValidatorsTests.Commands
{
[TestFixture]
[Category(TestType.Unit)]
public class AddBanlistCommandValidatorTests
{
private AddBanlistCommandValidator _sut;
[SetUp]
public void SetUp()
{
_sut = new AddBanlistCommandValidator();
}
[TestCase(-1)]
[TestCase(0)]
public void Given_An_Invalid_Id_Validation_Should_Fail(long id)
{
// Arrange
var command = new AddBanlistCommand { Id = id };
// Act
Action act = () => _sut.ShouldHaveValidationErrorFor(b => b.Id, command);
// Assert
act.Invoke();
}
[TestCase(-1)]
[TestCase(0)]
public void Given_An_Invalid_FormatId_Validation_Should_Fail(long formatId)
{
// Arrange
var command = new AddBanlistCommand { FormatId = formatId };
// Act
Action act = () => _sut.ShouldHaveValidationErrorFor(b => b.FormatId, command);
// Assert
act.Invoke();
}
[TestCase(null)]
[TestCase("")]
[TestCase(" ")]
public void Given_An_Invalid_Name_Validation_Should_Fail(string name)
{
// Arrange
var command = new AddBanlistCommand { Name = name };
// Act
Action act = () => _sut.ShouldHaveValidationErrorFor(b => b.Name, command);
// Assert
act.Invoke();
}
[Test]
public void Given_An_Invalid_Release_Validation_Should_Fail()
{
// Arrange
var command = new AddBanlistCommand();
// Act
Action act = () => _sut.ShouldHaveValidationErrorFor(b => b.ReleaseDate, command);
// Assert
act.Invoke();
}
[Test]
public void Given_An_Name_Greater_Than_255_Validation_Should_Fail()
{
// Arrange
var command = new AddBanlistCommand { Name = new string('*', 256) };
// Act
Action act = () => _sut.ShouldHaveValidationErrorFor(b => b.Name, command);
// Assert
act.Invoke();
}
}
}
|
import {Injectable} from '@angular/core';
import {Subject} from "rxjs/Subject";
import {Observable} from "rxjs/Observable";
@Injectable()
export class NotificationServiceProvider {
private notification = new Subject<any>();
sendNotification(body: any) {
this.notification.next(body);
}
getNotification(): Observable<any> {
return this.notification.asObservable();
}
}
|
package com.twu.biblioteca.utils;
public class StringUtils {
private static final String DOTS = "...";
private static final String SPACE = " ";
public static String smooth(String str, int controlLength) {
if (str.length() > controlLength) {
return str.substring(0, controlLength - 3).concat(DOTS);
}
StringBuilder nameBuilder = new StringBuilder(str);
for (int i = 0; i < controlLength - str.length(); i++) {
nameBuilder.append(SPACE);
}
return nameBuilder.toString();
}
}
|
package controllers
import javax.inject.Inject
import com.mohiva.play.silhouette.api.{Environment, Silhouette}
import com.mohiva.play.silhouette.impl.authenticators.SessionAuthenticator
import controllers.headers.ProvidesHeader
import formats.json.LabelFormats._
import models.label._
import models.user.User
import play.api.libs.json._
import play.api.mvc.Action
import scala.concurrent.Future
class LabelController @Inject() (implicit val env: Environment[User, SessionAuthenticator])
extends Silhouette[User, SessionAuthenticator] with ProvidesHeader {
/**
*
* @param regionId Region id
* @return
*/
def getLabelsFromCurrentMission(regionId: Int) = UserAwareAction.async { implicit request =>
request.identity match {
case Some(user) =>
val labels = LabelTable.getLabelsFromCurrentAuditMission(regionId, user.userId)
val jsLabels = JsArray(labels.map(l => Json.toJson(l)))
Future.successful(Ok(jsLabels))
case None =>
Future.successful(Redirect(s"/anonSignUp?url=/label/currentMission?regionId=$regionId"))
}
}
/**
* Gets all tags in the database in JSON.
*
* @return
*/
def getLabelTags() = Action.async { implicit request =>
Future.successful(Ok(JsArray(TagTable.selectAllTags().map { tag => Json.obj(
"tag_id" -> tag.tagId,
"label_type" -> LabelTypeTable.labelTypeIdToLabelType(tag.labelTypeId),
"tag" -> tag.tag
)})))
}
}
|
package main
import (
"strings"
"testing"
)
func checkSolve(file string, expected []string, unexpected []string, cacheUpdate bool, t *testing.T) {
candidates := loadCandidates(cacheUpdate)
r, err := solveImports(candidates, file)
if err != nil {
t.Fatal(err)
}
for _, exp := range expected {
if !strings.Contains(string(r), exp) {
t.Fatalf("Expected %s in result, got %s", exp, r)
}
}
for _, unexp := range unexpected {
if strings.Contains(string(r), unexp) {
t.Fatalf("Unexpected %s in result, got %s", unexp, r)
}
}
}
func TestComplexFile(t *testing.T) {
expected := []string{
"bytes",
"fmt",
"go/ast",
"go/format",
"go/token",
"os",
"reflect",
"strconv",
}
checkSolve("tests/fix_test.go", expected, []string{}, true, t)
}
func TestSolveAddImports(t *testing.T) {
expected := []string{
"\"fmt\"",
"\"go/ast\"",
"A comment",
}
checkSolve("tests/add_imports.go", expected, []string{}, false, t)
}
func TestRemoveUseless(t *testing.T) {
unexpected := []string{"\"os\""}
checkSolve("tests/remove_imports.go", []string{}, unexpected, false, t)
}
|
using System.Diagnostics;
/// <summary>
/// Gets and sets the product and the quantity of that product and displays the result in the cart.
/// </summary>
/// <author>Kathryn Browning</author>
/// <version>January 17, 2015</version>
public class CartItem
{
private Product _product;
private int _quantity;
/// <summary>
/// Initializes a new instance of the <see cref="CartItem"/> class.
/// </summary>
public CartItem() {}
/// <summary>
/// Initializes a new instance of the <see cref="CartItem"/> class.
/// </summary>
/// <param name="product">The product.</param>
/// <param name="quantity">The quantity.</param>
public CartItem(Product product, int quantity)
{
this.Product = product;
this.Quantity = quantity;
}
/// <summary>
/// Gets or sets the product.
/// </summary>
/// <value>
/// The product.
/// </value>
public Product Product
{
get { return this._product; }
set
{
Trace.Assert(value != null, "Invalid Product.");
this._product = value;
}
}
/// <summary>
/// Gets or sets the quantity.
/// </summary>
/// <value>
/// The quantity.
/// </value>
public int Quantity
{
get { return this._quantity; }
set
{
Trace.Assert(true, "Invalid Quantity of Item.");
this._quantity = value;
}
}
/// <summary>
/// Adds the quantity.
/// </summary>
/// <param name="quantity">The quantity.</param>
public void AddQuantity(int quantity)
{
this.Quantity += quantity;
}
/// <summary>
/// Displays this instance.
/// </summary>
/// <returns>How many of an item were selected, the item name, and how much an item costs</returns>
public string Display()
{
var displayString = string.Format("{0} ({1} at {2} each)",
this.Product.Name, this.Quantity.ToString(),
this.Product.UnitPrice.ToString("c"));
return displayString;
}
}
|
package partyrobot
// Welcome greets a person by name.
func Welcome(name string) string {
panic("Please implement the Welcome function")
}
// HappyBirthday wishes happy birthday to the birthday person and stands out his age.
func HappyBirthday(name string, age int) string {
panic("Please implement the HappyBirthday function")
}
// AssignTable assigns a table to each guest.
func AssignTable(name string, table int, neighbour, direction string, distance float64) string {
panic("Please implement the AssignTable function")
}
|
package bot.features.poll.model.results
import bot.features.poll.model.Poll
sealed class PollCreationResult {
object NotEnoughOptions : PollCreationResult()
object TooManyOptions : PollCreationResult()
object InvalidMaxAnswers : PollCreationResult()
data class PollCreated(val poll: Poll) : PollCreationResult()
}
|
package com.eudycontreras.calendarheatmaplibrary.common
import com.eudycontreras.calendarheatmaplibrary.DrawTarget
import com.eudycontreras.calendarheatmaplibrary.properties.RenderData
/**
* Copyright (C) 2020 Project X
*
* @Project ProjectX
* @author Eudy Contreras.
* @since April 2020
*/
interface DrawOverlay {
val overlayWidth: Float
val overlayHeight: Float
fun reDraw()
fun getRenderData(): RenderData
fun setRenderData(renderData: RenderData)
fun registerDrawTarget(drawTarget: DrawTarget)
fun unregisterDrawTarget(drawTarget: DrawTarget)
}
|
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const apiMetrics = require('prometheus-api-metrics');
app.use(apiMetrics())
app.use(bodyParser.json()); // for parsing application/json
app.post('/', (req, res) => {
if (!req.body) return res.sendStatus(400);
data = JSON.stringify(req.body);
console.log("received from front end " + data + "; echoing back");
res.send(data);
})
app.listen(process.env.APP_PORT, () => {
console.log('listening on ' + process.env.APP_PORT)
});
|
#ifndef REFLECT_HPP
#define REFLECT_HPP
#include "meta_utils/meta_utils.hpp"
#include "reflect_information/reflect_information.hpp"
#include "reflect_utils/reflect_utils.hpp"
/**
* @brief Reflection namespace
* @todo add old examples
* @todo serialization examples (console, json)
* @todo performance benchmarks
* @todo compile time benchmarks
* @todo memorization
* @todo Runtime reflection
* @todo Reflect constructors
* @todo Signals
* @todo Slots
* @todo Parameters
* @todo Enums
*/
namespace reflect {
using All = info::DefaultIndexGenerator; /**< All metainformation */
using AllVars = info::VariableIndexGenerator<All>; /**< All vars */
using ObjVars = info::ObjectIndexGenerator<AllVars>; /**< Object vars */
using StaticVars = info::StaticIndexGenerator<AllVars>; /**< Static vars */
using AllMethods = info::MethodIndexGenerator<All>; /**< All methods */
using ObjMethods =
info::ObjectIndexGenerator<AllMethods>; /**< Object methods */
using ConstMethods =
info::ConstMethodIndexGenerator<ObjMethods>; /**< Const methods */
using StaticMethods =
info::StaticIndexGenerator<AllMethods>; /**< Static methods */
} // namespace reflect
#endif // UTILS_HPP
|
import React, { useEffect, useRef, useState } from "react";
import { BootstrapTable, TableHeaderColumn } from "react-bootstrap-table";
import { Button } from "react-bootstrap";
import { Link } from "react-router-dom";
const MyList = ({
items,
children,
onDelete,
onSelect,
pagination,
createLink,
page,
sizePerPage,
totalCnt,
onChangePage,
}) => {
const [selected, setSelected] = useState([]);
const options = {
page: page,
sizePerPage: 20,
onPageChange: onChangePage,
onRowClick: function (row, columnIndex, rowIndex, e) {
onSelect(row.id);
},
};
function selectedDelete() {
onDelete(selected.map((result) => result.id));
}
function onRowSelect(row, isSelected) {
if (isSelected) {
setSelected(selected.concat(row));
} else {
setSelected(selected.filter((item) => item.id !== row.id));
}
}
async function onSelectAll(isSelected, currentDisplayAndSelectedData) {
if (isSelected) {
await setSelected([]);
setSelected(currentDisplayAndSelectedData);
} else {
await setSelected([]);
}
}
const selectRowProp = {
mode: "checkbox",
onSelect: onRowSelect,
onSelectAll: onSelectAll,
};
return (
<>
<BootstrapTable
data={items}
options={options}
selectRow={selectRowProp}
pagination={pagination}
fetchInfo={{ dataTotalSize: totalCnt }}
remote
>
{children}
</BootstrapTable>
<Link to={createLink}>
<Button variant="primary">생성</Button>
</Link>
{selected.length > 0 && (
<Button variant="danger" onClick={() => selectedDelete()}>
삭제
</Button>
)}
</>
);
};
export default MyList;
|
package com.kotlinbyte.infrastructure.datasource.remote.networking
import com.kotlinbyte.domain.vobject.AuthResult
import com.kotlinbyte.infrastructure.datasource.local.UserCredentialsLocalDataSource
import io.mockk.*
import junit.framework.Assert.assertEquals
import okhttp3.Interceptor
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import org.junit.After
import org.junit.Before
import org.junit.Test
class OkHttpExtTest {
companion object {
const val FAKE_TOKEN = "MINEIONINCEINCONEC"
}
private lateinit var requestSlot: CapturingSlot<Request>
private lateinit var mockedUserCredentialsProvider: UserCredentialsLocalDataSource
private lateinit var interceptor: Interceptor
private lateinit var mockedChain: Interceptor.Chain
@Before
fun setup() {
mockedUserCredentialsProvider = mockk()
mockedChain = mockk()
interceptor = OkHttpInterceptor(mockedUserCredentialsProvider)
requestSlot = slot()
val request = Request.Builder().url(EndPoints.BASE_URL).build()
coEvery { mockedUserCredentialsProvider.getAuth() } returns AuthResult(FAKE_TOKEN)
every { mockedChain.proceed(capture(requestSlot)) } answers {
with(Response.Builder()) {
protocol(Protocol.HTTP_2)
request(request)
code(300)
message("")
build()
}
}
}
@Test
fun `should contain auth header`() {
val endpoints =
EndPoints.authRequiredEndpointsList.filter { EndPoints.authenticationRequired(it) }
endpoints.forEach {
val request = with(Request.Builder()) {
url("${EndPoints.BASE_URL}${it}")
build()
}
val expectedRequest = with(request.newBuilder()) {
addHeader(HttpHeaders.AUTHORIZATION, FAKE_TOKEN)
build()
}
every { mockedChain.request() } returns request
interceptor.intercept(mockedChain)
assertEquals(
expectedRequest.headers(),
requestSlot.captured.headers()
)
}
}
@After
fun tearDown() {
clearAllMocks()
}
}
|
package io.eels.component.csv
import java.io.{BufferedInputStream, ByteArrayInputStream, File, InputStream}
import java.nio.file.{Files, StandardOpenOption}
import com.sksamuel.exts.io.Using
import com.typesafe.config.{Config, ConfigFactory}
import io.eels._
import io.eels.datastream.Publisher
import io.eels.schema.StructType
import org.apache.hadoop.fs.{FileSystem, Path}
case class CsvSource(inputFn: () => InputStream,
overrideSchema: Option[StructType] = None,
format: CsvFormat = CsvFormat(),
inferrer: SchemaInferrer = StringInferrer,
ignoreLeadingWhitespaces: Boolean = true,
ignoreTrailingWhitespaces: Boolean = true,
skipEmptyLines: Boolean = true,
emptyCellValue: String = null,
nullValue: String = null,
header: Header = Header.FirstRow,
skipRows: Option[Long] = None,
selectedColumns: Seq[String] = Seq.empty) extends Source with Using {
val config: Config = ConfigFactory.load()
def withSchemaInferrer(inferrer: SchemaInferrer): CsvSource = copy(inferrer = inferrer)
// sets whether this source has a header and if so where to read from
def withHeader(header: Header): CsvSource = copy(header = header)
def withSchema(schema: StructType): CsvSource = copy(overrideSchema = Some(schema))
def withDelimiter(c: Char): CsvSource = copy(format = format.copy(delimiter = c))
def withQuoteChar(c: Char): CsvSource = copy(format = format.copy(quoteChar = c))
def withQuoteEscape(c: Char): CsvSource = copy(format = format.copy(quoteEscape = c))
def withFormat(format: CsvFormat): CsvSource = copy(format = format)
// use this value when the cell/record is empty quotes in the source data
def withEmptyCellValue(emptyCellValue: String): CsvSource = copy(emptyCellValue = emptyCellValue)
// use this value when the cell/record is empty in the source data
def withNullValue(nullValue: String): CsvSource = copy(nullValue = nullValue)
def withSkipEmptyLines(skipEmptyLines: Boolean): CsvSource = copy(skipEmptyLines = skipEmptyLines)
def withIgnoreLeadingWhitespaces(ignore: Boolean): CsvSource = copy(ignoreLeadingWhitespaces = ignore)
def withIgnoreTrailingWhitespaces(ignore: Boolean): CsvSource = copy(ignoreTrailingWhitespaces = ignore)
def withSkipRows(count: Long): CsvSource = copy(skipRows = Some(count))
private def createParser() = {
CsvSupport.createParser(
format,
ignoreLeadingWhitespaces,
ignoreTrailingWhitespaces,
skipEmptyLines,
emptyCellValue,
nullValue,
skipRows,
selectedColumns
)
}
override def schema: StructType = overrideSchema.getOrElse {
val parser = createParser()
val in = inputFn()
try {
parser.beginParsing(in, "UTF-8")
val headers = header match {
case Header.None =>
// read the first row just to get the count of columns, then we'll call them column 1,2,3,4 etc
// todo change the column labels to a,b,c,d
val records = parser.parseNext()
(0 until records.size).map(_.toString).toList
case Header.FirstComment =>
while (parser.getContext.lastComment() == null && parser.parseNext() != null) {
}
val str = Option(parser.getContext.lastComment).getOrElse("").stripPrefix("#")
str.split(format.delimiter).toList
case Header.FirstRow =>
val row = parser.parseNext().toList
logger.debug(s"First row for header is $row")
row
}
inferrer.struct(headers)
} finally {
parser.stopParsing()
}
}
override def parts(): Seq[Publisher[Seq[Row]]] = {
val part = new CsvPublisher(createParser _, inputFn, header, schema)
List(part)
}
}
object CsvSource {
def apply(bytes: Array[Byte]): CsvSource = apply(() => new ByteArrayInputStream(bytes) {
override def close(): Unit = {
super.close()
}
})
def apply(path: Path)(implicit fs: FileSystem): CsvSource = apply(() => fs.open(path))
def apply(file: File): CsvSource = apply(file.toPath)
def apply(path: java.nio.file.Path): CsvSource = CsvSource(() => new BufferedInputStream(Files.newInputStream(path, StandardOpenOption.READ)))
}
|
/**
* Class decorator factory for describing an API.
*
* ```ts
* @api({ name: "Company API" })
* class CompanyApi {}
* ```
*
* @param config configuration
*/
export function api(config: ApiConfig) {
return (target: any) => {};
}
export interface ApiConfig {
/** Name of the API. This should be the name of the service that is being documented */
name: string;
}
|
package services
import concurrent._
import concurrent.duration._
import akka.actor.{ActorRef, Props}
import akka.util.Timeout
import akka.pattern.ask
import play.api.libs.concurrent.Akka
import play.api.libs.concurrent.Execution.Implicits._
import play.api.Play.current
import services.actors._
import models._
/**
* Not most elegant and specific name, but try to enforce
* separation between command and query/search
* per CQRS architecture
*
*/
trait SearchService extends misc.Logging {
def findAll(): Seq[ProductData]
def findByEan(ean: Long): Option[ProductData]
def findProductsInWarehouseAndName(name: String, warehouse: WarehouseData): Seq[ProductData]
}
class SearchServiceImpl extends SearchService {
def findAll(): Seq[ProductData] = {
Product.findAll
}
def findByEan(ean: Long): Option[ProductData] = {
Product.findByEan(ean)
}
def findProductsInWarehouseAndName(name: String, warehouse: WarehouseData): Seq[ProductData] = {
Product.findProductsInWarehouseAndName(name, warehouse)
}
}
|
import unittest
class Solution:
"""
This solution iterates over the string from the left to the right and constructs
a dictionary where each key is an index to the string and the value indicates
how many zeroes and ones are present to the left of the index. Once the dictionary
has been constructed it is iterated over to find the position where the sum of
zeroes_at_index + (total_ones - ones_at_index)
is maximized.
"""
def maxScore(self, s: str) -> int:
counts = {}
ones = 0
zeroes = 0
for i, digit in enumerate(s):
if digit == "1":
ones += 1
else:
zeroes += 1
counts[i] = (ones, zeroes)
total_ones = ones
max_sum = -1
for i in range(len(s) - 1):
ones, zeroes = counts[i]
sum_ = zeroes + (total_ones - ones)
if sum_ > max_sum:
max_sum = sum_
return max_sum
class TestSolution(unittest.TestCase):
def test_first_example(self):
self.assertEqual(Solution().maxScore("011101"), 5)
def test_second_example(self):
self.assertEqual(Solution().maxScore("00111"), 5)
def test_third_example(self):
self.assertEqual(Solution().maxScore("1111"), 3)
def test_fourth_example(self):
self.assertEqual(Solution().maxScore("00"), 1)
|
# Curso-Práctico de Javascript
...
## Taller #1: Figuras geométricas
-Primer paso: definir las formas geométricas
-Segundo paso: Implementar las formulas en JS
-Tercer paso: Crear funciones
-Cuarto paso: Integrar JS con HTML
-Quinto paso: Encontrar el perimetro y área de cada figura geometrica
## Taller #2: Descuentos de productos
-Primer paso: Definir el precio del producto
-Segundo paso: Implementar las formulas en JS
-Tercer paso: Crear funciones
-Cuarto paso: Integrar JS con HTML
-Quinto paso: Seleccionar un cupon disponible
-Sexto paso: Encontrar el valor total de acuerdo al cupon de descuento
## Taller #3: Ahorro mensual
-Primer paso: Definir los parámetros a evaluar
-Segundo paso: Implementar las formulas en JS
-Tercer paso: Crear funciones
-Cuarto paso: Integrar JS con HTML
-Quinto paso: Encontrar el valor total del ahorro de la familia en función del ingreso
-Sexto paso: Encontrar el valor promedio ganado anualmente de la familia
|
=begin
This file is part of the Arachni-RPC project and may be subject to
redistribution and commercial restrictions. Please see the Arachni-RPC
web site for more information on licensing and terms of use.
=end
module Toq
# Represents an RPC message, serves as the basis for {Request} and {Response}.
#
# @author Tasos "Zapotek" Laskos <tasos.laskos@arachni-scanner.com>
class Message
# @param [Hash] opts
# Sets instance attributes.
def initialize( opts = {} )
opts.each_pair { |k, v| send( "#{k}=".to_sym, v ) }
end
# Merges the attributes of another message with self.
#
# (The param doesn't *really* have to be a message, any object will do.)
#
# @param [Message] message
def merge!( message )
message.instance_variables.each do |var|
val = message.instance_variable_get( var )
instance_variable_set( var, val )
end
end
# Prepares the message for transmission (i.e. converts the message to a `Hash`).
#
# Attributes that should not be included can be skipped by implementing
# {#transmit?} and returning the appropriate value.
#
# @return [Hash]
def prepare_for_tx
instance_variables.inject({}) do |h, k|
h[normalize( k )] = instance_variable_get( k ) if transmit?( k )
h
end
end
# Decides which attributes should be skipped by {#prepare_for_tx}.
#
# @param [Symbol] attr
# Instance variable symbol (i.e. `:@token`).
def transmit?( attr )
true
end
private
def normalize( attr )
attr.to_s.gsub( '@', '' )
end
end
end
|
use chrono::{DateTime, Utc};
use futures::{Stream, StreamExt};
use std::{
fmt::{self, Display, Formatter},
str::FromStr,
task::Poll,
time::Duration,
};
#[derive(Clone, Copy)]
pub enum Color {
Black,
Red,
Green,
Yellow,
Blue,
Purple,
Cyan,
White,
Fixed(u8),
}
impl Display for Color {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Color::Black => f.write_str("40"),
Color::Red => f.write_str("41"),
Color::Green => f.write_str("42"),
Color::Yellow => f.write_str("43"),
Color::Blue => f.write_str("44"),
Color::Purple => f.write_str("45"),
Color::Cyan => f.write_str("46"),
Color::White => f.write_str("47"),
Color::Fixed(num) => write!(f, "48;5;{}", num),
}
}
}
impl FromStr for Color {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let color = match s.trim().to_ascii_lowercase().as_str() {
"black" => Color::Black,
"red" => Color::Red,
"green" => Color::Green,
"yellow" => Color::Yellow,
"blue" => Color::Blue,
"purple" => Color::Purple,
"cyan" => Color::Cyan,
"white" => Color::White,
s if s.chars().all(|c| c.is_ascii_digit()) => {
Color::Fixed(s.parse::<u8>().map_err(|e| e.to_string())?)
}
_ => return Err("Unknown color".to_owned()),
};
Ok(color)
}
}
enum Ansi {
ClearScreen,
Goto(u16, u16),
SetColor(Color),
ResetStyle,
}
impl Display for Ansi {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Ansi::ClearScreen => f.write_str("\u{001b}c"),
Ansi::Goto(x, y) => write!(f, "\x1B[{};{}H", y + 1, x + 1),
Ansi::SetColor(c) => write!(f, "\x1B[{}m", c),
Ansi::ResetStyle => f.write_str("\x1B[0m"),
}
}
}
const NUMBER_WIDTH: u16 = 6;
const NUMBER_HEIGHT: u16 = 5;
const NUMBER_TABLE: [[bool; NUMBER_WIDTH as usize / 2 * NUMBER_HEIGHT as usize]; 10] = {
const X: bool = true;
const O: bool = false;
[
[X, X, X, X, O, X, X, O, X, X, O, X, X, X, X], // 0
[O, O, X, O, O, X, O, O, X, O, O, X, O, O, X], // 1
[X, X, X, O, O, X, X, X, X, X, O, O, X, X, X], // 2
[X, X, X, O, O, X, X, X, X, O, O, X, X, X, X], // 3
[X, O, X, X, O, X, X, X, X, O, O, X, O, O, X], // 4
[X, X, X, X, O, O, X, X, X, O, O, X, X, X, X], // 5
[X, X, X, X, O, O, X, X, X, X, O, X, X, X, X], // 6
[X, X, X, O, O, X, O, O, X, O, O, X, O, O, X], // 7
[X, X, X, X, O, X, X, X, X, X, O, X, X, X, X], // 8
[X, X, X, X, O, X, X, X, X, O, O, X, X, X, X], // 9
]
};
fn format_number(
f: &mut Formatter<'_>,
number: usize,
left: u16,
top: u16,
color: Color,
) -> fmt::Result {
let table = &NUMBER_TABLE[number];
let mut i = 0;
let mut filled = false;
for y in 0..NUMBER_HEIGHT {
write!(f, "{}", Ansi::Goto(left, top + y))?;
for _ in 0..NUMBER_WIDTH / 2 {
if table[i] {
if !filled {
write!(f, "{}", Ansi::SetColor(color))?;
filled = true;
}
} else if filled {
write!(f, "{}", Ansi::ResetStyle)?;
filled = false;
}
f.write_str(" ")?;
i += 1;
}
}
write!(f, "{}", Ansi::ResetStyle)
}
struct Clockface {
datetime: DateTime<Utc>,
color: Color,
}
impl Display for Clockface {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
const LEFT_MARGIN: u16 = 0;
const TOP_MARGIN: u16 = 1;
let mut unix_time = self.datetime.timestamp();
let mut digits = Vec::new();
while unix_time > 0 {
digits.push(unix_time % 10);
unix_time /= 10;
}
const STEP: u16 = NUMBER_WIDTH + 1;
for (i, d) in digits.iter().rev().enumerate() {
format_number(
f,
*d as usize,
LEFT_MARGIN + i as u16 * STEP,
TOP_MARGIN,
self.color,
)?;
}
let datetime_str = self
.datetime
.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
write!(
f,
"{}{}{}",
Ansi::Goto(
LEFT_MARGIN
+ (digits.len() as u16 * STEP).saturating_sub(datetime_str.len() as u16) / 2,
TOP_MARGIN + NUMBER_HEIGHT + 1
),
datetime_str,
Ansi::Goto(0, TOP_MARGIN + NUMBER_HEIGHT + 2)
)
}
}
pub fn clock_stream(color: Color) -> impl Stream<Item = String> {
let mut interval = tokio::time::interval(Duration::from_secs(1));
let stream = futures::stream::poll_fn(move |cx| match interval.poll_tick(cx) {
Poll::Ready(_) => {
let response = Clockface {
datetime: Utc::now(),
color,
}
.to_string();
Poll::Ready(Some(response))
}
Poll::Pending => Poll::Pending,
});
futures::stream::once(async { Ansi::ClearScreen.to_string() }).chain(stream)
}
|
<?php
namespace Opportus\Orm;
/**
* The model factory...
*
* @version 0.0.1
* @package Opportus\Orm
* @author Clément Cazaud <opportus@gmail.com>
*/
class Factory
{
/**
* @var array $modelProperties
*/
protected $modelProperties;
/**
* @var array $modelPropertyValidationCallbacks
*/
protected $modelPropertyValidationCallbacks;
/**
* Constructor.
*
* @param array $modelProperties
* @param array $modelPropertyValidationCallbacks
*/
public function __construct(array $modelProperties, array $modelPropertyValidationCallbacks)
{
$this->modelProperties = $modelProperties;
$this->modelPropertyValidationCallbacks = $modelPropertyValidationCallbacks;
}
/**
* Creates a model.
*
* @param array $data Default:array()
* @return Model
*/
public function create(array $data = array())
{
return new Model($this->modelProperties, $this->modelPropertyValidationCallbacks, $data);
}
}
|
# frozen_string_literal: true
module Dmpopidor
module Models
module Plan
include DynamicFormHelper
# CHANGES : ADDED RESEARCH OUTPUT SUPPORT
# The most recent answer to the given question id optionally can create an answer if
# none exists.
#
# qid - The id for the question to find the answer for
# roid - The id for the research output to find the answer for
# create_if_missing - If true, will genereate a default answer
# to the question (defaults: true).
#
# Returns Answer
# Returns nil
def answer(qid, create_if_missing = true, roid = nil)
answer = answers.where(question_id: qid, research_output_id: roid).order("created_at DESC").first
question = ::Question.find(qid)
if answer.nil? && create_if_missing
answer = Answer.new
answer.plan_id = id
answer.question_id = qid
answer.text = question.default_value
default_options = []
question.question_options.each do |option|
default_options << option if option.is_default
end
answer.question_options = default_options
end
answer
end
# determines if the plan is reviewable by the specified user
#
# user_id - The Integer id for the user
#
# Returns Boolean
# CHANGES : Reviewer can be from a different org of the plan owner
def reviewable_by?(user_id)
reviewer = ::User.find(user_id)
feedback_requested? &&
reviewer.present? &&
reviewer.can_review_plans?
end
##
# Sets up the plan for feedback:
# emails confirmation messages to owners
# emails org admins and org contact
# adds org admins to plan with the 'reviewer' Role
# CHANGES : Added feedback_requestor & request_date columns
# def request_feedback(user)
# ::Plan.transaction do
# begin
# self.feedback_requested = true
# self.feedback_requestor = user
# self.feedback_request_date = DateTime.current()
# if save!
# # Send an email to the org-admin contact
# if user.org.contact_email.present?
# contact = ::User.new(email: user.org.contact_email,
# firstname: user.org.contact_name)
# UserMailer.feedback_notification(contact, self, user).deliver_now
# end
# return true
# else
# return false
# end
# rescue Exception => e
# Rails.logger.error e
# return false
# end
# end
# end
##
# Finalizes the feedback for the plan: Emails confirmation messages to owners
# sets flag on plans.feedback_requested to false removes org admins from the
# 'reviewer' Role for the Plan.
# CHANGES : Added feedback_requestor & request_date columns
def complete_feedback(org_admin)
::Plan.transaction do
begin
self.feedback_requested = false
self.feedback_requestor = nil
self.feedback_request_date = nil
if save!
# Send an email confirmation to the owners and co-owners
deliver_if(recipients: owner_and_coowners,
key: "users.feedback_provided") do |r|
UserMailer.feedback_complete(
r,
self,
org_admin).deliver_now
end
true
else
false
end
rescue ArgumentError => e
Rails.logger.error e
false
end
end
end
# The number of research outputs for a plan.
#
# Returns Integer
def num_research_outputs
research_outputs.count
end
# Return the JSON Fragment linked to the Plan
#
# Returns JSON
def json_fragment
Fragment::Dmp.where("(data->>'plan_id')::int = ?", id).first
end
def create_plan_fragments
template_locale = template.locale.eql?("en_GB") ? "eng" : "fra"
plan_owner = owner
FastGettext.with_locale template.locale do
dmp_fragment = Fragment::Dmp.create(
data: {
"plan_id" => id
},
madmp_schema: MadmpSchema.find_by(name: "DMPStandard"),
additional_info: {}
)
#################################
# PERSON & CONTRIBUTORS FRAGMENTS
#################################
person_data = {
"nameType" => d_("dmpopidor", "Personal"),
"lastName" => plan_owner.surname,
"firstName" => plan_owner.firstname,
"mbox" => plan_owner.email
} unless plan_owner.nil?
person = Fragment::Person.create(
data: person_data || {},
dmp_id: dmp_fragment.id,
madmp_schema: MadmpSchema.find_by(name: "PersonStandard"),
additional_info: { property_name: "person" }
)
dmp_coordinator = Fragment::Contributor.create(
data: {
"person" => { "dbid" => person.id },
"role" => d_("dmpopidor", "DMP manager")
},
dmp_id: dmp_fragment.id,
parent_id: nil,
madmp_schema: MadmpSchema.find_by(name: "DMPCoordinator"),
additional_info: { property_name: "contact" }
)
project_coordinator = Fragment::Contributor.create(
data: {
"person" => { "dbid" => person.id },
"role" => d_("dmpopidor", "Project coordinator")
},
dmp_id: dmp_fragment.id,
parent_id: nil,
madmp_schema: MadmpSchema.find_by(name: "PrincipalInvestigator"),
additional_info: { property_name: "principalInvestigator" }
)
#################################
# META & PROJECT FRAGMENTS
#################################
project = Fragment::Project.create(
data: {
"title" => title,
"description" => description,
"principalInvestigator" => { "dbid" => project_coordinator.id }
},
dmp_id: dmp_fragment.id,
parent_id: dmp_fragment.id,
madmp_schema: MadmpSchema.find_by(name: "ProjectStandard"),
additional_info: { property_name: "project" }
)
project.instantiate
meta = Fragment::Meta.create(
data: {
"title" => d_("dmpopidor", "\"%{project_title}\" project DMP") % { project_title: title },
"creationDate" => created_at.strftime("%F"),
"lastModifiedDate" => updated_at.strftime("%F"),
"dmpLanguage" => template_locale,
"dmpId" => identifier,
"contact" => { "dbid" => dmp_coordinator.id }
},
dmp_id: dmp_fragment.id,
parent_id: dmp_fragment.id,
madmp_schema: MadmpSchema.find_by(name: "MetaStandard"),
additional_info: { property_name: "meta" }
)
meta.instantiate
dmp_coordinator.update(parent_id: meta.id)
project_coordinator.update(parent_id: project.id)
end
end
def copy_plan_fragments(plan)
create_plan_fragments if json_fragment.nil?
incoming_dmp = plan.json_fragment
raw_project = incoming_dmp.project.get_full_fragment
raw_meta = incoming_dmp.meta.get_full_fragment
raw_meta = raw_meta.merge(
"title" => "Copy of " + raw_meta["title"]
)
json_fragment.project.raw_import(raw_project, json_fragment.project.madmp_schema)
json_fragment.meta.raw_import(raw_meta, json_fragment.meta.madmp_schema)
end
end
end
end
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
module Reflex.Material.Menu
( mdSimpleMenu
, mdMenuItem
, mdMenuDivider
) where
import Data.Monoid ((<>), mempty)
import Data.Map (Map)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Map as M
import Reflex.Dom
import Reflex.Material.Framework (attachSimpleMenu)
data MdSimpleMenu t k = MdSimpleMenu
{ _mdSimpleMenu_isOpen :: Dynamic t Bool
, _mdSimpleMenu_change :: Event t Bool
, _mdSimpleMenu_select :: Event t k
}
data MdSimpleMenuConfig t k = MdSimpleMenuConfig
{ _mdSimpleMenuConfig_show :: Event t k
, _mdSimpleMenuConfig_attributes :: Dynamic t (Map Text Text)
}
mdSimpleMenu :: MonadWidget t m => Event t Bool -> m a -> m (Event t Int)
mdSimpleMenu eOpen items = do
(el, _) <- elAttr' "div" attrs items
attachSimpleMenu eOpen el
where
attrs = "class" =: "mdc-simple-menu" <>
"tabindex" =: "-1" <>
"style" =: "position: absolute;"
mdMenuItem :: MonadWidget t m => Text -> m (Event t ())
mdMenuItem label = do
(el, _) <- elAttr' "li" attrs $ text label
return $ () <$ domEvent Click el
where attrs = "class" =: "mdc-list-item" <>
"role" =: "menuitem" <>
"tabindex" =: "0"
mdMenuDivider :: MonadWidget t m => m ()
mdMenuDivider = elAttr "li" ("class" =: "mdc-list-divider" <> "role" =: "separator") blank
|
-- PHP-Auth (https://github.com/delight-im/PHP-Auth)
-- Copyright (c) delight.im (https://www.delight.im/)
-- Licensed under the MIT License (https://opensource.org/licenses/MIT)
PRAGMA foreign_keys = OFF;
-- BUILD USER TABLE
-- -----------------------------------
CREATE TABLE IF NOT EXISTS "users" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
"email" VARCHAR(249) NOT NULL,
"password" VARCHAR(255) NOT NULL,
"username" VARCHAR(100) DEFAULT NULL,
"status" INTEGER NOT NULL CHECK ("status" >= 0) DEFAULT "0",
"verified" INTEGER NOT NULL CHECK ("verified" >= 0) DEFAULT "0",
"resettable" INTEGER NOT NULL CHECK ("resettable" >= 0) DEFAULT "1",
"roles_mask" INTEGER NOT NULL CHECK ("roles_mask" >= 0) DEFAULT "0",
"registered" INTEGER NOT NULL CHECK ("registered" >= 0),
"last_login" INTEGER CHECK ("last_login" >= 0) DEFAULT NULL,
"force_logout" INTEGER NOT NULL CHECK ("force_logout" >= 0) DEFAULT "0",
CONSTRAINT "email" UNIQUE ("email")
);
-- BUILD USERS CONFIRMATION TABLE
-- -----------------------------------
CREATE TABLE IF NOT EXISTS "users_confirmations" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
"user_id" INTEGER NOT NULL CHECK ("user_id" >= 0),
"email" VARCHAR(249) NOT NULL,
"selector" VARCHAR(16) NOT NULL,
"token" VARCHAR(255) NOT NULL,
"expires" INTEGER NOT NULL CHECK ("expires" >= 0),
CONSTRAINT "selector" UNIQUE ("selector")
);
CREATE INDEX IF NOT EXISTS "users_confirmations.email_expires" ON "users_confirmations" ("email", "expires");
CREATE INDEX IF NOT EXISTS "users_confirmations.user_id" ON "users_confirmations" ("user_id");
-- BUILD USERS REMEMBERED TABLE
-- -----------------------------------
CREATE TABLE IF NOT EXISTS "users_remembered" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
"user" INTEGER NOT NULL CHECK ("user" >= 0),
"selector" VARCHAR(24) NOT NULL,
"token" VARCHAR(255) NOT NULL,
"expires" INTEGER NOT NULL CHECK ("expires" >= 0),
CONSTRAINT "selector" UNIQUE ("selector")
);
CREATE INDEX IF NOT EXISTS "users_remembered.user" ON "users_remembered" ("user");
-- BUILD USERS RESETS TABLE
-- -----------------------------------
CREATE TABLE IF NOT EXISTS "users_resets" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
"user" INTEGER NOT NULL CHECK ("user" >= 0),
"selector" VARCHAR(20) NOT NULL,
"token" VARCHAR(255) NOT NULL,
"expires" INTEGER NOT NULL CHECK ("expires" >= 0),
CONSTRAINT "selector" UNIQUE ("selector")
);
CREATE INDEX IF NOT EXISTS "users_resets.user_expires" ON "users_resets" ("user", "expires");
-- BUILD USERS THROTTLING TABLE
-- -----------------------------------
CREATE TABLE IF NOT EXISTS "users_throttling" (
"bucket" VARCHAR(44) PRIMARY KEY NOT NULL,
"tokens" REAL NOT NULL CHECK ("tokens" >= 0),
"replenished_at" INTEGER NOT NULL CHECK ("replenished_at" >= 0),
"expires_at" INTEGER NOT NULL CHECK ("expires_at" >= 0)
);
CREATE INDEX IF NOT EXISTS "users_throttling.expires_at" ON "users_throttling" ("expires_at");
-- BUILD USER PROFILES TABLE
-- -----------------------------------
CREATE TABLE IF NOT EXISTS "users_profile" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
"user" INTEGER NOT NULL CHECK ("user" >= 0),
"nickname" VARCHAR(44) PRIMARY KEY NOT NULL,
"birthdate" INTEGER NOT NULL CHECK ("birthdate" >= -1270237152)
);
-- CREATE INDEX IF NOT EXISTS "profiles.expires_at" ON "profiles" ("expires_at");
-- BUILD USER SESSIONS TABLE
-- -----------------------------------
CREATE TABLE IF NOT EXISTS "users_sessions" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
"user_id" INTEGER NOT NULL CHECK ("user_id" >= 0),
"authtoken" VARCHAR(44) PRIMARY KEY NOT NULL,
"expires_at" INTEGER NOT NULL CHECK ("expires_at" >= 0)
CONSTRAINT "email" UNIQUE ("email")
);
CREATE INDEX IF NOT EXISTS "session.expires_at" ON "users_sessions" ("expires_at");
CREATE INDEX IF NOT EXISTS "session.user_id" ON "users_sessions" ("user_id");
|
-- PREGUNTA 1
CREATE TABLESPACE TBS_AUTO
DATAFILE 'C:\TEMP\DF_VEHICULO_AUTO.DBF'
SIZE 100M;
CREATE TABLESPACE TBS_CAMIONETA
DATAFILE 'C:\TEMP\DF_VEHICULO_CAMIONETA.DBF'
SIZE 100M;
CREATE TABLESPACE TBS_BUS
DATAFILE 'C:\TEMP\DF_VEHICULO_BUS.DBF'
SIZE 100M;
CREATE TABLESPACE TBS_CAMION
DATAFILE 'C:\TEMP\DF_VEHICULO_CAMION.DBF'
SIZE 100M;
CREATE TABLE Vehiculo
(
ID NUMERIC(10),
Tipo VARCHAR(10),
Anio INT,
Placa VARCHAR(10)
)
PARTITION BY LIST( Tipo)
(PARTITION Vehiculo_Auto VALUES('AUTO') tablespace TBS_AUTO,
PARTITION Vehiculo_Camioneta VALUES ('CAMIONETA') tablespace TBS_CAMIONETA,
PARTITION Vehiculo_Bus VALUES ('BUS') tablespace TBS_BUS,
PARTITION Vehiculo_Camion VALUES('CAMION') tablespace TBS_CAMION );
-- PREGUNTA 2
INSERT INTO Vehiculo(ID,TIPO,ANIO,PLACA)
SELECT LEVEL, 'AUTO', 2017,'XYZ'
FROM DUAL CONNECT BY LEVEL < 1000000;
-- PREGUNTA 3
INSERT INTO Vehiculo(ID,TIPO,ANIO,PLACA)
SELECT LEVEL, 'BUS', 2017,'XYZ'
FROM DUAL CONNECT BY LEVEL < 500000;
-- PREGUNTA 4
SELECT * FROM Vehiculo PARTITION ( Vehiculo_Auto );
-- PREGUNTA 5
/*
INSERT INTO Vehiculo(ID,TIPO,ANIO,PLACA)
SELECT LEVEL, 'MOTOS', 2017,'MYZ'
FROM DUAL CONNECT BY LEVEL < 100000;
-- AL EJECUTAR LA CONSULTA SALE ERROR PORQUE NO HAY NINGUNA PARTICION PARA MOTOS
*/
|
import pygame
import sys; sys.path.insert(0, "..")
import tools_for_pygame as pgt
pygame.init()
__test_name__ = "gui.GUIElement.position_mode"
screen = pygame.display.set_mode((800, 600), pygame.RESIZABLE)
pygame.display.set_caption(__test_name__)
clock = pygame.time.Clock()
fps = pgt.gui.Label(pos=0, font="consolas", text_size=20, color=pgt.WHITE)
button_image1 = pgt.draw.aa_rect(
None,
pygame.Rect(0, 0, 150, 40),
pgt.WHITE,
5,
2,
pgt.GRAY(130)
)
button_image2 = pgt.draw.aa_rect(
None,
pygame.Rect(0, 0, 200, 80),
pgt.WHITE,
5,
2,
pgt.GRAY(130)
)
button_image3 = pgt.draw.aa_rect(
None,
pygame.Rect(0, 0, 100, 50),
pgt.WHITE,
5,
2,
pgt.GRAY(130)
)
button1 = pgt.gui.Button(
pos=0,
image=button_image1,
size=(150, 40),
position_mode=pgt.AUTOMATIC,
padding_top=50,
text_label=pgt.gui.Label(
pos=0,
font="consolas",
text="Hello World!",
auto_size=True,
alignment=pgt.CENTER,
pos_point=pgt.CC,
anchor_point=pgt.CC,
offset=(-2, 3)
),
func=print,
func_args=["Hello World!"]
)
button2 = pgt.gui.Button(
pos=0,
image=button_image2,
size=(200, 80),
position_mode=pgt.AUTOMATIC,
text_label=pgt.gui.Label(
pos=0,
font="consolas",
text="Really big\nHello World!",
auto_size=True,
alignment=pgt.CENTER,
pos_point=pgt.CC,
anchor_point=pgt.CC,
offset=(-2, 3)
),
func=print,
func_args=["Big Hello World!"]
)
button3 = pgt.gui.Button(
pos=0,
image=button_image3,
size=(100, 50),
padding_bottom=30,
position_mode=pgt.AUTOMATIC,
text_label=pgt.gui.Label(
pos=0,
font="consolas",
text="Hello!",
auto_size=True,
alignment=pgt.CENTER,
pos_point=pgt.CC,
anchor_point=pgt.CC,
offset=(-2, 3)
),
func=print,
func_args=["Tiny Hello World!"]
)
layout = pgt.gui.GUILayout(
pos=pgt.Pos(100),
size=(90, 400),
rel_size=(0.5, None),
bg_color=pgt.GRAY(60),
adapt_height=True,
elements={
"button1": button1,
"button2": button2,
"button3": button3
}
)
while True:
clock.tick()
fps.text = int(clock.get_fps())
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(pgt.GRAY(50))
fps.draw(screen)
layout.draw(screen)
pygame.display.update()
|
// Подключение заголовочных файлов
// из стандартной библиотеки:
#include <iostream> // ввод/вывод.
#include <windows.h> // нужно для функций SetConsoleOutputCP и SetConsoleCP.
// Переход на кириллицу:
void cyrillic() {
// Эти строки нужны для правильного отображения кириллицы:
SetConsoleOutputCP(1251);
SetConsoleCP(1251);
// Также надо изменить шрифт в консоли на Lucida Console.
// Для замены шрифта кликаете правой кнопкой на надписи «Командная строка» окна консоли.
// В открывшемся меню выбираете «Свойства».
// В появившемся окне выбираете вкладку «Шрифт» и там выбираете «Lucida Console».
}
// Использование пространства имён
// стандартной библиотеки:
using namespace std;
enum week { Sun = 0, Mon = 1, Tue = 2, Wed = 3, Thur = 4, Fri = 5, Sat = 6 };
int main() {
cyrillic(); // вкл. кириллицу.
int k;
cout << "Введите целое число k (1 <= k <= 365) -> ";
cin >> k;
if (k < 1 || k > 365) {
cout << "Ошибка! k должно быть больше/равно 1 и меньше/равно 365." << endl;
}
int d;
cout << "Введите целое число d (1 <= d <= 7) -> ";
cin >> d;
if (d < 1 || d > 7) {
cout << "Ошибка! d должно быть больше/равно 1 и меньше/равно 7." << endl;
}
cout << "1 января - ";
switch (d % 7) {
case Mon:
cout << "понедельник";
break;
case Tue:
cout << "вторник";
break;
case Wed:
cout << "среда";
break;
case Thur:
cout << "четверг";
break;
case Fri:
cout << "пятница";
break;
case Sat:
cout << "суббота";
break;
case Sun:
cout << "воскресенье";
break;
}
cout << endl;
cout << k << "-й день года - ";
switch ( ( (k % 7) + (d - 1) ) % 7 ) {
case Mon:
cout << "понедельник (рабочий день)";
break;
case Tue:
cout << "вторник (рабочий день)";
break;
case Wed:
cout << "среда (рабочий день)";
break;
case Thur:
cout << "четверг (рабочий день)";
break;
case Fri:
cout << "пятница (рабочий день)";
break;
case Sat:
cout << "суббота";
break;
case Sun:
cout << "воскресенье";
break;
}
cout << endl;
// Пауза перед выходом из программы
// (программа ждёт ввода любого символа):
cin.get();
cin.get();
// Возврат нуля,
// что означает успешное завершение программы:
return 0;
}
|
declare module 'autosize-input' {
interface Options {
miWidth: number;
}
export default function(el: HTMLElement, options?: Options): () => void;
}
|
/*
* Copyright (C) 2018 by Author: Aroudj, Samir
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the License.txt file for details.
*/
#ifndef _SCENE_TREE_NODES_H_
#define _SCENE_TREE_NODES_H_
#include <vector>
#include "Math/Vector3.h"
#include "Platform/DataTypes.h"
#include "Platform/Storage/Path.h"
#include "SurfaceReconstruction/Scene/Tree/Scope.h"
// todo comments
namespace SurfaceReconstruction
{
// forward declarations
class Occupancy;
class Samples;
/// This class models objects which are single parts / nodes of Tree instances.
class Nodes
{
public:
/** only checks the position
todo */
static inline bool contains(const Math::Vector3 &positionWS, const Math::Vector3 &nodePosWS, const Real size, const Real tolerance = 0.0f);
static uint32 getChildIndexForOffset(const Math::Vector3 &offset);
/** todo
@param stepSize If stepSize is the child node size then the child node coords of the node at nodeCoordsWS are returned.
If stepSize is the nodesize itself then the coordinates of the corners/vertices of the node at nodeCoordsWS are returned. */
static Math::Vector3 getCoords(const Math::Vector3 &nodeCoordsWS, const Real stepSize, uint32 index);
static Math::Vector3 getSideCenterPositionWS(const Scope &scope, const uint32 sideIdx, const Real stepSize);
static bool isContainer(const Scope &scope, const uint32 sampleIdx);
static inline bool isInvalidNodeIdx(const uint32 nodeIdx);
public:
Nodes(const Scope &rootScope);
Nodes(const Storage::Path &fileName);
/** todo */
void checkSamplesOrder(const Scope &rootScope) const;
/** todo */
void checkSampleIndicesOfNodes() const;
void clear();
/** todo */
void eraseSamples(const uint32 *sampleOffsets);
/** todo */
bool eraseSamplesInNodes(uint32 *sampleOffsets, const uint32 *nodeStates, const uint32 oldSampleCount, const uint8 FLAG_OF_DOOM);
/** todo scope -> nodeIdx, nodeCoordsWS, nodeSize are set to the values of the lastly processed node which is either the closest tree end on failure or the containing node on search success.
@param scope todo */
bool findContainer(Scope &scope, const uint32 sampleIdx) const;
inline uint32 getChildBlock(const uint32 nodeIdx) const;
inline Scope getChildScope(const Scope &scope, const uint32 childIdx) const;
inline Scope getChildScope(const Scope &scope, const uint32 childIdx, const Real childSize) const;
inline uint32 getCount() const;
uint32 getDepth(const uint32 nodeIdx) const;
void getLeafNodes(std::vector<uint32> &leafNodes,
const Math::Vector3 &queryPosition, const Real queryRadius, const Scope &scope) const;
uint32 getNode(Scope &scope, const Math::Vector3 &containedPositionWS, const uint32 maxDepth) const;
inline uint32 getSampleCount(const uint32 nodeIdx) const;
uint32 getSamples(uint32 &sampleCount, const uint32 nodeIdx) const;
bool intersect(const Scope &scope, bool positiveSide, const uint32 sampleIdx) const;
inline bool isLeaf(const uint32 nodeIdx) const;
void loadFromFile(const Storage::Path &fileName);
void saveToFile(const Storage::Path &fileName) const;
private:
/** Balances the empty tree structure in order to have at maximum 1 depth level difference for each pair of adjacent leaf nodes.
@param rootScope todo*/
void balance(const Scope &rootScope);
uint32 computeTargetIndices(uint32 *targetIndices,
const uint32 nodeIdx, const uint32 nextFreeAddress) const;
/** todo */
void createNodes(const Scope &rootScope);
bool createNodesForBalancing(const uint32 depth, const Scope &scope, const Scope &rootScope);
/** todo scope -> nodeIdx, nodeCoordsWS, nodeSize are set to the values of the lastly processed node which is the newly created or found node which contains the entered sample.
@param scope todo */
void createNodesForContainment(Scope &scope, const uint32 sampleIdx);
uint32 createNodesForSampling(Scope scope, const bool positiveSide, const uint32 sampleIdx);
void createChildren(const uint32 currentNodeIdx);
/** todo does not allocate additional memory but is slower. */
void eraseSamplesInNodesInSitu(Samples &samples, const uint32 *nodeStates, const uint8 FLAG_OF_DOOM);
uint32 findReliableSamplingNode(const Scope &rootScope, const bool positiveSide, const uint32 sampleIdx) const;
bool fittingSamplingNodeCenter(const Math::Vector3 &nodeCoordsWS, const Real childSize, const bool positiveSide, const uint32 sampleIdx) const;
/** Reorders nodes in memory for higher cache coherence.
Also Sets sample start and end indices (sample area in memory) for each node according to the NEW ORDER. */
void reorder();
void reorder(const uint32 *targetIndices);
/** todo *
@return Returns a copy of the scene samples, but reordered in memory according to tree structure. */
void reorderSamplesAndFillNodes(const Scope &rootScope);
/** Reserves memory for nodeCount nodes.
@param nodeCount Memory for nodeCount nodes is reserved. */
void reserve(const uint32 nodeCount);
/** Resizes arrays which contain nodes data.
@param newCount Set this to the new number of nodes. */
void resize(const uint32 newNodeCount);
public:
static const uint32 CHILD_COUNT = 8;
static const uint32 FILE_VERSION;
static const uint32 INVALID_INDEX;
static const uint32 SIDE_COUNT = 6;
private:
// data for nodes themselves, nodeIdx = 0 is always the root
std::vector<uint32> mChildren; /// For each node: link to its block of Tree::CHILD_COUNT children / link to its first child, all other indices directly follow in the same memory block.
std::vector<uint32> mParents; /// For each node: link to its parent node or Nodes::INVALID_NODE_IDX for the root node with index 0
std::vector<uint32> mSamplesPerNodes; /// For each node: number of its contained samples, see mSampleStartIndices
std::vector<uint32> mSampleStartIndices; /// For each node: start index of its contained samples w.r.t. class Samples, see mSamplesPerNodes
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// inline function definitions ////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline bool Nodes::contains(const Math::Vector3 &positionWS, const Math::Vector3 &nodePosWS, const Real size, const Real tolerance)
{
return (positionWS.x >= nodePosWS.x - tolerance &&
positionWS.x < nodePosWS.x + size + tolerance &&
positionWS.y >= nodePosWS.y - tolerance &&
positionWS.y < nodePosWS.y + size + tolerance &&
positionWS.z >= nodePosWS.z - tolerance &&
positionWS.z < nodePosWS.z + size + tolerance);
}
inline bool Nodes::isInvalidNodeIdx(const uint32 nodeIdx)
{
return (INVALID_INDEX == nodeIdx);
}
inline uint32 Nodes::getChildBlock(const uint32 nodeIdx) const
{
return mChildren[nodeIdx];
}
inline Scope Nodes::getChildScope(const Scope &scope, const uint32 childIdx) const
{
const Real childSize = scope.getSize() * 0.5f;
const Math::Vector3 childCoords = getCoords(scope.getMinimumCoordinates(), childSize, childIdx);
const uint32 globalChildIdx = childIdx + mChildren[scope.getNodeIndex()];
assert(globalChildIdx < getCount());
return Scope(childCoords, childSize, globalChildIdx);
}
inline Scope Nodes::getChildScope(const Scope &scope, const uint32 childIdx, const Real childSize) const
{
const Math::Vector3 childCoords = getCoords(scope.getMinimumCoordinates(), childSize, childIdx);
const uint32 globalChildIdx = childIdx + mChildren[scope.getNodeIndex()];
assert(globalChildIdx < getCount());
return Scope(childCoords, childSize, globalChildIdx);
}
inline uint32 Nodes::getCount() const
{
return (uint32) mChildren.size();
}
inline uint32 Nodes::getSampleCount(const uint32 nodeIdx) const
{
return mSamplesPerNodes[nodeIdx];
}
inline bool Nodes::isLeaf(const uint32 nodeIdx) const
{
if (Nodes::isInvalidNodeIdx(nodeIdx))
return false;
return Nodes::isInvalidNodeIdx(mChildren[nodeIdx]);
}
}
#endif // _SCENE_TREE_NODES_H_
|
> **NOTE**: This example system can be used to make a minimal system that can
> be built using cross-compilation, to validate that the device goes to stage-2.
## Building
```
$ cd .../mobile-nixos
$ nix-build examples/hello --argstr device DEVICE-NAME -A build.default
```
## Installing
Follow the installation instructions for your device.
## Running
This system should boot using the usual stage-1 boot process, followed by a
specialized stage-2 configuration that runs a single-purpose application to
provide a tangible proof that the boot process has completed successfully.
Note that there is no expected way to use this system other than to see the
specialized application starting. This is not intended to be a starting point
to configure a "normal" system on your device.
|
package com.yc.jpaplus.example.dto.like_in;
import com.yc.jpaplus.core.base.annoation.Condition;
import com.yc.jpaplus.core.base.annoation.enums.LikeInLogic;
import com.yc.jpaplus.core.base.annoation.enums.Operator;
import com.yc.jpaplus.core.base.dto.JpaPlusDto;
import lombok.Data;
import java.util.List;
@Data
public class AddressLikeInDto extends JpaPlusDto {
@Condition(operator = Operator.LIKE_IN, likeInLogic = LikeInLogic.OR)
private List<String> address;
}
|
---
layout: slide
title: "Welcome to our second slide!"
---
Here is a simple example of EF Core DBContext:
```csharp
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace Intro
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=Blogging;Integrated Security=True");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public int Rating { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}
```
Use the left arrow to go back!
|
INSERT INTO burgers (name)
VALUES
("hamburger", false),
("cheeseburger", false),
("bacon burger", false);
|
use super::{Upsert, Number, Integer};
use super::{Bson, Array, Object};
use std::borrow::Cow;
/* TODO: Add easy API for dot notation */
/* TODO: Make every large argument be a CoWs (take Vec or &Vec) */
#[derive(Clone)]
pub struct Update<'a>(Object<'a>);
impl<'a> Update<'a> {
pub fn new() -> Self {
Update(Object::new())
}
pub fn field(&'a mut self, field: &'a str) -> UpdateField {
UpdateField {
root: &mut self.0,
field: field,
}
}
pub fn array(&'a mut self, array: &'a str) -> UpdateArray {
UpdateArray {
root: &mut self.0,
array: array,
}
}
pub fn isolate(mut self) -> Self {
self.0.insert(ISOLATED, 1.to_bson_int());
self
}
pub fn no_isolate(mut self) -> Self {
self.0.remove(ISOLATED);
self
}
}
pub struct UpdateField<'a> {
root: &'a mut Object<'a>,
field: &'a str,
}
impl<'a> UpdateField<'a> {
pub fn increment<N: Number<'a>>(self, amount: N) -> Self {
self.add_modifier(INCREMENT, amount.to_bson_num())
}
#[inline]
pub fn inc<N: Number<'a>>(self, amount: N) -> Self {
self.increment(amount)
}
pub fn multiply<N: Number<'a>>(self, amount: N) -> Self {
self.add_modifier(MULTIPLY, amount.to_bson_num())
}
#[inline]
pub fn mul<N: Number<'a>>(self, amount: N) -> Self {
self.multiply(amount)
}
pub fn min(self, value: Bson<'a>) -> Self {
self.add_modifier(MIN, value)
}
pub fn max(self, value: Bson<'a>) -> Self {
self.add_modifier(MAX, value)
}
pub fn and<I: Integer<'a>>(self, bits: I) -> Self {
self.bit(AND, bits.to_bson_int())
}
pub fn or<I: Integer<'a>>(self, bits: I) -> Self {
self.bit(OR, bits.to_bson_int())
}
pub fn xor<I: Integer<'a>>(self, bits: I) -> Self {
self.bit(XOR, bits.to_bson_int())
}
pub fn set(self, value: Bson<'a>) -> Self {
self.add_modifier(SET, value)
}
pub fn unset(self) -> Self {
self.add_modifier(UNSET, Bson::Str(""))
}
pub fn rename(self, name: &'a str) -> Self {
self.add_modifier(RENAME, Bson::Str(name))
}
pub fn set_on_insert(self, value: Bson<'a>) -> Self {
self.add_modifier(SET_ON_INSERT, value)
}
pub fn set_date_now(self) -> Self {
self.add_modifier(CURRENT_DATE, Bson::Str(DATE_TYPE))
}
pub fn set_timestamp_now(self) -> Self {
self.add_modifier(CURRENT_DATE, Bson::Str(TIMESTAMP_TYPE))
}
#[inline]
fn add_modifier(mut self, category: &'static str, value: Bson<'a>) -> Self {
{
let group = self.root.object(category);
group.insert(self.field, value);
}
self
}
#[inline]
fn bit(mut self, op: &'static str, bits: Bson<'a>) -> Self {
{
let bits_update = self.root.object(BIT);
let field_ops = bits_update.object(self.field);
field_ops.insert(op, bits);
}
self
}
}
pub struct UpdateArray<'a> {
root: &'a mut Object<'a>,
array: &'a str,
}
impl<'a> UpdateArray<'a> {
/* TODO: Implement first-matching ( $ symbol )
* and dot notation for arrays (including index)
* .first_matching()
* .index() | These can lead to either a field or another
* .dot() | array?
*/
/* TODO: Refactor for less code bloat */
pub fn push(self, value: Bson<'a>) -> Self {
self.add_modifier(PUSH, value)
}
#[inline]
pub fn push_at(self, value: Bson<'a>, position: u32) -> Self {
self.push_pos_cow(Cow::Owned(vec![value]), position)
}
pub fn push_all(self, values: &'a Array<'a>) -> Self {
{
let array = self.root.deep_object(PUSH, self.array);
array.insert(EACH, Bson::Array(Cow::Borrowed(values)));
}
self
}
#[inline]
pub fn push_all_at(self, values: &'a Array<'a>, position: u32) -> Self {
self.push_pos_cow(Cow::Borrowed(values), position)
}
pub fn slice(self, max: u32) -> Self {
{
let array = self.root.deep_object(PUSH, self.array);
array.entry(EACH).or_insert_with(|| Bson::Array(Cow::Owned(Vec::new())));
array.insert(SLICE, max.to_bson_int());
}
self
}
pub fn sort(self) -> Self {
self.sort_array(1, None)
}
pub fn rev_sort(self) -> Self {
self.sort_array(-1, None)
}
pub fn sort_by(self, field: &'a str) -> Self {
self.sort_array(1, Some(field))
}
pub fn rev_sort_by(self, field: &'a str) -> Self {
self.sort_array(-1, Some(field))
}
fn sort_array(mut self, direction: i32, spec: Option<&'a str>) -> Self {
{
let array = self.root.deep_object(PUSH, self.array);
array.entry(EACH).or_insert_with(|| Bson::Array(Cow::Owned(Vec::new())));
if let Some(field) = spec {
let sort = array.object(SORT);
sort.insert(field, direction.to_bson_int());
} else {
array.insert(SORT, direction.to_bson_int());
}
}
self
}
pub fn pull(self, value: Bson<'a>) -> Self {
self.add_modifier(PULL, value)
}
pub fn pull_all(self, values: &'a Array<'a>) -> Self {
self.add_modifier(PULL_ALL, Bson::Array(Cow::Borrowed(values)))
}
/* TODO: Requires Query ops pub fn pull_if(self, condition: ) */
pub fn pop_front(self) -> Self {
// TODO: Check if we should be using FloatingPoint()
// to avoid NumberInt("-1");
self.add_modifier(POP, (-1).to_bson_int())
}
pub fn pop_back(self) -> Self {
// TODO: Same as above
self.add_modifier(POP, 1.to_bson_int())
}
pub fn add_to_set(self, value: Bson<'a>) -> Self {
self.add_modifier(ADD_TO_SET, value)
}
pub fn add_all_to_set(self, values: &'a Array<'a>) -> Self {
{
let array = self.root.deep_object(ADD_TO_SET, self.array);
array.insert(EACH, Bson::Array(Cow::Borrowed(values)));
}
self
}
#[inline]
fn add_modifier(mut self, category: &'static str, value: Bson<'a>) -> Self {
{
let group = self.root.object(category);
group.insert(self.array, value);
}
self
}
fn push_pos_cow(self, values: Cow<'a, Array<'a>>, position: u32) -> Self {
{
let array = self.root.deep_object(PUSH, self.array);
array.insert(EACH, Bson::Array(values));
array.insert(POSITION, position.to_bson_int());
}
self
}
}
/*****************
* Update Fields *
*****************/
const INCREMENT: &'static str = "$inc";
const MULTIPLY: &'static str = "$mul";
const RENAME: &'static str = "$rename";
const SET_ON_INSERT: &'static str = "$setOnInsert";
const SET: &'static str = "$set";
const UNSET: &'static str = "$unset";
const MIN: &'static str = "$min";
const MAX: &'static str = "$max";
const CURRENT_DATE: &'static str = "$currentDate";
const DATE_TYPE: &'static str = "{$type:\"date\"}";
const TIMESTAMP_TYPE: &'static str = "{$type:\"timestamp\"}";
/*****************
* Update Arrays *
*****************/
/* Operators */
const FIRST: &'static str = "$";
const ADD_TO_SET: &'static str = "$addToSet";
const POP: &'static str = "$pop";
const PULL_ALL: &'static str = "$pullAll";
const PULL: &'static str = "$pull";
const PUSH: &'static str = "$push";
/* Modifiers */
const EACH: &'static str = "$each";
const SLICE: &'static str = "$slice";
const SORT: &'static str = "$sort";
const POSITION: &'static str = "$position";
/*********************
* Bitwise Operation *
*********************/
const BIT: &'static str = "$bit";
const AND: &'static str = "and";
const XOR: &'static str = "xor";
const OR: &'static str = "or";
/*************
* Isolation *
*************/
const ISOLATED: &'static str = "$isolated";
|
package tuktu.web.processors
import play.api.cache.Cache
import play.api.libs.iteratee.Enumeratee
import play.api.libs.json._
import play.api.libs.ws.WS
import play.api.Play.current
import scala.concurrent.Await
import scala.concurrent.duration.DurationInt
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import tuktu.api._
import tuktu.api.utils.evaluateTuktuString
/**
* Searches the geolocation of IP addresses using the freegeoip.net web service
* or one of its clones.
* See http://freegeoip.net/ for details and limitations.
*/
class FreeGeoIPProcessor(resultName: String) extends BaseProcessor(resultName)
{
var ip: String = _
var freegeoip: String = _
var format: String = _
override def initialize(config: JsObject) {
// Get the name of the field containing the ip to lookup.
ip = (config \ "ip").as[String]
// Get the url of the freegeoip service to call.
freegeoip = (config \ "geoipurl").asOpt[String].getOrElse("http://freegeoip.net")
// Get the format in which the geolocation data should be returned (i.e., json, csv or xml - default is json).
format = (config \ "format").asOpt[String].getOrElse("json")
}
override def processor(): Enumeratee[DataPacket, DataPacket] = Enumeratee.mapM((data: DataPacket) => {
val listfuture = data.data.map{ datum =>
val address = evaluateTuktuString(ip, datum)
lookupIP( address ).map{ result => datum + (resultName -> result) }
}
val futurelist = Future.sequence( listfuture )
futurelist.map{ fl => DataPacket( fl ) }
})
def lookupIP(ip: String): Future[Any] = {
val future = WS.url(freegeoip + "/" + format + "/" + ip).get
future.map(response =>
format match {
case "json" => response.json
case "csv" => response.body
case "xml" => response.xml.toString
case _ => "invalid format requested!"
})
}
}
|
package com.mikelau.zenith.dialogs
import android.content.Context
import android.os.Build
import androidx.annotation.StringRes
import com.mikelau.zenith.R
/** Ready to use progress dialog with custom implementation. Uniformed way of making a progress dialog **/
object ProgressDialogHelper {
private var progressDialog: android.app.ProgressDialog? = null
@JvmStatic
fun showProgress(context: Context, text: String, cancelable: Boolean?, touchOutside: Boolean?) {
progressDialog = if (Build.VERSION.SDK_INT >= 23) {
android.app.ProgressDialog(context, R.style.AppCompatAlertDialogStyle)
} else {
android.app.ProgressDialog(context)
}
progressDialog?.setMessage(text)
progressDialog?.isIndeterminate = false
progressDialog?.setCancelable(cancelable!!)
progressDialog?.setCanceledOnTouchOutside(touchOutside!!)
progressDialog?.show()
}
@JvmStatic
fun showProgress(context: Context, @StringRes text: Int, cancelable: Boolean?, touchOutside: Boolean?) {
progressDialog = if (Build.VERSION.SDK_INT >= 23) {
android.app.ProgressDialog(context, R.style.AppCompatAlertDialogStyle)
} else {
android.app.ProgressDialog(context)
}
progressDialog?.setMessage(context.resources.getString(text))
progressDialog?.isIndeterminate = false
progressDialog?.setCancelable(cancelable!!)
progressDialog?.setCanceledOnTouchOutside(touchOutside!!)
progressDialog?.show()
}
@JvmStatic
fun hideProgress() {
if (progressDialog != null && progressDialog?.isShowing!!)
progressDialog?.dismiss()
}
}
|
/*
* Copyright 2020 Robin Mercier
*
* 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 net.azzerial.jmgur.internal.entities;
import lombok.Setter;
import net.azzerial.jmgur.api.Jmgur;
import net.azzerial.jmgur.api.entities.Account;
import net.azzerial.jmgur.api.entities.Avatar;
import net.azzerial.jmgur.api.entities.Cover;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.OffsetDateTime;
import static net.azzerial.jmgur.internal.utils.Helper.print;
@Setter
public final class AccountImpl implements Account {
private final transient Jmgur api;
private long id;
private String url;
private String bio;
private Avatar avatar;
private Cover cover;
private int reputation;
private String reputationName;
private OffsetDateTime created;
private boolean isBlocked;
/* Constructors */
AccountImpl(@NotNull Jmgur api) {
this.api = api;
}
/* Getters & Setters */
@NotNull
@Override
public Jmgur getApi() {
return api;
}
@Override
public long getIdLong() {
return id;
}
@NotNull
@Override
public String getName() {
return url;
}
@Nullable
@Override
public String getBio() {
return bio;
}
@NotNull
@Override
public Avatar getAvatar() {
return avatar;
}
@NotNull
@Override
public Cover getCover() {
return cover;
}
@Override
public int getReputationScore() {
return reputation;
}
@NotNull
@Override
public String getReputationName() {
return reputationName;
}
@NotNull
@Override
public OffsetDateTime getCreationDate() {
return created;
}
@Override
public boolean isBlocked() {
return isBlocked;
}
/* Methods */
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name=" + print(url) +
", bio=" + print(bio) +
", avatar=" + avatar +
", cover=" + cover +
", reputation=" + reputation +
", reputationName=" + print(reputationName) +
", creationDate=" + created +
", blocked=" + isBlocked +
'}';
}
}
|
error() {
printf "%s\n" "$1" >&2
exit 1
}
run_wrapped_binary() {
# search for the wrapped binary in $PATH
#
# ignore paths before our own for compatibility with other wrappers
unwrapped=false
self=false
IFS=: read -ra path <<< "$PATH";
for p in "${path[@]}"; do
binary="$p/${0##*/}"
if $self && [[ -x "$binary" ]]; then
unwrapped="$binary"
break
elif [[ "$binary" -ef "$0" ]]; then
self=true
fi
done
exec "$unwrapped" "${arguments[@]}" "$@"
}
|
$(function(){
$("#pie").dxPieChart({
palette: paletteCollection[0],
dataSource: dataSource,
series: {},
legend: {
visible: false
},
onDrawn: function(e) {
var paletteName = e.component.option("palette"),
palette = DevExpress.viz.getPalette(paletteName).simpleSet,
paletteContainer = $(".palette-container");
paletteContainer.html("");
palette.forEach(function(color) {
$("<div>").css({
backgroundColor: color
})
.addClass("palette-item")
.appendTo(paletteContainer);
});
}
});
$("#palette").dxSelectBox({
items: paletteCollection,
value: paletteCollection[0],
onValueChanged: function(e) {
$("#pie").dxPieChart({
palette: e.value
});
}
});
$("#extension-mode").dxSelectBox({
items: paletteExtensionModes,
value: "Blend",
onValueChanged: function(e) {
$("#pie").dxPieChart({
paletteExtensionMode: e.value
});
}
});
});
|
module ExtEff.Bench
( countDownBench
, countDownExcBench
, httpBench
) where
import ExtEff.Stateful
import ExtEff.StatefulExcept
import ExtEff.HTTP
import Control.Eff.State.Strict
import Control.Eff.Exception
import Control.Eff
countDownBench :: Int -> (Int, Int)
countDownBench start = run . runState start $ countDownPut
countDownExcBench :: Int -> Either String (Int, Int)
countDownExcBench start = run . runError . runState start $ countDownExc
httpBench :: Int -> IO Int
httpBench n = runHttp (doHTTP n)
|
#!/bin/bash
current=0
threshold=$1
function kill_program()
{
pid=`ps ax|grep $1|grep -v grep|awk '{print $1}'`
echo "pid is ${pid}"
while [ -n "${pid}" ];
do
kill -TERM $pid
sleep 1
pid=`ps ax|grep $1|grep -v grep|awk '{print $1}'`
echo "pid is ${pid}"
done
}
while :
do
current=`taos -s 'select last_row(mem_taosd) from log.dn1'|tail -3|head -1|awk '{print $1}'|head -1`
echo "threshold is ${threshold}, current is ${current}"
if (( $(echo "$current > $threshold" | bc -l) )); then
kill_program $2
kill_program $3
break;
else
echo "sleep 30 seconds and check again."
sleep 30
fi
done
|
#ifndef GraphicsContextCullSaver_h
#define GraphicsContextCullSaver_h
#include "platform/graphics/GraphicsContext.h"
namespace blink {
class FloatRect;
class GraphicsContextCullSaver {
WTF_MAKE_FAST_ALLOCATED;
public:
GraphicsContextCullSaver(GraphicsContext& context)
: m_context(context)
, m_cullApplied(false)
{
}
GraphicsContextCullSaver(GraphicsContext& context, const FloatRect& rect)
: m_context(context)
, m_cullApplied(true)
{
context.beginCull(rect);
}
~GraphicsContextCullSaver()
{
if (m_cullApplied)
m_context.endCull();
}
void cull(const FloatRect& rect)
{
ASSERT(!m_cullApplied);
m_context.beginCull(rect);
m_cullApplied = true;
}
private:
GraphicsContext& m_context;
bool m_cullApplied;
};
} // namespace blink
#endif // GraphicsContextCullSaver_h
|
--#!sqlite
--#{info_book
--#{info_book.init
CREATE TABLE IF NOT EXISTS player(
);
--#}
--#}
|
package com.sujithjay.benchmark.merge
import org.scalameter.api._
/**
* @author Sujith
*/
object MergePerformance extends Bench.LocalTime{
val sizes = Gen.range("arraySizes")(0, 1500000, 300000)
val lists = for {
size <- sizes
} yield Tuple2((0 to (size, 2)).toList, (1 to (size, 2) ).toList)
performance of "Merge" in {
measure method "FunctionalMerge" in {
using(lists) config (
exec.independentSamples -> 1,
exec.reinstantiation.frequency -> 2,
exec.outliers.covMultiplier -> 1.5,
exec.outliers.suspectPercent -> 40
) in{
l=>
FunctionalMerge.merge(l._1, l._2)
}
}
}
val arrays = for {
size <- sizes
} yield Tuple2((0 to (size, 2)).toArray, (1 to (size, 2) ).toArray)
performance of "Merge" in {
measure method "ImperativeMerge" in {
using(arrays) config (
exec.independentSamples -> 1,
exec.reinstantiation.frequency -> 2,
exec.outliers.covMultiplier -> 1.5,
exec.outliers.suspectPercent -> 40
) in{
l=>
ImperativeMerge.merge(l._1, l._2)
}
}
}
}
|
package at.sunilson.vehicleMap.domain.entities
import com.google.android.libraries.maps.model.LatLng
import java.time.DayOfWeek
internal data class ChargingStation(
val id: Int,
val operator: String,
val address: String,
val connections: List<Connection>,
val location: LatLng?
)
internal data class Connection(
val maxKW: Int,
val quantity: Int,
val operational: Boolean
)
internal data class OpeningTime(
val dayOfWeek: DayOfWeek,
val startTime: String,
val endTime: String
)
|
export { parseForm, safeParseForm, parseFormAny } from "./parse-form";
export { errorChain, fieldChain, createCustomIssues } from "./chains";
export { useZorm } from "./use-zorm";
export { Zorm } from "./types";
export { useValue, Value, ValueSubscription } from "./use-value";
|
namespace NotifyMe.Rawbot.Amazon.Commands.ReadySignIn
{
using NotifyMe.Core.Mediator;
public class ReadySignInResponse : ResponseBase
{
}
}
|
#!/bin/bash
# Fill wp-config.php
./install/set-wp-config.sh
# Proceed to maybe install WordPress
./install/maybe-install-wp.sh
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mapr.drill.maprdb.tests.index;
import com.mapr.db.Admin;
import com.mapr.db.MapRDB;
import org.apache.drill.common.util.GuavaPatcher;
import java.util.HashMap;
import java.util.Map;
/**
* Copy classes to a MapR cluster node, then run a command like this:
* java -classpath /tmp/drill-cmd-1.9.0-SNAPSHOT.jar:/opt/mapr/drill/drill-1.9.0/jars/*:/opt/mapr/drill/drill-1.9.0/jars/3rdparty/*:/opt/mapr/drill/drill-1.9.0/jars/ext/*
* org.apache.drill.hbase.index.TableIndexGen -host 10.10.88.128 -port 5181 [-table pop3] [-size 1000000]
*/
class TestBigTable {
Admin admin;
boolean initialized = false;
LargeTableGen gen;
/*
"hbase.zookeeper.quorum": "10.10.88.128",
"hbase.zookeeper.property.clientPort": "5181"
*/
void init(String host, String port) {
try {
admin = MapRDB.newAdmin();
initialized = true;
gen = new LargeTableGen(admin);
} catch (Exception e) {
System.out.println("Connection to HBase threw" + e.getMessage());
}
}
}
public class TableIndexCmd {
public static Map<String,String> parseParameter(String[] params) {
HashMap<String,String> retParams = new HashMap<String, String>();
for (int i=0; i<params.length; ++i) {
if (params[i].startsWith("-") && i<params.length - 1) {
String paramName = params[i].replaceFirst("-*", "");
retParams.put(paramName, params[i+1]);
++i;
}
}
return retParams;
}
public static void pressEnterKeyToContinue()
{
System.out.println("Press any key to continue...");
try {
System.in.read();
} catch(Exception e) {}
}
public static void main(String[] args) {
GuavaPatcher.patch();
String inHost = new String("localhost");
String inPort = new String("5181");
String inTable = new String("/tmp/population");
String dictPath = "hbase";
boolean waitKeyPress = true;
long inSize = 10000;
Map<String, String> params = parseParameter(args);
if (args.length >= 2) {
if (params.get("host") != null) {
inHost = params.get("host");
}
if (params.get("port") != null) {
inPort = params.get("port");
}
if (params.get("table") != null) {
inTable = params.get("table");
}
if (params.get("size") != null) {
inSize = Long.parseLong(params.get("size"));
}
if (params.get("dict") != null) {
dictPath = params.get("dict");
}
if (params.get("wait") != null) {
String answer = params.get("wait");
waitKeyPress = answer.startsWith("y") || answer.startsWith("t")? true : false;
}
}
if (waitKeyPress == true) {
pressEnterKeyToContinue();
}
try {
TestBigTable tbt = new TestBigTable();
tbt.init(inHost, inPort);
tbt.gen.generateTableWithIndex(inTable, (int)(inSize & 0xFFFFFFFFL), null);
} catch(Exception e) {
System.out.println("generate big table got exception:" + e.getMessage());
e.printStackTrace();
}
}
}
|
import { StateTestRecord } from '@tussle/spec';
import { TussleStateService } from '@tussle/spec/interface/state';
import { stateServiceTests as stateSpecConformanceTests } from '@tussle/spec';
import { TussleStatePostgres } from './state';
import { Pool } from 'pg';
const pool = new Pool({
max: 1,
connectionString: (
process.env['POSTGRES_CONNECT_STRING'] ||
'postgresql://postgres:postgres@localhost'
),
});
afterAll(async () => {
await pool.query('TRUNCATE tussle_state;');
await pool.end();
});
function runStateTest<T extends TussleStateService<StateTestRecord>>(
name: string,
create: () => Promise<T>,
): void {
stateSpecConformanceTests(name, create);
}
runStateTest(
'@tussle/state-postgres',
async () => {
await pool.query('TRUNCATE tussle_state;');
return new TussleStatePostgres<StateTestRecord>({
table: 'tussle_state',
pool: () => pool,
});
},
);
|
<?php
namespace ipinfo\ipinfo;
use Exception;
use ipinfo\ipinfo\cache\DefaultCache;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
/**
* Exposes the IPinfo library to client code.
*/
class IPinfo
{
const API_URL = 'https://ipinfo.io';
const CACHE_MAXSIZE = 4096;
const CACHE_TTL = 86400; // 24 hours as seconds
const CACHE_KEY_VSN = '1'; // update when cache vals change for same key.
const COUNTRIES_FILE_DEFAULT = __DIR__ . '/countries.json';
const REQUEST_TYPE_GET = 'GET';
const STATUS_CODE_QUOTA_EXCEEDED = 429;
const REQUEST_TIMEOUT_DEFAULT = 2; // seconds
public $access_token;
public $cache;
public $countries;
protected $http_client;
public function __construct($access_token = null, $settings = [])
{
$this->access_token = $access_token;
/*
Support a timeout first-class, then a `guzzle_opts` key that can
override anything.
*/
$guzzle_opts = [
'http_errors' => false,
'headers' => $this->buildHeaders(),
'timeout' => $settings['timeout'] ?? self::REQUEST_TIMEOUT_DEFAULT
];
if (isset($settings['guzzle_opts'])) {
$guzzle_opts = array_merge($guzzle_opts, $settings['guzzle_opts']);
}
$this->http_client = new Client($guzzle_opts);
$countries_file = $settings['countries_file'] ?? self::COUNTRIES_FILE_DEFAULT;
$this->countries = $this->readCountryNames($countries_file);
if (array_key_exists('cache', $settings)) {
$this->cache = $settings['cache'];
} else {
$maxsize = $settings['cache_maxsize'] ?? self::CACHE_MAXSIZE;
$ttl = $settings['cache_ttl'] ?? self::CACHE_TTL;
$this->cache = new DefaultCache($maxsize, $ttl);
}
}
/**
* Get formatted details for an IP address.
* @param string|null $ip_address IP address to look up.
* @return Details Formatted IPinfo data.
* @throws IPinfoException
*/
public function getDetails($ip_address = null)
{
$response_details = $this->getRequestDetails((string) $ip_address);
return $this->formatDetailsObject($response_details);
}
/**
* Format details and return as an object.
* @param array $details IP address details.
* @return Details Formatted IPinfo Details object.
*/
public function formatDetailsObject($details = [])
{
$country = $details['country'] ?? null;
$details['country_name'] = $this->countries[$country] ?? null;
if (array_key_exists('loc', $details)) {
$coords = explode(',', $details['loc']);
$details['latitude'] = $coords[0];
$details['longitude'] = $coords[1];
} else {
$details['latitude'] = null;
$details['longitude'] = null;
}
return new Details($details);
}
/**
* Get details for a specific IP address.
* @param string $ip_address IP address to query API for.
* @return array IP response data.
* @throws IPinfoException
*/
public function getRequestDetails(string $ip_address)
{
$cachedRes = $this->cache->get($this->cacheKey($ip_address));
if ($cachedRes != null) {
return $cachedRes;
}
$url = self::API_URL;
if ($ip_address) {
$url .= "/$ip_address";
}
try {
$response = $this->http_client->request(
self::REQUEST_TYPE_GET,
$url
);
} catch (GuzzleException $e) {
throw new IPinfoException($e->getMessage());
} catch (Exception $e) {
throw new IPinfoException($e->getMessage());
}
if ($response->getStatusCode() == self::STATUS_CODE_QUOTA_EXCEEDED) {
throw new IPinfoException('IPinfo request quota exceeded.');
} elseif ($response->getStatusCode() >= 400) {
throw new IPinfoException('Exception: ' . json_encode([
'status' => $response->getStatusCode(),
'reason' => $response->getReasonPhrase(),
]));
}
$raw_details = json_decode($response->getBody(), true);
$this->cache->set($this->cacheKey($ip_address), $raw_details);
return $raw_details;
}
/**
* Gets a URL to a map on https://ipinfo.io/map given a list of IPs (max
* 500,000).
* @param array $ips list of IP addresses to put on the map.
* @return string URL to the map.
*/
public function getMapUrl($ips)
{
$url = sprintf("%s/map?cli=1", self::API_URL);
try {
$response = $this->http_client->request(
'POST',
$url,
[
'json' => $ips
]
);
} catch (GuzzleException $e) {
throw new IPinfoException($e->getMessage());
} catch (Exception $e) {
throw new IPinfoException($e->getMessage());
}
$res = json_decode($response->getBody(), true);
return $res['reportUrl'];
}
/**
* Build headers for API request.
* @return array Headers for API request.
*/
private function buildHeaders()
{
$headers = [
'user-agent' => 'IPinfoClient/PHP/2.2',
'accept' => 'application/json',
];
if ($this->access_token) {
$headers['authorization'] = "Bearer {$this->access_token}";
}
return $headers;
}
/**
* Read country names from a file and return as an array.
* @param string $countries_file JSON file of country_code => country_name mappings
* @return array country_code => country_name mappings
*/
private function readCountryNames($countries_file)
{
$file_contents = file_get_contents($countries_file);
return json_decode($file_contents, true);
}
/**
* Returns a versioned cache key given a user-input key.
* @param string $k key to transform into a versioned cache key.
* @return string the versioned cache key.
*/
private function cacheKey($k)
{
return sprintf('%s:%s', $k, self::CACHE_KEY_VSN);
}
}
|
package esg.security.utils.http;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* Class containing utility for issuing HTTP GET/POST requests.
* @author Luca Cinquini
*
*/
public class HttpUtils {
private static final Log LOG = LogFactory.getLog(HttpUtils.class);
/**
* Shared instance across all clients.
*/
private static CloseableHttpClient client = null;
static {
client = HttpClients.createDefault();
}
/**
* Method to execute a GET request.
*
* @param uri : the URL to be requested without any query parameters
* @param params: optional map of HTPP (name,value) query parameters
* @return
*/
public final static String get(final String uri, final Map<String, String> pars) throws Exception {
// build full URL with query string
String url = uri;
String delimiter = "?";
for (final String key : pars.keySet()) {
url += delimiter + URLEncoder.encode(key,"UTF-8") + "=" + URLEncoder.encode(pars.get(key),"UTF-8");
delimiter = "&";
}
// create GET request
HttpGet httpGet = new HttpGet(url);
// provide custom retry handler is necessary
//method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
CloseableHttpResponse response = client.execute(httpGet);
try {
// execute the method.
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new Exception("HTTP GET request failed: url="+url+" error=" + response.getStatusLine());
}
// read the response body.
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
// note: must fully consume the response
EntityUtils.consume(entity);
return body;
} catch (IOException e) {
LOG.warn(e.getMessage());
throw new Exception("Fatal transport error: " + e.getMessage());
} finally {
// release the connection.
response.close();
}
}
/**
* Method to execute a POST request.
*
* @param url : the URL to be requested without any query parameters
* @param params: optional map of HTPP (name,value) query parameters
* @return
*/
public final static String post(final String url, final Map<String, String> pars) throws Exception {
// create a POST request
HttpPost httpPost = new HttpPost(url);
// add request parameters
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
for (final String key : pars.keySet()) {
nvps.add(new BasicNameValuePair(key, pars.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
// provide custom retry handler is necessary
//method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
CloseableHttpResponse response = client.execute(httpPost);
try {
// execute the method.
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new Exception("HTTP POST request failed: url="+url+" error=" + response.getStatusLine());
}
// read the response body.
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
// note: must fully consume the response
EntityUtils.consume(entity);
return body;
} catch (IOException e) {
LOG.warn(e.getMessage());
throw new Exception("Fatal transport error: " + e.getMessage());
} finally {
// release the connection.
response.close();
}
}
/**
* Method that cleans up the HttpClient, but not necessarily guaranteed to be called in Java.
*/
protected void finalize() throws Throwable {
if (client!=null) {
client.close();
}
super.finalize();
}
}
|
#!/bin/bash
sbatch -N 1 -t $1 --job-name=sleep-$1 sleep.job $1
|
import '../event/play_card_event.dart';
import '../exceptions/action_exception.dart';
import '../model/enums/location.dart';
import '../model/game_state.dart';
import '../state_change/add_event_state_change.dart';
import '../state_change/move_card_state_change.dart';
import '../state_change/priority_state_change.dart';
import '../state_change/state_change.dart';
import 'action.dart';
/// Plays the card from your hand.
class PlayCardAction extends Action {
/// Card to play.
final int card;
/// Plays [card] from priority player's hand.
const PlayCardAction({required this.card});
@override
void validate(GameState state) {
final _card = state.getCardById(card);
if (_card.location != Location.hand) {
// Card not found in hand.
throw const ActionException('PlayCardAction: Card not in hand.');
}
if (!_card.canPlay(state)) {
throw const ActionException(
'PlayCardAction: Cannot play that card at this time.');
}
}
@override
List<StateChange> apply(GameState state) {
validate(state);
return [
MoveCardStateChange(card: card, location: Location.limbo),
AddEventStateChange(event: PlayCardEvent(card: card)),
PriorityStateChange(player: state.activePlayer),
];
}
/// Whether this action can be auto passed.
static bool canAutoPass(GameState state) {
return state.cards.every((card) {
try {
PlayCardAction(card: card.id).validate(state);
return false;
} on ActionException {
return true;
}
});
}
@override
List<Object> get props => [card];
/// Create from json.
static PlayCardAction fromJson(List<dynamic> json) => PlayCardAction(
card: json[0] as int,
);
}
|
package me.bausano.tsp.IO;
import me.bausano.tsp.Enum.Algorithm;
import me.bausano.tsp.Exception.InvalidAlgorithmChoiceException;
import me.bausano.tsp.IO.InputParser.InputParser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class Eloquent {
/**
* Computes the distances from file lines.
*/
private InputParser parser;
/**
* Chosen algorithm.
*/
private Algorithm algorithm;
/**
* Matrix of distances between the cities.
*/
private double[][] matrix;
/**
* Class constructor.
*
* @param parser Parses the lines from a file into a matrix.
*/
public Eloquent (InputParser parser) {
this.parser = parser;
}
/**
* Lets user select the algorithm which is going to solve the problem.
*
* @throws InvalidAlgorithmChoiceException Is thrown if the algorithm doesn't exist.
*/
public void requestAlgorithm() throws InvalidAlgorithmChoiceException {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine().trim();
if (input.length() == 0) {
input = "BRANCH_AND_BOUND_WITH_NEIGHBOUR";
}
try {
algorithm = Algorithm.valueOf(input);
} catch (Exception e) {
throw new InvalidAlgorithmChoiceException();
}
}
/**
* Asks for data from user and attempts to parse them.
*
* @throws Exception Any exception with input data.
*/
public void requestData() throws Exception {
Scanner scanner = new Scanner(System.in);
String path = scanner.nextLine().trim();
ArrayList<String> lines = parseFile(path);
matrix = parser.matrixFromArray(lines);
}
/**
* @return Chosen algorithm.
*/
public Algorithm getAlgorithm() {
return algorithm;
}
public double[][] getMap() {
return matrix;
}
/**
* Reads file line by line.
*
* @param path File path relative to the working directory.
*
* @return List of lines.
*
* @throws Exception Any IO Exception.
*/
private ArrayList<String> parseFile(String path) throws Exception {
ArrayList<String> lines = new ArrayList<>();
String line;
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
lines.add(line.trim());
}
bufferedReader.close();
return lines;
}
}
|
//Copyright(c) 2021-2030, Muhammad Rahman
//All rights reserved.
//This source code is licensed under the Apache 2.0 License found in the
//LICENSE file in the root directory of this source tree.
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Market.Price.Provider
{
public class StockPrice : INotifyPropertyChanged
{
private string _symbol = String.Empty;
private double _price = 0;
public string Symbol
{
get
{
return _symbol;
}
set
{
if (value != _symbol)
{
_symbol = value;
NotifyPropertyChanged();
}
}
}
public double Price
{
get
{
return _price;
}
set
{
if (value != _price)
{
_price = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class ProviderStockPrice
{
public string Symbol { get; set; }
public double Price { get; set; }
}
}
|
<?php
class Web_Model extends CI_Model
{
public function get_all_featured_product()
{
$this->db->select('*,tbl_product.publication_status as pstatus');
$this->db->from('tbl_product');
$this->db->join('tbl_category', 'tbl_category.id=tbl_product.product_category');
$this->db->join('tbl_brand', 'tbl_brand.brand_id=tbl_product.product_brand');
$this->db->order_by('tbl_product.product_id', 'ASC');
$this->db->where('tbl_product.publication_status', 1);
$this->db->where('product_feature', 1);
$this->db->where("tbl_product.product_quantity > 0");
$this->db->limit(8);
$info = $this->db->get();
return $info->result();
}
public function get_all_new_product()
{
$this->db->select('*,tbl_product.publication_status as pstatus');
$this->db->from('tbl_product');
$this->db->join('tbl_category', 'tbl_category.id=tbl_product.product_category');
$this->db->join('tbl_brand', 'tbl_brand.brand_id=tbl_product.product_brand');
$this->db->order_by('tbl_product.product_id', 'DESC');
$this->db->where('tbl_product.publication_status', 1);
$this->db->where("tbl_product.product_quantity > 0");
$this->db->limit(8);
$info = $this->db->get();
return $info->result();
}
public function get_all_product()
{
$this->db->select('*');
$this->db->from('tbl_product');
$this->db->join('tbl_category', 'tbl_category.id=tbl_product.product_category');
$this->db->join('tbl_brand', 'tbl_brand.brand_id=tbl_product.product_brand');
$this->db->order_by('tbl_product.product_id', 'DESC');
$this->db->where('tbl_product.publication_status', 1);
$this->db->where("tbl_product.product_quantity > 0");
$info = $this->db->get();
return $info->result();
}
public function get_all_product_pagi($limit, $offset, $brd, $prc)
{
$this->db->select('*');
$this->db->from('tbl_product');
$this->db->join('tbl_category', 'tbl_category.id=tbl_product.product_category');
$this->db->join('tbl_brand', 'tbl_brand.brand_id=tbl_product.product_brand');
$this->db->order_by('tbl_product.product_id', 'DESC');
$this->db->where('tbl_product.publication_status', 1);
if ($brd != null) {
$this->db->where('tbl_product.product_brand', $brd);
}
if ($prc != null) {
$this->db->where('tbl_product.product_price <', $prc);
}
$this->db->where("tbl_product.product_quantity > 0");
$this->db->limit($limit, $offset);
$info = $this->db->get();
return $info->result();
}
public function get_single_product($id)
{
$this->db->select('*');
$this->db->from('tbl_product');
$this->db->join('tbl_category', 'tbl_category.id=tbl_product.product_category');
$this->db->join('tbl_brand', 'tbl_brand.brand_id=tbl_product.product_brand');
$this->db->where('tbl_product.product_id', $id);
$this->db->where("tbl_product.product_quantity > 0");
$info = $this->db->get();
return $info->row();
}
public function get_all_category()
{
$this->db->select('*');
$this->db->from('tbl_category');
$this->db->where('publication_status', 1);
$this->db->order_by('tbl_category.id', 'DESC');
$info = $this->db->get();
return $info->result();
}
public function get_all_brand()
{
$this->db->select('*');
$this->db->from('tbl_brand');
$this->db->order_by('tbl_brand.brand_id', 'DESC');
$this->db->where('publication_status', 1);
$this->db->limit(6);
$info = $this->db->get();
return $info->result();
}
public function get_full_brand()
{
$this->db->select('*');
$this->db->from('tbl_brand');
$this->db->order_by('tbl_brand.brand_id', 'DESC');
$this->db->where('publication_status', 1);
$info = $this->db->get();
return $info->result();
}
public function get_all_product_by_cat($id, $brd, $prc)
{
$this->db->select('*');
$this->db->from('tbl_product');
$this->db->join('tbl_category', 'tbl_category.id=tbl_product.product_category');
$this->db->join('tbl_brand', 'tbl_brand.brand_id=tbl_product.product_brand');
$this->db->order_by('tbl_product.product_id', 'DESC');
$this->db->where('tbl_product.publication_status', 1);
if ($brd != null) {
$this->db->where('tbl_product.product_brand', $brd);
}
if ($prc != null) {
$this->db->where('tbl_product.product_price <', $prc);
}
$this->db->where("tbl_product.product_quantity > 0");
$this->db->where('tbl_category.id', $id);
$info = $this->db->get();
return $info->result();
}
public function get_cat_name($id)
{
$this->db->select('*');
$this->db->from('tbl_category');
$this->db->where('id', $id);
$info = $this->db->get();
return $info->row();
}
public function get_brd_name($id)
{
$this->db->select('*');
$this->db->from('tbl_brand');
$this->db->where('brand_id', $id);
$info = $this->db->get();
return $info->row();
}
public function get_all_product_by_brand($id, $prc)
{
$this->db->select('*');
$this->db->from('tbl_product');
$this->db->join('tbl_brand', 'tbl_brand.brand_id=tbl_product.product_brand');
$this->db->join('tbl_category', 'tbl_category.id=tbl_product.product_category');
$this->db->order_by('tbl_product.product_id', 'DESC');
$this->db->where('tbl_product.publication_status', 1);
if ($prc != null) {
$this->db->where('tbl_product.product_price <', $prc);
}
$this->db->where("tbl_product.product_quantity > 0");
$this->db->where('tbl_brand.brand_id', $id);
$info = $this->db->get();
return $info->result();
}
public function get_product_by_id($id)
{
$this->db->select('*');
$this->db->from('tbl_product');
$this->db->join('tbl_category', 'tbl_category.id=tbl_product.product_category');
$this->db->join('tbl_brand', 'tbl_brand.brand_id=tbl_product.product_brand');
$this->db->order_by('tbl_product.product_id', 'DESC');
$this->db->where('tbl_product.publication_status', 1);
$this->db->where("tbl_product.product_quantity > 0");
$this->db->where('tbl_product.product_id', $id);
$info = $this->db->get();
return $info->row();
}
public function update_product_when_buy($data, $id)
{
$this->db->where('product_id', $id);
return $this->db->update('tbl_product', $data);
}
public function save_customer_info($data)
{
$this->db->insert('tbl_customer', $data);
return $this->db->insert_id();
}
public function save_shipping_address($data)
{
$this->db->insert('tbl_shipping', $data);
return $this->db->insert_id();
}
public function get_customer_info($data)
{
$this->db->select('*');
$this->db->from('tbl_customer');
$this->db->where($data);
$info = $this->db->get();
return $info->row();
}
public function get_self_customer_info($id)
{
$this->db->select('*');
$this->db->from('tbl_customer');
$this->db->where('tbl_customer.customer_id', $id);;
$info = $this->db->get();
return $info->row();
}
public function get_order_history($id)
{
$this->db->select('*');
$this->db->from('tbl_order');
$this->db->join('tbl_shipping', 'tbl_shipping.shipping_id=tbl_order.shipping_id');
$this->db->where('tbl_order.customer_id', $id);
$info = $this->db->get();
return $info->result();
}
public function update_self_customer_info($data, $id)
{
$this->db->where('customer_id', $id);
return $this->db->update('tbl_customer', $data);
}
public function delete_order_info($id)
{
$this->db->select('*');
$this->db->from('tbl_order');
$this->db->where('order_id', $id);
$this->db->where('actions', 0);
$info = $this->db->get();
if ($info->num_rows()) {
$this->db->where('order_id', $id);
$this->db->where('actions', 0);
$this->db->delete('tbl_order');
return 1;
} else {
return 0;
}
}
public function get_all_order_detail_by_order($id)
{
$this->db->select('*');
$this->db->from('tbl_order_details');
$this->db->where('tbl_order_details.order_id', $id);
$info = $this->db->get();
return $info->result();
}
public function delete_order_details_info($id)
{
$this->db->where('order_id', $id);
return $this->db->delete('tbl_order_details');
}
public function delete_shipping_info($id)
{
$this->db->where('shipping_id', $id);
return $this->db->delete('tbl_shipping');
}
public function get_promo_value($data)
{
$this->db->select('promo_value');
$this->db->from('tbl_promo');
$this->db->where('tbl_promo.promo_code', $data);
$this->db->where('tbl_promo.active_code', 1);
$info = $this->db->get();
return $info->row();
}
public function save_order_info($data)
{
$this->db->insert('tbl_order', $data);
return $this->db->insert_id();
}
public function save_order_details_info($oddata)
{
$this->db->insert('tbl_order_details', $oddata);
}
public function get_all_slider_post()
{
$this->db->select('*');
$this->db->from('tbl_slider');
$this->db->where('publication_status', 1);
$info = $this->db->get();
return $info->result();
}
public function get_all_popular_posts()
{
$this->db->select('*');
$this->db->from('tbl_product');
$this->db->where('publication_status', 1);
$this->db->where("product_quantity > 0");
$this->db->limit(4);
$info = $this->db->get();
return $info->result();
}
public function get_all_search_product($search)
{
$this->db->select('*');
$this->db->from('tbl_product');
$this->db->join('tbl_category', 'tbl_category.id=tbl_product.product_category');
$this->db->join('tbl_brand', 'tbl_brand.brand_id=tbl_product.product_brand');
$this->db->order_by('tbl_product.product_id', 'DESC');
$this->db->where('tbl_product.product_quantity > ', 0);
$this->db->where('tbl_product.publication_status', 1);
$this->db->like('tbl_product.product_title', $search, 'both');
$this->db->or_like('tbl_product.product_short_description', $search, 'both');
$this->db->or_like('tbl_product.product_long_description', $search, 'both');
$this->db->or_like('tbl_category.category_name', $search, 'both');
$this->db->or_like('tbl_brand.brand_name', $search, 'both');
$info = $this->db->get();
return $info->result();
}
}
|
package com.github.ezauton.core.util
import com.github.ezauton.conversion.ms
import com.github.ezauton.conversion.seconds
import com.github.ezauton.core.action.*
import com.github.ezauton.core.simulation.parallel
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.util.concurrent.TimeoutException
class ActionTest {
@Test
fun `overloaded periodic tries to become stable`() = runBlocking{
var bool = false
var timesRun = 0
val period = 20.ms
val duration = 2.seconds
val timedPeriodicAction = periodicAction(period, duration = duration) {
timesRun += 1
if (!bool) {
bool = true
delay(1_000.ms)
}
}
try {
timedPeriodicAction.runWithTimeout(2_500.ms)
} catch (ignored: TimeoutException) {
}
val expected = duration / period
assertEquals(expected, timesRun.toDouble(), 2.0)
}
@Test
fun `action group of parallels test`() = runBlocking {
var counter = 0
val actionGroup = action {
parallel { counter++ }
parallel { counter++ }
parallel { counter++ }
}
actionGroup.run()
assertEquals(3, counter)
}
@Test
fun `ephemeral actions test`() = runBlocking {
var counter = 0
val actionGroup = action {
parallel {
delay(3.seconds)
if (counter == 1) counter++
}
ephemeralScope {
parallel {
delay(2.seconds)
if (counter == 1) counter++
}
delay(1.seconds)
if (counter == 0) counter++
}
}
actionGroup.runWithTimeout(4.seconds)
assertEquals(2, counter)
}
}
|
# slugboot
aggressively cache at the application layer for offline-only webapps
With this module serving as a kind of web bios, you can create identical "slug"
domains (with https certs) that can be flashed with any application. The
application payload is stored in indexedDB.
This way, you can load webapps from p2p networks over webrtc, bluetooth LE,
or acoustic couplers. The webapps stay saved on your computer and you can open
them on a slug domain whenever you wish.
# security
slugboot uses trust on first use to initialize a generic webapp container that
cannot be updated except through an application's own direct intervention.
Unfortunately, until ServiceWorker version 2 ships with a
[Service-Worker-Max-Age][1] header, service worker
[Max-Age is capped to 24 hours][2]. This means the original domain that loaded
the slugboot worker could later ship a malicious version of `/worker.js`.
To mitigate this attack for now, users should add a record in `/etc/hosts` for
slugbooted domains that points back to localhost. For example:
```
127.0.0.1 slug.example.com
```
The request or certificate check will fail for requests to `/worker.js`, so the old
worker will continue to run as before.
[1]: https://github.com/slightlyoff/ServiceWorker/issues/721
[2]: https://github.com/slightlyoff/ServiceWorker/blob/master/explainer.md#updating-a-service-worker
# example
create a main.js file:
``` js
var slug = require('slugboot')('/worker.js')
slug.version(function (err, v) {
if (err) return console.error(err)
if (v) return console.log('already uploaded a version')
slug.fetch('/')
slug.fetch('/bundle.js')
slug.fetch('/worker.js')
slug.put('/hello.txt', 'HI THERE')
slug.commit(function (err) {
if (err) return console.error(err)
else console.log('uploaded version')
})
})
window.slug = slug
```
set up `public/` with the slugboot worker.js file:
```
$ npm i -g browserify ecstatic
$ mkdir public
$ echo '<script src="bundle.js"></script>' > public/index.html
$ cp `node -pe "require.resolve('slugboot/worker.js')"` public/
$ browserify main.js > public/bundle.js
$ ecstatic -H 'Service-Worker-Max-Age: 3153600000000' -p 44000 public/
```
Now open `http://localhost:44000` and poke around with the `slug` instance on
the REPL.
# api
``` js
var slugboot = require('slugboot')
```
## var slug = slugboot(workerURL)
Create a new slugboot instance from a `workerURL` path string to the slugboot
service worker code.
## slug.put(path, body, cb)
Stage a string `body` to be saved at the path string `path`.
`cb(err)` fires with any errors.
## slug.fetch(src, dst, cb)
Request the document at the url string `src` and save the result to the path at
`dst`.
If `dst` is not given, it will use the pathname of `src`.
`cb(err)` fires with any errors.
## slug.copy(src, dst, cb)
Copy the file path `src` from the current active version to `dst` in the staging
version.
`cb(err)` fires with any errors.
## slug.commit(cb)
Commit any staged changes and increment the version.
`cb(err)` fires with any errors.
## slug.version(cb)
Query for the integer version as `cb(err, version)`.
Before flashing, the `version` will be undefined.
The first version after a commit is version 1.
# install
```
npm install slugboot
```
# license
BSD
|
---
id: environment-variables
title: Environment Variables
---
The following is a list of the environment variables used by Apify SDK that are available to the user:
## `APIFY_HEADLESS`
If set to `1`, web browsers launched by Apify SDK will run in the headless mode. You can still override
this setting in the code, e.g. by passing the `headless: true` option to the
[`Apify.launchPuppeteer()`](/docs/api/apify#launchPuppeteer) function. But having this setting
in an environment variable allows you to develop the crawler locally in headful mode to simplify the debugging,
and only run the crawler in headless mode once you deploy it to the Apify Cloud. By default, the browsers
are launched in headful mode, i.e. with windows.
## `APIFY_LOCAL_STORAGE_DIR`
Defines the path to a local directory where [`KeyValueStore`](/docs/api/key-value-store),
[`Dataset`](/docs/api/dataset), and [`RequestQueue`](/docs/api/request-queue) store their data.
Typically it is set to `./apify_storage`. If omitted, you should define the [`APIFY_TOKEN`](#APIFY_TOKEN)
environment variable instead.
## `APIFY_LOG_LEVEL`
Specifies the minimum log level, which can be one of the following values (in order of severity):
`DEBUG`, `INFO`, `WARNING` and `ERROR`. By default, the log level is set to `INFO`,
which means that `DEBUG` messages are not printed to console. See the [`utils.log`](/docs/api/log)
namespace for logging utilities.
## `APIFY_MEMORY_MBYTES`
Sets the amount of system memory in megabytes to be used by the [`AutoscaledPool`](/docs/api/autoscaled-pool).
It is used to limit the number of concurrently running tasks. By default, the max amount of memory
to be used is set to one quarter of total system memory, i. e. on a system with 8192 MB of memory,
the autoscaling feature will only use up to 2048 MB of memory.
## `APIFY_PROXY_PASSWORD`
Optional password to [Apify Proxy](https://docs.apify.com/proxy) for IP address rotation.
If you have have an Apify Account, you can find the password on the [Proxy page](https://my.apify.com/proxy)
in the Apify app. This feature is optional. You can use your own proxies or no proxies at all.
## `APIFY_TOKEN`
The API token for your Apify Account. It is used to access the Apify API, e.g. to access cloud storage
or to run an actor in the Apify Cloud. You can find your API token on the
[Account - Integrations](https://my.apify.com/account#integrations) page. If omitted,
you should define the `APIFY_LOCAL_STORAGE_DIR` environment variable instead.
|
<?php
namespace GDO\RandomOrg\Test;
use GDO\Tests\TestCase;
use GDO\RandomOrg\Module_RandomOrg;
use function PHPUnit\Framework\assertLessThanOrEqual;
use function PHPUnit\Framework\assertGreaterThanOrEqual;
final class RandomTest extends TestCase
{
public function testAPI()
{
$mod = Module_RandomOrg::instance();
$n = $mod->cfgChunkSize() + 10; # test to exceed chunk size.
$sum = 0;
for ($i = 0; $i < $n; $i++)
{
$rand = $mod->rand(1, 10);
if (!$rand)
{
echo 1;
}
$sum += $rand;
assertLessThanOrEqual(10, $rand, 'TestMax if random number is in range');
assertGreaterThanOrEqual(1, $rand, 'TestMin if random number is in range');
}
$sum /= $n;
assertLessThanOrEqual(6.0, $sum, 'TestMax if random number stochastic matches.');
assertGreaterThanOrEqual(5.0, $sum, 'TestMin if random number stochastic matches.');
}
}
|
module.exports = {
options: {
// On TravisCI, sometimes the tests that require I/O need extra time.
timeout: 10000,
reporter: 'mocha-multi',
reporterOptions: {
spec: '-',
},
},
unit: ['dist/unit-tests.js'],
functional: ['dist/functional-tests.js'],
};
if (process.env.COVERAGE === 'y') {
var path = require('path');
var coverageReporterModulePath = path.resolve(
path.join(__dirname, '..', '..', 'tests', 'coverage-reporter.js')
);
module.exports.options.reporterOptions[coverageReporterModulePath] = '-';
}
|
import { Listable } from "../../common/Listable";
import { probablyUniqueString } from "../../common/Toolbox";
import { DurationTiming } from "../Combatant/DurationTiming";
import { StatBlock } from "../StatBlock/StatBlock";
export interface SavedCombatant {
Id: string;
StatBlock: StatBlock;
MaxHP: number;
CurrentHP: number;
TemporaryHP: number;
Initiative: number;
InitiativeGroup?: string;
Alias: string;
IndexLabel: number;
Tags: string[] | SavedTag[];
Hidden: boolean;
InterfaceVersion: string;
}
export interface SavedTag {
Text: string;
DurationRemaining: number;
DurationTiming: DurationTiming;
DurationCombatantId: string;
}
export interface SavedEncounter<T> extends Listable {
ActiveCombatantId: string;
RoundCounter?: number;
Combatants: T[];
}
export function DefaultSavedEncounter(): SavedEncounter<SavedCombatant> {
return {
ActiveCombatantId: null,
RoundCounter: 0,
Combatants: [],
Name: "DEFAULT_SAVED_ENCOUNTER",
Id: probablyUniqueString(),
Path: "",
Version: process.env.VERSION,
};
}
|
/*
* Copyright (c) 2014. Pokevian 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.
*/
package com.pokevian.app.smartfleet.ui.common;
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.pokevian.app.smartfleet.R;
public class WaitForDialog extends Dialog {
public WaitForDialog(Context context) {
super(context, R.style.AppTheme_Dialog_Transparent);
setContentView(R.layout.dialog_waitfor);
}
public WaitForDialog(Context context, int messageResId) {
this(context, R.style.AppTheme_Light_Dialog, messageResId);
}
public WaitForDialog(Context context, int theme, int messageResId) {
super(context, theme);
View view = LayoutInflater.from(context).inflate(R.layout.dialog_waitfor, null);
TextView messageText = (TextView) view.findViewById(R.id.message);
messageText.setText(messageResId);
messageText.setVisibility(View.VISIBLE);
setContentView(view);
}
}
|
package com.lucasrochagit.src.business.mapper;
import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.lucasrochagit.src.business.mapper.interfaces.IFileModelMapper;
import com.lucasrochagit.src.business.model.FileModel;
import com.lucasrochagit.src.infrastructure.entity.FileEntity;
import org.springframework.stereotype.Service;
@Service
public class FileModelMapper implements IFileModelMapper {
private final Mapper mapper = DozerBeanMapperBuilder.buildDefault();
@Override
public FileModel serialize(FileEntity fileEntity) {
return mapper.map(fileEntity, FileModel.class);
}
@Override
public FileEntity deserialize(FileModel fileModel) {
return mapper.map(fileModel, FileEntity.class);
}
}
|
package com.willoutwest.kalahari.asset.readers
import com.willoutwest.kalahari.asset.AssetCache
import com.willoutwest.kalahari.asset.AssetKey
import com.willoutwest.kalahari.asset.AssetReader
import com.willoutwest.kalahari.math.Color3
import com.willoutwest.kalahari.math.intToComponent
import com.willoutwest.kalahari.texture.Image
import java.io.InputStream
import javax.imageio.ImageIO
/**
* Represents an implementation of [AssetReader] that converts an input
* stream to an image
*/
class ImageReader : AssetReader {
override fun load(key: AssetKey, stream: InputStream,
assets: AssetCache): Any {
val buffered = ImageIO.read(stream)
val data = mutableListOf<Color3>()
for(y in 0 until buffered.height) {
for(x in 0 until buffered.width) {
val rgb = buffered.getRGB(x, y)
val blue = intToComponent(rgb and 0xff)
val green = intToComponent((rgb and 0xff00) shr 8)
val red = intToComponent((rgb and 0xff0000) shr 16)
data.add(Color3(red, green, blue))
}
}
return Image(buffered.width, buffered.height, data)
}
}
|
export default {
"port": 8080,
"bodyLimit": "100kb",
"corsHeaders": ["Link"]
}
|
<?php
namespace EasyAI;
class Stack
{
private $open = [];
private $done = [];
public function clear()
{
$this->open = [];
$this->done = [];
}
/**
* Function adds URL into stack and if it is new or existing but not yet parsed
* returns StackItem object
* if old and parsed already returns FALSE.
*
* @access public
* @param string $url The url of the endpoint.
* @return StackItem The new object to work with, or FALSE if object done already.
*/
public function add($url, StackItem $itemClass = null)
{
$item = null;
if ($url instanceof StackItem) {
$item = $url;
} else {
if ($itemClass) {
$name = get_class($itemClass);
$item = new $name($url);
} else {
$item = new StackItem($url);
}
}
if (!$item) {
return false;
}
if (isset($this->done[$item->hash])) {
return false;
}
$this->open[$item->hash] = $item;
return $item;
}
/**
* Function checks for open/waiting item in stack and if it is so it is moving
* to complete/done stack, so less items left opened.
*
* @access public
* @param StackItem $item The item to reveal.
* @return TRUE if item moved from open to complete, FALSE if complete already.
*/
public function reveal(StackItem $item)
{
if (isset($this->open[$item->hash])) {
$this->done[$item->hash] = $item;
unset($this->open[$item->hash]);
return true;
}
return false;
}
/**
* To be fare we work with FIFO model.
* So returns the first item which were added.
* Php does not sort assoc arrays by keywors as js does with objects,
* so we can easily return [first in] item.
*
* @access public
* @return StackItem The item if exists (at least one) and FALSE if not.
*/
public function pop()
{
if (count($this->open)) {
return reset($this->open);
}
return false;
}
/**
* Return count of open items.
*
* @access public
* @return int The count.
*/
public function length()
{
return count($this->open);
}
}
|
@if($product->qty >= 0)
<form method="post" action="{{ route('cart.add-to-cart') }}">
{{ csrf_field() }}
<input type="hidden" name="slug" value="{{ $product->slug }}"/>
<div class="badge badge-success fill">In Stock</div>
<hr>
<div class="row">
<div class="form-group col-md-2" style="">
<label>Qty</label>
<input type="number" name="qty" class="form-control" value="1"/>
</div>
</div>
<div class="clearfix"></div>
<div class="float-left" style="margin-right: 5px;">
<button type="submit" class="btn btn-primary" href="{{ route('cart.add-to-cart', $product->id) }}">
Add to Cart
</button>
</div>
</form>
@else
<div class="product-stock text-danger">Out of Stock</div>
<hr>
<div class="row">
<div class="form-group col-md-2" style="">
<label>Qty</label>
<input type="text" disabled="" name="qty" class="form-control" value="1"/>
</div>
</div>
<div class="clearfix"></div>
<div class="float-left" style="margin-right: 5px;">
<button type="button" disabled class="btn btn-default" href="#">Add to Cart</button>
</div>
@endif
|
#!/usr/bin/env bash
set -Eeuo pipefail
exec::git::stash() {
exec command git stash "$@"
}
setup_colors() {
if [[ -t 2 ]] && [[ -z "${NO_COLOR-}" ]] && [[ "${TERM-}" != "dumb" ]]; then
NOFORMAT='\033[0m' RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m'
fi
}
msg() {
echo >&2 -e "${1-}"
}
info() {
msg "${GREEN}$1${NOFORMAT}"
}
warn() {
msg "${YELLOW}$1${NOFORMAT}"
}
err() {
msg "${RED}$1${NOFORMAT}"
}
die() {
err "${1-}"
exit "${2-1}"
}
NOFORMAT='' RED='' GREEN='' YELLOW=''
first_argument="${1-}"
if [[ "$first_argument" = "save" ]]; then
die "$0 $first_argument is deprecated so the execution is prohibided."
fi
if [[ "$first_argument" =~ -.* ]]; then
subcommand="push"
elif (("$# > 0")); then
subcommand="$first_argument"
shift 1
else
subcommand="push"
fi
if [[ ! "$subcommand" = "push" ]]; then
exec::git::stash "$subcommand" "$@"
fi
_args=()
message=''
while :; do
if (("$# == 0")); then
break
fi
case "${1-}" in
-m | --message)
message="${2-}"
shift
;;
*)
_args+=("${1-}")
;;
esac
shift
done
if [[ -z "$message" ]]; then
die "-m <a reason why you stach changes> is required to avoid confusion."
fi
branch_name="$(git rev-parse --abbrev-ref HEAD)"
head_log="$(git log --pretty="format:%h %s" -1)"
# git stash's message can't handle branch names that contain '/' properly
IFS=" " set -- "-m" "$branch_name ($(git rev-parse --short HEAD)): because of $message. ref: $head_log" "${_args[@]}"
exec::git::stash push "$@"
|
aws iam remove-role-from-instance-profile \
--instance-profile-name=aws-elasticbeanstalk-ec2-role \
--role-name=aws-elasticbeanstalk-ec2-role
|
import { GetServerSidePropsContext } from 'next'
import { getSession, useSession } from 'next-auth/client'
import { Stack } from '@chakra-ui/react'
import prisma from '../../lib/prisma'
import { ADMIN_INCLUDE, AdminStory } from '../../lib/model/story'
import AdminLayout from '../../layouts/Admin'
import HeadTags from '../../components/common/HeadTags'
import ContentBox from '../../components/common/ContentBox'
import StoryCard from '../../components/admin/StoryCard'
interface AdminPageProps {
stories: AdminStory[] | []
filtered: boolean
}
function AdminPage({ stories, filtered }: AdminPageProps) {
const [session] = useSession()
return (
<>
<HeadTags>
<meta name="robots" content="noindex" />
</HeadTags>
<ContentBox pb={2}>
<Stack spacing={8}>
{session && (
<>
{stories.map((story) => (
<StoryCard key={story.id} story={story} filteredView={filtered} />
))}
</>
)}
</Stack>
</ContentBox>
</>
)
}
AdminPage.setLayout = AdminLayout
export default AdminPage
export async function getServerSideProps({ req, query }: GetServerSidePropsContext) {
const session = await getSession({ req })
const deleted = query.deleted === 'true'
const approved = query.approved === 'true'
let stories = []
if (session) {
stories = await prisma.story.findMany({
where: {
approved,
deleted,
},
orderBy: { createdAt: 'asc' },
include: ADMIN_INCLUDE,
})
}
return {
props: { stories, filtered: deleted || approved },
}
}
|
"""
Helper functions to load and save CSV data.
This contains a helper function for loading and saving CSV files.
"""
# Import csv
import csv
# Import Path from pathlib
from pathlib import Path
def load_csv(csvpath):
"""
Reads the CSV file from path provided.
Args:
csvpath (Path): The csv file path.
Returns:
A list of lists that contains the rows of data from the CSV file.
"""
# Reference the file path the user inputted in app.py
with open(csvpath, "r") as csvfile:
# Create an empty list to append filtered data to
data = []
# Read the list of all bank loans
csvreader = csv.reader(csvfile, delimiter=",")
# Skip the csv Header
next(csvreader)
# Read the csv data
for row in csvreader:
# Append rows of qualifying loans to the data list container
data.append(row)
# Return the list of qualifying bank loans
return data
# Create a new function called save_csv to export a csv file
def save_csv(data):
bank_data = data
# Create headers for the export file
header = ["Lender" , "Max Loan", "Max LTV", "Max DTI", "Min Credit Score", "Interest Rate"]
# Create output path for csv file
csvexportpath = Path("qualifying_loans.csv")
# Open and write the csv file
with open(csvexportpath, "w", newline = '') as csvfile:
# Write the csv
csvwriter = csv.writer(csvfile, delimiter = ",")
# Write the headers to the csv
csvwriter.writerow(header)
# Write the rows of qualifying loans to the csv
for loan in bank_data:
csvwriter.writerow(loan)
# Return the saved csv file
return data
|
/* Copyright © 2021 HornsApp. All rights reserved. */
package com.yesferal.hornsapp.core.domain.usecase
import com.yesferal.hornsapp.core.MockitoTest
import com.yesferal.hornsapp.core.domain.abstraction.ConcertRepository
import com.yesferal.hornsapp.core.domain.entity.Concert
import com.yesferal.hornsapp.core.domain.entity.drawer.CategoryDrawer
import com.yesferal.hornsapp.core.domain.util.HaResult
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito
/**
* This class will test [GetUpcomingConcertsUseCase]
*
* @author Yesferal
*/
class GetUpcomingConcertsUseCaseTest: MockitoTest {
private val METAL = "METAL"
@Mock
lateinit var concertRepository: ConcertRepository
lateinit var filterConcertsByCategoryUseCase: FilterConcertsByCategoryUseCase
lateinit var getUpcomingConcertsUseCase: GetUpcomingConcertsUseCase
@Before
override fun mockClasses() {
filterConcertsByCategoryUseCase = FilterConcertsByCategoryUseCase()
runBlocking {
Mockito.`when`(concertRepository.getConcerts())
.thenReturn(HaResult.Success(getConcerts()))
}
}
private fun getConcerts() = listOf(
Concert.Builder("1").addTimeInMillis(100).addTags(listOf(METAL, "ROCK")).build(),
Concert.Builder("2").addTimeInMillis(90).addTags(listOf("ROCK")).build(),
Concert.Builder("3").addTimeInMillis(80).build(),
Concert.Builder("4").addTimeInMillis(70).addTags(listOf("JAZZ", METAL)).build(),
Concert.Builder("5").addTimeInMillis(60).addTags(listOf(METAL)).build()
)
@Test
fun givenGetConcerts_WhenAllTagsAreRequested_ThenReturnWholeList() {
runBlocking {
// Given
getUpcomingConcertsUseCase = GetUpcomingConcertsUseCase(concertRepository, filterConcertsByCategoryUseCase)
// When
val filter = CategoryDrawer.ALL
val result = getUpcomingConcertsUseCase.invoke(filter)
// Then
val expected = 5
Assert.assertEquals(true, result is HaResult.Success)
Assert.assertEquals(expected, (result as HaResult.Success).value.size)
}
}
@Test
fun givenGetConcerts_WhenATagIsRequested_ThenReturnTheListFiltered() {
runBlocking {
// Given
getUpcomingConcertsUseCase = GetUpcomingConcertsUseCase(concertRepository, filterConcertsByCategoryUseCase)
// When
val filter = METAL
val result = getUpcomingConcertsUseCase.invoke(filter)
// Then
val expected = 3
Assert.assertEquals(true, result is HaResult.Success)
Assert.assertEquals(expected, (result as HaResult.Success).value.size)
Assert.assertNotEquals(null, result.value[0].tags)
Assert.assertEquals(true, result.value[0].tags!!.contains(METAL))
Assert.assertNotEquals(null, result.value[1].tags)
Assert.assertEquals(true, result.value[1].tags!!.contains(METAL))
Assert.assertNotEquals(null, result.value[2].tags)
Assert.assertEquals(true, result.value[2].tags!!.contains(METAL))
}
}
@Test
fun givenGetConcerts_WhenAreRequested_ThenReturnSortByTimeInMillis() {
runBlocking {
// Given
getUpcomingConcertsUseCase = GetUpcomingConcertsUseCase(concertRepository, filterConcertsByCategoryUseCase)
// When
val filter = CategoryDrawer.ALL
val result = getUpcomingConcertsUseCase.invoke(filter)
// Then
val expected = 5
Assert.assertEquals(true, result is HaResult.Success)
Assert.assertEquals(expected, (result as HaResult.Success).value.size)
Assert.assertEquals(60L, result.value[0].timeInMillis)
Assert.assertEquals(70L, result.value[1].timeInMillis)
Assert.assertEquals(80L, result.value[2].timeInMillis)
Assert.assertEquals(90L, result.value[3].timeInMillis)
Assert.assertEquals(100L, result.value[4].timeInMillis)
}
}
}
|
import HeaderBackground from './HeaderBackground'
import headerOptions from './headerOptions'
import HeaderTitle from './HeaderTitle'
export { HeaderBackground, headerOptions, HeaderTitle }
|
package main
import "fmt"
func main() {
a := []byte("foo")
b := append(a, []byte("bar")...)
c := append(a, []byte("baz")...)
fmt.Println(string(a), string(b), string(c))
}
|
// ELECTRO ENGINE
// Copyright(c) 2021 - Electro Team - All rights reserved
#include "epch.hpp"
namespace Electro
{
struct ExporterOptions
{
String ExportPath;
String ApplicationName;
};
class RuntimeExporter
{
public:
// Exports the currently active Project
static void ExportCurrent(const ExporterOptions& options);
};
}
|
package br.com.jfelipe.kart.domain.race
import br.com.jfelipe.kart.domain.shared.Pilot
import java.time.LocalTime
import java.time.format.DateTimeFormatter.ISO_LOCAL_TIME
import java.time.format.DateTimeFormatterBuilder
import java.time.temporal.ChronoField.HOUR_OF_DAY
data class Lap(
val hour: LocalTime,
val number: Int,
val time: LocalTime,
val averageSpeed: Float,
val pilot: Pilot
) {
companion object {
private val MAX_LAPS = 4
private val LOCAL_TIME_WITHOUT_HOURS = DateTimeFormatterBuilder()
.appendPattern("m:ss.SSS")
.parseDefaulting(HOUR_OF_DAY, 0)
.toFormatter()
}
class Builder {
private var hour: LocalTime? = null
private var number: Int? = null
private var time: LocalTime? = null
private var averageSpeed: Float? = null
private var pilot: Pilot? = null
fun hour(hour: String) = apply { this.hour = LocalTime.parse(hour, ISO_LOCAL_TIME) }
fun number(number: String): Builder {
if (number.toInt() > MAX_LAPS) {
throw IllegalArgumentException("Number max laps are $MAX_LAPS")
} else {
this.number = number.toInt()
}
return this
}
fun time(time: String) = apply { this.time = LocalTime.parse(time, LOCAL_TIME_WITHOUT_HOURS) }
fun averageSpeed(averageSpeed: String) = apply { this.averageSpeed = averageSpeed.replace(',', '.').toFloat() }
fun pilot(pilot: Pilot) = apply { this.pilot = pilot }
fun build() = Lap(
hour ?: error("Lap hour is required"),
number ?: error("Lap number is required"),
time ?: error("Lap time is required"),
averageSpeed ?: error("Lap average speed is required"),
pilot ?: error("Lap shared is required")
)
}
}
|
/*
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*
*/
package com.microsoft.device.display.samples.widget.feed
data class RssItem(
var title: String?,
var creator: String?,
var date: String?,
var body: String?,
var href: String?
)
|
[{
shouldDeps : ['tick', 'idle']
},
{
tech : 'spec.js',
shouldDeps : { tech : 'js', block : 'dom' }
}]
|
; ModuleID = 'amy-module'
source_filename = "<string>"
%Either = type { i1, i64* }
declare i8* @GC_malloc(i64)
define %Either* @h() {
entry:
%0 = getelementptr %Either, %Either* null, i32 1
%1 = ptrtoint %Either* %0 to i64
%2 = call i8* @GC_malloc(i64 %1)
%res1 = bitcast i8* %2 to %Either*
%res11 = alloca %Either
%3 = getelementptr %Either, %Either* %res11, i32 0, i32 0
store i1 true, i1* %3
%4 = getelementptr i64, i64* null, i32 1
%5 = ptrtoint i64* %4 to i64
%6 = call i8* @GC_malloc(i64 %5)
%7 = bitcast i8* %6 to i64*
store i64 1, i64* %7
%8 = getelementptr %Either, %Either* %res11, i32 0, i32 1
store i64* %7, i64** %8
%9 = getelementptr %Either, %Either* null, i32 1
%10 = ptrtoint %Either* %9 to i64
%11 = call i8* @GC_malloc(i64 %10)
%ret = bitcast i8* %11 to %Either*
%ret2 = alloca %Either
%12 = getelementptr %Either, %Either* %ret2, i32 0, i32 0
store i1 true, i1* %12
%13 = bitcast %Either* %res11 to i64*
%14 = getelementptr %Either, %Either* %ret2, i32 0, i32 1
store i64* %13, i64** %14
ret %Either* %ret2
}
define %Either* @f() {
entry:
%0 = getelementptr %Either, %Either* null, i32 1
%1 = ptrtoint %Either* %0 to i64
%2 = call i8* @GC_malloc(i64 %1)
%res2 = bitcast i8* %2 to %Either*
%res21 = alloca %Either
%3 = getelementptr %Either, %Either* %res21, i32 0, i32 0
store i1 false, i1* %3
%4 = getelementptr i64, i64* null, i32 1
%5 = ptrtoint i64* %4 to i64
%6 = call i8* @GC_malloc(i64 %5)
%7 = bitcast i8* %6 to i64*
store i64 42, i64* %7
%8 = getelementptr %Either, %Either* %res21, i32 0, i32 1
store i64* %7, i64** %8
%9 = getelementptr %Either, %Either* %res21, i32 0, i32 0
%10 = load i1, i1* %9
%11 = getelementptr %Either, %Either* %res21, i32 0, i32 1
%12 = load i64*, i64** %11
switch i1 %10, label %case.0.ret [
i1 false, label %case.0.ret
i1 true, label %case.1.ret
]
case.0.ret: ; preds = %entry, %entry
%_u2 = load i64, i64* %12
%13 = getelementptr %Either, %Either* null, i32 1
%14 = ptrtoint %Either* %13 to i64
%15 = call i8* @GC_malloc(i64 %14)
%16 = bitcast i8* %15 to %Either*
%17 = alloca %Either
%18 = getelementptr %Either, %Either* %17, i32 0, i32 0
store i1 false, i1* %18
%19 = getelementptr i64, i64* null, i32 1
%20 = ptrtoint i64* %19 to i64
%21 = call i8* @GC_malloc(i64 %20)
%22 = bitcast i8* %21 to i64*
store i64 %_u2, i64* %22
%23 = getelementptr %Either, %Either* %17, i32 0, i32 1
store i64* %22, i64** %23
br label %case.end.ret
case.1.ret: ; preds = %entry
%24 = alloca i64*
store i64* %12, i64** %24
%_u3 = load i64*, i64** %24
%25 = getelementptr %Either, %Either* null, i32 1
%26 = ptrtoint %Either* %25 to i64
%27 = call i8* @GC_malloc(i64 %26)
%28 = bitcast i8* %27 to %Either*
%29 = alloca %Either
%30 = getelementptr %Either, %Either* %29, i32 0, i32 0
store i1 true, i1* %30
%31 = getelementptr %Either, %Either* %29, i32 0, i32 1
store i64* %_u3, i64** %31
br label %case.end.ret
case.end.ret: ; preds = %case.1.ret, %case.0.ret
%ret = phi %Either* [ %17, %case.0.ret ], [ %29, %case.1.ret ]
ret %Either* %ret
}
define i64 @main() {
entry:
%res3 = call %Either* @f()
%0 = getelementptr %Either, %Either* %res3, i32 0, i32 0
%1 = load i1, i1* %0
%2 = getelementptr %Either, %Either* %res3, i32 0, i32 1
%3 = load i64*, i64** %2
switch i1 %1, label %case.0.ret [
i1 false, label %case.0.ret
i1 true, label %case.1.ret
]
case.0.ret: ; preds = %entry, %entry
%_u10 = load i64, i64* %3
%4 = alloca i64
store i64 %_u10, i64* %4
%5 = load i64, i64* %4
br label %case.end.ret
case.1.ret: ; preds = %entry
%_u11 = load i64, i64* %3
%res4 = call %Either* @h()
%6 = getelementptr %Either, %Either* %res4, i32 0, i32 0
%7 = load i1, i1* %6
%8 = getelementptr %Either, %Either* %res4, i32 0, i32 1
%9 = load i64*, i64** %8
switch i1 %7, label %case.0.6 [
i1 false, label %case.0.6
i1 true, label %case.1.6
]
case.0.6: ; preds = %case.1.ret, %case.1.ret
%_u6 = load i64, i64* %9
%10 = alloca i64
store i64 %_u6, i64* %10
%11 = load i64, i64* %10
br label %case.end.6
case.1.6: ; preds = %case.1.ret
%_u7 = bitcast i64* %9 to %Either*
%12 = getelementptr %Either, %Either* %_u7, i32 0, i32 0
%13 = load i1, i1* %12
%14 = getelementptr %Either, %Either* %_u7, i32 0, i32 1
%15 = load i64*, i64** %14
switch i1 %13, label %case.0.13 [
i1 false, label %case.0.13
i1 true, label %case.1.13
]
case.0.13: ; preds = %case.1.6, %case.1.6
%_u8 = load i64, i64* %15
%16 = alloca i64
store i64 %_u8, i64* %16
%17 = load i64, i64* %16
br label %case.end.13
case.1.13: ; preds = %case.1.6
%_u9 = load i64, i64* %15
%18 = alloca i64
store i64 %_u11, i64* %18
%19 = load i64, i64* %18
br label %case.end.13
case.end.13: ; preds = %case.1.13, %case.0.13
%20 = phi i64 [ %17, %case.0.13 ], [ %19, %case.1.13 ]
br label %case.end.6
case.end.6: ; preds = %case.end.13, %case.0.6
%21 = phi i64 [ %11, %case.0.6 ], [ %20, %case.end.13 ]
br label %case.end.ret
case.end.ret: ; preds = %case.end.6, %case.0.ret
%ret = phi i64 [ %5, %case.0.ret ], [ %21, %case.end.6 ]
ret i64 %ret
}
|
package uo.sdm.mapintegrationapp.persistence.tables;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import uo.sdm.mapintegrationapp.model.Place;
import uo.sdm.mapintegrationapp.model.types.PlaceType;
/**
* Created by Hans on 25/06/2015.
*/
public class PlacesTable {
public static final String TABLE_NAME = "places";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_LATITUDE = "latitude";
public static final String COLUMN_LONGITUDE = "longitude";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_RESEARCHING = "researching";
public static final String COLUMN_RESEARCH_END = "research_end";
public static final String CREATE = "CREATE TABLE "
+ TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_LATITUDE + " REAL NOT NULL, "
+ COLUMN_LONGITUDE + " REAL NOT NULL, "
+ COLUMN_TYPE + " TEXT NOT NULL, "
+ COLUMN_RESEARCHING + " BOOLEAN NOT NULL, "
+ COLUMN_RESEARCH_END + " INT NOT NULL"
+ ");";
public static final String DROP = "DROP TABLE IF EXISTS " + TABLE_NAME;
public static void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE);
}
public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP);
onCreate(db);
}
}
|
function save_loc()
loc=""
if haskey(ENV,"FW_SAVE_LOC")
loc=ENV["FW_SAVE_LOC"]
else
loc=ENV["APPDATA"]*"/FoamWorld/sav/"
ENV["FW_SAVE_LOC"]=loc
end
end
function save_game(g::Game,path::String=save_loc()*g.set["name"])
if !isdir(path)
mkdir(path)
end
cd(path)
write_code("setting.fw",g.set)
end
function load_game(path::String)
g=Game()
cd(path)
g.set=read_code("setting.fw")
end
function get_loadedimg(s::String)
if haskey(loadedimgs,s)
return @inbounds loadedimgs[s]
else
return loadedimgs["notexture"]
end
end
|
# FSM
A small library which implements an event-driven FSM, where the implementation
exists entirely within state entry and exit handlers.
## Usage
The first step is to define the set of states and events which are involved in
the FSM. This is accomplished using the `FSM_STATE_DEF(NAME)` and
`FSM_EVENT_DEF(NAME)` macros. Next, all valid transitions should be defined in
an array of `fsm_transition_t` instances. The `FSM_STATE(NAME)` and
`FSM_EVENT(NAME)` macros can be used to referenced the defined states and
events respectively. These macros allow for convenient naming and namespacing
of states and events, while allowing the transitions array to be defined at
compile time, and thus live in program space (.rodata), as opposed to RAM.
A state entry and exit handler should be defined, and passed along with the
the transitions array to fsm_init() to initialize the FSM.
Events are then passed to `fsm_process_event()` which generates appropriate
state entry / exit callbacks, if there is an appropriate transition defined.
## Compile Options
Additional features of the FSM library can be enabled by compiling with the
following defines:
* `FSM_USE_LOGGING` - Controls logging via the `logging` library. Set to 1 to
enable logging of error conditions and state transitions. Set to 2 to also
enable logging of ignored events.
## Example
```
// FSM States
FSM_STATE_DEF(OFF);
FSM_STATE_DEF(GREEN);
FSM_STATE_DEF(RED);
// FSM Events
FSM_EVENT_DEF(REQUESTED_OFF);
FSM_EVENT_DEF(REQUESTED_GREEN);
FSM_EVENT_DEF(REQUESTED_RED);
// FSM Transitions
static const fsm_transition_t LED_FSM_TRANSITIONS[] = {
{FSM_STATE(OFF), FSM_STATE(GREEN), FSM_EVENT(REQUESTED_GREEN)},
{FSM_STATE(OFF), FSM_STATE(RED), FSM_EVENT(REQUESTED_RED)},
{FSM_STATE(GREEN), FSM_STATE(OFF), FSM_EVENT(REQUESTED_OFF)},
{FSM_STATE(GREEN), FSM_STATE(RED), FSM_EVENT(REQUESTED_RED)},
{FSM_STATE(RED), FSM_STATE(OFF), FSM_EVENT(REQUESTED_OFF)},
{FSM_STATE(RED), FSM_STATE(GREEN), FSM_EVENT(REQUESTED_GREEN)},
};
static void fsm_on_state_enter_handler(const fsm_t* fsm, fsm_state_t state) {
if (state == FSM_STATE(GREEN)) {
gpio_set(GREEN_LED_PIN, HIGH);
} else if (state == FSM_STATE(RED)) {
gpio_set(RED_LED_PIN, HIGH);
}
}
static void fsm_on_state_exit_handler(const fsm_t* fsm, fsm_state_t state) {
if (state == FSM_STATE(GREEN)) {
gpio_set(GREEN_LED_PIN, LOW);
} else if (state == FSM_STATE(RED)) {
gpio_set(RED_LED_PIN, LOW);
}
}
void led_thread(void) {
fsm_t fsm = {
.transitions = FSM_TRANSITIONS,
.num_transitions = ARRAY_LENGTH(FSM_TRANSITIONS),
.on_state_enter_handler = fsm_on_state_enter_handler,
.on_state_exit_handler = fsm_on_state_exit_handler,
.initial_state = FSM_STATE(OFF),
};
fsm_init(&fsm);
while (true) {
// get request
if (/* requested off */) {
fsm_process_event(&fsm, FSM_EVENT(REQUESTED_OFF));
} else if (/* requested green */) {
fsm_process_event(&fsm, FSM_EVENT(REQUESTED_GREEN));
} else if (/* requested red */) {
fsm_process_event(&fsm, FSM_EVENT(REQUESTED_RED));
}
}
}
```
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Elm.Render.Render
( writeElmPages,
)
where
import qualified Data.Text.IO as TIO
import Data.Time.Clock (getCurrentTime)
import Elm.Render.Fitness (renderFitnessPage)
import Elm.Render.Running (renderRunningPage)
import Fitness.Garmin
writeElmPages :: IO ()
writeElmPages = do
currentTime <- getCurrentTime
activities <- getActivitiesFromDir fitFileDir
runningPage <- renderRunningPage currentTime activities
fitnessPage <- renderFitnessPage currentTime activities
TIO.writeFile "/home/matt/projects/LifeOfMatt/src/Elm/Fitness/Autogen/Fitness.elm" fitnessPage
TIO.writeFile "/home/matt/projects/LifeOfMatt/src/Elm/Fitness/Autogen/Running.elm" runningPage
-- TIO.putStr fitnessPage
|
<?php
namespace App\Eloquent\Repositories;
use App\Eloquent\Interfaces\AuthInterface;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
class AuthRepository implements AuthInterface
{
/**
* Authenticate a user
* @param array $credentials
* @param bool $remember Remember the user
* @return mixed
*/
public function login(array $credentials, $remember = false)
{
try {
if ((Auth::attempt(['email' => $credentials['email'], 'password' => $credentials['password']])) ||
(Auth::attempt(['phone_number' => $credentials['email'], 'password' => $credentials['password']]))) {
$user = Auth::User();
Session::put('user', $user);
$user = Session::get('user');
return $user;
}
} catch (\Exception $e) {
return 'Invalid login credentials';
}
}
/**
* Log the user out of the application.
* @return bool
*/
public function logout()
{
Auth::logout();
}
/**
* Activate the given used id
* @param int $userId
* @param string $code
* @return mixed
*/
public function activate($userId, $code)
{
// TODO: Implement activate() method.
}
/**
* Create a reminders code for the given user
* @param $user
* @return mixed
*/
public function createReminderCode($user)
{
// TODO: Implement createReminderCode() method.
}
/**
* Completes the reset password process
* @param $user
* @param string $code
* @param string $password
* @return bool
*/
public function completeResetPassword($user, $code, $password)
{
// TODO: Implement completeResetPassword() method.
}
/**
* Determines if the current user has access to given permission
* @param $permission
* @return bool
*/
public function hasAccess($permission)
{
// TODO: Implement hasAccess() method.
}
/**
* Check if the user is logged in
* @return mixed
*/
public function check()
{
// TODO: Implement check() method.
}
/**
* Get the ID for the currently authenticated user
* @return int
*/
public function id()
{
// TODO: Implement id() method.
}
}
|
using System;
namespace ActiproSoftware.ProductSamples.MicroChartsSamples.Common {
/// <summary>
/// Stores sales-related data, and is used by various samples for this product.
/// Any similar custom data objects could be used to generate chart data.
/// </summary>
public class SalesData {
private decimal amount;
private DateTime date;
/////////////////////////////////////////////////////////////////////////////////////////////////////
// OBJECT
/////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Initializes a new instance of the <c>SalesData</c> class.
/// </summary>
/// <param name="date">The date for which the amount is specified.</param>
/// <param name="amount">The sales amount.</param>
public SalesData(DateTime date, decimal amount) {
this.date = date;
this.amount = amount;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// PUBLIC PROCEDURES
/////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets the sales amount.
/// </summary>
/// <value>The sales amount.</value>
public decimal Amount {
get {
return amount;
}
}
/// <summary>
/// Gets the date for which the amount is specified.
/// </summary>
/// <value>The date for which the amount is specified.</value>
public DateTime Date {
get {
return date;
}
}
}
}
|
class AddUniqueIndicesBrainzCodeAndNameToMediumFormats < ActiveRecord::Migration[5.2]
def change
reversible do |indices|
indices.up do
execute <<-DDL.gsub /^\s+/, ''
CREATE UNIQUE INDEX medium_formats_brainz_code_index
ON medium_formats(brainz_code);
CREATE UNIQUE INDEX medium_formats_name_index
ON medium_formats(name);
DDL
end
indices.down do
execute <<-DDL.gsub /^\s+/, ''
DROP INDEX medium_formats_brainz_code_index;
DROP INDEX medium_formats_name_index;
DDL
end
end
end
end
|
# source: https://github.com/OvercastNetwork/OCN/blob/master/app/models/subscribable.rb
module Subscribable
extend ActiveSupport::Concern
included do
has_many :subscriptions, as: :subscribable, class_name: 'Subscription'
before_destroy do
subscriptions.destroy_all
end
end
def link
# No link
end
# Return the subclass of Subscription::Alert to send for subscriptions
# to this object
Alert = Subscription::Alert
def alert_class
self.class::Alert
end
# Can the given user view this object? This will be checked before each
# alert is sent to the subscriber.
def can_view?(_user)
true
end
def subscribe_user(user)
return unless can_view?(user)
unless (sub = subscriptions.user(user).one)
sub = Subscription.new(subscribable: self, user: user)
end
sub.unsubscribed = false
sub.save!
true
end
def unsubscribe_user(user)
subscriptions.user(user).cancel!
end
def unsubscribe_all
subscriptions.cancel!
end
def subscriber?(user)
subscriptions.active.user(user).exists?
end
def subscription_for(user)
subscriptions.user(user).one
end
# Send an alert to all subscribers, excluding any given in :except:
def alert_subscribers(except: nil, **opts)
subscriptions.active.each do |sub|
sub.alert_subscriber(except: except, **opts)
end
end
def mark_read!(by: nil)
q = subscriptions
q = q.in(user: by.to_a) if by
q.alerts.mark_read!
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.