text
stringlengths 184
4.48M
|
|---|
/**
* @file PCapNGOption.h
* @author Abhiroop Datta (abhiroopdatta7@gmail.com)
* @brief
* @version 0.1
* @date 2022-10-24
*
* @copyright Copyright (c) 2022
*
*/
#ifndef __PCAPNG_OPTION_H__
#define __PCAPNG_OPTION_H__
#include "PCapNGBuffer.h"
#include <cstddef>
#include <cstdint>
namespace PCapNG
{
size_t Pad32(size_t val);
class OptionBase
{
public:
OptionBase(uint16_t type)
{
_type = type;
}
virtual void serialize() = 0;
friend Buffer &operator<<(Buffer &optionBuffer, OptionBase &obj)
{
uint8_t pad = 0;
obj.serialize();
auto length = obj.OptionLength();
optionBuffer << obj._type;
optionBuffer << length;
optionBuffer << obj._value;
// PAD
uint8_t padWith = 0;
auto padLength = Pad32(length) - length;
for (auto i = 0; i < padLength; i++)
optionBuffer << padWith;
return optionBuffer;
}
uint16_t _type;
enum OPTION_TYPE
{
OPTION_END = 0,
OPTION_COMMENT = 1,
OPTION_CUSTOM_STR = 2988,
OPTION_CUSTOM = 2989,
OPTION_CUSTOM_STR_NO_COPY = 19372,
OPTION_CUSTOM_NO_COPY = 19373,
};
protected:
Buffer _value;
private:
Buffer _optionDetails;
inline uint16_t OptionLength()
{
uint16_t length = _value.size();
return length;
}
};
class EndOfOption : public OptionBase
{
public:
EndOfOption() : OptionBase(OPTION_END)
{
}
void serialize() override
{
}
};
/* Custom Options */
class CustomOption : public OptionBase
{
public:
CustomOption(const uint16_t type, const uint32_t pen, ::std::string data) : OptionBase(type)
{
_pen = pen;
data.append(data.c_str(), data.size());
}
CustomOption(const uint16_t type, const uint32_t pen, const char *buffer, const size_t size) : OptionBase(type)
{
_pen = pen;
data.append(buffer, size);
}
void serialize() override
{
_value << _pen;
_value << data;
}
private:
uint32_t _pen;
Buffer data;
};
class Option : public OptionBase
{
public:
Option(uint16_t tpye, const ::std::string dec) : OptionBase(tpye)
{
_optionDetails.append(dec.c_str(), dec.size());
}
Option(uint16_t tpye, const char *dec, size_t size) : OptionBase(tpye)
{
_optionDetails.append(dec, size);
}
void serialize() override
{
_value << _optionDetails;
}
private:
Buffer _optionDetails;
};
} // namespace PCapNG
#endif /* __PCAPNG_OPTION_H__ */
|
import { ProductStore, Product } from '../../models/product';
import { OrderStore, Order, Order_Product, Cart } from '../../models/order';
import { UserModel, User } from '../../models/user';
import { DashboardQueries } from '../../services/dashboard';
const orderStore = new OrderStore();
const productStore = new ProductStore();
const userModel = new UserModel();
const dashboard = new DashboardQueries();
describe('/services/dashboard unit test suite', () => {
describe('Check the definition of all methods', () => {
it('should be defined for productsInOrders method', () => {
expect(dashboard.productsInOrders).toBeDefined();
});
it('should be defined for usersWithOrders method', () => {
expect(dashboard.usersWithOrders).toBeDefined();
});
it('should be defined for fiveMostExpensiveProducts method', () => {
expect(dashboard.fiveMostExpensiveProducts).toBeDefined();
});
it('should be defined for fiveMostPopularProducts method', () => {
expect(dashboard.fiveMostPopularProducts).toBeDefined();
});
it('should be defined for indexProductsByCategory method', () => {
expect(dashboard.indexProductsByCategory).toBeDefined();
});
});
describe('Check returns of all methods associated with dashboard service', () => {
let user: User;
let order: Order;
let addedProductInCart: Order_Product;
let product_ids: number[] = [];
beforeAll(async () => {
for (let i = 1; i < 10; i++) {
const tempProduct: Product = (await productStore.create({
name: `product${i} name`,
price: i * 10,
category: `product${i} category`,
})) as Product;
product_ids.push(tempProduct.id as number);
}
});
afterAll(async () => {
// delete products
for (let i = 1; i < 10; i++) {
await productStore.delete(product_ids[i - 1] as number);
}
});
beforeEach(async () => {
user = {
first_name: 'Dashboarduser first name',
last_name: 'user last name',
email: 'useremail@gmail.com',
password: 'password123',
user_role: 0,
};
// create user
user = (await userModel.create(user)) as User;
order = {
status: 'Pending',
user_id: Number(user.id),
};
// create order for that user
order = await orderStore.create(order);
});
afterEach(async () => {
await orderStore.delete(Number(order.id), Number(order.user_id));
await userModel.delete(Number(user.id));
});
it('should return all products that have been included in orders', async () => {
// add product to that order
addedProductInCart = (await orderStore.addProductToCart(
Number(order.id),
Number(product_ids[1]),
1
)) as Order_Product;
const result = await dashboard.productsInOrders();
expect(result).toBeInstanceOf(Object);
expect(Object.keys(result).length).toBe(1);
await orderStore.removeProductFromCart(
Number(order.id),
Number(product_ids[1])
);
});
it('should return all users with orders', async () => {
// add product to that order
addedProductInCart = (await orderStore.addProductToCart(
Number(order.id),
Number(product_ids[1]),
1
)) as Order_Product;
const result = await dashboard.usersWithOrders();
expect(result).toBeInstanceOf(Object);
expect(Object.keys(result).length).toBe(1);
await orderStore.removeProductFromCart(
Number(order.id),
Number(product_ids[1])
);
});
it('should return the five most expensive products', async () => {
const result = await dashboard.fiveMostExpensiveProducts();
expect(result).toBeInstanceOf(Object);
expect(Object.keys(result).length).toBe(5);
});
it('should index products of specific category', async () => {
const result = (await dashboard.indexProductsByCategory(
'product1 category'
)) as Object;
expect(result).toBeInstanceOf(Object);
expect(Object.keys(result).length).toBe(1);
});
});
});
|
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
public class Post {
private int id;
private String texto;
private Autor autor;
private LocalDateTime data;
private int quantidadeDeLikes;
private String filePath; // Caminho do arquivo - responsabilidade extra
public Post(int id, String texto, Autor autor, String filePath) {
this.id = id;
this.texto = texto;
this.autor = autor;
this.data = LocalDateTime.now();
this.quantidadeDeLikes = 0;
this.filePath = filePath;
}
public int getId() {
return id;
}
public String getTexto() {
return texto;
}
public Autor getAutor() {
return autor;
}
public LocalDateTime getData() {
return data;
}
public int getQuantidadeDeLikes() {
return quantidadeDeLikes;
}
public void saveToFile() {
try (FileWriter writer = new FileWriter(filePath)) {
writer.write("ID: " + id + "\n");
writer.write("Texto: " + texto + "\n");
writer.write("Autor: " + autor.getNome() + "\n");
writer.write("Data: " + data + "\n");
writer.write("Quantidade de Likes: " + quantidadeDeLikes + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
<script lang="ts">
import Account from "./Account.svelte";
import MoreActions from "./MoreActions.svelte";
import AddAccount from "./AddAccount.svelte";
import Filter from "./Filter.svelte";
import type {
AddAccountType,
AccountsType,
AccountType,
} from "../utils/types";
import {
Card,
CardBody,
CardHeader,
CardSubtitle,
CardTitle,
} from "sveltestrap";
import { getBalance } from "tangle-connect";
import { onMount } from "svelte";
export const API_ENDPOINT =
"https://api.lb-0.h.chrysalis-devnet.iota.cafe:443";
export let accounts: AccountsType = [];
const POLLING_INTERVEL = 20000;
let showaddaccount: boolean = false;
let newAccId: number;
$: filterstr = "";
$: filteredtotal = accounts.length;
$: totalaccounts = accounts.length;
$: filteredtotalamount = 0;
$: {
if (totalaccounts === 0) {
newAccId = 1;
} else {
newAccId = Math.max(...accounts.map((t) => t.id)) + 1;
}
}
//Poll each account for updated balance
function pollandUpdate(): void {
accounts.forEach((acc) => {
getBalance(acc.key)
.then((bal) => {
if (bal) {
if (acc.amount !== bal) {
acc.amount = bal;
}
}
})
.catch(() => {
console.log("Non valid address");
});
});
accounts = accounts;
}
onMount(async () => {
setInterval(pollandUpdate, POLLING_INTERVEL);
});
//Remove account from the accounts list
function removeAccount(account: AccountType): void {
accounts = accounts.filter((t) => t.id !== account.id);
}
//Once the user adds a new account, verify the account key is valid
function validateKey(newkey: string): boolean {
if (newkey.length) {
let rexp = new RegExp("[a-z0-9]");
if (rexp.test(newkey)) {
let obj = accounts.find((o) => o.key === newkey);
if (!obj) {
return true;
}
}
}
return false;
}
//Fetch balance from the network and then add the account to the list
async function addAcc(newkey: CustomEvent<AddAccountType>) {
if (newkey && newkey.detail && newkey.detail) {
let detail: AddAccountType = newkey.detail;
if (detail.ok) {
let key = detail.key.trim();
if (validateKey(key)) {
getBalance(key)
.then((bal) => {
let newacc: AccountType = {
id: newAccId,
key: key,
amount: bal ? bal : 0,
};
accounts = [...accounts, newacc];
})
.catch(() => {
let newacc: AccountType = { id: newAccId, key: key, amount: 0 };
accounts = [...accounts, newacc];
});
}
}
}
filterstr = filterstr;
accounts = accounts;
showaddaccount = false;
}
//Use filter text to lookup keys and balances and return only matching
const filterAccounts = (filterstr: string) => {
if (filterstr !== "") {
let accs = accounts.filter(
(ele) =>
(ele.amount === parseInt(filterstr) ? true : false) ||
ele.key.includes(filterstr)
);
filteredtotalamount = 0;
accs.forEach((acc) => {
filteredtotalamount += acc.amount;
});
filteredtotal = accs.length;
return accs;
} else {
filteredtotalamount = 0;
accounts.forEach((acc) => {
filteredtotalamount += acc.amount;
});
filteredtotal = accounts.length;
return accounts;
}
};
//Capture filter text
const filterCriteria = (event: CustomEvent<string>) => {
if (event && event.detail) {
filterstr = event.detail;
console.log(filterstr);
accounts = accounts;
}
};
//Show add account card
function showAddAccount() {
showaddaccount = true;
}
</script>
<div class="todoapp stack-large">
<Card class="mb-3 shadow p-3 mb-5 bg-white rounded">
<CardHeader>
<CardTitle>Your Accounts Balances</CardTitle>
</CardHeader>
<CardBody>
<CardSubtitle
>Total balance in these {filteredtotal} accounts is {filteredtotalamount}</CardSubtitle
>
</CardBody>
</Card>
<div class="overflow-auto mb-3 mb-md-0 mr-md-3 border p-3">
<Filter on:filteracc={filterCriteria} />
<div
class="overflow-auto mb-3 mb-md-0 mr-md-3 border p-3"
style="max-height: 280px;"
>
<ul class="todo-list stack-large" aria-labelledby="list-heading">
{#each filterAccounts(filterstr) as account (account.id)}
{accounts && accounts.length ? " " : "_"}
<li class="todo">
<div class="row justify-content-md-center">
<div class="col">
<Account {account} on:remove={(e) => removeAccount(e.detail)} />
</div>
</div>
</li>
{:else}
<li>Nothing to do here!</li>
{/each}
</ul>
</div>
<div class="row justify-content-md-center">
{#if showaddaccount}
<AddAccount on:updateacclist={addAcc} />
{:else}
<MoreActions {accounts} on:showdlg={showAddAccount} />
{/if}
</div>
</div>
</div>
|
import Head from 'next/head';
import { useWeb3Context } from '@/context/Web3Context';
import useREther from '@/contracts/useREther';
import { useEffect, useState } from 'react';
export default function Home() {
const [balance, setBalance] = useState<string>();
const { account, connect, utils } = useWeb3Context();
const contract = useREther();
useEffect(() => {
const fetchBalance = async () => {
if (account) {
const value = await contract?.methods.balanceOf(account).call();
setBalance(utils.fromWei(value, 'ether'));
}
};
fetchBalance();
}, [account, contract, utils]);
return (
<>
<Head>
<title>rEther</title>
<meta name='description' content='rEther ATM' />
<meta
name='viewport'
content='width=device-width, initial-scale=1'
/>
<link rel='icon' href='/favicon.ico' />
</Head>
<main>
<h1>Account: {account || 'Not connected'}</h1>
<h3>{!!balance && `Balance: ${balance}`}</h3>
<button onClick={connect}>Connect wallet</button>
</main>
</>
);
}
|
import React, { useEffect } from 'react'
import { Form, Input, Button, Select } from 'antd';
import '../../styles/formularios.css'
const { Option } = Select;
export const PermisosForm = ({
onFinish,
loading,
acciones,
dataEdit
}) => {
const [form] = Form.useForm();
useEffect(()=> {
if(dataEdit) {
const acciones = dataEdit.acciones.map(accion => accion._id);
console.log(acciones);
form.setFieldsValue({
name:dataEdit.name,
path:dataEdit.path,
acciones
})
}
}, [])
return (
<div className='contenedor-formulario'>
<Form
onFinish={onFinish}
form={form}
>
<label >Nombre</label>
<Form.Item
className='campo-permiso'
name="name"
rules={[
{required:true, message:'El nombre es requerido'},
{min:5, message:'Debe tener al menos 5 caracteres'}
]}
>
<Input placeholder='Nombre de la ruta' minLength={5} maxLength={25}/>
</Form.Item>
<label >Ruta</label>
<Form.Item
className='campo-permiso'
name="path"
rules={[
{required:true, message:'La ruta es requerida'},
{min:5, message:'Debe tener al menos 5 caracteres'}
]}
>
<Input disabled={dataEdit} placeholder='Ruta ejem: /permisos' minLength={5} maxLength={25}/>
</Form.Item>
<Form.Item
className='campo-permiso'
name="acciones"
>
<Select
mode="multiple"
allowClear
style={{ width: '100%' }}
placeholder="Please select"
>
{
acciones.length > 0 && (
acciones.map(el => (
<Option key={el._id}>{el.name}</Option>
))
)
}
</Select>
</Form.Item>
<Form.Item>
<Button
className='button'
type='primary'
htmlType='submit'
loading={loading}
>
Guardar cambios
</Button>
</Form.Item>
</Form>
</div>
)
}
|
/* Webcamoid, webcam capture application.
* Copyright (C) 2016 Gonzalo Exequiel Pedone
*
* Webcamoid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Webcamoid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Webcamoid. If not, see <http://www.gnu.org/licenses/>.
*
* Web-Site: http://webcamoid.github.io/
*/
import QtQuick 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.3
import Ak 1.0
ColumnLayout {
id: configs
property int cellSize: 50
function updateKernel(index, value)
{
var kernel = Convolve.kernel
kernel[index] = value
Convolve.kernel = kernel
}
Connections {
target: Convolve
function onBiasChanged(bias)
{
sldBias.value = bias
spbBias.value = bias
}
}
Label {
//: https://en.wikipedia.org/wiki/Kernel_(image_processing)
text: qsTr("Convolve matrix")
}
GridLayout {
columns: 3
// Row 0
TextField {
id: k00
text: Convolve.kernel[0]
selectByMouse: true
validator: RegExpValidator {
regExp: /-?\d+/
}
Layout.preferredWidth: cellSize
Accessible.name: qsTr("Column 0, Row 0")
onTextChanged: updateKernel(0, text)
}
TextField {
id: k01
text: Convolve.kernel[1]
selectByMouse: true
validator: RegExpValidator {
regExp: /-?\d+/
}
Layout.preferredWidth: cellSize
Accessible.name: qsTr("Column 1, Row 0")
onTextChanged: updateKernel(1, text)
}
TextField {
id: k02
text: Convolve.kernel[2]
selectByMouse: true
validator: RegExpValidator {
regExp: /-?\d+/
}
Layout.preferredWidth: cellSize
Accessible.name: qsTr("Column 2, Row 0")
onTextChanged: updateKernel(2, text)
}
// Row 1
TextField {
id: k10
text: Convolve.kernel[3]
selectByMouse: true
validator: RegExpValidator {
regExp: /-?\d+/
}
Layout.preferredWidth: cellSize
Accessible.name: qsTr("Column 0, Row 1")
onTextChanged: updateKernel(3, text)
}
TextField {
id: k11
text: Convolve.kernel[4]
selectByMouse: true
validator: RegExpValidator {
regExp: /-?\d+/
}
Layout.preferredWidth: cellSize
Accessible.name: qsTr("Column 1, Row 1")
onTextChanged: updateKernel(4, text)
}
TextField {
id: k12
text: Convolve.kernel[5]
selectByMouse: true
validator: RegExpValidator {
regExp: /-?\d+/
}
Layout.preferredWidth: cellSize
Accessible.name: qsTr("Column 2, Row 1")
onTextChanged: updateKernel(5, text)
}
// Row 2
TextField {
id: k20
text: Convolve.kernel[6]
selectByMouse: true
validator: RegExpValidator {
regExp: /-?\d+/
}
Layout.preferredWidth: cellSize
Accessible.name: qsTr("Column 0, Row 2")
onTextChanged: updateKernel(6, text)
}
TextField {
id: k21
text: Convolve.kernel[7]
selectByMouse: true
validator: RegExpValidator {
regExp: /-?\d+/
}
Layout.preferredWidth: cellSize
Accessible.name: qsTr("Column 1, Row 2")
onTextChanged: updateKernel(7, text)
}
TextField {
id: k22
text: Convolve.kernel[8]
selectByMouse: true
validator: RegExpValidator {
regExp: /-?\d+/
}
Layout.preferredWidth: cellSize
Accessible.name: qsTr("Column 2, Row 2")
onTextChanged: updateKernel(8, text)
}
}
GridLayout {
columns: 3
Label {
id: txtFactor
text: qsTr("Factor")
}
TextField {
text: AkFrac.create(Convolve.factor).string
placeholderText: qsTr("Factor")
validator: RegExpValidator {
regExp: /-?\d+\/\d+/
}
Layout.columnSpan: 2
Layout.fillWidth: true
Accessible.name: txtFactor.text
onTextChanged: Convolve.factor = AkFrac.create(text).toVariant()
}
Label {
id: txtBias
text: qsTr("Bias")
}
Slider {
id: sldBias
value: Convolve.bias
stepSize: 1
from: -255
to: 255
Layout.fillWidth: true
Accessible.name: txtBias.text
onValueChanged: Convolve.bias = value
}
SpinBox {
id: spbBias
value: Convolve.bias
stepSize: sldBias.stepSize
from: sldBias.from
to: sldBias.to
editable: true
Accessible.name: txtBias.text
onValueChanged: Convolve.bias = Number(value)
}
}
}
|
/*************************************************************************
* Copyright 2009-2014 Eucalyptus Systems, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
* Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
* CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
* additional information or have any questions.
************************************************************************/
package com.eucalyptus.cloudformation.workflow
import com.amazonaws.services.simpleworkflow.flow.core.AndPromise
import com.amazonaws.services.simpleworkflow.flow.core.Promise
import com.amazonaws.services.simpleworkflow.flow.core.Settable
import com.eucalyptus.cloudformation.entity.StackEntity
import com.eucalyptus.cloudformation.entity.StackEntityHelper
import com.eucalyptus.cloudformation.entity.StackResourceEntity
import com.eucalyptus.cloudformation.resources.ResourceAction
import com.eucalyptus.cloudformation.resources.ResourceResolverManager
import com.eucalyptus.cloudformation.template.dependencies.DependencyManager
import com.google.common.base.Throwables
import com.google.common.collect.Lists
import com.google.common.collect.Maps
import com.netflix.glisten.WorkflowOperations
import com.netflix.glisten.impl.swf.SwfWorkflowOperations
import groovy.transform.CompileStatic
import groovy.transform.TypeCheckingMode
import org.apache.log4j.Logger
/**
* Created by ethomas on 10/6/14.
*/
@CompileStatic(TypeCheckingMode.SKIP)
public class CommonDeleteRollbackPromises {
private static final Logger LOG = Logger.getLogger(CommonDeleteRollbackPromises.class);
@Delegate
WorkflowOperations<StackActivity> workflowOperations;
String stackOperationInProgressStatus;
String stackOperationInProgressStatusReason;
String stackOperationFailedStatus;
String stackOperationCompleteStatus;
boolean deleteStackRecordsWhenSuccessful;
CommonDeleteRollbackPromises(WorkflowOperations<StackActivity> workflowOperations, String stackOperationInProgressStatus,
String stackOperationInProgressStatusReason, String stackOperationFailedStatus, String stackOperationCompleteStatus,
boolean deleteStackRecordsWhenSuccessful) {
this.workflowOperations = workflowOperations
this.stackOperationInProgressStatus = stackOperationInProgressStatus
this.stackOperationInProgressStatusReason = stackOperationInProgressStatusReason
this.stackOperationFailedStatus = stackOperationFailedStatus
this.stackOperationCompleteStatus = stackOperationCompleteStatus
this.deleteStackRecordsWhenSuccessful = deleteStackRecordsWhenSuccessful
}
public Promise<?> getPromise(String stackId, String accountId, String resourceDependencyManagerJson, String effectiveUserId) {
Promise<String> deleteInitialStackPromise = promiseFor(
activities.createGlobalStackEvent(
stackId,
accountId,
stackOperationInProgressStatus,
stackOperationInProgressStatusReason
)
);
waitFor(deleteInitialStackPromise) {
DependencyManager resourceDependencyManager = StackEntityHelper.jsonToResourceDependencyManager(
resourceDependencyManagerJson
);
Map<String, Settable<String>> deletedResourcePromiseMap = Maps.newConcurrentMap();
for (String resourceId : resourceDependencyManager.getNodes()) {
deletedResourcePromiseMap.put(resourceId, new Settable<String>()); // placeholder promise
}
doTry {
// This is in case any part of deleting the stack fails
// Now for each resource, set up the promises and the dependencies they have for each other (remember the order is reversed)
for (String resourceId : resourceDependencyManager.getNodes()) {
String resourceIdLocalCopy = new String(resourceId);
// passing "resourceId" into a waitFor() uses the for reference pointer after the for loop has expired
Collection<Promise<String>> promisesDependedOn = Lists.newArrayList();
// We have the opposite direction in delete than create,
for (String dependingResourceId : resourceDependencyManager.getDependentNodes(resourceIdLocalCopy)) {
promisesDependedOn.add(deletedResourcePromiseMap.get(dependingResourceId));
}
AndPromise dependentAndPromise = new AndPromise(promisesDependedOn);
waitFor(dependentAndPromise) {
Promise<String> currentResourcePromise = getDeletePromise(resourceIdLocalCopy, stackId, accountId, effectiveUserId);
deletedResourcePromiseMap.get(resourceIdLocalCopy).chain(currentResourcePromise);
return currentResourcePromise;
}
}
AndPromise allResourcePromises = new AndPromise(deletedResourcePromiseMap.values());
waitFor(allResourcePromises) {
// check if any failures...
boolean resourceFailure = false;
for (Promise promise : allResourcePromises.getValues()) {
if (promise.isReady() && "FAILURE".equals(promise.get())) {
resourceFailure = true;
break;
}
}
if (resourceFailure) {
return waitFor(promiseFor(activities.determineDeleteResourceFailures(stackId, accountId))) { String errorMessage ->
promiseFor(activities.createGlobalStackEvent(
stackId,
accountId,
stackOperationFailedStatus,
errorMessage)
);
}
} else {
return waitFor(
promiseFor(activities.createGlobalStackEvent(stackId, accountId,
stackOperationCompleteStatus,
""))
) {
if (deleteStackRecordsWhenSuccessful) {
promiseFor(activities.deleteAllStackRecords(stackId, accountId));
} else {
promiseFor("");
}
}
}
}
}.withCatch { Throwable t ->
CreateStackWorkflowImpl.LOG.error(t);
CreateStackWorkflowImpl.LOG.debug(t, t);
Throwable cause = Throwables.getRootCause(t);
Promise<String> errorMessagePromise = Promise.asPromise((cause != null) && (cause.getMessage() != null) ? cause.getMessage() : "");
if (cause != null && cause instanceof ResourceFailureException) {
errorMessagePromise = promiseFor(activities.determineDeleteResourceFailures(stackId, accountId));
}
waitFor(errorMessagePromise) { String errorMessage ->
promiseFor(activities.createGlobalStackEvent(
stackId,
accountId,
stackOperationFailedStatus,
errorMessage)
);
}
}.getResult()
}
}
Promise<String> getDeletePromise(String resourceId,
String stackId,
String accountId,
String effectiveUserId) {
Promise<String> getResourceTypePromise = promiseFor(activities.getResourceType(stackId, accountId, resourceId));
waitFor(getResourceTypePromise) { String resourceType ->
ResourceAction resourceAction = new ResourceResolverManager().resolveResourceAction(resourceType);
Promise<String> initPromise = promiseFor(activities.initDeleteResource(resourceId, stackId, accountId, effectiveUserId));
waitFor(initPromise) { String result ->
if ("SKIP".equals(result)) {
return promiseFor("SUCCESS");
} else {
return doTry {
waitFor(promiseFor(resourceAction.getDeletePromise(workflowOperations, resourceId, stackId, accountId, effectiveUserId))) {
return promiseFor(activities.finalizeDeleteResource(resourceId, stackId, accountId, effectiveUserId));
}
}.withCatch { Throwable t->
Throwable rootCause = Throwables.getRootCause(t);
return promiseFor(activities.failDeleteResource(resourceId, stackId, accountId, effectiveUserId, rootCause.getMessage()));
}.getResult();
}
}
}
}
}
|
#include "variadic_functions.h"
/**
* sum_them_all - Sums up all the variadic integers
*@n: Number of arguments
*
*Return: Sum of the arguments or Zero
*/
int sum_them_all(const unsigned int n, ...)
{
unsigned int i, sum = 0;
va_list sumint;
va_start(sumint, n);
if (n == 0)
return (0);
for (i = 1; i <= n; i++)
sum += va_arg(sumint, unsigned int);
va_end(sumint);
return (sum);
}
|
import { signOut } from "next-auth/react"
import { z } from "zod"
import { ShowAlertType } from "@/types/api"
import { toast } from "@/components/ui/use-toast"
import i18n from "./i18n"
import { ErrorResponseParams, GenericErrorResponse } from "./response"
export const handleApiError = (error: any, showAlertType?: ShowAlertType) => {
if (error.response.status === 403) {
toast({
title: i18n.t("Something went wrong"),
description: i18n.t("The session has expired"),
variant: "destructive",
})
signOut({
callbackUrl: `${window.location.origin}/login`,
})
return
}
const errorResponse: ErrorResponseParams = error.response
.data as ErrorResponseParams
if (errorResponse.alertType && showAlertType) {
showAlertType(errorResponse.alertType)
} else if (errorResponse.description) {
toast({
title: errorResponse.error,
description: errorResponse.description,
variant: "destructive",
})
} else {
toast({
title: i18n.t("Something went wrong"),
description: errorResponse.error,
variant: "destructive",
})
}
}
export class Unauthorized extends Error {
constructor(message = "Unauthorized") {
super(message)
}
}
export const handleCatchApi = (error: Error) => {
if (error instanceof z.ZodError) {
return new Response(JSON.stringify(error.issues), { status: 422 })
}
if (error instanceof Unauthorized) {
return new Response("Unauthorized", { status: 403 })
}
return GenericErrorResponse(error)
}
|
package com.acerta.rest.config.middlewares;
import java.time.LocalDateTime;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.acerta.rest.config.middlewares.template.ExceptionModelTemplate;
@ControllerAdvice
public class ExceptionHandlerMiddlewareConfig extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
System.out.println("HttpMessageNotReadableException");
return handleExceptionInternal(ex, "HttpMessageNotReadableException", new HttpHeaders(), status, request);
}
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
System.out.println("NoHandlerFoundException");
String mensagem = "A rota '" + ex.getRequestURL() + "' não existe";
return new ResponseEntity<>(mensagem, HttpStatus.NOT_FOUND);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
System.out.println("MethodArgumentNotValidException");
BindingResult bindingResult = ex.getBindingResult();
String message = null;
if (bindingResult.getAllErrors().size() > 0) {
message = bindingResult.getAllErrors().get(0).getDefaultMessage();
}
HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
ExceptionModelTemplate problem = createTemplateException(httpStatus, "BADREQUEST", null, message);
return handleExceptionInternal(ex, problem, headers, HttpStatus.BAD_REQUEST, request);
}
private ExceptionModelTemplate createTemplateException(HttpStatus status, String title, String message,
String details) {
ExceptionModelTemplate exceptionTemplate = new ExceptionModelTemplate();
exceptionTemplate.setTimestamp(LocalDateTime.now());
exceptionTemplate.setStatus(status.value());
exceptionTemplate.setTitle(title);
exceptionTemplate.setDetail(details);
exceptionTemplate.setUserMessage(message);
return exceptionTemplate;
}
}
|
//
// AppDelegate.swift
// Swwwitch
//
// Created by chen he on 2019/3/29.
// Copyright © 2019 chen he. All rights reserved.
//
import Cocoa
extension Notification.Name {
static let killLauncher = Notification.Name("killLauncher")
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.squareLength)
let popover = NSPopover()
var eventMonitor: EventMonitor?
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
if let button = statusItem.button {
button.image = NSImage(named:NSImage.Name("Switch"))
button.action = #selector(togglePopover(_:))
}
popover.contentViewController = SwitchViewController.instantiateController()
eventMonitor = EventMonitor(mask: [.leftMouseDown, .rightMouseDown]) { [weak self] event in
guard let self = self else { return }
if self.popover.isShown {
self.closePopover(sender: event)
}
}
let launcherAppId = "app.chen.osx.SwwwitchLauncher"
let runningApps = NSWorkspace.shared.runningApplications
let isRunning = !runningApps.filter { $0.bundleIdentifier == launcherAppId }.isEmpty
if isRunning {
DistributedNotificationCenter.default().post(name: .killLauncher,
object: Bundle.main.bundleIdentifier!)
}
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
@objc func togglePopover(_ sender: Any?) {
if popover.isShown {
closePopover(sender: sender)
} else {
showPopover(sender: sender)
}
}
func showPopover(sender: Any?) {
if let button = statusItem.button {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
eventMonitor?.start()
}
}
func closePopover(sender: Any?) {
popover.performClose(sender)
eventMonitor?.stop()
}
}
|
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:resturnat_app/services/data.dart';
import 'package:resturnat_app/utils/list_tiles.dart';
class FoodMenu extends StatefulWidget {
const FoodMenu({super.key});
@override
State<FoodMenu> createState() => _FoodMenuState();
}
class _FoodMenuState extends State<FoodMenu> {
List<Map<String, dynamic>> foodCategories = Menu().food;
@override
Widget build(BuildContext context) {
List<Tab> myTabs = [];
List<Widget> myTabsView = [];
for (var category in foodCategories) {
myTabs.add(Tab(
text: category['category'],
));
myTabsView.add(_buildTabView(category));
}
return DefaultTabController(
length: myTabs.length,
child: Scaffold(
backgroundColor: Colors.blueGrey[100],
appBar: AppBar(
actions: [
Image.asset('lib/images/dish.png'),
],
elevation: 0,
backgroundColor: Colors.transparent,
centerTitle: true,
iconTheme: IconThemeData(color: Colors.black87),
title: Text(
'Food Menu',
style: TextStyle(
color: Colors.black87,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
bottom: TabBar(
tabs: myTabs,
isScrollable: true,
labelColor: Colors.black87,
),
),
body: SafeArea(
child: TabBarView(
children: myTabsView,
),
),
),
);
}
Widget _buildTabView(Map<String, dynamic> category) {
List<Map<String, dynamic>> items = category['items'];
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return MenuListTiles(
name: items[index]['name'],
price: items[index]['price'].toString(),
images: items[index]['image'],
);
},
);
}
}
|
import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/app/core/api.service';
import { Project, Task } from '../../app.component';
@Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.scss']
})
export class HomePageComponent implements OnInit {
title = 'angular-app-taskio';
today = new Date();
sectionTitle1 = 'Today\'s Tasks';
sectionTitle2 = 'My Projects';
constructor(private api: ApiService) {}
ngOnInit(): void {
this.api.getUserPosts();
}
tasks: Array<Task> = [
{
title: 'Your first task',
complete: false,
description: 'Eng Task'
},
{
title: 'Your second task',
complete: false
},
{
title: 'Another task',
complete: false
},
{
title: 'task 4#',
complete: true
}
];
projects: Array<Project> = [
{
title: 'my first project',
description: 'such an awesome project, I am sure it would be a huge success.',
image: 'https://cdn.pixabay.com/photo/2023/02/20/07/26/problem-7801590__340.jpg',
status: 'PLANNED'
},
{
title: 'Art project',
description: 'because I love creating art',
image: 'https://cdn.pixabay.com/photo/2016/06/25/12/55/art-1478831__340.jpg',
status: 'IN PROGRESS'
}
];
listStatusCss(): string {
return this.tasks.length <= 3 ? 'text-success' : 'text-dark';
}
getImagePath() {
return "https://cdn.pixabay.com/photo/2023/01/31/05/59/zebra-7757193_640.jpg";
}
getTaskById(id: number) {
return this.tasks[id];
}
completedCss(task: Task): string {
return task.complete ? 'text-decoration-line-through' : ''
}
}
|
/********************************************************************************************************
* @file CmdTestActivity.java
*
* @brief for TLSR chips
*
* @author telink
* @date Sep. 30, 2017
*
* @par Copyright (c) 2017, Telink Semiconductor (Shanghai) Co., Ltd. ("TELINK")
*
* 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.telink.ble.mesh.ui;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import com.telink.ble.mesh.TelinkMeshApplication;
import com.telink.ble.mesh.core.MeshUtils;
import com.telink.ble.mesh.core.message.MeshMessage;
import com.telink.ble.mesh.core.message.NotificationMessage;
import com.telink.ble.mesh.core.message.aggregator.AggregatorItem;
import com.telink.ble.mesh.core.message.aggregator.OpcodeAggregatorSequenceMessage;
import com.telink.ble.mesh.core.message.aggregator.OpcodeAggregatorStatusMessage;
import com.telink.ble.mesh.core.message.config.DefaultTTLGetMessage;
import com.telink.ble.mesh.core.message.config.FriendGetMessage;
import com.telink.ble.mesh.core.message.config.RelayGetMessage;
import com.telink.ble.mesh.core.message.generic.OnOffSetMessage;
import com.telink.ble.mesh.core.message.generic.OnOffStatusMessage;
import com.telink.ble.mesh.core.message.lighting.LightnessDefaultGetMessage;
import com.telink.ble.mesh.core.message.lighting.LightnessRangeGetMessage;
import com.telink.ble.mesh.core.networking.AccessType;
import com.telink.ble.mesh.demo.R;
import com.telink.ble.mesh.foundation.Event;
import com.telink.ble.mesh.foundation.EventListener;
import com.telink.ble.mesh.foundation.MeshService;
import com.telink.ble.mesh.foundation.event.StatusNotificationEvent;
import com.telink.ble.mesh.ui.widget.HexFormatTextWatcher;
import com.telink.ble.mesh.util.Arrays;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* add cycle test
*/
public class CmdTestActivity extends BaseActivity implements View.OnClickListener, EventListener<String> {
/**
* message type, use application key for common message, use device key for config message
*/
private final String[] ACCESS_TYPES = {"Application(App Key)", "Device(Device Key)"};
/**
* preset messages
*/
private final String[] PRESET_ACCESS_MESSAGES = {
"Vendor On",
"Vendor Off",
"Vendor On/Off Get",
"Vendor On NO-ACK",
"Vendor Off NO-ACK",
"Generic On",
"Generic Off",
"Opcode Aggregator(Lightness Default Get, + Lightness Range Get)",
"Opcode Aggregator(TTL Get + Friend Get + Relay Get)",
"[Custom]" // custom message
};
private final int MSG_DST_ADR = 0xFFFF;
private int appKeyIndex;
private View ll_name;
private EditText et_ac_type, et_actions, et_dst_adr, et_opcode,
et_rsp_opcode, et_rsp_max, et_retry_cnt, et_params, et_ttl, et_tid, et_name;
private TextView tv_params_preview;
private ImageView iv_toggle;
private AlertDialog mShowPresetDialog, accessDialog;
private static final int MSG_APPEND_LOG = 0x202;
private static final int MSG_REFRESH_SCROLL = 0x201;
private SimpleDateFormat dateFormat;
private TextView tv_log;
private ScrollView sv_log;
private View ll_content;
private AccessType selectedType = AccessType.APPLICATION;
private Handler handler = new Handler();
private EditText et_interval, et_count;
private Button btn_start_test;
private int interval;
private int count;
private int testIndex;
private boolean isTesting;
private Handler logHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == MSG_APPEND_LOG) {
tv_log.append("\n" + dateFormat.format(new Date()) + ": " + msg.obj + "\n");
logHandler.obtainMessage(MSG_REFRESH_SCROLL).sendToTarget();
} else if (msg.what == MSG_REFRESH_SCROLL) {
sv_log.fullScroll(View.FOCUS_DOWN);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!validateNormalStart(savedInstanceState)) {
return;
}
setContentView(R.layout.activity_cmd_test);
initTitle();
tv_params_preview = findViewById(R.id.tv_params_preview);
et_dst_adr = findViewById(R.id.et_dst_adr);
et_opcode = findViewById(R.id.et_opcode);
et_rsp_opcode = findViewById(R.id.et_rsp_opcode);
et_rsp_max = findViewById(R.id.et_rsp_max);
et_retry_cnt = findViewById(R.id.et_retry_cnt);
et_ttl = findViewById(R.id.et_ttl);
et_tid = findViewById(R.id.et_tid);
et_name = findViewById(R.id.et_name);
ll_name = findViewById(R.id.ll_name);
et_params = findViewById(R.id.et_params);
et_params.addTextChangedListener(new HexFormatTextWatcher(tv_params_preview));
et_ac_type = findViewById(R.id.et_ac_type);
et_ac_type.setOnClickListener(this);
et_actions = findViewById(R.id.et_actions);
et_actions.setOnClickListener(this);
tv_log = findViewById(R.id.tv_log);
sv_log = findViewById(R.id.sv_log);
iv_toggle = findViewById(R.id.iv_toggle);
iv_toggle.setOnClickListener(this);
ll_content = findViewById(R.id.ll_content);
dateFormat = new SimpleDateFormat("HH:mm:ss.SSS", Locale.CHINA);
appKeyIndex = TelinkMeshApplication.getInstance().getMeshInfo().getDefaultAppKeyIndex();
onActionSelect(0);
onAccessTypeSelect(0);
TelinkMeshApplication.getInstance().addEventListener(OnOffStatusMessage.class.getName(), this);
TelinkMeshApplication.getInstance().addEventListener(StatusNotificationEvent.EVENT_TYPE_NOTIFICATION_MESSAGE_UNKNOWN, this);
TelinkMeshApplication.getInstance().addEventListener(OpcodeAggregatorStatusMessage.class.getName(), this);
et_interval = findViewById(R.id.et_interval);
et_count = findViewById(R.id.et_count);
btn_start_test = findViewById(R.id.btn_start_test);
btn_start_test.setOnClickListener(v -> {
if (isTesting) {
onTestComplete("manual stop");
handler.removeCallbacksAndMessages(null);
} else {
startTest();
}
});
}
MeshMessage sendingMessage;
private void startTest() {
try {
MeshMessage meshMessage = assembleMessage();
if (meshMessage != null) {
this.sendingMessage = meshMessage;
interval = Integer.parseInt(et_interval.getText().toString());
count = Integer.parseInt(et_count.getText().toString());
if (interval < 1) {
toastMsg("interval input err");
return;
}
if (count < 1) {
toastMsg("count input err");
return;
}
testIndex = 0;
isTesting = true;
updateButtonState();
next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void next() {
if (this.sendingMessage == null) {
onTestComplete("message err");
return;
}
logHandler.obtainMessage(MSG_APPEND_LOG, "test ->" + testIndex).sendToTarget();;
MeshService.getInstance().sendMeshMessage(this.sendingMessage);
testIndex++;
if (testIndex >= count) {
onTestComplete("test complete");
} else {
handler.postDelayed(SENDING_TASK, interval);
}
}
private Runnable SENDING_TASK = new Runnable() {
@Override
public void run() {
next();
}
};
private void onTestComplete(String info) {
logHandler.obtainMessage(MSG_APPEND_LOG, info).sendToTarget();
isTesting = false;
updateButtonState();
}
private void updateButtonState() {
runOnUiThread(() -> btn_start_test.setText(isTesting ? "stop test" : "start test"));
}
private void initTitle() {
enableBackNav(true);
setTitle("CMD");
Toolbar toolbar = findViewById(R.id.title_bar);
toolbar.inflateMenu(R.menu.message_assemble);
toolbar.setOnMenuItemClickListener(item -> {
if (item.getItemId() == R.id.item_send) {
try {
MeshMessage meshMessage = assembleMessage();
if (meshMessage != null) {
boolean msgSent = MeshService.getInstance().sendMeshMessage(meshMessage);
String info = String.format("send message: opcode -- %04X params -- %s", meshMessage.getOpcode(), Arrays.bytesToHexString(meshMessage.getParams()));
if (!msgSent) {
info += " -> failed";
}
logHandler.obtainMessage(MSG_APPEND_LOG, info).sendToTarget();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
});
}
@Override
protected void onDestroy() {
super.onDestroy();
TelinkMeshApplication.getInstance().removeEventListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.et_ac_type:
showAccessDialog();
break;
case R.id.et_actions:
showActionDialog();
break;
case R.id.iv_toggle:
layoutToggle();
break;
}
}
private void layoutToggle() {
if (ll_content.getVisibility() == View.VISIBLE) {
ll_content.setVisibility(View.GONE);
iv_toggle.setImageResource(R.drawable.ic_arrow_down);
} else {
ll_content.setVisibility(View.VISIBLE);
iv_toggle.setImageResource(R.drawable.ic_arrow_up);
}
}
private MeshMessage assembleMessage() throws Exception {
String dstInput = et_dst_adr.getText().toString().trim();
if (TextUtils.isEmpty(dstInput)) {
toastMsg("input dst adr!");
return null;
}
final int dstAdr = Integer.valueOf(dstInput, 16);
if (dstAdr > 0xFFFF) {
toastMsg("invalid dst adr!");
return null;
}
String opcodeInput = et_opcode.getText().toString().trim();
if (TextUtils.isEmpty(opcodeInput)) {
toastMsg("input opcode!");
return null;
}
final int opcode = Integer.valueOf(opcodeInput, 16);
final byte[] params = Arrays.hexToBytes(et_params.getText().toString().trim());
String rspOpcodeInput = et_rsp_opcode.getText().toString().trim();
final int rspOpcode;
final int rspMax;
final int retryCnt;
if (TextUtils.isEmpty(rspOpcodeInput)) {
rspOpcode = MeshMessage.OPCODE_INVALID;
rspMax = 0;
retryCnt = 0;
} else {
rspOpcode = Integer.valueOf(rspOpcodeInput, 16);
String rspMaxInput = et_rsp_max.getText().toString().trim();
if (TextUtils.isEmpty(rspMaxInput)) {
rspMax = 0;
} else {
rspMax = Integer.valueOf(rspMaxInput, 10);
}
String retryCntInput = et_retry_cnt.getText().toString().trim();
if (TextUtils.isEmpty(retryCntInput)) {
retryCnt = 0;
} else {
retryCnt = Integer.valueOf(retryCntInput, 10);
}
}
String ttlInput = et_ttl.getText().toString().trim();
if (TextUtils.isEmpty(ttlInput)) {
toastMsg("input ttl!");
return null;
}
final int ttl = Integer.valueOf(ttlInput, 10);
String tidInput = et_tid.getText().toString().trim();
int tidPosition;
if (TextUtils.isEmpty(tidInput)) {
tidPosition = -1;
} else {
tidPosition = Integer.parseInt(tidInput);
}
MeshMessage meshMessage = new MeshMessage();
meshMessage.setAccessType(selectedType);
meshMessage.setDestinationAddress(dstAdr);
meshMessage.setOpcode(opcode);
meshMessage.setParams(params);
meshMessage.setResponseOpcode(rspOpcode);
meshMessage.setResponseMax(rspMax);
meshMessage.setRetryCnt(retryCnt);
meshMessage.setTtl(ttl);
meshMessage.setTidPosition(tidPosition);
return meshMessage;
}
private void resetUI(MeshMessage meshMessage) {
if (meshMessage == null) return;
final AccessType accessType = meshMessage.getAccessType();
final int dstAdr = meshMessage.getDestinationAddress();
final int opcode = meshMessage.getOpcode();
final byte[] params = meshMessage.getParams();
final int rspOpcode = meshMessage.getResponseOpcode();
final int rspMax = meshMessage.getResponseMax();
final int retryCnt = meshMessage.getRetryCnt();
final int ttl = meshMessage.getTtl();
final int tidPosition = meshMessage.getTidPosition();
et_ac_type.setText(accessType == AccessType.APPLICATION ? ACCESS_TYPES[0] : ACCESS_TYPES[1]);
selectedType = accessType;
et_dst_adr.setText(String.format("%04X", dstAdr));
et_opcode.setText(MeshUtils.formatIntegerByHex(opcode));
et_params.setText(Arrays.bytesToHexString(params));
et_rsp_opcode.setText(
rspOpcode == MeshMessage.OPCODE_INVALID
?
"" : MeshUtils.formatIntegerByHex(rspOpcode));
et_rsp_max.setText(String.valueOf(rspMax));
et_retry_cnt.setText(String.valueOf(retryCnt));
et_ttl.setText(String.valueOf(ttl));
et_tid.setText(tidPosition < 0 ? "" : String.valueOf(tidPosition));
}
private void onAccessTypeSelect(int position) {
if (position == 0) {
selectedType = AccessType.APPLICATION;
} else {
selectedType = AccessType.DEVICE;
}
et_ac_type.setText(ACCESS_TYPES[position]);
}
private void onActionSelect(int position) {
et_actions.setText(PRESET_ACCESS_MESSAGES[position]);
MeshMessage meshMessage = null;
/*
"Vendor On",
"Vendor Off",
"Vendor On/Off Get",
"Vendor On NO-ACK",
"Vendor Off NO-ACK",
"Generic On",
"Generic Off",
"[Custom]"
*/
// on/off (generic/vendor) command tid position is 1
final int onOffTidPosition = 1;
switch (position) {
case 0: // Vendor On
meshMessage = createVendorMessage(0x0211C2, 0x0211C4, new byte[]{0x01, 0x00}, onOffTidPosition);
break;
case 1: // Vendor Off
meshMessage = createVendorMessage(0x0211C2, 0x0211C4, new byte[]{0x00, 0x00}, onOffTidPosition);
break;
case 2: // vendor on/off get
meshMessage = createVendorMessage(0x0211C1, 0x0211C4, null, onOffTidPosition);
break;
case 3: // Vendor On NO-ACK
meshMessage = createVendorMessage(0x0211C3, MeshMessage.OPCODE_INVALID, new byte[]{0x01, 0x00}, onOffTidPosition);
break;
case 4: // Vendor Off NO-ACK
meshMessage = createVendorMessage(0x0211C3, MeshMessage.OPCODE_INVALID, new byte[]{0x00, 0x00}, onOffTidPosition);
break;
case 5: // Generic On
meshMessage = OnOffSetMessage.getSimple(MSG_DST_ADR, appKeyIndex, OnOffSetMessage.ON, true, 0);
break;
case 6: // Generic Off
meshMessage = OnOffSetMessage.getSimple(MSG_DST_ADR, appKeyIndex, OnOffSetMessage.OFF, true, 0);
break;
case 7: // OpcodeAggregatorSequenceMessage - app key
{
int elementAddress = 0x0002;
List<MeshMessage> aggMsgs = new ArrayList<>();
aggMsgs.add(new LightnessDefaultGetMessage());
aggMsgs.add(new LightnessRangeGetMessage());
byte[] params = MeshUtils.aggregateMessages(elementAddress, aggMsgs);
meshMessage = new OpcodeAggregatorSequenceMessage(0x0002, AccessType.APPLICATION, appKeyIndex, params);
break;
}
case 8: // OpcodeAggregatorSequenceMessage - device key
{
int elementAddress = 0x0002;
List<MeshMessage> aggMsgs = new ArrayList<>();
aggMsgs.add(new DefaultTTLGetMessage());
aggMsgs.add(new RelayGetMessage());
aggMsgs.add(new FriendGetMessage());
byte[] params = MeshUtils.aggregateMessages(elementAddress, aggMsgs);
meshMessage = new OpcodeAggregatorSequenceMessage(0x0002, AccessType.DEVICE, appKeyIndex, params);
break;
}
case 9:
createNewMessage();
return;
}
resetUI(meshMessage);
}
private void createNewMessage() {
et_dst_adr.setText(String.format("%04X", MSG_DST_ADR));
et_opcode.setText("");
et_params.setText("");
et_rsp_opcode.setText("");
et_rsp_max.setText("0");
et_retry_cnt.setText(String.valueOf(MeshMessage.DEFAULT_RETRY_CNT));
et_ttl.setText(String.valueOf(MeshMessage.DEFAULT_TTL));
et_tid.setText("");
}
private MeshMessage createVendorMessage(int opcode, int rspOpcode, byte[] params, int tidPosition) {
MeshMessage meshMessage = new MeshMessage();
meshMessage.setDestinationAddress(MSG_DST_ADR);
meshMessage.setOpcode(opcode);
meshMessage.setParams(params);
meshMessage.setResponseOpcode(rspOpcode);
// meshMessage.setResponseMax(0);
// meshMessage.setRetryCnt(2);
// meshMessage.setTtl(5);
meshMessage.setTidPosition(tidPosition);
return meshMessage;
}
private void showAccessDialog() {
if (accessDialog == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setItems(ACCESS_TYPES, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onAccessTypeSelect(which);
accessDialog.dismiss();
}
});
builder.setTitle("Types");
accessDialog = builder.create();
}
accessDialog.show();
}
private void showActionDialog() {
if (mShowPresetDialog == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setItems(PRESET_ACCESS_MESSAGES, (dialog, which) -> {
onActionSelect(which);
mShowPresetDialog.dismiss();
});
builder.setTitle("Actions");
mShowPresetDialog = builder.create();
}
mShowPresetDialog.show();
}
@Override
public void performed(Event<String> event) {
if (event.getType().equals(OnOffStatusMessage.class.getName())) {
logHandler.obtainMessage(MSG_APPEND_LOG, "On Off status notify").sendToTarget();
} else if (event.getType().equals(StatusNotificationEvent.EVENT_TYPE_NOTIFICATION_MESSAGE_UNKNOWN)) {
NotificationMessage notificationMessage = ((StatusNotificationEvent) event).getNotificationMessage();
int opcode = notificationMessage.getOpcode();
logHandler.obtainMessage(MSG_APPEND_LOG, String.format("Unknown status notify opcode:%04X", opcode) + " -- params:" + Arrays.bytesToHexString(notificationMessage.getParams())).sendToTarget();
} else if (event.getType().equals(OpcodeAggregatorStatusMessage.class.getName())) {
NotificationMessage notificationMessage = ((StatusNotificationEvent) event).getNotificationMessage();
OpcodeAggregatorStatusMessage aggStatusMsg = (OpcodeAggregatorStatusMessage) notificationMessage.getStatusMessage();
List<AggregatorItem> items = aggStatusMsg.statusItems;
StringBuilder desc = new StringBuilder("Opcode Aggregator Status: \n");
desc.append("raw:").append(Arrays.bytesToHexString(notificationMessage.getParams())).append("\n");
desc.append("parsed:\n");
desc.append("\tstatus=").append(aggStatusMsg.status).append("\n")
.append(String.format("\telementAdr=%04X", aggStatusMsg.elementAddress)).append("\n");
for (AggregatorItem item : items) {
desc.append("\t").append(item.toString()).append("\n");
}
logHandler.obtainMessage(MSG_APPEND_LOG, desc.toString()).sendToTarget();
}
}
}
|
/*
* Copyright (C) 2010 vektor
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.cuni.mff.ksi.jinfer.base.interfaces;
import cz.cuni.mff.ksi.jinfer.base.objects.FolderType;
import java.io.InputStream;
import java.util.List;
/**
* Interface of any class that can take an InputStream and produce {@link List} of elements T
* from it. The class must work as a singleton, subsequent calls to
* {@link cz.cuni.mff.ksi.jinfer.base.interfaces.Processor#process(InputStream)}
* will be on the same instance.
*
* @param <T> Type of items returned in List by {@link #process(java.io.InputStream) } method.
* @author vektor
*/
public interface Processor<T> {
/**
* Which folder does this processor operate on.
*
* @return Folder on which this processor operates.
*/
FolderType getFolder();
/**
* Which extension can this processor process.
*
* @return File extension this processor can process.
*/
String getExtension();
/**
* Whether this processor can process also different extensions than that
* specified in
* {@link cz.cuni.mff.ksi.jinfer.base.interfaces.Processor#getExtension()}.
*
* @return True if this processor can process files with extensions
* different from what
* {@link cz.cuni.mff.ksi.jinfer.base.interfaces.Processor#getExtension()}
* reports. False otherwise.
*/
boolean processUndefined();
/**
* Returns the {@link List} of type defined for this processor which represents the input.
*
* @param s Input of any arbitrary type.
* @return Rules contained within. Empty list if there are no rules or an error occurs.
* @throws InterruptedException When user interrupts the processing operation at any moment.
*/
List<T> process(final InputStream s) throws InterruptedException;
/**
* Get {@link Class} of the type this processor returns by process method within {@link List}.
* @return {@link Class} of the type this processor returns by process method within {@link List}.
*/
Class<?> getResultType();
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="nav.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A=="
crossorigin="anonymous" referrerpolicy="no-referrer">
</head>
<body>
<header>
<div class="navbar" id="navbar">
<div class="name">
<a href="#"><img id="navbar-img" src="website-development.webp"></a>
<li><a href="#">GreenState.Tech</a></li>
</div>
<div class="hamburger">
<div class="line1"></div>
<div class="line2"></div>
<div class="line3"></div>
</div>
<ul class="navbar-links">
<li><a href="index.html"><i class="fas fa-house"></i> Hjem</a></li>
<li><a href="info.html"><i class="fa-solid fa-list"></i> Info</a></li>
<li><a href="regler.html"><i class="fa-solid fa-clipboard"></i> Om os</a></li>
</ul>
</div>
</header>
<script src="script.js"></script>
<main>
<section class="intro">
<div class="intro-content">
<h1>GreenState Tech</h1>
<h3>We shape the future</h3>
</p>
<p class="lg-p"> <a class="content-link" href="#">Se hvad vi tilbyder <i
class="fas fa-arrow-alt-circle-right"></i></a> </p>
</div>
<div class="intro-img"> <img src="website-development.webp" alt=""> </div>
</section>
<section class="features">
<div class="features-item">
<div class="features-item-head"> <img
src="https://hannahshiels.github.io/front-end-mentor/fylo-dark-theme-landing-page-master/images/icon-access-anywhere.svg"
alt=""> </div>
<div class="features-item-body mt-2">
<h3>Lorem</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto eos officia itaque sunt quisquam, enim sed temporibus excepturi similique ipsa veritatis ullam iusto! Nihil id harum voluptates minima porro cumque?</p>
</div>
</div>
<div class="features-item">
<div class="features-item-head"> <img
src="https://hannahshiels.github.io/front-end-mentor/fylo-dark-theme-landing-page-master/images/icon-security.svg"
alt=""> </div>
<div class="features-item-body mt-2">
<h3>Lorem</h3>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Molestiae quos quisquam magni, necessitatibus alias vero ullam? Facilis sapiente, temporibus facere aliquid unde quos nisi est assumenda asperiores nulla at dicta.</p>
</div>
</div>
<div class="features-item">
<div class="features-item-head"> <img
src="https://hannahshiels.github.io/front-end-mentor/fylo-dark-theme-landing-page-master/images/icon-collaboration.svg"
alt=""> </div>
<div class="features-item-body mt-2">
<h3>Lorem</h3>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Inventore laudantium nesciunt voluptate repudiandae ullam eveniet iusto deleniti, porro ab molestiae officia asperiores aut ex in sed quae! Reiciendis, dolores facere.</p>
</div>
</div>
<div class="features-item">
<div class="features-item-head"> <img
src="https://hannahshiels.github.io/front-end-mentor/fylo-dark-theme-landing-page-master/images/icon-any-file.svg"
alt=""> </div>
<div class="features-item-body mt-2">
<h3>Lorem</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint esse tenetur perspiciatis quo labore dolorem eligendi, molestiae eveniet, voluptatum error porro consequuntur, voluptates et perferendis modi quisquam quaerat voluptatibus amet.</p>
</div>
</div>
</section>
<section class="productive">
<div class="productive-img"> <img
src="https://hannahshiels.github.io/front-end-mentor/fylo-dark-theme-landing-page-master/images/illustration-stay-productive.png"
alt=""> </div>
<div class="productive-content">
<h2>Stay productive, wherever you are</h2>
<p class="lg-p"> Never let location be an issue when accessing your files. Fylo has you covered for all
of your file storage needs. </p>
<p class="lg-p"> Securely share files and folders with friends, family and colleagues for live
collaboration. No email attachments required.
</p>
<p class="lg-p"> <a class="content-link" href="#">See how Fylo works <i
class="fas fa-arrow-alt-circle-right"></i></a> </p>
</div>
</section>
<section class="price-table">
<div class="pricing-table">
<h2 class="pricing-table__header">- BASIC -</h2>
<h3 class="pricing-table__price">£50</h3>
<a target="_blank" class="pricing-table__button" href="#">
Join Now!
</a>
<ul class="pricing-table__list">
<li>30 day free trial</li>
<li>50gb storage space</li>
<li>20% discount</li>
<li class="ni">24 hour support</li>
</ul>
</div>
<div class="pricing-table featured-table">
<h2 class="pricing-table__header">- BUSINESS -</h2>
<h3 class="pricing-table__price">£80</h3>
<a target="_blank" class="pricing-table__button" href="#">
Join Now!
</a>
<ul class="pricing-table__list">
<li>40 day free trial</li>
<li>100gb storage space</li>
<li>25% discount</li>
<li>24 hour support</li>
</ul>
</div>
<div class="pricing-table">
<h2 class="pricing-table__header">- PREMIUM -</h2>
<h3 class="pricing-table__price">£130</h3>
<a target="_blank" class="pricing-table__button" href="#">
Join Now!
</a>
<ul class="pricing-table__list">
<li>50 day free trial</li>
<li>200gb storage space</li>
<li>40% discount</li>
<li>24 hour support</li>
</ul>
</div>
<div class="pricing-table">
<h2 class="pricing-table__header">- PREMIUM -</h2>
<h3 class="pricing-table__price">£130</h3>
<a target="_blank" class="pricing-table__button" href="#">
Join Now!
</a>
<ul class="pricing-table__list">
<li>50 day free trial</li>
<li>200gb storage space</li>
<li>40% discount</li>
<li>24 hour support</li>
</ul>
</div>
</section>
<section class="testimonial">
<div class="testimonial-item">
<div class="testimonial-item-text">
<p>Fylo has improved our team productivity by an order of magnitude. Since making the switch our
team has become a well-oiled collaboration machine.</p>
</div>
<div class="testimonial-item-reviewer">
<div class="testimonial-item-reviewer-img"> <img
src="https://hannahshiels.github.io/front-end-mentor/fylo-dark-theme-landing-page-master/images/profile-1.jpg"
alt=""></div>
<div class="ml-1 testimonial-item-reviewer-text">
<h4>Anders Rehmeier</h4>
<p>Founder & CEO</p>
</div>
</div>
</div>
<div class="testimonial-item">
<div class="testimonial-item-text">
<p>Fylo has improved our team productivity by an order of magnitude. Since making the switch our
team has become a well-oiled collaboration machine.</p>
</div>
<div class="testimonial-item-reviewer">
<div class="testimonial-item-reviewer-img"> <img
src="https://hannahshiels.github.io/front-end-mentor/fylo-dark-theme-landing-page-master/images/profile-2.jpg"
alt=""></div>
<div class="ml-1 testimonial-item-reviewer-text">
<h4> Bruce McKenzie </h4>
<p>Founder & CEO, Huddle</p>
</div>
</div>
</div>
</section>
</main>
<footer>
<section class="contact-info">
<div class="contact-info-logo"> <img
src="https://hannahshiels.github.io/front-end-mentor/fylo-dark-theme-landing-page-master/images/logo.svg"
alt=""> </div>
<div class="contact-info-location">
<div class="contact-info-location-item">
<i class="fa-solid fa-location-dot img-footer"></i>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua</p>
</div>
</div>
<div class="contact-info-contacts">
<div class="contact-info-contacts-item">
<i class="fa-solid fa-phone img-footer"></i>
<p>example@fylo.com</p>
</div>
<div class="contact-info-contacts-item ">
<i class="fa-solid fa-envelope img-footer"></i>
<p>example@fylo.com</p>
</div>
</div>
<nav class="contact-info-links">
<ul class="contact-info-links-list">
<li> <a href="#">About Us</a> </li>
<li> <a href="#">Jobs</a> </li>
<li> <a href="#">Press</a> </li>
<li> <a href="#">Blog</a> </li>
</ul>
<ul class="contact-info-links-list">
<li> <a href="#">Contact Us</a> </li>
<li> <a href="#">Terms</a> </li>
<li> <a href="#">Privacy</a> </li>
</ul>
</nav>
<div class="contact-info-social-links">
<a class="icon-link" href="#">
<div class="contact-info-social-link-item flex-center"> <i class="fab fa-facebook-f"></i></div>
</a>
<a class="icon-link" href="#">
<div class="contact-info-social-link-item flex-center"> <i class="fab fa-twitter"></i></div>
</a>
<a class="icon-link" href="#">
<div class="contact-info-social-link-item flex-center"> <i class="fab fa-instagram"></i> </div>
</a>
</div>
</section>
</footer>
</body>
</html>
|
const { SlashCommandBuilder } = require('@discordjs/builders');
module.exports = {
// Define the command using SlashCommandBuilder
data: new SlashCommandBuilder()
.setName('rps') // Set the command name
.setDescription('Play a game of Rock, Paper, Scissors.') // Set the description
// Add a string option for the user's choice with predefined choices
.addStringOption(option =>
option.setName('choice')
.setDescription('Your choice: rock, paper, or scissors.')
.setRequired(true)
.addChoices(
{ name: 'Rock', value: 'rock'},
{ name: 'Paper', value: 'paper'},
{ name: 'Scissors', value: 'scissors'}
)),
// The execute function that runs when the command is used
async execute(interaction) {
// Retrieve the user's choice from the command interaction
const userChoice = interaction.options.getString('choice');
// Possible choices for the bot
const choices = ['rock', 'paper', 'scissors'];
// Randomly select the bot's choice
const botChoice = choices[Math.floor(Math.random() * choices.length)];
// Determine the result of the game
let result;
if (userChoice === botChoice) {
result = 'It\'s a draw!';
} else if (
(userChoice === 'rock' && botChoice === 'scissors') ||
(userChoice === 'paper' && botChoice === 'rock') ||
(userChoice === 'scissors' && botChoice === 'paper')
) {
result = 'You win!';
} else {
result = 'You lose!';
}
// Reply to the interaction with the outcome of the game
await interaction.reply(`You chose ${userChoice}, I chose ${botChoice}. ${result}`);
},
};
|
import React, { useState } from 'react';
function DynamicSelect({ menu, index }) {
const [total, setTotal] = useState(0);
const [form, setForm] = useState('');
const handleChange = (event) => {
const { value, name } = event.target;
setForm({
...form,
[name]: value,
});
setTotal(total + parseInt(value));
};
return (
<fieldset>
<label className='animate-bounce block text-lime-500 text-2xl font-bold mb-2 py-1'>
{`${index + 1}. ${menu[index].title}`}
</label>
<select
name={`opcion${index}`}
onChange={handleChange}
className='appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline'
>
<option selected='selected' value='0'>
Seleccione una opción
</option>
{menu[index].options.map((item) => (
<option value={item.cost}>{item.value}</option>
))}
</select>
</fieldset>
);
}
export default DynamicSelect;
/*AQUI COMIENZA LO QUE ESTABA EN QUOTES
import React, { useState, useEffect } from 'react';
import {
createDocument,
getDocument,
} from '../../firebase/collectionsFirebase';
import DynamicSelect from '../DynamicSelect';
function Quotes() {
const [menu, setMenu] = useState({});
const [total, setTotal] = useState(0);
const [index, setIndex] = useState(0);
const [form, setForm] = useState('');
const handleChange = (event) => {
const { value, name } = event.target;
setForm({
...form,
[name]: value,
});
//console.log(form, typeof form);
setTotal(total + parseInt(value));
setIndex(index + 1);
};
//console.log('total', total);
const handleClick = (event) => {
event.preventDefault();
createDocument('test', form);
};
useEffect(() => {
getDocument('services', 'Ep6ATdkUcqWIqUcTSuC7').then(({ menus }) => {
setMenu(menus);
});
}, []);
return (
<div className='w-full max-w-xs m-auto'>
{!menu.length ? (
<p>Loading...</p>
) : (
<>AQUI COMIENZA LO QUE CRISTIAN HIZO COMENTAR, QUE LO GUARDARA PARA FUTURAS REFERENCIAS
{/*menu.map((element) => (
<>
<p>{element.title}</p>
<select
name='opcion1'
//onChange={handleChange}
className='appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline'
>
<option value=''>Seleccione una opción</option>
{element.options.map((item) => (
<option value={item.cost}>{item.value}</option>
))}
</select>
</>
))}AQUI TERMINA LO QUE COMENTO CRISTIAN
<label className='animate-bounce block text-lime-500 text-2xl font-bold mb-2 py-1'>
{`${index + 1}. ${menu[index].title}`}
</label>
<select
name={`opcion${index}`}
onChange={handleChange}
className='appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline'
>
<option selected='selected' value='0'>
Seleccione una opción
</option>
{menu[index].options.map((item) => (
<option value={item.cost}>{item.value}</option>
))}
</select>
<DynamicSelect menu={menu} index={index} />
{Object.keys(form).length === 7 && (
<div className='flex items-center justify-between '>
<button
onClick={handleClick}
className='transition
duration-700
ease-in-out
transform hover:-translate-y-1
hover:scale-110
bg-lime-500
hover:bg-cyan-300
text-slate-900
font-semibold
py-3 px-6
rounded-md'
>
Enviar especificaciones
</button>
</div>
)}
</>
)}
</div>
);
}
export default Quotes;*/
|
/* ---------------------- ASTAR x THREEJS BASIC SKETCH ---------------------- */
// ThreeJS instance is available through the THREE variable
// Make sure you added the threejs dependency on your workspace manager
/* -------------------------- SCENE INITIALIZATION -------------------------- */
const scene = new THREE.Scene();
scene.background = new THREE.Color("#663399");
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.set(0, 0, 5);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
/* -------------------- BASIC BOX DISPLAY WITH WIREFRAME -------------------- */
const geometry = new THREE.BoxGeometry(2, 2, 2, 3, 3, 3);
const material = new THREE.MeshBasicMaterial({ color: "#490165" });
const material_wireframe = new THREE.MeshBasicMaterial({
color: "#ff69b4",
wireframe: true,
});
const box = new THREE.Mesh(geometry, material);
const box_wireframe = new THREE.Mesh(geometry, material_wireframe);
scene.add(box);
scene.add(box_wireframe);
let box_size = createControl("SIZE", 1);
let wireframe_toggle = createControl("WIREFRAME", "note_off");
/* --------------------------- ANIMATE / REAL TIME -------------------------- */
window.postMessage("from hello world, hello", "*");
function animate() {
requestAnimationFrame(animate);
window.postMessage(
{
type: "timestamp",
timestamp: Date.now(),
},
"*"
);
// let counter = 0;
// while (counter < Math.random() * (1e9 - 1e7) + 1e7) {
// counter++;
// }
// Change the box size through the ASTAR control
box.scale.set(box_size.value, box_size.value, box_size.value);
box_wireframe.scale.set(
box_size.value * 1.1,
box_size.value * 1.1,
box_size.value * 1.1
);
// Display or hide the box wireframe through the ASTAR control
if (wireframe_toggle.value === "note_on") {
box_wireframe.visible = true;
} else {
box_wireframe.visible = false;
}
// Rotate the box
box.rotation.x += 0.01;
box.rotation.z -= 0.004;
box_wireframe.rotation.x += 0.01;
box_wireframe.rotation.z -= 0.004;
// Render the scene
renderer.render(scene, camera);
}
animate();
|
import { useSelector } from "react-redux";
import { Footer, Header, PostCard, UserProfileCard, Sidebar, WhoToFollowCard, ScrollToTop } from "../../components"
export const Profile = () => {
const { allPosts } = useSelector(state => state.post);
const { userData: { username, fullName } } = useSelector(state => state.auth);
const currentUserPost = allPosts?.filter(post => post.username === username);
return (
<main className="main-container">
<ScrollToTop />
<Header />
<section className="content-container grid">
<div className="left-container fixed ">
<Sidebar />
</div>
<section className="mid-container flex flex-col gap-4 min-h-screen">
<div className="flex mx-8 mt-6 items-center">
<h1 className="text-2xl font-bold font-primary">{fullName}</h1>
<p className="text-sm mx-2 text-gray-600 font-semibold font-primary"> ({currentUserPost?.length} posts )</p>
</div>
<div>
{/* User details here */}
<UserProfileCard />
<p className="mx-8 my-6 text-xl font-bold">Your Posts : </p>
{
currentUserPost.length === 0 ?
<p className="text-xl mt-10 text-center">No post.</p>
:
currentUserPost?.map(post => {
return <PostCard post={post} key={post._id} />
})
}
</div>
</section>
<section className="right-container fixed hidden text-xs lg:block xl:text-base">
<WhoToFollowCard />
</section>
</section>
<Footer />
</main>
)
}
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:share/share.dart';
import 'CustomDrawer().dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController textFieldController = TextEditingController();
TextEditingController repeatController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: CustomDrawer(),
appBar: AppBar(
backgroundColor: Colors.deepPurple,
title: Text(
'تکرار کننده ای متن',
style: TextStyle(
color: Colors.white,
fontFamily: 'Lalezar-Regular',
),
),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.white),
),
child: Padding(
padding: const EdgeInsets.only(left: 1),
child: TextField(
controller: textFieldController,
textAlign: TextAlign.center,
keyboardType: TextInputType.text,
decoration: InputDecoration(
hintStyle: TextStyle(
color: Colors.grey,
fontFamily: 'Lalezar-Regular',
),
border: InputBorder.none,
hintText: "متن را وارد کنید",
),
),
),
),
),
SizedBox(height: 10),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.white),
),
child: Padding(
padding: const EdgeInsets.only(left: 1),
child: TextField(
controller: repeatController,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
decoration: InputDecoration(
hintStyle: TextStyle(
color: Colors.grey,
fontFamily: 'Lalezar-Regular',
),
border: InputBorder.none,
hintText: "تعداد تکرار را وارد کنید",
),
),
),
),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 150,
child: ElevatedButton(
onPressed: () {
String textToShare = textFieldController.text;
String repeatCountString = repeatController.text;
if (textToShare.isNotEmpty &&
repeatCountString.isNotEmpty) {
int repeatCount = int.parse(repeatCountString);
if (repeatCount > 0) {
_shareTextWithRepeat(textToShare, repeatCount);
} else {
// Handle invalid repeat count
print('Invalid repeat count');
}
} else {
// Handle empty text or repeat count case
print('Text field or repeat count is empty');
}
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.deepPurpleAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
padding: EdgeInsets.symmetric(
vertical: 15.0,
horizontal: 15.0,
),
),
child: Text(
'ارسال',
style: TextStyle(
color: Colors.white,
fontFamily: 'Lalezar-Regular',
fontSize: 24,
),
),
),
),
Container(
width: 150,
child: ElevatedButton(
onPressed: () {
String textToCopy = textFieldController.text;
String repeatCountString = repeatController.text;
int repeatCount = int.tryParse(repeatCountString) ?? 0;
if (textToCopy.isNotEmpty && repeatCount > 0) {
String textToCopyRepeated =
List.generate(repeatCount, (index) => textToCopy)
.join('\n');
Clipboard.setData(
ClipboardData(text: textToCopyRepeated));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.deepPurple,
elevation: 10,
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.all(5),
content: Text(
'متن تکرار شده کپی شد',
textAlign: TextAlign.center,
// این خط اضافه شده است
style: TextStyle(
color: Colors.white,
fontFamily: 'Lalezar-Regular',
fontSize: 18,
),
),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.deepPurple,
elevation: 10,
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.all(5),
duration: Duration(seconds: 1),
content: Text(
'لطفا متنی را وارد کنید',
style: TextStyle(
color: Colors.white,
fontFamily: 'Lalezar-Regular',
fontSize: 18,
),
),
),
);
}
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.deepPurpleAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
padding: EdgeInsets.symmetric(
vertical: 15.0,
horizontal: 15.0,
),
),
child: Text(
'کپی',
style: TextStyle(
color: Colors.white,
fontFamily: 'Lalezar-Regular',
fontSize: 24,
),
),
),
),
],
),
],
),
),
);
}
void _shareTextWithRepeat(String text, int repeatCount) {
String repeatedText =
List.generate(repeatCount, (index) => text).join('\n');
Share.share(repeatedText);
}
}
|
using AcademyF.Week2.EsercitazioneDesignPattern.Decorator;
using AcademyF.Week2.EsercitazioneDesignPattern.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace AcademyF.Week2.EsercitazioneDesignPattern.Test
{
public class DecoratorTest
{
[Fact]
public void ShouldHaveEmployeeWithoutBenefit()
{
//Se un impiegato è un impiegato semplice mi aspetto che non abbia nessun tipo di
//benefit
//ARRANGE
Employee employee = new Employee
{
FirstName = "Mario",
LastName = "Rossi"
};
//ACT
string benefit = employee.ViewBenefit();
//ASSERT
//Mi aspetto che la stringa contentente i benefit sia vuota
Assert.Equal("", benefit);
Assert.True(string.IsNullOrEmpty(benefit));
}
[Fact]
public void ShouldHaveCarParkingNotNullForEmployee()
{
//Per impiegati caratterizzati dal benefit posto auto voglio che
//il codice del posto auto sia non nullo o diverso da stringa vuota
//ARRANGE
Employee employee = new Employee
{
FirstName = "Mario",
LastName = "Rossi"
};
//Creo il componente in grado di arricchire l'impiegato con il benefit
//posto auto
employee = new EmployeeParkingCar(employee, "P3456");
//ACT
string benefit = employee.ViewBenefit();
//ASSERT
Assert.NotEqual("", benefit); //VALIDO MA NON PERFETTAMENTE COMPRENSIBILE
Assert.True(!string.IsNullOrEmpty(benefit));
Assert.Contains("P3456", benefit);
}
[Fact]
public void ShouldHaveHealtyPolicyNullForEmployee()
{
//Per impiegati caratterizzati dal benefit assistenza sanitaria voglio che
//il codice dell'assistenza sia non nullo o diverso da stringa vuota
//ARRANGE
Employee employee = new Employee
{
FirstName = "Mario",
LastName = "Rossi"
};
//Creo il componente in grado di arricchire l'impiegato con il benefit
//posto auto
employee = new EmployeeHealthyPolicy(employee, "H123");
//ACT
string benefit = employee.ViewBenefit();
//ASSERT
Assert.NotEqual("", benefit); //VALIDO MA NON PERFETTAMENTE COMPRENSIBILE
Assert.True(!string.IsNullOrEmpty(benefit));
Assert.Contains("H123", benefit);
}
[Fact]
public void ShouldHaveCar()
{
//Per impiegati caratterizzati dal benefit macchina aziendale voglio che
//il codice della targa e il modello sia non nullo o diverso da stringa vuota
//ARRANGE
Employee employee = new Employee
{
FirstName = "Mario",
LastName = "Rossi"
};
//Creo il componente in grado di arricchire l'impiegato con il benefit
//posto auto
employee = new EmployeeCar(employee, "H123", "Punto");
//ACT
string benefit = employee.ViewBenefit();
//ASSERT
Assert.NotEqual("", benefit); //VALIDO MA NON PERFETTAMENTE COMPRENSIBILE
Assert.True(!string.IsNullOrEmpty(benefit));
Assert.Contains("H123", benefit);
Assert.Contains("Punto", benefit);
}
[Fact]
public void ShouldHaveRestaurantTicket()
{
//Per impiegati caratterizzati dal benefit Mensa voglio che
//il codice della carta sia non nullo o diverso da stringa vuota
//e il numero dei pasti siano maggiori di 0
//ARRANGE
Employee employee = new Employee
{
FirstName = "Mario",
LastName = "Rossi"
};
//Creo il componente in grado di arricchire l'impiegato con il benefit
//posto auto
employee = new EmployeeRestaurant(employee, "H1etete23", 4);
//ACT
string benefit = employee.ViewBenefit();
//ASSERT
Assert.NotEqual("", benefit); //VALIDO MA NON PERFETTAMENTE COMPRENSIBILE
Assert.True(!string.IsNullOrEmpty(benefit));
Assert.Contains("H1etete23", benefit);
Assert.Contains("4", benefit);
}
[Fact]
public void ShouldHaveAllBenefits()
{
//Per impiegati caratterizzati sia dal benefit assistenza sanitaria che posto auto
//voglio che sia il codice dell'assistenza che quello del posto auto
//sia non nullo o diverso da stringa vuota
//ARRANGE
//Creo come dipendente di partenza un dipendente che abbia il posto auto assegnato
Employee employee = new Employee
{
FirstName = "Mario",
LastName = "Rossi"
};
var employeeParkingCar = new EmployeeParkingCar(employee, "WE4889");
//Creo il componente in grado di arricchire l'impiegato con il benefit
//posto auto
employee = new EmployeeHealthyPolicy(employeeParkingCar, "H123");
employee = new EmployeeRestaurant(employee, "H1etete23", 4);
employee = new EmployeeCar(employee, "H123", "Punto");
employee = new EmployeeParkingCar(employee, "P3456");
//ACT
string benefit = employee.ViewBenefit();
//ASSERT
Assert.NotEqual("", benefit); //VALIDO MA NON PERFETTAMENTE COMPRENSIBILE
Assert.True(!string.IsNullOrEmpty(benefit));
Assert.Contains("H123", benefit);
Assert.Contains("Punto", benefit);
Assert.Contains("WE4889", benefit);
Assert.Contains("H1etete23", benefit);
Assert.Contains("4", benefit);
Assert.Contains("P3456", benefit);
}
}
}
|
package es.storeapp.web.forms;
import jakarta.validation.constraints.*;
import org.springframework.web.multipart.MultipartFile;
public class UserProfileForm {
@NotNull(message = "El nombre no puede ser nulo")
@NotBlank(message = "El nombre no puede estar en blanco")
@Size(min = 4, message = "El nombre debe tener al menos 4 caracteres")
private String name;
@NotNull(message = "El correo electrónico no puede ser nulo")
@NotBlank(message = "El correo electrónico no puede estar en blanco")
@Email(message = "Debe ingresar una dirección de correo electrónico válida")
private String email;
private String password;
@NotNull(message = "La dirección no puede ser nula")
@NotBlank(message = "La dirección no puede estar en blanco")
private String address;
private MultipartFile image;
public UserProfileForm() {
}
public UserProfileForm(String name, String email, String address) {
this.name = name;
this.email = email;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
}
|
import streamlit as st
SSS_URL = 'https://special-song-search.onrender.com'
def st_readme_introduction():
st.subheader('Introduction', divider=True, anchor='intro')
with st.expander('Show/Hide', expanded=True):
st.markdown("""
Special-song-search is a web application that allows you to search
for new songs fitting all of your requirments.
Rather than using a machine learning model which needs to collect
your data to make some acceptable recommendations, Special Song
Search provides several options and relies on you to specify what
is most important to you. This means:
1. It doesn't have to store your data.
2. It can quickly alter its recommendations.
3. If you like the results, it won't keep re-recommending the same
small set of songs as some other recommendation engines do.
""")
st.image('https://raw.githubusercontent.com/jmlazaro25/special-song-search/main/images/display_example.png')
def st_readme_build():
st.subheader('Build', divider=True)
with st.expander('Show/Hide', expanded=True):
st.markdown("""
This is the result of:
1. Collecting open artist and song (recording) data from
[MusicBrainz](https://musicbrainz.org/)'s API,
2. Storing it in a new database using SQLAlchemy for faster access,
4. And creating a Streamlit app with which users can interact and
indirectly query the SQL database.
""")
def st_readme_data_preview():
st.subheader('Data Preview', divider=True)
with st.expander('Show/Hide', expanded=True):
st.markdown("""
In the modest data collection that has been done so far, the top 30
recording tags account for slightly over half of tags used:
""")
st.image('https://raw.githubusercontent.com/jmlazaro25/special-song-search/main/images/recording_tag_freq.png')
st.markdown("""
Notably, rock has several variations appearing in the top 30
recording tags: "alternative rock," "pop rock," "indie rock,"
"classic rock," "hard rock," "folk rock," "progressive rock," and
"blues rock." This also occurs with other genre tags such pop. This
begs the question: How much of this is overlap (i.e. recordings
being labelled "rock" and one or more variations vs. just being
labelled "rock")?
""")
st.image('https://raw.githubusercontent.com/jmlazaro25/special-song-search/main/images/rock_heatmap.png')
st.markdown(
"""
This heatmap shows the count of recordings with a tag-pair as a
fraction of the count of the tag on the diagonal for the tag-pair's
row. The bright left-most column indicates that recordings tagged
with any other variation of rock are also likely tagged with rock
itself. For anyone who likes other forms of rock, but not
alternative rock, they should rest assured that even though it is
the most common subset of rock in this dataset, it still only
accounts for a fifth of all rock and they can search for another
subgenre with little overlap. Anyone wanting to slowly explore new
genres or subgenres can choose their favorite tag and search for
new tags with which it often appears together. data_analysis.ipynb
in the project's Github repo shows how these plots can be generated
and goes into more detail about the data.
""",
unsafe_allow_html=True
)
def st_readme():
st_readme_introduction()
st_readme_build()
st_readme_data_preview()
def st_exec_summary():
st.markdown(
f"""
Special Song Search is a song recommendation project I made as I was
unsatisfied with commercial song recommendation engines. It is
primarily for individuals who would like fine grained control over
their recommendations and/or don't want to their data collected and
used for targeted advertising.
You can see an example of the web app below and try it
here: [{SSS_URL}]({SSS_URL}). (Your patience is appreciated as it is
hosted on Render's free teir.)
""",
unsafe_allow_html=True
)
def st_all():
st.header('Special Song Search')
st_exec_summary()
st.subheader('Contents', divider=True)
st.markdown(
'#### 1. [Introduction](#intro)\n'
'#### 2. [Build](#build)\n'
'#### 3. [Data Preview](#data-preview)\n',
unsafe_allow_html=True
)
st_readme()
|
/*
* Copyright © 2007, 2008 Ryan Lortie
* Copyright © 2010 Codethink Limited
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*
* Author: Ryan Lortie <desrt@desrt.ca>
*/
/* Prologue {{{1 */
#include "config.h"
#include <glib/ghash.h>
#include <glib/gmem.h>
#include <glib/gslice.h>
#include <glib/gstrfuncs.h>
#include <glib/gtestutils.h>
#include <glib/gvariant-core.h>
#include <glib/gvariant-serialiser.h>
#include <string.h>
#include "gvariant-internal.h"
/**
* SECTION:gvariant
* @title: GVariant
* @short_description: strongly typed value datatype
* @see_also: GVariantType
*
* #GVariant is a variant datatype; it can contain one or more values
* along with information about the type of the values.
*
* A #GVariant may contain simple types, like an integer, or a boolean value;
* or complex types, like an array of two strings, or a dictionary of key
* value pairs. A #GVariant is also immutable: once it's been created neither
* its type nor its content can be modified further.
*
* GVariant is useful whenever data needs to be serialized, for example when
* sending method parameters in DBus, or when saving settings using GSettings.
*
* When creating a new #GVariant, you pass the data you want to store in it
* along with a string representing the type of data you wish to pass to it.
*
* For instance, if you want to create a #GVariant holding an integer value you
* can use:
*
* |[<!-- language="C" -->
* GVariant *v = g_variant_new ("u", 40);
* ]|
*
* The string "u" in the first argument tells #GVariant that the data passed to
* the constructor (40) is going to be an unsigned integer.
*
* More advanced examples of #GVariant in use can be found in documentation for
* [GVariant format strings][gvariant-format-strings-pointers].
*
* The range of possible values is determined by the type.
*
* The type system used by #GVariant is #GVariantType.
*
* #GVariant instances always have a type and a value (which are given
* at construction time). The type and value of a #GVariant instance
* can never change other than by the #GVariant itself being
* destroyed. A #GVariant cannot contain a pointer.
*
* #GVariant is reference counted using g_variant_ref() and
* g_variant_unref(). #GVariant also has floating reference counts --
* see g_variant_ref_sink().
*
* #GVariant is completely threadsafe. A #GVariant instance can be
* concurrently accessed in any way from any number of threads without
* problems.
*
* #GVariant is heavily optimised for dealing with data in serialised
* form. It works particularly well with data located in memory-mapped
* files. It can perform nearly all deserialisation operations in a
* small constant time, usually touching only a single memory page.
* Serialised #GVariant data can also be sent over the network.
*
* #GVariant is largely compatible with D-Bus. Almost all types of
* #GVariant instances can be sent over D-Bus. See #GVariantType for
* exceptions. (However, #GVariant's serialisation format is not the same
* as the serialisation format of a D-Bus message body: use #GDBusMessage,
* in the gio library, for those.)
*
* For space-efficiency, the #GVariant serialisation format does not
* automatically include the variant's length, type or endianness,
* which must either be implied from context (such as knowledge that a
* particular file format always contains a little-endian
* %G_VARIANT_TYPE_VARIANT which occupies the whole length of the file)
* or supplied out-of-band (for instance, a length, type and/or endianness
* indicator could be placed at the beginning of a file, network message
* or network stream).
*
* A #GVariant's size is limited mainly by any lower level operating
* system constraints, such as the number of bits in #gsize. For
* example, it is reasonable to have a 2GB file mapped into memory
* with #GMappedFile, and call g_variant_new_from_data() on it.
*
* For convenience to C programmers, #GVariant features powerful
* varargs-based value construction and destruction. This feature is
* designed to be embedded in other libraries.
*
* There is a Python-inspired text language for describing #GVariant
* values. #GVariant includes a printer for this language and a parser
* with type inferencing.
*
* ## Memory Use
*
* #GVariant tries to be quite efficient with respect to memory use.
* This section gives a rough idea of how much memory is used by the
* current implementation. The information here is subject to change
* in the future.
*
* The memory allocated by #GVariant can be grouped into 4 broad
* purposes: memory for serialised data, memory for the type
* information cache, buffer management memory and memory for the
* #GVariant structure itself.
*
* ## Serialised Data Memory
*
* This is the memory that is used for storing GVariant data in
* serialised form. This is what would be sent over the network or
* what would end up on disk, not counting any indicator of the
* endianness, or of the length or type of the top-level variant.
*
* The amount of memory required to store a boolean is 1 byte. 16,
* 32 and 64 bit integers and double precision floating point numbers
* use their "natural" size. Strings (including object path and
* signature strings) are stored with a nul terminator, and as such
* use the length of the string plus 1 byte.
*
* Maybe types use no space at all to represent the null value and
* use the same amount of space (sometimes plus one byte) as the
* equivalent non-maybe-typed value to represent the non-null case.
*
* Arrays use the amount of space required to store each of their
* members, concatenated. Additionally, if the items stored in an
* array are not of a fixed-size (ie: strings, other arrays, etc)
* then an additional framing offset is stored for each item. The
* size of this offset is either 1, 2 or 4 bytes depending on the
* overall size of the container. Additionally, extra padding bytes
* are added as required for alignment of child values.
*
* Tuples (including dictionary entries) use the amount of space
* required to store each of their members, concatenated, plus one
* framing offset (as per arrays) for each non-fixed-sized item in
* the tuple, except for the last one. Additionally, extra padding
* bytes are added as required for alignment of child values.
*
* Variants use the same amount of space as the item inside of the
* variant, plus 1 byte, plus the length of the type string for the
* item inside the variant.
*
* As an example, consider a dictionary mapping strings to variants.
* In the case that the dictionary is empty, 0 bytes are required for
* the serialisation.
*
* If we add an item "width" that maps to the int32 value of 500 then
* we will use 4 byte to store the int32 (so 6 for the variant
* containing it) and 6 bytes for the string. The variant must be
* aligned to 8 after the 6 bytes of the string, so that's 2 extra
* bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
* for the dictionary entry. An additional 1 byte is added to the
* array as a framing offset making a total of 15 bytes.
*
* If we add another entry, "title" that maps to a nullable string
* that happens to have a value of null, then we use 0 bytes for the
* null value (and 3 bytes for the variant to contain it along with
* its type string) plus 6 bytes for the string. Again, we need 2
* padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
*
* We now require extra padding between the two items in the array.
* After the 14 bytes of the first item, that's 2 bytes required.
* We now require 2 framing offsets for an extra two
* bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item
* dictionary.
*
* ## Type Information Cache
*
* For each GVariant type that currently exists in the program a type
* information structure is kept in the type information cache. The
* type information structure is required for rapid deserialisation.
*
* Continuing with the above example, if a #GVariant exists with the
* type "a{sv}" then a type information struct will exist for
* "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
* will share the same type information. Additionally, all
* single-digit types are stored in read-only static memory and do
* not contribute to the writable memory footprint of a program using
* #GVariant.
*
* Aside from the type information structures stored in read-only
* memory, there are two forms of type information. One is used for
* container types where there is a single element type: arrays and
* maybe types. The other is used for container types where there
* are multiple element types: tuples and dictionary entries.
*
* Array type info structures are 6 * sizeof (void *), plus the
* memory required to store the type string itself. This means that
* on 32-bit systems, the cache entry for "a{sv}" would require 30
* bytes of memory (plus malloc overhead).
*
* Tuple type info structures are 6 * sizeof (void *), plus 4 *
* sizeof (void *) for each item in the tuple, plus the memory
* required to store the type string itself. A 2-item tuple, for
* example, would have a type information structure that consumed
* writable memory in the size of 14 * sizeof (void *) (plus type
* string) This means that on 32-bit systems, the cache entry for
* "{sv}" would require 61 bytes of memory (plus malloc overhead).
*
* This means that in total, for our "a{sv}" example, 91 bytes of
* type information would be allocated.
*
* The type information cache, additionally, uses a #GHashTable to
* store and lookup the cached items and stores a pointer to this
* hash table in static storage. The hash table is freed when there
* are zero items in the type cache.
*
* Although these sizes may seem large it is important to remember
* that a program will probably only have a very small number of
* different types of values in it and that only one type information
* structure is required for many different values of the same type.
*
* ## Buffer Management Memory
*
* #GVariant uses an internal buffer management structure to deal
* with the various different possible sources of serialised data
* that it uses. The buffer is responsible for ensuring that the
* correct call is made when the data is no longer in use by
* #GVariant. This may involve a g_free() or a g_slice_free() or
* even g_mapped_file_unref().
*
* One buffer management structure is used for each chunk of
* serialised data. The size of the buffer management structure
* is 4 * (void *). On 32-bit systems, that's 16 bytes.
*
* ## GVariant structure
*
* The size of a #GVariant structure is 6 * (void *). On 32-bit
* systems, that's 24 bytes.
*
* #GVariant structures only exist if they are explicitly created
* with API calls. For example, if a #GVariant is constructed out of
* serialised data for the example given above (with the dictionary)
* then although there are 9 individual values that comprise the
* entire dictionary (two keys, two values, two variants containing
* the values, two dictionary entries, plus the dictionary itself),
* only 1 #GVariant instance exists -- the one referring to the
* dictionary.
*
* If calls are made to start accessing the other values then
* #GVariant instances will exist for those values only for as long
* as they are in use (ie: until you call g_variant_unref()). The
* type information is shared. The serialised data and the buffer
* management structure for that serialised data is shared by the
* child.
*
* ## Summary
*
* To put the entire example together, for our dictionary mapping
* strings to variants (with two entries, as given above), we are
* using 91 bytes of memory for type information, 29 bytes of memory
* for the serialised data, 16 bytes for buffer management and 24
* bytes for the #GVariant instance, or a total of 160 bytes, plus
* malloc overhead. If we were to use g_variant_get_child_value() to
* access the two dictionary entries, we would use an additional 48
* bytes. If we were to have other dictionaries of the same type, we
* would use more memory for the serialised data and buffer
* management for those dictionaries, but the type information would
* be shared.
*/
/* definition of GVariant structure is in gvariant-core.c */
/* this is a g_return_val_if_fail() for making
* sure a (GVariant *) has the required type.
*/
#define TYPE_CHECK(value, TYPE, val) \
if \
G_UNLIKELY(!g_variant_is_of_type(value, TYPE)) \
{ \
g_return_if_fail_warning(G_LOG_DOMAIN, G_STRFUNC, \
"g_variant_is_of_type (" #value \
", " #TYPE ")"); \
return val; \
}
/* Numeric Type Constructor/Getters {{{1 */
/* < private >
* g_variant_new_from_trusted:
* @type: the #GVariantType
* @data: the data to use
* @size: the size of @data
*
* Constructs a new trusted #GVariant instance from the provided data.
* This is used to implement g_variant_new_* for all the basic types.
*
* Note: @data must be backed by memory that is aligned appropriately for the
* @type being loaded. Otherwise this function will internally create a copy of
* the memory (since GLib 2.60) or (in older versions) fail and exit the
* process.
*
* Returns: a new floating #GVariant
*/
static GVariant* g_variant_new_from_trusted(const GVariantType* type,
gconstpointer data, gsize size)
{
GVariant* value;
GBytes* bytes;
bytes = g_bytes_new(data, size);
value = g_variant_new_from_bytes(type, bytes, TRUE);
g_bytes_unref(bytes);
return value;
}
/**
* g_variant_new_boolean:
* @value: a #gboolean value
*
* Creates a new boolean #GVariant instance -- either %TRUE or %FALSE.
*
* Returns: (transfer none): a floating reference to a new boolean #GVariant
*instance
*
* Since: 2.24
**/
GVariant* g_variant_new_boolean(gboolean value)
{
guchar v = value;
return g_variant_new_from_trusted(G_VARIANT_TYPE_BOOLEAN, &v, 1);
}
/**
* g_variant_get_boolean:
* @value: a boolean #GVariant instance
*
* Returns the boolean value of @value.
*
* It is an error to call this function with a @value of any type
* other than %G_VARIANT_TYPE_BOOLEAN.
*
* Returns: %TRUE or %FALSE
*
* Since: 2.24
**/
gboolean g_variant_get_boolean(GVariant* value)
{
const guchar* data;
TYPE_CHECK(value, G_VARIANT_TYPE_BOOLEAN, FALSE);
data = g_variant_get_data(value);
return data != NULL ? *data != 0 : FALSE;
}
/* the constructors and accessors for byte, int{16,32,64}, handles and
* doubles all look pretty much exactly the same, so we reduce
* copy/pasting here.
*/
#define NUMERIC_TYPE(TYPE, type, ctype) \
GVariant* g_variant_new_##type(ctype value) \
{ \
return g_variant_new_from_trusted(G_VARIANT_TYPE_##TYPE, &value, \
sizeof value); \
} \
ctype g_variant_get_##type(GVariant* value) \
{ \
const ctype* data; \
TYPE_CHECK(value, G_VARIANT_TYPE_##TYPE, 0); \
data = g_variant_get_data(value); \
return data != NULL ? *data : 0; \
}
/**
* g_variant_new_byte:
* @value: a #guint8 value
*
* Creates a new byte #GVariant instance.
*
* Returns: (transfer none): a floating reference to a new byte #GVariant
*instance
*
* Since: 2.24
**/
/**
* g_variant_get_byte:
* @value: a byte #GVariant instance
*
* Returns the byte value of @value.
*
* It is an error to call this function with a @value of any type
* other than %G_VARIANT_TYPE_BYTE.
*
* Returns: a #guint8
*
* Since: 2.24
**/
NUMERIC_TYPE(BYTE, byte, guint8)
/**
* g_variant_new_int16:
* @value: a #gint16 value
*
* Creates a new int16 #GVariant instance.
*
* Returns: (transfer none): a floating reference to a new int16 #GVariant
*instance
*
* Since: 2.24
**/
/**
* g_variant_get_int16:
* @value: a int16 #GVariant instance
*
* Returns the 16-bit signed integer value of @value.
*
* It is an error to call this function with a @value of any type
* other than %G_VARIANT_TYPE_INT16.
*
* Returns: a #gint16
*
* Since: 2.24
**/
NUMERIC_TYPE(INT16, int16, gint16)
/**
* g_variant_new_uint16:
* @value: a #guint16 value
*
* Creates a new uint16 #GVariant instance.
*
* Returns: (transfer none): a floating reference to a new uint16 #GVariant
*instance
*
* Since: 2.24
**/
/**
* g_variant_get_uint16:
* @value: a uint16 #GVariant instance
*
* Returns the 16-bit unsigned integer value of @value.
*
* It is an error to call this function with a @value of any type
* other than %G_VARIANT_TYPE_UINT16.
*
* Returns: a #guint16
*
* Since: 2.24
**/
NUMERIC_TYPE(UINT16, uint16, guint16)
/**
* g_variant_new_int32:
* @value: a #gint32 value
*
* Creates a new int32 #GVariant instance.
*
* Returns: (transfer none): a floating reference to a new int32 #GVariant
*instance
*
* Since: 2.24
**/
/**
* g_variant_get_int32:
* @value: a int32 #GVariant instance
*
* Returns the 32-bit signed integer value of @value.
*
* It is an error to call this function with a @value of any type
* other than %G_VARIANT_TYPE_INT32.
*
* Returns: a #gint32
*
* Since: 2.24
**/
NUMERIC_TYPE(INT32, int32, gint32)
/**
* g_variant_new_uint32:
* @value: a #guint32 value
*
* Creates a new uint32 #GVariant instance.
*
* Returns: (transfer none): a floating reference to a new uint32 #GVariant
*instance
*
* Since: 2.24
**/
/**
* g_variant_get_uint32:
* @value: a uint32 #GVariant instance
*
* Returns the 32-bit unsigned integer value of @value.
*
* It is an error to call this function with a @value of any type
* other than %G_VARIANT_TYPE_UINT32.
*
* Returns: a #guint32
*
* Since: 2.24
**/
NUMERIC_TYPE(UINT32, uint32, guint32)
/**
* g_variant_new_int64:
* @value: a #gint64 value
*
* Creates a new int64 #GVariant instance.
*
* Returns: (transfer none): a floating reference to a new int64 #GVariant
*instance
*
* Since: 2.24
**/
/**
* g_variant_get_int64:
* @value: a int64 #GVariant instance
*
* Returns the 64-bit signed integer value of @value.
*
* It is an error to call this function with a @value of any type
* other than %G_VARIANT_TYPE_INT64.
*
* Returns: a #gint64
*
* Since: 2.24
**/
NUMERIC_TYPE(INT64, int64, gint64)
/**
* g_variant_new_uint64:
* @value: a #guint64 value
*
* Creates a new uint64 #GVariant instance.
*
* Returns: (transfer none): a floating reference to a new uint64 #GVariant
*instance
*
* Since: 2.24
**/
/**
* g_variant_get_uint64:
* @value: a uint64 #GVariant instance
*
* Returns the 64-bit unsigned integer value of @value.
*
* It is an error to call this function with a @value of any type
* other than %G_VARIANT_TYPE_UINT64.
*
* Returns: a #guint64
*
* Since: 2.24
**/
NUMERIC_TYPE(UINT64, uint64, guint64)
/**
* g_variant_new_handle:
* @value: a #gint32 value
*
* Creates a new handle #GVariant instance.
*
* By convention, handles are indexes into an array of file descriptors
* that are sent alongside a D-Bus message. If you're not interacting
* with D-Bus, you probably don't need them.
*
* Returns: (transfer none): a floating reference to a new handle #GVariant
*instance
*
* Since: 2.24
**/
/**
* g_variant_get_handle:
* @value: a handle #GVariant instance
*
* Returns the 32-bit signed integer value of @value.
*
* It is an error to call this function with a @value of any type other
* than %G_VARIANT_TYPE_HANDLE.
*
* By convention, handles are indexes into an array of file descriptors
* that are sent alongside a D-Bus message. If you're not interacting
* with D-Bus, you probably don't need them.
*
* Returns: a #gint32
*
* Since: 2.24
**/
NUMERIC_TYPE(HANDLE, handle, gint32)
/**
* g_variant_new_double:
* @value: a #gdouble floating point value
*
* Creates a new double #GVariant instance.
*
* Returns: (transfer none): a floating reference to a new double #GVariant
*instance
*
* Since: 2.24
**/
/**
* g_variant_get_double:
* @value: a double #GVariant instance
*
* Returns the double precision floating point value of @value.
*
* It is an error to call this function with a @value of any type
* other than %G_VARIANT_TYPE_DOUBLE.
*
* Returns: a #gdouble
*
* Since: 2.24
**/
NUMERIC_TYPE(DOUBLE, double, gdouble)
/* Container type Constructor / Deconstructors {{{1 */
/**
* g_variant_new_maybe:
* @child_type: (nullable): the #GVariantType of the child, or %NULL
* @child: (nullable): the child value, or %NULL
*
* Depending on if @child is %NULL, either wraps @child inside of a
* maybe container or creates a Nothing instance for the given @type.
*
* At least one of @child_type and @child must be non-%NULL.
* If @child_type is non-%NULL then it must be a definite type.
* If they are both non-%NULL then @child_type must be the type
* of @child.
*
* If @child is a floating reference (see g_variant_ref_sink()), the new
* instance takes ownership of @child.
*
* Returns: (transfer none): a floating reference to a new #GVariant maybe
*instance
*
* Since: 2.24
**/
GVariant* g_variant_new_maybe(const GVariantType* child_type, GVariant* child)
{
GVariantType* maybe_type;
GVariant* value;
g_return_val_if_fail(
child_type == NULL || g_variant_type_is_definite(child_type), 0);
g_return_val_if_fail(child_type != NULL || child != NULL, NULL);
g_return_val_if_fail(child_type == NULL || child == NULL ||
g_variant_is_of_type(child, child_type),
NULL);
if (child_type == NULL)
child_type = g_variant_get_type(child);
maybe_type = g_variant_type_new_maybe(child_type);
if (child != NULL)
{
GVariant** children;
gboolean trusted;
children = g_new(GVariant*, 1);
children[0] = g_variant_ref_sink(child);
trusted = g_variant_is_trusted(children[0]);
value = g_variant_new_from_children(maybe_type, children, 1, trusted);
}
else
value = g_variant_new_from_children(maybe_type, NULL, 0, TRUE);
g_variant_type_free(maybe_type);
return value;
}
/**
* g_variant_get_maybe:
* @value: a maybe-typed value
*
* Given a maybe-typed #GVariant instance, extract its value. If the
* value is Nothing, then this function returns %NULL.
*
* Returns: (nullable) (transfer full): the contents of @value, or %NULL
*
* Since: 2.24
**/
GVariant* g_variant_get_maybe(GVariant* value)
{
TYPE_CHECK(value, G_VARIANT_TYPE_MAYBE, NULL);
if (g_variant_n_children(value))
return g_variant_get_child_value(value, 0);
return NULL;
}
/**
* g_variant_new_variant: (constructor)
* @value: a #GVariant instance
*
* Boxes @value. The result is a #GVariant instance representing a
* variant containing the original value.
*
* If @child is a floating reference (see g_variant_ref_sink()), the new
* instance takes ownership of @child.
*
* Returns: (transfer none): a floating reference to a new variant #GVariant
*instance
*
* Since: 2.24
**/
GVariant* g_variant_new_variant(GVariant* value)
{
g_return_val_if_fail(value != NULL, NULL);
g_variant_ref_sink(value);
return g_variant_new_from_children(G_VARIANT_TYPE_VARIANT,
g_memdup(&value, sizeof value), 1,
g_variant_is_trusted(value));
}
/**
* g_variant_get_variant:
* @value: a variant #GVariant instance
*
* Unboxes @value. The result is the #GVariant instance that was
* contained in @value.
*
* Returns: (transfer full): the item contained in the variant
*
* Since: 2.24
**/
GVariant* g_variant_get_variant(GVariant* value)
{
TYPE_CHECK(value, G_VARIANT_TYPE_VARIANT, NULL);
return g_variant_get_child_value(value, 0);
}
/**
* g_variant_new_array:
* @child_type: (nullable): the element type of the new array
* @children: (nullable) (array length=n_children): an array of
* #GVariant pointers, the children
* @n_children: the length of @children
*
* Creates a new #GVariant array from @children.
*
* @child_type must be non-%NULL if @n_children is zero. Otherwise, the
* child type is determined by inspecting the first element of the
* @children array. If @child_type is non-%NULL then it must be a
* definite type.
*
* The items of the array are taken from the @children array. No entry
* in the @children array may be %NULL.
*
* All items in the array must have the same type, which must be the
* same as @child_type, if given.
*
* If the @children are floating references (see g_variant_ref_sink()), the
* new instance takes ownership of them as if via g_variant_ref_sink().
*
* Returns: (transfer none): a floating reference to a new #GVariant array
*
* Since: 2.24
**/
GVariant* g_variant_new_array(const GVariantType* child_type,
GVariant* const* children, gsize n_children)
{
GVariantType* array_type;
GVariant** my_children;
gboolean trusted;
GVariant* value;
gsize i;
g_return_val_if_fail(n_children > 0 || child_type != NULL, NULL);
g_return_val_if_fail(n_children == 0 || children != NULL, NULL);
g_return_val_if_fail(
child_type == NULL || g_variant_type_is_definite(child_type), NULL);
my_children = g_new(GVariant*, n_children);
trusted = TRUE;
if (child_type == NULL)
child_type = g_variant_get_type(children[0]);
array_type = g_variant_type_new_array(child_type);
for (i = 0; i < n_children; i++)
{
TYPE_CHECK(children[i], child_type, NULL);
my_children[i] = g_variant_ref_sink(children[i]);
trusted &= g_variant_is_trusted(children[i]);
}
value = g_variant_new_from_children(array_type, my_children, n_children,
trusted);
g_variant_type_free(array_type);
return value;
}
/*< private >
* g_variant_make_tuple_type:
* @children: (array length=n_children): an array of GVariant *
* @n_children: the length of @children
*
* Return the type of a tuple containing @children as its items.
**/
static GVariantType* g_variant_make_tuple_type(GVariant* const* children,
gsize n_children)
{
const GVariantType** types;
GVariantType* type;
gsize i;
types = g_new(const GVariantType*, n_children);
for (i = 0; i < n_children; i++)
types[i] = g_variant_get_type(children[i]);
type = g_variant_type_new_tuple(types, n_children);
g_free(types);
return type;
}
/**
* g_variant_new_tuple:
* @children: (array length=n_children): the items to make the tuple out of
* @n_children: the length of @children
*
* Creates a new tuple #GVariant out of the items in @children. The
* type is determined from the types of @children. No entry in the
* @children array may be %NULL.
*
* If @n_children is 0 then the unit tuple is constructed.
*
* If the @children are floating references (see g_variant_ref_sink()), the
* new instance takes ownership of them as if via g_variant_ref_sink().
*
* Returns: (transfer none): a floating reference to a new #GVariant tuple
*
* Since: 2.24
**/
GVariant* g_variant_new_tuple(GVariant* const* children, gsize n_children)
{
GVariantType* tuple_type;
GVariant** my_children;
gboolean trusted;
GVariant* value;
gsize i;
g_return_val_if_fail(n_children == 0 || children != NULL, NULL);
my_children = g_new(GVariant*, n_children);
trusted = TRUE;
for (i = 0; i < n_children; i++)
{
my_children[i] = g_variant_ref_sink(children[i]);
trusted &= g_variant_is_trusted(children[i]);
}
tuple_type = g_variant_make_tuple_type(children, n_children);
value = g_variant_new_from_children(tuple_type, my_children, n_children,
trusted);
g_variant_type_free(tuple_type);
return value;
}
/*< private >
* g_variant_make_dict_entry_type:
* @key: a #GVariant, the key
* @val: a #GVariant, the value
*
* Return the type of a dictionary entry containing @key and @val as its
* children.
**/
static GVariantType* g_variant_make_dict_entry_type(GVariant* key,
GVariant* val)
{
return g_variant_type_new_dict_entry(g_variant_get_type(key),
g_variant_get_type(val));
}
/**
* g_variant_new_dict_entry: (constructor)
* @key: a basic #GVariant, the key
* @value: a #GVariant, the value
*
* Creates a new dictionary entry #GVariant. @key and @value must be
* non-%NULL. @key must be a value of a basic type (ie: not a container).
*
* If the @key or @value are floating references (see g_variant_ref_sink()),
* the new instance takes ownership of them as if via g_variant_ref_sink().
*
* Returns: (transfer none): a floating reference to a new dictionary entry
*#GVariant
*
* Since: 2.24
**/
GVariant* g_variant_new_dict_entry(GVariant* key, GVariant* value)
{
GVariantType* dict_type;
GVariant** children;
gboolean trusted;
g_return_val_if_fail(key != NULL && value != NULL, NULL);
g_return_val_if_fail(!g_variant_is_container(key), NULL);
children = g_new(GVariant*, 2);
children[0] = g_variant_ref_sink(key);
children[1] = g_variant_ref_sink(value);
trusted = g_variant_is_trusted(key) && g_variant_is_trusted(value);
dict_type = g_variant_make_dict_entry_type(key, value);
value = g_variant_new_from_children(dict_type, children, 2, trusted);
g_variant_type_free(dict_type);
return value;
}
/**
* g_variant_lookup: (skip)
* @dictionary: a dictionary #GVariant
* @key: the key to lookup in the dictionary
* @format_string: a GVariant format string
* @...: the arguments to unpack the value into
*
* Looks up a value in a dictionary #GVariant.
*
* This function is a wrapper around g_variant_lookup_value() and
* g_variant_get(). In the case that %NULL would have been returned,
* this function returns %FALSE. Otherwise, it unpacks the returned
* value and returns %TRUE.
*
* @format_string determines the C types that are used for unpacking
* the values and also determines if the values are copied or borrowed,
* see the section on
* [GVariant format strings][gvariant-format-strings-pointers].
*
* This function is currently implemented with a linear scan. If you
* plan to do many lookups then #GVariantDict may be more efficient.
*
* Returns: %TRUE if a value was unpacked
*
* Since: 2.28
*/
gboolean g_variant_lookup(GVariant* dictionary, const gchar* key,
const gchar* format_string, ...)
{
GVariantType* type;
GVariant* value;
/* flatten */
g_variant_get_data(dictionary);
type = g_variant_format_string_scan_type(format_string, NULL, NULL);
value = g_variant_lookup_value(dictionary, key, type);
g_variant_type_free(type);
if (value)
{
va_list ap;
va_start(ap, format_string);
g_variant_get_va(value, format_string, NULL, &ap);
g_variant_unref(value);
va_end(ap);
return TRUE;
}
else
return FALSE;
}
/**
* g_variant_lookup_value:
* @dictionary: a dictionary #GVariant
* @key: the key to lookup in the dictionary
* @expected_type: (nullable): a #GVariantType, or %NULL
*
* Looks up a value in a dictionary #GVariant.
*
* This function works with dictionaries of the type a{s*} (and equally
* well with type a{o*}, but we only further discuss the string case
* for sake of clarity).
*
* In the event that @dictionary has the type a{sv}, the @expected_type
* string specifies what type of value is expected to be inside of the
* variant. If the value inside the variant has a different type then
* %NULL is returned. In the event that @dictionary has a value type other
* than v then @expected_type must directly match the value type and it is
* used to unpack the value directly or an error occurs.
*
* In either case, if @key is not found in @dictionary, %NULL is returned.
*
* If the key is found and the value has the correct type, it is
* returned. If @expected_type was specified then any non-%NULL return
* value will have this type.
*
* This function is currently implemented with a linear scan. If you
* plan to do many lookups then #GVariantDict may be more efficient.
*
* Returns: (transfer full): the value of the dictionary key, or %NULL
*
* Since: 2.28
*/
GVariant* g_variant_lookup_value(GVariant* dictionary, const gchar* key,
const GVariantType* expected_type)
{
GVariantIter iter;
GVariant* entry;
GVariant* value;
g_return_val_if_fail(
g_variant_is_of_type(dictionary, G_VARIANT_TYPE("a{s*}")) ||
g_variant_is_of_type(dictionary, G_VARIANT_TYPE("a{o*}")),
NULL);
g_variant_iter_init(&iter, dictionary);
while ((entry = g_variant_iter_next_value(&iter)))
{
GVariant* entry_key;
gboolean matches;
entry_key = g_variant_get_child_value(entry, 0);
matches = strcmp(g_variant_get_string(entry_key, NULL), key) == 0;
g_variant_unref(entry_key);
if (matches)
break;
g_variant_unref(entry);
}
if (entry == NULL)
return NULL;
value = g_variant_get_child_value(entry, 1);
g_variant_unref(entry);
if (g_variant_is_of_type(value, G_VARIANT_TYPE_VARIANT))
{
GVariant* tmp;
tmp = g_variant_get_variant(value);
g_variant_unref(value);
if (expected_type && !g_variant_is_of_type(tmp, expected_type))
{
g_variant_unref(tmp);
tmp = NULL;
}
value = tmp;
}
g_return_val_if_fail(expected_type == NULL || value == NULL ||
g_variant_is_of_type(value, expected_type),
NULL);
return value;
}
/**
* g_variant_get_fixed_array:
* @value: a #GVariant array with fixed-sized elements
* @n_elements: (out): a pointer to the location to store the number of items
* @element_size: the size of each element
*
* Provides access to the serialised data for an array of fixed-sized
* items.
*
* @value must be an array with fixed-sized elements. Numeric types are
* fixed-size, as are tuples containing only other fixed-sized types.
*
* @element_size must be the size of a single element in the array,
* as given by the section on
* [serialized data memory][gvariant-serialised-data-memory].
*
* In particular, arrays of these fixed-sized types can be interpreted
* as an array of the given C type, with @element_size set to the size
* the appropriate type:
* - %G_VARIANT_TYPE_INT16 (etc.): #gint16 (etc.)
* - %G_VARIANT_TYPE_BOOLEAN: #guchar (not #gboolean!)
* - %G_VARIANT_TYPE_BYTE: #guint8
* - %G_VARIANT_TYPE_HANDLE: #guint32
* - %G_VARIANT_TYPE_DOUBLE: #gdouble
*
* For example, if calling this function for an array of 32-bit integers,
* you might say `sizeof(gint32)`. This value isn't used except for the purpose
* of a double-check that the form of the serialised data matches the caller's
* expectation.
*
* @n_elements, which must be non-%NULL, is set equal to the number of
* items in the array.
*
* Returns: (array length=n_elements) (transfer none): a pointer to
* the fixed array
*
* Since: 2.24
**/
gconstpointer g_variant_get_fixed_array(GVariant* value, gsize* n_elements,
gsize element_size)
{
GVariantTypeInfo* array_info;
gsize array_element_size;
gconstpointer data;
gsize size;
TYPE_CHECK(value, G_VARIANT_TYPE_ARRAY, NULL);
g_return_val_if_fail(n_elements != NULL, NULL);
g_return_val_if_fail(element_size > 0, NULL);
array_info = g_variant_get_type_info(value);
g_variant_type_info_query_element(array_info, NULL, &array_element_size);
g_return_val_if_fail(array_element_size, NULL);
if
G_UNLIKELY(array_element_size != element_size)
{
if (array_element_size)
g_critical(
"g_variant_get_fixed_array: assertion "
"'g_variant_array_has_fixed_size (value, element_size)' "
"failed: array size %" G_GSIZE_FORMAT " does not match "
"given element_size %" G_GSIZE_FORMAT ".",
array_element_size, element_size);
else
g_critical(
"g_variant_get_fixed_array: assertion "
"'g_variant_array_has_fixed_size (value, element_size)' "
"failed: array does not have fixed size.");
}
data = g_variant_get_data(value);
size = g_variant_get_size(value);
if (size % element_size)
*n_elements = 0;
else
*n_elements = size / element_size;
if (*n_elements)
return data;
return NULL;
}
/**
* g_variant_new_fixed_array:
* @element_type: the #GVariantType of each element
* @elements: a pointer to the fixed array of contiguous elements
* @n_elements: the number of elements
* @element_size: the size of each element
*
* Constructs a new array #GVariant instance, where the elements are
* of @element_type type.
*
* @elements must be an array with fixed-sized elements. Numeric types are
* fixed-size as are tuples containing only other fixed-sized types.
*
* @element_size must be the size of a single element in the array.
* For example, if calling this function for an array of 32-bit integers,
* you might say sizeof(gint32). This value isn't used except for the purpose
* of a double-check that the form of the serialised data matches the caller's
* expectation.
*
* @n_elements must be the length of the @elements array.
*
* Returns: (transfer none): a floating reference to a new array #GVariant
*instance
*
* Since: 2.32
**/
GVariant* g_variant_new_fixed_array(const GVariantType* element_type,
gconstpointer elements, gsize n_elements,
gsize element_size)
{
GVariantType* array_type;
gsize array_element_size;
GVariantTypeInfo* array_info;
GVariant* value;
gpointer data;
g_return_val_if_fail(g_variant_type_is_definite(element_type), NULL);
g_return_val_if_fail(element_size > 0, NULL);
array_type = g_variant_type_new_array(element_type);
array_info = g_variant_type_info_get(array_type);
g_variant_type_info_query_element(array_info, NULL, &array_element_size);
if
G_UNLIKELY(array_element_size != element_size)
{
if (array_element_size)
g_critical(
"g_variant_new_fixed_array: array size %" G_GSIZE_FORMAT
" does not match given element_size %" G_GSIZE_FORMAT ".",
array_element_size, element_size);
else
g_critical("g_variant_get_fixed_array: array does not have "
"fixed size.");
return NULL;
}
data = g_memdup(elements, n_elements * element_size);
value = g_variant_new_from_data(array_type, data, n_elements * element_size,
FALSE, g_free, data);
g_variant_type_free(array_type);
g_variant_type_info_unref(array_info);
return value;
}
/* String type constructor/getters/validation {{{1 */
/**
* g_variant_new_string:
* @string: a normal UTF-8 nul-terminated string
*
* Creates a string #GVariant with the contents of @string.
*
* @string must be valid UTF-8, and must not be %NULL. To encode
* potentially-%NULL strings, use g_variant_new() with `ms` as the
* [format string][gvariant-format-strings-maybe-types].
*
* Returns: (transfer none): a floating reference to a new string #GVariant
*instance
*
* Since: 2.24
**/
GVariant* g_variant_new_string(const gchar* string)
{
g_return_val_if_fail(string != NULL, NULL);
g_return_val_if_fail(g_utf8_validate(string, -1, NULL), NULL);
return g_variant_new_from_trusted(G_VARIANT_TYPE_STRING, string,
strlen(string) + 1);
}
/**
* g_variant_new_take_string: (skip)
* @string: a normal UTF-8 nul-terminated string
*
* Creates a string #GVariant with the contents of @string.
*
* @string must be valid UTF-8, and must not be %NULL. To encode
* potentially-%NULL strings, use this with g_variant_new_maybe().
*
* This function consumes @string. g_free() will be called on @string
* when it is no longer required.
*
* You must not modify or access @string in any other way after passing
* it to this function. It is even possible that @string is immediately
* freed.
*
* Returns: (transfer none): a floating reference to a new string
* #GVariant instance
*
* Since: 2.38
**/
GVariant* g_variant_new_take_string(gchar* string)
{
GVariant* value;
GBytes* bytes;
g_return_val_if_fail(string != NULL, NULL);
g_return_val_if_fail(g_utf8_validate(string, -1, NULL), NULL);
bytes = g_bytes_new_take(string, strlen(string) + 1);
value = g_variant_new_from_bytes(G_VARIANT_TYPE_STRING, bytes, TRUE);
g_bytes_unref(bytes);
return value;
}
/**
* g_variant_new_printf: (skip)
* @format_string: a printf-style format string
* @...: arguments for @format_string
*
* Creates a string-type GVariant using printf formatting.
*
* This is similar to calling g_strdup_printf() and then
* g_variant_new_string() but it saves a temporary variable and an
* unnecessary copy.
*
* Returns: (transfer none): a floating reference to a new string
* #GVariant instance
*
* Since: 2.38
**/
GVariant* g_variant_new_printf(const gchar* format_string, ...)
{
GVariant* value;
GBytes* bytes;
gchar* string;
va_list ap;
g_return_val_if_fail(format_string != NULL, NULL);
va_start(ap, format_string);
string = g_strdup_vprintf(format_string, ap);
va_end(ap);
bytes = g_bytes_new_take(string, strlen(string) + 1);
value = g_variant_new_from_bytes(G_VARIANT_TYPE_STRING, bytes, TRUE);
g_bytes_unref(bytes);
return value;
}
/**
* g_variant_new_object_path:
* @object_path: a normal C nul-terminated string
*
* Creates a D-Bus object path #GVariant with the contents of @string.
* @string must be a valid D-Bus object path. Use
* g_variant_is_object_path() if you're not sure.
*
* Returns: (transfer none): a floating reference to a new object path #GVariant
*instance
*
* Since: 2.24
**/
GVariant* g_variant_new_object_path(const gchar* object_path)
{
g_return_val_if_fail(g_variant_is_object_path(object_path), NULL);
return g_variant_new_from_trusted(G_VARIANT_TYPE_OBJECT_PATH, object_path,
strlen(object_path) + 1);
}
/**
* g_variant_is_object_path:
* @string: a normal C nul-terminated string
*
* Determines if a given string is a valid D-Bus object path. You
* should ensure that a string is a valid D-Bus object path before
* passing it to g_variant_new_object_path().
*
* A valid object path starts with `/` followed by zero or more
* sequences of characters separated by `/` characters. Each sequence
* must contain only the characters `[A-Z][a-z][0-9]_`. No sequence
* (including the one following the final `/` character) may be empty.
*
* Returns: %TRUE if @string is a D-Bus object path
*
* Since: 2.24
**/
gboolean g_variant_is_object_path(const gchar* string)
{
g_return_val_if_fail(string != NULL, FALSE);
return g_variant_serialiser_is_object_path(string, strlen(string) + 1);
}
/**
* g_variant_new_signature:
* @signature: a normal C nul-terminated string
*
* Creates a D-Bus type signature #GVariant with the contents of
* @string. @string must be a valid D-Bus type signature. Use
* g_variant_is_signature() if you're not sure.
*
* Returns: (transfer none): a floating reference to a new signature #GVariant
*instance
*
* Since: 2.24
**/
GVariant* g_variant_new_signature(const gchar* signature)
{
g_return_val_if_fail(g_variant_is_signature(signature), NULL);
return g_variant_new_from_trusted(G_VARIANT_TYPE_SIGNATURE, signature,
strlen(signature) + 1);
}
/**
* g_variant_is_signature:
* @string: a normal C nul-terminated string
*
* Determines if a given string is a valid D-Bus type signature. You
* should ensure that a string is a valid D-Bus type signature before
* passing it to g_variant_new_signature().
*
* D-Bus type signatures consist of zero or more definite #GVariantType
* strings in sequence.
*
* Returns: %TRUE if @string is a D-Bus type signature
*
* Since: 2.24
**/
gboolean g_variant_is_signature(const gchar* string)
{
g_return_val_if_fail(string != NULL, FALSE);
return g_variant_serialiser_is_signature(string, strlen(string) + 1);
}
/**
* g_variant_get_string:
* @value: a string #GVariant instance
* @length: (optional) (default 0) (out): a pointer to a #gsize,
* to store the length
*
* Returns the string value of a #GVariant instance with a string
* type. This includes the types %G_VARIANT_TYPE_STRING,
* %G_VARIANT_TYPE_OBJECT_PATH and %G_VARIANT_TYPE_SIGNATURE.
*
* The string will always be UTF-8 encoded, and will never be %NULL.
*
* If @length is non-%NULL then the length of the string (in bytes) is
* returned there. For trusted values, this information is already
* known. For untrusted values, a strlen() will be performed.
*
* It is an error to call this function with a @value of any type
* other than those three.
*
* The return value remains valid as long as @value exists.
*
* Returns: (transfer none): the constant string, UTF-8 encoded
*
* Since: 2.24
**/
const gchar* g_variant_get_string(GVariant* value, gsize* length)
{
gconstpointer data;
gsize size;
g_return_val_if_fail(value != NULL, NULL);
g_return_val_if_fail(
g_variant_is_of_type(value, G_VARIANT_TYPE_STRING) ||
g_variant_is_of_type(value, G_VARIANT_TYPE_OBJECT_PATH) ||
g_variant_is_of_type(value, G_VARIANT_TYPE_SIGNATURE),
NULL);
data = g_variant_get_data(value);
size = g_variant_get_size(value);
if (!g_variant_is_trusted(value))
{
switch (g_variant_classify(value))
{
case G_VARIANT_CLASS_STRING:
if (g_variant_serialiser_is_string(data, size))
break;
data = "";
size = 1;
break;
case G_VARIANT_CLASS_OBJECT_PATH:
if (g_variant_serialiser_is_object_path(data, size))
break;
data = "/";
size = 2;
break;
case G_VARIANT_CLASS_SIGNATURE:
if (g_variant_serialiser_is_signature(data, size))
break;
data = "";
size = 1;
break;
default:
g_assert_not_reached();
}
}
if (length)
*length = size - 1;
return data;
}
/**
* g_variant_dup_string:
* @value: a string #GVariant instance
* @length: (out): a pointer to a #gsize, to store the length
*
* Similar to g_variant_get_string() except that instead of returning
* a constant string, the string is duplicated.
*
* The string will always be UTF-8 encoded.
*
* The return value must be freed using g_free().
*
* Returns: (transfer full): a newly allocated string, UTF-8 encoded
*
* Since: 2.24
**/
gchar* g_variant_dup_string(GVariant* value, gsize* length)
{
return g_strdup(g_variant_get_string(value, length));
}
/**
* g_variant_new_strv:
* @strv: (array length=length) (element-type utf8): an array of strings
* @length: the length of @strv, or -1
*
* Constructs an array of strings #GVariant from the given array of
* strings.
*
* If @length is -1 then @strv is %NULL-terminated.
*
* Returns: (transfer none): a new floating #GVariant instance
*
* Since: 2.24
**/
GVariant* g_variant_new_strv(const gchar* const* strv, gssize length)
{
GVariant** strings;
gsize i;
g_return_val_if_fail(length == 0 || strv != NULL, NULL);
if (length < 0)
length = g_strv_length((gchar**)strv);
strings = g_new(GVariant*, length);
for (i = 0; i < length; i++)
strings[i] = g_variant_ref_sink(g_variant_new_string(strv[i]));
return g_variant_new_from_children(G_VARIANT_TYPE_STRING_ARRAY, strings,
length, TRUE);
}
/**
* g_variant_get_strv:
* @value: an array of strings #GVariant
* @length: (out) (optional): the length of the result, or %NULL
*
* Gets the contents of an array of strings #GVariant. This call
* makes a shallow copy; the return result should be released with
* g_free(), but the individual strings must not be modified.
*
* If @length is non-%NULL then the number of elements in the result
* is stored there. In any case, the resulting array will be
* %NULL-terminated.
*
* For an empty array, @length will be set to 0 and a pointer to a
* %NULL pointer will be returned.
*
* Returns: (array length=length zero-terminated=1) (transfer container): an
*array of constant strings
*
* Since: 2.24
**/
const gchar** g_variant_get_strv(GVariant* value, gsize* length)
{
const gchar** strv;
gsize n;
gsize i;
TYPE_CHECK(value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
g_variant_get_data(value);
n = g_variant_n_children(value);
strv = g_new(const gchar*, n + 1);
for (i = 0; i < n; i++)
{
GVariant* string;
string = g_variant_get_child_value(value, i);
strv[i] = g_variant_get_string(string, NULL);
g_variant_unref(string);
}
strv[i] = NULL;
if (length)
*length = n;
return strv;
}
/**
* g_variant_dup_strv:
* @value: an array of strings #GVariant
* @length: (out) (optional): the length of the result, or %NULL
*
* Gets the contents of an array of strings #GVariant. This call
* makes a deep copy; the return result should be released with
* g_strfreev().
*
* If @length is non-%NULL then the number of elements in the result
* is stored there. In any case, the resulting array will be
* %NULL-terminated.
*
* For an empty array, @length will be set to 0 and a pointer to a
* %NULL pointer will be returned.
*
* Returns: (array length=length zero-terminated=1) (transfer full): an array of
*strings
*
* Since: 2.24
**/
gchar** g_variant_dup_strv(GVariant* value, gsize* length)
{
gchar** strv;
gsize n;
gsize i;
TYPE_CHECK(value, G_VARIANT_TYPE_STRING_ARRAY, NULL);
n = g_variant_n_children(value);
strv = g_new(gchar*, n + 1);
for (i = 0; i < n; i++)
{
GVariant* string;
string = g_variant_get_child_value(value, i);
strv[i] = g_variant_dup_string(string, NULL);
g_variant_unref(string);
}
strv[i] = NULL;
if (length)
*length = n;
return strv;
}
/**
* g_variant_new_objv:
* @strv: (array length=length) (element-type utf8): an array of strings
* @length: the length of @strv, or -1
*
* Constructs an array of object paths #GVariant from the given array of
* strings.
*
* Each string must be a valid #GVariant object path; see
* g_variant_is_object_path().
*
* If @length is -1 then @strv is %NULL-terminated.
*
* Returns: (transfer none): a new floating #GVariant instance
*
* Since: 2.30
**/
GVariant* g_variant_new_objv(const gchar* const* strv, gssize length)
{
GVariant** strings;
gsize i;
g_return_val_if_fail(length == 0 || strv != NULL, NULL);
if (length < 0)
length = g_strv_length((gchar**)strv);
strings = g_new(GVariant*, length);
for (i = 0; i < length; i++)
strings[i] = g_variant_ref_sink(g_variant_new_object_path(strv[i]));
return g_variant_new_from_children(G_VARIANT_TYPE_OBJECT_PATH_ARRAY,
strings, length, TRUE);
}
/**
* g_variant_get_objv:
* @value: an array of object paths #GVariant
* @length: (out) (optional): the length of the result, or %NULL
*
* Gets the contents of an array of object paths #GVariant. This call
* makes a shallow copy; the return result should be released with
* g_free(), but the individual strings must not be modified.
*
* If @length is non-%NULL then the number of elements in the result
* is stored there. In any case, the resulting array will be
* %NULL-terminated.
*
* For an empty array, @length will be set to 0 and a pointer to a
* %NULL pointer will be returned.
*
* Returns: (array length=length zero-terminated=1) (transfer container): an
*array of constant strings
*
* Since: 2.30
**/
const gchar** g_variant_get_objv(GVariant* value, gsize* length)
{
const gchar** strv;
gsize n;
gsize i;
TYPE_CHECK(value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
g_variant_get_data(value);
n = g_variant_n_children(value);
strv = g_new(const gchar*, n + 1);
for (i = 0; i < n; i++)
{
GVariant* string;
string = g_variant_get_child_value(value, i);
strv[i] = g_variant_get_string(string, NULL);
g_variant_unref(string);
}
strv[i] = NULL;
if (length)
*length = n;
return strv;
}
/**
* g_variant_dup_objv:
* @value: an array of object paths #GVariant
* @length: (out) (optional): the length of the result, or %NULL
*
* Gets the contents of an array of object paths #GVariant. This call
* makes a deep copy; the return result should be released with
* g_strfreev().
*
* If @length is non-%NULL then the number of elements in the result
* is stored there. In any case, the resulting array will be
* %NULL-terminated.
*
* For an empty array, @length will be set to 0 and a pointer to a
* %NULL pointer will be returned.
*
* Returns: (array length=length zero-terminated=1) (transfer full): an array of
*strings
*
* Since: 2.30
**/
gchar** g_variant_dup_objv(GVariant* value, gsize* length)
{
gchar** strv;
gsize n;
gsize i;
TYPE_CHECK(value, G_VARIANT_TYPE_OBJECT_PATH_ARRAY, NULL);
n = g_variant_n_children(value);
strv = g_new(gchar*, n + 1);
for (i = 0; i < n; i++)
{
GVariant* string;
string = g_variant_get_child_value(value, i);
strv[i] = g_variant_dup_string(string, NULL);
g_variant_unref(string);
}
strv[i] = NULL;
if (length)
*length = n;
return strv;
}
/**
* g_variant_new_bytestring:
* @string: (array zero-terminated=1) (element-type guint8): a normal
* nul-terminated string in no particular encoding
*
* Creates an array-of-bytes #GVariant with the contents of @string.
* This function is just like g_variant_new_string() except that the
* string need not be valid UTF-8.
*
* The nul terminator character at the end of the string is stored in
* the array.
*
* Returns: (transfer none): a floating reference to a new bytestring #GVariant
*instance
*
* Since: 2.26
**/
GVariant* g_variant_new_bytestring(const gchar* string)
{
g_return_val_if_fail(string != NULL, NULL);
return g_variant_new_from_trusted(G_VARIANT_TYPE_BYTESTRING, string,
strlen(string) + 1);
}
/**
* g_variant_get_bytestring:
* @value: an array-of-bytes #GVariant instance
*
* Returns the string value of a #GVariant instance with an
* array-of-bytes type. The string has no particular encoding.
*
* If the array does not end with a nul terminator character, the empty
* string is returned. For this reason, you can always trust that a
* non-%NULL nul-terminated string will be returned by this function.
*
* If the array contains a nul terminator character somewhere other than
* the last byte then the returned string is the string, up to the first
* such nul character.
*
* g_variant_get_fixed_array() should be used instead if the array contains
* arbitrary data that could not be nul-terminated or could contain nul bytes.
*
* It is an error to call this function with a @value that is not an
* array of bytes.
*
* The return value remains valid as long as @value exists.
*
* Returns: (transfer none) (array zero-terminated=1) (element-type guint8):
* the constant string
*
* Since: 2.26
**/
const gchar* g_variant_get_bytestring(GVariant* value)
{
const gchar* string;
gsize size;
TYPE_CHECK(value, G_VARIANT_TYPE_BYTESTRING, NULL);
/* Won't be NULL since this is an array type */
string = g_variant_get_data(value);
size = g_variant_get_size(value);
if (size && string[size - 1] == '\0')
return string;
else
return "";
}
/**
* g_variant_dup_bytestring:
* @value: an array-of-bytes #GVariant instance
* @length: (out) (optional) (default NULL): a pointer to a #gsize, to store
* the length (not including the nul terminator)
*
* Similar to g_variant_get_bytestring() except that instead of
* returning a constant string, the string is duplicated.
*
* The return value must be freed using g_free().
*
* Returns: (transfer full) (array zero-terminated=1 length=length)
*(element-type guint8): a newly allocated string
*
* Since: 2.26
**/
gchar* g_variant_dup_bytestring(GVariant* value, gsize* length)
{
const gchar* original = g_variant_get_bytestring(value);
gsize size;
/* don't crash in case get_bytestring() had an assert failure */
if (original == NULL)
return NULL;
size = strlen(original);
if (length)
*length = size;
return g_memdup(original, size + 1);
}
/**
* g_variant_new_bytestring_array:
* @strv: (array length=length): an array of strings
* @length: the length of @strv, or -1
*
* Constructs an array of bytestring #GVariant from the given array of
* strings.
*
* If @length is -1 then @strv is %NULL-terminated.
*
* Returns: (transfer none): a new floating #GVariant instance
*
* Since: 2.26
**/
GVariant* g_variant_new_bytestring_array(const gchar* const* strv,
gssize length)
{
GVariant** strings;
gsize i;
g_return_val_if_fail(length == 0 || strv != NULL, NULL);
if (length < 0)
length = g_strv_length((gchar**)strv);
strings = g_new(GVariant*, length);
for (i = 0; i < length; i++)
strings[i] = g_variant_ref_sink(g_variant_new_bytestring(strv[i]));
return g_variant_new_from_children(G_VARIANT_TYPE_BYTESTRING_ARRAY, strings,
length, TRUE);
}
/**
* g_variant_get_bytestring_array:
* @value: an array of array of bytes #GVariant ('aay')
* @length: (out) (optional): the length of the result, or %NULL
*
* Gets the contents of an array of array of bytes #GVariant. This call
* makes a shallow copy; the return result should be released with
* g_free(), but the individual strings must not be modified.
*
* If @length is non-%NULL then the number of elements in the result is
* stored there. In any case, the resulting array will be
* %NULL-terminated.
*
* For an empty array, @length will be set to 0 and a pointer to a
* %NULL pointer will be returned.
*
* Returns: (array length=length) (transfer container): an array of constant
*strings
*
* Since: 2.26
**/
const gchar** g_variant_get_bytestring_array(GVariant* value, gsize* length)
{
const gchar** strv;
gsize n;
gsize i;
TYPE_CHECK(value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
g_variant_get_data(value);
n = g_variant_n_children(value);
strv = g_new(const gchar*, n + 1);
for (i = 0; i < n; i++)
{
GVariant* string;
string = g_variant_get_child_value(value, i);
strv[i] = g_variant_get_bytestring(string);
g_variant_unref(string);
}
strv[i] = NULL;
if (length)
*length = n;
return strv;
}
/**
* g_variant_dup_bytestring_array:
* @value: an array of array of bytes #GVariant ('aay')
* @length: (out) (optional): the length of the result, or %NULL
*
* Gets the contents of an array of array of bytes #GVariant. This call
* makes a deep copy; the return result should be released with
* g_strfreev().
*
* If @length is non-%NULL then the number of elements in the result is
* stored there. In any case, the resulting array will be
* %NULL-terminated.
*
* For an empty array, @length will be set to 0 and a pointer to a
* %NULL pointer will be returned.
*
* Returns: (array length=length) (transfer full): an array of strings
*
* Since: 2.26
**/
gchar** g_variant_dup_bytestring_array(GVariant* value, gsize* length)
{
gchar** strv;
gsize n;
gsize i;
TYPE_CHECK(value, G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL);
g_variant_get_data(value);
n = g_variant_n_children(value);
strv = g_new(gchar*, n + 1);
for (i = 0; i < n; i++)
{
GVariant* string;
string = g_variant_get_child_value(value, i);
strv[i] = g_variant_dup_bytestring(string, NULL);
g_variant_unref(string);
}
strv[i] = NULL;
if (length)
*length = n;
return strv;
}
/* Type checking and querying {{{1 */
/**
* g_variant_get_type:
* @value: a #GVariant
*
* Determines the type of @value.
*
* The return value is valid for the lifetime of @value and must not
* be freed.
*
* Returns: a #GVariantType
*
* Since: 2.24
**/
const GVariantType* g_variant_get_type(GVariant* value)
{
GVariantTypeInfo* type_info;
g_return_val_if_fail(value != NULL, NULL);
type_info = g_variant_get_type_info(value);
return (GVariantType*)g_variant_type_info_get_type_string(type_info);
}
/**
* g_variant_get_type_string:
* @value: a #GVariant
*
* Returns the type string of @value. Unlike the result of calling
* g_variant_type_peek_string(), this string is nul-terminated. This
* string belongs to #GVariant and must not be freed.
*
* Returns: the type string for the type of @value
*
* Since: 2.24
**/
const gchar* g_variant_get_type_string(GVariant* value)
{
GVariantTypeInfo* type_info;
g_return_val_if_fail(value != NULL, NULL);
type_info = g_variant_get_type_info(value);
return g_variant_type_info_get_type_string(type_info);
}
/**
* g_variant_is_of_type:
* @value: a #GVariant instance
* @type: a #GVariantType
*
* Checks if a value has a type matching the provided type.
*
* Returns: %TRUE if the type of @value matches @type
*
* Since: 2.24
**/
gboolean g_variant_is_of_type(GVariant* value, const GVariantType* type)
{
return g_variant_type_is_subtype_of(g_variant_get_type(value), type);
}
/**
* g_variant_is_container:
* @value: a #GVariant instance
*
* Checks if @value is a container.
*
* Returns: %TRUE if @value is a container
*
* Since: 2.24
*/
gboolean g_variant_is_container(GVariant* value)
{
return g_variant_type_is_container(g_variant_get_type(value));
}
/**
* g_variant_classify:
* @value: a #GVariant
*
* Classifies @value according to its top-level type.
*
* Returns: the #GVariantClass of @value
*
* Since: 2.24
**/
/**
* GVariantClass:
* @G_VARIANT_CLASS_BOOLEAN: The #GVariant is a boolean.
* @G_VARIANT_CLASS_BYTE: The #GVariant is a byte.
* @G_VARIANT_CLASS_INT16: The #GVariant is a signed 16 bit integer.
* @G_VARIANT_CLASS_UINT16: The #GVariant is an unsigned 16 bit integer.
* @G_VARIANT_CLASS_INT32: The #GVariant is a signed 32 bit integer.
* @G_VARIANT_CLASS_UINT32: The #GVariant is an unsigned 32 bit integer.
* @G_VARIANT_CLASS_INT64: The #GVariant is a signed 64 bit integer.
* @G_VARIANT_CLASS_UINT64: The #GVariant is an unsigned 64 bit integer.
* @G_VARIANT_CLASS_HANDLE: The #GVariant is a file handle index.
* @G_VARIANT_CLASS_DOUBLE: The #GVariant is a double precision floating
* point value.
* @G_VARIANT_CLASS_STRING: The #GVariant is a normal string.
* @G_VARIANT_CLASS_OBJECT_PATH: The #GVariant is a D-Bus object path
* string.
* @G_VARIANT_CLASS_SIGNATURE: The #GVariant is a D-Bus signature string.
* @G_VARIANT_CLASS_VARIANT: The #GVariant is a variant.
* @G_VARIANT_CLASS_MAYBE: The #GVariant is a maybe-typed value.
* @G_VARIANT_CLASS_ARRAY: The #GVariant is an array.
* @G_VARIANT_CLASS_TUPLE: The #GVariant is a tuple.
* @G_VARIANT_CLASS_DICT_ENTRY: The #GVariant is a dictionary entry.
*
* The range of possible top-level types of #GVariant instances.
*
* Since: 2.24
**/
GVariantClass g_variant_classify(GVariant* value)
{
g_return_val_if_fail(value != NULL, 0);
return *g_variant_get_type_string(value);
}
/* Pretty printer {{{1 */
/* This function is not introspectable because if @string is NULL,
@returns is (transfer full), otherwise it is (transfer none), which
is not supported by GObjectIntrospection */
/**
* g_variant_print_string: (skip)
* @value: a #GVariant
* @string: (nullable) (default NULL): a #GString, or %NULL
* @type_annotate: %TRUE if type information should be included in
* the output
*
* Behaves as g_variant_print(), but operates on a #GString.
*
* If @string is non-%NULL then it is appended to and returned. Else,
* a new empty #GString is allocated and it is returned.
*
* Returns: a #GString containing the string
*
* Since: 2.24
**/
GString* g_variant_print_string(GVariant* value, GString* string,
gboolean type_annotate)
{
if
G_UNLIKELY(string == NULL)
string = g_string_new(NULL);
switch (g_variant_classify(value))
{
case G_VARIANT_CLASS_MAYBE:
if (type_annotate)
g_string_append_printf(string, "@%s ",
g_variant_get_type_string(value));
if (g_variant_n_children(value))
{
gchar* printed_child;
GVariant* element;
/* Nested maybes:
*
* Consider the case of the type "mmi". In this case we could
* write "just just 4", but "4" alone is totally unambiguous,
* so we try to drop "just" where possible.
*
* We have to be careful not to always drop "just", though,
* since "nothing" needs to be distinguishable from "just
* nothing". The case where we need to ensure we keep the
* "just" is actually exactly the case where we have a nested
* Nothing.
*
* Instead of searching for that nested Nothing, we just print
* the contained value into a separate string and see if we
* end up with "nothing" at the end of it. If so, we need to
* add "just" at our level.
*/
element = g_variant_get_child_value(value, 0);
printed_child = g_variant_print(element, FALSE);
g_variant_unref(element);
if (g_str_has_suffix(printed_child, "nothing"))
g_string_append(string, "just ");
g_string_append(string, printed_child);
g_free(printed_child);
}
else
g_string_append(string, "nothing");
break;
case G_VARIANT_CLASS_ARRAY:
/* it's an array so the first character of the type string is 'a'
*
* if the first two characters are 'ay' then it's a bytestring.
* under certain conditions we print those as strings.
*/
if (g_variant_get_type_string(value)[1] == 'y')
{
const gchar* str;
gsize size;
gsize i;
/* first determine if it is a byte string.
* that's when there's a single nul character: at the end.
*/
str = g_variant_get_data(value);
size = g_variant_get_size(value);
for (i = 0; i < size; i++)
if (str[i] == '\0')
break;
/* first nul byte is the last byte -> it's a byte string. */
if (i == size - 1)
{
gchar* escaped = g_strescape(str, NULL);
/* use double quotes only if a ' is in the string */
if (strchr(str, '\''))
g_string_append_printf(string, "b\"%s\"", escaped);
else
g_string_append_printf(string, "b'%s'", escaped);
g_free(escaped);
break;
}
else
{
/* fall through and handle normally... */
}
}
/*
* if the first two characters are 'a{' then it's an array of
* dictionary entries (ie: a dictionary) so we print that
* differently.
*/
if (g_variant_get_type_string(value)[1] == '{')
/* dictionary */
{
const gchar* comma = "";
gsize n, i;
if ((n = g_variant_n_children(value)) == 0)
{
if (type_annotate)
g_string_append_printf(
string, "@%s ", g_variant_get_type_string(value));
g_string_append(string, "{}");
break;
}
g_string_append_c(string, '{');
for (i = 0; i < n; i++)
{
GVariant *entry, *key, *val;
g_string_append(string, comma);
comma = ", ";
entry = g_variant_get_child_value(value, i);
key = g_variant_get_child_value(entry, 0);
val = g_variant_get_child_value(entry, 1);
g_variant_unref(entry);
g_variant_print_string(key, string, type_annotate);
g_variant_unref(key);
g_string_append(string, ": ");
g_variant_print_string(val, string, type_annotate);
g_variant_unref(val);
type_annotate = FALSE;
}
g_string_append_c(string, '}');
}
else
/* normal (non-dictionary) array */
{
const gchar* comma = "";
gsize n, i;
if ((n = g_variant_n_children(value)) == 0)
{
if (type_annotate)
g_string_append_printf(
string, "@%s ", g_variant_get_type_string(value));
g_string_append(string, "[]");
break;
}
g_string_append_c(string, '[');
for (i = 0; i < n; i++)
{
GVariant* element;
g_string_append(string, comma);
comma = ", ";
element = g_variant_get_child_value(value, i);
g_variant_print_string(element, string, type_annotate);
g_variant_unref(element);
type_annotate = FALSE;
}
g_string_append_c(string, ']');
}
break;
case G_VARIANT_CLASS_TUPLE:
{
gsize n, i;
n = g_variant_n_children(value);
g_string_append_c(string, '(');
for (i = 0; i < n; i++)
{
GVariant* element;
element = g_variant_get_child_value(value, i);
g_variant_print_string(element, string, type_annotate);
g_string_append(string, ", ");
g_variant_unref(element);
}
/* for >1 item: remove final ", "
* for 1 item: remove final " ", but leave the ","
* for 0 items: there is only "(", so remove nothing
*/
g_string_truncate(string, string->len - (n > 0) - (n > 1));
g_string_append_c(string, ')');
}
break;
case G_VARIANT_CLASS_DICT_ENTRY:
{
GVariant* element;
g_string_append_c(string, '{');
element = g_variant_get_child_value(value, 0);
g_variant_print_string(element, string, type_annotate);
g_variant_unref(element);
g_string_append(string, ", ");
element = g_variant_get_child_value(value, 1);
g_variant_print_string(element, string, type_annotate);
g_variant_unref(element);
g_string_append_c(string, '}');
}
break;
case G_VARIANT_CLASS_VARIANT:
{
GVariant* child = g_variant_get_variant(value);
/* Always annotate types in nested variants, because they are
* (by nature) of variable type.
*/
g_string_append_c(string, '<');
g_variant_print_string(child, string, TRUE);
g_string_append_c(string, '>');
g_variant_unref(child);
}
break;
case G_VARIANT_CLASS_BOOLEAN:
if (g_variant_get_boolean(value))
g_string_append(string, "true");
else
g_string_append(string, "false");
break;
case G_VARIANT_CLASS_STRING:
{
const gchar* str = g_variant_get_string(value, NULL);
gunichar quote = strchr(str, '\'') ? '"' : '\'';
g_string_append_c(string, quote);
while (*str)
{
gunichar c = g_utf8_get_char(str);
if (c == quote || c == '\\')
g_string_append_c(string, '\\');
if (g_unichar_isprint(c))
g_string_append_unichar(string, c);
else
{
g_string_append_c(string, '\\');
if (c < 0x10000)
switch (c)
{
case '\a':
g_string_append_c(string, 'a');
break;
case '\b':
g_string_append_c(string, 'b');
break;
case '\f':
g_string_append_c(string, 'f');
break;
case '\n':
g_string_append_c(string, 'n');
break;
case '\r':
g_string_append_c(string, 'r');
break;
case '\t':
g_string_append_c(string, 't');
break;
case '\v':
g_string_append_c(string, 'v');
break;
default:
g_string_append_printf(string, "u%04x", c);
break;
}
else
g_string_append_printf(string, "U%08x", c);
}
str = g_utf8_next_char(str);
}
g_string_append_c(string, quote);
}
break;
case G_VARIANT_CLASS_BYTE:
if (type_annotate)
g_string_append(string, "byte ");
g_string_append_printf(string, "0x%02x", g_variant_get_byte(value));
break;
case G_VARIANT_CLASS_INT16:
if (type_annotate)
g_string_append(string, "int16 ");
g_string_append_printf(string, "%" G_GINT16_FORMAT,
g_variant_get_int16(value));
break;
case G_VARIANT_CLASS_UINT16:
if (type_annotate)
g_string_append(string, "uint16 ");
g_string_append_printf(string, "%" G_GUINT16_FORMAT,
g_variant_get_uint16(value));
break;
case G_VARIANT_CLASS_INT32:
/* Never annotate this type because it is the default for numbers
* (and this is a *pretty* printer)
*/
g_string_append_printf(string, "%" G_GINT32_FORMAT,
g_variant_get_int32(value));
break;
case G_VARIANT_CLASS_HANDLE:
if (type_annotate)
g_string_append(string, "handle ");
g_string_append_printf(string, "%" G_GINT32_FORMAT,
g_variant_get_handle(value));
break;
case G_VARIANT_CLASS_UINT32:
if (type_annotate)
g_string_append(string, "uint32 ");
g_string_append_printf(string, "%" G_GUINT32_FORMAT,
g_variant_get_uint32(value));
break;
case G_VARIANT_CLASS_INT64:
if (type_annotate)
g_string_append(string, "int64 ");
g_string_append_printf(string, "%" G_GINT64_FORMAT,
g_variant_get_int64(value));
break;
case G_VARIANT_CLASS_UINT64:
if (type_annotate)
g_string_append(string, "uint64 ");
g_string_append_printf(string, "%" G_GUINT64_FORMAT,
g_variant_get_uint64(value));
break;
case G_VARIANT_CLASS_DOUBLE:
{
gchar buffer[100];
gint i;
g_ascii_dtostr(buffer, sizeof buffer, g_variant_get_double(value));
for (i = 0; buffer[i]; i++)
if (buffer[i] == '.' || buffer[i] == 'e' || buffer[i] == 'n' ||
buffer[i] == 'N')
break;
/* if there is no '.' or 'e' in the float then add one */
if (buffer[i] == '\0')
{
buffer[i++] = '.';
buffer[i++] = '0';
buffer[i++] = '\0';
}
g_string_append(string, buffer);
}
break;
case G_VARIANT_CLASS_OBJECT_PATH:
if (type_annotate)
g_string_append(string, "objectpath ");
g_string_append_printf(string, "\'%s\'",
g_variant_get_string(value, NULL));
break;
case G_VARIANT_CLASS_SIGNATURE:
if (type_annotate)
g_string_append(string, "signature ");
g_string_append_printf(string, "\'%s\'",
g_variant_get_string(value, NULL));
break;
default:
g_assert_not_reached();
}
return string;
}
/**
* g_variant_print:
* @value: a #GVariant
* @type_annotate: %TRUE if type information should be included in
* the output
*
* Pretty-prints @value in the format understood by g_variant_parse().
*
* The format is described [here][gvariant-text].
*
* If @type_annotate is %TRUE, then type information is included in
* the output.
*
* Returns: (transfer full): a newly-allocated string holding the result.
*
* Since: 2.24
*/
gchar* g_variant_print(GVariant* value, gboolean type_annotate)
{
return g_string_free(g_variant_print_string(value, NULL, type_annotate),
FALSE);
}
/* Hash, Equal, Compare {{{1 */
/**
* g_variant_hash:
* @value: (type GVariant): a basic #GVariant value as a #gconstpointer
*
* Generates a hash value for a #GVariant instance.
*
* The output of this function is guaranteed to be the same for a given
* value only per-process. It may change between different processor
* architectures or even different versions of GLib. Do not use this
* function as a basis for building protocols or file formats.
*
* The type of @value is #gconstpointer only to allow use of this
* function with #GHashTable. @value must be a #GVariant.
*
* Returns: a hash value corresponding to @value
*
* Since: 2.24
**/
guint g_variant_hash(gconstpointer value_)
{
GVariant* value = (GVariant*)value_;
switch (g_variant_classify(value))
{
case G_VARIANT_CLASS_STRING:
case G_VARIANT_CLASS_OBJECT_PATH:
case G_VARIANT_CLASS_SIGNATURE:
return g_str_hash(g_variant_get_string(value, NULL));
case G_VARIANT_CLASS_BOOLEAN:
/* this is a very odd thing to hash... */
return g_variant_get_boolean(value);
case G_VARIANT_CLASS_BYTE:
return g_variant_get_byte(value);
case G_VARIANT_CLASS_INT16:
case G_VARIANT_CLASS_UINT16:
{
const guint16* ptr;
ptr = g_variant_get_data(value);
if (ptr)
return *ptr;
else
return 0;
}
case G_VARIANT_CLASS_INT32:
case G_VARIANT_CLASS_UINT32:
case G_VARIANT_CLASS_HANDLE:
{
const guint* ptr;
ptr = g_variant_get_data(value);
if (ptr)
return *ptr;
else
return 0;
}
case G_VARIANT_CLASS_INT64:
case G_VARIANT_CLASS_UINT64:
case G_VARIANT_CLASS_DOUBLE:
/* need a separate case for these guys because otherwise
* performance could be quite bad on big endian systems
*/
{
const guint* ptr;
ptr = g_variant_get_data(value);
if (ptr)
return ptr[0] + ptr[1];
else
return 0;
}
default:
g_return_val_if_fail(!g_variant_is_container(value), 0);
g_assert_not_reached();
}
}
/**
* g_variant_equal:
* @one: (type GVariant): a #GVariant instance
* @two: (type GVariant): a #GVariant instance
*
* Checks if @one and @two have the same type and value.
*
* The types of @one and @two are #gconstpointer only to allow use of
* this function with #GHashTable. They must each be a #GVariant.
*
* Returns: %TRUE if @one and @two are equal
*
* Since: 2.24
**/
gboolean g_variant_equal(gconstpointer one, gconstpointer two)
{
gboolean equal;
g_return_val_if_fail(one != NULL && two != NULL, FALSE);
if (g_variant_get_type_info((GVariant*)one) !=
g_variant_get_type_info((GVariant*)two))
return FALSE;
/* if both values are trusted to be in their canonical serialised form
* then a simple memcmp() of their serialised data will answer the
* question.
*
* if not, then this might generate a false negative (since it is
* possible for two different byte sequences to represent the same
* value). for now we solve this by pretty-printing both values and
* comparing the result.
*/
if (g_variant_is_trusted((GVariant*)one) &&
g_variant_is_trusted((GVariant*)two))
{
gconstpointer data_one, data_two;
gsize size_one, size_two;
size_one = g_variant_get_size((GVariant*)one);
size_two = g_variant_get_size((GVariant*)two);
if (size_one != size_two)
return FALSE;
data_one = g_variant_get_data((GVariant*)one);
data_two = g_variant_get_data((GVariant*)two);
equal = memcmp(data_one, data_two, size_one) == 0;
}
else
{
gchar *strone, *strtwo;
strone = g_variant_print((GVariant*)one, FALSE);
strtwo = g_variant_print((GVariant*)two, FALSE);
equal = strcmp(strone, strtwo) == 0;
g_free(strone);
g_free(strtwo);
}
return equal;
}
/**
* g_variant_compare:
* @one: (type GVariant): a basic-typed #GVariant instance
* @two: (type GVariant): a #GVariant instance of the same type
*
* Compares @one and @two.
*
* The types of @one and @two are #gconstpointer only to allow use of
* this function with #GTree, #GPtrArray, etc. They must each be a
* #GVariant.
*
* Comparison is only defined for basic types (ie: booleans, numbers,
* strings). For booleans, %FALSE is less than %TRUE. Numbers are
* ordered in the usual way. Strings are in ASCII lexographical order.
*
* It is a programmer error to attempt to compare container values or
* two values that have types that are not exactly equal. For example,
* you cannot compare a 32-bit signed integer with a 32-bit unsigned
* integer. Also note that this function is not particularly
* well-behaved when it comes to comparison of doubles; in particular,
* the handling of incomparable values (ie: NaN) is undefined.
*
* If you only require an equality comparison, g_variant_equal() is more
* general.
*
* Returns: negative value if a < b;
* zero if a = b;
* positive value if a > b.
*
* Since: 2.26
**/
gint g_variant_compare(gconstpointer one, gconstpointer two)
{
GVariant* a = (GVariant*)one;
GVariant* b = (GVariant*)two;
g_return_val_if_fail(g_variant_classify(a) == g_variant_classify(b), 0);
switch (g_variant_classify(a))
{
case G_VARIANT_CLASS_BOOLEAN:
return g_variant_get_boolean(a) - g_variant_get_boolean(b);
case G_VARIANT_CLASS_BYTE:
return ((gint)g_variant_get_byte(a)) -
((gint)g_variant_get_byte(b));
case G_VARIANT_CLASS_INT16:
return ((gint)g_variant_get_int16(a)) -
((gint)g_variant_get_int16(b));
case G_VARIANT_CLASS_UINT16:
return ((gint)g_variant_get_uint16(a)) -
((gint)g_variant_get_uint16(b));
case G_VARIANT_CLASS_INT32:
{
gint32 a_val = g_variant_get_int32(a);
gint32 b_val = g_variant_get_int32(b);
return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
}
case G_VARIANT_CLASS_UINT32:
{
guint32 a_val = g_variant_get_uint32(a);
guint32 b_val = g_variant_get_uint32(b);
return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
}
case G_VARIANT_CLASS_INT64:
{
gint64 a_val = g_variant_get_int64(a);
gint64 b_val = g_variant_get_int64(b);
return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
}
case G_VARIANT_CLASS_UINT64:
{
guint64 a_val = g_variant_get_uint64(a);
guint64 b_val = g_variant_get_uint64(b);
return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
}
case G_VARIANT_CLASS_DOUBLE:
{
gdouble a_val = g_variant_get_double(a);
gdouble b_val = g_variant_get_double(b);
return (a_val == b_val) ? 0 : (a_val > b_val) ? 1 : -1;
}
case G_VARIANT_CLASS_STRING:
case G_VARIANT_CLASS_OBJECT_PATH:
case G_VARIANT_CLASS_SIGNATURE:
return strcmp(g_variant_get_string(a, NULL),
g_variant_get_string(b, NULL));
default:
g_return_val_if_fail(!g_variant_is_container(a), 0);
g_assert_not_reached();
}
}
/* GVariantIter {{{1 */
/**
* GVariantIter: (skip)
*
* #GVariantIter is an opaque data structure and can only be accessed
* using the following functions.
**/
struct stack_iter
{
GVariant* value;
gssize n, i;
const gchar* loop_format;
gsize padding[3];
gsize magic;
};
G_STATIC_ASSERT(sizeof(struct stack_iter) <= sizeof(GVariantIter));
struct heap_iter
{
struct stack_iter iter;
GVariant* value_ref;
gsize magic;
};
#define GVSI(i) ((struct stack_iter*)(i))
#define GVHI(i) ((struct heap_iter*)(i))
#define GVSI_MAGIC ((gsize)3579507750u)
#define GVHI_MAGIC ((gsize)1450270775u)
#define is_valid_iter(i) (i != NULL && GVSI(i)->magic == GVSI_MAGIC)
#define is_valid_heap_iter(i) (is_valid_iter(i) && GVHI(i)->magic == GVHI_MAGIC)
/**
* g_variant_iter_new:
* @value: a container #GVariant
*
* Creates a heap-allocated #GVariantIter for iterating over the items
* in @value.
*
* Use g_variant_iter_free() to free the return value when you no longer
* need it.
*
* A reference is taken to @value and will be released only when
* g_variant_iter_free() is called.
*
* Returns: (transfer full): a new heap-allocated #GVariantIter
*
* Since: 2.24
**/
GVariantIter* g_variant_iter_new(GVariant* value)
{
GVariantIter* iter;
iter = (GVariantIter*)g_slice_new(struct heap_iter);
GVHI(iter)->value_ref = g_variant_ref(value);
GVHI(iter)->magic = GVHI_MAGIC;
g_variant_iter_init(iter, value);
return iter;
}
/**
* g_variant_iter_init: (skip)
* @iter: a pointer to a #GVariantIter
* @value: a container #GVariant
*
* Initialises (without allocating) a #GVariantIter. @iter may be
* completely uninitialised prior to this call; its old value is
* ignored.
*
* The iterator remains valid for as long as @value exists, and need not
* be freed in any way.
*
* Returns: the number of items in @value
*
* Since: 2.24
**/
gsize g_variant_iter_init(GVariantIter* iter, GVariant* value)
{
GVSI(iter)->magic = GVSI_MAGIC;
GVSI(iter)->value = value;
GVSI(iter)->n = g_variant_n_children(value);
GVSI(iter)->i = -1;
GVSI(iter)->loop_format = NULL;
return GVSI(iter)->n;
}
/**
* g_variant_iter_copy:
* @iter: a #GVariantIter
*
* Creates a new heap-allocated #GVariantIter to iterate over the
* container that was being iterated over by @iter. Iteration begins on
* the new iterator from the current position of the old iterator but
* the two copies are independent past that point.
*
* Use g_variant_iter_free() to free the return value when you no longer
* need it.
*
* A reference is taken to the container that @iter is iterating over
* and will be releated only when g_variant_iter_free() is called.
*
* Returns: (transfer full): a new heap-allocated #GVariantIter
*
* Since: 2.24
**/
GVariantIter* g_variant_iter_copy(GVariantIter* iter)
{
GVariantIter* copy;
g_return_val_if_fail(is_valid_iter(iter), 0);
copy = g_variant_iter_new(GVSI(iter)->value);
GVSI(copy)->i = GVSI(iter)->i;
return copy;
}
/**
* g_variant_iter_n_children:
* @iter: a #GVariantIter
*
* Queries the number of child items in the container that we are
* iterating over. This is the total number of items -- not the number
* of items remaining.
*
* This function might be useful for preallocation of arrays.
*
* Returns: the number of children in the container
*
* Since: 2.24
**/
gsize g_variant_iter_n_children(GVariantIter* iter)
{
g_return_val_if_fail(is_valid_iter(iter), 0);
return GVSI(iter)->n;
}
/**
* g_variant_iter_free:
* @iter: (transfer full): a heap-allocated #GVariantIter
*
* Frees a heap-allocated #GVariantIter. Only call this function on
* iterators that were returned by g_variant_iter_new() or
* g_variant_iter_copy().
*
* Since: 2.24
**/
void g_variant_iter_free(GVariantIter* iter)
{
g_return_if_fail(is_valid_heap_iter(iter));
g_variant_unref(GVHI(iter)->value_ref);
GVHI(iter)->magic = 0;
g_slice_free(struct heap_iter, GVHI(iter));
}
/**
* g_variant_iter_next_value:
* @iter: a #GVariantIter
*
* Gets the next item in the container. If no more items remain then
* %NULL is returned.
*
* Use g_variant_unref() to drop your reference on the return value when
* you no longer need it.
*
* Here is an example for iterating with g_variant_iter_next_value():
* |[<!-- language="C" -->
* // recursively iterate a container
* void
* iterate_container_recursive (GVariant *container)
* {
* GVariantIter iter;
* GVariant *child;
*
* g_variant_iter_init (&iter, container);
* while ((child = g_variant_iter_next_value (&iter)))
* {
* g_print ("type '%s'\n", g_variant_get_type_string (child));
*
* if (g_variant_is_container (child))
* iterate_container_recursive (child);
*
* g_variant_unref (child);
* }
* }
* ]|
*
* Returns: (nullable) (transfer full): a #GVariant, or %NULL
*
* Since: 2.24
**/
GVariant* g_variant_iter_next_value(GVariantIter* iter)
{
g_return_val_if_fail(is_valid_iter(iter), FALSE);
if
G_UNLIKELY(GVSI(iter)->i >= GVSI(iter)->n)
{
g_critical("g_variant_iter_next_value: must not be called again "
"after NULL has already been returned.");
return NULL;
}
GVSI(iter)->i++;
if (GVSI(iter)->i < GVSI(iter)->n)
return g_variant_get_child_value(GVSI(iter)->value, GVSI(iter)->i);
return NULL;
}
/* GVariantBuilder {{{1 */
/**
* GVariantBuilder:
*
* A utility type for constructing container-type #GVariant instances.
*
* This is an opaque structure and may only be accessed using the
* following functions.
*
* #GVariantBuilder is not threadsafe in any way. Do not attempt to
* access it from more than one thread.
**/
struct stack_builder
{
GVariantBuilder* parent;
GVariantType* type;
/* type constraint explicitly specified by 'type'.
* for tuple types, this moves along as we add more items.
*/
const GVariantType* expected_type;
/* type constraint implied by previous array item.
*/
const GVariantType* prev_item_type;
/* constraints on the number of children. max = -1 for unlimited. */
gsize min_items;
gsize max_items;
/* dynamically-growing pointer array */
GVariant** children;
gsize allocated_children;
gsize offset;
/* set to '1' if all items in the container will have the same type
* (ie: maybe, array, variant) '0' if not (ie: tuple, dict entry)
*/
guint uniform_item_types : 1;
/* set to '1' initially and changed to '0' if an untrusted value is
* added
*/
guint trusted : 1;
gsize magic;
};
G_STATIC_ASSERT(sizeof(struct stack_builder) <= sizeof(GVariantBuilder));
struct heap_builder
{
GVariantBuilder builder;
gsize magic;
gint ref_count;
};
#define GVSB(b) ((struct stack_builder*)(b))
#define GVHB(b) ((struct heap_builder*)(b))
#define GVSB_MAGIC ((gsize)1033660112u)
#define GVSB_MAGIC_PARTIAL ((gsize)2942751021u)
#define GVHB_MAGIC ((gsize)3087242682u)
#define is_valid_builder(b) (b != NULL && GVSB(b)->magic == GVSB_MAGIC)
#define is_valid_heap_builder(b) (GVHB(b)->magic == GVHB_MAGIC)
/* Just to make sure that by adding a union to GVariantBuilder, we
* didn't accidentally change ABI. */
G_STATIC_ASSERT(sizeof(GVariantBuilder) == sizeof(gsize[16]));
static gboolean ensure_valid_builder(GVariantBuilder* builder)
{
if (is_valid_builder(builder))
return TRUE;
if (builder->u.s.partial_magic == GVSB_MAGIC_PARTIAL)
{
static GVariantBuilder cleared_builder;
/* Make sure that only first two fields were set and the rest is
* zeroed to avoid messing up the builder that had parent
* address equal to GVSB_MAGIC_PARTIAL. */
if (memcmp(cleared_builder.u.s.y, builder->u.s.y,
sizeof cleared_builder.u.s.y))
return FALSE;
g_variant_builder_init(builder, builder->u.s.type);
}
return is_valid_builder(builder);
}
/**
* g_variant_builder_new:
* @type: a container type
*
* Allocates and initialises a new #GVariantBuilder.
*
* You should call g_variant_builder_unref() on the return value when it
* is no longer needed. The memory will not be automatically freed by
* any other call.
*
* In most cases it is easier to place a #GVariantBuilder directly on
* the stack of the calling function and initialise it with
* g_variant_builder_init().
*
* Returns: (transfer full): a #GVariantBuilder
*
* Since: 2.24
**/
GVariantBuilder* g_variant_builder_new(const GVariantType* type)
{
GVariantBuilder* builder;
builder = (GVariantBuilder*)g_slice_new(struct heap_builder);
g_variant_builder_init(builder, type);
GVHB(builder)->magic = GVHB_MAGIC;
GVHB(builder)->ref_count = 1;
return builder;
}
/**
* g_variant_builder_unref:
* @builder: (transfer full): a #GVariantBuilder allocated by
*g_variant_builder_new()
*
* Decreases the reference count on @builder.
*
* In the event that there are no more references, releases all memory
* associated with the #GVariantBuilder.
*
* Don't call this on stack-allocated #GVariantBuilder instances or bad
* things will happen.
*
* Since: 2.24
**/
void g_variant_builder_unref(GVariantBuilder* builder)
{
g_return_if_fail(is_valid_heap_builder(builder));
if (--GVHB(builder)->ref_count)
return;
g_variant_builder_clear(builder);
GVHB(builder)->magic = 0;
g_slice_free(struct heap_builder, GVHB(builder));
}
/**
* g_variant_builder_ref:
* @builder: a #GVariantBuilder allocated by g_variant_builder_new()
*
* Increases the reference count on @builder.
*
* Don't call this on stack-allocated #GVariantBuilder instances or bad
* things will happen.
*
* Returns: (transfer full): a new reference to @builder
*
* Since: 2.24
**/
GVariantBuilder* g_variant_builder_ref(GVariantBuilder* builder)
{
g_return_val_if_fail(is_valid_heap_builder(builder), NULL);
GVHB(builder)->ref_count++;
return builder;
}
/**
* g_variant_builder_clear: (skip)
* @builder: a #GVariantBuilder
*
* Releases all memory associated with a #GVariantBuilder without
* freeing the #GVariantBuilder structure itself.
*
* It typically only makes sense to do this on a stack-allocated
* #GVariantBuilder if you want to abort building the value part-way
* through. This function need not be called if you call
* g_variant_builder_end() and it also doesn't need to be called on
* builders allocated with g_variant_builder_new() (see
* g_variant_builder_unref() for that).
*
* This function leaves the #GVariantBuilder structure set to all-zeros.
* It is valid to call this function on either an initialised
* #GVariantBuilder or one that is set to all-zeros but it is not valid
* to call this function on uninitialised memory.
*
* Since: 2.24
**/
void g_variant_builder_clear(GVariantBuilder* builder)
{
gsize i;
if (GVSB(builder)->magic == 0)
/* all-zeros or partial case */
return;
g_return_if_fail(ensure_valid_builder(builder));
g_variant_type_free(GVSB(builder)->type);
for (i = 0; i < GVSB(builder)->offset; i++)
g_variant_unref(GVSB(builder)->children[i]);
g_free(GVSB(builder)->children);
if (GVSB(builder)->parent)
{
g_variant_builder_clear(GVSB(builder)->parent);
g_slice_free(GVariantBuilder, GVSB(builder)->parent);
}
memset(builder, 0, sizeof(GVariantBuilder));
}
/**
* g_variant_builder_init: (skip)
* @builder: a #GVariantBuilder
* @type: a container type
*
* Initialises a #GVariantBuilder structure.
*
* @type must be non-%NULL. It specifies the type of container to
* construct. It can be an indefinite type such as
* %G_VARIANT_TYPE_ARRAY or a definite type such as "as" or "(ii)".
* Maybe, array, tuple, dictionary entry and variant-typed values may be
* constructed.
*
* After the builder is initialised, values are added using
* g_variant_builder_add_value() or g_variant_builder_add().
*
* After all the child values are added, g_variant_builder_end() frees
* the memory associated with the builder and returns the #GVariant that
* was created.
*
* This function completely ignores the previous contents of @builder.
* On one hand this means that it is valid to pass in completely
* uninitialised memory. On the other hand, this means that if you are
* initialising over top of an existing #GVariantBuilder you need to
* first call g_variant_builder_clear() in order to avoid leaking
* memory.
*
* You must not call g_variant_builder_ref() or
* g_variant_builder_unref() on a #GVariantBuilder that was initialised
* with this function. If you ever pass a reference to a
* #GVariantBuilder outside of the control of your own code then you
* should assume that the person receiving that reference may try to use
* reference counting; you should use g_variant_builder_new() instead of
* this function.
*
* Since: 2.24
**/
void g_variant_builder_init(GVariantBuilder* builder, const GVariantType* type)
{
g_return_if_fail(type != NULL);
g_return_if_fail(g_variant_type_is_container(type));
memset(builder, 0, sizeof(GVariantBuilder));
GVSB(builder)->type = g_variant_type_copy(type);
GVSB(builder)->magic = GVSB_MAGIC;
GVSB(builder)->trusted = TRUE;
switch (*(const gchar*)type)
{
case G_VARIANT_CLASS_VARIANT:
GVSB(builder)->uniform_item_types = TRUE;
GVSB(builder)->allocated_children = 1;
GVSB(builder)->expected_type = NULL;
GVSB(builder)->min_items = 1;
GVSB(builder)->max_items = 1;
break;
case G_VARIANT_CLASS_ARRAY:
GVSB(builder)->uniform_item_types = TRUE;
GVSB(builder)->allocated_children = 8;
GVSB(builder)->expected_type =
g_variant_type_element(GVSB(builder)->type);
GVSB(builder)->min_items = 0;
GVSB(builder)->max_items = -1;
break;
case G_VARIANT_CLASS_MAYBE:
GVSB(builder)->uniform_item_types = TRUE;
GVSB(builder)->allocated_children = 1;
GVSB(builder)->expected_type =
g_variant_type_element(GVSB(builder)->type);
GVSB(builder)->min_items = 0;
GVSB(builder)->max_items = 1;
break;
case G_VARIANT_CLASS_DICT_ENTRY:
GVSB(builder)->uniform_item_types = FALSE;
GVSB(builder)->allocated_children = 2;
GVSB(builder)->expected_type =
g_variant_type_key(GVSB(builder)->type);
GVSB(builder)->min_items = 2;
GVSB(builder)->max_items = 2;
break;
case 'r': /* G_VARIANT_TYPE_TUPLE was given */
GVSB(builder)->uniform_item_types = FALSE;
GVSB(builder)->allocated_children = 8;
GVSB(builder)->expected_type = NULL;
GVSB(builder)->min_items = 0;
GVSB(builder)->max_items = -1;
break;
case G_VARIANT_CLASS_TUPLE: /* a definite tuple type was given */
GVSB(builder)->allocated_children = g_variant_type_n_items(type);
GVSB(builder)->expected_type =
g_variant_type_first(GVSB(builder)->type);
GVSB(builder)->min_items = GVSB(builder)->allocated_children;
GVSB(builder)->max_items = GVSB(builder)->allocated_children;
GVSB(builder)->uniform_item_types = FALSE;
break;
default:
g_assert_not_reached();
}
GVSB(builder)->children =
g_new(GVariant*, GVSB(builder)->allocated_children);
}
static void g_variant_builder_make_room(struct stack_builder* builder)
{
if (builder->offset == builder->allocated_children)
{
builder->allocated_children *= 2;
builder->children =
g_renew(GVariant*, builder->children, builder->allocated_children);
}
}
/**
* g_variant_builder_add_value:
* @builder: a #GVariantBuilder
* @value: a #GVariant
*
* Adds @value to @builder.
*
* It is an error to call this function in any way that would create an
* inconsistent value to be constructed. Some examples of this are
* putting different types of items into an array, putting the wrong
* types or number of items in a tuple, putting more than one value into
* a variant, etc.
*
* If @value is a floating reference (see g_variant_ref_sink()),
* the @builder instance takes ownership of @value.
*
* Since: 2.24
**/
void g_variant_builder_add_value(GVariantBuilder* builder, GVariant* value)
{
g_return_if_fail(ensure_valid_builder(builder));
g_return_if_fail(GVSB(builder)->offset < GVSB(builder)->max_items);
g_return_if_fail(!GVSB(builder)->expected_type ||
g_variant_is_of_type(value, GVSB(builder)->expected_type));
g_return_if_fail(
!GVSB(builder)->prev_item_type ||
g_variant_is_of_type(value, GVSB(builder)->prev_item_type));
GVSB(builder)->trusted &= g_variant_is_trusted(value);
if (!GVSB(builder)->uniform_item_types)
{
/* advance our expected type pointers */
if (GVSB(builder)->expected_type)
GVSB(builder)->expected_type =
g_variant_type_next(GVSB(builder)->expected_type);
if (GVSB(builder)->prev_item_type)
GVSB(builder)->prev_item_type =
g_variant_type_next(GVSB(builder)->prev_item_type);
}
else
GVSB(builder)->prev_item_type = g_variant_get_type(value);
g_variant_builder_make_room(GVSB(builder));
GVSB(builder)->children[GVSB(builder)->offset++] =
g_variant_ref_sink(value);
}
/**
* g_variant_builder_open:
* @builder: a #GVariantBuilder
* @type: the #GVariantType of the container
*
* Opens a subcontainer inside the given @builder. When done adding
* items to the subcontainer, g_variant_builder_close() must be called. @type
* is the type of the container: so to build a tuple of several values, @type
* must include the tuple itself.
*
* It is an error to call this function in any way that would cause an
* inconsistent value to be constructed (ie: adding too many values or
* a value of an incorrect type).
*
* Example of building a nested variant:
* |[<!-- language="C" -->
* GVariantBuilder builder;
* guint32 some_number = get_number ();
* g_autoptr (GHashTable) some_dict = get_dict ();
* GHashTableIter iter;
* const gchar *key;
* const GVariant *value;
* g_autoptr (GVariant) output = NULL;
*
* g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ua{sv})"));
* g_variant_builder_add (&builder, "u", some_number);
* g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
*
* g_hash_table_iter_init (&iter, some_dict);
* while (g_hash_table_iter_next (&iter, (gpointer *) &key, (gpointer *)
*&value))
* {
* g_variant_builder_open (&builder, G_VARIANT_TYPE ("{sv}"));
* g_variant_builder_add (&builder, "s", key);
* g_variant_builder_add (&builder, "v", value);
* g_variant_builder_close (&builder);
* }
*
* g_variant_builder_close (&builder);
*
* output = g_variant_builder_end (&builder);
* ]|
*
* Since: 2.24
**/
void g_variant_builder_open(GVariantBuilder* builder, const GVariantType* type)
{
GVariantBuilder* parent;
g_return_if_fail(ensure_valid_builder(builder));
g_return_if_fail(GVSB(builder)->offset < GVSB(builder)->max_items);
g_return_if_fail(
!GVSB(builder)->expected_type ||
g_variant_type_is_subtype_of(type, GVSB(builder)->expected_type));
g_return_if_fail(
!GVSB(builder)->prev_item_type ||
g_variant_type_is_subtype_of(GVSB(builder)->prev_item_type, type));
parent = g_slice_dup(GVariantBuilder, builder);
g_variant_builder_init(builder, type);
GVSB(builder)->parent = parent;
/* push the prev_item_type down into the subcontainer */
if (GVSB(parent)->prev_item_type)
{
if (!GVSB(builder)->uniform_item_types)
/* tuples and dict entries */
GVSB(builder)->prev_item_type =
g_variant_type_first(GVSB(parent)->prev_item_type);
else if (!g_variant_type_is_variant(GVSB(builder)->type))
/* maybes and arrays */
GVSB(builder)->prev_item_type =
g_variant_type_element(GVSB(parent)->prev_item_type);
}
}
/**
* g_variant_builder_close:
* @builder: a #GVariantBuilder
*
* Closes the subcontainer inside the given @builder that was opened by
* the most recent call to g_variant_builder_open().
*
* It is an error to call this function in any way that would create an
* inconsistent value to be constructed (ie: too few values added to the
* subcontainer).
*
* Since: 2.24
**/
void g_variant_builder_close(GVariantBuilder* builder)
{
GVariantBuilder* parent;
g_return_if_fail(ensure_valid_builder(builder));
g_return_if_fail(GVSB(builder)->parent != NULL);
parent = GVSB(builder)->parent;
GVSB(builder)->parent = NULL;
g_variant_builder_add_value(parent, g_variant_builder_end(builder));
*builder = *parent;
g_slice_free(GVariantBuilder, parent);
}
/*< private >
* g_variant_make_maybe_type:
* @element: a #GVariant
*
* Return the type of a maybe containing @element.
*/
static GVariantType* g_variant_make_maybe_type(GVariant* element)
{
return g_variant_type_new_maybe(g_variant_get_type(element));
}
/*< private >
* g_variant_make_array_type:
* @element: a #GVariant
*
* Return the type of an array containing @element.
*/
static GVariantType* g_variant_make_array_type(GVariant* element)
{
return g_variant_type_new_array(g_variant_get_type(element));
}
/**
* g_variant_builder_end:
* @builder: a #GVariantBuilder
*
* Ends the builder process and returns the constructed value.
*
* It is not permissible to use @builder in any way after this call
* except for reference counting operations (in the case of a
* heap-allocated #GVariantBuilder) or by reinitialising it with
* g_variant_builder_init() (in the case of stack-allocated). This
* means that for the stack-allocated builders there is no need to
* call g_variant_builder_clear() after the call to
* g_variant_builder_end().
*
* It is an error to call this function in any way that would create an
* inconsistent value to be constructed (ie: insufficient number of
* items added to a container with a specific number of children
* required). It is also an error to call this function if the builder
* was created with an indefinite array or maybe type and no children
* have been added; in this case it is impossible to infer the type of
* the empty array.
*
* Returns: (transfer none): a new, floating, #GVariant
*
* Since: 2.24
**/
GVariant* g_variant_builder_end(GVariantBuilder* builder)
{
GVariantType* my_type;
GVariant* value;
g_return_val_if_fail(ensure_valid_builder(builder), NULL);
g_return_val_if_fail(GVSB(builder)->offset >= GVSB(builder)->min_items,
NULL);
g_return_val_if_fail(!GVSB(builder)->uniform_item_types ||
GVSB(builder)->prev_item_type != NULL ||
g_variant_type_is_definite(GVSB(builder)->type),
NULL);
if (g_variant_type_is_definite(GVSB(builder)->type))
my_type = g_variant_type_copy(GVSB(builder)->type);
else if (g_variant_type_is_maybe(GVSB(builder)->type))
my_type = g_variant_make_maybe_type(GVSB(builder)->children[0]);
else if (g_variant_type_is_array(GVSB(builder)->type))
my_type = g_variant_make_array_type(GVSB(builder)->children[0]);
else if (g_variant_type_is_tuple(GVSB(builder)->type))
my_type = g_variant_make_tuple_type(GVSB(builder)->children,
GVSB(builder)->offset);
else if (g_variant_type_is_dict_entry(GVSB(builder)->type))
my_type = g_variant_make_dict_entry_type(GVSB(builder)->children[0],
GVSB(builder)->children[1]);
else
g_assert_not_reached();
value = g_variant_new_from_children(
my_type,
g_renew(GVariant*, GVSB(builder)->children, GVSB(builder)->offset),
GVSB(builder)->offset, GVSB(builder)->trusted);
GVSB(builder)->children = NULL;
GVSB(builder)->offset = 0;
g_variant_builder_clear(builder);
g_variant_type_free(my_type);
return value;
}
/* GVariantDict {{{1 */
/**
* GVariantDict:
*
* #GVariantDict is a mutable interface to #GVariant dictionaries.
*
* It can be used for doing a sequence of dictionary lookups in an
* efficient way on an existing #GVariant dictionary or it can be used
* to construct new dictionaries with a hashtable-like interface. It
* can also be used for taking existing dictionaries and modifying them
* in order to create new ones.
*
* #GVariantDict can only be used with %G_VARIANT_TYPE_VARDICT
* dictionaries.
*
* It is possible to use #GVariantDict allocated on the stack or on the
* heap. When using a stack-allocated #GVariantDict, you begin with a
* call to g_variant_dict_init() and free the resources with a call to
* g_variant_dict_clear().
*
* Heap-allocated #GVariantDict follows normal refcounting rules: you
* allocate it with g_variant_dict_new() and use g_variant_dict_ref()
* and g_variant_dict_unref().
*
* g_variant_dict_end() is used to convert the #GVariantDict back into a
* dictionary-type #GVariant. When used with stack-allocated instances,
* this also implicitly frees all associated memory, but for
* heap-allocated instances, you must still call g_variant_dict_unref()
* afterwards.
*
* You will typically want to use a heap-allocated #GVariantDict when
* you expose it as part of an API. For most other uses, the
* stack-allocated form will be more convenient.
*
* Consider the following two examples that do the same thing in each
* style: take an existing dictionary and look up the "count" uint32
* key, adding 1 to it if it is found, or returning an error if the
* key is not found. Each returns the new dictionary as a floating
* #GVariant.
*
* ## Using a stack-allocated GVariantDict
*
* |[<!-- language="C" -->
* GVariant *
* add_to_count (GVariant *orig,
* GError **error)
* {
* GVariantDict dict;
* guint32 count;
*
* g_variant_dict_init (&dict, orig);
* if (!g_variant_dict_lookup (&dict, "count", "u", &count))
* {
* g_set_error (...);
* g_variant_dict_clear (&dict);
* return NULL;
* }
*
* g_variant_dict_insert (&dict, "count", "u", count + 1);
*
* return g_variant_dict_end (&dict);
* }
* ]|
*
* ## Using heap-allocated GVariantDict
*
* |[<!-- language="C" -->
* GVariant *
* add_to_count (GVariant *orig,
* GError **error)
* {
* GVariantDict *dict;
* GVariant *result;
* guint32 count;
*
* dict = g_variant_dict_new (orig);
*
* if (g_variant_dict_lookup (dict, "count", "u", &count))
* {
* g_variant_dict_insert (dict, "count", "u", count + 1);
* result = g_variant_dict_end (dict);
* }
* else
* {
* g_set_error (...);
* result = NULL;
* }
*
* g_variant_dict_unref (dict);
*
* return result;
* }
* ]|
*
* Since: 2.40
**/
struct stack_dict
{
GHashTable* values;
gsize magic;
};
G_STATIC_ASSERT(sizeof(struct stack_dict) <= sizeof(GVariantDict));
struct heap_dict
{
struct stack_dict dict;
gint ref_count;
gsize magic;
};
#define GVSD(d) ((struct stack_dict*)(d))
#define GVHD(d) ((struct heap_dict*)(d))
#define GVSD_MAGIC ((gsize)2579507750u)
#define GVSD_MAGIC_PARTIAL ((gsize)3488698669u)
#define GVHD_MAGIC ((gsize)2450270775u)
#define is_valid_dict(d) (d != NULL && GVSD(d)->magic == GVSD_MAGIC)
#define is_valid_heap_dict(d) (GVHD(d)->magic == GVHD_MAGIC)
/* Just to make sure that by adding a union to GVariantDict, we didn't
* accidentally change ABI. */
G_STATIC_ASSERT(sizeof(GVariantDict) == sizeof(gsize[16]));
static gboolean ensure_valid_dict(GVariantDict* dict)
{
if (is_valid_dict(dict))
return TRUE;
if (dict->u.s.partial_magic == GVSD_MAGIC_PARTIAL)
{
static GVariantDict cleared_dict;
/* Make sure that only first two fields were set and the rest is
* zeroed to avoid messing up the builder that had parent
* address equal to GVSB_MAGIC_PARTIAL. */
if (memcmp(cleared_dict.u.s.y, dict->u.s.y, sizeof cleared_dict.u.s.y))
return FALSE;
g_variant_dict_init(dict, dict->u.s.asv);
}
return is_valid_dict(dict);
}
/**
* g_variant_dict_new:
* @from_asv: (nullable): the #GVariant with which to initialise the
* dictionary
*
* Allocates and initialises a new #GVariantDict.
*
* You should call g_variant_dict_unref() on the return value when it
* is no longer needed. The memory will not be automatically freed by
* any other call.
*
* In some cases it may be easier to place a #GVariantDict directly on
* the stack of the calling function and initialise it with
* g_variant_dict_init(). This is particularly useful when you are
* using #GVariantDict to construct a #GVariant.
*
* Returns: (transfer full): a #GVariantDict
*
* Since: 2.40
**/
GVariantDict* g_variant_dict_new(GVariant* from_asv)
{
GVariantDict* dict;
dict = g_slice_alloc(sizeof(struct heap_dict));
g_variant_dict_init(dict, from_asv);
GVHD(dict)->magic = GVHD_MAGIC;
GVHD(dict)->ref_count = 1;
return dict;
}
/**
* g_variant_dict_init: (skip)
* @dict: a #GVariantDict
* @from_asv: (nullable): the initial value for @dict
*
* Initialises a #GVariantDict structure.
*
* If @from_asv is given, it is used to initialise the dictionary.
*
* This function completely ignores the previous contents of @dict. On
* one hand this means that it is valid to pass in completely
* uninitialised memory. On the other hand, this means that if you are
* initialising over top of an existing #GVariantDict you need to first
* call g_variant_dict_clear() in order to avoid leaking memory.
*
* You must not call g_variant_dict_ref() or g_variant_dict_unref() on a
* #GVariantDict that was initialised with this function. If you ever
* pass a reference to a #GVariantDict outside of the control of your
* own code then you should assume that the person receiving that
* reference may try to use reference counting; you should use
* g_variant_dict_new() instead of this function.
*
* Since: 2.40
**/
void g_variant_dict_init(GVariantDict* dict, GVariant* from_asv)
{
GVariantIter iter;
gchar* key;
GVariant* value;
GVSD(dict)->values = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
(GDestroyNotify)g_variant_unref);
GVSD(dict)->magic = GVSD_MAGIC;
if (from_asv)
{
g_variant_iter_init(&iter, from_asv);
while (g_variant_iter_next(&iter, "{sv}", &key, &value))
g_hash_table_insert(GVSD(dict)->values, key, value);
}
}
/**
* g_variant_dict_lookup:
* @dict: a #GVariantDict
* @key: the key to lookup in the dictionary
* @format_string: a GVariant format string
* @...: the arguments to unpack the value into
*
* Looks up a value in a #GVariantDict.
*
* This function is a wrapper around g_variant_dict_lookup_value() and
* g_variant_get(). In the case that %NULL would have been returned,
* this function returns %FALSE. Otherwise, it unpacks the returned
* value and returns %TRUE.
*
* @format_string determines the C types that are used for unpacking the
* values and also determines if the values are copied or borrowed, see the
* section on [GVariant format strings][gvariant-format-strings-pointers].
*
* Returns: %TRUE if a value was unpacked
*
* Since: 2.40
**/
gboolean g_variant_dict_lookup(GVariantDict* dict, const gchar* key,
const gchar* format_string, ...)
{
GVariant* value;
va_list ap;
g_return_val_if_fail(ensure_valid_dict(dict), FALSE);
g_return_val_if_fail(key != NULL, FALSE);
g_return_val_if_fail(format_string != NULL, FALSE);
value = g_hash_table_lookup(GVSD(dict)->values, key);
if (value == NULL ||
!g_variant_check_format_string(value, format_string, FALSE))
return FALSE;
va_start(ap, format_string);
g_variant_get_va(value, format_string, NULL, &ap);
va_end(ap);
return TRUE;
}
/**
* g_variant_dict_lookup_value:
* @dict: a #GVariantDict
* @key: the key to lookup in the dictionary
* @expected_type: (nullable): a #GVariantType, or %NULL
*
* Looks up a value in a #GVariantDict.
*
* If @key is not found in @dictionary, %NULL is returned.
*
* The @expected_type string specifies what type of value is expected.
* If the value associated with @key has a different type then %NULL is
* returned.
*
* If the key is found and the value has the correct type, it is
* returned. If @expected_type was specified then any non-%NULL return
* value will have this type.
*
* Returns: (transfer full): the value of the dictionary key, or %NULL
*
* Since: 2.40
**/
GVariant* g_variant_dict_lookup_value(GVariantDict* dict, const gchar* key,
const GVariantType* expected_type)
{
GVariant* result;
g_return_val_if_fail(ensure_valid_dict(dict), NULL);
g_return_val_if_fail(key != NULL, NULL);
result = g_hash_table_lookup(GVSD(dict)->values, key);
if (result &&
(!expected_type || g_variant_is_of_type(result, expected_type)))
return g_variant_ref(result);
return NULL;
}
/**
* g_variant_dict_contains:
* @dict: a #GVariantDict
* @key: the key to lookup in the dictionary
*
* Checks if @key exists in @dict.
*
* Returns: %TRUE if @key is in @dict
*
* Since: 2.40
**/
gboolean g_variant_dict_contains(GVariantDict* dict, const gchar* key)
{
g_return_val_if_fail(ensure_valid_dict(dict), FALSE);
g_return_val_if_fail(key != NULL, FALSE);
return g_hash_table_contains(GVSD(dict)->values, key);
}
/**
* g_variant_dict_insert:
* @dict: a #GVariantDict
* @key: the key to insert a value for
* @format_string: a #GVariant varargs format string
* @...: arguments, as per @format_string
*
* Inserts a value into a #GVariantDict.
*
* This call is a convenience wrapper that is exactly equivalent to
* calling g_variant_new() followed by g_variant_dict_insert_value().
*
* Since: 2.40
**/
void g_variant_dict_insert(GVariantDict* dict, const gchar* key,
const gchar* format_string, ...)
{
va_list ap;
g_return_if_fail(ensure_valid_dict(dict));
g_return_if_fail(key != NULL);
g_return_if_fail(format_string != NULL);
va_start(ap, format_string);
g_variant_dict_insert_value(dict, key,
g_variant_new_va(format_string, NULL, &ap));
va_end(ap);
}
/**
* g_variant_dict_insert_value:
* @dict: a #GVariantDict
* @key: the key to insert a value for
* @value: the value to insert
*
* Inserts (or replaces) a key in a #GVariantDict.
*
* @value is consumed if it is floating.
*
* Since: 2.40
**/
void g_variant_dict_insert_value(GVariantDict* dict, const gchar* key,
GVariant* value)
{
g_return_if_fail(ensure_valid_dict(dict));
g_return_if_fail(key != NULL);
g_return_if_fail(value != NULL);
g_hash_table_insert(GVSD(dict)->values, g_strdup(key),
g_variant_ref_sink(value));
}
/**
* g_variant_dict_remove:
* @dict: a #GVariantDict
* @key: the key to remove
*
* Removes a key and its associated value from a #GVariantDict.
*
* Returns: %TRUE if the key was found and removed
*
* Since: 2.40
**/
gboolean g_variant_dict_remove(GVariantDict* dict, const gchar* key)
{
g_return_val_if_fail(ensure_valid_dict(dict), FALSE);
g_return_val_if_fail(key != NULL, FALSE);
return g_hash_table_remove(GVSD(dict)->values, key);
}
/**
* g_variant_dict_clear:
* @dict: a #GVariantDict
*
* Releases all memory associated with a #GVariantDict without freeing
* the #GVariantDict structure itself.
*
* It typically only makes sense to do this on a stack-allocated
* #GVariantDict if you want to abort building the value part-way
* through. This function need not be called if you call
* g_variant_dict_end() and it also doesn't need to be called on dicts
* allocated with g_variant_dict_new (see g_variant_dict_unref() for
* that).
*
* It is valid to call this function on either an initialised
* #GVariantDict or one that was previously cleared by an earlier call
* to g_variant_dict_clear() but it is not valid to call this function
* on uninitialised memory.
*
* Since: 2.40
**/
void g_variant_dict_clear(GVariantDict* dict)
{
if (GVSD(dict)->magic == 0)
/* all-zeros case */
return;
g_return_if_fail(ensure_valid_dict(dict));
g_hash_table_unref(GVSD(dict)->values);
GVSD(dict)->values = NULL;
GVSD(dict)->magic = 0;
}
/**
* g_variant_dict_end:
* @dict: a #GVariantDict
*
* Returns the current value of @dict as a #GVariant of type
* %G_VARIANT_TYPE_VARDICT, clearing it in the process.
*
* It is not permissible to use @dict in any way after this call except
* for reference counting operations (in the case of a heap-allocated
* #GVariantDict) or by reinitialising it with g_variant_dict_init() (in
* the case of stack-allocated).
*
* Returns: (transfer none): a new, floating, #GVariant
*
* Since: 2.40
**/
GVariant* g_variant_dict_end(GVariantDict* dict)
{
GVariantBuilder builder;
GHashTableIter iter;
gpointer key, value;
g_return_val_if_fail(ensure_valid_dict(dict), NULL);
g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
g_hash_table_iter_init(&iter, GVSD(dict)->values);
while (g_hash_table_iter_next(&iter, &key, &value))
g_variant_builder_add(&builder, "{sv}", (const gchar*)key,
(GVariant*)value);
g_variant_dict_clear(dict);
return g_variant_builder_end(&builder);
}
/**
* g_variant_dict_ref:
* @dict: a heap-allocated #GVariantDict
*
* Increases the reference count on @dict.
*
* Don't call this on stack-allocated #GVariantDict instances or bad
* things will happen.
*
* Returns: (transfer full): a new reference to @dict
*
* Since: 2.40
**/
GVariantDict* g_variant_dict_ref(GVariantDict* dict)
{
g_return_val_if_fail(is_valid_heap_dict(dict), NULL);
GVHD(dict)->ref_count++;
return dict;
}
/**
* g_variant_dict_unref:
* @dict: (transfer full): a heap-allocated #GVariantDict
*
* Decreases the reference count on @dict.
*
* In the event that there are no more references, releases all memory
* associated with the #GVariantDict.
*
* Don't call this on stack-allocated #GVariantDict instances or bad
* things will happen.
*
* Since: 2.40
**/
void g_variant_dict_unref(GVariantDict* dict)
{
g_return_if_fail(is_valid_heap_dict(dict));
if (--GVHD(dict)->ref_count == 0)
{
g_variant_dict_clear(dict);
g_slice_free(struct heap_dict, (struct heap_dict*)dict);
}
}
/* Format strings {{{1 */
/*< private >
* g_variant_format_string_scan:
* @string: a string that may be prefixed with a format string
* @limit: (nullable) (default NULL): a pointer to the end of @string,
* or %NULL
* @endptr: (nullable) (default NULL): location to store the end pointer,
* or %NULL
*
* Checks the string pointed to by @string for starting with a properly
* formed #GVariant varargs format string. If no valid format string is
* found then %FALSE is returned.
*
* If @string does start with a valid format string then %TRUE is
* returned. If @endptr is non-%NULL then it is updated to point to the
* first character after the format string.
*
* If @limit is non-%NULL then @limit (and any character after it) will
* not be accessed and the effect is otherwise equivalent to if the
* character at @limit were nul.
*
* See the section on [GVariant format strings][gvariant-format-strings].
*
* Returns: %TRUE if there was a valid format string
*
* Since: 2.24
*/
gboolean g_variant_format_string_scan(const gchar* string, const gchar* limit,
const gchar** endptr)
{
#define next_char() (string == limit ? '\0' : *string++)
#define peek_char() (string == limit ? '\0' : *string)
char c;
switch (next_char())
{
case 'b':
case 'y':
case 'n':
case 'q':
case 'i':
case 'u':
case 'x':
case 't':
case 'h':
case 'd':
case 's':
case 'o':
case 'g':
case 'v':
case '*':
case '?':
case 'r':
break;
case 'm':
return g_variant_format_string_scan(string, limit, endptr);
case 'a':
case '@':
return g_variant_type_string_scan(string, limit, endptr);
case '(':
while (peek_char() != ')')
if (!g_variant_format_string_scan(string, limit, &string))
return FALSE;
next_char(); /* consume ')' */
break;
case '{':
c = next_char();
if (c == '&')
{
c = next_char();
if (c != 's' && c != 'o' && c != 'g')
return FALSE;
}
else
{
if (c == '@')
c = next_char();
/* ISO/IEC 9899:1999 (C99) §7.21.5.2:
* The terminating null character is considered to be
* part of the string.
*/
if (c != '\0' && strchr("bynqiuxthdsog?", c) == NULL)
return FALSE;
}
if (!g_variant_format_string_scan(string, limit, &string))
return FALSE;
if (next_char() != '}')
return FALSE;
break;
case '^':
if ((c = next_char()) == 'a')
{
if ((c = next_char()) == '&')
{
if ((c = next_char()) == 'a')
{
if ((c = next_char()) == 'y')
break; /* '^a&ay' */
}
else if (c == 's' || c == 'o')
break; /* '^a&s', '^a&o' */
}
else if (c == 'a')
{
if ((c = next_char()) == 'y')
break; /* '^aay' */
}
else if (c == 's' || c == 'o')
break; /* '^as', '^ao' */
else if (c == 'y')
break; /* '^ay' */
}
else if (c == '&')
{
if ((c = next_char()) == 'a')
{
if ((c = next_char()) == 'y')
break; /* '^&ay' */
}
}
return FALSE;
case '&':
c = next_char();
if (c != 's' && c != 'o' && c != 'g')
return FALSE;
break;
default:
return FALSE;
}
if (endptr != NULL)
*endptr = string;
#undef next_char
#undef peek_char
return TRUE;
}
/**
* g_variant_check_format_string:
* @value: a #GVariant
* @format_string: a valid #GVariant format string
* @copy_only: %TRUE to ensure the format string makes deep copies
*
* Checks if calling g_variant_get() with @format_string on @value would
* be valid from a type-compatibility standpoint. @format_string is
* assumed to be a valid format string (from a syntactic standpoint).
*
* If @copy_only is %TRUE then this function additionally checks that it
* would be safe to call g_variant_unref() on @value immediately after
* the call to g_variant_get() without invalidating the result. This is
* only possible if deep copies are made (ie: there are no pointers to
* the data inside of the soon-to-be-freed #GVariant instance). If this
* check fails then a g_critical() is printed and %FALSE is returned.
*
* This function is meant to be used by functions that wish to provide
* varargs accessors to #GVariant values of uncertain values (eg:
* g_variant_lookup() or g_menu_model_get_item_attribute()).
*
* Returns: %TRUE if @format_string is safe to use
*
* Since: 2.34
*/
gboolean g_variant_check_format_string(GVariant* value,
const gchar* format_string,
gboolean copy_only)
{
const gchar* original_format = format_string;
const gchar* type_string;
/* Interesting factoid: assuming a format string is valid, it can be
* converted to a type string by removing all '@' '&' and '^'
* characters.
*
* Instead of doing that, we can just skip those characters when
* comparing it to the type string of @value.
*
* For the copy-only case we can just drop the '&' from the list of
* characters to skip over. A '&' will never appear in a type string
* so we know that it won't be possible to return %TRUE if it is in a
* format string.
*/
type_string = g_variant_get_type_string(value);
while (*type_string || *format_string)
{
gchar format = *format_string++;
switch (format)
{
case '&':
if
G_UNLIKELY(copy_only)
{
/* for the love of all that is good, please don't mark
* this string for translation... */
g_critical(
"g_variant_check_format_string() is being called "
"by a function with a GVariant varargs "
"interface to validate the passed format string "
"for type safety. The passed format "
"(%s) contains a '&' character which would result "
"in a pointer being returned to the "
"data inside of a GVariant instance that may no "
"longer exist by the time the function "
"returns. Modify your code to use a format string "
"without '&'.",
original_format);
return FALSE;
}
/* fall through */
case '^':
case '@':
/* ignore these 2 (or 3) */
continue;
case '?':
/* attempt to consume one of 'bynqiuxthdsog' */
{
char s = *type_string++;
if (s == '\0' || strchr("bynqiuxthdsog", s) == NULL)
return FALSE;
}
continue;
case 'r':
/* ensure it's a tuple */
if (*type_string != '(')
return FALSE;
/* fall through */
case '*':
/* consume a full type string for the '*' or 'r' */
if (!g_variant_type_string_scan(type_string, NULL,
&type_string))
return FALSE;
continue;
default:
/* attempt to consume exactly one character equal to the format
*/
if (format != *type_string++)
return FALSE;
}
}
return TRUE;
}
/*< private >
* g_variant_format_string_scan_type:
* @string: a string that may be prefixed with a format string
* @limit: (nullable) (default NULL): a pointer to the end of @string,
* or %NULL
* @endptr: (nullable) (default NULL): location to store the end pointer,
* or %NULL
*
* If @string starts with a valid format string then this function will
* return the type that the format string corresponds to. Otherwise
* this function returns %NULL.
*
* Use g_variant_type_free() to free the return value when you no longer
* need it.
*
* This function is otherwise exactly like
* g_variant_format_string_scan().
*
* Returns: (nullable): a #GVariantType if there was a valid format string
*
* Since: 2.24
*/
GVariantType* g_variant_format_string_scan_type(const gchar* string,
const gchar* limit,
const gchar** endptr)
{
const gchar* my_end;
gchar* dest;
gchar* new;
if (endptr == NULL)
endptr = &my_end;
if (!g_variant_format_string_scan(string, limit, endptr))
return NULL;
dest = new = g_malloc(*endptr - string + 1);
while (string != *endptr)
{
if (*string != '@' && *string != '&' && *string != '^')
*dest++ = *string;
string++;
}
*dest = '\0';
return (GVariantType*)G_VARIANT_TYPE(new);
}
static gboolean valid_format_string(const gchar* format_string, gboolean single,
GVariant* value)
{
const gchar* endptr;
GVariantType* type;
type = g_variant_format_string_scan_type(format_string, NULL, &endptr);
if
G_UNLIKELY(type == NULL || (single && *endptr != '\0'))
{
if (single)
g_critical("'%s' is not a valid GVariant format string",
format_string);
else
g_critical("'%s' does not have a valid GVariant format "
"string as a prefix",
format_string);
if (type != NULL)
g_variant_type_free(type);
return FALSE;
}
if
G_UNLIKELY(value && !g_variant_is_of_type(value, type))
{
gchar* fragment;
gchar* typestr;
fragment = g_strndup(format_string, endptr - format_string);
typestr = g_variant_type_dup_string(type);
g_critical("the GVariant format string '%s' has a type of "
"'%s' but the given value has a type of '%s'",
fragment, typestr, g_variant_get_type_string(value));
g_variant_type_free(type);
g_free(fragment);
g_free(typestr);
return FALSE;
}
g_variant_type_free(type);
return TRUE;
}
/* Variable Arguments {{{1 */
/* We consider 2 main classes of format strings:
*
* - recursive format strings
* these are ones that result in recursion and the collection of
* possibly more than one argument. Maybe types, tuples,
* dictionary entries.
*
* - leaf format string
* these result in the collection of a single argument.
*
* Leaf format strings are further subdivided into two categories:
*
* - single non-null pointer ("nnp")
* these either collect or return a single non-null pointer.
*
* - other
* these collect or return something else (bool, number, etc).
*
* Based on the above, the varargs handling code is split into 4 main parts:
*
* - nnp handling code
* - leaf handling code (which may invoke nnp code)
* - generic handling code (may be recursive, may invoke leaf code)
* - user-facing API (which invokes the generic code)
*
* Each section implements some of the following functions:
*
* - skip:
* collect the arguments for the format string as if
* g_variant_new() had been called, but do nothing with them. used
* for skipping over arguments when constructing a Nothing maybe
* type.
*
* - new:
* create a GVariant *
*
* - get:
* unpack a GVariant *
*
* - free (nnp only):
* free a previously allocated item
*/
static gboolean g_variant_format_string_is_leaf(const gchar* str)
{
return str[0] != 'm' && str[0] != '(' && str[0] != '{';
}
static gboolean g_variant_format_string_is_nnp(const gchar* str)
{
return str[0] == 'a' || str[0] == 's' || str[0] == 'o' || str[0] == 'g' ||
str[0] == '^' || str[0] == '@' || str[0] == '*' || str[0] == '?' ||
str[0] == 'r' || str[0] == 'v' || str[0] == '&';
}
/* Single non-null pointer ("nnp") {{{2 */
static void g_variant_valist_free_nnp(const gchar* str, gpointer ptr)
{
switch (*str)
{
case 'a':
g_variant_iter_free(ptr);
break;
case '^':
if (g_str_has_suffix(str, "y"))
{
if (str[2] != 'a') /* '^a&ay', '^ay' */
g_free(ptr);
else if (str[1] == 'a') /* '^aay' */
g_strfreev(ptr);
break; /* '^&ay' */
}
else if (str[2] != '&') /* '^as', '^ao' */
g_strfreev(ptr);
else /* '^a&s', '^a&o' */
g_free(ptr);
break;
case 's':
case 'o':
case 'g':
g_free(ptr);
break;
case '@':
case '*':
case '?':
case 'v':
g_variant_unref(ptr);
break;
case '&':
break;
default:
g_assert_not_reached();
}
}
static gchar g_variant_scan_convenience(const gchar** str, gboolean* constant,
guint* arrays)
{
*constant = FALSE;
*arrays = 0;
for (;;)
{
char c = *(*str)++;
if (c == '&')
*constant = TRUE;
else if (c == 'a')
(*arrays)++;
else
return c;
}
}
static GVariant* g_variant_valist_new_nnp(const gchar** str, gpointer ptr)
{
if (**str == '&')
(*str)++;
switch (*(*str)++)
{
case 'a':
if (ptr != NULL)
{
const GVariantType* type;
GVariant* value;
value = g_variant_builder_end(ptr);
type = g_variant_get_type(value);
if
G_UNLIKELY(!g_variant_type_is_array(type))
g_error("g_variant_new: expected array GVariantBuilder but "
"the built value has type '%s'",
g_variant_get_type_string(value));
type = g_variant_type_element(type);
if
G_UNLIKELY(!g_variant_type_is_subtype_of(
type, (GVariantType*)*str))
{
gchar* type_string =
g_variant_type_dup_string((GVariantType*)*str);
g_error("g_variant_new: expected GVariantBuilder array "
"element "
"type '%s' but the built value has element "
"type '%s'",
type_string,
g_variant_get_type_string(value) + 1);
g_free(type_string);
}
g_variant_type_string_scan(*str, NULL, str);
return value;
}
else
/* special case: NULL pointer for empty array */
{
const GVariantType* type = (GVariantType*)*str;
g_variant_type_string_scan(*str, NULL, str);
if
G_UNLIKELY(!g_variant_type_is_definite(type))
g_error("g_variant_new: NULL pointer given with indefinite "
"array type; unable to determine which type of empty "
"array to construct.");
return g_variant_new_array(type, NULL, 0);
}
case 's':
{
GVariant* value;
value = g_variant_new_string(ptr);
if (value == NULL)
value = g_variant_new_string("[Invalid UTF-8]");
return value;
}
case 'o':
return g_variant_new_object_path(ptr);
case 'g':
return g_variant_new_signature(ptr);
case '^':
{
gboolean constant;
guint arrays;
gchar type;
type = g_variant_scan_convenience(str, &constant, &arrays);
if (type == 's')
return g_variant_new_strv(ptr, -1);
if (type == 'o')
return g_variant_new_objv(ptr, -1);
if (arrays > 1)
return g_variant_new_bytestring_array(ptr, -1);
return g_variant_new_bytestring(ptr);
}
case '@':
if
G_UNLIKELY(!g_variant_is_of_type(ptr, (GVariantType*)*str))
{
gchar* type_string =
g_variant_type_dup_string((GVariantType*)*str);
g_error("g_variant_new: expected GVariant of type '%s' but "
"received value has type '%s'",
type_string, g_variant_get_type_string(ptr));
g_free(type_string);
}
g_variant_type_string_scan(*str, NULL, str);
return ptr;
case '*':
return ptr;
case '?':
if
G_UNLIKELY(!g_variant_type_is_basic(g_variant_get_type(ptr)))
g_error("g_variant_new: format string '?' expects basic-typed "
"GVariant, but received value has type '%s'",
g_variant_get_type_string(ptr));
return ptr;
case 'r':
if
G_UNLIKELY(!g_variant_type_is_tuple(g_variant_get_type(ptr)))
g_error("g_variant_new: format string 'r' expects tuple-typed "
"GVariant, but received value has type '%s'",
g_variant_get_type_string(ptr));
return ptr;
case 'v':
return g_variant_new_variant(ptr);
default:
g_assert_not_reached();
}
}
static gpointer g_variant_valist_get_nnp(const gchar** str, GVariant* value)
{
switch (*(*str)++)
{
case 'a':
g_variant_type_string_scan(*str, NULL, str);
return g_variant_iter_new(value);
case '&':
(*str)++;
return (gchar*)g_variant_get_string(value, NULL);
case 's':
case 'o':
case 'g':
return g_variant_dup_string(value, NULL);
case '^':
{
gboolean constant;
guint arrays;
gchar type;
type = g_variant_scan_convenience(str, &constant, &arrays);
if (type == 's')
{
if (constant)
return g_variant_get_strv(value, NULL);
else
return g_variant_dup_strv(value, NULL);
}
else if (type == 'o')
{
if (constant)
return g_variant_get_objv(value, NULL);
else
return g_variant_dup_objv(value, NULL);
}
else if (arrays > 1)
{
if (constant)
return g_variant_get_bytestring_array(value, NULL);
else
return g_variant_dup_bytestring_array(value, NULL);
}
else
{
if (constant)
return (gchar*)g_variant_get_bytestring(value);
else
return g_variant_dup_bytestring(value, NULL);
}
}
case '@':
g_variant_type_string_scan(*str, NULL, str);
/* fall through */
case '*':
case '?':
case 'r':
return g_variant_ref(value);
case 'v':
return g_variant_get_variant(value);
default:
g_assert_not_reached();
}
}
/* Leaves {{{2 */
static void g_variant_valist_skip_leaf(const gchar** str, va_list* app)
{
if (g_variant_format_string_is_nnp(*str))
{
g_variant_format_string_scan(*str, NULL, str);
va_arg(*app, gpointer);
return;
}
switch (*(*str)++)
{
case 'b':
case 'y':
case 'n':
case 'q':
case 'i':
case 'u':
case 'h':
va_arg(*app, int);
return;
case 'x':
case 't':
va_arg(*app, guint64);
return;
case 'd':
va_arg(*app, gdouble);
return;
default:
g_assert_not_reached();
}
}
static GVariant* g_variant_valist_new_leaf(const gchar** str, va_list* app)
{
if (g_variant_format_string_is_nnp(*str))
return g_variant_valist_new_nnp(str, va_arg(*app, gpointer));
switch (*(*str)++)
{
case 'b':
return g_variant_new_boolean(va_arg(*app, gboolean));
case 'y':
return g_variant_new_byte(va_arg(*app, guint));
case 'n':
return g_variant_new_int16(va_arg(*app, gint));
case 'q':
return g_variant_new_uint16(va_arg(*app, guint));
case 'i':
return g_variant_new_int32(va_arg(*app, gint));
case 'u':
return g_variant_new_uint32(va_arg(*app, guint));
case 'x':
return g_variant_new_int64(va_arg(*app, gint64));
case 't':
return g_variant_new_uint64(va_arg(*app, guint64));
case 'h':
return g_variant_new_handle(va_arg(*app, gint));
case 'd':
return g_variant_new_double(va_arg(*app, gdouble));
default:
g_assert_not_reached();
}
}
/* The code below assumes this */
G_STATIC_ASSERT(sizeof(gboolean) == sizeof(guint32));
G_STATIC_ASSERT(sizeof(gdouble) == sizeof(guint64));
static void g_variant_valist_get_leaf(const gchar** str, GVariant* value,
gboolean free, va_list* app)
{
gpointer ptr = va_arg(*app, gpointer);
if (ptr == NULL)
{
g_variant_format_string_scan(*str, NULL, str);
return;
}
if (g_variant_format_string_is_nnp(*str))
{
gpointer* nnp = (gpointer*)ptr;
if (free && *nnp != NULL)
g_variant_valist_free_nnp(*str, *nnp);
*nnp = NULL;
if (value != NULL)
*nnp = g_variant_valist_get_nnp(str, value);
else
g_variant_format_string_scan(*str, NULL, str);
return;
}
if (value != NULL)
{
switch (*(*str)++)
{
case 'b':
*(gboolean*)ptr = g_variant_get_boolean(value);
return;
case 'y':
*(guint8*)ptr = g_variant_get_byte(value);
return;
case 'n':
*(gint16*)ptr = g_variant_get_int16(value);
return;
case 'q':
*(guint16*)ptr = g_variant_get_uint16(value);
return;
case 'i':
*(gint32*)ptr = g_variant_get_int32(value);
return;
case 'u':
*(guint32*)ptr = g_variant_get_uint32(value);
return;
case 'x':
*(gint64*)ptr = g_variant_get_int64(value);
return;
case 't':
*(guint64*)ptr = g_variant_get_uint64(value);
return;
case 'h':
*(gint32*)ptr = g_variant_get_handle(value);
return;
case 'd':
*(gdouble*)ptr = g_variant_get_double(value);
return;
}
}
else
{
switch (*(*str)++)
{
case 'y':
*(guint8*)ptr = 0;
return;
case 'n':
case 'q':
*(guint16*)ptr = 0;
return;
case 'i':
case 'u':
case 'h':
case 'b':
*(guint32*)ptr = 0;
return;
case 'x':
case 't':
case 'd':
*(guint64*)ptr = 0;
return;
}
}
g_assert_not_reached();
}
/* Generic (recursive) {{{2 */
static void g_variant_valist_skip(const gchar** str, va_list* app)
{
if (g_variant_format_string_is_leaf(*str))
g_variant_valist_skip_leaf(str, app);
else if (**str == 'm') /* maybe */
{
(*str)++;
if (!g_variant_format_string_is_nnp(*str))
va_arg(*app, gboolean);
g_variant_valist_skip(str, app);
}
else /* tuple, dictionary entry */
{
g_assert(**str == '(' || **str == '{');
(*str)++;
while (**str != ')' && **str != '}')
g_variant_valist_skip(str, app);
(*str)++;
}
}
static GVariant* g_variant_valist_new(const gchar** str, va_list* app)
{
if (g_variant_format_string_is_leaf(*str))
return g_variant_valist_new_leaf(str, app);
if (**str == 'm') /* maybe */
{
GVariantType* type = NULL;
GVariant* value = NULL;
(*str)++;
if (g_variant_format_string_is_nnp(*str))
{
gpointer nnp = va_arg(*app, gpointer);
if (nnp != NULL)
value = g_variant_valist_new_nnp(str, nnp);
else
type = g_variant_format_string_scan_type(*str, NULL, str);
}
else
{
gboolean just = va_arg(*app, gboolean);
if (just)
value = g_variant_valist_new(str, app);
else
{
type = g_variant_format_string_scan_type(*str, NULL, NULL);
g_variant_valist_skip(str, app);
}
}
value = g_variant_new_maybe(type, value);
if (type != NULL)
g_variant_type_free(type);
return value;
}
else /* tuple, dictionary entry */
{
GVariantBuilder b;
if (**str == '(')
g_variant_builder_init(&b, G_VARIANT_TYPE_TUPLE);
else
{
g_assert(**str == '{');
g_variant_builder_init(&b, G_VARIANT_TYPE_DICT_ENTRY);
}
(*str)++; /* '(' */
while (**str != ')' && **str != '}')
g_variant_builder_add_value(&b, g_variant_valist_new(str, app));
(*str)++; /* ')' */
return g_variant_builder_end(&b);
}
}
static void g_variant_valist_get(const gchar** str, GVariant* value,
gboolean free, va_list* app)
{
if (g_variant_format_string_is_leaf(*str))
g_variant_valist_get_leaf(str, value, free, app);
else if (**str == 'm')
{
(*str)++;
if (value != NULL)
value = g_variant_get_maybe(value);
if (!g_variant_format_string_is_nnp(*str))
{
gboolean* ptr = va_arg(*app, gboolean*);
if (ptr != NULL)
*ptr = value != NULL;
}
g_variant_valist_get(str, value, free, app);
if (value != NULL)
g_variant_unref(value);
}
else /* tuple, dictionary entry */
{
gint index = 0;
g_assert(**str == '(' || **str == '{');
(*str)++;
while (**str != ')' && **str != '}')
{
if (value != NULL)
{
GVariant* child = g_variant_get_child_value(value, index++);
g_variant_valist_get(str, child, free, app);
g_variant_unref(child);
}
else
g_variant_valist_get(str, NULL, free, app);
}
(*str)++;
}
}
/* User-facing API {{{2 */
/**
* g_variant_new: (skip)
* @format_string: a #GVariant format string
* @...: arguments, as per @format_string
*
* Creates a new #GVariant instance.
*
* Think of this function as an analogue to g_strdup_printf().
*
* The type of the created instance and the arguments that are expected
* by this function are determined by @format_string. See the section on
* [GVariant format strings][gvariant-format-strings]. Please note that
* the syntax of the format string is very likely to be extended in the
* future.
*
* The first character of the format string must not be '*' '?' '@' or
* 'r'; in essence, a new #GVariant must always be constructed by this
* function (and not merely passed through it unmodified).
*
* Note that the arguments must be of the correct width for their types
* specified in @format_string. This can be achieved by casting them. See
* the [GVariant varargs documentation][gvariant-varargs].
*
* |[<!-- language="C" -->
* MyFlags some_flags = FLAG_ONE | FLAG_TWO;
* const gchar *some_strings[] = { "a", "b", "c", NULL };
* GVariant *new_variant;
*
* new_variant = g_variant_new ("(t^as)",
* // This cast is required.
* (guint64) some_flags,
* some_strings);
* ]|
*
* Returns: a new floating #GVariant instance
*
* Since: 2.24
**/
GVariant* g_variant_new(const gchar* format_string, ...)
{
GVariant* value;
va_list ap;
g_return_val_if_fail(valid_format_string(format_string, TRUE, NULL) &&
format_string[0] != '?' &&
format_string[0] != '@' &&
format_string[0] != '*' && format_string[0] != 'r',
NULL);
va_start(ap, format_string);
value = g_variant_new_va(format_string, NULL, &ap);
va_end(ap);
return value;
}
/**
* g_variant_new_va: (skip)
* @format_string: a string that is prefixed with a format string
* @endptr: (nullable) (default NULL): location to store the end pointer,
* or %NULL
* @app: a pointer to a #va_list
*
* This function is intended to be used by libraries based on
* #GVariant that want to provide g_variant_new()-like functionality
* to their users.
*
* The API is more general than g_variant_new() to allow a wider range
* of possible uses.
*
* @format_string must still point to a valid format string, but it only
* needs to be nul-terminated if @endptr is %NULL. If @endptr is
* non-%NULL then it is updated to point to the first character past the
* end of the format string.
*
* @app is a pointer to a #va_list. The arguments, according to
* @format_string, are collected from this #va_list and the list is left
* pointing to the argument following the last.
*
* Note that the arguments in @app must be of the correct width for their
* types specified in @format_string when collected into the #va_list.
* See the [GVariant varargs documentation][gvariant-varargs].
*
* These two generalisations allow mixing of multiple calls to
* g_variant_new_va() and g_variant_get_va() within a single actual
* varargs call by the user.
*
* The return value will be floating if it was a newly created GVariant
* instance (for example, if the format string was "(ii)"). In the case
* that the format_string was '*', '?', 'r', or a format starting with
* '@' then the collected #GVariant pointer will be returned unmodified,
* without adding any additional references.
*
* In order to behave correctly in all cases it is necessary for the
* calling function to g_variant_ref_sink() the return result before
* returning control to the user that originally provided the pointer.
* At this point, the caller will have their own full reference to the
* result. This can also be done by adding the result to a container,
* or by passing it to another g_variant_new() call.
*
* Returns: a new, usually floating, #GVariant
*
* Since: 2.24
**/
GVariant* g_variant_new_va(const gchar* format_string, const gchar** endptr,
va_list* app)
{
GVariant* value;
g_return_val_if_fail(valid_format_string(format_string, !endptr, NULL),
NULL);
g_return_val_if_fail(app != NULL, NULL);
value = g_variant_valist_new(&format_string, app);
if (endptr != NULL)
*endptr = format_string;
return value;
}
/**
* g_variant_get: (skip)
* @value: a #GVariant instance
* @format_string: a #GVariant format string
* @...: arguments, as per @format_string
*
* Deconstructs a #GVariant instance.
*
* Think of this function as an analogue to scanf().
*
* The arguments that are expected by this function are entirely
* determined by @format_string. @format_string also restricts the
* permissible types of @value. It is an error to give a value with
* an incompatible type. See the section on
* [GVariant format strings][gvariant-format-strings].
* Please note that the syntax of the format string is very likely to be
* extended in the future.
*
* @format_string determines the C types that are used for unpacking
* the values and also determines if the values are copied or borrowed,
* see the section on
* [GVariant format strings][gvariant-format-strings-pointers].
*
* Since: 2.24
**/
void g_variant_get(GVariant* value, const gchar* format_string, ...)
{
va_list ap;
g_return_if_fail(valid_format_string(format_string, TRUE, value));
/* if any direct-pointer-access formats are in use, flatten first */
if (strchr(format_string, '&'))
g_variant_get_data(value);
va_start(ap, format_string);
g_variant_get_va(value, format_string, NULL, &ap);
va_end(ap);
}
/**
* g_variant_get_va: (skip)
* @value: a #GVariant
* @format_string: a string that is prefixed with a format string
* @endptr: (nullable) (default NULL): location to store the end pointer,
* or %NULL
* @app: a pointer to a #va_list
*
* This function is intended to be used by libraries based on #GVariant
* that want to provide g_variant_get()-like functionality to their
* users.
*
* The API is more general than g_variant_get() to allow a wider range
* of possible uses.
*
* @format_string must still point to a valid format string, but it only
* need to be nul-terminated if @endptr is %NULL. If @endptr is
* non-%NULL then it is updated to point to the first character past the
* end of the format string.
*
* @app is a pointer to a #va_list. The arguments, according to
* @format_string, are collected from this #va_list and the list is left
* pointing to the argument following the last.
*
* These two generalisations allow mixing of multiple calls to
* g_variant_new_va() and g_variant_get_va() within a single actual
* varargs call by the user.
*
* @format_string determines the C types that are used for unpacking
* the values and also determines if the values are copied or borrowed,
* see the section on
* [GVariant format strings][gvariant-format-strings-pointers].
*
* Since: 2.24
**/
void g_variant_get_va(GVariant* value, const gchar* format_string,
const gchar** endptr, va_list* app)
{
g_return_if_fail(valid_format_string(format_string, !endptr, value));
g_return_if_fail(value != NULL);
g_return_if_fail(app != NULL);
/* if any direct-pointer-access formats are in use, flatten first */
if (strchr(format_string, '&'))
g_variant_get_data(value);
g_variant_valist_get(&format_string, value, FALSE, app);
if (endptr != NULL)
*endptr = format_string;
}
/* Varargs-enabled Utility Functions {{{1 */
/**
* g_variant_builder_add: (skip)
* @builder: a #GVariantBuilder
* @format_string: a #GVariant varargs format string
* @...: arguments, as per @format_string
*
* Adds to a #GVariantBuilder.
*
* This call is a convenience wrapper that is exactly equivalent to
* calling g_variant_new() followed by g_variant_builder_add_value().
*
* Note that the arguments must be of the correct width for their types
* specified in @format_string. This can be achieved by casting them. See
* the [GVariant varargs documentation][gvariant-varargs].
*
* This function might be used as follows:
*
* |[<!-- language="C" -->
* GVariant *
* make_pointless_dictionary (void)
* {
* GVariantBuilder builder;
* int i;
*
* g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
* for (i = 0; i < 16; i++)
* {
* gchar buf[3];
*
* sprintf (buf, "%d", i);
* g_variant_builder_add (&builder, "{is}", i, buf);
* }
*
* return g_variant_builder_end (&builder);
* }
* ]|
*
* Since: 2.24
*/
void g_variant_builder_add(GVariantBuilder* builder, const gchar* format_string,
...)
{
GVariant* variant;
va_list ap;
va_start(ap, format_string);
variant = g_variant_new_va(format_string, NULL, &ap);
va_end(ap);
g_variant_builder_add_value(builder, variant);
}
/**
* g_variant_get_child: (skip)
* @value: a container #GVariant
* @index_: the index of the child to deconstruct
* @format_string: a #GVariant format string
* @...: arguments, as per @format_string
*
* Reads a child item out of a container #GVariant instance and
* deconstructs it according to @format_string. This call is
* essentially a combination of g_variant_get_child_value() and
* g_variant_get().
*
* @format_string determines the C types that are used for unpacking
* the values and also determines if the values are copied or borrowed,
* see the section on
* [GVariant format strings][gvariant-format-strings-pointers].
*
* Since: 2.24
**/
void g_variant_get_child(GVariant* value, gsize index_,
const gchar* format_string, ...)
{
GVariant* child;
va_list ap;
/* if any direct-pointer-access formats are in use, flatten first */
if (strchr(format_string, '&'))
g_variant_get_data(value);
child = g_variant_get_child_value(value, index_);
g_return_if_fail(valid_format_string(format_string, TRUE, child));
va_start(ap, format_string);
g_variant_get_va(child, format_string, NULL, &ap);
va_end(ap);
g_variant_unref(child);
}
/**
* g_variant_iter_next: (skip)
* @iter: a #GVariantIter
* @format_string: a GVariant format string
* @...: the arguments to unpack the value into
*
* Gets the next item in the container and unpacks it into the variable
* argument list according to @format_string, returning %TRUE.
*
* If no more items remain then %FALSE is returned.
*
* All of the pointers given on the variable arguments list of this
* function are assumed to point at uninitialised memory. It is the
* responsibility of the caller to free all of the values returned by
* the unpacking process.
*
* Here is an example for memory management with g_variant_iter_next():
* |[<!-- language="C" -->
* // Iterates a dictionary of type 'a{sv}'
* void
* iterate_dictionary (GVariant *dictionary)
* {
* GVariantIter iter;
* GVariant *value;
* gchar *key;
*
* g_variant_iter_init (&iter, dictionary);
* while (g_variant_iter_next (&iter, "{sv}", &key, &value))
* {
* g_print ("Item '%s' has type '%s'\n", key,
* g_variant_get_type_string (value));
*
* // must free data for ourselves
* g_variant_unref (value);
* g_free (key);
* }
* }
* ]|
*
* For a solution that is likely to be more convenient to C programmers
* when dealing with loops, see g_variant_iter_loop().
*
* @format_string determines the C types that are used for unpacking
* the values and also determines if the values are copied or borrowed.
*
* See the section on
* [GVariant format strings][gvariant-format-strings-pointers].
*
* Returns: %TRUE if a value was unpacked, or %FALSE if there as no value
*
* Since: 2.24
**/
gboolean g_variant_iter_next(GVariantIter* iter, const gchar* format_string,
...)
{
GVariant* value;
value = g_variant_iter_next_value(iter);
g_return_val_if_fail(valid_format_string(format_string, TRUE, value),
FALSE);
if (value != NULL)
{
va_list ap;
va_start(ap, format_string);
g_variant_valist_get(&format_string, value, FALSE, &ap);
va_end(ap);
g_variant_unref(value);
}
return value != NULL;
}
/**
* g_variant_iter_loop: (skip)
* @iter: a #GVariantIter
* @format_string: a GVariant format string
* @...: the arguments to unpack the value into
*
* Gets the next item in the container and unpacks it into the variable
* argument list according to @format_string, returning %TRUE.
*
* If no more items remain then %FALSE is returned.
*
* On the first call to this function, the pointers appearing on the
* variable argument list are assumed to point at uninitialised memory.
* On the second and later calls, it is assumed that the same pointers
* will be given and that they will point to the memory as set by the
* previous call to this function. This allows the previous values to
* be freed, as appropriate.
*
* This function is intended to be used with a while loop as
* demonstrated in the following example. This function can only be
* used when iterating over an array. It is only valid to call this
* function with a string constant for the format string and the same
* string constant must be used each time. Mixing calls to this
* function and g_variant_iter_next() or g_variant_iter_next_value() on
* the same iterator causes undefined behavior.
*
* If you break out of a such a while loop using g_variant_iter_loop() then
* you must free or unreference all the unpacked values as you would with
* g_variant_get(). Failure to do so will cause a memory leak.
*
* Here is an example for memory management with g_variant_iter_loop():
* |[<!-- language="C" -->
* // Iterates a dictionary of type 'a{sv}'
* void
* iterate_dictionary (GVariant *dictionary)
* {
* GVariantIter iter;
* GVariant *value;
* gchar *key;
*
* g_variant_iter_init (&iter, dictionary);
* while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
* {
* g_print ("Item '%s' has type '%s'\n", key,
* g_variant_get_type_string (value));
*
* // no need to free 'key' and 'value' here
* // unless breaking out of this loop
* }
* }
* ]|
*
* For most cases you should use g_variant_iter_next().
*
* This function is really only useful when unpacking into #GVariant or
* #GVariantIter in order to allow you to skip the call to
* g_variant_unref() or g_variant_iter_free().
*
* For example, if you are only looping over simple integer and string
* types, g_variant_iter_next() is definitely preferred. For string
* types, use the '&' prefix to avoid allocating any memory at all (and
* thereby avoiding the need to free anything as well).
*
* @format_string determines the C types that are used for unpacking
* the values and also determines if the values are copied or borrowed.
*
* See the section on
* [GVariant format strings][gvariant-format-strings-pointers].
*
* Returns: %TRUE if a value was unpacked, or %FALSE if there was no
* value
*
* Since: 2.24
**/
gboolean g_variant_iter_loop(GVariantIter* iter, const gchar* format_string,
...)
{
gboolean first_time = GVSI(iter)->loop_format == NULL;
GVariant* value;
va_list ap;
g_return_val_if_fail(first_time || format_string == GVSI(iter)->loop_format,
FALSE);
if (first_time)
{
TYPE_CHECK(GVSI(iter)->value, G_VARIANT_TYPE_ARRAY, FALSE);
GVSI(iter)->loop_format = format_string;
if (strchr(format_string, '&'))
g_variant_get_data(GVSI(iter)->value);
}
value = g_variant_iter_next_value(iter);
g_return_val_if_fail(
!first_time || valid_format_string(format_string, TRUE, value), FALSE);
va_start(ap, format_string);
g_variant_valist_get(&format_string, value, !first_time, &ap);
va_end(ap);
if (value != NULL)
g_variant_unref(value);
return value != NULL;
}
/* Serialised data {{{1 */
static GVariant* g_variant_deep_copy(GVariant* value)
{
switch (g_variant_classify(value))
{
case G_VARIANT_CLASS_MAYBE:
case G_VARIANT_CLASS_ARRAY:
case G_VARIANT_CLASS_TUPLE:
case G_VARIANT_CLASS_DICT_ENTRY:
case G_VARIANT_CLASS_VARIANT:
{
GVariantBuilder builder;
GVariantIter iter;
GVariant* child;
g_variant_builder_init(&builder, g_variant_get_type(value));
g_variant_iter_init(&iter, value);
while ((child = g_variant_iter_next_value(&iter)))
{
g_variant_builder_add_value(&builder,
g_variant_deep_copy(child));
g_variant_unref(child);
}
return g_variant_builder_end(&builder);
}
case G_VARIANT_CLASS_BOOLEAN:
return g_variant_new_boolean(g_variant_get_boolean(value));
case G_VARIANT_CLASS_BYTE:
return g_variant_new_byte(g_variant_get_byte(value));
case G_VARIANT_CLASS_INT16:
return g_variant_new_int16(g_variant_get_int16(value));
case G_VARIANT_CLASS_UINT16:
return g_variant_new_uint16(g_variant_get_uint16(value));
case G_VARIANT_CLASS_INT32:
return g_variant_new_int32(g_variant_get_int32(value));
case G_VARIANT_CLASS_UINT32:
return g_variant_new_uint32(g_variant_get_uint32(value));
case G_VARIANT_CLASS_INT64:
return g_variant_new_int64(g_variant_get_int64(value));
case G_VARIANT_CLASS_UINT64:
return g_variant_new_uint64(g_variant_get_uint64(value));
case G_VARIANT_CLASS_HANDLE:
return g_variant_new_handle(g_variant_get_handle(value));
case G_VARIANT_CLASS_DOUBLE:
return g_variant_new_double(g_variant_get_double(value));
case G_VARIANT_CLASS_STRING:
return g_variant_new_string(g_variant_get_string(value, NULL));
case G_VARIANT_CLASS_OBJECT_PATH:
return g_variant_new_object_path(g_variant_get_string(value, NULL));
case G_VARIANT_CLASS_SIGNATURE:
return g_variant_new_signature(g_variant_get_string(value, NULL));
}
g_assert_not_reached();
}
/**
* g_variant_get_normal_form:
* @value: a #GVariant
*
* Gets a #GVariant instance that has the same value as @value and is
* trusted to be in normal form.
*
* If @value is already trusted to be in normal form then a new
* reference to @value is returned.
*
* If @value is not already trusted, then it is scanned to check if it
* is in normal form. If it is found to be in normal form then it is
* marked as trusted and a new reference to it is returned.
*
* If @value is found not to be in normal form then a new trusted
* #GVariant is created with the same value as @value.
*
* It makes sense to call this function if you've received #GVariant
* data from untrusted sources and you want to ensure your serialised
* output is definitely in normal form.
*
* If @value is already in normal form, a new reference will be returned
* (which will be floating if @value is floating). If it is not in normal form,
* the newly created #GVariant will be returned with a single non-floating
* reference. Typically, g_variant_take_ref() should be called on the return
* value from this function to guarantee ownership of a single non-floating
* reference to it.
*
* Returns: (transfer full): a trusted #GVariant
*
* Since: 2.24
**/
GVariant* g_variant_get_normal_form(GVariant* value)
{
GVariant* trusted;
if (g_variant_is_normal_form(value))
return g_variant_ref(value);
trusted = g_variant_deep_copy(value);
g_assert(g_variant_is_trusted(trusted));
return g_variant_ref_sink(trusted);
}
/**
* g_variant_byteswap:
* @value: a #GVariant
*
* Performs a byteswapping operation on the contents of @value. The
* result is that all multi-byte numeric data contained in @value is
* byteswapped. That includes 16, 32, and 64bit signed and unsigned
* integers as well as file handles and double precision floating point
* values.
*
* This function is an identity mapping on any value that does not
* contain multi-byte numeric data. That include strings, booleans,
* bytes and containers containing only these things (recursively).
*
* The returned value is always in normal form and is marked as trusted.
*
* Returns: (transfer full): the byteswapped form of @value
*
* Since: 2.24
**/
GVariant* g_variant_byteswap(GVariant* value)
{
GVariantTypeInfo* type_info;
guint alignment;
GVariant* new;
type_info = g_variant_get_type_info(value);
g_variant_type_info_query(type_info, &alignment, NULL);
if (alignment)
/* (potentially) contains multi-byte numeric data */
{
GVariantSerialised serialised;
GVariant* trusted;
GBytes* bytes;
trusted = g_variant_get_normal_form(value);
serialised.type_info = g_variant_get_type_info(trusted);
serialised.size = g_variant_get_size(trusted);
serialised.data = g_malloc(serialised.size);
g_variant_store(trusted, serialised.data);
g_variant_unref(trusted);
g_variant_serialised_byteswap(serialised);
bytes = g_bytes_new_take(serialised.data, serialised.size);
new = g_variant_new_from_bytes(g_variant_get_type(value), bytes, TRUE);
g_bytes_unref(bytes);
}
else
/* contains no multi-byte data */
new = value;
return g_variant_ref_sink(new);
}
/**
* g_variant_new_from_data:
* @type: a definite #GVariantType
* @data: (array length=size) (element-type guint8): the serialised data
* @size: the size of @data
* @trusted: %TRUE if @data is definitely in normal form
* @notify: (scope async): function to call when @data is no longer needed
* @user_data: data for @notify
*
* Creates a new #GVariant instance from serialised data.
*
* @type is the type of #GVariant instance that will be constructed.
* The interpretation of @data depends on knowing the type.
*
* @data is not modified by this function and must remain valid with an
* unchanging value until such a time as @notify is called with
* @user_data. If the contents of @data change before that time then
* the result is undefined.
*
* If @data is trusted to be serialised data in normal form then
* @trusted should be %TRUE. This applies to serialised data created
* within this process or read from a trusted location on the disk (such
* as a file installed in /usr/lib alongside your application). You
* should set trusted to %FALSE if @data is read from the network, a
* file in the user's home directory, etc.
*
* If @data was not stored in this machine's native endianness, any multi-byte
* numeric values in the returned variant will also be in non-native
* endianness. g_variant_byteswap() can be used to recover the original values.
*
* @notify will be called with @user_data when @data is no longer
* needed. The exact time of this call is unspecified and might even be
* before this function returns.
*
* Note: @data must be backed by memory that is aligned appropriately for the
* @type being loaded. Otherwise this function will internally create a copy of
* the memory (since GLib 2.60) or (in older versions) fail and exit the
* process.
*
* Returns: (transfer none): a new floating #GVariant of type @type
*
* Since: 2.24
**/
GVariant* g_variant_new_from_data(const GVariantType* type, gconstpointer data,
gsize size, gboolean trusted,
GDestroyNotify notify, gpointer user_data)
{
GVariant* value;
GBytes* bytes;
g_return_val_if_fail(g_variant_type_is_definite(type), NULL);
g_return_val_if_fail(data != NULL || size == 0, NULL);
if (notify)
bytes = g_bytes_new_with_free_func(data, size, notify, user_data);
else
bytes = g_bytes_new_static(data, size);
value = g_variant_new_from_bytes(type, bytes, trusted);
g_bytes_unref(bytes);
return value;
}
/* Epilogue {{{1 */
/* vim:set foldmethod=marker: */
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Markdown Previewer</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor"
crossorigin="anonymous"
/>
<script src="./js/marked.js"></script>
<script>
function updatePreview() {
let previewElement = document.getElementById("preview");
let editorValue = document.getElementById("editor").value;
let markedUpHTML = marked.parse(editorValue, {breaks: true});
previewElement.innerHTML = markedUpHTML;
}
function setDefault() {
let defaultText = `\
# aboho Markdown Previewer
## freecodecamp project
[Learn More about Andrew Boho](http://andrewboho.net)
<dl>
<dt>Definition list</dt>
<dd>is something people use sometimes.</dd>
<dt>Markdown in HTML</dt>
<dd>Does *not* work **very** well. Use HTML <em>tags</em>.</dd>
</dl>
\`This is an inline code block.\`
\`\`\`
Multi-line
Code
Block
\`\`\`
- Code
- All
- Day
> Blockquote. Blockquote. Blockquote.
> Blockquote. Blockquote. Blockquote.
> Blockquote. Blockquote. Blockquote.
**Bolded Text**

`;
let editorField = document.getElementById("editor");
let previewElement = document.getElementById("preview");
editorField.value = defaultText;
previewElement.innerHTML = marked.parse(defaultText, {breaks: true});
}
</script>
</head>
<body onload="setDefault()">
<div class="container-fluid">
<div class="row">
<div class="col text-center text-white bg-dark">
<h1>Markdown Previewer by aboho</h1>
</div>
</div>
<div class="row form-group">
<div class="col-6 bg-info d-flex flex-column">
<h2>Editor:</h2>
<hr>
<textarea id="editor" onkeyup="updatePreview()" class="form-control flex-grow-1"></textarea>
</div>
<div class="col-6 bg-secondary text-light">
<h2>Output:</h2>
<hr>
<div id="preview"></div>
</div>
</div>
</div>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js"
integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2"
crossorigin="anonymous"
></script>
<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
</body>
</html>
|
namespace CommsRadioAPI;
/// <summary>
/// Implement this abstract class to define the behaviour of a Comms Radio mode in a given state.
/// </summary>
public abstract class AStateBehaviour
{
/// <summary>
/// The state of the Comms Radio when it exhibits the behaviour described by the implementing class.
/// </summary>
public readonly CommsRadioState state;
/// <summary>
/// Instantiate a new action/update handler with the given Comms Radio state.
/// </summary>
/// <param name="state">The state of the Comms Radio when it exhibits the behaviour of the handler class.</param>
public AStateBehaviour(CommsRadioState state)
{
this.state = state;
}
/// <summary>
/// This method is called when the instance becomes the active state of the Comms Radio.<br/>
/// This can happen when transitioning to this state or when enabling the Comms Radio.<br/>
/// Use it to do any required setup.<br/>
/// Be sure to stop any long running coroutines that are started here in <c>OnLeave</c>!
/// </summary>
/// <param name="utility">Provides access to some useful functionality, eg. <c>StartCoroutine</c>.</param>
/// <param name="previous">The <c>AStateBehaviour</c> that was previously active, or <c>null</c> if the mode is being enabled.
public virtual void OnEnter(CommsRadioUtility utility, AStateBehaviour? previous) {}
/// <summary>
/// This method is called when the instance is no longer the active state of the Comms Radio.<br/>
/// This can happen when transitioning away from this state or when disabling the Comms Radio.<br/>
/// Use it to do any required cleanup, like stopping long running coroutines that were started by <c>OnEnter</c>.
/// </summary>
/// <param name="utility">Provides access to some useful functionality, eg. <c>StopCoroutine</c>.</param>
/// <param name="next">The <c>AStateBehaviour</c> that is about to become active, or <c>null</c> if the mode is being disabled.
public virtual void OnLeave(CommsRadioUtility utility, AStateBehaviour? next) {}
/// <summary>
/// Use this method to respond to player input to the Comms Radio.<br/>
/// <c>InputAction.Activate</c> must always result in a state transition.
/// </summary>
/// <param name="utility">Provides access to some useful functionality, eg. <c>StartCoroutine</c>.</param>
/// <param name="action">The action that the player has taken.</param>
/// <returns>The next state/action/update handler to use. Do NOT return <c>this</c>. Use <c>ButtonBehaviourType.Ignore</c> instead if you wish to ignore the Up & Down buttons.</returns>
public abstract AStateBehaviour OnAction(CommsRadioUtility utility, InputAction action);
/// <summary>
/// This method runs on each cycle of the game loop.<br/>
/// It can be used, for example, to keep track of where the Comms Radio laser is pointing.
/// </summary>
/// <param name="utility">Provides access to some useful functionality, eg. <c>StartCoroutine</c>.</param>
/// <returns>The next state/action/update handler to use. Return <c>this</c> if no state transition is necessary.</returns>
public virtual AStateBehaviour OnUpdate(CommsRadioUtility utility)
{
return this;
}
}
|
use core::panic;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use dusk_phantom::lang::{run, Resource};
use realfft::num_complex::Complex32;
fn eval_benchmark(c: &mut Criterion) {
let len = 1024;
let complex: Vec<Complex32> = vec![Complex32::new(1.0, 0.0); len];
let code = "let lp: Float -> Float -> Float = (l: Float) => (i: Float) => if i < l then 1 else 0 in (i: Float) => (fft(i).norm * lp(800)(i), fft(i).angle).polar";
let code_value = match run(code) {
Ok(x) => x,
Err(err) => panic!("failed to run code: {}", err),
};
let resource = Resource {
fft: &complex,
modulation: &vec![],
beat: 0.0,
second: 0.0,
};
let data = (resource, code_value);
c.bench_with_input(BenchmarkId::new("mutate", "1024"), &data, |b, (r, c)| {
b.iter(|| {
let _ = c.clone().collect(0..len, r);
})
});
}
criterion_group!(benches, eval_benchmark);
criterion_main!(benches);
|
package hust.soict.dsai.aims.media;
import hust.soict.dsai.aims.exception.PlayerException;
public class DigitalVideoDisc extends Disc {
// DVD also implements Playable but through Disc
public DigitalVideoDisc(String title, String category, String director, int length, float cost) {
super(title, category, cost, director, length);
}
@Override
public String toString() {
//to String method for printing out in Ex6 lab03
return "DVD - "+this.getId()+" - "+this.getTitle()+" - "+this.getCategory()+" - "+this.getDirector()+" - "+this.getLength()+": "+this.getCost()+" $";
}
public void play() throws PlayerException {
if (this.getLength() > 0) {
System.out.println("Playing DVD: " + this.getTitle());
System.out.println("DVD length: " + this.getLength());
} else {
System.err.println("Player exception in DVD");
throw new PlayerException("ERRO: DVD length is non-positive!");
}
}
@Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(!(obj instanceof DigitalVideoDisc))
return false;
return (((Media) obj).getTitle() == this.getTitle());
}
}
|
import user from '@testing-library/user-event';
import React from 'react';
import { act, fireEvent, render, } from '../utils/test';
import { SuggestInput, } from './SuggestInput';
describe('<SuggestInput />', () => {
it('triggers onChange and onSelect events correctly', async () => {
const handleChange = jest.fn();
const handleSelect = jest.fn();
const { getByRole, getByText, } = render(
<SuggestInput
suggestions={[
'Line 1',
'Line 2',
]}
onChange={handleChange}
onSelect={handleSelect} />
);
await act(async () => {
await user.type(getByRole('textbox'), 'L');
await new Promise(resolve => setTimeout(resolve, 500));
});
expect(handleChange).toHaveBeenCalledTimes(2);
expect(handleChange).toHaveBeenLastCalledWith('L');
fireEvent.click(getByText('Line 1'));
expect(handleSelect).toHaveBeenCalledTimes(1);
expect(handleSelect).toHaveBeenCalledWith('Line 1');
});
});
|
; Arbitrary pre-assignments to
; show the magic.
MOV R1, #0x15
MOV R2, #0x12
MOV R3, #0x14
MOV R4, #0x65
MOV R5, #0x45
MOV R0, #0x200
STMIA R0!, {R1, R2, R3, R4, R5}
; Stored some values to memory. Let's delete them.
; The code bellow will fill the R1-R5 with zeros
; Instead of writing "MOV Rx, 0" I did this. You'll
; understand what it does after this line. But for now,
; just know that it clears all the given registers.
LDMIA R0!, {R1, R2, R3, R4, R5}
; Load Multiple (Increment After)
; A instruction to get multiple
; values from the memory to registers.
; Increment after means that it will
; assign the (last memory address + 0x4)
; to the register that holds starting point
; after the operation.
;
; We need to give a starting point
; for memory to get the values.
;
; Usage:
; LDM <startingpoint>, {<stored registers>}
; LDMIA <startingpoint>!, {<stored registers>}
; Note:
; LDM doesn't work in VisUAL2, but you can use LDMIA
; without ! mark on the starting point register.
MOV R0, #0x200 ; Starting point for to seek registers.
LDMIA R0!, {R8, R9, R10, R11, R12}
|
package ru.zhurkin.warehouseapp.mvc;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.zhurkin.warehouseapp.model.order.OrderDetails;
import ru.zhurkin.warehouseapp.service.OrderDetailsService;
import ru.zhurkin.warehouseapp.support.dto.OrderDetailsBodyDTO;
import ru.zhurkin.warehouseapp.support.mapper.OrderDetailsMapper;
@Controller
@RequestMapping("/order-details")
@RequiredArgsConstructor
public class MVCOrderDetailsController {
private final OrderDetailsService orderDetailsService;
private final OrderDetailsMapper orderDetailsMapper;
@GetMapping
public String getAll(@RequestParam(value = "page", defaultValue = "1") int page,
@RequestParam(value = "size", defaultValue = "5") int pageSize,
Model model) {
PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "startDate"));
Page<OrderDetails> orderDetailsPage = orderDetailsService.getAll(pageRequest);
Page<OrderDetailsBodyDTO> orderDetailsDtoPage = new PageImpl<>(orderDetailsMapper.toDtos(orderDetailsPage.getContent()), pageRequest, orderDetailsPage.getTotalElements());
model.addAttribute("detailedOrders", orderDetailsDtoPage);
return "/details/viewOrderDetails";
}
}
|
use once_cell::sync::Lazy;
use serde::Deserialize;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
Toml(#[from] toml::de::Error),
}
#[derive(Debug, Deserialize, Clone)]
pub struct SpotifyConfig {
pub client_id: String,
pub client_secret: String,
}
#[derive(Debug, Deserialize, Clone)]
pub struct AppConfig {
pub port: u16,
pub cookie_secret: String,
}
#[derive(Debug, Deserialize, Clone)]
pub struct Configuration {
pub spotify: SpotifyConfig,
pub app: AppConfig,
}
pub static CONFIGURATION_INSTANCE: Lazy<Configuration> =
Lazy::new(|| load_config_file().expect("Could not load config.toml"));
impl Configuration {
pub fn read() -> &'static Configuration {
&CONFIGURATION_INSTANCE
}
pub fn app() -> &'static AppConfig {
&CONFIGURATION_INSTANCE.app
}
pub fn spotify() -> &'static SpotifyConfig {
&CONFIGURATION_INSTANCE.spotify
}
}
fn load_config_file() -> Result<Configuration, Error> {
let config_file = std::fs::read_to_string("config.toml")?;
let config = toml::from_str(&config_file)?;
Ok(config)
}
|
<div
class="container grid grid-cols-3 xl:grid-cols-5 grid-rows-[repeat(5,_minmax(0,_15rem))] md:grid-rows-[repeat(4,_minmax(0,_20rem))] xl:grid-rows-2 gap-8 xl:h-[40rem]"
style="opacity: 0;"
x-data="social"
>
<figure class="col-start-1 col-span-3 md:col-span-2 row-start-2 lg:row-start-1 row-span-1 lg:row-span-2 border-4 border-primary">
<img
class="w-full h-full object-cover object-center"
src="{{ section.settings.image_1 | img_url: 'grande' }}"
draggable="false"
/>
</figure>
<div class="col-start-1 lg:col-start-3 col-span-3 lg:col-span-1 row-start-1 row-span-1 border-4 border-primary border-dashed flex flex-col gap-2 items-center justify-center text-center pb-2">
{% if section.settings.show_heading %}
<h1 class="text-2xl font-semibold">
{{ section.settings.heading_text }}
</h1>
{% endif %}
{% if section.settings.show_description %}
<div>
{{ section.settings.description_richtext }}
</div>
{% endif %}
{% if section.settings.show_link %}
<a
class="link link-primary"
href="{{ section.settings.link_url }}"
>
{{ section.settings.link_text }}
</a>
{% endif %}
</div>
<figure class="col-start-1 md:col-start-3 col-span-3 md:col-span-1 row-start-3 md:row-start-2 row-span-1 border-4 border-primary">
<img
class="w-full h-full object-cover object-center"
src="{{ section.settings.image_2 | img_url: 'grande' }}"
draggable="false"
/>
</figure>
<figure class="col-start-1 xl:col-start-4 col-span-3 xl:col-span-2 row-start-4 md:row-start-3 xl:row-start-1 row-span-1 border-4 border-primary">
<img
class="w-full h-full object-cover object-center"
src="{{ section.settings.image_3 | img_url: 'grande' }}"
draggable="false"
/>
</figure>
<figure class="col-start-1 xl:col-start-4 col-span-3 xl:col-span-2 row-start-5 md:row-start-4 xl:row-start-2 row-span-1 border-4 border-primary">
<img
class="w-full h-full object-cover object-center"
src="{{ section.settings.image_4 | img_url: 'grande' }}"
draggable="false"
/>
</figure>
</div>
<script>
document.addEventListener("alpine:init", () => {
Alpine.data("social", () => ({
waypoint: null,
init() {
this.waypoint = new Waypoint({
element: this.$el,
offset: "50%",
handler: this.introAnimation.bind(this)
})
},
introAnimation() {
this.waypoint.destroy()
anime({
targets: this.$el.children,
opacity: [0, 1],
scale: [0.5, 1],
delay: anime.stagger(100),
easing: "easeOutElastic(1, 2)",
begin: () => this.$el.style.opacity = 1
})
}
}))
})
</script>
{% schema %}
{
"name": "Social",
"tag": "section",
"settings": [
{
"type": "header",
"content": "Heading"
},
{
"type": "checkbox",
"id": "show_heading",
"label": "Show heading",
"default": true
},
{
"type": "text",
"id": "heading_text",
"label": "Heading text",
"default": "Social Heading"
},
{
"type": "header",
"content": "Description"
},
{
"type": "checkbox",
"id": "show_description",
"label": "Show description",
"default": true
},
{
"type": "richtext",
"id": "description_richtext",
"label": "Description text",
"default": "<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit.</p>"
},
{
"type": "header",
"content": "Link"
},
{
"type": "checkbox",
"id": "show_link",
"label": "Show link",
"default": true
},
{
"type": "text",
"id": "link_text",
"label": "Link text",
"default": "@our_social_name"
},
{
"type": "url",
"id": "link_url",
"label": "Link url"
},
{
"type": "header",
"content": "Images"
},
{
"type": "image_picker",
"id": "image_1",
"label": "Image 1"
},
{
"type": "image_picker",
"id": "image_2",
"label": "Image 2"
},
{
"type": "image_picker",
"id": "image_3",
"label": "Image 3"
},
{
"type": "image_picker",
"id": "image_4",
"label": "Image 4"
}
],
"presets": [
{
"name": "Social"
}
]
}
{% endschema %}
|
import React from "react";
import Link from "next/link";
import MetaSeo from "../components/MetaSeo";
import constant from "../utilities/constant";
import Typewriter from "typewriter-effect";
import Image from "next/image";
export default function Home({ setting }) {
return (
<div className="flex justify-center h-[90vh] xl:items-center xl:flex-row flex-col-reverse">
<MetaSeo
title="Hafiz Iqbal Sahrunizar"
description="Hafiz Iqbal Sahrunizar, bekerja sebagai backend golang developer."
/>
<div className="xl:w-7/12" data-aos="fade-up">
<h1 className="font-doodle h-20 lg:h-auto tracking-widest xl:text-4xl text-3xl text-center xl:text-left">
<Typewriter
options={{
strings: setting.title.split("|"),
autoStart: true,
loop: true,
delay: 75,
}}
/>
</h1>
<p className="mt-5 mb-4 text-center xl:text-left leading-7">
{setting.subtitle}
</p>
<p className="text-center z-50 xl:text-left">
See
<Link href={"/portfolio"}>
<span className="font-semibold underline hover:text-blue-500 cursor-pointer"> Portfolio</span>
</Link>{" "}
And{" "}
<a href={setting.cv_link} target={"_blank"} rel="noreferrer">
<span className="font-semibold underline hover:text-blue-500 cursor-pointer">Download My CV</span>
</a>
</p>
</div>
<div className="xl:w-5/12 flex xl:justify-end justify-center h-80 ">
<Image
src={`${setting.img?.path}`}
layout="fixed"
height={300}
width={300}
alt="BG-Image"
className={`object-contain mb-10 xl:mb-0 dark:invert invert-0`}
/>
</div>
</div>
);
}
export async function getStaticProps() {
return {
props: {
setting: {
title: 'Hi, Nice to meet you :)|My name Hafiz Sahrunizar :D|I`m A Software Engineer|Wanna Be My Friends :D|Don`t hestitate contact me!',
cv_link: 'https://drive.google.com/file/d/1OzB-tdyHaT-7DKvNpLLpyd6lILDtCj3w/view?usp=sharing',
subtitle: 'I’m an ex-software engineer from XL Axiata tbk, diving deep into Golang for three years. Recently, I`ve also been playing around with Next.js for some frontend stuff. Nikola Tesla is My Role Model :D',
img: {
path: "https://firebasestorage.googleapis.com/v0/b/personal-website-1d263.appspot.com/o/photo-profile%2Fnikola-tesla-vintage-illustration-free-vector-removebg-preview.png?alt=media&token=b0d73a25-d159-4658-80b5-86ba96484c82"
}
},
},
};
}
|
import { getConfigMap } from './get-config';
import { ServiceIdentifier } from './environment-identifier';
import * as functions from 'firebase-functions';
import {
ConfigMapEnvironmentReference,
EnvironmentReference,
} from './environment-reference';
import { EnrollServices } from '../models';
import { EnvironmentVariableDict } from './environment-variable-dict';
import { Octokit } from 'octokit';
import * as yaml from 'js-yaml';
const repositoryLinks: Record<string, string> = {
maine: 'cme_k8s',
dchbx: 'dchbx_k8s',
};
const extraFolder = ['enroll', 'edidb'] as Partial<EnrollServices>[];
const needsParsing = [
'medicaid-gateway',
'crm-gateway',
'b2b-gateway',
'fdsh-gateway',
] as Partial<EnrollServices>[];
const pat: string =
functions.config().gh.pat ?? process.env.GH_PAT ?? 'cme_k8s';
export const getService = async ({
orgId,
envId,
serviceId,
}: ServiceIdentifier): Promise<EnvironmentVariableDict> => {
const environmentValues = await getConfigMap({ orgId, envId });
const octokit = new Octokit({ auth: pat });
// If the service name is like `medicaid-gateway` convert it
// to `medicaid_gateway` for the folder path
const serviceFolderName = needsParsing.includes(serviceId)
? serviceId.replace('-', '_')
: serviceId;
// If the service name is like `enroll` or `edidb` there is an
// extra folder that the yaml file is nested in
const path = extraFolder.includes(serviceId)
? `base/${serviceFolderName}/web/${serviceId}.yaml`
: `base/${serviceFolderName}/${serviceId}.yaml`;
const githubResponse = await octokit.rest.repos.getContent({
owner: 'ideacrew',
repo: repositoryLinks[orgId] || 'cme_k8s',
path,
headers: { accept: 'application/vnd.github.v3.raw' },
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rawYaml: string = githubResponse.data as any;
// Need to loadAll because these yaml files have multiple documents
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [deployment] = yaml.loadAll(rawYaml) as any[];
const environmentReferenceList = deployment.spec.template.spec.containers[0]
.env as EnvironmentReference[];
// Filter out references to secret keys
const filteredVariables = environmentReferenceList.filter(reference => {
const cfReference = reference as ConfigMapEnvironmentReference;
return (
cfReference.valueFrom !== undefined &&
cfReference.valueFrom.configMapKeyRef !== undefined
);
});
const serviceVariables: EnvironmentVariableDict = {};
// Loop over the environment variable references in the Service yaml file
// and pair those with the values that come from the base and env config map
for (const reference of filteredVariables) {
const { name } = reference;
serviceVariables[name] = environmentValues[name] ?? 'undefined';
}
return serviceVariables;
};
|
import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shop_app/modules/Shop_App/Login/states.dart';
import '../../../layout/Shop_App/ShoopingLayout.dart';
import '../../../layout/Shop_App/cubit.dart';
import '../../../shared/network/local/cash_helper.dart';
import '../../../shared/shared_component/components.dart';
import '../../../shared/shared_component/constants.dart';
import '../register/shop_register_screen.dart';
import 'cubit.dart';
// ignore: must_be_immutable
class ShopLoginScreen extends StatelessWidget {
ShopLoginScreen({Key? key}) : super(key: key);
final passwordController = TextEditingController();
final emailController = TextEditingController();
var formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (BuildContext context) => ShopLoginCubit(),
child: BlocConsumer<ShopLoginCubit, ShopLoginStates>(
listener: (context, state) {
if (state is ShopLoginSuccessState) {
if (state.loginModel.status!) {
showToast(
msg: state.loginModel.message.toString(),
state: ToastStates.SUCCESS);
CacheHelper.saveData(
key: 'token', value: state.loginModel.data!.token)
.then((value) {
token = state.loginModel.data!.token!;
navigateAndFinish(context, ShopLayout());
ShopCubit.get(context).getUserData();
ShopCubit.get(context).getFavData();
navigateAndFinish(context, ShopLayout());
});
} else {
showToast(
msg: state.loginModel.message.toString(),
state: ToastStates.ERROR);
print(state.loginModel.message);
}
}
},
builder: (context, state) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Form(
key: formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Login',
style: Theme.of(context)
.textTheme
.headline4
?.copyWith(
color: Colors.orange.withOpacity(0.7),
fontWeight: FontWeight.bold),
),
Text(
'login now to browse our hot offers',
style:
Theme.of(context).textTheme.bodyText2!.copyWith(
color: Colors.grey,
),
),
const SizedBox(
height: 30.0,
),
defaultFormField(
raduis: 15,
controller: emailController,
type: TextInputType.emailAddress,
validate: (value) {
if (value!.isEmpty) {
return 'Please Enter Your Email address';
}
return null;
},
prefixIcon: Icons.email,
label: 'Email Address',
prefix: Icons.email_outlined,
onFieldSubmitted: (value) {},
),
const SizedBox(
height: 10.0,
),
defaultFormField(
raduis: 15,
controller: passwordController,
type: TextInputType.visiblePassword,
isPassword: ShopLoginCubit.get(context).isPassword,
onFieldSubmitted: (value) {
if (formKey.currentState!.validate()) {
ShopLoginCubit.get(context).loginUsers(
email: emailController.text,
password: passwordController.text);
}
},
validate: (value) {
if (value!.isEmpty) {
return 'Password is to short';
}
return null;
},
prefixIcon: Icons.lock,
suffixIcon: ShopLoginCubit.get(context).suffix,
suffixPressed: () {
ShopLoginCubit.get(context)
.changePasswordVisibility();
},
label: 'Password',
prefix: Icons.password_outlined,
onSubmit: (value) {
if (formKey.currentState!.validate()) {
ShopLoginCubit.get(context).loginUsers(
email: emailController.text,
password: passwordController.text,
);
}
},
),
const SizedBox(
height: 30.0,
),
ConditionalBuilder(
condition: state is! ShopLoginLoadingState,
builder: (context) => Container(
height: 50,
child: defaultButton(
background: Colors.orange,
function: () {
// debugPrint(emailController.text);
// debugPrint(passwordController.text);
if (formKey.currentState!.validate()) {
ShopLoginCubit.get(context).loginUsers(
email: emailController.text,
password: passwordController.text);
}
},
isUpperCase: false,
radius: 15,
text: 'Login'),
),
fallback: (context) =>
const Center(child: CircularProgressIndicator()),
),
const SizedBox(
height: 10.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Don\'t have an account? '),
TextButton(
onPressed: () {
navigateTo(context, ShopRegisterScreen());
},
child: Text('register now')),
],
)
],
),
),
),
),
),
);
},
),
);
}
}
|
### 解题思路
本题使用**双索引尾指针**,从每个数组的最后一个元素开始比较
通过while循环,依次对两个数组的**最尾元素**进行比较,将大的元素放入合并后的nums1的**最尾处**
最后通过System.arraycopy(nums2, 0, nums1, 0, l2 + 1);将nums2数组剩下的元素放到nums1的最前面去即可完成合并。
### 代码
```java
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int l1 = m - 1;
int l2 = n - 1;
int len = m + n - 1;
while(l1 >= 0 && l2 >= 0){
nums1[len--] = nums1[l1] > nums2[l2] ? nums1[l1--] : nums2[l2--];
}
// 将nums2数组从下标0开始,拷贝到nums1数组中,从下标0位置开始,长度为l2+1
System.arraycopy(nums2, 0, nums1, 0, l2 + 1);
}
}
```
|
<?php
require(__DIR__ . "/config/auth.php");
$title = "Add New User";
//Permissions check
if (!check_user_permission(PERMISSION_ADD_USER)) {
// @header("HTTP/1.1 403 Forbidden");
redirect("/", "403 Forbidden");
exit();
}
require_once(FILEROOT . "/header.php");
?>
<style>
form .form-label.helper:has(+ [required]):after {
content: " * ";
font-weight: bold;
font-size: 1rem;
color: darkred;
}
input:focus:required:invalid {
box-shadow: none;
}
select:invalid,
input:invalid {
box-shadow: 0 0 5px 1px #eb7878;
}
select:valid:required,
input:valid:required {
box-shadow: 0 0 5px 1px darkgreen;
}
</style>
<main>
<div class="container-xl mt-4 px-4">
<nav class="nav nav-borders">
<h4 class="m-0">Add New User</h4>
</nav>
<hr class="mt-0 mb-4">
<div class="card mb-2">
<div id="new-user-details" class="card-body ms-4">
<noscript>
<span class="fw-lighter text-danger">* indcates required field</span>
</noscript>
<form action="<?php echo WEBROOT; ?>/process-user.php" method="post" class="form" id="add-user" name="add-user" novalidate>
<fieldset class="d-flex gap-5 mb-2 p-3 border rounded-1 align-items-center flex-wrap">
<div class="form-element flex-grow-1">
<label class="form-label helper" for="firstname">First Name</label>
<input type="text" class="form-control" id="firstname" name="firstname" required maxlength="20">
</div>
<div class="form-element flex-grow-1">
<label class="form-label helper" for="lastname">Last Name</label>
<input type="text" class="form-control" id="lastname" name="lastname" required maxlength="20">
</div>
<div class="form-element flex-grow-1">
<label class="form-label helper" for="middlename">Middle Name</label>
<input type="text" class="form-control" id="middlename" name="middlename" minlength="2" maxlength="20">
</div>
<div class="form-element flex-grow-1">
<label class="form-label helper" for="commonname">Common Name (Preferred to be known as)</label>
<input type="text" class="form-control" id="commonname" name="commonname" minlength="2" maxlength="20">
</div>
</fieldset>
<fieldset class="d-flex gap-5 mb-2 p-3 border rounded-1 align-items-center flex-wrap">
<div class="form-element flex-grow-1">
<label class="form-label helper" for="username">Username</label>
<input type="text" pattern="[a-z]\.[a-z]+[0-9]{0,2}" class="form-control" id="username" name="username" required minlength="3" maxlength="20" autocomplete="username">
</div>
<div class="form-element flex-grow-1">
<label class="form-label helper" for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" required minlength="3">
</div>
</fieldset>
<fieldset class="d-flex gap-5 my-2 p-3 border rounded-1 align-items-center flex-wrap">
<div class="form-element flex-grow-1">
<label class="form-label helper" for="password">Password</label>
<input type="password" id="password" name="password" class="form-control" required autocomplete="new-password" minlength="6">
</div>
<div class="form-element flex-grow-1">
<label class="form-label helper" for="confirm-password">Confirm Password</label>
<input type="password" id="confirm-password" name="confirm-password" class="form-control" required autocomplete="new-password" minlength="6">
</div>
</fieldset>
<fieldset class="d-flex gap-5 mb-2 p-3 border rounded-1 align-items-center flex-wrap">
<div class="form-element flex-grow-1">
<label class="form-label helper" for="house">House</label>
<select name="house" class="form-select" id="house" aria-label="Select School House" required>
<option selected disabled value="">Select a School House</option>
<?php foreach (SCHOOL_HOUSES as $house) : ?>
<option required value="<?php echo $house; ?>">
<?php echo ucwords(strtolower(($house))); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-element flex-grow-1">
<label class="form-label helper" for="year">Year</label>
<select name="year" class="form-select" id="year" aria-label="Select School Year" required>
<option selected disabled value="">Select a School Year</option>
<?php foreach (SCHOOL_YEARS as $year) : ?>
<option required value="<?php echo $year; ?>">
<?php echo ucwords(strtolower(($year))); ?>
</option>
<?php endforeach; ?>
</select>
</div>
</fieldset>
<div id="form-errors">
<ul class="form-errorlist"></ul>
</div>
<div class="my-3 d-flex align-items-center justify-content-center gap-3 flex-wrap">
<input type="submit" class="btn btn-outline-primary rounded-0 btn-lg" id="submitbutton" value="Add User">
<input type="reset" class="btn btn-outline-light btn-lg rounded-0 text-secondary border border-dark" value="Reset All">
</div>
</form>
</div>
</div>
</div>
</main>
<script>
function labelMandatoryFields() {
const mandatoryFormFieldsLabels = document.querySelectorAll("form .form-label:has(+ [required])");
mandatoryFormFieldsLabels.forEach((field) => {
const badge = document.createElement("span");
badge.classList.add("badge", "text-bg-warning", "indicator", "mx-1");
badge.textContent = "Required";
field.insertAdjacentElement("afterend", badge);
field.classList.remove("helper"); //Remove this for presentation purposes (used for fallback if JS disabled)
});
}
function formValidation() {
const addUserForm = document.getElementById('add-user');
const firstNameField = document.getElementById("firstname");
const lastNameField = document.getElementById("lastname");
const usernameField = document.getElementById("username");
const passwordField = document.getElementById("password");
const confirmPasswordField = document.getElementById("confirm-password");
const emailField = document.getElementById("email");
const yearField = document.getElementById("year");
const houseField = document.getElementById("house");
const submitButton = document.getElementById("submitbutton")
const formErrors = document.getElementById("form-errors");
const formErrorList = document.querySelector(".form-errorlist");
//Default Section
firstNameField.addEventListener('blur', e => {
if (firstNameField.validity.valid && !usernameField.value && lastNameField.validity.valid) {
//suggest username
usernameField.value = firstNameField.value[0].toLowerCase() + "." + lastNameField.value.toLowerCase();
}
});
lastNameField.addEventListener('blur', e => {
if (lastNameField.validity.valid && !usernameField.value && firstNameField.validity.valid) {
//suggest username
usernameField.value = firstNameField.value[0].toLowerCase() + "." + lastNameField.value.toLowerCase();
}
});
usernameField.addEventListener('blur', e => {
// Perform validation here
if (usernameField.validity.patternMismatch) {
usernameField.setCustomValidity("Username should be in the format 'a.bcd...' (with an optional number if pattern exists)")
} else {
usernameField.setCustomValidity("")
//Add value to email address by default
if (!emailField.value) {
emailField.value = usernameField.value + "@hogwarts.wiz";
}
}
// Add more validation rules as needed
});
addUserForm.addEventListener("submit", async e => {
e.preventDefault();
//Handle non-HTML errors
formErrorList.innerHTML = '';
let hasError = false;
let selectedYearValue = yearField.options[yearField.selectedIndex].text;
let selectedHouseValue = houseField.options[houseField.selectedIndex].text
let h6Element = formErrors.querySelector('h6');
if (h6Element) {
h6Element.remove();
}
//Password mismatch
if (passwordField.value != confirmPasswordField.value) {
formErrorList.insertAdjacentHTML("afterbegin", "<li class='ms-3'>The passwords entered do not match</li>");
hasError = true;
}
//Invalid Email Domain
if (emailField.value.split("@")[1] != "hogwarts.wiz") {
formErrorList.insertAdjacentHTML("afterbegin", "<li class='ms-3'>The email domain is not valid (must be <span class='fw-bolder'>@hogwarts.wiz</span>)</li>");
hasError = true;
}
//Year or House Logic
if (yearField.value == "STAFF" && houseField.value != "HOGWARTS") {
formErrorList.insertAdjacentHTML("afterbegin", `<li class='ms-3'>'House' must be set to <span class='fw-bolder'>Hogwarts</span> when 'Year' is <span class='fw-bolder'>${selectedYearValue}</span></li>`);
hasError = true;
} else if (yearField.value == "NONE" && houseField.value != "NONE") {
formErrorList.insertAdjacentHTML("afterbegin", `<li class='ms-3'>'House' must be set to <span class='fw-bolder'>None</span> when 'Year' is <span class='fw-bolder'>${selectedYearValue}</span></li>`);
hasError = true;
} else if (yearField.value.includes("YEAR") && houseField.value == "NONE") {
formErrorList.insertAdjacentHTML("afterbegin", `<li class='ms-3'>'House' must not be set to <span class='fw-bolder'>None</span> when 'Year' is <span class='fw-bolder'>${selectedYearValue}</span></li>`);
hasError = true;
}
if (hasError) {
formErrors.insertAdjacentHTML("afterbegin", "<h6 class='fw-bolder rounded-0 m-2 p-1'>The form contains errors</h6>")
formErrors.className = "alert alert-danger m-1 p-0 rounded-0 border border-danger";
} else {
//Submit the form via FetchAPI
try {
const formData = new FormData(addUserForm);
const response = await fetch('<?php echo WEBROOT; ?>/process-user.php', {
method: 'POST',
body: formData,
});
if (response.ok) {
formErrors.className = '';
formErrors.className = "alert alert-warning m-1 p-0 rounded-0 border border-warning";
formErrors.insertAdjacentHTML("afterbegin", "<h6 class='fw-bolder rounded-0 m-2 p-1'>Please wait - Processing...</h6>")
const responseData = await response.text();
let h6Element = formErrors.querySelector('h6');
if (h6Element) {
h6Element.remove();
}
formErrors.className = '';
formErrors.className = "alert alert-success m-1 p-0 rounded-0 border border-success";
formErrors.insertAdjacentHTML("afterbegin", "<h6 class='fw-bolder rounded-0 m-2 p-1'>Processing Complete - User Created</h6>")
formErrorList.insertAdjacentHTML("afterbegin", `<li class='pb-1 ms-3'><a href="<?php echo WEBROOT; ?>/profile.php?user=${usernameField.value}">View User</a></li>`);
} else {
// Handle server error
if (response.status === 400) {
const errorData = await response.json();
const errorReturned = errorData.error;
const errorListDisplay = errorData.error.map(error => `<li class='pb-1 ms-3'>${error}</li>`).join('');
formErrorList.innerHTML = '';
let h6Element = formErrors.querySelector('h6');
if (h6Element) {
h6Element.remove();
}
formErrorList.insertAdjacentHTML("afterbegin", errorListDisplay);
formErrors.insertAdjacentHTML("afterbegin", "<h6 class='fw-bolder rounded-0 m-2 p-1'>The form contains errors</h6>")
formErrors.className = "alert alert-danger m-1 p-0 rounded-0 border border-danger";
} else {
console.error('Server error:', response.statusText);
}
}
} catch (error) {
console.error('Fetch error:', error);
}
// addUserForm.submit();
}
});
}
labelMandatoryFields();
formValidation();
</script>
<?php require_once(FILEROOT . "/footer.php"); ?>
|
require "vec"
require "bullet"
module(..., package.seeall)
function forward(vessel)
local result = vec.new()
result.x = math.cos(vessel.rotation)
result.y = math.sin(vessel.rotation)
return result
end
function update(display, dt, scene, vessel)
local joystick = love.joystick.getJoysticks()[1]
-- Rotation
local circlepad_x, circlepad_y = joystick:getAxes()
local circlepad = 0
if (math.abs(circlepad_x) > math.abs(circlepad_y)) then circlepad = circlepad_x else circlepad = circlepad_y end
if (math.abs(circlepad) < 0.1) then circlepad = 0 end -- deadzone
local dpad = 0
if joystick:isGamepadDown("dpleft") then dpad = -1 end
if joystick:isGamepadDown("dpright") then dpad = 1 end
local sum = circlepad + dpad
if sum > 1 then sum = 1 end
if sum < -1 then sum = -1 end
local angle = sum * 10
vessel.rotation = vessel.rotation + angle * dt
vessel.rotation = vessel.rotation % (2 * math.pi)
-- Velocity
if joystick:isGamepadDown("a") then
local fwd = forward(vessel)
fwd = vec.scale(fwd, 50)
vessel.position.x = vessel.position.x + fwd.x * dt
vessel.position.y = vessel.position.y + fwd.y * dt
end
vessel.position.x = vessel.position.x % display.width
vessel.position.y = vessel.position.y % display.height
-- Shooting
if (joystick:isGamepadDown("y") or joystick:isGamepadDown("rightshoulder") or joystick:isGamepadDown("leftshoulder")) and vessel.shootTimer <= 0 then
local b = bullet.new(
vec.from(
vessel.position.x + math.cos(vessel.rotation) * 10,
vessel.position.y + math.sin(vessel.rotation) * 10
),
vec.scale(forward(vessel), 400)
)
table.insert(scene.bullets, b)
vessel.shootTimer = 0.5
end
if (vessel.shootTimer > 0) then
vessel.shootTimer = vessel.shootTimer - dt
end
end
function render(display, vessel)
love.graphics.setColor(1, 1, 1)
for y = -1, 1 do
for x = -1, 1 do
love.graphics.origin()
love.graphics.translate(x * display.width, y * display.height)
local w, h = vessel.sprite:getDimensions()
love.graphics.draw(vessel.sprite, vessel.position.x, vessel.position.y, vessel.rotation, 1,1, w/2, h/2)
end
end
love.graphics.origin()
end
function new()
local ship = {}
ship.shootTimer = 0
ship.position = vec.new()
ship.rotation = 0
ship.velocity = vec.new()
ship.sprite = love.graphics.newImage("art/ship.t3s")
local w,h = ship.sprite:getDimensions()
ship.radius = math.max(w, h) / 2
return ship
end
|
<?php
namespace App\Http\Controllers;
use App\Models\ath;
use App\Models\product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @param \App\Models\ath $ath
* @return \Illuminate\Http\Response
*/
public function index(ath $ath)
{
$data = DB::table('product')->get();
return view('Menudashboard.allproduct', ['data'=>$data]);
}
/**
* Show the form for creating a new resource.
*
* @param \App\Models\ath $ath
* @return \Illuminate\Http\Response
*/
public function create(ath $ath)
{
return view('Menudashboard.createnew');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\ath $ath
* @return \Illuminate\Http\Response
*/
public function store(Request $request, ath $ath)
{
$eImage = "";
if($image=$request->file(key:'image')){
$destinationPath='img/';
$eImage = date('YmdHis').".".$image->getClientoriginalExtension();
$image->move($destinationPath, $eImage);
}
$productName = $request->productName;
$productModel = $request->productModel;
$Price=$request->Price;
$image = $eImage;
$dob = $request->dob;
$description = $request->description;
DB::table('product')->insert([
'productName' => $productName,
'productModel' => $productModel,
'Price'=>$Price,
'dob' => $dob,
'image' => $image,
'description' => $description,
]);
$data = DB::table('product')->get();
return view('Menudashboard.allproduct', ['data'=>$data]);
}
/**
* Display the specified resource.
*
* @param \App\Models\ath $ath
* @param \{{ namespacedModel }} ${{ modelVariable }}
* @return \Illuminate\Http\Response
*/
public function show(ath $ath)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\ath $ath
* @param \{{ namespacedModel }} ${{ modelVariable }}
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$product = DB::table('product')->where('id', $id)->first();
return view('Menudashboard.update', ['product' => $product]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\ath $ath
* @param \{{ namespacedModel }} ${{ modelVariable }}
* @return \Illuminate\Http\Response
*/
public function update(Request $request,$id)
{
$eImage = "";
if ($image = $request->file('image')) {
$destinationPath = 'img/';
$eImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $eImage);
$data['image'] = $eImage;
}
else {
$product = DB::table('product')->find($id);
$data['image'] = $product->image; // Keep the existing image value
}
$productName = $request->productName;
$productModel = $request->productModel;
$Price=$request->Price;
$image = $eImage;
$dob = $request->dob;
$description = $request->description;
DB::table('product')->where('id', $id)->update([
'productName' => $productName,
'productModel' => $productModel,
'Price'=>$Price,
'dob' => $dob,
'image' => $image,
'description' => $description,
]);
$data = DB::table('product')->get();
return view('Menudashboard.allproduct', ['data' => $data]);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\ath $ath
* @param \{{ namespacedModel }} ${{ modelVariable }}
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
product::destroy($id);
$data = Product::all();
return view('Menudashboard.allproduct', ['data' => $data]);
}
}
|
import { RESPONSE } from "../../controllers.types";
import { Team } from "../../../models/Team";
import { Folder } from "../../../models/Folder";
import { BODY_CREATE_FOLDER, BODY_EDIT_FOLDER } from "./documents.types";
// Helpers
import { isNameRepeatedDocuments } from "../../helpers/index";
import { shiftChildrenToParent } from "../../helpers/documents";
export const getDocumentsFromBucket = async (req, res) => {
let response: RESPONSE = {
isAuth: true,
message: "",
readMsg: false,
typeMsg: "danger",
data: {}
};
try {
const { bucketId, teamId, folderId } = req.params;
if (isNaN(bucketId) || isNaN(teamId)) {
response.readMsg = true;
response.message = "Invalid credentials.";
res.json(response);
return;
}
const buckets: Array<any> = await req.user.getBuckets({
where: {
id: bucketId
}
});
if (buckets.length == 0) {
response.message = "Invalid id.";
res.json(response);
return;
}
const bucket: any = buckets[0];
const teamRef: any = await Team.findByPk(bucket.teamId);
if (!teamRef) {
response.message = "Invalid id.";
res.json(response);
return;
}
let arrayFinalFolders: Array<any> = [];
let config: any;
if (folderId != "null") {
config = {
hasParent: true,
folderId
};
} else {
config = {
hasParent: false
};
}
const arrayFolders: Array<any> = await bucket.getFolders({
where: config
});
for (let i = 0; i < arrayFolders.length; i++) {
const { ...folderData } = arrayFolders[i].toJSON();
arrayFinalFolders.push({
...folderData,
type: "",
User_Read_Files: []
});
}
let arrayFinalFiles: Array<any> = [];
const arrayFiles: Array<any> = await bucket.getFiles({
where: config
});
for (let i = 0; i < arrayFiles.length; i++) {
const usersRef: Array<any> = await arrayFiles[i].getUsers();
let arrayUsers: Array<any> = [];
for (let j = 0; j < usersRef.length; j++) {
let username: string = usersRef[j].globalUsername;
const teamsUserRef: Array<any> = await usersRef[j].getTeams({
where: {
id: teamRef.id
}
});
if (teamsUserRef.length > 0) {
const teamUserRef: any = teamsUserRef[0];
username = teamUserRef.User_Team.username;
}
const { password: userPswd, ...userData } = usersRef[j].toJSON();
arrayUsers.push({
userData,
username
});
}
const { ...fileData } = arrayFiles[i].toJSON();
arrayFinalFiles.push({
...fileData,
User_Read_Files: arrayUsers
});
}
// Get team from bucket
let arrayFinalUsers: Array<any> = [];
const arrayUsers: Array<any> = await bucket.getUsers();
for (let i = 0; i < arrayUsers.length; i++) {
const teamsUserRef: Array<any> = await arrayUsers[i].getTeams({
where: {
id: teamId
}
});
if (teamsUserRef.length == 0) continue;
const teamRef: any = teamsUserRef[0];
const companiesUserRef: Array<any> = await arrayUsers[i].getCompanies({
where: {
id: teamRef.companyId
}
});
if (companiesUserRef.length == 0) continue;
const companyUserRef = companiesUserRef[0];
const { password: userPswd, ...userData } = arrayUsers[i].toJSON();
arrayFinalUsers.push({
...userData,
username: teamRef.User_Team.username,
typeUser: companyUserRef.User_Company.typeUser
});
}
response.data = {
folders: arrayFinalFolders,
files: arrayFinalFiles,
users: arrayFinalUsers
};
res.json(response);
} catch (error) {
console.error(error);
// Send Error
response.data = {};
response.isAuth = true;
response.message = error.message;
response.readMsg = true;
response.typeMsg = "danger";
res.json(response);
}
};
export const createFolder = async (req, res) => {
let response: RESPONSE = {
isAuth: true,
message: "",
readMsg: true,
typeMsg: "danger",
data: {}
};
try {
const {
name,
folderId,
bucketId,
companyId
}: BODY_CREATE_FOLDER = req.body;
if (isNaN(bucketId) || isNaN(folderId) || isNaN(companyId)) {
response.readMsg = true;
response.message = "Invalid credentials.";
res.json(response);
return;
}
if (name.trim() == "") {
response.readMsg = true;
response.message = "Invalid name.";
res.json(response);
return;
}
if (await isNameRepeatedDocuments(name, folderId, bucketId, false)) {
response.readMsg = true;
response.message = "Name is repeated.";
res.json(response);
return;
}
const buckets: Array<any> = await req.user.getBuckets({
where: {
id: bucketId
}
});
if (buckets.length == 0) {
response.message = "Invalid id.";
res.json(response);
return;
}
const companiesUserRef: Array<any> = await req.user.getCompanies({
where: {
id: companyId
}
});
if (companiesUserRef.length == 0) {
response.message = "Invalid id.";
res.json(response);
return;
}
const companyRef: any = companiesUserRef[0];
const bucket: any = buckets[0];
// Create folder
const newFolder: any = await Folder.create({
name,
isProtected:
companyRef.User_Company.typeUser == "Admin" ||
companyRef.User_Company.typeUser == "Employee",
hasParent: folderId != 0
});
// Add to parent
if (folderId != 0) {
const parentFolder: any = await Folder.findByPk(folderId);
if (parentFolder) {
await parentFolder.addFolder(newFolder);
}
}
// Add to bucket
await bucket.addFolder(newFolder);
response.message = "Folder created successfully!";
response.typeMsg = "success";
res.json(response);
} catch (error) {
console.error(error);
// Send Error
response.data = {};
response.isAuth = true;
response.message = error.message;
response.readMsg = true;
response.typeMsg = "danger";
res.json(response);
}
};
export const editFolder = async (req, res) => {
let response: RESPONSE = {
isAuth: true,
message: "",
readMsg: true,
typeMsg: "danger",
data: {}
};
try {
const {
name,
folderId,
bucketId,
companyId,
isProtected
}: BODY_EDIT_FOLDER = req.body;
if (isNaN(folderId)) {
response.readMsg = true;
response.message = "Invalid credentials.";
res.json(response);
return;
}
if (name.trim() == "") {
response.readMsg = true;
response.message = "Invalid name.";
res.json(response);
return;
}
const buckets: Array<any> = await req.user.getBuckets({
where: {
id: bucketId
}
});
if (buckets.length == 0) {
response.message = "Invalid id.";
res.json(response);
return;
}
const companiesUserRef: Array<any> = await req.user.getCompanies({
where: {
id: companyId
}
});
if (companiesUserRef.length == 0) {
response.message = "Invalid id.";
res.json(response);
return;
}
const companyRef: any = companiesUserRef[0];
// Edit folder
const folderRef: any = await Folder.findByPk(folderId);
if (
await isNameRepeatedDocuments(name, folderRef.folderId, bucketId, name == folderRef.name)
) {
response.readMsg = true;
response.message = "Name is repeated.";
res.json(response);
return;
}
if (!folderRef) {
response.message = "Invalid id.";
res.json(response);
return;
}
// Check if you have permission
if (companyRef.User_Company.typeUser == "Client" && folderRef.isProtected) {
response.message = "You don't have the permission to edit this document.";
res.json(response);
return;
}
await folderRef.update({
name,
isProtected
});
response.message = "Folder edited successfully!";
response.typeMsg = "success";
res.json(response);
} catch (error) {
console.error(error);
// Send Error
response.data = {};
response.isAuth = true;
response.message = error.message;
response.readMsg = true;
response.typeMsg = "danger";
res.json(response);
}
};
export const deleteFolder = async (req, res) => {
let response: RESPONSE = {
isAuth: true,
message: "",
readMsg: true,
typeMsg: "danger",
data: {}
};
try {
const { folderId, bucketId, companyId } = req.params;
if (isNaN(folderId)) {
response.readMsg = true;
response.message = "Invalid credentials.";
res.json(response);
return;
}
const buckets: Array<any> = await req.user.getBuckets({
where: {
id: bucketId
}
});
if (buckets.length == 0) {
response.message = "Invalid id.";
res.json(response);
return;
}
const companiesUserRef: Array<any> = await req.user.getCompanies({
where: {
id: companyId
}
});
if (companiesUserRef.length == 0) {
response.message = "Invalid id.";
res.json(response);
return;
}
const companyRef: any = companiesUserRef[0];
const folderRef: any = await Folder.findByPk(folderId);
if (!folderRef) {
response.message = "Invalid id.";
res.json(response);
return;
}
// Check if you have permission
if (companyRef.User_Company.typeUser == "Client" && folderRef.isProtected) {
response.message =
"You don't have the permission to delete this document.";
res.json(response);
return;
}
// Delete connections
await shiftChildrenToParent(folderRef);
// Destroy folder
await folderRef.destroy();
response.message = "Folder deleted successfully!";
response.typeMsg = "success";
res.json(response);
} catch (error) {
console.error(error);
// Send Error
response.data = {};
response.isAuth = true;
response.message = error.message;
response.readMsg = true;
response.typeMsg = "danger";
res.json(response);
}
};
|
import { Box, Spinner } from "@chakra-ui/react"
import { useEffect, useState } from "react"
import { useAppDispatch, useAppSelector } from "../app/hooks"
import {
getRepoAsync,
selectError,
selectRepo,
selectStatus,
selectUrl,
setStatus,
} from "../features/repos/reposSlice"
import { CheckIfExistRepo } from "../utils/IssuesSort"
import HeadingComponent from "./ui/HeadTitel"
import ColumnsContainer from "./ui/ColumnsContainer"
import { IReposData } from "../app/types"
function HomeMainSection() {
const currentUrl = useAppSelector(selectUrl)
const repos = useAppSelector(selectRepo)
const [repoData, setRepoData] = useState<IReposData[]>()
const status = useAppSelector(selectStatus)
const error = useAppSelector(selectError)
const dispatch = useAppDispatch()
useEffect(() => {
if (currentUrl !== null) {
// Check by url if repository with issues was fetched before and added to the store
const url: string | IReposData = CheckIfExistRepo(repos, currentUrl)
if (typeof url === "string") {
dispatch(getRepoAsync(url))
} else {
dispatch(setStatus("idle"))
setRepoData([url])
}
}
}, [currentUrl, repos])
return (
<main data-testid="main-section">
<Box my={"24px"} mx={"auto"}>
{status === "loading" ? (
<Spinner mx={"auto"} size={["sm", "md", "lg", "xl"]} />
) : null}
{status === "failed" ? <HeadingComponent text={error} /> : null}
{currentUrl !== null && status === "idle" ? (
<>
{repoData !== undefined
? repoData.map((el, i) => (
<ColumnsContainer data={el.issues} key={i} />
))
: repos.map((el, i) => (
<ColumnsContainer data={el.issues} key={i} />
))}
</>
) : null}
</Box>
</main>
)
}
export default HomeMainSection
|
import 'dart:async';
import 'package:animator/animator.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/models/user.dart';
import 'package:fluttershare/pages/activity_feed.dart';
import 'package:fluttershare/pages/comments.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:fluttershare/widgets/progress.dart';
import 'package:fluttershare/widgets/full_image.dart';
class Post extends StatefulWidget {
final String postId;
final String ownerId;
final String username;
final String location;
final String description;
final String mediaUrl;
final dynamic likes;
Post({
this.postId,
this.ownerId,
this.username,
this.location,
this.description,
this.mediaUrl,
this.likes,
});
factory Post.fromDocument(DocumentSnapshot doc) {
return Post(
postId: doc['postId'],
ownerId: doc['ownerId'],
username: doc['username'],
location: doc['location'],
description: doc['description'],
mediaUrl: doc['mediaUrl'],
likes: doc['likes'],
);
}
int getLikeCount(likes) {
if (likes == null) {
return 0;
}
int count = 0;
likes.values.forEach((val) {
if (val == true) {
count += 1;
}
});
return count;
}
@override
_PostState createState() => _PostState(
postId: this.postId,
ownerId: this.ownerId,
username: this.username,
location: this.location,
description: this.description,
mediaUrl: this.mediaUrl,
likes: this.likes,
likeCount: getLikeCount(this.likes),
);
}
class _PostState extends State<Post> {
final String currentUserId = currentUser?.id;
final String postId;
final String ownerId;
final String username;
final String location;
final String description;
final String mediaUrl;
bool showHeart = false;
int likeCount;
Map likes;
bool isLiked;
_PostState({
this.postId,
this.ownerId,
this.username,
this.location,
this.description,
this.mediaUrl,
this.likes,
this.likeCount,
});
handleDeletePost(BuildContext parentContext) {
return showDialog(
context: parentContext,
builder: (context) {
return SimpleDialog(
title: Text(
'Remove this post?',
),
children: <Widget>[
SimpleDialogOption(
onPressed: () {
Navigator.pop(context);
deletePost();
},
child: Text(
'Delete',
style: TextStyle(
color: Colors.red,
),
),
),
SimpleDialogOption(
onPressed: () => Navigator.pop(context),
child: Text(
'Cancel',
),
),
],
);
},
);
}
deletePost() async {
postsRef
.document(ownerId)
.collection('userPosts')
.document(postId)
.get()
.then((doc) {
if (doc.exists) {
doc.reference.delete();
}
});
storageRef.child('post_$postId.jpg').delete();
QuerySnapshot activityFeedSnapshot = await activityFeedRef
.document(ownerId)
.collection('feedItems')
.where('postId', isEqualTo: postId)
.getDocuments();
activityFeedSnapshot.documents.forEach((doc) {
if (doc.exists) {
doc.reference.delete();
}
});
QuerySnapshot commentsSnapshot = await commentsRef
.document(postId)
.collection('comments')
.getDocuments();
commentsSnapshot.documents.forEach((doc) {
if (doc.exists) {
doc.reference.delete();
}
});
}
handleLikePost() {
bool _isLiked = likes[currentUserId] == true;
if (_isLiked) {
postsRef
.document(ownerId)
.collection('userPosts')
.document(postId)
.updateData({'likes.$currentUserId': false});
removeLikeFromActivityFeed();
setState(() {
likeCount -= 1;
isLiked = false;
likes[currentUserId] = false;
});
} else if (!_isLiked) {
postsRef
.document(ownerId)
.collection('userPosts')
.document(postId)
.updateData({'likes.$currentUserId': true});
addLikeToActivityFeed();
setState(() {
likeCount += 1;
isLiked = true;
likes[currentUserId] = true;
showHeart = true;
});
Timer(Duration(milliseconds: 500), () {
setState(() {
showHeart = false;
});
});
}
}
addLikeToActivityFeed() {
bool isNotPostOwner = currentUserId != ownerId;
if (isNotPostOwner) {
activityFeedRef
.document(ownerId)
.collection('feedItems')
.document(postId)
.setData({
'type': 'like',
'username': currentUser.username,
'userId': currentUser.id,
'userProfileImage': currentUser.photoUrl,
'postId': postId,
'mediaUrl': mediaUrl,
'timestamp': timestamp,
});
}
}
removeLikeFromActivityFeed() {
bool isNotPostOwner = currentUserId != ownerId;
if (isNotPostOwner) {
activityFeedRef
.document(ownerId)
.collection('feedItems')
.document(postId)
.get()
.then((doc) {
if (doc.exists) {
doc.reference.delete();
}
});
}
}
buildPostFooter() {
return Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(padding: EdgeInsets.only(top: 40.0, left: 20.0)),
GestureDetector(
onTap: handleLikePost,
child: Icon(
isLiked ? Icons.favorite : Icons.favorite_border,
size: 28.0,
color: Colors.pink,
),
),
Padding(padding: EdgeInsets.only(right: 20.0)),
GestureDetector(
onTap: () => showComments(
context,
postId: postId,
ownerId: ownerId,
mediaUrl: mediaUrl,
),
child: Icon(
Icons.chat,
size: 28.0,
color: Colors.blue[900],
),
),
],
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 20.0),
child: Text(
'$likeCount likes',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 20.0),
child: Text(
'$username',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
Expanded(
child: Text(
description,
overflow: TextOverflow.ellipsis,
),
),
],
),
],
);
}
buildHeader() {
return FutureBuilder(
future: usersRef.document(ownerId).get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
User user = User.fromDocument(snapshot.data);
bool isPostOwner = currentUserId == ownerId;
return Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
CircleAvatar(
radius: 15.0,
backgroundImage:
CachedNetworkImageProvider(user.photoUrl),
),
SizedBox(
width: 5.0,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
GestureDetector(
onTap: () => showProfile(context, profileId: user.id),
child: Text(
user.username,
style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
Text(
location,
style: TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.bold,
color: Colors.grey[500],
),
),
],
),
],
),
isPostOwner
? Icon(
Icons.more_vert,
)
: Text(''),
],
),
);
});
}
buildPostPicture() {
return GestureDetector(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FullPhoto(url: mediaUrl),
),
),
onDoubleTap: handleLikePost,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Container(
height: MediaQuery.of(context).size.width - 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30.0),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
spreadRadius: 2.0,
blurRadius: 20.0,
offset: Offset(0, 10),
),
],
image: DecorationImage(
fit: BoxFit.cover,
image: CachedNetworkImageProvider(mediaUrl),
),
),
),
Positioned(
bottom: 17.0,
right: 70.0,
child: GestureDetector(
onTap: handleLikePost,
child: Icon(
isLiked ? Icons.favorite : Icons.favorite_border,
size: 35,
color: Colors.red.withOpacity(0.7),
),
),
),
Positioned(
bottom: 20.0,
right: 20.0,
child: GestureDetector(
onTap: () => showComments(
context,
postId: postId,
ownerId: ownerId,
mediaUrl: mediaUrl,
),
child: Icon(
Icons.chat,
size: 28.0,
color: Colors.blue[600],
),
),
),
showHeart
? Animator(
duration: Duration(milliseconds: 300),
tween: Tween(begin: 0.8, end: 1.4),
curve: Curves.elasticOut,
cycles: 0,
builder: (context, animatorState, child) => Transform.scale(
scale: animatorState.value,
child: Icon(
Icons.favorite,
size: 80.0,
color: Colors.red,
),
),
)
: Text(""),
],
),
);
}
@override
Widget build(BuildContext context) {
isLiked = (likes[currentUserId] == true);
return Container(
margin: EdgeInsets.all(15.0),
padding: EdgeInsets.symmetric(horizontal: 25.0, vertical: 20.0),
decoration: BoxDecoration(
color: Colors.grey.withOpacity(0.1),
borderRadius: BorderRadius.circular(30),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
buildHeader(),
SizedBox(height: 10.0),
buildPostPicture(),
SizedBox(height: 5.0),
Row(
children: <Widget>[
Container(
child: Text(
'$likeCount likes',
style: TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.bold,
color: Colors.grey,
),
),
),
Expanded(
child: Text(""),
),
Expanded(
child: Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 20.0),
child: Text(
'$username',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
SizedBox(width: 8.0),
Expanded(
child: Text(
description,
overflow: TextOverflow.ellipsis,
),)
],
),
),
],
),
SizedBox(height: 8.0),
],
),
);
}
}
showComments(BuildContext context,
{String postId, String ownerId, String mediaUrl}) {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return Comments(
postId: postId,
postOwnerId: ownerId,
postMediaUrl: mediaUrl,
);
}));
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- insert adjacent text method kisi b position pr
koi b text add karne k lye use hota he agar hm
aik he text ko do different places pe add karte
hain to wo copy hota he. -->
<div id="mydiv">
<h1 id="myh1">Heading 1</h1>
<h2 id="myh2">Heading 2</h2>
<h3 id="myh3">Heading 3</h3>
</div>
<script>
// formula
// targetElement.insertAdjacenttext('position','element')
// position : 'beforebegin' | 'afterbegin' |
// 'beforeend' | 'afterend'..
var target = document.getElementById('myh2');
//var newElement = document.createElement('span');
//newElement.textContent = "This is a span";
// ye is tarah error de raha he. text me srf text
// he likh sakte hain.
var newElement = "This is a span";
// agar isme text k sath <span> tag k sath likhte
// hain to wo b as a text show hota he..
target.insertAdjacentText('beforeend',newElement);
target.insertAdjacentText('afterend',newElement);
var parentNode = document.getElementById('mydiv');
console.log(parentNode);//prints at both places..
// q k ye copy hota he.
</script>
</body>
</html>
|
#!/usr/bin/env python
"""
Example to demonstrate multiple threads interaction
- Hmm, what happens when lock is not acquired?
Copyright: Red Hat, Inc. 2018
Author: Lukas Doktor <ldoktor@redhat.com>
License: GPLv3+
"""
import threading
import time
class SplitPrintThread(threading.Thread):
"""
Prints individual words of the message
"""
def __init__(self, name, msg, lock):
"""
:param name: Name of the thread
:param msg: Message to be sliced and printed
"""
super(SplitPrintThread, self).__init__(name=name)
self.__msg = msg.split(' ')
self.__lock = lock
def run(self):
#if self.__lock.acquire(1):
if self.__lock.acquire(0):
try:
for word in self.__msg:
print("%s: %s" % (self.name, word))
time.sleep(0)
finally:
self.__lock.release()
else:
try:
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
import black_box
black_box.cleanup()
except Exception as details:
print("Fail to cleanup: %s" % details)
def say(no_threads, msg):
"""
Spawns $no_workers to print the message
:param no_threads: How many threads to spawn
:param msg: Message to be printed
"""
lock = threading.Lock()
threads = [SplitPrintThread("worker%s" % i, msg, lock)
for i in range(no_threads)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
if __name__ == "__main__":
say(3, "Welcome to the world of debugging")
|
import { Request, Response } from "express";
import { PrismaClient } from "@prisma/client";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import { generateTokens } from "../../utilities/jwt";
const prisma = new PrismaClient();
export async function createUser(req: Request, res: Response) {
interface Data {
username: string;
email: string;
password: string;
gender: string;
height: number;
weight: number;
date_of_birth: string;
}
const data: Data = req.body; // Extracting data from request object
data.password = await bcrypt.hash(data.password, 10); // Hashing the password before storing in the db
try {
const result = await prisma.user.create({
data,
select: {
username: true,
email: true,
id: true,
},
});
const result2 = await prisma.goal.create({
data: {
userId: result.id,
},
});
const { access_token, refresh_token } = generateTokens(
result.email,
result.username,
result.id
);
console.log(result);
res
.status(200)
.json({ message: "Signed Up :)", access_token, refresh_token });
} catch (error) {
console.log(error);
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTablesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tables', function (Blueprint $table) {
$table->increments('id');
$table->integer('restaurant_id');
$table->tinyInteger('table_number');
$table->integer('number_of_person');
$table->integer('seating_type_id');
$table->tinyInteger('is_available')->default(1)->unsigned();
$table->tinyInteger('at_smoking_area')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tables');
}
}
|
"use server";
import * as z from "zod";
import * as argon2 from "argon2";
import { getPasswordResetTokenByToken } from "@/data/password-reset-token";
import { getUserByEmail } from "@/data/user";
import { NewPasswordSchema } from "@/schemas-form";
import sanityClient from "@/app/libs/sanity";
export const newPassword = async (
values: z.infer<typeof NewPasswordSchema>,
token?: string | null
) => {
if (!token) {
return { error: "Missing token!" };
}
const validatedFields = NewPasswordSchema.safeParse(values);
if (!validatedFields.success) {
return { error: "Invalid fields!" };
}
const { password } = validatedFields.data;
const existingToken = await getPasswordResetTokenByToken(token);
if (!existingToken) {
return { error: "Invalid token!" };
}
const hasExpired = new Date(existingToken.expires) < new Date();
if (hasExpired) {
return { error: "Token has expired!" };
}
const existingUser = await getUserByEmail(existingToken.email);
if (!existingUser) {
return { error: "Email does not exist!" };
}
const hashedPassword = await argon2.hash(password);
await sanityClient
.patch(existingUser._id)
.set({ password: hashedPassword })
.commit();
await sanityClient
.delete(existingToken._id)
.then(() => {})
.catch((err) => {
console.error("Delete failed: ", err.message);
});
return { success: "Password updated!" };
};
|
import 'dart:io';
import 'package:favorite_place/providers/user_places.dart';
import 'package:favorite_place/widget/image_input.dart';
import 'package:favorite_place/widget/location_input.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class AddPlaceScreen extends ConsumerStatefulWidget {
const AddPlaceScreen({super.key});
@override
ConsumerState<AddPlaceScreen> createState() => _AddPlaceScreenState();
}
class _AddPlaceScreenState extends ConsumerState<AddPlaceScreen> {
final _titleController = TextEditingController();
File? _selectImage;
void _savePlace() {
final enteredTitle = _titleController.text;
if (_selectImage == null || enteredTitle.isEmpty) {
return;
}
ref.read(userPlacesProvider.notifier).addPlace(enteredTitle, _selectImage!);
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Add new Place'),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(12),
child: Column(
children: [
TextField(
decoration: const InputDecoration(
labelText: 'Title',
),
style: TextStyle(
color: Theme.of(context).colorScheme.onBackground,
),
controller: _titleController,
),
const SizedBox(
height: 10,
),
//Image Input : this is the fild where we are taking image as input
ImageInput(
onPickImage: (image) {
_selectImage = image;
},
),
const SizedBox(
height: 10,
),
LocationInput(),
const SizedBox(
height: 16,
),
ElevatedButton.icon(
onPressed: _savePlace,
icon: const Icon(Icons.add),
label: const Text('Add Place'),
),
],
),
),
);
}
}
|
<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\RegistrationFormType;
use App\Security\AppCustomAuthenticator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
class RegistrationController extends AbstractController
{
private $mailer;
public function __construct(MailerInterface $mailer)
{
$this->mailer = $mailer;
}
/**
* @Route("/register", name="app_register")
*/
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, UserAuthenticatorInterface $userAuthenticator, AppCustomAuthenticator $authenticator, EntityManagerInterface $entityManager,MailerInterface $mailer ): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
//Définition du rôle et de l'état actif de l'utilisateur :
$user->setRoles(['ROLE_CLIENT']);
$user->setActive(true);
$user->setRegisteredAt(new \DateTime());
//Persist et flush de l'entité utilisateur en base de données :
$entityManager->persist($user);
$entityManager->flush();
//envoi mail
$userEmail = $user->getEmail();
// $this->sendWelcomeEmail($userEmail);
$email = (new Email())
->from('contact@femHealth.com')
->to($user->getEmail())
->subject('Welcome to Our Application')
->html('<p>Welcome to Our Application! We are excited to have you on board.</p>');
$this->mailer->send($email);
// do anything else you need here, like send an email
//Authentification de l'utilisateur nouvellement enregistré
return $userAuthenticator->authenticateUser(
$user,
$authenticator,
$request
);
}
//Rendu du formulaire d'inscription en cas d'erreur
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
}
|
import React from 'react';
import useFetch from '../hooks/useFetch';
import {
POST_CREATE_TOKEN,
GET_USER,
POST_DELETE_REFRESH_TOKEN
} from '../api/api';
import storage from '../functions/handleLocalStorage';
import { useNavigate } from 'react-router-dom';
export const UserContext = React.createContext();
export const UserStorage = ({ children }) => {
const [user, setUser] = React.useState(null);
const [login, setlogin] = React.useState(false);
const navigate = useNavigate();
const { loading, error, request } = useFetch();
const getUser = React.useCallback(async () => {
const accessToken = storage.get('accessToken');
if (accessToken) {
const { url, options } = GET_USER({ accessToken });
const { response, json } = await request(url, options);
if (response.ok && json.data) {
setUser(json.data);
return true;
}
} else {
setUser(null);
return false;
}
}, []);
const userLogin = React.useCallback(async (email, password) => {
const { url, options } = POST_CREATE_TOKEN({ email, password });
const { json, response } = await request(url, options);
if (response.ok && json.data) {
storage.set('accessToken', json.data.accessToken);
storage.set('refreshToken', json.data.refreshToken);
await getUser();
setlogin(true);
navigate('/dashboard');
}
}, []);
const userLogout = React.useCallback(async () => {
const refreshToken = storage.get('refreshToken');
if (refreshToken) {
const { url, options } = POST_DELETE_REFRESH_TOKEN({ refreshToken });
const { response, json } = await request(url, options);
storage.delete('accessToken');
storage.delete('refreshToken');
setUser(null);
setlogin(false);
} else {
storage.delete('accessToken');
storage.delete('refreshToken');
setUser(null);
setlogin(false);
}
}, []);
const autoUserLogin = React.useCallback(async () => {
const isTokenValidated = await getUser();
if (!isTokenValidated) {
userLogout()
} else {
setlogin(true);
navigate('/dashboard');
}
}, []);
// React.useEffect(() => {
// autoUserLogin();
// }, []);
return (
<UserContext.Provider
value={{ loading, error, userLogin, login, user, userLogout }}
>
{children}
</UserContext.Provider>
);
};
|
import {
Body,
Controller,
Get,
Param,
Post,
Put,
UploadedFile,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { FirebaseAuth } from 'src/common/decorators/auth.decorator';
import { CreateUserWithEmailInput } from './dto/create-user-with-email.input';
import { UpdateUserInput } from './dto/update-user.input';
import { UserWithTokenEntity } from './entities/user-with-token.entity';
import { UserEntity } from './entities/user.entity';
import { CreateUserWithEmail } from './use-case/create-user-with-email';
import { UserService } from './user.service';
import { AuthGuard } from 'src/common/guards/auth.guard';
import { FileInterceptor } from '@nestjs/platform-express';
import { UpdateFileToFirebaseStorage } from 'src/common/file/update-file-service';
import {
SignInWithGithubInput,
SignInWithGoogleInput,
} from './dto/sign-in-with-google-or-github.input';
import { SignInWithGoogleOrGithubService } from './use-case/sign-in-with-google-or-github.service';
import { FirebaseAppName } from 'src/common/enums/storage-type';
@Controller('user')
export class UserController {
constructor(
private readonly userService: UserService,
private readonly createUserWithEmail: CreateUserWithEmail,
private readonly signInWithGoogleOrGithubService: SignInWithGoogleOrGithubService,
private readonly updateFileToFirebaseStorage: UpdateFileToFirebaseStorage,
) {}
@Get()
async findAll(): Promise<UserEntity[]> {
return await this.userService.findAll();
}
@Get('find-by-id/:id')
async findById(@Param('id') id: string): Promise<UserEntity> {
return await this.userService.find(id);
}
@Get('find-by-firebase-uid')
@UseGuards(AuthGuard)
async findByFirebaseUID(@FirebaseAuth() authUser: any): Promise<UserEntity> {
return await this.userService.findByFirebaseUID(authUser.uid);
}
// 認証使わない(SSRの際に使用する)
@Get(':firebaseUID')
async findByFirebaseUIDWithoutFirebaseAuth(
@Param('firebaseUID') firebaseUID: string,
) {
return await this.userService.findByFirebaseUID(firebaseUID);
}
@Post()
async createWithEmailAndPassword(
@Body() input: CreateUserWithEmailInput,
): Promise<UserWithTokenEntity> {
return await this.createUserWithEmail.handle(input);
}
@Post('sign-in-with-google-or-github')
@UseGuards(AuthGuard)
async signInWithGoogleOrGithub(
@FirebaseAuth() authUser: any,
@Body() githubInput?: { githubAccount: string },
): Promise<UserEntity> {
//TODO: authUserの型をそもそも判定しておきたい
const signInInput: SignInWithGoogleInput | SignInWithGithubInput = {
firebaseUID: authUser.uid,
email: authUser.email,
name: authUser.name,
imageUrl: authUser.picture,
githubAccount: githubInput.githubAccount,
};
return await this.signInWithGoogleOrGithubService.handle(signInInput);
}
@Put('update-by-firebase-uid')
@UseGuards(AuthGuard)
@UseInterceptors(FileInterceptor('imageFile'))
async update(
@FirebaseAuth() authUser: any,
@Body() input: UpdateUserInput,
@UploadedFile() imageFile?: Express.Multer.File,
): Promise<any> {
if (imageFile) {
const user = await this.userService.findByFirebaseUID(authUser.uid);
//firebaseのstorageに保存 & 画像url生成
const newImageUrl = await this.updateFileToFirebaseStorage.handle(
imageFile,
FirebaseAppName.USER,
user.imageUrl,
);
input = {
...input,
imageUrl: newImageUrl,
};
}
input = {
...input,
age: input.age ? parseInt(input.age as string) : null,
};
return await this.userService.updateByFirebaseUID(
authUser.uid,
input as UpdateUserInput & { age: number | null },
);
}
}
|
import { createContext, useState } from "react";
interface AppContextInterface {
dark: boolean;
changeMode: () => void;
}
export const AppCtx = createContext<AppContextInterface | null>(null);
export const OurApp = (props: any) => {
const [dark, setDark] = useState(true);
const AppContext: AppContextInterface = {
dark: dark,
changeMode: () => {
setDark((old) => !old);
},
};
return <AppCtx.Provider value={AppContext}>{props.children}</AppCtx.Provider>;
};
|
import time
import msgpack
import logging
import redis
import uuid
from datetime import datetime
from typing import Dict
from ml_sdk.communication.redis import RedisSettings
from ml_sdk.database import DatabaseInterface
from ml_sdk.io import TestJob, TrainJob, JobID, InferenceOutput, InferenceInput, ModelVersion
logger = logging.getLogger(__name__)
class RedisDatabase(DatabaseInterface):
def __init__(self, settings: RedisSettings):
self.topic = settings.topic
redis_pool = redis.ConnectionPool(**settings.conf)
self.redis = redis.StrictRedis(connection_pool=redis_pool)
@staticmethod
def _decode(msg):
return msgpack.unpackb(msg, use_list=False, raw=False)
@staticmethod
def _encode(msg):
return msgpack.packb(msg, use_bin_type=True)
def get_test_job(self, job_id: JobID) -> TestJob:
job = self._decode(self.redis.get(job_id))
job = TestJob(**job)
processed_keys = self.redis.keys(f"{self.topic}_{job_id}_*")
results = self.redis.mget(processed_keys)
job.results = [self._decode(r) for r in results]
job.processed = len(results)
return job
def create_test_job(self, total: int) -> TestJob:
job_id = uuid.uuid4()
job = TestJob(
job_id=JobID(job_id),
total=total,
started_at=str(datetime.now())
)
self.redis.set(str(job_id), self._encode(dict(job)))
return job
def update_test_job(self, job: TestJob, task: InferenceOutput):
task_id = f"{self.topic}_{job.job_id}_{uuid.uuid4()}"
self.redis.set(task_id, self._encode(task))
def get_train_job(self, job_id: JobID) -> TrainJob:
job = self._decode(self.redis.get(job_id))
return TrainJob(**job)
def create_train_job(self) -> TrainJob:
job_id = uuid.uuid4()
job = TrainJob(
job_id=JobID(job_id),
total=100,
started_at=str(datetime.now())
)
self.redis.set(str(job_id), self._encode(dict(job)))
return job
def update_train_job(self, job: TrainJob, version: ModelVersion):
job_id = job.job_id
job = self.get_train_job(job_id)
job.processed = job.total
job.version = version
job.end_at = str(datetime.now())
self.redis.set(str(job_id), self._encode(dict(job)))
|
package com.example.changshuai.microuniversity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.changshuai.microuniversity.dao.PeripheralShopDao;
import com.example.changshuai.microuniversity.entity.PeripheralShop;
import com.example.changshuai.microuniversity.listener.TopBackListener;
import java.util.List;
import static com.example.changshuai.microuniversity.R.id.tv_name;
public class PeripheralShopActivity extends AppCompatActivity {
private TextView action_bar_title;
private ImageView action_bar_back;
private ListView ps_list;
private PeripheralShopDao peripheralShopDao;
private List<PeripheralShop> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_peripheral_shop);
action_bar_title = (TextView) findViewById(R.id.action_bar_title1);
action_bar_title.setText("周边店铺");
action_bar_back = (ImageView) findViewById(R.id.action_bar_back);
action_bar_back.setOnClickListener(new TopBackListener(this, action_bar_back));
peripheralShopDao = new PeripheralShopDao(this);
if (peripheralShopDao.findAll().size() == 0){
addFakeData();
}
list = peripheralShopDao.findAll();
ps_list = (ListView) findViewById(R.id.ps_list);
ps_list.setAdapter(new PSListViewApdater(this));
}
public void addFakeData(){
long basenumber = 13500000000l;
for(int i = 0;i<10;i++){
peripheralShopDao.add("张三"+i, "半亩塘"+i, "美容美发"+i, String.valueOf(basenumber+i));
}
Toast.makeText(this, "数据添加完毕", Toast.LENGTH_LONG).show();
}
private class PSListViewApdater extends BaseAdapter {
private Context context;
private TextView ilps_telephone;
public PSListViewApdater(Context context) {
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view =null;
if(convertView==null){
view = View.inflate(context, R.layout.item_list_ps, null);
}else{
view = convertView;
}
TextView ilps_name = (TextView) view.findViewById(R.id.ilps_name);
TextView ilps_context = (TextView) view.findViewById(R.id.ilps_context);
TextView ilps_address = (TextView) view.findViewById(R.id.ilps_address);
ilps_telephone = (TextView) view.findViewById(R.id.ilps_telephone);
Button ilps_call = (Button) view.findViewById(R.id.ilps_call);
ilps_name.setText(list.get(position).getName());
ilps_context.setText(list.get(position).getContext());
ilps_address.setText(list.get(position).getAddress());
ilps_telephone.setText(list.get(position).getTelephone());
ilps_call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Telphone = ilps_telephone.getText().toString();
Uri uri = Uri.parse("tel:" + Telphone);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_DIAL);
intent.setData(uri);
startActivity(intent);
}
});
return view;
}
}
}
|
# Инкапсуляция заключается в сборе в одно место данных и методов для работы с ними
# и предоставлении пользователю публичного интерфейса (API)
# _ - знак того, что атрибут не предназначен для прямого использования
class Human:
def __init__(self, first_name: str, last_name: str, status: str, age: int):
self._first_name = first_name
self._last_name = last_name
self._status = status
self.__age = age
def set_age(self, age):
if age < 1 or age > 120:
raise ValueError(f'Age must be in range 1-120')
self.__age = age
def describe(self):
print(f'This is {self._first_name} {self._last_name}, '
f'I am {self.__age} years old. My status: {self._status}')
if __name__ == '__main__':
first_human = Human('Monte', 'Cristo', 'prison', 42)
first_human.set_age(119)
first_human.describe()
|
// This code was taken and adapted from LLVM project:
//===-- Nearest integer floating-point operations ---------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// https://github.com/llvm/llvm-project/blob/main/libc/utils/FPUtil/NearestIntegerOperations.h
#include <cstdint>
#include "sdl_proxy/sdl_stdinc.h"
#if defined(arm) && !defined(__SOFTFP__) && !defined(__VFP_FP__) && !defined(__MAVERICK__)
inline void swap_halfes(uint64_t &x)
{
uint64_t y = ((x & 0xFFFFFFFF00000000) >> 32) & 0xFFFFFFFF;
x = ((x << 32) & 0xFFFFFFFF00000000) & y;
}
#else // Do nothing
# define swap_halfes(x)
#endif
namespace PgeFloatProp
{
static const uint32_t bitWidth = sizeof(uint64_t) << 3;
static const uint32_t mantissaWidth = 52;
static const uint32_t exponentWidth = 11;
static const uint64_t mantissaMask = (uint64_t(1) << mantissaWidth) - 1;
static const uint64_t signMask = uint64_t(1) << (exponentWidth + mantissaWidth);
static const uint64_t exponentMask = ~(signMask | mantissaMask);
static const uint32_t exponentBias = 1023;
// If a number x is a NAN, then it is a quiet NAN if:
// QuietNaNMask & bits(x) != 0
// Else, it is a signalling NAN.
static const uint64_t quietNaNMask = 0x0008000000000000ULL;
}
union PgeFPBits
{
uint64_t bits;
void setMantissa(uint64_t mantVal)
{
swap_halfes(bits);
mantVal &= (PgeFloatProp::mantissaMask);
bits &= ~(PgeFloatProp::mantissaMask);
bits |= mantVal;
swap_halfes(bits);
}
uint64_t getMantissa() const
{
uint64_t ret = bits;
swap_halfes(ret);
return ret & PgeFloatProp::mantissaMask;
}
void setUnbiasedExponent(uint64_t expVal)
{
swap_halfes(bits);
expVal = (expVal << (PgeFloatProp::mantissaWidth)) & PgeFloatProp::exponentMask;
bits &= ~(PgeFloatProp::exponentMask);
bits |= expVal;
swap_halfes(bits);
}
uint16_t getUnbiasedExponent() const
{
uint64_t ret = bits;
swap_halfes(ret);
return uint16_t((ret & PgeFloatProp::exponentMask) >>
(PgeFloatProp::mantissaWidth));
}
void setSign(bool signVal)
{
swap_halfes(bits);
bits &= ~(PgeFloatProp::signMask);
uint64_t sign = uint64_t(signVal) << (PgeFloatProp::bitWidth - 1);
bits |= sign;
swap_halfes(bits);
}
bool getSign() const
{
uint64_t ret = bits;
swap_halfes(ret);
return ((ret & PgeFloatProp::signMask) >> (PgeFloatProp::bitWidth - 1));
}
double val;
static const int exponentBias = (1 << (PgeFloatProp::exponentWidth - 1)) - 1;
static const int maxExponent = (1 << PgeFloatProp::exponentWidth) - 1;
static const uint64_t minSubnormal = uint64_t(1);
static const uint64_t maxSubnormal = (uint64_t(1) << PgeFloatProp::mantissaWidth) - 1;
static const uint64_t minNormal = (uint64_t(1) << PgeFloatProp::mantissaWidth);
static const uint64_t maxNormal = ((uint64_t(maxExponent) - 1) << PgeFloatProp::mantissaWidth) | maxSubnormal;
explicit PgeFPBits(double x) : val(x) {}
explicit PgeFPBits(uint64_t x) : bits(x) {}
PgeFPBits() : bits(0) {}
explicit operator double()
{
return val;
}
uint64_t uintval() const
{
uint64_t ret = bits;
swap_halfes(ret);
return ret;
}
int getExponent() const
{
return int(getUnbiasedExponent()) - exponentBias;
}
bool isZero() const
{
return getMantissa() == 0 && getUnbiasedExponent() == 0;
}
bool isInf() const
{
return getMantissa() == 0 && getUnbiasedExponent() == maxExponent;
}
bool isNaN() const
{
return getUnbiasedExponent() == maxExponent && getMantissa() != 0;
}
bool isInfOrNaN() const
{
return getUnbiasedExponent() == maxExponent;
}
static PgeFPBits zero()
{
return PgeFPBits();
}
static PgeFPBits negZero()
{
return PgeFPBits(uint64_t(1) << (sizeof(uint64_t) * 8 - 1));
}
static PgeFPBits inf()
{
PgeFPBits bits;
bits.setUnbiasedExponent(maxExponent);
return bits;
}
static PgeFPBits negInf()
{
PgeFPBits bits = inf();
bits.setSign(1);
return bits;
}
static double buildNaN(uint64_t v)
{
PgeFPBits bits = inf();
bits.setMantissa(v);
return double(bits);
}
};
SDL_FORCE_INLINE double pge_toNearest(double x)
{
PgeFPBits bits(x);
// If x is infinity NaN or zero, return it.
if(bits.isInfOrNaN() || bits.isZero())
return x;
bool isNeg = bits.getSign();
int exponent = bits.getExponent();
// If the exponent is greater than the most negative mantissa
// exponent, then x is already an integer.
if(exponent >= (int)PgeFloatProp::mantissaWidth)
return x;
if(exponent <= -1)
{
if(exponent <= -2 || bits.getMantissa() == 0)
return isNeg ? (-0.0) : (0.0); // abs(x) <= 0.5
else
return isNeg ? (-1.0) : (1.0); // abs(x) > 0.5
}
uint32_t trimSize = PgeFloatProp::mantissaWidth - exponent;
PgeFPBits newBits = bits;
newBits.setMantissa((bits.getMantissa() >> trimSize) << trimSize);
double truncValue = double(newBits);
if(truncValue == x)
return x;
uint64_t trimValue = bits.getMantissa() & ((uint64_t(1) << trimSize) - 1);
uint64_t halfValue = (uint64_t(1) << (trimSize - 1));
// If exponent is 0, trimSize will be equal to the mantissa width, and
// truncIsOdd` will not be correct. So, we handle it as a special case
// below.
uint64_t truncIsOdd = newBits.getMantissa() & (uint64_t(1) << trimSize);
if(trimValue > halfValue)
return isNeg ? truncValue - double(1.0) : truncValue + double(1.0);
else if(trimValue == halfValue)
{
if(exponent == 0)
return isNeg ? double(-2.0) : double(2.0);
if(truncIsOdd)
return isNeg ? truncValue - double(1.0) : truncValue + double(1.0);
else
return truncValue;
}
else
return truncValue;
}
|
package org.recipefinder.recipefinder.auth;
import org.recipefinder.recipefinder.auth.dto.AuthenticationRequest;
import org.recipefinder.recipefinder.auth.dto.AuthenticationResponse;
import org.recipefinder.recipefinder.auth.dto.RegisterRequest;
import org.recipefinder.recipefinder.config.JwtService;
import org.recipefinder.recipefinder.customer.Customer;
import org.recipefinder.recipefinder.customer.CustomerRepository;
import org.recipefinder.recipefinder.customer.Role;
import org.recipefinder.recipefinder.exceptions.AuthenticationException;
import org.recipefinder.recipefinder.exceptions.customer.CustomerNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class AuthenticationService {
private final CustomerRepository customerRepository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
private final AuthenticationManager authenticationManager;
@Autowired
public AuthenticationService(AuthenticationManager authenticationManager, CustomerRepository customerRepository, PasswordEncoder passwordEncoder, JwtService jwtService) {
this.authenticationManager = authenticationManager;
this.customerRepository = customerRepository;
this.passwordEncoder = passwordEncoder;
this.jwtService = jwtService;
}
public AuthenticationResponse register(RegisterRequest registerRequest) {
if (isValidRegistrationData(registerRequest)) {
throw new AuthenticationException("Please provide all required fields (email, firstName, lastName, password)");
}
var customer = new Customer(
registerRequest.email(),
registerRequest.firstName(),
registerRequest.lastName(),
passwordEncoder.encode(registerRequest.password()),
Role.ROLE_USER
);
customerRepository.save(customer);
var jwtToken = jwtService.generateJwtToken(customer);
return new AuthenticationResponse(HttpStatus.CREATED.value(), HttpStatus.CREATED.toString(), jwtToken);
}
private boolean isValidRegistrationData(RegisterRequest registerRequest) {
return registerRequest.password() == null
|| registerRequest.password().isBlank()
|| registerRequest.email() == null
|| registerRequest.email().isBlank()
|| registerRequest.firstName() == null
|| registerRequest.firstName().isBlank()
|| registerRequest.lastName() == null
|| registerRequest.lastName().isBlank();
}
public AuthenticationResponse login(AuthenticationRequest loginRequest) {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginRequest.email(),
loginRequest.password()
)
);
var customer = customerRepository.findCustomerByEmail(loginRequest.email())
.orElseThrow(() -> new CustomerNotFoundException("Invalid email or password"));
var jwtToken = jwtService.generateJwtToken(customer);
return new AuthenticationResponse(HttpStatus.OK.value(), HttpStatus.OK.toString(), jwtToken);
}
}
|
#!/usr/local/bin/ruby
#--
# Have faith in the way things are.
#
# titlecase.rb
# current v.: 0.0.1
# date: 2013.06.25
#++
# == Description
# uppercase first letters of words
#
# == Usage
# titlecase.rb
#
# == Author
# rimbaud1854
#
# == Copyright
# Copyright (c) 2013 rimbaudcode
# Licensed under GPLv3+. No warranty provided.
class String
# Dave Thomas and Andrew Hunt. Programming Ruby
def titlecase
gsub(/\b\w/) do |first| first.upcase end
end
def titlecase!
gsub!(/\b\w/) do |first| first.upcase end
end
end
if $0 == __FILE__
begin
puts "this is a string".titlecase
exit
rescue
$stderr.puts "#{$!}"
$@.each do |item| $stderr.puts item end
abort
ensure
#
end
end
|
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import useAuth from '../../../hooks/useAuth';
import usePatient from '../../../hooks/usePatient';
import { AppointmentList } from '../../../components';
import Loading from '../../../components/Loading';
const AppointmentPatient = () => {
const {
auth: { user },
} = useAuth();
const {
appointmentList,
getAppointment,
pages,
page,
setPage,
itemsCount,
loading,
} = usePatient();
const [startDate, setStartDate] = useState({
startDate: '',
endDate: '',
});
useEffect(() => {
const get = async () => {
await getAppointment(user.patientID, page, startDate);
};
get();
}, [page, startDate]);
return (
<div className='md:m-auto mt-20 w-full'>
<div className='flex justify-center'>
<div className='w-full h-3/4 bg-white rounded-lg shadow-lg lg:w-3/4 p-5'>
<span className='flex justify-between my-2'>
<h3 className='text-2xl font-bold'>Mis turnos</h3>
<Link
to='/turnos'
className='flex justify-center bg-main hover:bg-secondary text-white p-2 ml-auto rounded-md'>
Crear turnos
</Link>
</span>
{appointmentList?.items?.length > 0 ? (
<AppointmentList
turnos={appointmentList?.items}
pages={pages}
page={page}
setPage={setPage}
itemsCount={itemsCount}
loading={loading}
startDate={startDate}
setStartDate={setStartDate}
user={user}
/>
) : (
<div>No se encontraron turnos registrados</div>
)}
</div>
</div>
</div>
);
};
export default AppointmentPatient;
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Import SafeMath library to prevent integer overflow and underflow errors
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract SlotMachine {
// Use SafeMath for uint256 to prevent integer overflow and underflow errors
using SafeMath for uint256;
// Contract owner's address and betting amount
address payable public owner;
uint256 public bettingAmount;
// Contract balance and player balances
uint256 public balance;
mapping(address => uint256) public playerBalance;
// Keep track of players who have already played
mapping(address => bool) public hasPlayed;
// Events for when a player plays and claims winnings
event Played(address player, uint256 amount, uint8[] results, bool won);
event WinningsClaimed(address player, uint256 amount);
// Constructor function that initializes the contract owner and betting amount
constructor() {
owner = payable(msg.sender);
bettingAmount = 0.01 ether; // Set default betting amount to 0.01 ether
balance = 0;
}
// Function for playing the slot machine
function play() public payable {
// Check if player has sent enough ether to place a bet
require(msg.value >= bettingAmount, "Insufficient bet amount.");
// Check if player has already played
require(!hasPlayed[msg.sender], "You have already played.");
// Generate random results using a seed derived from current block data and player address
uint8[] memory results = new uint8[](3);
uint256 seed = uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, msg.sender)));
for (uint8 i = 0; i < 3; i++) {
results[i] = uint8((seed >> (i * 8)) & 0xff) % 10; // Get random number between 0 and 9
}
// Calculate winnings based on the results
uint256 winnings = 0;
if (results[0] == results[1] && results[1] == results[2]) {
winnings = bettingAmount.mul(100); // Three of a kind pays 100x the betting amount
} else if (results[0] == results[1] || results[1] == results[2]) {
winnings = bettingAmount.mul(10); // Two of a kind pays 10x the betting amount
} else if (results[0] == results[2]) {
winnings = bettingAmount.mul(5); // Two of a kind with the third number matching pays 5x the betting amount
}
// Update player balance and contract balance
playerBalance[msg.sender] = winnings.add(playerBalance[msg.sender]);
balance = balance.add(msg.value).sub(winnings);
hasPlayed[msg.sender] = true;
// Emit event
emit Played(msg.sender, msg.value, results, winnings > 0); // Pass in whether the player won or not
}
// Function for players to claim their winnings
function claimWinnings() public {
// Check if player has any winnings to claim
require(playerBalance[msg.sender] > 0, "You have no winnings to claim.");
// Transfer winnings to player
uint256 amount = playerBalance[msg.sender];
playerBalance[msg.sender] = 0;
payable(msg.sender).transfer(amount);
// Emit event
emit WinningsClaimed(msg.sender, amount);
}
// Function for the contract owner to withdraw the contract balance
function withdrawBalance() public {
// Check if caller is the contract owner
require(msg.sender == owner, "Only the contract owner can withdraw the balance.");
// Transfer balance to owner
uint256 amount = balance;
balance = 0;
owner.transfer(amount);
}
// Function for the contract owner to update the betting amount
function setBettingAmount(uint256 newAmount) public {
// Check if caller is the contract owner
require(msg.sender == owner, "Only the contract owner can update the betting amount.");
// Update betting amount
bettingAmount = newAmount;
}
// Function to get the current contract balance
function getBalance() public view returns (uint256) {
return balance;
}
// Function to get a player's current balance
function getPlayerBalance() public view returns (uint256) {
return playerBalance[msg.sender];
}}
|
import { useEffect, useState } from "react";
import Loading from "./Loading";
import { ITeam } from "../Interfaces/ITeam";
import Error from "./Error";
import { ITeamsProps } from "../Interfaces/ITeamsProps";
export default function Teams({ leagueId, season, failedLogin, error }: ITeamsProps): JSX.Element {
const [teams, setTeams] = useState<ITeam[]>([]);
const [teamId, setTeamId] = useState<number | string>();
useEffect(() => {
const fetchTeams = async () => {
try {
const token = localStorage.getItem('token');
if (leagueId && season) {
const result = await fetch(`${process.env.REACT_APP_URL_TEAMS}${leagueId}&season=${season}` as string, {
"method": "GET",
"headers": {
"x-rapidapi-host": "v3.football.api-sports.io",
"x-rapidapi-key": `${token}`
}
});
const teamsData = await result.json();
const teamsMap = teamsData.response.map((item: { team: string[]; }) => item.team);
setTeams(teamsMap);
};
} catch (error) {
console.error(error);
}
};
fetchTeams();
}, [leagueId, season]);
console.log(teams);
console.log(teamId);
// const handleSelectChange = (event) => {
// setSelectedValue(event.target.value);
// };
if (!teams.length) {
return (<Loading />);
};
return (
<section className="teams-selection">
{
(failedLogin)
?
<Error error={error} />
:
<>
<p>Selecione um Time</p>
<select value={teamId} onChange={({ target: { value } }) => {
console.log(value);
setTeamId(value)
}}>
{teams.map((team: ITeam) => (
<option key={team.id} value={team.id}>{team.name}</option>
))}
</select>
</>
}
</section>
)
};
|
# Landing Page Clone do Banco Itaú
Este é um projeto de uma landing page clone do Banco Itaú, desenvolvido utilizando React, HTML e a biblioteca Styled-components para estilização. O React Hook UseRef foi utilizado para manipular eventos de clique do usuário.
## Funcionalidades
- Réplica da interface da página inicial do Banco Itaú (uma das versões já criada).
- Manipulação de eventos de clique do usuário para interação com elementos da página.
## Componentes
Este projeto é composto por três componentes principais:
1. **Header**: Este componente representa o cabeçalho da página, contendo o logotipo e possíveis links de navegação.
2. **Section Hero**: Este componente representa a seção inicial da página, que normalmente contém uma mensagem de boas-vindas, informações sobre os produtos ou serviços principais e uma imagem de destaque.
3. **SectionService**: Este componente representa a seção de serviços do Banco Itaú, destacando os principais serviços oferecidos pela instituição.
## Pré-requisitos
Antes de começar, verifique se você possui os seguintes requisitos:
- Node.js instalado na sua máquina
- Yarn instalado na sua máquina
- Um navegador web moderno
## Instalação e Uso
Para instalar e usar este projeto, siga estes passos:
1. Clone este repositório:
```
git clone https://github.com/seu-usuario/landing-page-clone
```
2. Navegue até o diretório do projeto:
```
cd landing-page-clone
```
3. Instale as dependências:
```
yarn install
```
4. Inicie a aplicação:
```
yarn start
```
5. Acesse a aplicação em seu navegador web em `http://localhost:3000`.
## Preview:

*Display da Aplicação. A versão mobile será criada através dos Media Queries.*
## Contribuição
Contribuições são o que tornam a comunidade de código aberto um lugar incrível para aprender, inspirar e criar. Quaisquer contribuições que você fizer são **muito bem-vindas**.
1. Fork o projeto
2. Crie uma branch para sua feature (`git checkout -b feature/AmazingFeature`)
3. Faça commit de suas mudanças (`git commit -m 'Adiciona uma feature incrível'`)
4. Faça push para a branch (`git push origin feature/AmazingFeature`)
5. Abra um Pull Request
|
---
id: 144
title: Read/write on ext2/ext3/ext4 partitions from Mac & HFS+ from Linux
author: Jose Cerrejon
icon: pen-to-square
date: 2013-05-01 08:50:00
prev: /
next: false
category:
- Linux
- Apple
tag:
- Linux
- Apple
---
# Read/write on ext2/ext3/ext4 partitions from Mac & HFS+ from Linux
<a href="/images/2013/05/ubu_desktop.jpg" target="_blank" title="Press to see in a new window"><img src="/images/2013/05/ubu_desktop_min.jpg" width="324" height="242"></a>
I have spent almost a week with *Ubuntu 13.04* on my *iMac*, and the most difficult to me was to config the keyboard and mouse *Bluetooth* and access to both partitions from each operating system, more mostly by ignorance, so here are my notes, because has not been easy to find the solution. Let's Started!
- - -
### Access HFS+ partition from Ubuntu
In theory, we can access the file system without problems, but when we try it on any folder in */Users/yourusername*, we find the following message:

To fix this, nothing easier than starting our *OSX*, and right click on the folder you want to access from *Linux* and select *Get Info*. Below, we can see the user permissions. In our case, we will share the *Downloads* folder.
We see that the permissions for *everyone* is set to *No Access*.

So we change it to Read or Read/Write.


***TIP:*** Maybe is not a good idea to *OSX* that you set up write permissions in your file system from another operating system. As a general rule I set read only, and create a *NTFS* partition to data exchange.
With these steps, you will have access to the partition of our *OSX* and best, without installing anything.

### Access ext2/ext3/ext4 partitions from OSX
To access our *Linux* partitions, we will install two applications: [OSXFUSE](http://osxfuse.github.io) and [fuse-ext2](http://sourceforge.net/projects/fuse-ext2/).

Once you reboot the system, we will have access to our *Linux* file system, in this case *disk0s3*.

I recommend its use in moderation, and with a little care when copying files. Better if you use it to read files. Until next time!
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strdup.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: panoma <marvin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/12/19 15:25:33 by panoma #+# #+# */
/* Updated: 2022/12/19 15:38:00 by panoma ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strdup(const char *s1)
{
char *new;
size_t len;
int i;
len = ft_strlen(s1);
new = malloc(sizeof(char) * (len + 1));
if (!new)
return (NULL);
i = 0;
while (s1[i])
{
new[i] = s1[i];
i++;
}
new[i] = '\0';
return (new);
}
|
# 原文
我出我车,于彼牧矣[^1]。自天子所[^2],谓我来矣[^3]。召彼仆夫[^4],谓之载矣。王事多难,维其棘矣[^5]。
我出我车,于彼郊矣。设此旐矣[^6],建彼旄矣[^7]。彼旟旐斯[^8],胡不旆旆[^9]?忧心悄悄[^10],仆夫况瘁[^11]。
王命南仲[^12],往城于方[^13]。出车彭彭[^14],旂旐央央[^15]。天子命我,城彼朔方。赫赫南仲[^16],玁狁于襄[^17]。
昔我往矣,黍稷方华[^18]。今我来思,雨雪载涂[^19]。王事多难,不遑启居。岂不怀归?畏此简书[^20]。
喓喓草虫[^21],趯趯阜螽[^22]。未见君子,忧心忡忡。既见君子,我心则降[^23]。赫赫南仲,薄伐西戎[^24]。
春日迟迟[^25],卉木萋萋[^26]。仓庚喈喈[^27],采蘩祁祁[^28]。执讯获丑[^29],薄言还归。赫赫南仲,玁狁于夷[^30]。
# 笔记
# 题解
这是一位武士自述他跟随统帅南仲出征及凯旋的诗。当时西周面临的敌人,北有玁狁,西有昆夷,为了王朝的安定,周王朝曾多次派兵征讨。以南仲为统帅的这次征讨,取得了辉煌的战果。诗人以满腔热情歌颂了南仲的赫赫战功,同时也表达了自己身历其境的艰辛困苦和胜利后的喜悦之情。方玉润《诗经原始》说:“此诗以伐玁狁为主脑,西戎为余波,凯还为正意,出征为追述,征夫往来所见为实景,室家思念为虚怀。”概括了诗的整体架构。接着方氏又分述各章内容,他说:“其首二章,先叙出军车旂之盛,旟旐飞扬,仆夫况瘁,已将大将征伐声势赫赫写出,惊心动魄,照人耳目。次又言王之命仲,仲之承王,愈加郑重。义正词严,声灵百倍,早使敌人丧胆,玁狁慑服。故不烦一镞一矢,但城朔方而边患自除。非‘赫赫南仲’上承天子威灵,下同士卒劳苦,何能收功立效之速如是哉?”接着他又叙述三、四、五章的内容:“不但此也,方议回军,复事西戎。故以得胜王师加诸一隅亡虏,更不待衂刃而自解矣。此尤见南仲恩威并著,谋国远略有非他将所能及者。然当其将还未还时,征夫往来,景物变迁,故觉可感,即其室家,抚景怀人,宁无怨思?总以王事多难,简书迫我,故不敢顾私情而辞公义耳。迨至今而春回日煖,草长莺飞,采蘩妇子,祁祁郊外,而壮士凯还,则执讯获丑,献俘天子,归功大帅。”可谓言简意赅,将诗的内容概括无余。但诗中有些句子有仿效的痕迹,如第四章套用《采薇》中的诗句,第五章运用了《草虫》中的句子等,使有的章节显得不太自然流畅。
# 译文
我乘着我的战车,来到那城郊野外。打从天子的住地,派遣我到这里来。唤来御车众武士,快把武器来装载。国家危难的时刻,事情紧急莫等待。
我乘着我的战车,来到那城郊野外。车上飘着龟蛇旗,旄牛尾旗竖起来。还有壮观鹰隼旗,无不猎猎迎风摆。忧虑战事心不安,仆夫憔悴身累坏。
王命将军为南仲,往那北方去筑城。战车行驶声隆隆,军旗招展色鲜明。天子给我下命令,到那朔方去筑城。威名赫赫我南仲,将那玁狁扫出境。
往昔北征离家乡,黍稷发花扬清香。如今队伍转回来,大雪飘飘化泥浆。国家多灾又多难,日日忙碌不得安。难道不想回家转?只因军令难违反。
草丛蝈蝈喓喓叫,田间野地蚱蜢跳。未曾看见南仲面,忧心忡忡愁思绕。如今见到南仲面,心情平静不焦躁。威名赫赫我南仲,早把西戎来清剿。
春天到来白日长,草木茂盛色苍苍。黄莺喳喳枝头唱,采蘩姑娘采摘忙。审问俘虏记战绩,胜利归来回家乡。威名赫赫我南仲,平定玁狁国运昌。
# 注释
[^1]: 于:往,到。牧:郊外。
[^2]: 所:地方,处所。
[^3]: 谓:使。
[^4]: 仆夫:御夫,驾车的人。
[^5]: 维:发语词。棘:通“亟”,紧急。
[^6]: 旐(zhào):绘有龟蛇图形的旗帜。
[^7]: 旄(máo):用旄牛尾做装饰的旗帜。
[^8]: 旟(yú):绘有鹰隼图形的旗帜。斯:语助词。
[^9]: 旆旆(pèi):旗帜飞扬的样子。
[^10]: 悄悄:忧愁的样子。
[^11]: 况瘁(cuì):憔悴的样子。
[^12]: 南仲:周宣王时大将,亦作“南中”。
[^13]: 城:筑城。方:指朔方,北方。
[^14]: 彭彭:盛多的样子。
[^15]: 旂(qí):绘有双龙图形并有铃的旗帜。央央:鲜明的样子。
[^16]: 赫赫:声名显赫。
[^17]: 襄:除。
[^18]: 方:正。华:开花。
[^19]: 载涂:满路。涂,同“途”。
[^20]: 简书:写在竹简上的文书。此指周王的命令。
[^21]: 喓喓(yāo):虫鸣声。
[^22]: 趯趯(tì):跳跃的样子。阜螽(zhōng):蚱蜢。
[^23]: 降:下,指放心。
[^24]: 薄:语助词,含有勉励之意。
[^25]: 迟迟:日长的样子。
[^26]: 卉(huì):草。萋萋:茂盛的样子。
[^27]: 仓庚:黄莺。喈喈:鸟鸣声。
[^28]: 祁祁:众多的样子。
[^29]: 执:捕获。讯:审问。丑:指敌人。
[^30]: 夷:平定。
|
"""Tienda_Online URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include, re_path
from django.conf.urls import url
from django.conf.urls.static import serve, static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('jet/', include('jet.urls', 'jet')), # Django JET URLS
path('', include('inicio.urls')),
re_path('ckeditor/', include('ckeditor_uploader.urls')), #URL para el texto con formato
#url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
path('__debug__/', include(debug_toolbar.urls)),
# For django versions before 2.0:
# url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="../../icon-fa/all.min.css" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"
integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog=="
crossorigin="anonymous"
/>
</head>
<body>
<!-- 对代码进行编译为浏览器可识别的代码,这里使用了jsx -->
<!-- https://www.babeljs.cn -->
<script src="https://unpkg.com/@babel/standalone@7.17.11/babel.min.js"></script>
<!-- vue框架,著名的前端框架 -->
<!-- https://v3.cn.vuejs.org/ -->
<script src="https://unpkg.com/vue@3.2.33/dist/vue.global.js"></script>
<!-- css in ts的一个解决方案 -->
<!-- https://wormery.github.io/wtsc/ -->
<script src="https://unpkg.com/@wormery/wtsc@2.0.0-bate.38/dist/wtsc.iife.js"></script>
<!-- <script src="https://unpkg.com/@wormery/wtsc@2.0.0-bate.38/dist/wtsc.iife.prod.js"></script> -->
<div id="app"></div>
<script type="text/babel">
const { createApp, h, ref, computed } = Vue;
const { defWTSC, rgb, px, PE, vh, vw } = wtsc;
// babel会将标签编译为React.createElement,所以我们打了个补丁
const React = { createElement: h };
const w = defWTSC({});
const Heart = {
setup() {
return () => <i class="fa-solid fa-heart"></i>;
},
};
const SendHeartBtn = {
setup() {
return () => <i class="fa-solid fa-gift"></i>;
},
};
const App = {
setup() {
return () => (
<div>
<Heart></Heart>
<SendHeartBtn></SendHeartBtn>
</div>
);
},
};
createApp(App).mount("#app");
</script>
</body>
</html>
|
package com.kata.social.mediakata;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.kata.social.mediakata.initializer.Postgres;
import org.springframework.transaction.annotation.Transactional;
//@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@ActiveProfiles("test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = {
Postgres.Initializer.class
})
@Transactional
public abstract class AbstractSpringTest {
@Autowired
protected MockMvc mockMvc;
@Autowired
protected ObjectMapper objectMapper;
@BeforeAll
static void init() {
Postgres.postgreSQLContainer.start();
}
@AfterAll
static void deinit() {
Postgres.postgreSQLContainer.stop();
}
}
|
package com.pankaj.asteroids.game;
import com.pankaj.asteroids.home.GameOverController;
import javafx.animation.AnimationTimer;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Screen;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class AsteroidsApplication {
public static int WIDTH = 600;
public static int HEIGHT = 400;
public AtomicInteger points;
public void startGame(Stage primaryStage) throws Exception {
Map<KeyCode, Boolean> pressedKeys = new HashMap<>();
Pane pane = new Pane();
pane.setPrefSize(WIDTH, HEIGHT);
Text text = new Text(10, 20, "Points: 0");
pane.getChildren().add(text);
points = new AtomicInteger();
Ship ship = new Ship(WIDTH / 2, HEIGHT / 2);
List<Asteroid> asteroids = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Random rnd = new Random();
Asteroid asteroid = new Asteroid(rnd.nextInt(WIDTH / 3), rnd.nextInt(HEIGHT));
asteroids.add(asteroid);
}
List<Projectile> projectiles = new ArrayList<>();
pane.getChildren().add(ship.getCharacter());
asteroids.forEach(asteroid -> {
pane.getChildren().add(asteroid.getCharacter());
});
Scene scene = new Scene(pane);
scene.setOnKeyPressed(event -> {
pressedKeys.put(event.getCode(), Boolean.TRUE);
});
scene.setOnKeyReleased(event -> {
pressedKeys.put(event.getCode(), Boolean.FALSE);
});
new AnimationTimer() {
public void handle(long now) {
if (pressedKeys.getOrDefault(KeyCode.LEFT, false)) {
ship.turnLeft();
}
if (pressedKeys.getOrDefault(KeyCode.RIGHT, false)) {
ship.turnRight();
}
if (pressedKeys.getOrDefault(KeyCode.UP, false)) {
ship.accelerate();
}
if (pressedKeys.getOrDefault(KeyCode.SPACE, false) && projectiles.size() < 7) {
Projectile projectile = new Projectile((int) ship.getCharacter().getTranslateX(), (int) ship.getCharacter().getTranslateY());
projectile.getCharacter().setRotate(ship.getCharacter().getRotate());
projectile.accelerate();
projectile.setMovement(projectile.getMovement().normalize().multiply(3));
projectiles.add(projectile);
pane.getChildren().add(projectile.getCharacter());
}
ship.move();
asteroids.forEach(asteroid -> asteroid.move());
asteroids.forEach(
asteroid -> {
if (ship.collide(asteroid)) {
stop();
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/GameOver.fxml"));
GameOverController controller = loader.getController();
controller.setCurrent_score(points);
Parent root = (Parent)loader.load();
primaryStage.setScene(new Scene(root));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
);
projectiles.forEach(projectile -> {
projectile.move();
});
List<Projectile> projectilesToRemove = projectiles.stream()
.map(projectile -> {
asteroids.forEach(asteroid -> {
if (asteroid.collide(projectile)) {
text.setText("Points: " + points.addAndGet(1000));
}
});
return projectile;
}).filter(
projectile -> {
List<Asteroid> collisions = asteroids.stream().filter(
asteroid -> asteroid.collide(projectile)).collect(Collectors.toList());
if (collisions.isEmpty()
) {
return false;
}
collisions.stream().forEach(toBeremoved -> {
asteroids.remove(toBeremoved);
pane.getChildren().remove(toBeremoved.getCharacter());
}
);
return true;
}).collect(Collectors.toList());
projectilesToRemove.stream().forEach(projectile -> {
pane.getChildren().remove(projectile.getCharacter());
projectiles.remove(projectile);
});
if (Math.random() < 0.005) {
Asteroid asteroid = new Asteroid(WIDTH, HEIGHT);
if (!asteroid.collide(ship)) {
asteroids.add(asteroid);
pane.getChildren().add(asteroid.getCharacter());
}
}
}
}.start();
primaryStage.setTitle("Astroids!");
primaryStage.setScene(scene);
primaryStage.show();
}
}
|
// BALANCED HEIGHT TREE => MAX(LEFT HEIGHT, RIGHT HEIGHT) <= 1
#include<bits/stdc++.h>
using namespace std;
struct Node{ // BINARY TREE'S NODE STORE ONE VALUE AND HAVE TWO POINTERS POINTING TO IT'S TWO CHILDREN
int data;
struct Node*left; // FOR LEFT SUB-TREE
struct Node*right; // FOR RIGHT SUB-TREE
Node(int val){ // CONSTRUCTOR INITIALISING LEFT AND RIGHT POINTERS BY NULL
data=val;
left=NULL;
right=NULL;
}
};
// APPROACH 1 -
// USING CALC_HEIGHT FUNCTION TO GET HEIGHT
// TIME COMPLEXITY => O(N^2)
int calcHeight(Node* root){
if(root==NULL) return 0;
return max(calcHeight(root->left),calcHeight(root->right))+1;
}
bool checkBalanceTree(struct Node*root){
if(root==NULL) return true;
if(checkBalanceTree(root->left)==false){ // IF ANY ONE ROOT WILL RETURN FALSE THEN TILL END WE WILL GET OUR ANS TO BE FALSE
return false;
}
if(checkBalanceTree(root->right)==false){
return false;
}
int lh=calcHeight(root->left); // CALCULATE LH AND RH FOR NODE THEN CHECK CONDITION ON IT
int rh=calcHeight(root->right);
if(abs(lh-rh)<=1) return true; // IF CONDITION SATISFY THEN TRUE ELSE FALSE
else return false;
}
// APPROACH 2 -
// OPTIMISED USING POINTER CONCEPT
// TIME COMPLEXITY => O(N)
bool checkBalance_Opt(struct Node*root,int &height){ // USING AMPERSANT OPERATOR FOR HEIGHT
if(root==NULL) return true;
int lh=0,rh=0;
if(checkBalance_Opt(root->left,lh)==false){
return false;
}
if(checkBalance_Opt(root->right,rh)==false){
return false;
}
height=max(lh,rh)+1; // HERE WE ARE SIMUTANEOUSLY CALCULATING THE LH AND RH TO GET HEIGHT OF TREE
if(abs(lh-rh)<=1) return true; // THEN CHECKING THE CONDITION ON ONE TRAVERSAL
else return false;
}
int main(){
struct Node* root= new Node(1);
root->left=new Node(2);
root->right=new Node(3);
root->left->left=new Node(4);
root->left->left->left=new Node(5);
if(checkBalanceTree(root)) cout<<"Balanced\n";
else cout<<"Unbalanced\n";
int height=0;
if(checkBalance_Opt(root,height)) cout<<"Balanced\n";
else cout<<"Unbalanced\n";
return 0;
}
|
import React, { useState } from 'react';
import { useQuery, gql } from '@apollo/client';
import { TScore } from '../types';
import Login from './Login';
import Register from './Register';
import Game from './Game';
const HIGH_SCORES = gql`
query GetHighScores {
allScores(orderBy: "score_DESC") {
player {
name
}
score
}
}
`;
export default () => {
const { loading, error, data } = useQuery(HIGH_SCORES);
const [showPopUp, setShowPopUp] = useState(false);
const [login, setLogin] = useState(true);
const [loggedIn, setLoggedIn] = useState<any>(null);
const [newGame, setNewGame] = useState(false);
function togglePopUp() {
setShowPopUp(!showPopUp);
}
function toggleLogin() {
setLogin(true);
togglePopUp();
}
function toggleRegister() {
setLogin(false);
togglePopUp();
}
if (error) {
console.error(error);
}
return newGame ? (
<Game bestScore={data.allScores[0]?.score || 0} />
) : (
<div className="container">
<div className="text-center">
<h1>2048</h1>
<h2>LeaderBoard</h2>
</div>
{loading ? (
<p>Loading data...</p>
) : (
<pre>
<table className="w-100">
<tbody>
{data?.allScores?.map((score: TScore, index: number) => (
<tr key={index} className="table-row">
<td>{index}</td>
<td>{score.player.name}</td>
<td className="text-right">{score.score}</td>
</tr>
))}
</tbody>
</table>
<div className="button-container">
{!loggedIn && (
<>
<button className="button-white" onClick={toggleLogin}>
Log in
</button>
<button className="button-black" onClick={toggleRegister}>
Register
</button>
</>
)}
{loggedIn && (
<button className="button-white" onClick={() => setNewGame(true)}>
New Game
</button>
)}
</div>
<div className="text-center">
{loggedIn
? `Hello ${loggedIn.name}, nice to see you again!`
: 'Log in or register to start a new game'}
</div>
</pre>
)}
{showPopUp && (
<>
<div className="pop-up-container" onClick={togglePopUp}></div>
<div className="pop-up">
{login ? (
<Login toggle={togglePopUp} setLoggedInUser={setLoggedIn} />
) : (
<Register toggle={togglePopUp} />
)}
</div>
</>
)}
</div>
);
};
|
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import loginService from "../service/loginService";
/**
* Async thunk for user login. Attempts to log the user with credentials.
* If successful and rememberMe is true, the receved jwt token is encrypted and stored.
* @param {string} username - The user's username.
* @param {string} password - The user's password.
* @param {boolean} rememberMe - To remember the checked user
* @returns {Object} - The user token and rememberMe.
*/
export const loginUser = createAsyncThunk(
"auth/loginUser",
async ({ username, password, rememberMe }, { rejectWithValue }) => {
try {
const { token } = await loginService(username, password);
if (rememberMe) {
localStorage.setItem("Token", token);
}
return { token, rememberMe };
} catch (err) {
return rejectWithValue(err.message);
}
}
);
const initialState = {
token: null,
remember: false,
loading: false,
error: null,
};
const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
userLogout: (state, action) => {
state.token = null;
state.remember = false;
state.loading = false;
state.error = null;
},
},
extraReducers: (builder) => {
builder
.addCase(loginUser.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(loginUser.fulfilled, (state, action) => {
state.token = action.payload.token;
state.remember = action.payload.rememberMe;
state.loading = false;
state.error = null;
})
.addCase(loginUser.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message;
});
},
});
export const { userLogout } = authSlice.actions;
export default authSlice.reducer;
|
共享资源:
指的是多个线程同时对同一份资源进行访问(读写操作),被多个线程访问的资源就被称为共享资源,如何保证多个线程访问到的数据是一致的,则被称为数据同步或者资源同步。
synchronized:
synchronized关键字可以实现一个简单的策略来防止线程干扰和内存一致性错误,如果一个对象对多个线程是可见的,那么该对象的所有读或者写都将通过同步的方式来进行。具体表现如下:
1)synchronized关键字提供了一种锁机制,能够确保共享变量的互斥访问,从而防止数据不一致问题的出现。
2)synchronized关键字包括monitor enter 和 monitor exit两个JVM指令,它能够保证在任何时候任何线程执行到monitor enter成功之前都必须从主内存中获取数据,而不是缓存中
在monitor exit运行成功之后,共享变量被更新后的值必须刷入主内存。
2)synchronized指令严格遵守java happens-before规则,一个monitor exit之前必定要有一个monitor enter。
synchronized需要注意的问题:
1、与monitor关联的对象不能为空
2、synchronized作用域太大
3、不同的monitor企图锁相同的方法
4、多个锁的交叉导致死锁
|
import { browser } from "k6/experimental/browser";
import { sleep } from "k6";
import { check } from "k6";
export const options = {
scenarios: {
ui: {
executor: "shared-iterations", // para realizar iteraciones sin indicar el tiempo
options: {
browser: {
type: "chromium",
},
},
},
},
thresholds: {
checks: ["rate==1.0"],
},
};
export default async () => {
const page = browser.newPage();
try {
await page.goto("http://localhost:4200");
page.locator('input[name="nombre"]').type("Pablo Motos");
sleep(1);
page.locator('input[name="DNI"]').type("111111111");
sleep(1);
const button = page.locator('button[name="login"]');
sleep(1);
await Promise.all([
page.waitForNavigation({ waitUntil: "networkidle" }),
button.click(),
]);
sleep(1);
const paciente = page.$$("table tbody tr")[0];
await Promise.all([page.waitForNavigation(), paciente.click()]);
sleep(1);
const viewButton = page.locator('button[name="view"]');
await Promise.all([
page.waitForNavigation({ waitUntil: "networkidle" }),
viewButton.click(),
]);
sleep(1);
const predictButton = page.locator('button[name="predict"]');
predictButton.click();
const prediction = page.locator('span[name="predict"]').textContent();
check(prediction, {
"PredicciónRealizada": prediction === "Probabilidad de cáncer:",
});
} finally {
page.close();
}
};
|
import Layout from "../components/Layout";
import "../components/NoteModal/Note.css";
import Note from "../components/NoteModal/Note";
import NewNote from "../components/NoteModal/NewNoteModal";
import React, { useState } from "react";
import Checklist from "../components/checklists/Checklist";
export default function MyStuff() {
const [notes, setNote] = useState([""]);
const [modalShow, setModalShow] = useState(false);
const [noteIndex, setIndex] = useState(0);
//typing is important in typescript, contrary to regular React, pls make sure to include types (like :any to your code)
const addNote = function (value: string) {
return setNote((notes) => [...notes, value]);
};
const deleteNote = (index: any) => {
notes.splice(index, 1);
setNote((notes) => [...notes]);
};
//note is deleted using splice feature, splice returns orifinal notes index, prior to addition
const editNote = (value: string) => {
notes.splice(noteIndex, 1);
setNote((notes) => [...notes, value]);
};
//using feature, edits previousy created notes, and pushes new notes (from index where edits happened) to notes array
const editNoteIndex = (index: any) => {
setIndex(index);
};
//returns index of where edit occurs
return (
<Layout>
<div>
<Checklist />
<Note addNote={addNote} />
<div className="parent">
{/* map function, iterates over notes array to return as unordered list items */}
{notes.map((note, index) => {
return (
<div className="child" key={index}>
{" "}
<div>
<button
type="button"
className="close"
aria-label="Close"
onClick={() => deleteNote(index)}
>
<span aria-hidden="true">×</span>
</button>
</div>
<div
onClick={() => {
setModalShow(true);
editNoteIndex(index);
}}
>
{" "}
{note}{" "}
</div>
<NewNote
show={modalShow}
editNote={editNote}
notes={notes}
index={noteIndex}
onHide={() => setModalShow(false)}
/>
</div>
);
})}
</div>
</div>
</Layout>
);
}
|
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { TransactionsService } from 'src/app/transactions/transactions.service';
@Component({
selector: 'app-current-market-position',
templateUrl: './current-market-position.component.html',
styleUrls: ['./current-market-position.component.css']
})
export class CurrentMarketPositionComponent implements OnInit {
chart: any;
chartOptions = {
animationEnabled: true,
title: {
text: "Market Position",
},
data: [{
type: "pie",
startAngle: 90,
toolTipContent: "{y} - #percent %",
yValueFormatString: "R$ #,###.##",
showInLegend: true,
legendText: "{name}",
dataPoints: [
{ y: 0, name: "FIIs" },
{ y: 0, name: "Stocks" }
]
}]
};
constructor(private transactionsService: TransactionsService,
private activatedRoute: ActivatedRoute) {
}
ngOnInit(): void {
this.activatedRoute.queryParams.subscribe(params => {
this.getMonthlyTransactions(params['year']);
});
}
getChartInstance(chart: object) {
this.chart = chart;
}
getMonthlyTransactions(year: any) {
this.transactionsService.list(year)
.subscribe((rsp: any = {}) => {
let transactions = rsp.data;
let totalFIIs = 0;
let totalStocks = 0;
for (let index = 0; index < transactions.length; index++) {
const element = transactions[index];
if (element.asset.asset_type.id === "1") { //FIIs
totalFIIs += Number(element.total);
} else if (element.asset.asset_type.id === "2") {
totalStocks += Number(element.total);
}
}
this.chartOptions.data[0].dataPoints[0].y = totalFIIs;
this.chartOptions.data[0].dataPoints[1].y = totalStocks;
this.chart.render();
});
}
}
|
using OsmSharp;
using System.Collections.Generic;
namespace osm;
internal static class Inspector
{
private static readonly Dictionary<long, Point> _nodes = new();
public static Place Inspect(Node node)
{
if (node is not null)
{
/* Nodes are used for way and relation definitions. Not defined
* nodes mean the file is broken, no reason to continue further. */
var d = node.Id is not null && node.Longitude is not null && node.Latitude is not null;
if (!d) { Reporter.ReportUndefined(node); }
// extract and verify position
var lon = node.Longitude.Value;
var lat = node.Latitude.Value;
if (!CrsEpsg3857.IsWithin(lon, lat)) { Reporter.ReportOutbound(node); }
// keep node for later usage
_nodes.Add(node.Id.Value, new() { lon = lon, lat = lat });
if (node.Tags is null || node.Tags.Count == 0) { return null; }
// extract keywords and tags
var grain = new Place();
KeywordExtractor.Extract(node.Tags, grain.keywords);
if (grain.keywords.Count > 0)
{
AttributeExtractor.Extract(node.Tags, grain);
NameExtractor.Extract(node.Tags, grain);
LinkedExtractor.Extract(node, grain.linked);
grain.location = new() { lon = lon, lat = lat };
grain.position = new(lon, lat);
return grain;
}
}
return null;
}
private static bool TryGetSequence(Way way, out List<Point> sequence)
{
sequence = new();
foreach (var id in way.Nodes)
{
if (!_nodes.TryGetValue(id, out var node)) { return false; }
sequence.Add(new() { lon = node.lon, lat = node.lat });
}
return true;
}
public static Place Inspect(Way way)
{
if (way is not null)
{
// check if the way is properly defined
if (way.Id is null || way.Nodes is null) { Reporter.ReportUndefined(way); }
// small or open ways are skipped, closed polygons pass
if (way.Nodes.Length < 4 || way.Nodes[0] != way.Nodes[^1] || way.Tags is null || way.Tags.Count == 0) { return null; }
var grain = new Place();
if (!TryGetSequence(way, out var seq)) { return null; }
KeywordExtractor.Extract(way.Tags, grain.keywords);
if (grain.keywords.Count > 0)
{
AttributeExtractor.Extract(way.Tags, grain);
NameExtractor.Extract(way.Tags, grain);
LinkedExtractor.Extract(way, grain.linked);
/* Note that both IsCounterClockwise and Centroid
* use closedness of the shape verified above. */
/* GeoJSON assumes counterclockwise external rings,
* see https://www.rfc-editor.org/rfc/rfc7946#appendix-B.1! */
if (!Cartesian.IsCounterClockwise(seq)) { seq.Reverse(); }
var cen = Cartesian.Centroid(seq);
grain.attributes.polygon = seq;
grain.location = new() { lon = cen.lon, lat = cen.lat };
grain.position = new(cen.lon, cen.lat);
return grain;
}
}
return null;
}
}
|
package com.mauto.myapplication.prebooking
import android.app.ProgressDialog
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.mauto.myapplication.R
import com.mauto.myapplication.home.livedata.HomeLiveData
import com.mauto.myapplication.home.model.TransactionData
import com.mauto.myapplication.home.model.TransactionFinalResponse
import com.mauto.myapplication.utils.ApiConstant
import com.mindorks.placeholderview.ExpandablePlaceHolderView
import kotlinx.android.synthetic.main.booking_history.close_view
import kotlinx.android.synthetic.main.booking_history.no_customer_records
class PreBookingHistoryActivity : AppCompatActivity() {
lateinit var expandablePlaceHolderView: ExpandablePlaceHolderView;
lateinit var model: HomeLiveData
lateinit var pd: ProgressDialog
var distinctByArray: MutableList<TransactionData> = ArrayList<TransactionData>();
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.booking_history)
pd = ProgressDialog(this@PreBookingHistoryActivity)
pd.setMessage("Loading...")
model = ViewModelProvider(this)[HomeLiveData::class.java]
expandablePlaceHolderView =
findViewById<ExpandablePlaceHolderView>(R.id.expandablePlaceHolder)
loadData()
expandablePlaceHolderView.setOnClickListener {
Toast.makeText(applicationContext, "Clicked", Toast.LENGTH_LONG).show()
}
close_view.setOnClickListener {
finish()
}
}
private fun loadData() {
if (model == null)
model = ViewModelProvider(this)[HomeLiveData::class.java]
pd.show()
//Calling API from Observer
model.getHistory(ApiConstant.OBJ_HEADER_PRE_BOOKING)
?.observe(this, Observer { this.setUserStatus(it) })
}
private fun setUserStatus(list: TransactionFinalResponse?) {
if (list!!.status.equals("1")) {
if (pd != null)
pd.dismiss()
distinctByArray = list!!.response!!.data
// total.text = list!!.response!!.summary!!.total_amount
no_customer_records.visibility = View.GONE
var categoryMap = HashMap<String, List<TransactionData>>()
for (refund: TransactionData in distinctByArray) {
var bookingList1: MutableList<TransactionData>? =
categoryMap[refund.customerName] as MutableList<TransactionData>?
if (bookingList1 == null) {
bookingList1 = ArrayList<TransactionData>()
}
bookingList1.add(refund)
categoryMap[refund.customerName.toString()] = bookingList1
}
categoryMap.forEach { (key, value) ->
println("$key = $value")
expandablePlaceHolderView.addView(
HeaderView(
this,
key,
value[0].txnAmount!!,
value[0].gateway!!,
value[0].txnDate!!
)
)
for (movie in value) {
expandablePlaceHolderView.addView(
ChildView(
this,
movie.customerName!!,
movie.txnAmount!!,
movie.gateway!!,
movie.txnDate!!
)
)
}
}
} else {
if (pd != null)
pd.dismiss()
no_customer_records.visibility = View.VISIBLE
}
}
}
|
import CartsService from "../services/carts.services.js";
import { Exception } from "../helpers/utils.js";
import UsersService from "../services/users.services.js";
import ProductsController from "./products.controller.js";
import TicketController from "./ticket.controller.js";
import { getNewId } from "../helpers/utils.js";
export default class CartController {
static async get(filter = {}) {
const carts = await CartsService.findAll(filter)
return carts;
}
static async create(newCart = {}) {
const cart = await CartsService.create(newCart)
return cart;
}
static async getById(cid) {
return await CartsService.findById(cid)
}
static async deleteById(cid) {
await CartController.getById(cid)
req.logger.info("Eliminando el carrito");
await CartsService.deleteById(cid);
req.logger.info("Carrito eliminado correctamente");
}
static async addProductToCart(cartId, productId, quantity) {
try {
// console.log('entra al controlador');
// console.log("cartId", cartId)
const user = await UsersService.findAll({ cartId })
if (user[0].rol === 'admin') {
throw new Exception('El admin no puede agregar productos al carrito', 401)
}
const cart = await CartController.getById(cartId)
// console.log("quantity", quantity)
// const cart = await CartModel.findById(cartId);
// console.log("cart.products: ", cart.products[0].productId._id, productId)
// return;
if (!cart) {
throw new Exception('No se encontro el carrito', 404)
}
console.log("cart.products", cart.products)
const existingProductIndex = cart.products.findIndex(
(product) => String(product.productId._id) === String(productId)
);
// console.log(existingProductIndex);
if (existingProductIndex !== -1) {
cart.products[existingProductIndex].quantity += Number(quantity)
} else {
cart.products.push({ productId, quantity })
}
console.log("cart.products", cart.products)
const updatedCart = await CartsService.updateById(cartId, cart.products);
const cartUpdated = await CartsService.findById(cartId);
// console.log("cartUpdated", cartUpdated)
return cartUpdated;
// return updatedCart;
} catch (error) {
console.error("Error", error.message);
throw new Exception("Error al agregar producto al carrito", 500)
}
}
static async removeProductFromCart(cid, productId) {
try {
const cart = await CartController.getById(cid);
if (!cart) {
throw new Exception('No se encontro el carrito', 404)
}
// console.log(productId);
// console.log(cart);
// console.log("cart.products", cart.products)
const existingProductIndex = cart.products.findIndex(
(product) => String(product.productId._id) === String(productId)
);
if (existingProductIndex !== -1) {
// console.log("existingProduct", existingProductIndex);
cart.products.splice(existingProductIndex, 1)
// console.log("cart.products", cart.products)
// const updatedCart = await CartsService.updateById(cid, cart)
const updatedCart = await CartsService.updateById(cid, cart.products)
return updatedCart;
} else {
throw new Exception('No se encontro el producto en el carrito', 404)
}
} catch (error) {
throw new Exception("Error al eliminar el producto del carrito", 500)
}
}
static async removeAllProductsFromCart(cid) {
try {
const cart = await CartController.getById(cid);
if (!cart) {
throw new Exception('No existe el carrito', 404);
}
cart.products = [];
const updatedCart = await CartsService.updateById(cid, cart.products)
return updatedCart;
} catch (error) {
throw new Exception('Error al eliminar los productos del carrito', 500)
}
}
static async updateProductQuantityFromCart(cid, pid, quantity) {
try {
const cart = await CartsService.findById(cid);
if (!cart) {
throw new Exception('No existe el carrito', 404);
}
const existingProductIndex = cart.products.findIndex(
(product) => String(product.productId) === String(pid)
);
// console.log(existingProductIndex);
if (existingProductIndex !== -1) {
// console.log("existingProductIndex", existingProductIndex);
cart.products[existingProductIndex].quantity = Number(quantity)
}
const updatedCart = await CartsService.updateById(cid, cart.products)
return updatedCart;
} catch (error) {
throw new Exception('Error al actualizar el producto del carrito', 500)
}
}
static async updateProductsFromCart(cid, products) {
try {
const cart = await CartsService.findById(cid);
// console.log("cid", cid)
// console.log("products", products)
// console.log(typeof products)
if (!cart) {
throw new Exception('No existe el carrito', 404);
}
// primero que nada vacio el carrito...
await CartController.removeAllProductsFromCart(cid);
// console.log('carrito vacio', await CartController.getById(cid))
// console.log('products.products', products.products)
products.products.forEach(async (prod) => {
// console.log("prod", cid, prod)
await CartController.addProductToCart(cid, prod.productId, prod.quantity)
})
const updatedCart = await cart.save();
return updatedCart;
} catch (error) {
throw new Exception('Error al actualizar los productos del carrito', 500)
}
}
static async createPurchase(cid) {
try {
const user = await UsersService.findAll({ cartId: cid });
let amount = 0;
// console.log("user", user)
if (user.length > 0) {
let cart = await CartsService.findById({ _id: user[0].cartId._id });
// console.log("cart en createPurchase", cart)
if (cart.products.length > 0) {
let productsWithoutStock = [];
let productsWithStock = [];
let updatedProducts;
for (const [index, prod] of cart.products.entries()) {
if (prod.productId.stock < prod.quantity) {
// console.log('Stock insuficiente');
productsWithoutStock.push({ _id: prod.productId._id, quantity: prod.quantity });
} else {
// console.log('Hay stock');
productsWithStock.push({ _id: prod.productId._id, quantity: prod.quantity });
updatedProducts = await ProductsController.updateById(prod.productId._id, {
stock: prod.productId.stock - prod.quantity,
});
amount += prod.productId.price * prod.quantity;
// Remove product from cart (without worrying about concurrency)
cart = await CartController.removeProductFromCart(cid, prod.productId._id);
}
}
// Generate ticket after processing all products
const ticket = await TicketController.create({
code: getNewId(),
purchase_datetime: Date.now(),
amount,
purchaser: user[0].email,
});
return { user, productsWithoutStock, cart, ticket };
} else {
throw new Error('El carrito esta vacio, no se puede realizar la compra')
}
}
} catch (error) {
console.log("Error", error.message)
}
}
// static async createPurchase(cid) {
// const user = await UsersService.findAll({ cartId: cid })
// let amount = 0;
// if (user.length > 0) {
// let cart = await CartsService.findById({ _id: user[0].cartId })
// let productsWithoutStock = [];
// let productsWithStock = [];
// let updatedProducts;
// for (const [index, prod] of cart.products.entries()) {
// if (prod.productId.stock < prod.quantity) {
// console.log('Stock insuficiente');
// productsWithoutStock.push({ _id: prod.productId._id, quantity: prod.quantity });
// } else {
// console.log('Hay stock');
// productsWithStock.push({ _id: prod.productId._id, quantity: prod.quantity });
// updatedProducts = await ProductsController.updateById(prod.productId._id, {
// stock: prod.productId.stock - prod.quantity,
// });
// amount += prod.productId.price * prod.quantity;
// // console.log('amount', amount);
// // console.log('removing...', cid, prod.productId, index);
// // console.log('prev', index, cart);
// cart = await CartController.removeProductFromCart(cid, prod.productId._id);
// // console.log('post', index, cart);
// }
// }
// // await Promise.all(cart.products.map(async (prod, index) => {
// // if (prod.productId.stock < prod.quantity) {
// // console.log('Stock insuficiente');
// // productsWithoutStock.push({ _id: prod.productId._id, quantity: prod.quantity })
// // } else {
// // // console.log('Hay stock')
// // productsWithStock.push({ _id: prod.productId._id, quantity: prod.quantity })
// // updatedProducts = await ProductsController.updateById(prod.productId._id,
// // {
// // stock: prod.productId.stock - prod.quantity
// // }
// // )
// // // console.log(`price ${prod.productId.price} * ${prod.quantity}`);
// // amount += prod.productId.price * prod.quantity
// // // console.log('amount', amount)
// // // console.log("removing...", cid, prod.productId, index)
// // console.log("prev", index, cart)
// // cart = await CartController.removeProductFromCart(cid, prod.productId._id)
// // console.log("post", index, cart)
// // }
// // }))
// // console.log('amount', amount)
// const ticket = await TicketController.create({
// code: getNewId(),
// purchase_datetime: Date.now(),
// amount,
// purchaser: user[0].email
// })
// return { user, productsWithoutStock, cart, ticket }
// }
// }
}
|
"""Adapted from <https://github.com/annikabrundyn> and <https://github.com/akshaykvnit>"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from monai.networks.nets.unet import UNet
from configparser import ConfigParser
import os
import sys
import os.path as osp
ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '../../'))
sys.path.append(ROOT_DIR)
from utilities.parser_conversions import str_to_tuple
class UNet(nn.Module):
def __init__(self, n_classes: int, cfg: ConfigParser):
params = cfg['PARAMETERS']
n_layers = params.getint('num_layers')
# Add background class for multiclass approach
n_classes = n_classes + 1 if n_classes > 1 else n_classes
in_channels = n_classes + 1
feats_start = params.getint('features_start')
trilinear = params.getboolean('trilinear')
padding = params.getint('padding')
kernel_size = str_to_tuple(params['kernel_size'], int)
act = params['activation']
slope = params.getfloat('activation_slope')
if n_layers < 1:
raise ValueError(
f"Num_layers = {n_layers}, expected: num_layers > 0")
super().__init__()
self.num_layers = n_layers
layers = [DoubleConv3d(in_channels, feats_start, kernel_size, padding, act, slope)]
feats = feats_start
for _ in range(n_layers - 1):
layers.append(Down3d(feats, feats * 2, kernel_size, padding, act, slope))
feats *= 2
for _ in range(n_layers - 1):
layers.append(Up3d(feats, feats // 2, trilinear, kernel_size, padding, act, slope))
feats //= 2
out_conv = nn.Conv3d(feats, n_classes, kernel_size=1)
layers.append(out_conv)
self.layers = nn.ModuleList(layers)
def forward(self, x):
# TODO: it is clone necessary?
identity = x[:, 1:]
xi = [self.layers[0](x)]
# Down path
for layer in self.layers[1: self.num_layers]:
xi.append(layer(xi[-1]))
# Up path
for i, layer in enumerate(self.layers[self.num_layers: -1]):
xi[-1] = layer(xi[-1], xi[-2 - i])
output = self.layers[-1](xi[-1])
return output + identity, output
class DoubleConv3d(nn.Module):
def __init__(self, in_ch: int, out_ch: int, kernel_size=(3, 3, 3), padding=1, act='relu', slope=0.2):
super().__init__()
self.net = nn.Sequential(nn.Conv3d(in_ch, out_ch, kernel_size=kernel_size, padding=padding),
nn.InstanceNorm3d(out_ch),
self.activation(act, slope),
nn.Conv3d(out_ch, out_ch, kernel_size=kernel_size, padding=padding),
nn.InstanceNorm3d(out_ch),
self.activation(act, slope))
def activation(self, act, slope):
act_fn = nn.Module
if act == 'relu':
act_fn = nn.ReLU()
elif act == 'leaky_relu':
act_fn = nn.LeakyReLU(negative_slope=slope)
elif act == 'prelu':
act_fn = nn.PReLU(num_parameters=1)
return act_fn
def forward(self, x):
return self.net(x)
class Down3d(nn.Module):
def __init__(self, in_ch: int, out_ch: int, kernel_size=(3, 3, 3), padding=1, act='relu', slope=0.2):
super().__init__()
self.net = nn.Sequential(
nn.MaxPool3d(kernel_size=2, stride=2),
DoubleConv3d(in_ch, out_ch, kernel_size, padding, act, slope)
)
def forward(self, x):
return self.net(x)
class Up3d(nn.Module):
"""Upsampling (by either trilinear interpolation or transpose convolutions) followed by concatenation of feature
map from contracting path, followed by DoubleConv3D."""
def __init__(self, in_ch: int, out_ch: int, trilinear: bool = False, kernel_size=(3, 3), padding=1, act='relu', slope=0.2):
super().__init__()
self.upsample = None
if trilinear:
conv = nn.Conv3d(in_ch, in_ch // 2, kernel_size=1)
ups = nn.Upsample(scale_factor=2, mode="trilinear", align_corners=True)
self.upsample = nn.Sequential(ups, conv)
else:
conv_trans = nn.ConvTranspose3d(in_ch, in_ch // 2, kernel_size=2, stride=2)
self.upsample = conv_trans
self.conv = DoubleConv3d(in_ch, out_ch, kernel_size=kernel_size, padding=padding, act=act, slope=slope)
def forward(self, x1, x2):
x1 = self.upsample(x1)
# Pad x1 to the size of x2
diff_d = x2.shape[2] - x1.shape[2]
diff_h = x2.shape[3] - x1.shape[3]
diff_w = x2.shape[4] - x1.shape[4]
x1 = F.pad(x1, [diff_w // 2, diff_w - diff_w // 2,
diff_h // 2, diff_h - diff_h // 2,
diff_d // 2, diff_d - diff_d // 2])
# Concatenate along the channels axis
x = torch.cat([x2, x1], dim=1)
return self.conv(x)
|
from tkinter import *
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
import seaborn as sns
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
from ParetoVA import pseudo_pareto
class ParetoClass:
def __init__(self, master):
self.master = master
self.label1 = Label(master, text="b", height=4)
self.input1 = Entry(master)
self.label3 = Label(master, text="V.A.", height=1)
self.input3 = Entry(master)
self.canvas_FDP = None
self.canvas_FPA = None
self.figure = None
self.name="Pareto"
#mu, sigma = 0, 0.2 # media y desvio estandar
#Input1 = mu
#Input2 = sigma
#Input3 = VARIABLE ALEATORIA
def renderWidgets(self):
self.label1.grid(column=0,row=1)
self.input1.grid(column=1,row=1)
self.label3.grid(column=0,row=3)
self.input3.grid(column=1,row=3)
def removeWidgets(self):
self.label1.grid_remove()
self.input1.grid_remove()
self.label3.grid_remove()
self.input3.grid_remove()
def renderVA(self):
#Call VA from Normal Distribution and save as string
va = str(pseudo_pareto())
self.input3.delete(0, 'end')
self.input3.insert(END,va)
def removeVA(self):
self.label3.grid_remove()
self.input3.grid_remove()
def renderGraph(self):
self.renderFDP()
self.renderFPA()
def renderFDP(self):
#np.random.seed(seed) # replicar random
b = float(self.input1.get())
# Graficando Pareto
pareto = stats.pareto(b=b)
x = np.linspace(pareto.ppf(0.01),
pareto.ppf(0.99), 100)
fp = pareto.pdf(x) # Función de Probabilidad
self.figure = Figure(figsize=(5, 4), dpi=100)
self.figure.add_subplot(111).plot(x, fp, '--')
self.canvas_FDP = FigureCanvasTkAgg(self.figure, master=self.master) # A tk.DrawingArea.
self.canvas_FDP.draw()
self.canvas_FDP.get_tk_widget().grid(column=1,row=5)
def renderFPA(self):
#np.random.seed(seed) # replicar random
# Graficando Pareto
b = float(self.input1.get())
pareto = stats.pareto(b=b)
x = np.linspace(pareto.ppf(0.01),
pareto.ppf(0.99), 100)
fp = pareto.cdf(x) # Función de Probabilidad
self.figure = Figure(figsize=(5, 4), dpi=100)
self.figure.add_subplot(111).plot(x, fp, '--')
self.canvas_FPA = FigureCanvasTkAgg(self.figure, master=self.master) # A tk.DrawingArea.
self.canvas_FPA.draw()
self.canvas_FPA.get_tk_widget().grid(column=3,row=5)
def clearGraph(self):
self.canvas_FDP.get_tk_widget().grid_remove()
self.canvas_FPA.get_tk_widget().grid_remove()
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta
name="description"
content="Mae Tran is a front-end developer based in Canada, watch and check out her projects and contact for inquiries"
/>
<title>Front-end developer - Mae Tran</title>
<link rel="stylesheet" href="style.css" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"
></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">
<img
src="images/phflag2.png"
alt="phlogo"
width="50px"
height="40px"
/>
Mae Tran
</a>
<button
class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarNavAltMarkup"
aria-controls="navbarNavAltMarkup"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link active" aria-current="page" href="index.html"
>Home</a
>
<a class="nav-link" href="about.html">About</a>
<a class="nav-link" href="about.html#contact">Contact</a>
</div>
</div>
</div>
</nav>
<h2 class="text-center">👋🏿 Mabuhay! I am</h2>
<h1 class="text-center">Mae Tran</h1>
<h3 class="text-center">Filipino Front-end developer, based in Canada</h3>
<div class="links">
<a
href="/about.html#contact"
class="contact-link"
title="Contact Mae Tran"
>Contact Me</a
>
<a href="/about.html" class="about-link" title="Abount Mae Tran"
>About Me</a
>
</div>
<div class="container">
<div class="row">
<div class="col-sm-6">
<img
src="images/yoga.png"
alt="yoga project"
class="img-fluid rounded d-none d-sm-block"
/>
</div>
<div class="col-sm-6">
<h2 class="mb-3">Yoga App</h2>
<p>
"yoke' or 'union' is a group of physical, mental, and spiritual
practices or disciplines which originated in ancient India and aim
to control (yoke) and still the mind, recognizing a detached
witness-consciousness untouched by the mind (Citta) and mundane
suffering (Duḥkha). There is a wide variety of schools of yoga,
practices, and goals in Hinduism, Buddhism, and Jainism, and
traditional and modern yoga is practiced worldwide."
</p>
<div class="mt-5">
<a
href="https://www.youtube.com/watch?v=oX6I6vs1EFs"
class="app-link launch-link"
title="Yoga App project"
>Launch App</a
>
</div>
</div>
</div>
<div class="row mt-5">
<div class="col-sm-6">
<h2 class="mb-3">Weather App</h2>
<p>
Weather is the state of the atmosphere, describing for example the
degree to which it is hot or cold, wet or dry, calm or stormy, clear
or cloudy. On Earth, most weather phenomena occur in the lowest
layer of the planet's atmosphere, the troposphere, just below the
stratosphere. Weather refers to day-to-day temperature,
precipitation, and other atmospheric conditions, whereas climate is
the term for the averaging of atmospheric conditions over longer
periods of time.
</p>
<div class="mt-5">
<a
href="https://frosty-goodall-cc407d.netlify.app/"
class="app-link launch-link"
title="Weather App project"
>Launch App</a
>
</div>
</div>
<div class="col-sm-6">
<img
src="images/weather.png"
alt="weather project"
class="img-fluid rounded mt-3 pt-3 d-none d-sm-block"
/>
</div>
</div>
<div class="row mt-5">
<div class="col-sm-6">
<img
src="images/yogurt.png"
alt="yogurt project"
class="img-fluid rounded d-none d-sm-block"
/>
</div>
<div class="col-sm-6">
<h2 class="mb-3">Yogurt App</h2>
<p>
Yogurt, also spelled yoghurt, yogourt or yoghourt, is a food
produced by bacterial fermentation of milk. The bacteria used to
make yogurt are known as yogurt cultures. Fermentation of sugars in
the milk by these bacteria produces lactic acid, which acts on milk
protein to give yogurt its texture and characteristic tart flavor.
Cow's milk is the milk most commonly used to make yogurt. Milk from
water buffalo, goats, ewes, mares, camels, and yaks are also used to
produce yogurt. The milk used may be homogenized or not. It may be
pasteurized or raw. Each type of milk produces substantially
different results.
</p>
<div class="mt-5">
<a
href="https://www.youtube.com/watch?v=z6GPM1BqIkI"
class="app-link launch-link"
title="Yogurt App Project"
>Launch App</a
>
</div>
</div>
</div>
</div>
</body>
</html>
|
/*
1 meter = 3.281 feet
1 liter = 0.264 gallon
1 kilogram = 2.204 pound
*/
const convertBtn = document.getElementById("convertButton")
const inputField = document.getElementById("inputField")
const lengthParagraph = document.getElementById("lengthParagraph")
const volumeParagraph = document.getElementById("volumeParagraph")
const massParagraph = document.getElementById("massParagraph")
// let conversionNum = Number(inputField.value)
// console.log(conversionNum)
convertBtn.addEventListener("click", function() {
const conversionNum = Number(inputField.value)
convert(conversionNum)
console.log(conversionNum)
})
function convert(num) {
showLengthConversion(num)
showVolumeConversion(num)
showMassConversion(num)
conversionNum = 0
inputField.value = ""
}
function showLengthConversion(num) {
const feetConversion = (num * 3.281).toFixed(3)
const meterConversion = (num / 3.281).toFixed(3)
lengthParagraph.textContent = `${num} meters = ${feetConversion} feet | ${num} feet = ${meterConversion} meters`
}
function showVolumeConversion(num) {
const litreConversion = (num / 0.264).toFixed(3)
const gallonConversion = (num * 0.264).toFixed(3)
volumeParagraph.textContent = `${num} litres = ${gallonConversion} gallons | ${num} gallons = ${litreConversion} litres`
}
function showMassConversion(num) {
const poundConversion = (num * 2.204).toFixed(3)
const KiloConversion = (num / 2.204).toFixed(3)
massParagraph.textContent = `${num} kilos = ${poundConversion} pounds | ${num} pounds = ${KiloConversion} kilos`
}
|
import { Box, Button, Divider, Flex, Icon, Image, Link, Spinner, Stack, Text } from '@chakra-ui/react';
import { updateDoc, doc} from 'firebase/firestore';
import { ref, uploadString, getDownloadURL } from 'firebase/storage';
import React, { useRef, useState } from 'react';
import { useAuthState } from 'react-firebase-hooks/auth';
import { useDocument } from 'react-firebase-hooks/firestore';
import { FaHome } from 'react-icons/fa';
import { HiOutlineDotsHorizontal } from 'react-icons/hi';
import { useRecoilValue } from 'recoil';
import { clubState } from '../../atoms/clubsAtom';
import { auth, firestore, storage } from '../../firebase/clientApp';
import useSelectFile from '../../hooks/useSelectFile';
const AboutUser:React.FC= () => {
const [user]=useAuthState(auth);
const mySnippets=useRecoilValue(clubState).mySnippets;
const selectedFileRef=useRef<HTMLInputElement>(null);
const {selectedFile,onSelectFile}=useSelectFile();
const [uploadingImage,setUploadingImage]=useState(false);
const [value,loading,error]=useDocument(doc(firestore,`users/${user?.uid}`));
const onUpdateImage=async()=>{
if(!selectedFile) return;
setUploadingImage(true);
try {
const imageRef=ref(storage,`users/${user?.uid}/image`);
await uploadString(imageRef,selectedFile,"data_url");
const downloadURL= await getDownloadURL(imageRef);
await updateDoc(doc(firestore,`users/${user?.uid}`),{
photoURL:downloadURL,
})
} catch (error) {
console.log("onUpdateImage error",error);
}
setUploadingImage(false);
};
return (
<>
<Box position="sticky" top="14px">
<Flex justify="space-between" align="center" bg="blue.500" color="white" p={3} borderRadius={5}>
<Text fontSize="9pt" fontWeight={700}>About User</Text>
<Icon as={HiOutlineDotsHorizontal}/>
</Flex>
<Flex direction="column" bg="white" p={3} borderRadius={5}>
<Stack>
<Flex width="100%" p={2} fontSize="10pt">
<Flex direction="column" flexGrow={1}>
<Text>{mySnippets.filter((snippet)=>snippet.isModerator).length}</Text>
<Text>Created Clubs</Text>
</Flex>
<Flex direction="column" flexGrow={1}>
<Text>{mySnippets.length}</Text>
<Text>Joined Clubs</Text>
</Flex>
</Flex>
<Divider/>
<Flex align="center" width="100%" fontSize="15pt" fontWeight={600}>
<Text>
{user?.displayName || user?.email?.split("@")[0]}
</Text>
</Flex>
<Link href="/">
<Button mt={3} height="30px" width="100%" _hover={{bg:"red"}}>Create Post</Button>
</Link>
{user?.uid && (
<>
<Divider/>
<Stack spacing={1} fontSize="10pt">
<Text fontWeight={600}>Admin</Text>
<Flex align="center" justify="space-between">
<Text color="blue.500" cursor="pointer" _hover={{textDecoration:"underline"}} onClick={()=>selectedFileRef.current?.click()}>Change Image</Text>
{user?.photoURL || selectedFile || value?.data()!!.photoURL ? (
<Image src={selectedFile || value?.data()!!.photoURL || user?.photoURL as string} borderRadius="full" alt="profile Image" boxSize="60px"/>
):(
<Icon
as={FaHome}
fontSize={64}
bg="blue.500"
color="gray.100"
border="4px solid white"
p={3}
borderRadius="50%"
/>
)}
</Flex>
{selectedFile && (
(uploadingImage ? (
<Spinner/>
):(
<Text cursor="pointer" onClick={onUpdateImage}>Save Changes</Text>
))
)}
<input type="file" hidden ref={selectedFileRef} onChange={onSelectFile}/>
</Stack>
</>
)}
</Stack>
</Flex>
</Box>
</>
)
}
export default AboutUser;
|
<?php
namespace App\Tests\Traits;
use App\Repository\UserRepository;
trait RegistrationTrait
{
private function registrationSuccess(): void
{
$client = self::createClient();
$container = self::getContainer();
$repository = $container->get(UserRepository::class);
$data = [
'email' => 'test123@example.com',
'plainPassword' => '123123',
];
$response = $client->request('POST', $_SERVER['HTTP_HOST'] . '/api/registration', [
'headers' => ['Content-Type' => 'application/ld+json'],
'json' => $data,
]);
$this->assertResponseStatusCodeSame(201);
$json = $response->toArray();
$inDb = $repository->findOneByPassword(md5("123123"));
$this->assertNotEmpty($inDb);
$this->assertTrue($json['email'] == $data['email']);
$this->assertTrue($inDb->getEmail() == $data['email']);
}
}
|
---
permalink: switch-netapp-cn1610/install-fastpath-rcf-831.html
sidebar: sidebar
keywords: fastpath, software, install, netapp cluster switches, rcfs, ontap
summary: 对于运行 ONTAP 8.3.1 或更高版本的 NetApp CN1601 管理交换机和 CN1610 集群交换机,安装步骤相同。但是,这两种型号需要不同的软件和 RCF 。
---
= 安装适用于ONTAP 8.3.1及更高版本的FastPath软件和RCF
:allow-uri-read:
:icons: font
:imagesdir: ../media/
[role="lead"]
按照此操作步骤 安装适用于ONTAP 8.3.1及更高版本的FastPath软件和RCF。
对于运行 ONTAP 8.3.1 或更高版本的 NetApp CN1601 管理交换机和 CN1610 集群交换机,安装步骤相同。但是,这两种型号需要不同的软件和 RCF 。
== 查看要求
.您需要的内容
* 交换机配置的当前备份。
* 一个完全正常运行的集群(日志中没有错误、并且集群网络接口卡(NIC)没有缺陷或类似问题)。
* 集群交换机上功能完备的端口连接。
* 已设置所有集群端口。
* 已设置所有集群逻辑接口(LIF)(不得迁移)。
* 成功的通信路径:ONTAP (权限:高级) `cluster ping-cluster -node node1` 命令必须指明这一点 `larger than PMTU communication` 在所有路径上均成功。
* 受支持的FastPath、RCF和ONTAP 版本。
+
请务必参考上的交换机兼容性表 http://mysupport.netapp.com/NOW/download/software/cm_switches_ntap/["NetApp CN1601 和 CN1610 交换机"^] 页面上显示了受支持的 FastPath , RCF 和 ONTAP 版本。
== 安装FastPath软件
以下操作步骤 使用集群模式Data ONTAP 8.2语法。因此、集群Vserver、LIF名称和命令行界面输出与Data ONTAP 8.3中的不同。
RCF 和 FastPath 版本中的命令语法之间可能存在命令依赖关系。
NOTE: 在 RCF 1.2 版中,出于安全考虑,已明确禁用对 Telnet 的支持。要在安装RCF 1.2时避免连接问题、请验证是否已启用安全外壳(SSH)。。 https://library.netapp.com/ecm/ecm_get_file/ECMP1117874["《NetApp CN1610交换机管理员指南》"^] 了解有关 SSH 的详细信息。
.关于示例
此操作步骤中的示例使用以下交换机和节点命名:
* 两个 NetApp 交换机名称分别为 CS1 和 CS2 。
* 集群逻辑接口( LIF )的名称分别是 node1 和 node1_clus1 和 node1_clus2 , node2 和 node2_clus2 。(一个集群中最多可以有24个节点。)
* Storage Virtual Machine ( SVM )的名称是 Cluster 。
* `cluster1 ::: * >` 提示符指示集群的名称。
* 每个节点上的集群端口均名为 e0a 和 e0b 。
+
https://hwu.netapp.com/["Hardware Universe"^] 提供有关您的平台支持的实际集群端口的详细信息。
* 支持的交换机间链路(ISL)为端口0/13到0/16。
* 支持的节点连接为端口0/1到0/12。
=== 第1步:迁移集群
. 显示有关集群上网络端口的信息:
+
`network port show -_ipspace cluster_`
+
.显示示例
[%collapsible]
====
以下示例显示了命令的输出类型:
[listing]
----
cluster1::> network port show -ipspace cluster
Speed (Mbps)
Node Port IPspace Broadcast Domain Link MTU Admin/Oper
------ --------- ------------ ---------------- ----- ------- ------------
node1
e0a Cluster Cluster up 9000 auto/10000
e0b Cluster Cluster up 9000 auto/10000
node2
e0a Cluster Cluster up 9000 auto/10000
e0b Cluster Cluster up 9000 auto/10000
4 entries were displayed.
----
====
. 显示有关集群上 LIF 的信息:
+
`network interface show -_role cluster_`
+
.显示示例
[%collapsible]
====
以下示例显示了集群上的逻辑接口。在此示例中, ` -role` 参数显示有关与集群端口关联的 LIF 的信息:
[listing]
----
cluster1::> network interface show -role cluster
(network interface show)
Logical Status Network Current Current Is
Vserver Interface Admin/Oper Address/Mask Node Port Home
----------- ---------- ---------- ------------------ ------------- ------- ----
Cluster
node1_clus1 up/up 10.254.66.82/16 node1 e0a true
node1_clus2 up/up 10.254.206.128/16 node1 e0b true
node2_clus1 up/up 10.254.48.152/16 node2 e0a true
node2_clus2 up/up 10.254.42.74/16 node2 e0b true
4 entries were displayed.
----
====
. 在每个相应节点上,使用节点管理 LIF 将 node1_clus2 迁移到 node1 上的 e0a ,将 node2_clus2 迁移到 node2 上的 e0a :
+
`网络接口迁移`
+
您必须在拥有相应集群 LIF 的控制器控制台上输入命令。
+
.显示示例
[%collapsible]
====
[listing]
----
cluster1::> network interface migrate -vserver Cluster -lif node1_clus2 -destination-node node1 -destination-port e0a
cluster1::> network interface migrate -vserver Cluster -lif node2_clus2 -destination-node node2 -destination-port e0a
----
====
+
NOTE: 对于此命令,集群的名称区分大小写,应在每个节点上运行此命令。无法在常规集群 LIF 中运行此命令。
. 在节点上使用 `network interface show` 命令验证是否已进行迁移。
+
.显示示例
[%collapsible]
====
以下示例显示 clus2 已迁移到节点 node1 和 node2 上的端口 e0a :
[listing]
----
cluster1::> **network interface show -role cluster**
Logical Status Network Current Current Is
Vserver Interface Admin/Oper Address/Mask Node Port Home
----------- ---------- ---------- ------------------ ------------- ------- ----
Cluster
node1_clus1 up/up 10.254.66.82/16 node1 e0a true
node1_clus2 up/up 10.254.206.128/16 node1 e0a false
node2_clus1 up/up 10.254.48.152/16 node2 e0a true
node2_clus2 up/up 10.254.42.74/16 node2 e0a false
4 entries were displayed.
----
====
. 将权限级别更改为高级,在系统提示您继续时输入 y :
+
`set -privilege advanced`
+
此时将显示高级提示符( * > )。
. 关闭两个节点上的集群端口 e0b :
+
`network port modify -node _node_name_ -port _port_name_ -up-admin false`
+
您必须在拥有相应集群 LIF 的控制器控制台上输入命令。
+
.显示示例
[%collapsible]
====
以下示例显示了关闭所有节点上的端口 e0b 的命令:
[listing]
----
cluster1::*> network port modify -node node1 -port e0b -up-admin false
cluster1::*> network port modify -node node2 -port e0b -up-admin false
----
====
. 验证两个节点上的端口 e0b 是否均已关闭:
+
`network port show`
+
.显示示例
[%collapsible]
====
[listing]
----
cluster1::*> network port show -role cluster
Speed (Mbps)
Node Port IPspace Broadcast Domain Link MTU Admin/Oper
------ --------- ------------ ---------------- ----- ------- ------------
node1
e0a Cluster Cluster up 9000 auto/10000
e0b Cluster Cluster down 9000 auto/10000
node2
e0a Cluster Cluster up 9000 auto/10000
e0b Cluster Cluster down 9000 auto/10000
4 entries were displayed.
----
====
. 关闭 CS1 上的交换机间链路( ISL )端口。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs1) #configure
(cs1) (Config)#interface 0/13-0/16
(cs1) (Interface 0/13-0/16)#shutdown
(cs1) (Interface 0/13-0/16)#exit
(cs1) (Config)#exit
----
====
. 备份 CS2 上的当前活动映像。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs2) # show bootvar
Image Descriptions
active :
backup :
Images currently available on Flash
--------------------------------------------------------------------
unit active backup current-active next-active
--------------------------------------------------------------------
1 1.1.0.5 1.1.0.3 1.1.0.5 1.1.0.5
(cs2) # copy active backup
Copying active to backup
Copy operation successful
----
====
=== 第2步:安装FastPath软件和RCF
. 验证正在运行的 FastPath 软件版本。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs2) # show version
Switch: 1
System Description............................. NetApp CN1610, 1.1.0.5, Linux
2.6.21.7
Machine Type................................... NetApp CN1610
Machine Model.................................. CN1610
Serial Number.................................. 20211200106
Burned In MAC Address.......................... 00:A0:98:21:83:69
Software Version............................... 1.1.0.5
Operating System............................... Linux 2.6.21.7
Network Processing Device...................... BCM56820_B0
Part Number.................................... 111-00893
--More-- or (q)uit
Additional Packages............................ FASTPATH QOS
FASTPATH IPv6 Management
----
====
. 将映像文件下载到交换机。
+
将映像文件复制到活动映像意味着,重新启动时,该映像将建立正在运行的 FastPath 版本。上一个映像仍可用作备份。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs2) #copy sftp://root@10.22.201.50//tftpboot/NetApp_CN1610_1.2.0.7.stk active
Remote Password:********
Mode........................................... SFTP
Set Server IP.................................. 10.22.201.50
Path........................................... /tftpboot/
Filename....................................... NetApp_CN1610_1.2.0.7.stk
Data Type...................................... Code
Destination Filename........................... active
Management access will be blocked for the duration of the transfer
Are you sure you want to start? (y/n) y
SFTP Code transfer starting...
File transfer operation completed successfully.
----
====
. 确认当前和下一个活动的启动映像版本:
+
`s如何启动 var`
+
.显示示例
[%collapsible]
====
[listing]
----
(cs2) #show bootvar
Image Descriptions
active :
backup :
Images currently available on Flash
--------------------------------------------------------------------
unit active backup current-active next-active
--------------------------------------------------------------------
1 1.1.0.8 1.1.0.8 1.1.0.8 1.2.0.7
----
====
. 在交换机上安装新映像版本的兼容 RCF 。
+
如果RCF版本已正确、请启动ISL端口。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs2) #copy tftp://10.22.201.50//CN1610_CS_RCF_v1.2.txt nvram:script CN1610_CS_RCF_v1.2.scr
Mode........................................... TFTP
Set Server IP.................................. 10.22.201.50
Path........................................... /
Filename....................................... CN1610_CS_RCF_v1.2.txt
Data Type...................................... Config Script
Destination Filename........................... CN1610_CS_RCF_v1.2.scr
File with same name already exists.
WARNING:Continuing with this command will overwrite the existing file.
Management access will be blocked for the duration of the transfer
Are you sure you want to start? (y/n) y
Validating configuration script...
[the script is now displayed line by line]
Configuration script validated.
File transfer operation completed successfully.
----
====
+
NOTE: 在调用脚本之前,必须将 ` .scr` 扩展名设置为文件名的一部分。此扩展适用于 FastPath 操作系统。
+
将脚本下载到交换机后,交换机会自动验证该脚本。输出将转到控制台。
. 验证脚本是否已下载并保存到您为其指定的文件名中。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs2) #script list
Configuration Script Name Size(Bytes)
-------------------------------- -----------
CN1610_CS_RCF_v1.2.scr 2191
1 configuration script(s) found.
2541 Kbytes free.
----
====
. 将此脚本应用于交换机。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs2) #script apply CN1610_CS_RCF_v1.2.scr
Are you sure you want to apply the configuration script? (y/n) y
[the script is now displayed line by line]...
Configuration script 'CN1610_CS_RCF_v1.2.scr' applied.
----
====
. 验证所做的更改是否已应用于交换机,然后保存:
+
`s如何运行配置`
+
.显示示例
[%collapsible]
====
[listing]
----
(cs2) #show running-config
----
====
. 保存正在运行的配置,使其在重新启动交换机时成为启动配置。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs2) #write memory
This operation may take a few minutes.
Management interfaces will not be available during this time.
Are you sure you want to save? (y/n) y
Config file 'startup-config' created successfully.
Configuration Saved!
----
====
. 重新启动交换机。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs2) #reload
The system has unsaved changes.
Would you like to save them now? (y/n) y
Config file 'startup-config' created successfully.
Configuration Saved!
System will now restart!
----
====
=== 第3步:验证安装
. 重新登录,然后验证交换机是否正在运行新版本的 FastPath 软件。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs2) #show version
Switch: 1
System Description............................. NetApp CN1610, 1.2.0.7,Linux
3.8.13-4ce360e8
Machine Type................................... NetApp CN1610
Machine Model.................................. CN1610
Serial Number.................................. 20211200106
Burned In MAC Address.......................... 00:A0:98:21:83:69
Software Version............................... 1.2.0.7
Operating System............................... Linux 3.8.13-4ce360e8
Network Processing Device...................... BCM56820_B0
Part Number.................................... 111-00893
CPLD version................................... 0x5
Additional Packages............................ FASTPATH QOS
FASTPATH IPv6 Management
----
====
+
重新启动完成后,您必须登录以验证映像版本,查看正在运行的配置,并在接口 3/64 上查找问题描述 ,它是 RCF 的版本标签。
. 启动活动交换机 CS1 上的 ISL 端口。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs1) #configure
(cs1) (Config) #interface 0/13-0/16
(cs1) (Interface 0/13-0/16) #no shutdown
(cs1) (Interface 0/13-0/16) #exit
(cs1) (Config) #exit
----
====
. 验证 ISL 是否正常运行:
+
`s如何使用端口通道 3/1`
+
链路状态字段应指示 `up` 。
+
.显示示例
[%collapsible]
====
[listing]
----
(cs1) #show port-channel 3/1
Local Interface................................ 3/1
Channel Name................................... ISL-LAG
Link State..................................... Up
Admin Mode..................................... Enabled
Type........................................... Static
Load Balance Option............................ 7
(Enhanced hashing mode)
Mbr Device/ Port Port
Ports Timeout Speed Active
------ ------------- --------- -------
0/13 actor/long 10G Full True
partner/long
0/14 actor/long 10G Full True
partner/long
0/15 actor/long 10G Full False
partner/long
0/16 actor/long 10G Full True
partner/long
----
====
. 在所有节点上启动集群端口 e0b :
+
`network port modify`
+
您必须在拥有相应集群 LIF 的控制器控制台上输入命令。
+
.显示示例
[%collapsible]
====
以下示例显示了 node1 和 node2 上的端口 e0b :
[listing]
----
cluster1::*> network port modify -node node1 -port e0b -up-admin true
cluster1::*> network port modify -node node2 -port e0b -up-admin true
----
====
. 验证所有节点上的端口 e0b 是否均已启动:
+
`network port show -ipspace cluster`
+
.显示示例
[%collapsible]
====
[listing]
----
cluster1::*> network port show -ipspace cluster
Speed (Mbps)
Node Port IPspace Broadcast Domain Link MTU Admin/Oper
------ --------- ------------ ---------------- ----- ------- ------------
node1
e0a Cluster Cluster up 9000 auto/10000
e0b Cluster Cluster up 9000 auto/10000
node2
e0a Cluster Cluster up 9000 auto/10000
e0b Cluster Cluster up 9000 auto/10000
4 entries were displayed.
----
====
. 验证两个节点上的 LIF 现在是否为主(`true` ):
+
`network interface show -_role cluster_`
+
.显示示例
[%collapsible]
====
[listing]
----
cluster1::*> network interface show -role cluster
Logical Status Network Current Current Is
Vserver Interface Admin/Oper Address/Mask Node Port Home
----------- ---------- ---------- ------------------ ------------- ------- ----
Cluster
node1_clus1 up/up 169.254.66.82/16 node1 e0a true
node1_clus2 up/up 169.254.206.128/16 node1 e0b true
node2_clus1 up/up 169.254.48.152/16 node2 e0a true
node2_clus2 up/up 169.254.42.74/16 node2 e0b true
4 entries were displayed.
----
====
. 显示节点成员的状态:
+
`cluster show`
+
.显示示例
[%collapsible]
====
[listing]
----
cluster1::*> cluster show
Node Health Eligibility Epsilon
-------------------- ------- ------------ ------------
node1 true true false
node2 true true false
2 entries were displayed.
----
====
. 返回到管理权限级别:
+
`set -privilege admin`
. 重复上述步骤、在另一台交换机CS1上安装FastPath软件和RCF。
|
/**
* @file: app/template/register-from/register-from.component.ts
* @author: Leonid Vinikov <czf.leo123@gmail.com>
*/
//-----------------------------------------------------------------------------------------------------------------------------------------------------
import { Router } from "@angular/router";
import { Component, ViewChild, OnInit } from "@angular/core";
import { InvisibleReCaptchaComponent } from "ngx-captcha";
import { Logger } from "app/logger";
import { Validator } from "app/validator";
import { API_Service } from "app/api/service";
import { API_Service_Authorization } from "app/api/authorization/service";
import {
API_Model_Authorization_Send,
API_Model_Authorization_Recv,
API_Model_Authorization_States
} from "app/api/authorization/model";
//-----------------------------------------------------------------------------------------------------------------------------------------------------
const C_NoticeTime: number = 10000;
const C_DelayBeforeReroute = 1200;
//-----------------------------------------------------------------------------------------------------------------------------------------------------
@Component({
selector: "app-login-form",
templateUrl: "./login-form.component.html",
styleUrls: ["./login-form.component.css"],
providers: []
})
//-----------------------------------------------------------------------------------------------------------------------------------------------------
export class LoginFormComponent implements OnInit {
//----------------------------------------------------------------------
private logger: Logger;
public noticeType: string;
public noticeMsg: string;
private noticeTimeout: any;
private formData: API_Model_Authorization_Send;
//----------------------------------------------------------------------
@ViewChild("captchaElem") captchaElem: InvisibleReCaptchaComponent;
//----------------------------------------------------------------------
constructor(
private router: Router,
private api: API_Service,
private auth: API_Service_Authorization) {
// ----
this.logger = new Logger(this);
this.logger.debug("constructor", "");
this.noticeType = null;
this.formData = {
email: "",
password: "",
captcha: ""
}
this.clearNotice();
}
//----------------------------------------------------------------------
public ngOnInit() {
}
//----------------------------------------------------------------------
private validateForm(): boolean {
var frmData = this.formData;
if (false == Validator.isEmail(frmData.email)) {
this.setNotice("info", "Please type valid email address.");
return false;
}
if (frmData.password.length <= 0) {
this.setNotice("info", "Please type password.");
return false;
}
if (this.api.getAuthState() == API_Model_Authorization_States.VERIFY && ! this.formData.captcha.length) {
//this.captchaElem.resetCaptcha();
this.logger.debug("validateFrom", " captcha is empty, requesting captcha")
this.logger.debug("validateFrom", " this.captchaElem.execute();")
this.captchaElem.execute();
return false;
}
return true;
}
//----------------------------------------------------------------------
private loginResult(data: API_Model_Authorization_Recv) {
this.logger.startWith("loginResult", data);
switch (data.code) {
case "block":
switch (data.subcode) {
case "verify":
this.setNotice("info", "We are Confirm that you are not robot!, Checking ...");
setTimeout(() => {
if (this.formData.captcha.length > 0) {
this.captchaElem.resetCaptcha();
this.logger.debug("loginResul::timeOut", " this.captchaElem.resetCaptcha();")
}
this.logger.debug("loginResult", " this.captchaElem.execute();")
this.captchaElem.execute();
}, 1000);
break;
default:
this.setNotice("danger", "You have been blocked due too many attempts");
}
break;
case "mail":
switch (data.subcode) {
case "short":
this.setNotice("danger", "The email is too short.");
break;
default:
this.setNotice("danger", "Invalid email.");
}
case "wrong":
this.setNotice("danger", "Wrong username or password.");
break;
case "success":
this.setNotice("success", "You have been successfully logged in.");
this.noticeTimeout = setTimeout(() => {
this.router.navigate(['feed']);
}, 400);
break;
}
}
//----------------------------------------------------------------------
private handleCaptcha(handle, event = null) {
this.logger.startWith("handleCaptcha", { handle: handle, event: event });
switch (handle) {
case "success":
{
this.formData.captcha = event;
this.setNotice("success", "We recognize you as human, please type valid infomration.");
}
break;
}
}
//----------------------------------------------------------------------
private processForm() {
this.logger.debug("processForm", "");
// clear all errors before send
this.clearNotice();
if (this.validateForm()) {
this.auth.login(this.formData, this.loginResult.bind(this));
}
// clear all errors after x time
this.clearNoticeTimeout();
this.noticeTimeout = setTimeout(() => {
this.clearNotice();
}, C_NoticeTime);
}
//----------------------------------------------------------------------
private setNotice(type: string, message: string) {
this.noticeType = type;
this.noticeMsg = message;
}
//----------------------------------------------------------------------
private clearNotice() {
this.noticeType = null;
}
//----------------------------------------------------------------------
private clearNoticeTimeout() {
clearTimeout(this.noticeTimeout);
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------
|
p45:
-Atomic transaction
An atomic transaction is a possibly complex series of actions that is considered to be a single
operation by those who are not involved directly in performing the transaction.
Example : retrait de 100$ à la banque qui nécessite la vérification du solde, la soustraction au solde si oui, la maj du solde, et l'envoie de l'argent.
-CRUD
Qualités d'une bonne db :
*Retrieval=> notre bd doit nous permettre de retrouver n'importe quoi qu'on a enregistrer
*Consistency :
If you perform the same search twice in a row, you should get the same results.
*Validity :
Consistency means different parts of the database
don’t hold contradictory views of the same information.
The user interface could also make the user pick the state from a drop-down list and avoid this
problem, but the database should still protect itself against invalid data wherever possible.
Easy Error Correction :
changer le nom de tous les produits d'un certains type devrait être trivial. Mias il faut un bon design pour ne pas changer tous les produits et seulement un certains type.
Speed : designer de tel sorteà obtenir rapidement les informations nécessaires.
Atomic transaction :
The transaction either happens completely or none of its pieces happen
ACID :
ACID is an acronym describing four features that an effective transaction system should provide.
Atomicity, Consistency, Isolation, and Durability.
-Isolation means the transaction isolates the details of the transaction from everyone except the person
making the transaction.
Anyone who looks in the database
will see the $100 somewhere, either in Alice’s account before the transaction or in Bob’s account
afterward.
Durability
means that once a transaction is committed, it will not disappear later.
Once the transaction is committed, it is final
BASE : for nosql
BASE stands for Basically Available, Soft state, and Eventually consistent.
B :
Relational databases spend a lot of effort requiring data to be immediately consistent. These databases do, however, guarantee that any query will return some sort of result, even if it’s a failure
Soft state :
means that the state of the data may change over time, Because these databases do not
require immediate consistency, it may take a while for changes to filter through the entire system.
BACKUP :
Good database design can help make backups a bit easier. If you arrange the data so that changes
occur in a fairly localized area, you can back up that area frequently and not waste time backing up
data that changes only rarely
Low Cost and Extensibility
EASY OF USE
Just by looking at the names of the tables, fields, and other
database entities that organize the data, this type of user should be able to figure out how different
pieces of data go together and how to use them to retrieve the data they need.
SECURITY
using a database design that restricts users’ access to what they really need to
know can help.
Brewer’s theorem : CAP
|
/*
* Copyright 2019-2119 gao_xianglong@sina.com
*
* 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.github.test.netty02;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
/**
* @author gao_xianglong@sina.com
* @version 0.1-SNAPSHOT
* @date created in 2022/5/28 16:54
*/
public class EchoClientHandler extends SimpleChannelInboundHandler {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
var bf = (ByteBuf) msg;
System.out.printf("c->s:%s\n", ((ByteBuf) msg).toString(CharsetUtil.UTF_8));
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
var channel = ctx.channel();
var local = channel.localAddress().toString();
var remote = channel.remoteAddress().toString();
System.out.printf("%s成功连接%s\n", local, remote);
ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Netty", CharsetUtil.UTF_8));
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
var channel = ctx.channel();
var local = channel.localAddress().toString();
var remote = channel.remoteAddress().toString();
System.out.printf("%s断开%s的连接\n", local, remote);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
|
<?php
/**
* MultiWorld - PocketMine plugin that manages worlds.
* Copyright (C) 2018 - 2020 CzechPMDevs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace czechpmdevs\multiworld\util;
use pocketmine\block\Air;
use pocketmine\block\Block;
use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\StringTag;
/**
* Class BlockLoader
* @package czechpmdevs\multiworld\util
*/
class BlockLoader {
public const SIDE_HELPER = [
"bottom" => ["east" => 0, "west" => 1, "south" => 2, "north" => 3],
"top" => ["east" => 4, "west" => 5, "south" => 6, "north" => 7]
];
public const BLOCK_MAP = [
"minecraft:air" => [0, 0],
"minecraft:cobblestone" => [4, 0],
"minecraft:torch" => [50, 5],
"minecraft:pumpkin" => [86, 1],
"minecraft:carved_pumpkin" => [86, 1], // wrong id
"minecraft:dark_oak_slab" => [158, "type" => ["bottom" => 5, "top" => 13]],
"minecraft:dark_oak_log" => [162, "axis" => ["y" => 1, "x" => 5, "z" => 9]],
"minecraft:dark_oak_fence" => [85, 5],
"minecraft:illager_captain_wall_banner" => [177, 4], // 2=>z-;3=>z+;4=>x-;5=>x+
"minecraft:birch_planks" => [5, 2],
"minecraft:dark_oak_planks" => [5, 5],
"minecraft:white_wool" => [35, 0],
"minecraft:hay_block" => [170, 0],
"minecraft:cobblestone_stairs" => [67, "sides" => self::SIDE_HELPER],
"minecraft:mossy_cobblestone_stairs" => [67, "sides" => self::SIDE_HELPER], // wrong id (isn't implemented)
"minecraft:dark_oak_stairs" => [164, "sides" => self::SIDE_HELPER],
"minecraft:vine" => [106, "facing" => ["north" => 4, "east" => 8 , "south" => 1, "west" => 2]],
"minecraft:cobblestone_wall" => [139, 0],
"minecraft:mossy_cobblestone_wall" => [139, 1],
"minecraft:cobblestone_slab" => [44, "type" => ["bottom" => 3, "top" => 11]],
"minecraft:mossy_cobblestone_slab" => [182, "type" => ["bottom" => 5, "top" => 13]],
"minecraft:mossy_cobblestone" => [48, 0],
"minecraft:crafting_table" => [58, 0],
"minecraft:structure_block" => [0, 0] // 252
];
/**
* @param CompoundTag $state
*
* @return SimpleBlockData
*/
public static function getBlockByState(CompoundTag $state): SimpleBlockData {
$data = self::BLOCK_MAP[$state->getString("Name")] ?? 0;
if($data === 0) {
return new SimpleBlockData(0, 0);
}
$id = $data[0];
if(isset($data[1])) {
return new SimpleBlockData($id, $data[1]);
}
if(isset($data["axis"])) {
return new SimpleBlockData($id, $data["axis"][$state->getCompoundTag("Properties")->getString("axis")]);
}
if(isset($data["type"])) {
return new SimpleBlockData($id, $data["type"][$state->getCompoundTag("Properties")->getString("type")]);
}
if(isset($data["sides"])) {
return new SimpleBlockData($id, $data["sides"][$state->getCompoundTag("Properties")->getString("half")][$state->getCompoundTag("Properties")->getString("facing")]);
}
if(isset($data["facing"])) {
$facing = null;
$properties = $state->getCompoundTag("Properties");
if($properties->offsetExists("facing"))
$facing = $state->getCompoundTag("Properties")->getString("facing");
else {
/**
* @var string $side
* @var StringTag $value
*/
foreach ($properties->getValue() as $side => $value) {
if($value->getValue() == "true") {
$facing = $side;
break;
}
}
}
return new SimpleBlockData($id, $data["facing"][$facing]);
}
return new SimpleBlockData(0, 0);
}
}
/**
* Class SimpleBlockData
* @package czechpmdevs\multiworld\util
*/
class SimpleBlockData {
/** @var int $id */
public $id;
/** @var int $meta */
public $meta;
/**
* SimpleBlockData constructor.
* @param int $id
* @param int $meta
*/
public function __construct(int $id, int $meta) {
$this->id = $id;
$this->meta = $meta;
}
/**
* @return int
*/
public function getId(): int {
return $this->id;
}
/**
* @return int
*/
public function getMeta(): int {
return $this->meta;
}
}
|
<!DOCTYPE HTML>
<html >
<head>
<meta charset="UTF-8">
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('http://images.bestswifter.com/sw.js')
}
</script>
<title>异步与回调的设计哲学 | 全栈养成计划</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=3, minimum-scale=1">
<meta name="author" content="Fullstack">
<meta name="description" content="本文的例子用 JavaScript 语法给出,希望读者至少有使用过 Promise 的经验,如果用过 async/await 则更好,对于客户端的开发者,我相信语法不是阅读的瓶颈,思维才是,因此也可以了解一下异步编程模型的演变过程。
异步编程入门CPSCPS 的全称是 (Continuation-P">
<link rel="alternate" href="atom.xml" title="全栈养成计划" type="application/atom+xml">
<link rel="icon" href="/img/favicon.ico">
<link rel="apple-touch-icon" href="/img/pacman.jpg">
<link rel="apple-touch-icon-precomposed" href="/img/pacman.jpg">
<link rel="stylesheet" href="/css/style.css">
<script type="text/javascript">
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?8b8cc550e083bb800d2b0d350318e611";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
</head>
<body>
<header>
<div>
<div id="imglogo">
<a href="/"><img src="/img/logo.svg" alt="全栈养成计划" title="全栈养成计划"/></a>
</div>
<div id="textlogo">
<h1 class="site-name"><a href="/" title="全栈养成计划">全栈养成计划</a></h1>
<h2 class="blog-motto">每天学点新知识~</h2>
</div>
<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
</a></div>
<nav class="animated">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/archives">Archives</a></li>
<li><a href="/categories">categories</a></li>
<li><a href="/tags">tags</a></li>
<li>
<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
<label>Search</label>
<input type="text" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
<input type="hidden" name="q" value="site:fullstack.blog">
</form>
</li>
</ul>
</nav>
</div>
</header>
<div id="container">
<div id="main" class="post" itemscope itemprop="blogPost">
<article itemprop="articleBody">
<header class="article-info clearfix">
<h1 itemprop="name">
<a href="/2017/02/26/异步与回调的设计哲学/" title="异步与回调的设计哲学" itemprop="url">异步与回调的设计哲学</a>
</h1>
<p class="article-author">By
<a href="http://fullstack.blog" title="Fullstack">Fullstack</a>
</p>
<p class="article-time">
<time datetime="2017-02-26T14:23:20.000Z" itemprop="datePublished">2017-02-26</time>
Updated:<time datetime="2017-02-26T14:25:42.000Z" itemprop="dateModified">2017-02-26</time>
</p>
</header>
<div class="article-content">
<div id="toc" class="toc-article">
<strong class="toc-title">Contents</strong>
<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#异步编程入门"><span class="toc-number">1.</span> <span class="toc-text">异步编程入门</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#CPS"><span class="toc-number">1.1.</span> <span class="toc-text">CPS</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#没什么卵用的-CPS"><span class="toc-number">1.2.</span> <span class="toc-text">没什么卵用的 CPS</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Promise"><span class="toc-number">2.</span> <span class="toc-text">Promise</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#CPS-的本质"><span class="toc-number">2.1.</span> <span class="toc-text">CPS 的本质</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-的本质"><span class="toc-number">2.2.</span> <span class="toc-text">Promise 的本质</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-的基本概念"><span class="toc-number">2.3.</span> <span class="toc-text">Promise 的基本概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-小细节"><span class="toc-number">2.4.</span> <span class="toc-text">Promise 小细节</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#生成器-Generator"><span class="toc-number">3.</span> <span class="toc-text">生成器 Generator</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Generator-in-JavaScript"><span class="toc-number">3.1.</span> <span class="toc-text">Generator in JavaScript</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Generator-的实现"><span class="toc-number">3.2.</span> <span class="toc-text">Generator 的实现</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Async-Await"><span class="toc-number">4.</span> <span class="toc-text">Async/Await</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#回调改为线性"><span class="toc-number">4.1.</span> <span class="toc-text">回调改为线性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#“同步”-写法的设计哲学"><span class="toc-number">4.2.</span> <span class="toc-text">“同步” 写法的设计哲学</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#参考资料"><span class="toc-number">5.</span> <span class="toc-text">参考资料</span></a></li></ol>
</div>
<p>本文的例子用 JavaScript 语法给出,希望读者至少有使用过 Promise 的经验,如果用过 async/await 则更好,对于客户端的开发者,我相信语法不是阅读的瓶颈,思维才是,因此也可以了解一下异步编程模型的演变过程。</p>
<h1 id="异步编程入门"><a href="#异步编程入门" class="headerlink" title="异步编程入门"></a>异步编程入门</h1><h2 id="CPS"><a href="#CPS" class="headerlink" title="CPS"></a>CPS</h2><p>CPS 的全称是 (Continuation-Passing Style),这个名词听上去比较高大上(背后涉及到很多数学方面的东西),实际上如果只是想了解什么是 CPS 的话,并不是太难。</p>
<p>我们看下面这段代码,你肯定会觉得太简单了:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">a, b</span>) </span>{</div><div class="line"> <span class="keyword">return</span> a + b;</div><div class="line">}</div><div class="line"></div><div class="line">int a = sum(<span class="number">1</span>, <span class="number">2</span>); <span class="comment">// 第一行业务代码 </span></div><div class="line"><span class="built_in">console</span>.log(a); <span class="comment">// 第二行业务代码</span></div></pre></td></tr></table></figure>
<p>隐藏在这两行代码背后的是串行编程的思想,也就是说第一行代码执行出结果以后才会执行第二行代码。</p>
<p>可如果 <code>sum</code> 这个函数耗时比较久怎么办呢,一般我们不会选择等待它执行完,而是提供一个回调,在执行完耗时操作以后再执行回调,同时避免阻塞主线程:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">asum</span>(<span class="params">a, b, callback</span>) </span>{</div><div class="line"> <span class="keyword">const</span> r = a + b;</div><div class="line"> setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</div><div class="line"> callback(r);</div><div class="line"> }, <span class="number">0</span>);</div><div class="line">}</div><div class="line"></div><div class="line">asum(<span class="number">1</span>, <span class="number">2</span>, r => <span class="built_in">console</span>.log(r));</div></pre></td></tr></table></figure>
<p>于是,业务方不用等待 <code>asum</code> 的返回结果了,现在它只要提供一个回调函数。这种写法就叫做 CPS。</p>
<p>CPS 可以总结为一个很重要的思想: <strong>“我不用等执行结果,我先假设结果已经有了,然后描述一下如何利用这个结果,至于调用的时机,由结果提供方负责管理”</strong>。</p>
<h2 id="没什么卵用的-CPS"><a href="#没什么卵用的-CPS" class="headerlink" title="没什么卵用的 CPS"></a>没什么卵用的 CPS</h2><p>扯了这么多 CPS,其实我想说的是,很多介绍 Promise 的文章上来就谈 CPS,更有甚者直接聊起了 CPS 的背后数学模型。实际上 CPS 对异步编程没什么卵用,主要是它的概念太普遍,太容易理解了,我敢打赌几乎所有的开发者都或多或少的用过 CPS。</p>
<p>毕竟回调函调每个人都用过,只不过你不一定知道这是 CPS 而已。比如随便举一个 AFNetworking 中的例子:</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">NSURLSessionDataTask</span> *dataTask = [manager dataTaskWithRequest:request completionHandler:^(<span class="built_in">NSURLResponse</span> *response, <span class="keyword">id</span> responseObject, <span class="built_in">NSError</span> *error) {</div><div class="line"> <span class="keyword">if</span> (error) {</div><div class="line"> <span class="built_in">NSLog</span>(<span class="string">@"Error: %@"</span>, error);</div><div class="line"> } <span class="keyword">else</span> {</div><div class="line"> <span class="built_in">NSLog</span>(<span class="string">@"%@ %@"</span>, response, responseObject);</div><div class="line"> }</div><div class="line">}];</div></pre></td></tr></table></figure>
<h1 id="Promise"><a href="#Promise" class="headerlink" title="Promise"></a>Promise</h1><p>写过 JavaScript 的人应该都接触过 Promise,首先明确一个概念,Promise 是一些列规范的总称,现有的规范有 Promise/A、Promise/B、Promise/A+ 等等,每个规范都有自己的实现,当然也可以自己提供一个实现,只要能满足规范中的描述即可。</p>
<p>写过 Promise 或者 RAC/RxSwift 的读者估计对一长串 <code>then</code> 方法记忆深刻,不知道大家是否思考过,为什么会设计这种链式写法呢?</p>
<p>我当然不想听到什么“方法调用以后还返回自己”这种废话,要能反复调用 then 方法必然要返回同一个类的对象啊。。。要想搞清楚为什么要这么设计,或者为什么可以这么设计,我们先来看看传统的 CPS(基于回调) 写法如何处理嵌套的异步事件。</p>
<p>如果我需要请求第一个接口,并且用这个接口返回的数据请求下一个接口,那代码看起来大概是这样的:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">request(url1, parms1, response => {</div><div class="line"> <span class="comment">// 处理 response</span></div><div class="line"> request(url2, params2, response => {</div><div class="line"> <span class="comment">// 处理第二个接口的数据</span></div><div class="line"> })</div><div class="line">})</div></pre></td></tr></table></figure>
<p>上述代码用伪代码写起来看上去还能接受,不过可以参考 OC 的繁琐代码,试想一个双层嵌套就已经如此麻烦, 三层嵌套该怎么写是好呢?</p>
<h2 id="CPS-的本质"><a href="#CPS-的本质" class="headerlink" title="CPS 的本质"></a>CPS 的本质</h2><p>我们抽象一下上面的逻辑,CPS 的含义是不直接等待异步数据返回,而是传入一个回调函数来处理未来的数据。换句话讲:</p>
<p><strong>回调事件是一个普通事件,内部可能还会发起一个异步事件</strong></p>
<p>这种世界观的好处在于,通过事件的嵌套形成了一套递归模型,理论上能够解决任意多层的嵌套。当然缺点也是显而易见的,<strong>语义上的嵌套最终导致了代码上的嵌套</strong>,影响了可读性和可维护性。</p>
<p>这种嵌套模型可以用下面这幅图来表示:</p>
<p><img src="http://images.bestswifter.com/1488098032.png" alt="CPS 回调的本质"></p>
<p>可以看到图中只有两种图形,椭圆形表示一般性事件(回调也是一个事件),而圆角矩形表示一个异步过程,当执行完以后,就会接着执行它连接着的事件。</p>
<h2 id="Promise-的本质"><a href="#Promise-的本质" class="headerlink" title="Promise 的本质"></a>Promise 的本质</h2><p>当然,我们是有办法解决嵌套问题的,俗话说得好:</p>
<blockquote>
<p>任何计算机问题都可以通过添加一个中间层来解决</p>
</blockquote>
<p>而 Promise 的本质则是下面这幅图:</p>
<p><img src="http://images.bestswifter.com/1488098234.png" alt="Promise 的本质"></p>
<p>可以看到,我们引入了新的 Promise 层,一个 Promise 内部封装了异步过程,和异步过程结束以后的回调。如果这个回调的内部可以生成一个新的 Promise。于是嵌套模型就变成了链式模型,这也是为什么我们经常能看到 <code>then</code> 方法的调用链。</p>
<p>需要强调的是,即使你用了 Promise,也可以在回调函数中直接执行异步过程,这样就回到了嵌套模型。所以 Promise 的精髓实际上在于回调函数中返回一个新的 Promise 对象。</p>
<h2 id="Promise-的基本概念"><a href="#Promise-的基本概念" class="headerlink" title="Promise 的基本概念"></a>Promise 的基本概念</h2><p>数据结构学得好的读者看到上面这幅图应该会想到链表。不过一个 Promise 内部可以持有多个新的 Promise,所以采用的不是链表结构而是有些类似于多叉树。简化版的 Promise 定义如下:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">Promise</span>(<span class="params">resolver</span>) </span>{</div><div class="line"> <span class="keyword">this</span>.state = PENDING;</div><div class="line"> <span class="keyword">this</span>.value = <span class="keyword">void</span> <span class="number">0</span>;</div><div class="line"> <span class="keyword">this</span>.queue = []; <span class="comment">// 持有接下来要执行的 promise</span></div><div class="line"> <span class="keyword">if</span> (resolver !== INTERNAL) {</div><div class="line"> safelyResolveThen(<span class="keyword">this</span>, resolver);</div><div class="line"> }</div><div class="line">}</div></pre></td></tr></table></figure>
<p>对一个 Promise 对象调用 <code>then</code> 方法,实际上是判断 Promise 的状态是否还是 <code>PENDING</code>,如果是的话就生成一个新的 Promise 保存在数组中。否则直接执行 then 方法参数中 block。</p>
<p>当一个 Promise 内部执行完以后,比如说是进入了 <code>FULLFILLED</code> 状态,就会遍历自己持有的所有的 Promise 并告诉他们也去执行 <code>resolve</code> 方法,进入 <code>REJECTED</code> 状态也是同理。</p>
<p>如果能够理解这层思想,你就可以理解为什么有前后关系顺序的几个异步事件可以用 <code>then</code> 这种同步写法串联了。因为调用 <code>then</code> 实际上是预先保留了一个回调,只有当上一个 Promise 结束以后才会通知到下一个 Promise。</p>
<h2 id="Promise-小细节"><a href="#Promise-小细节" class="headerlink" title="Promise 小细节"></a>Promise 小细节</h2><p>关于 Promise 的实现原理,这篇文章不想描述太多,感兴趣的读者可以参考 <a href="https://zhuanlan.zhihu.com/p/25178630" target="_blank" rel="external">深入 Promise(一)——Promise 实现详解</a>,读完以后可以看一下作者的后续文章中的四个题目,检验一下是否真的理解了: <a href="https://zhuanlan.zhihu.com/p/25198178" target="_blank" rel="external">深入 Promise(二)——进击的 Promise</a>。</p>
<p>这里我只想强调一下几个容易理解错的地方。首先,Promise 会接受一个函数作为自己的参数,也就是下面代码中的 <code>fucntion (resolve, reject){ /* do something */ }</code>:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>) </span>{</div><div class="line"> resolve(<span class="string">'hello'</span>);</div><div class="line">});</div><div class="line"><span class="built_in">console</span>.log(ppppp);</div><div class="line"><span class="comment">// 打印出 Promise { 'hello' } 而不是 Promise { 'pedding' }</span></div><div class="line"><span class="comment">// 证明 Promise 已经在创建时就决议</span></div></pre></td></tr></table></figure>
<p>在创建 Promise 时,这个参数函数就会被执行, 执行这个函数需要两个参数 <code>resoleve</code> 和 <code>reject</code>,它并不是通过 <code>then</code> 方法提供而是由 Promise 在内部自己提供,换句话说这两个参数是已知的。</p>
<p>因此如果按照上述代码来写, 在创建 Promise 时就会立刻调用 <code>resolve('hello')</code>,然后把状态标记为 <code>FULLFILLED</code> 并且让内部的 <code>value</code> 值为 <code>"hello"</code>。这样后来执行 <code>then</code> 的时候会判断到 Promise 已经决议,直接把 <code>value</code> 的值放到 then 的闭包中,而且这个过程是异步执行(参考文章中 immediate 的使用)。</p>
<p>有的文章会谈到 Promise 的错误处理,实际上这里没有什么高深的学问或者黑科技。如果在 Promise 内部调用 <code>setTimeout</code> 异步的抛出错误,外面还是接不到。</p>
<p>Promise 处理错误的原则是提供了一个 <code>reject</code> 回调,并且用 <code>reject</code> 方法来代替抛出错误的做法。这样做相当于约定了一套错误协议,把错误直接转嫁到业务方的逻辑中。</p>
<p>另一个需要重点理解的是 <code>then</code> 方法提供的闭包中,返回的内容,因为这才是链式模型的核心。</p>
<p>在 Promise 内部的 <code>doResolve</code> 方法中会有以下关键判断:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> then = getThen(value);</div><div class="line"><span class="keyword">if</span> (then) {</div><div class="line"> safelyResolveThen(self, then);</div><div class="line">} <span class="keyword">else</span> {</div><div class="line"> self.state = FULFILLED;</div><div class="line"> self.value = value;</div><div class="line"> self.queue.forEach(<span class="function"><span class="keyword">function</span> (<span class="params">queueItem</span>) </span>{</div><div class="line"> queueItem.callFulfilled(value);</div><div class="line"> });</div><div class="line">}</div></pre></td></tr></table></figure>
<p>因此如果这里的 value 不是基本类型,就会重新走一遍 <code>safelyResolveThen</code>,相当于重新解一遍 Promise 了。</p>
<p>所以正确的异步嵌套逻辑应该是: </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>) </span>{</div><div class="line"> resolve(<span class="string">'hello'</span>);</div><div class="line">})</div><div class="line">p.then(<span class="function"><span class="params">value</span> =></span> {</div><div class="line"> <span class="built_in">console</span>.log(value);</div><div class="line"> <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>) </span>{</div><div class="line"> resolve(<span class="string">'world'</span>)</div><div class="line"> });</div><div class="line">}).then(<span class="function"><span class="params">value</span> =></span> {</div><div class="line"> <span class="built_in">console</span>.log(value);</div><div class="line">});</div><div class="line"></div><div class="line"><span class="comment">// 第一行打印出 hello</span></div><div class="line"><span class="comment">// 第二行打印出 world</span></div></pre></td></tr></table></figure>
<h1 id="生成器-Generator"><a href="#生成器-Generator" class="headerlink" title="生成器 Generator"></a>生成器 Generator</h1><p>我们先看一个 Python 中的例子,如何打印斐波那契数列的前五个元素:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">fab</span><span class="params">(max)</span>:</span> </div><div class="line"> n, a, b = <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span> </div><div class="line"> <span class="keyword">while</span> n < max: </div><div class="line"> <span class="keyword">print</span> b </div><div class="line"> a, b = b, a + b </div><div class="line"> n = n + <span class="number">1</span></div></pre></td></tr></table></figure>
<p>得益于 Python 简洁的语法,函数实现仅用了六行代码:</p>
<p><img src="http://images.bestswifter.com/1488103781.png" alt="fab 函数"></p>
<p>不过缺点在于, 每次调用函数都会打印所有数字,不能实现按需打印:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span> n <span class="keyword">in</span> fab(<span class="number">5</span>): </div><div class="line"> <span class="keyword">print</span> n</div></pre></td></tr></table></figure>
<p>我们先不考虑为什么 <code>fab(5)</code> 能放在 <code>in</code> 关键字后面,至少能分次打印就意味着我们需要一个对象,内部保存上一次的结果,这样才能正确的生成下一个值。</p>
<p>感兴趣的读者可以用对象来实现一下上述需求, 并且对比一下引入对象后带来的复杂度增加。一种既不增加复杂度,也能保留上下文的技术是使用生成器,只需要修改一个单词即可:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">fab</span><span class="params">(max)</span>:</span> </div><div class="line"> n, a, b = <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span> </div><div class="line"> <span class="keyword">while</span> n < max: </div><div class="line"> <span class="keyword">yield</span> b <span class="comment">#原来是 print b</span></div><div class="line"> a, b = b, a + b </div><div class="line"> n = n + <span class="number">1</span></div></pre></td></tr></table></figure>
<p><code>yield</code> 关键字的含义是 <strong>当外界调用 next 方法时生成器内部开始执行,直到遇到 yield 关键字,此时把 yield 后面的值传递出去作为 next() 的结果,然后继续执行函数,直到再次遇到 yield 方法时暂停</strong>。</p>
<h2 id="Generator-in-JavaScript"><a href="#Generator-in-JavaScript" class="headerlink" title="Generator in JavaScript"></a>Generator in JavaScript</h2><p>上面举 Python 的例子是因为生成器在 Python 中最为简单,最好理解。在 JavaScript 中,生成器的概念稍微复杂一点,主要涉及两个变化。</p>
<ol>
<li>要求在 function 后面加上星号(*) 表示这是一个生成器而不是普通函数。</li>
<li><code>next()</code> 方法可以传递参数,在生成器内部表现为 yield 的返回值。</li>
</ol>
<p>举个例子:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">generator</span>(<span class="params">count</span>) </span>{</div><div class="line"> <span class="built_in">console</span>.log(count);</div><div class="line"> <span class="keyword">const</span> result = <span class="keyword">yield</span> <span class="number">100</span></div><div class="line"> <span class="built_in">console</span>.log(result + count);</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">const</span> g = generator(<span class="number">2</span>); <span class="comment">// 什么都不输出</span></div><div class="line"><span class="built_in">console</span>.log(g.next().value); <span class="comment">// 第一次打印 2,随后打印 100</span></div><div class="line">g.next(<span class="number">9</span>); <span class="comment">// 打印 11</span></div></pre></td></tr></table></figure>
<p>逐行解释一下:</p>
<ol>
<li>调用 <code>generator</code> 时,生成器并没有执行,所以什么都没有输出。</li>
<li>调用 <code>g.next</code> 时,函数开始执行,打印 <code>2</code>,遇到 yield,拿到了 yield 生成的内容,也就是 100,传递给 <code>next()</code> 的调用结果,所以第二行打印 100。</li>
<li>再次调用 <code>next()</code> 方法,生成器内部恢复执行,由于 <code>next()</code> 方法传入参数 9,所以 <code>result</code> 的值是 9,第三行打印 11。</li>
</ol>
<p>可见 JavaScript 中的生成器通过 <code>yield value</code> 和<code>next(value)</code> 实现了值的内外双向传递。</p>
<h2 id="Generator-的实现"><a href="#Generator-的实现" class="headerlink" title="Generator 的实现"></a>Generator 的实现</h2><p>我不知道 Generator 在 JavaScript 和 Python 中的实现原理,然而用 Objective-C 确实可以模拟出来。考虑到生成器内部 <strong>运行 -> 等待 -> 恢复运行</strong> 的特点,信号量是最佳的实现方案。</p>
<p><code>yield</code> 实际上就是信号量的 <code>wait</code> 方法,而 <code>next()</code> 实际上就是信号量的 <code>signal</code> 方法。当然还要处理好数据的交互问题。总的来说思路还是比较清晰的。</p>
<h1 id="Async-Await"><a href="#Async-Await" class="headerlink" title="Async/Await"></a>Async/Await</h1><p>我们先举一个例子,看一下 Promise 的使用,每次调用函数 <code>p()</code> 都会生成一个新的 Promise 对象,内部的操作是把参数加一并返回,不妨把函数 p 想象成某个耗时操作。 </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">p</span>(<span class="params">t</span>) </span>{</div><div class="line"> <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>) </span>{</div><div class="line"> setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</div><div class="line"> resolve(t + <span class="number">1</span>);</div><div class="line"> }, t);</div><div class="line"> });</div><div class="line">}</div></pre></td></tr></table></figure>
<p>假设我需要反复的、线性的执行这个耗时操作,代码将是这样的: </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">p(<span class="number">0</span>).then( <span class="function"><span class="params">r</span> =></span> {</div><div class="line"> <span class="built_in">console</span>.log(r);</div><div class="line"> <span class="keyword">return</span> p(r);</div><div class="line">}).then( <span class="function"><span class="params">r</span> =></span> {</div><div class="line"> <span class="built_in">console</span>.log(r);</div><div class="line"> <span class="keyword">return</span> p(r);</div><div class="line">}).then( <span class="function"><span class="params">r</span> =></span> {</div><div class="line"> <span class="built_in">console</span>.log(r);</div><div class="line"> <span class="keyword">return</span> p(r);</div><div class="line">});</div></pre></td></tr></table></figure>
<p>可见我们调用三次 <code>then</code> 方法,执行了三次加一操作,因此会有三行输出,分别是 1、2、3。</p>
<h2 id="回调改为线性"><a href="#回调改为线性" class="headerlink" title="回调改为线性"></a>回调改为线性</h2><p>文章的一开头就说了,代码总是线性执行, 遇到异步操作不会进行等待,而是直接设置好回调函数并继续向后执行。</p>
<p>实际上,如果借助于 Generator 暂停、恢复的特性,我们可以用同步的方式来写异步代码。比如我们先定义一个生成器 <code>linear()</code> 表示内部将要线性执行异步代码:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">linear</span>(<span class="params"></span>) </span>{</div><div class="line"> <span class="keyword">const</span> r1 = <span class="keyword">yield</span> p(<span class="number">0</span>);</div><div class="line"> <span class="built_in">console</span>.log(r1);</div><div class="line"> <span class="keyword">const</span> r2 = <span class="keyword">yield</span> p(r1);</div><div class="line"> <span class="built_in">console</span>.log(r2);</div><div class="line"> <span class="keyword">const</span> r3 = <span class="keyword">yield</span> p(r2);</div><div class="line"> <span class="built_in">console</span>.log(r3);</div><div class="line">}</div></pre></td></tr></table></figure>
<p>我们看到 yield 的值是一个 Promise 对象,为了拿到这个对象,需要调用 <code>g.next().value</code>。因此为了让第一个输出打印来,代码是这样的: </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">g.next().value.then(<span class="function"><span class="params">value</span> =></span> { <span class="comment">// 其实是 Promise.then 的模式</span></div><div class="line"> <span class="comment">// 正如上一节 Generator 的例子中所述,第一个 next 会启动 Generator,并且卡在第一个 yield 上</span></div><div class="line"> <span class="comment">// 为了让程序向后执行,还需要再调用一次 next,其中的参数 0 会赋值给 r1。</span></div><div class="line"> g.next(<span class="number">0</span>).value.then()</div><div class="line">})</div></pre></td></tr></table></figure>
<p>如何模拟完整的三个 Promise 调用呢,这要求我们的代码不断向内迭代,同时用一个值保存上一次的结果:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> t = <span class="number">0</span>;</div><div class="line"><span class="keyword">var</span> g = linear();</div><div class="line">g.next().value.then(<span class="function"><span class="params">value</span> =></span> {</div><div class="line"> t = value;</div><div class="line"> g.next(t).value.then(<span class="function"><span class="params">value</span> =></span> {</div><div class="line"> t = value;</div><div class="line"> g.next(t).value.then(<span class="function"><span class="params">value</span> =></span> {</div><div class="line"> t = value;</div><div class="line"> g.next(t)</div><div class="line"> })</div><div class="line"> })</div><div class="line">})</div></pre></td></tr></table></figure>
<p>这种写法的运行结果和之前用 <code>then</code> 语法的运行结果完全一致。</p>
<p>有的读者可能会想问,这种写法完全没有看到好处啊,反而像是回退到了最初的模式,各种嵌套不利于代码阅读和理解。</p>
<p>然而仔细观察这段代码就会发现,嵌套逻辑中更多的是架构逻辑而非业务逻辑,业务逻辑都放在 Promise 内部实现了,因此这里的复杂代码实际上是可以做精简的,它是一个结构高度一致的递归模型。</p>
<p>我们注意到 <code>g.next().value.then</code>的内部实际上是重复了外面的调用过程,如何描述这样的递归呢,有一个小技巧,只要在最外层包一个函数,然后递归执行函数就行:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 递归必然要有可以递归的函数,因此我们在外面包装一层函数</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">recursive</span>(<span class="params"></span>) </span>{</div><div class="line"> g.next(t).value.then(<span class="function"><span class="params">value</span> =></span> {</div><div class="line"> t = value;</div><div class="line"> <span class="keyword">return</span> value;</div><div class="line"> }).then( <span class="function"><span class="params">result</span> =></span> recursive())</div><div class="line">}</div><div class="line"></div><div class="line">recursive();</div></pre></td></tr></table></figure>
<p>然而有一个问题在于,我们必须在 <code>recursive()</code> 函数外面创建生成器 <code>g</code>,否则放在函数内部就会导致递归创建新的。因此我们可以加一个内部函数处理核心的递归问题,而外部函数处理生成器和临时变量的创建:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">recursive</span>(<span class="params">generator</span>) </span>{</div><div class="line"> <span class="keyword">let</span> t; <span class="comment">// 临时变量,用来存储</span></div><div class="line"> <span class="keyword">var</span> g = linear(); <span class="comment">// 创建整个递归过程中唯一的生成器</span></div><div class="line"> </div><div class="line"> <span class="function"><span class="keyword">function</span> <span class="title">_recursive</span>(<span class="params"></span>) </span>{</div><div class="line"> g.next(t).value.then(<span class="function"><span class="params">value</span> =></span> {</div><div class="line"> t = value;</div><div class="line"> <span class="keyword">return</span> value;</div><div class="line"> }).then(<span class="function"><span class="params">()</span> =></span> _recursive())</div><div class="line"> }</div><div class="line"> _recursive();</div><div class="line">}</div><div class="line"></div><div class="line">recursive(linear);</div></pre></td></tr></table></figure>
<p>可以看到这个 <code>recursive</code> 函数完全与业务无关,对于任何生成器函数,比如说叫 g,都可以通过 <code>recursive(g)</code> 来进行调用。</p>
<p>这也就通过实际例子简单的证明了即使是异步事件也可以采用同步写法。</p>
<p>需要注明的是,这<strong>并不是</strong> async/await 语法的真正实现,这种写法的问题在于,await 外面的每一层函数都要标注为 async,然而没办法把每一个函数都转换成生成器,然后调用 <code>recursive()</code></p>
<p>感兴趣的同学可以了解一下 <a href="https://goo.gl/jlXboV" target="_blank" rel="external">babel 转换前后的代码</a>。</p>
<h2 id="“同步”-写法的设计哲学"><a href="#“同步”-写法的设计哲学" class="headerlink" title="“同步” 写法的设计哲学"></a>“同步” 写法的设计哲学</h2><p>标记了 async 的函数返回结果总是一个 Promise 对象,如果函数内部抛出了异常,就会调用 reject 方法并携带异常信息。否则就会把函数返回值作为 resolve 函数的参数调用。</p>
<p>理解了这一点以后,我们会发现 async/await 其实是<strong>异步操作的向外转移</strong>。</p>
<p>比如说 p 是一个 Promise 对象,我们可能会这样写: </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"></span>) </span>{</div><div class="line"> <span class="keyword">var</span> value = <span class="keyword">await</span> p;</div><div class="line"> <span class="built_in">console</span>.log(<span class="string">'value = '</span> + value);</div><div class="line"> <span class="keyword">return</span> value;</div><div class="line">}</div><div class="line">test().then(<span class="function"><span class="params">value</span> =></span> <span class="built_in">console</span>.log(value));</div></pre></td></tr></table></figure>
<p>我们一定程度上可以把 <code>test</code> 当做生成器来看:</p>
<ol>
<li>调用 test 方法时,首先会执行 test 内部的代码,直到遇到 await。</li>
<li>test 方法暂时退出,执行正常的逻辑,此时 test 的返回值尚不可用,但是它是一个 Promise,可以设置 then 回调。</li>
<li>await 等待的异步操作结束,test 方法返回,执行 then 回调</li>
</ol>
<p>因此我们发现异步操作并没有消失,也不可能消失,只是从 <code>await</code> 的地方转移到了外面的 <code>async</code> 函数上。如果这个函数的返回值有用,那么外部还得使用 <code>await</code> 进行等待,并且把方法标记为 <code>async</code>。</p>
<p>所以个人建议在使用 <code>await</code> 关键字的时候,首先应该判断对异步操作的依赖情况,比如以下场景就非常合适:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">async</span> sendRequest(url) {</div><div class="line"> <span class="keyword">const</span> response = <span class="keyword">await</span> fetch(url); <span class="comment">// 异步请求网络</span></div><div class="line"> <span class="keyword">const</span> result = <span class="keyword">await</span> asyncStore(response); <span class="comment">// 得到结果后异步存储数据</span></div><div class="line">}</div></pre></td></tr></table></figure>
<p>考虑到 <code>await</code> 会阻塞执行,如果某个 Promise 后面的代码任然需要执行(比如存储、统计、日志等),则不建议盲目使用 <code>await</code>:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"></span>) </span>{</div><div class="line"> <span class="keyword">var</span> s = <span class="keyword">await</span> fetch(url);</div><div class="line"> <span class="built_in">console</span>.log(<span class="string">'这里输出不了啊'</span>);</div><div class="line">}</div></pre></td></tr></table></figure>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><ol>
<li><a href="http://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/" target="_blank" rel="external">Python yield 使用浅析</a></li>
<li><a href="http://liubin.org/promises-book/" target="_blank" rel="external">JavaScript Promise迷你书(中文版)</a></li>
<li><a href="http://mp.weixin.qq.com/s?__biz=MzIwNjQwMzUwMQ==&mid=2247484976&idx=1&sn=af2a8b2cabdef9f9396120ca1dd0eae5&chksm=972364f2a054ede406670bf591e0723655c207994a92f7620d4392b66c467610d4be55feab9d#rd" target="_blank" rel="external">36个代码块,带你读懂异常处理的优雅演进</a></li>
<li><a href="https://zhuanlan.zhihu.com/p/25178630" target="_blank" rel="external">深入 Promise(一)——Promise 实现详解</a></li>
</ol>
</div>
<footer class="article-footer clearfix">
<div class="article-tags">
<span></span> <a href="/tags/JavaScript/">JavaScript</a><a href="/tags/Promise/">Promise</a>
</div>
<div class="article-share" id="share">
<div data-url="http://fullstack.blog/2017/02/26/异步与回调的设计哲学/" data-title="异步与回调的设计哲学 | 全栈养成计划" data-tsina="null" class="share clearfix">
</div>
</div>
</footer>
</article>
<nav class="article-nav clearfix">
<div class="prev" >
<a href="/2017/03/09/业务爬坑与总结——开屏广告热启动实现方案/" title="业务爬坑与总结——开屏广告热启动实现方案">
<strong>PREVIOUS:</strong><br/>
<span>
业务爬坑与总结——开屏广告热启动实现方案</span>
</a>
</div>
<div class="next">
<a href="/2017/02/17/复盘微博短链接盗窃门/" title="复盘微博短链接盗窃门">
<strong>NEXT:</strong><br/>
<span>复盘微博短链接盗窃门
</span>
</a>
</div>
</nav>
</div>
<div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>
<div id="toc" class="toc-aside">
<strong class="toc-title">Contents</strong>
<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#异步编程入门"><span class="toc-number">1.</span> <span class="toc-text">异步编程入门</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#CPS"><span class="toc-number">1.1.</span> <span class="toc-text">CPS</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#没什么卵用的-CPS"><span class="toc-number">1.2.</span> <span class="toc-text">没什么卵用的 CPS</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Promise"><span class="toc-number">2.</span> <span class="toc-text">Promise</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#CPS-的本质"><span class="toc-number">2.1.</span> <span class="toc-text">CPS 的本质</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-的本质"><span class="toc-number">2.2.</span> <span class="toc-text">Promise 的本质</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-的基本概念"><span class="toc-number">2.3.</span> <span class="toc-text">Promise 的基本概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-小细节"><span class="toc-number">2.4.</span> <span class="toc-text">Promise 小细节</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#生成器-Generator"><span class="toc-number">3.</span> <span class="toc-text">生成器 Generator</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Generator-in-JavaScript"><span class="toc-number">3.1.</span> <span class="toc-text">Generator in JavaScript</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Generator-的实现"><span class="toc-number">3.2.</span> <span class="toc-text">Generator 的实现</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Async-Await"><span class="toc-number">4.</span> <span class="toc-text">Async/Await</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#回调改为线性"><span class="toc-number">4.1.</span> <span class="toc-text">回调改为线性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#“同步”-写法的设计哲学"><span class="toc-number">4.2.</span> <span class="toc-text">“同步” 写法的设计哲学</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#参考资料"><span class="toc-number">5.</span> <span class="toc-text">参考资料</span></a></li></ol>
</div>
<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">
<div class="widget-wrap">
<h3 class="widget-title">扫码关注我的公众号,从大前端的角度聊聊 iOS,安卓和前端开发</h3>
<div class="widget">
<img src="/img/weixin_qr.jpg" style="width: 100%">
</div>
</div>
<div class="tagslist">
<p class="asidetitle">标签</p>
<ul class="clearfix">
<li><a href="/tags/Android/" title="Android">Android<sup>3</sup></a></li>
<li><a href="/tags/HTML/" title="HTML">HTML<sup>1</sup></a></li>
<li><a href="/tags/Java/" title="Java">Java<sup>1</sup></a></li>
<li><a href="/tags/JavaScript/" title="JavaScript">JavaScript<sup>2</sup></a></li>
<li><a href="/tags/Promise/" title="Promise">Promise<sup>1</sup></a></li>
<li><a href="/tags/python/" title="python">python<sup>1</sup></a></li>
<li><a href="/tags/zen/" title="zen">zen<sup>1</sup></a></li>
<li><a href="/tags/前端/" title="前端">前端<sup>3</sup></a></li>
<li><a href="/tags/总结分享/" title="总结分享">总结分享<sup>1</sup></a></li>
<li><a href="/tags/编程语言/" title="编程语言">编程语言<sup>2</sup></a></li>
<li><a href="/tags/网络/" title="网络">网络<sup>1</sup></a></li>
<li><a href="/tags/计算机基础知识/" title="计算机基础知识">计算机基础知识<sup>1</sup></a></li>
</ul>
</div>
<div class="rsspart">
<a href="atom.xml" target="_blank" title="rss">RSS</a>
</div>
<div class="linkslist">
<p class="asidetitle">友情链接</p>
<ul>
<li><a href="https://bestswifter.com" target="_blank" title="Bestswifter">Bestswifter 的博客</a></li>
</ul>
</div>
<div class="linkslist">
<p class="asidetitle">微博关注</p>
<ul>
<li><iframe width="100%" height="550" class="share_self" frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=550&fansRow=1&ptype=1&speed=0&skin=1&isTitle=1&noborder=1&isWeibo=1&isFans=1&uid=5678670890&verifier=53247bfc&dpc=1"></iframe></li>
</ul>
</div>
</aside>
</div>
</div>
<footer><div id="footer" >
<div class="line">
<span></span>
<div class="author"></div>
</div>
<div class="social-font clearfix">
</div>
<p class="copyright">Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/A-limon/pacman" target="_blank" title="Pacman">Pacman</a> © 2018
<a href="http://fullstack.blog" target="_blank" title="Fullstack">Fullstack</a>
</p>
</div>
</footer>
<script src="/js/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.navbar').click(function(){
$('header nav').toggleClass('shownav');
});
var myWidth = 0;
function getSize(){
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth;
} else if( document.documentElement && document.documentElement.clientWidth) {
myWidth = document.documentElement.clientWidth;
};
};
var m = $('#main'),
a = $('#asidepart'),
c = $('.closeaside'),
o = $('.openaside');
$(window).resize(function(){
getSize();
if (myWidth >= 1024) {
$('header nav').removeClass('shownav');
}else
{
m.removeClass('moveMain');
a.css('display', 'block').removeClass('fadeOut');
o.css('display', 'none');
$('#toc.toc-aside').css('display', 'none');
}
});
c.click(function(){
a.addClass('fadeOut').css('display', 'none');
o.css('display', 'block').addClass('fadeIn');
m.addClass('moveMain');
});
o.click(function(){
o.css('display', 'none').removeClass('beforeFadeIn');
a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');
m.removeClass('moveMain');
});
$(window).scroll(function(){
o.css("top",Math.max(80,260-$(this).scrollTop()));
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
var ai = $('.article-content>iframe'),
ae = $('.article-content>embed'),
t = $('#toc'),
h = $('article h2')
ah = $('article h2'),
ta = $('#toc.toc-aside'),
o = $('.openaside'),
c = $('.closeaside');
if(ai.length>0){
ai.wrap('<div class="video-container" />');
};
if(ae.length>0){
ae.wrap('<div class="video-container" />');
};
if(ah.length==0){
t.css('display','none');
}else{
c.click(function(){
ta.css('display', 'block').addClass('fadeIn');
});
o.click(function(){
ta.css('display', 'none');
});
$(window).scroll(function(){
ta.css("top",Math.max(140,320-$(this).scrollTop()));
});
};
});
</script>
<script type="text/javascript">
$(document).ready(function(){
var $this = $('.share'),
url = $this.attr('data-url'),
encodedUrl = encodeURIComponent(url),
title = $this.attr('data-title'),
tsina = $this.attr('data-tsina');
var html = [
'<a href="#" class="overlay" id="qrcode"></a>',
'<div class="qrcode clearfix"><span>扫描二维码分享到微信朋友圈</span><a class="qrclose" href="#share"></a><strong>Loading...Please wait</strong><img id="qrcode-pic" data-src="http://s.jiathis.com/qrcode.php?url=' + encodedUrl + '"/></div>',
'<a href="#textlogo" class="article-back-to-top" title="Top"></a>',
'<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
'<a href="#qrcode" class="article-share-qrcode" title="QRcode"></a>',
'<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
'<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="Weibo"></a>',
'<span title="Share to"></span>'
].join('');
$this.append(html);
$('.article-share-qrcode').click(function(){
var imgSrc = $('#qrcode-pic').attr('data-src');
$('#qrcode-pic').attr('src', imgSrc);
$('#qrcode-pic').load(function(){
$('.qrcode strong').text(' ');
});
});
});
</script>
</body>
</html>
<a href="https://github.com/bestswifter"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://camo.githubusercontent.com/567c3a48d796e2fc06ea80409cc9dd82bf714434/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f6c6566745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_left_darkblue_121621.png"></a>
|
package Extras;
import io.cucumber.java.en.*;
import org.junit.Assert;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Extras {
String e = System.setProperty("webdriver.chrome.driver", "src/test/resources/browserBinaries/chromedriver.exe");
WebDriver driver;
WebDriverWait wait;
/* BACKGROUND */
@Given("me encuentro en el Main de RESTool App")
public void validateMainView() {
driver = new ChromeDriver();
wait = new WebDriverWait(driver, 10);
driver.get("https://dsternlicht.github.io/RESTool/#/characters?search=");
driver.manage().window().maximize();
String title = driver.findElement(By.xpath("//h2")).getText();
Assert.assertEquals(title, "Cast & Characters");
}
@When("doy click en la pestaña Extras")
public void clickOnLinkEmployees(){
driver.findElement(By.xpath("//a[@href='#/extras']")).click();
}
@Then("Compruebo que me encuentro en el modulo de Extras")
public void ValidateRedirectionToModuleEmployees(){
String title = driver.findElement(By.xpath("//h2[contains(text(),'Extras')]")).getText();
Assert.assertEquals(title, "Extras");
}
/* ADD ITEM */
@When("doy click en el botón Add Item en Extras")
public void clickOnAddItem(){
driver.findElement(By.xpath("//button[@class='button add-item green']")).click();
}
@And("Ingreso {string} en el campo name en Extras y doy Enter")
public void insertName(String arg){
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.popup-content section form")));
String value = driver.findElement(By.cssSelector("div.popup section form div.form-row:first-child input")).getAttribute("Value");
if (value != "") {
driver.findElement(By.cssSelector("div.popup section form div.form-row:first-child input")).clear();
driver.findElement(By.cssSelector("div.popup-content section form div input[value='"+value+"']")).sendKeys(arg, Keys.ENTER);
}else{
driver.findElement(By.cssSelector("div.popup-content section form div:first-child input")).sendKeys(arg, Keys.ENTER);
}
}
@And("compruebo la alerta con el texto Great Success! en Extras")
public void CheckTheSuccessAlert(){
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(), 'Great Success!')]")));
}
@And("Visualizo {string} en la tabla de Extras")
public void checkExtrasAddedInTable(String arg){
String value = driver.findElement(By.xpath("//label[contains(text(), 'Search')]//following::input")).getAttribute("Value");
if(value != ""){
driver.findElement(By.xpath("//label[contains(text(), 'Search')]//following::input[@value='"+value+"']")).clear();
driver.findElement(By.xpath("//label[contains(text(), 'Search')]//following::input[@value='"+value+"']")).sendKeys(arg, Keys.ENTER);
}else{
driver.findElement(By.xpath("//label[contains(text(), 'Search')]//following::input[@value='']")).sendKeys(arg, Keys.ENTER);
}
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//td//following::span[contains(text(), '"+arg+"')]")));
}
@And("Cierro el navegador en Extras")
public void closeBrowser(){
driver.quit();
}
/* UPDATE ITEM */
@When("busco mi {string} y doy click en el botón de Update Item en Extras")
public void clickOnUpdateItem(String arg){
driver.findElement(By.xpath("//label[contains(text(), 'Search')]//following::input[@value='']")).sendKeys(arg, Keys.ENTER);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(@class, 'actions-wrapper')]//button[@title='Edit']")));
driver.findElement(By.xpath("//div[contains(@class, 'actions-wrapper')]//button[@title='Edit']")).click();
}
/* DELETE ITEM */
@When("busco mi {string} y doy click en el botón de Delete Item")
public void clickOnDeleteItem(String arg){
driver.findElement(By.xpath("//label[contains(text(), 'Search')]//following::input[@value='']")).sendKeys(arg, Keys.ENTER);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[@class='pure-table']")));
driver.findElement(By.xpath("//div[contains(@class, 'actions-wrapper')]//button[@title='Delete']")).click();
}
@And("doy click en el botón Aceptar")
public void clickOnAcceptAlert(){
Alert alert = driver.switchTo().alert();
String alertContent = alert.getText();
Assert.assertEquals("Are you sure you want to delete this item?", alertContent);
alert.accept();
}
@And("Compruebo la inexistencia de {string} en la tabla de Extras")
public void clickOnAcceptAlert(String arg){
driver.navigate().back();
driver.navigate().refresh();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//section[@class='query-params-form']")));
driver.findElement(By.xpath("//label[contains(text(), 'Search')]//following::input[@value='']")).sendKeys(arg, Keys.ENTER);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//table[@class='pure-table']//following::td//following::span[contains(text(), '"+arg+"')]")));
}
}
|
import { useState } from "react";
import Header from "./components/Header.jsx";
import UserInput from "./components/UserInput.jsx";
import Results from "./components/Results.jsx";
export default function App() {
const [userInput, setUserInput] = useState({
initialInvestment: 10000,
annualInvestment: 1200,
expectedReturn: 6,
duration: 10,
});
function handleChange(inputIdentifier, newValue) {
setUserInput((prevUserInput) => {
return {
...prevUserInput,
[inputIdentifier]: +newValue,
};
});
}
const inputIsValid = userInput.duration > 0;
return (
<>
<Header />
<UserInput userInput={userInput} onChange={handleChange} />
{inputIsValid ? (
<Results input={userInput} />
) : (
<p className="center">Please enter a duration greater than zero.</p>
)}
</>
);
}
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lottery/app/extension/num_extension.dart';
import 'package:lottery/app/extension/string_extension.dart';
import 'package:lottery/app/extension/widget_extension.dart';
import 'package:lottery/app/pages/discover/view/comm/discover_app_bar.dart';
import 'package:lottery/app/utils/currency_util.dart';
import '../../../../config/app_config.dart';
class ConfirmBettingModel {
String? name;
String? subTitle;
String? money;
double? odd;
String? userBalance;
ConfirmBettingModel(
{this.name, this.subTitle, this.money, this.odd, this.userBalance});
ConfirmBettingModel.fromJson(Map<String, dynamic> json) {
name = json['name'];
subTitle = json['subTitle'];
money = json['money'];
odd = json['odd'];
userBalance = json['userBalance'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['name'] = name;
data['subTitle'] = subTitle;
data['money'] = money;
data['odd'] = odd;
data['userBalance'] = userBalance;
return data;
}
ConfirmBettingModel copyWith(
{String? name,
String? subTitle,
String? money,
double? odd,
String? userBalance}) {
return ConfirmBettingModel(
name: name ?? this.name,
subTitle: subTitle ?? this.subTitle,
money: money ?? this.money,
odd: odd ?? this.odd,
userBalance: userBalance ?? this.userBalance);
}
}
class ConfirmBetting extends StatefulWidget {
final ConfirmBettingModel data;
const ConfirmBetting({Key? key, required this.data}) : super(key: key);
@override
// ignore: library_private_types_in_public_api
_ConfirmBettingState createState() => _ConfirmBettingState();
}
class _ConfirmBettingState extends State<ConfirmBetting>
with TickerProviderStateMixin {
late final TextEditingController textEditorcontroller =
TextEditingController(text: widget.data.money)..addListener(_listener);
late double winMoney = (double.tryParse(widget.data.money ?? '1') ?? 1) *
((widget.data.odd ?? 1) - 1);
late String money = widget.data.money ?? "1";
bool isChecked = false;
_listener() {
setState(() {
money = textEditorcontroller.text;
winMoney = (double.tryParse(textEditorcontroller.text) ?? 1) *
((widget.data.odd ?? 1) - 1);
});
}
@override
void didUpdateWidget(covariant ConfirmBetting oldWidget) {
// TODO: implement didUpdateWidget
// if (oldWidget.data.money != )
super.didUpdateWidget(oldWidget);
}
@override
void dispose() {
// TODO: implement dispose
textEditorcontroller.removeListener(_listener);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: DiscoverAppBar(
title: "投注确认",
onPress: () {
Navigator.pop(context);
},
actions: [
const Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(right: 8.0),
child: Text("清空", style: TextStyle(color: Colors.black)),
),
],
).onTap(() {
Get.back();
})
],
),
body: DefaultTextStyle(
style: const TextStyle(
// color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w500),
child: DefaultTextStyle(
style: TextStyle(color: "#7c88a8".hexToColor()),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: ListView.builder(
itemCount: 1,
itemBuilder: (context, index) => Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
children: [
Text("${widget.data.name}"),
Text("${widget.data.subTitle}")
],
)),
Expanded(
flex: 2,
child: Row(
crossAxisAlignment:
CrossAxisAlignment.center,
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.only(
left: 15.0, top: 15),
child: Container(
// linear-gradient(180deg,#fff,#f4f4fa)
decoration: BoxDecoration(
borderRadius: (6.0).radius,
border: Border.all(
width: 1,
color:
"#d9ddf0".hexToColor(),
),
color:
"#fbfcfd".hexToColor()),
child: TextField(
controller:
textEditorcontroller,
decoration:
const InputDecoration(
isDense: true,
border: InputBorder.none,
contentPadding:
EdgeInsets.symmetric(
horizontal: 5,
vertical: 15),
// errorText: "",
),
)),
)),
Padding(
padding: const EdgeInsets.only(
left: 8.0, top: 15),
child: Text(
"可赢${winMoney.formattedWithFixedDecimals(2)}"),
)
],
)),
Expanded(
child: Container(
padding: const EdgeInsets.only(top: 15),
alignment: Alignment.centerRight,
child: const Icon(
Icons.delete,
color: Colors.grey,
),
).onTap(() {
Get.back();
}))
],
)),
),
Container(
height: .5,
color: "#ebf0fb".hexToColor(),
),
// 显示下单内容
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
RichText(
text: TextSpan(
text: "1",
style: TextStyle(color: "#7c88a8".hexToColor()),
children: [
const TextSpan(text: "单,"),
TextSpan(
text: "$money",
style:
TextStyle(color: "#ff8c05".hexToColor())),
TextSpan(text: AppConfig.betAmountUnit()),
])),
Row(
children: [
Text('停用投注确认框(可于设置中再开启)'),
Checkbox(
value: isChecked,
onChanged: (value) {
setState(() {
isChecked = value ?? false;
});
})
],
)
],
),
),
Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: RichText(
textAlign: TextAlign.left,
text: TextSpan(
style: TextStyle(color: "#7c88a8".hexToColor()),
text: "当期剩余盈利额度:",
children: [
TextSpan(
text: "${widget.data.userBalance}",
style: TextStyle(
color: "#ff8c05".hexToColor())),
TextSpan(text: AppConfig.betAmountUnit())
]))),
// 底部显示
ClipRRect(
borderRadius: (10.0).radius,
child: Container(
width: MediaQuery.of(context).size.width,
height: 50,
alignment: Alignment.center,
decoration: BoxDecoration(
image: DecorationImage(
image:
AssetImage("assets/images/bet/btn_sel_bg.png")
.useNetWork(),
fit: BoxFit.fitWidth)),
margin: EdgeInsets.fromLTRB(10, 10, 10,
MediaQuery.of(context).padding.bottom + 10),
child: const Text("确认投注",
style: TextStyle(color: Colors.white)),
),
)
],
),
)));
}
}
|
import RipaLocation from '@/components/molecules/RipaLocation.vue'
import { shallowMount, mount } from '@vue/test-utils'
import { defaultStop } from '@/utilities/stop.js'
import Vuetify from 'vuetify'
import { computed } from 'vue'
describe('Ripa Location', () => {
let vuetify
let wrapper
let stop
const mockGeolocation = {
getCurrentPosition: jest.fn().mockReturnValue(200),
watchPosition: jest.fn(),
}
global.navigator.geolocation = mockGeolocation
const schoolsList = JSON.parse('[{"cdsCode":"1","fullName":"High School"}]')
const countyCitiesList = JSON.parse('[{"id":"1","fullName":"CountyCity"}]')
const nonCountyCitiesList = JSON.parse(
'[{"id":"2","fullName":"NonCountyCity"}]',
)
const beatsList = JSON.parse('[{"id":"1","fullName":"Beat 1"}]')
beforeEach(() => {
vuetify = new Vuetify()
stop = defaultStop()
})
afterEach(() => {
wrapper.destroy()
})
const factory = propsData => {
return mount(RipaLocation, {
vuetify,
propsData: {
...propsData,
onOpenFavorites: jest.fn(),
onOpenLastLocation: jest.fn(),
onSaveFavorite: jest.fn(),
onGpsLocation: jest.fn(),
},
provide: {
loadingPiiStep1: computed(() => false),
loadingGps: computed(() => false),
isOnlineAndAuthenticated() {
return true
},
beats: computed(() => beatsList),
countyCities: computed(() => countyCitiesList),
nonCountyCities: computed(() => nonCountyCitiesList),
schools: computed(() => schoolsList),
displayBeatInput() {
return true
},
lastLocation() {
return {}
},
validLastLocation: computed(() => true),
favoriteLocations: computed(() => []),
statutes: computed(() => [{ id: 'test' }]),
online: computed(() => true),
},
})
}
const schoolTestCases = [
{
school: null,
expected: ['A school is required'],
},
{
school: '1',
expected: [true],
},
]
it('should match snapshot', () => {
wrapper = mount(RipaLocation, {
vuetify,
propsData: {
value: stop,
onOpenFavorites: jest.fn(),
onOpenLastLocation: jest.fn(),
onSaveFavorite: jest.fn(),
onGpsLocation: jest.fn(),
},
provide: {
loadingPiiStep1: computed(() => false),
loadingGps: computed(() => false),
isOnlineAndAuthenticated() {
return true
},
beats: computed(() => beatsList),
countyCities: computed(() => countyCitiesList),
nonCountyCities: computed(() => nonCountyCitiesList),
schools: computed(() => schoolsList),
displayBeatInput() {
return true
},
lastLocation() {
return {}
},
validLastLocation: computed(() => true),
favoriteLocations: computed(() => []),
statutes: computed(() => [{ id: 'test' }]),
online: computed(() => true),
},
})
expect(wrapper.html()).toMatchSnapshot()
})
schoolTestCases.forEach(test => {
it(`should validate school: ${test.school} as: ${test.expected}`, () => {
stop.location.isSchool = true
stop.location.school = test.school
wrapper = factory({
value: stop,
schools: schoolsList,
})
expect(wrapper.vm.schoolRules).toEqual(test.expected)
})
})
it('should validate block number', () => {
wrapper = factory({ value: stop })
expect(wrapper.vm.blockNumberRules).toEqual([
'A block number is required',
'Block number plus street name must be between 5 and 250 characters',
])
stop.location.blockNumber = '1000'
stop.location.streetName = 'Test'
expect(wrapper.vm.blockNumberRules).toStrictEqual([true, true])
})
it('should validate V2 block number', () => {
wrapper = factory({ value: stop })
expect(wrapper.vm.blockNumberRulesV2).toEqual([
'A block number is required',
'Block number must be between 1 and 8 characters',
])
stop.location.blockNumber = '12'
stop.location.streetName = 'V2 Test'
expect(wrapper.vm.blockNumberRulesV2).toStrictEqual([true, true])
})
it('should validate street name', () => {
wrapper = factory({ value: stop })
expect(wrapper.vm.streetNameRules).toEqual([
'A street name is required',
'Block number plus street name must be between 5 and 250 characters',
])
stop.location.streetName = 'Anystreet St'
expect(wrapper.vm.streetNameRules).toStrictEqual([true, true])
})
it('should validate V2 street name', () => {
wrapper = factory({ value: stop })
expect(wrapper.vm.streetNameRulesV2).toEqual([
'A street name is required',
'Street name must be between 1 and 50 characters',
])
stop.location.streetName = 'Anystreet St'
expect(wrapper.vm.streetNameRulesV2).toStrictEqual([true, true])
})
it('should validate intersection', () => {
stop.stopVersion = 1
wrapper = factory({ value: stop })
expect(wrapper.vm.intersectionRules).toEqual([
'An intersection is required',
'Intersection must be between 5 and 250 characters',
])
stop.location.intersection = ''
expect(wrapper.vm.intersectionRules).toEqual([
'An intersection is required',
'Intersection must be between 5 and 250 characters',
])
stop.location.intersection = '5th and Main'
expect(wrapper.vm.streetNameRules).toStrictEqual([true, true])
stop.location.intersection = null
stop.location.blockNumber = '1000'
stop.location.streetName = 'Anystreet St'
expect(wrapper.vm.streetNameRules).toStrictEqual([true, true])
stop.location.intersection = '5th and Main'
expect(wrapper.vm.streetNameRules).toStrictEqual([true, true])
})
it('should validate highway', () => {
wrapper = factory({ value: stop })
stop.location.toggleLocationOptions = true
expect(wrapper.vm.highwayRules).toEqual([
'A highway and closest exit is required',
'Highway and closest exit must be between 5 and 250 characters',
])
stop.location.highwayExit = 'Exit 1A'
expect(wrapper.vm.highwayRules).toStrictEqual([true, true])
})
it('should validate highway V2', () => {
stop.location.toggleLocationOptions = true
wrapper = factory({ value: stop })
expect(wrapper.vm.highwayRulesV2).toEqual([
'Must fill out both highway and exit in order to use highway and exit',
'Highway must be between 1 and 75 characters',
'Closest exit must be between 1 and 50 characters',
])
const updatedStop = stop
updatedStop.location.highway = 'Valid Highway'
updatedStop.location.exit = ''
wrapper.vm.propsData = { value: updatedStop }
wrapper.vm.handleInput()
expect(wrapper.vm.highwayRulesV2).toEqual([
'Must fill out both highway and exit in order to use highway and exit',
true,
'Closest exit must be between 1 and 50 characters',
])
updatedStop.location.exit = 'Valid Exit'
updatedStop.location.highway = ''
wrapper.vm.propsData = { value: updatedStop }
wrapper.vm.handleInput()
expect(wrapper.vm.highwayRulesV2).toEqual([
'Must fill out both highway and exit in order to use highway and exit',
'Highway must be between 1 and 75 characters',
true,
])
updatedStop.location.exit = 'x'.repeat(51)
updatedStop.location.highway = 'Valid Highway'
wrapper.vm.propsData = { value: updatedStop }
wrapper.vm.handleInput()
expect(wrapper.vm.highwayRulesV2).toEqual([
true,
true,
'Closest exit must be between 1 and 50 characters',
])
updatedStop.location.highway = 'x'.repeat(76)
updatedStop.location.exit = 'Valid Exit'
wrapper.vm.propsData = { value: updatedStop }
wrapper.vm.handleInput()
expect(wrapper.vm.highwayRulesV2).toEqual([
true,
'Highway must be between 1 and 75 characters',
true,
])
updatedStop.location.highway = 'Highway'
updatedStop.location.exit = 'Exit'
wrapper.vm.propsData = { value: updatedStop }
wrapper.vm.handleInput()
expect(wrapper.vm.highwayRulesV2).toStrictEqual([true, true, true])
})
it.skip('should validate exit V2', () => {
wrapper = factory({ value: stop })
stop.location.toggleLocationOptions = true
expect(wrapper.vm.highwayRulesV2).toEqual([
'Must fill out both highway and exit in order to use highway and exit',
'Highway must be between 1 and 75 characters',
'Closest exit must be between 1 and 50 characters',
])
stop.location.exit = 'Exit'
wrapper.vm.model = stop
expect(wrapper.vm.highwayRulesV2).toStrictEqual([true, true])
})
it('should validate landmark', () => {
wrapper = factory({ value: stop })
stop.location.toggleLocationOptions = true
expect(wrapper.vm.landmarkRules).toEqual([
'A road marker, landmark, or other description is required',
'Road marker, landmark or other description must be between 5 and 250 characters',
])
stop.location.landmark = 'Exit 1A'
expect(wrapper.vm.landmarkRules).toStrictEqual([true, true])
})
it('should validate V2 landmark', () => {
stop.location.toggleLocationOptions = true
wrapper = factory({ value: stop })
expect(wrapper.vm.landmarkRulesV2).toEqual([
'A road marker, landmark, or other description is required',
'Road marker, landmark or other description must be between 5 and 150 characters',
])
stop.location.landmark = 'Exit 1A'
expect(wrapper.vm.landmarkRulesV2).toStrictEqual([true, true])
})
it('should validate latitude coordinate for v2 stop', () => {
wrapper = factory({ value: stop })
expect(wrapper.vm.latitudeRules[0]('')).toEqual('Latitude is required')
expect(wrapper.vm.latitudeRules[1]('')).toEqual(
'A valid latitude with a maximum of 3 digits after the decimal is required',
)
expect(wrapper.vm.latitudeRules[0]('-11.230')).toEqual(true)
expect(wrapper.vm.latitudeRules[1]('-11.230')).toEqual(
'A valid latitude with a maximum of 3 digits after the decimal is required',
)
expect(wrapper.vm.latitudeRules[0]('11.2301')).toEqual(true)
expect(wrapper.vm.latitudeRules[1]('11.2301')).toEqual(
'A valid latitude with a maximum of 3 digits after the decimal is required',
)
expect(wrapper.vm.latitudeRules[0]('11.230')).toEqual(true)
expect(wrapper.vm.latitudeRules[1]('11.230')).toEqual(true)
})
it('should validate longitude coordinate for v2 stop', () => {
wrapper = factory({ value: stop })
expect(wrapper.vm.longitudeRules[0]('')).toEqual('Longitude is required')
expect(wrapper.vm.longitudeRules[1]('')).toEqual(
'A valid negative longitude with a maximum of 3 digits after the decimal is required',
)
expect(wrapper.vm.longitudeRules[0]('123.123')).toEqual(true)
expect(wrapper.vm.longitudeRules[1]('123.123')).toEqual(
'A valid negative longitude with a maximum of 3 digits after the decimal is required',
)
expect(wrapper.vm.longitudeRules[0]('-123.1231')).toEqual(true)
expect(wrapper.vm.longitudeRules[1]('-123.1231')).toEqual(
'A valid negative longitude with a maximum of 3 digits after the decimal is required',
)
expect(wrapper.vm.longitudeRules[0]('-123.123')).toEqual(true)
expect(wrapper.vm.longitudeRules[1]('-123.123')).toEqual(true)
})
it('should return the geolocation score', () => {
wrapper = factory({ value: stop })
const getCurrPos = jest.spyOn(
global.navigator.geolocation,
'getCurrentPosition',
)
wrapper.vm.isGeolocationAvailable()
expect(getCurrPos).toHaveBeenCalled()
})
it.todo('should handle input out of county')
it.todo('should handle out of county toggle')
})
|
import express from 'express'
import asyncHandler from 'express-async-handler'
import { User, UserDocument } from '../models/user.model'
const router = express.Router()
router.route('/').post(
asyncHandler(async (req: express.Request, res: express.Response) => {
const { username, email, password } = req.body
const userExists = await User.findOne({ email })
if (userExists) {
res.status(400).json('メールアドレスは既に登録しました')
}
const user = await User.create({
username,
email,
password,
} as UserDocument)
if (user) {
//注册成功后设置session
req.session.userInfo = user
res.status(201).json({
id: user.id,
name: user.username,
email: user.email,
})
} else {
res.status(400).json('無効なユーザーデータ!')
}
})
)
router.route('/update').put(
asyncHandler(async (req: express.Request, res: express.Response) => {
const { username, email, password } = req.body
const user = await User.findOne({ email })
console.log(`user: ${user}`)
const data = {
password: req.body.newPassword,
username: username,
email: email,
}
//登录成功后设置session
if (user && (await user.matchPW(password))) {
req.session.userInfo = data
User.findOneAndUpdate({ email }, { $set: data }, {}, (err, data) => {
if (err) {
console.log('error: ' + err)
} else if (!data) {
console.log('データが見つかりません')
console.log(data)
} else if (data) {
console.log('アップデートしました!')
console.log(data)
}
})
res.status(201).json(data)
} else {
res.status(400).json('パスワードが間違いました!')
}
})
)
router.route('/userInfo').get((req: express.Request, res: express.Response) => {
req.session.userInfo
? res.status(200).json({
message: '',
data: req.session.userInfo,
code: 0,
})
: res.status(200).json({
message: 'もう一度サインインしてください',
data: req.session.userInfo,
code: 1,
})
})
router.route('/login').post(
asyncHandler(async (req: express.Request, res: express.Response) => {
const { email, password } = req.body
const user = await User.findOne({ email })
const data = {
id: user?._id,
username: user?.username,
email: user?.email,
}
//登录成功后设置session
if (user && (await user.matchPW(password))) {
req.session.userInfo = data
res.status(201).json(data)
} else {
res.status(400).json('メールアドレスまたはパスワードが間違いました!')
}
})
)
router.route('/logout').get((req: express.Request, res: express.Response) => {
req.session.destroy((err) => {
console.log(err)
})
res.status(200).json({ logout: '1' })
})
export default router
|
import { buildQueries } from '@testing-library/react'
import PropTypes from 'prop-types'
import React, { useState } from 'react'
export default function Home() {
const [myStyle,setmyStyle]=useState({
color : 'white',
backgroundColor : 'black',
border :'1px'
})
const [textButton,setTextButton]=useState('Enable White Mode')
const toggleStyle=()=>{
if(myStyle.color==='white'){
setmyStyle({
color : 'black',
backgroundColor : 'white',
border :'1px'
})
setTextButton('Enable Dark Mode');
}
else{
setmyStyle({
color : 'white',
backgroundColor : 'black',
border : '1px'
})
//alert("hii");
setTextButton('Enable White Mode');
}
}
return (
<>
<div className='container' style={myStyle}><div className="accordion" id="accordionExample">
<div className="accordion-item" style={myStyle}>
<h2 className="accordion-header" id="headingOne" >
<button className="accordion-button" style={myStyle} type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Accordion Item #1
</button>
</h2>
<div id="collapseOne" className="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
<div className="accordion-body">
<strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classNamees that we use to style each element. These classNamees control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
</div>
</div>
</div>
<div className="accordion-item" style={myStyle}>
<h2 className="accordion-header" id="headingTwo">
<button className="accordion-button collapsed" style={myStyle} type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
Accordion Item #2
</button>
</h2>
<div id="collapseTwo" className="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
<div className="accordion-body">
<strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classNamees that we use to style each element. These classNamees control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
</div>
</div>
</div>
<div className="accordion-item" style={myStyle}>
<h2 className="accordion-header" id="headingThree">
<button className="accordion-button collapsed" style={myStyle} type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
Accordion Item #3
</button>
</h2>
<div id="collapseThree" className="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionExample">
<div className="accordion-body">
<strong>This is the third item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classNamees that we use to style each element. These classNamees control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
</div>
</div>
</div>
</div>
</div>
<div className='container'>
<button type='button' className='btn btn-primary' onClick={toggleStyle}>{textButton}</button>
</div>
</>
)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.