text
stringlengths 184
4.48M
|
---|
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:first_test/constants/routes.dart';
import 'package:first_test/pop_ups.dart';
import 'package:first_test/services/auth/auth_exceptions.dart';
import 'package:first_test/services/firebase_auth_provider.dart';
import 'package:flutter/material.dart';
import "package:font_awesome_flutter/font_awesome_flutter.dart";
import 'verify_email_view.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
late final _controllerMail;
late final _controllerPassword;
@override
void initState() {
_controllerMail = TextEditingController();
_controllerPassword = TextEditingController();
super.initState();
}
@override
void dispose() {
_controllerMail.dispose();
_controllerPassword.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromRGBO(29, 161, 242, 1),
appBar: AppBar(
title: const Text("Twitter"),
centerTitle: true,
backgroundColor: const Color.fromRGBO(29, 161, 242, 1),
foregroundColor: const Color.fromARGB(255, 255, 255, 255),
),
body: ListView(scrollDirection: Axis.vertical, children: [
Center(
child: Column(
children: [
const SizedBox(height: 50),
const Icon(
FontAwesomeIcons.twitter,
color: Colors.white,
size: 100,
),
const SizedBox(height: 20),
const Text(
"Login",
style: TextStyle(
color: Colors.white,
fontSize: 25,
fontWeight: FontWeight.bold),
),
const SizedBox(height: 40),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: TextField(
controller: _controllerMail,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
hintText: "Enter your email",
),
autocorrect: false,
enableSuggestions: false,
keyboardType: TextInputType.emailAddress,
),
),
const SizedBox(height: 20),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: TextField(
controller: _controllerPassword,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
hintText: "Enter your password",
),
autocorrect: false,
enableSuggestions: false,
obscureText: true,
),
),
Padding(
padding: const EdgeInsets.only(
left: 200,
),
child: TextButton(
onPressed: () {},
child: Text(
"Forgot your password?",
style: TextStyle(color: Colors.grey.shade300),
),
),
),
const SizedBox(height: 30),
GestureDetector(
onTap: () async {
String email = _controllerMail.text;
String password = _controllerPassword.text;
try {
final provider = FirebaseAuthProvider();
await provider.logIn(email: email, password: password);
final user = provider.currentUser;
if (!user!.isEmailVerified) {
Navigator.of(context).pushNamedAndRemoveUntil(
Routes.getVerifyEmailRoute, (route) => true);
} else {
Navigator.of(context).pushNamedAndRemoveUntil(
Routes.getLoggedInRoute, (route) => false);
}
} on UserNotLoggedInException catch (e) {
await loginScreenErrorPopUp(
context: context, error: e.message, sepByDash: false);
} on LogInException catch (e) {
await loginScreenErrorPopUp(
context: context, error: e.message, sepByDash: true);
} on GenericException catch (e) {
await loginScreenErrorPopUp(
context: context, error: e.message, sepByDash: false);
}
},
child: Container(
width: 170,
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: const Color.fromRGBO(124, 202, 235, 1),
),
child: const Center(
child: Text("Login",
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold)),
),
),
),
TextButton(
onPressed: () {
Navigator.of(context).pushNamedAndRemoveUntil(
Routes.getRegisterRoute, (route) => false);
},
style: ButtonStyle(
foregroundColor:
MaterialStatePropertyAll(Colors.grey.shade300)),
child: const Text("Don't have account yet?"))
],
),
),
]),
);
}
}
|
package control
import (
"fmt"
)
type Student struct {
FirstName string
LastName string
}
type IntSlice []int
type Speaker interface {
Speak() string
run() string
}
type Dog struct {
Name string
}
type Man struct {
Name string
}
func (d Dog) Speak() string {
return "Woof!"
}
func (d Dog) run() string {
return "90km/h"
}
func (p Man) Speak() string {
return "Hello!"
}
func (p Man) run() string {
return "50km/h"
}
func MakeSound(s Speaker) {
fmt.Println(s.Speak())
}
func (s IntSlice) Sum() int {
total := 0
for _, v := range s {
total += v
}
return total
}
func (s IntSlice) Average() float64 {
return float64(s.Sum()) / float64(len(s))
}
func (s Student) FullName() string {
return s.FirstName + " " + s.LastName
}
func Function(name string) string {
fmt.Printf("------- %s -------\n", name)
return "Hello, " + name
}
|
namespace youtube_dl_gui_updater;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Windows.Forms;
using murrty.controls;
internal partial class frmUpdater : Form {
private const int MaxRetries = 5;
private const int RetryDelay = 1_000;
private const string ApplicationDownloadUrl = "https://github.com/murrty/{0}/releases/download/{1}/{0}.exe";
private UpdateData UpdateData;
private Process ProgramProcess;
private readonly ApplicationHandles ApplicationData;
private readonly bool DownloadLatest = false;
//private bool Received = false;
private frmUpdater() {
InitializeComponent();
LoadLanguage();
ManagedHttpClient.UpdateSyncContext(SynchronizationContext.Current);
lbUpdaterVersion.Text = Program.CurrentVersion.ToString();
pbDownloadProgress.Style = ProgressBarStyle.Marquee;
}
public frmUpdater(ApplicationHandles? ApplicationData) : this() {
if (ApplicationData is null || !ApplicationData.HasValue) {
DownloadLatest = true;
pbDownloadProgress.Text = "getting latest version...";
}
else {
this.ApplicationData = ApplicationData.Value;
ProgramProcess = Process.GetProcessById(this.ApplicationData.ProcessID);
pbDownloadProgress.Text = "waiting for update data...";
}
}
public frmUpdater(UpdateData? UpdateData) : this() {
if (UpdateData is null || !UpdateData.HasValue) {
DownloadLatest = true;
pbDownloadProgress.Text = "getting latest version...";
}
else this.UpdateData = UpdateData.Value;
}
protected override void WndProc(ref Message m) {
switch (m.Msg) {
case CopyData.WM_COPYDATA: {
UpdateData = CopyData.GetParam<UpdateData>(m.LParam);
UpdateData.UpdateHash = UpdateData.UpdateHash.ToLowerInvariant();
if (!UpdateData.FileName.ToLowerInvariant().EndsWith(".exe"))
UpdateData.FileName += ".exe";
CopyData.SendMessage(ApplicationData.MessageHandle, CopyData.WM_UPDATERREADY, 0, 0);
//Received = true;
m.Result = IntPtr.Zero;
} break;
default: {
base.WndProc(ref m);
} break;
}
}
private async void frmUpdater_Shown(object sender, EventArgs e) {
await RunUpdate();
}
private void LoadLanguage() {
this.Text = Language.frmUpdater;
lbUpdaterHeader.Text = Language.lbUpdaterHeader;
lbUpdaterDetails.Text = Language.lbUpdaterDetails;
pbDownloadProgress.Text = Language.pbDownloadProgressPreparing;
}
private async Task RunUpdate() {
// Check if the latest version needs to be downloaded.
if (DownloadLatest)
await GetVersionFromGithub();
// Wait for the main application to exit.
if (ProgramProcess is not null)
await WaitForApplication();
// This will be the backup location for the current version.
string BackupLocation = UpdateData.FileName + ".old";
// The temp path of the file.
string UpdateDestination = $"{Environment.CurrentDirectory}\\update.part";
// The URL that will be downloaded using the client
string FileUrl = string.Format(ApplicationDownloadUrl, Language.ApplicationName, UpdateData.NewVersion.ToString());
// Whethre the old and new version have been moved.
bool MovedOldVersion = false, MovedNewVersion = false;
try {
// Delete the old backup, if it exists, since it's clearly unused.
if (File.Exists(BackupLocation))
File.Delete(BackupLocation);
// Add the events.
Program.DownloadClient.ProgressChanged += DownloadProgressChanged;
Program.DownloadClient.DownloadComplete += DownloadCompleted;
// Download the update.
await GetUpdate(FileUrl, UpdateDestination);
// Check the file size.
if (new FileInfo(UpdateDestination).Length <= 512) {
File.Delete(UpdateDestination);
tmrForm.Stop();
this.Text = this.Text.Trim('.');
pbDownloadProgress.Style = ProgressBarStyle.Blocks;
pbDownloadProgress.ProgressState = ProgressState.Error;
pbDownloadProgress.Text = Language.pbDownloadProgressDownloadTooSmall;
return;
}
if (UpdateData.UpdateHash is not null) {
// Verify the file hash.
pbDownloadProgress.Text = "calculating new update hash...";
await VerifyHash(FileUrl, UpdateDestination);
}
else {
pbDownloadProgress.Invoke(() => pbDownloadProgress.Text = Language.pbDownloadProgressSkippingHashCalculating);
}
// Move the old file to the backup path.
if (File.Exists(UpdateData.FileName)) {
File.Move(UpdateData.FileName, BackupLocation);
MovedOldVersion = true;
}
// Move the new update to the last location.
File.Move(UpdateDestination, UpdateData.FileName);
MovedNewVersion = true;
// Finally, run it.
pbDownloadProgress.Value = pbDownloadProgress.Maximum;
pbDownloadProgress.Style = ProgressBarStyle.Blocks;
pbDownloadProgress.Text = Language.pbDownloadProgressDownloadFinishedLaunching;
Process.Start(UpdateData.FileName);
// Kill this process.
Program.ExitCode = 0;
this.DialogResult = DialogResult.OK;
this.Dispose();
}
catch {
tmrForm.Stop();
this.Text = this.Text.Trim('.');
pbDownloadProgress.Style = ProgressBarStyle.Blocks;
pbDownloadProgress.ProgressState = ProgressState.Error;
pbDownloadProgress.Text = Language.pbDownloadProgressErrorProcessingDownload;
if (MovedNewVersion) {
File.Delete(UpdateData.FileName);
File.Move(BackupLocation, UpdateData.FileName);
}
else if (MovedOldVersion) {
File.Move(BackupLocation, UpdateData.FileName);
}
else if (File.Exists(UpdateDestination)) {
File.Delete(UpdateDestination);
pbDownloadProgress.Text = Language.pbDownloadProgressErrorDownloading;
}
}
}
private async Task GetVersionFromGithub() {
try {
UpdateData = await Github.GetUpdateData();
Process RunningProcess = Process.GetProcessesByName(Language.ApplicationName).FirstOrDefault();
if (RunningProcess != default)
ProgramProcess = RunningProcess;
}
catch {
pbDownloadProgress.Text = "could not get latest version.";
}
}
private async Task WaitForApplication() {
// We are gonna gather the update data from the running process.
// WM_UPDATEREADY is a non-standard message that tells youtube-dl-gui to send the updater is ready and that it should close.
// The updater is going to wait for the main program to exit, allowing the user to finish any in-progress downloads.
CopyData.SendMessage(ApplicationData.MessageHandle, CopyData.WM_UPDATEDATAREQUEST, this.Handle, 0);
pbDownloadProgress.Text = Language.pbDownloadProgressWaitingForClose;
//while (!Received)
// await Task.Delay(500);
// Wait for the exit.
await Task.Run(ProgramProcess.WaitForExit);
}
private async Task GetUpdate(string FileUrl, string FileDestination) {
// The progress bar has a max of 200. Half of it is used for the download progress.
pbDownloadProgress.Invoke(() => {
pbDownloadProgress.Style = ProgressBarStyle.Blocks;
pbDownloadProgress.Value = 50;
});
// Delete the previous download part file, if it exists.
if (File.Exists(FileDestination))
File.Delete(FileDestination);
// Set the style to blocks so progress can be reported.
pbDownloadProgress.Invoke(() => {
pbDownloadProgress.Style = ProgressBarStyle.Blocks;
pbDownloadProgress.Text = "0%";
});
bool CanRetry;
int Retries = 0;
// Going to attempt 5 times to download the update.
// Additionally allows retrying in case it errors.
do {
try {
// zzz
await Program.DownloadClient.DownloadFileTaskAsync(new Uri(FileUrl, UriKind.Absolute), FileDestination, Program.CancelToken.Token);
CanRetry = false;
}
// zzz
catch (Exception ex) {
while (ex.InnerException is not null)
ex = ex.InnerException;
if (ex is ThreadAbortException or TaskCanceledException or OperationCanceledException)
throw ex;
if (Retries != MaxRetries && (ex is not HttpException hex || (int)hex.StatusCode > 499)) {
await Task.Delay(RetryDelay);
Retries++;
CanRetry = true;
continue;
}
switch ((DialogResult)this.Invoke(() => Log.ReportException(ex, true, true, this))) {
case DialogResult.Abort: throw new OperationCanceledException("Abort requested");
case DialogResult.Retry: {
CanRetry = true;
} break;
default: throw;
}
}
} while (CanRetry);
// zzz
}
private async Task VerifyHash(string Url, string FileName) {
// Simple logic to scan hash and compare it.
// Not absolutely perfect, but it works well enough.
pbDownloadProgress.Text = Language.pbDownloadProgressCalculatingHash;
using SHA256 CNG = SHA256.Create();
using FileStream UpdateFileStream = File.OpenRead(FileName);
byte[] Data = await Task.Run(() => CNG.ComputeHash(UpdateFileStream));
string ReceivedHash = BitConverter.ToString(Data).Replace("-", "").ToLowerInvariant();
string ExpectedHash = UpdateData.UpdateHash.ToLowerInvariant();
if (ReceivedHash != ExpectedHash) {
pbDownloadProgress.Invoke(() => {
pbDownloadProgress.Text = Language.pbDownloadProgressHashNoMatch;
pbDownloadProgress.ProgressState = ProgressState.Paused;
});
switch ((DialogResult)this.Invoke(() => MessageBox.Show(this, string.Format(Language.dlgUpdaterUpdatedVersionHashNoMatch, ExpectedHash, ReceivedHash), Language.ApplicationName, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Warning))) {
case DialogResult.Abort:
throw new CryptographicException("The known hash of the file does not match the hash caluclated by the updater.");
case DialogResult.Retry: {
File.Delete(FileName);
this.Invoke(() => {
tmrForm.Start();
pbDownloadProgress.Value = 50;
pbDownloadProgress.ProgressState = ProgressState.Normal;
});
await GetUpdate(Url, FileName);
} return;
case DialogResult.Ignore: {
pbDownloadProgress.Invoke(() => pbDownloadProgress.ProgressState = ProgressState.Normal);
} break;
}
}
}
private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) {
this.Invoke(() => {
pbDownloadProgress.Value = (int)e.Percentage + 50;
pbDownloadProgress.Text = e.Percentage.ToString();
});
}
private void DownloadCompleted(object sender, DownloadFinishedEventArgs e) {
pbDownloadProgress.Invoke(() => pbDownloadProgress.Text = "100%");
}
private void tmrForm_Tick(object sender, EventArgs e) {
// This really is just for appearance.
this.Text = this.Text.EndsWith("...") ? this.Text.Trim('.') : this.Text + ".";
}
}
|
<?php
namespace App\Lib\CurrencyDataProvider;
use App\Constants\Status;
use App\Events\MarketDataEvent;
use App\Lib\CurlRequest;
use App\Models\Currency;
use App\Models\CurrencyDataProvider as CurrencyDataProviderModel;
use App\Models\MarketData;
use Exception;
class CoinmarketCap extends CurrencyDataProvider
{
/*
|--------------------------------------------------------------------------
| CoinmarketCap
|--------------------------------------------------------------------------
|
| This class extends the `CurrencyDataProvider` class and serves as a data provider for
| retrieving cryptocurrency data from the CoinmarketCap service. It implements the necessary
| methods to fetch cryptocurrency symbols, convert currency, and update market data specific
| to the CoinmarketCap data provider.
|
*/
/**
* Update cryptocurrency prices and market data.
*
* @return void
* @throws Exception if there is an error with the API call or data processing.
*
*/
public function updateCryptoPrice()
{
$convertTo = $this->fetchCryptoConvertTo();
$cryptoCurrencyList = $this->cryptoCurrencyList();
$symbol = $cryptoCurrencyList->pluck('symbol')->implode(',');
$parameters = [
'symbol' => $symbol,
'convert' => $convertTo
];
$data = $this->apiCall($parameters);
if (@$data->status->error_code != 0) {
$this->setException(@$data->status->error_message);
}
$updatedMarketData = [];
foreach ($data->data ?? [] as $item) {
$symbol = strtoupper($item->symbol);
$cryptoCurrency = $cryptoCurrencyList->where('symbol', $symbol)->first();
if (!$cryptoCurrency) {
continue;
}
$marketData = $cryptoCurrency->marketData;
$itemData = $item->quote->$convertTo;
if (!$marketData || !$itemData) {
continue;
}
$cryptoCurrency->rank = $item->cmc_rank;
$cryptoCurrency->rate = $itemData->price;
$cryptoCurrency->save();
$updatedMarketData[] = $this->updateMarketData($marketData, $itemData, $convertTo);
}
try {
event(new MarketDataEvent($updatedMarketData));
} catch (Exception $ex) {
$this->setException($ex->getMessage());
}
echo 'CRYPTO PRICE UPDATE <br/> ' . date("h:m:s") . ' ';
}
/**
* Update market data for all active markets.
*
* @return void
* @throws Exception if there is an error with the API call or data processing.
*
*/
public function updateMarkets()
{
$conflagration = $this->configuration();
$markets = $this->marketList();
$updatedMarketData = [];
foreach ($markets as $market) {
$pairs = $market->pairs;
$symbol = $pairs->pluck('marketData.symbol')->implode(',');
$convertTo = $market->currency->symbol;
$parameters = [
'symbol' => $symbol,
'convert' => $convertTo
];
$data = $this->apiCall($parameters, $conflagration);
if ($data->status->error_code != 0) {
$this->setException(@$data->status->error_message);
}
foreach ($data->data ?? [] as $item) {
$symbol = strtoupper($item->symbol);
$pair = $pairs->where('coin.symbol', $symbol)->first();
$marketData = @$pair->marketData;
$itemData = @$item->quote->$convertTo;
if (!$pair || !$marketData || !$itemData) {
continue;
}
$updatedMarketData[] = $this->updateMarketData($marketData, $itemData, $convertTo);
}
}
try {
event(new MarketDataEvent($updatedMarketData));
} catch (Exception $ex) {
$this->setException($ex->getMessage());
}
echo 'CRYPTO PRICE UPDATE <br/> ' . date("h:m:s");
}
/**
* Make an API call to the CoinmarketCap API.
*
* @param array $parameters
* @param array|null $conflagration
* @return object
*
*/
public function apiCall($parameters = null, $conflagration = null, $endPoint = "cryptocurrency/quotes/latest")
{
if (!$conflagration) $conflagration = $this->configuration();
$url = $conflagration['base_url'] . $endPoint;
$apiKey = $conflagration['api_key'];
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY:' . $apiKey
];
$qs = $parameters ? http_build_query($parameters) : "";
$response = CurlRequest::curlContent("{$url}?{$qs}", $headers);
return json_decode($response);
}
/**
* Update the market data for a specific market with the provided data.
*
* @param \App\Models\MarketData $systemMarketData
* @param mixed $providerMarketData
* @param string $convertTo
* @return string
*
*/
protected function updateMarketData($systemMarketData, $providerMarketData, $convertTo)
{
$systemMarketData->last_price = $systemMarketData->price;
$systemMarketData->last_percent_change_1h = $systemMarketData->percent_change_1h;
$systemMarketData->last_percent_change_24h = $systemMarketData->percent_change_24h;
$systemMarketData->last_percent_change_7d = $systemMarketData->percent_change_7d;
$htmlClasses = [
'price_change' => upOrDown($providerMarketData->price, $systemMarketData->price),
'percent_change_1h' => upOrDown($providerMarketData->percent_change_1h, $systemMarketData->percent_change_1h),
'percent_change_24h' => upOrDown($providerMarketData->percent_change_24h, $systemMarketData->percent_change_24h),
'percent_change_7d' => upOrDown($providerMarketData->percent_change_7d, $systemMarketData->percent_change_7d),
];
$systemMarketData->price = abs($providerMarketData->price);
$systemMarketData->percent_change_1h = abs($providerMarketData->percent_change_1h);
$systemMarketData->percent_change_24h = abs($providerMarketData->percent_change_24h);
$systemMarketData->percent_change_7d = abs($providerMarketData->percent_change_7d);
$systemMarketData->market_cap = abs($providerMarketData->market_cap);
$systemMarketData->volume_24h = abs($providerMarketData->volume_change_24h);
$systemMarketData->html_classes = $htmlClasses;
$systemMarketData->save();
return json_encode([
'symbol' => $systemMarketData->symbol,
'price' => $systemMarketData->price,
'percent_change_1h' => $systemMarketData->percent_change_1h,
'percent_change_24h' => $systemMarketData->percent_change_24h,
'html_classes' => $systemMarketData->html_classes,
'id' => $systemMarketData->id,
'market_cap' => $systemMarketData->market_cap,
'html_classes' => $systemMarketData->html_classes,
'last_price' => $systemMarketData->last_price,
]);
}
/**
* Get the configuration parameters for the CoinmarketCap API.
*
* @return array
*
*/
public function configuration()
{
$provider = $this->provider ? $this->provider : CurrencyDataProviderModel::where('alias', "CoinmarketCap")->first();
return [
'api_key' => @$provider->configuration->api_key->value,
'base_url' => "https://pro-api.coinmarketcap.com/v1/"
];
}
/**
* import crypto & fiat currency from CoinmarketCap API.
*
* @return integer
*
*/
public function import($parameters, $type)
{
$endPoint = $type == Status::CRYPTO_CURRENCY ? 'cryptocurrency/listings/latest' : 'fiat/map';
$data = $this->apiCall($parameters, null, $endPoint);
if (@$data->status->error_code != 0) {
$this->setException(@$data->status->error_message);
}
$currencies = [];
$marketData = [];
$now = now();
foreach ($data->data as $item) {
$currencies[] = [
'type' => @$type,
'name' => @$item->name,
'symbol' => @$item->symbol,
'sign' => @$item->sign ?? '',
'rank' => @$item->cmc_rank ?? 0,
'rate' => @$item->quote->USD->price ?? 0,
'created_at' => $now,
'updated_at' => $now,
];
}
$importCount = Currency::insertOrIgnore($currencies);
if ($type == Status::FIAT_CURRENCY || $importCount <= 0) return $importCount;
$marketData = [];
foreach ($currencies as $currency) {
$currency = Currency::where('symbol', @$currency['symbol'])->first();
if (!$currency) continue;
if (MarketData::where('pair_id', 0)->where('currency_id', $currency->id)->exists()) continue;
$marketData[] = [
'currency_id' => $currency->id,
'symbol' => @$currency->symbol,
'price' => @$currency->rate,
'pair_id' => 0,
'created_at' => $now,
'updated_at' => $now,
];
}
MarketData::insertOrIgnore($marketData);
return $importCount;
}
}
|
#how many employees are there
SELECT
COUNT(emp_no)
FROM
employees;
#how many unique first names
SELECT
COUNT(DISTINCT first_name)
FROM
employees;
#eldest person in the database
SELECT
MIN(birth_date)
FROM
employees;
#youngest person
SELECT
MAX(birth_date)
FROM
employees;
#order by alphabetical order of employee name
SELECT
*
FROM
employees
ORDER BY first_name;
SELECT
*
FROM
employees
ORDER BY emp_no DESC;
SELECT
*
FROM
employees
ORDER BY first_name, last_name;
#unique first names and its count
SELECT
first_name, COUNT(first_name)
FROM
employees
GROUP BY first_name
ORDER BY first_name;
SELECT
gender, COUNT(gender)
FROM
employees
GROUP BY gender;
#alias a result
SELECT
first_name, COUNT(first_name) AS names_count
FROM
employees
GROUP BY first_name
ORDER BY first_name;
#having
SELECT
first_name, COUNT(first_name) AS names_count
FROM
employees
GROUP BY first_name
HAVING COUNT(first_name) > 250
ORDER BY first_name;
#where & having both
SELECT
first_name, COUNT(first_name) AS names_count
FROM
employees
WHERE
hire_date > '1999-01-01'
GROUP BY first_name
HAVING COUNT(first_name) < 200
ORDER BY first_name DESC;
#10 highest salaries
SELECT
*
FROM
salaries
ORDER BY salary DESC
LIMIT 10;
|
import {IsNotEmpty, IsNumber, IsString, Length, Min } from "class-validator";
export class CalculateExchangeDto {
@IsString({message:'La moneda origen debe ser un string'})
@IsNotEmpty({message:'La moneda origen es requerido'})
@Length(3, 3,{message:'Solo se permite 3 carácteres'})
moneda_origen:string;
@IsString({message:'La moneda destino debe ser un string'})
@IsNotEmpty({message:'La moneda destino es requerido'})
@Length(3, 3,{message:'Solo se permite 3 carácteres'})
moneda_destino:string;
@IsNumber({},{message:'El monto debe ser un número'})
@Min(0.01, { message: 'El monto debe ser mayor o igual a 0.01' })
@IsNotEmpty({message:'El monto es requerido'})
monto:number;
}
|
## 1 \*\* Enzyme testing front-end with redux
import { mount } from 'enzyme';
import configureMockStore from 'redux-mock-store';
## 2 \*\* mocking
const reactRedux = jest.mock('react-redux', () => ({
useDispatch: jest.fn(),
useSelector: jest.fn()
},
}));
const useStatespy = jest.spyOn(React, 'useState');
expect(spy).toHaveBeenCalled();
const initialState = {};
const mockStore = configureMockStore(initialState);
const store = mockStore({ startup: { complete: false } });
const onSubmitFn = jest.fn();
### 3 \*\* creating the rapper via mount form enzyme
```
const wrapperFn = props => mount(
<Provider store={store}>
<CreateEventForm {...props} onSubmit={onSubmitFn} />
</Provider>,
);
```
## 4 \*\* we have to use jest.mock and to kill it we have to jest.unmock()
beforeEach(() => {
wrapper = wrapperFn(props);
component = findByDataAttribute(wrapper, 'create-event');
expect(component.text()).toEqual('Hello, World!');
});
```
const findDataByAttribute = (wrapper, attribute) => wrapper.find('[data-test="header"]')
```
## Events triggering
link.at(0).simulate('click');
submitButton.simulate('click');
nameInput[i].props().onChange('test');
descInput[i].props().onChange('test');
expect(nameInput[i].props().value).toEqual('test');
expect(descInput[i].props().value).toEqual('test');
## 5 \*\* jest.spyOne vs jest.mock
- jest.spyOn is used to spy on a specific function within a module,
- jest.mock is used to replace an entire module with a mock object.
## 6 \*\* testing the server
const server = require('./server.js')
const request = require('supertest');
/// get test
const expectedBody = { api: 'running!' };
const response = await request(server).get('/');
expect(response.status).toBe(200);
expect(response.type).toEqual('application/json');
expect(response.body).toEqual(expectedBody);
// post test
const res = await request(app)
.post('/users')
.send({ name: 'John', age: 30 });
expect(res.status).toEqual(201);
expect(res.body).toHaveProperty('name', 'John');
expect(res.body).toHaveProperty('age', 30);
## 7 \*\* mocking axios
jest.mock('axios');
```
const mockedResponse = { data: { message: 'Hello World' } };
axios.get.mockResolvedValue(mockedResponse);
const res = await request(app).get('/');
expect(res.status).toEqual(200);
expect(res.body).toEqual({ message: 'Hello World' });
```
## 8 \*\* jest.requireActual('mongodb')
in some scenarios we need to mock only a portion of mongodb and not all of it but we still
need the original parts along with the mocked portion
```
jest.mock('mongodb', () => {
const originalModule = jest.requireActual('mongodb');
return {
__esModule: true,
...originalModule,
MongoClient: jest.fn().mockImplementation(() => {
return {
connect: jest.fn().mockResolvedValue(null),
db: jest.fn().mockReturnValue({})
{
{
```
## 9 shallow vs mount in enzyme
shallow to render the parent without children but mount is to render everything
## 10 \*\* chai is a popular assertion for node
const chai = require('chai');
const expect = chai.expect;
const myValue = 5;
expect(myValue).to.equal(5);
## 11 ** Sinon.js is a library for creating and manipulating spies, and mocks
const myFunction = (a, b) => { return a + b };
const spy = sinon.spy(myFunction);
console.log(spy(1, 2)); // 3
console.log(spy.called); // true
console.log(spy.callCount); // 1
console.log(spy.firstCall.args); // [1, 2]
console.log(spy.firstCall.returnValue); // 3
## 12 ** Mocka is less then jest
## 13 ** react testing liberary
import { screen, fireEvent , act, render , waitFor} from '@testing-library/react';
|
def gen_fun1(my_list):
for name in my_list:
yield "_______"
yield "Name:"
yield name
yield " "
""" Run:
for i in gen_fun1(names):
print(i)
"""
def rev_str(my_str):
length = len(my_str)
for i in range(length - 1, -1, -1):
yield my_str[i]
""" For loop to reverse the string
for char in rev_str("hello"):
print(char)
"""
# One line code for suming all numbers in a list:
# print(sum(x for x in list_numbers))
# Iterator Class
class PowTwo:
def __init__(self, max=0):
self.n = 0
self.max = max
def __iter__(self):
return self
def __next__(self):
if self.n > self.max:
raise StopIteration
result = 2 ** self.n
self.n += 1
return result
# The Iterator class can be turned into a generator:
def PowTwoGen(max=0):
n = 0
while n < max:
yield 2 ** n
n += 1
# Represent Infinite Stream
def all_even():
n = 0
while True:
yield n
n += 2
# If we want to find out the sum of squares of numbers in the
# Fibonacci series, we can do it in the following way by pipelining the output of generator functions together.
def fibonacci_numbers(nums):
x, y = 0, 1
for _ in range(nums):
x, y = y, x+y
yield x
def square(nums):
for num in nums:
yield num**2
# print(sum(square(fibonacci_numbers(10))))
"""
Notes:
Yield - Pauses the function saving all the states and continues to the next calls.
Generators have lazy execution and only create on demand.
Advantages to using Generators:
1. Memory Efficient - A normal function to return a sequence will create the entire sequence in memory before returning the result.
This is great for a sequence that is very very large.
2. Easier to impliment than iterator classes.
3. Can represent an infinite stream of data.
4. Can pipeline generators together
"""
|
import { useState } from "react";
import { connect } from "react-redux";
import { handleAddTweet } from "../actions/tweets";
const NewTweet = ({dispatch, id}) => {
const [text, setText] = useState("");
const handleChange = (e) => {
const text = e.target.value;
setText(text);
};
const handleSubmit = (e) => {
e.preventDefault();
dispatch(handleAddTweet(text, id))
setText("");
};
const tweetLeft = 280 - text.length;
return (
<div>
<h3 className="center">Compose new Tweet</h3>
<form className="new-tweet" onSubmit={handleSubmit}>
{/* todo: Redirect to / if submitted */}
<textarea
placeholder="What's happening?"
value={text}
onChange={handleChange}
className="textarea"
maxLength={280}
/>
{tweetLeft <= 100 && <div className="tweet-length">{tweetLeft}</div>}
<button className="btn" type="submit" disabled={text === ""}>
Submit
</button>
</form>
</div>
);
};
export default connect()(NewTweet);
|
import { credentials } from '../support/credentials';
export class LoginPage {
URL = '';
visit(): this {
cy.visit(this.URL);
return this;
}
fillUsernameInput(username: string): this {
cy.get('input[id="user-name"]').should('be.visible').type(username);
return this;
}
fillPasswordInput(password: string): this {
cy.get('input[id="password"]').should('be.visible').type(password);
return this;
}
clickLoginButton(): this {
cy.get('input[id="login-button"]').should('be.visible').click();
return this;
}
assertCookieAfterLogin(username: string): this {
cy.getCookie('session-username')
.should('exist')
.and('have.property', 'value', username);
return this;
}
assertLoginPageHeader(): this {
cy.get('.login_logo').should('be.visible').and('have.text', 'Swag Labs');
return this;
}
assertAuthenticationForm(): this {
const loginFormSelectors = ['#user-name', '#password', '#login-button'];
cy.get('.login-box').within(() => {
loginFormSelectors.forEach((selector) => {
cy.get(selector).should('be.visible').and('not.be.disabled');
});
});
return this;
}
assertTestingCredentials(): this {
cy.get('.login_credentials_wrap-inner #login_credentials')
.within(() => {
cy.get('h4').should('have.text', 'Accepted usernames are:');
})
.then((element) => {
credentials.username.forEach((username) => {
expect(element).to.contain(username);
});
});
cy.get('.login_credentials_wrap-inner .login_password')
.within(() => {
cy.get('h4').should('have.text', 'Password for all users:');
})
.then((element) => {
expect(element).to.contain(credentials.password);
});
return this;
}
assertErrorMessageNotExist(): this {
cy.get('h3[data-test="error"]').should('not.exist');
return this;
}
}
|
package stepDefinitions;
import java.util.Map;
import java.util.Properties;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import Factory.BaseClass;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.cucumber.datatable.DataTable;
import pageObjects.AccountCreatedPage;
import pageObjects.AccountRegisterPage;
import pageObjects.HomePage;
public class AccountRegisterSteps {
WebDriver driver;
Properties p;
HomePage hp;
AccountRegisterPage arp;
AccountCreatedPage acp;
@Given("User navigates to Register Account page")
public void user_navigates_to_register_account_page() {
BaseClass.getLogger().info("Navigating to the Account Register Page....");
hp = new HomePage(BaseClass.getDriver());
hp.clickMyAccount();
hp.clickRegister();
}
@Given("User provides all required details")
public void user_provides_all_required_details(DataTable dataTable) {
Map<String, String> dataMap = dataTable.asMap(String.class,String.class);
BaseClass.getLogger().info("Enter all the details in the Account Registeration Page...");
arp = new AccountRegisterPage(BaseClass.getDriver());
arp.setFirstName(dataMap.get("FirstName"));
arp.setLastName(dataMap.get("LastName"));
String email = BaseClass.randomAlphaNumeric().concat("@gmail.com");
//arp.setEmail(email);
//System.out.println(email);
arp.setEmail(BaseClass.randomAlphaNumeric()+"@gmail.com");
arp.setTelephone(dataMap.get("Telephone"));
arp.setPassword(dataMap.get("Password"));
arp.setConfirmPwd(dataMap.get("Password"));
}
@Given("User clicks on the private policy check box")
public void user_clicks_on_the_private_policy_check_box() {
BaseClass.getLogger().info("User clicks the private policy check box...");
arp = new AccountRegisterPage(BaseClass.getDriver());
arp.clickAgree();
}
@When("User clicks on Continue button")
public void user_clicks_on_continue_button() {
BaseClass.getLogger().info("User clicks the Continue Button...");
arp = new AccountRegisterPage(BaseClass.getDriver());
arp.clickContinue();
}
@Then("User account gets created successfully.")
public void user_account_gets_created_successfully() {
BaseClass.getLogger().info("Verify the Account created message...");
acp = new AccountCreatedPage(BaseClass.getDriver());
boolean display = acp.AccCreatedDisplay();
Assert.assertTrue(display);
}
}
|
import React, { useEffect, useState } from 'react';
import '../App.css';
export default function AppStats() {
const [isLoaded, setIsLoaded] = useState(false);
const [stats, setStats] = useState({});
const [error, setError] = useState(null);
const getStats = () => {
const url = `http://acit3855group4kafka.eastus2.cloudapp.azure.com/processing/events/stats`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
setStats(data);
setIsLoaded(true);
})
.catch(err => {
console.error("Error loading stats: ", err.message);
setError(err);
setIsLoaded(true);
});
};
useEffect(() => {
const interval = setInterval(getStats, 2000); // Update every 2 seconds
return () => clearInterval(interval); // This will clear the interval when the component unmounts.
}, []);
if (error) {
return <div className="error">Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>
<h1>Latest Stats</h1>
<table className="StatsTable">
<tbody>
<tr>
<th>Vehicle Status Events</th>
<th>Incident Report Events</th>
</tr>
<tr>
<td>Total Vehicle Status Events: {stats.num_vehicle_status_events}</td>
<td>Total Incident Report Events: {stats.num_incident_events}</td>
</tr>
<tr>
<td>Max Distance Travelled: {stats.max_distance_travelled}</td>
<td>Max Incident Severity: {stats.max_incident_severity}</td>
</tr>
</tbody>
</table>
<h3>Last Updated: {stats.last_updated}</h3>
</div>
);
}
}
|
import UIKit
import SnapKit
final class NewsViewController : UIViewController {
private let newsViewModel: NewsViewModel
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.register(ArticleTableViewCell.self, forCellReuseIdentifier: ArticleTableViewCell.identifier)
tableView.separatorStyle = .none
tableView.backgroundColor = Colors.News.background
return tableView
}()
private lazy var activityIndicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView()
return indicator
}()
init(newsViewModel: NewsViewModel) {
self.newsViewModel = newsViewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError()
}
override func loadView() {
super.loadView()
view.backgroundColor = Colors.News.background
self.title = Strings.News.title
view.addSubview(tableView)
tableView.snp.makeConstraints { make in
make.left.top.right.bottom.equalTo(view.safeAreaLayoutGuide)
}
view.addSubview(activityIndicator)
activityIndicator.snp.makeConstraints { make in
make.centerX.equalTo(view.safeAreaLayoutGuide)
make.centerY.equalTo(view.safeAreaLayoutGuide)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.prefersLargeTitles = true
updateVisibleCells()
self.hideBackButtonTitle()
}
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.startAnimating()
newsViewModel.articleRemovedFromFavoritesAction = { [weak self] indexPath in
guard let self = self else {return}
guard let cell = self.tableView.cellForRow(at: indexPath) as? ArticleTableViewCell else {return}
let article = self.newsViewModel.articles[indexPath.row]
cell.update(by: article)
}
newsViewModel.load { [weak self] result in
guard let self = self else {return}
self.activityIndicator.stopAnimating()
switch result {
case .failure(let error):
self.showMessage(title: "Ошибка", message: error.localizedDescription)
case .success(_):
self.tableView.reloadData()
}
}
tableView.reloadData()
}
private func updateVisibleCells() {
guard let selectedIndexPath = tableView.indexPathForSelectedRow else {return}
let article = newsViewModel.articles[selectedIndexPath.row]
let cell = tableView.cellForRow(at: selectedIndexPath) as? ArticleTableViewCell
cell?.update(by: article)
}
}
extension NewsViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 256
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedArticle = newsViewModel.articles[indexPath.row]
self.navigationController?.pushViewController(ArticleViewController(article: selectedArticle), animated: true)
}
}
extension NewsViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newsViewModel.articles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ArticleTableViewCell.identifier, for: indexPath) as! ArticleTableViewCell
cell.selectionStyle = .none
let article = newsViewModel.articles[indexPath.row]
cell.update(by: article)
return cell
}
}
|
import PropTypes from "prop-types";
import {
WrapperContainerWBckg,
StyledResponsiveContainer,
Title,
RenderLegendStyled,
} from "./style";
import { getScaledValue } from "./utils";
import { RadialBarChart, RadialBar } from "recharts";
import colors from "../../utils/colors";
/**
* Display the User Score in the form of a Radial bar chart
* @component
* @param {array} data
* @return ( <Radialbarchart
data={data}
sizes={{minWidth,minHeight,maxWidth,maxHeight}}
/>)
*/
const Radialbarchart = ({ data }) => {
let scaledValue = getScaledValue(data[0].value, 0, 100, 200, -200);
return (
<WrapperContainerWBckg>
<Title>Score</Title>
<StyledResponsiveContainer
backgroundColor={colors.backgroundColor}
width="100%"
height="100%"
>
<RadialBarChart
cx="50%"
cy="50%"
innerRadius="70%"
outerRadius="70%"
startAngle={200}
endAngle={scaledValue}
barSize={10}
data={data}
>
<circle
className="whiteCircle"
cx="50%"
cy="50%"
r="30%"
stroke="none"
fill={colors.white}
/>
<RadialBar
clockWise={true}
dataKey="value"
cornerRadius={5}
background="black"
/>
</RadialBarChart>
</StyledResponsiveContainer>
<RenderLegendStyled value={data[0].value} />
</WrapperContainerWBckg>
);
};
export default Radialbarchart;
Radialbarchart.propTypes = {
data: PropTypes.array.isRequired,
};
|
import React, {useEffect, useState} from 'react';
import {Button, Card, message, Table, Typography} from "antd";
import {getColumns, ITableDataType} from "./tableProps";
import {ILevelForm} from "../../types/forms";
import LevelApi from "../../api/level-api";
import LevelModal from "../../components/LevelModal/LevelModal";
const {Title} = Typography;
const Levels = () => {
const [tableData, setTableData] = useState<ITableDataType[]>([]);
const [loadingTable, setLoadingTable] = useState<boolean>(false);
const [showModal, setShowModal] = useState<boolean>(false);
const [loadingButton, setLoadingButton] = useState<boolean>(false);
const [levelData, setLevelData] = useState<ILevelForm>();
const [editLevelId, setEditLevelId] = useState<number>(0);
const fetchLevels = () => {
setLoadingTable(true);
LevelApi.getLevels().then(res => {
setTableData(res.data.map(item => {
return {
key: item.id,
text: item.text,
subjects: item.subjects
}
}))
}).catch((e) => {
message.error('Ошибка получения данных!');
});
setLoadingTable(false);
};
const createLevel = (data: ILevelForm) => {
setLoadingButton(true);
LevelApi.createLevel(data.text).then(res => {
setTableData([...tableData, {
key: res.data.id,
text: res.data.text,
subjects: res.data.subjects
}])
setShowModal(false);
}).catch(e => {
message.error('Ошибка создания уровня!');
})
setLoadingButton(false);
}
const editLevel = (data: ILevelForm) => {
setLoadingButton(true);
LevelApi.editLevel(editLevelId, data.text).then(res => {
setTableData(tableData.map(item => {
return item.key === editLevelId
?
{
key: res.data.id,
text: res.data.text,
subjects: res.data.subjects
}
: item
}))
setShowModal(false);
}).catch(e => {
if (e.response.data === 'Schedule not found') message.error('Уровень не найден!');
else message.error('Ошибка редактирования уровня!');
})
setLoadingButton(false);
};
const onEditLevel = (levelId: number) => {
message.loading('Загрузка данных');
LevelApi.getLevel(levelId).then(res => {
setLevelData({
id: res.data.id,
text: res.data.text,
subjects: res.data.subjects.map(subject => {
return {
value: subject.subject.id,
}
})
});
message.destroy();
setShowModal(true);
setEditLevelId(levelId)
}).catch(e => {
message.destroy();
message.error('Ошибка загрузки данных!');
});
}
const removeLevel = (levelId: number) => {
message.loading('Удаление уровня');
LevelApi.removeLevel(levelId).then(res => {
message.destroy();
setTableData(tableData.filter(item => item.key !== levelId));
}).catch(e => {
message.error('Ошибка удаления!');
})
};
useEffect(() => {
fetchLevels()
}, [])
return (
<>
<Card>
<div className='pageHeader'>
<Title level={4}>Уровни подготовки</Title>
<Button type="primary" onClick={() => {
setLevelData(undefined)
setShowModal(true)
}}>Создать уровень</Button>
</div>
<Table
columns={getColumns(onEditLevel, removeLevel)}
dataSource={tableData}
rowClassName='tableRow'
loading={loadingTable}
pagination={{showSizeChanger: true}}
bordered
scroll={{x: 400}}
/>
</Card>
<LevelModal
open={showModal}
onClose={() => {setShowModal(false)}}
onSubmit={levelData ? editLevel : createLevel}
loading={loadingButton}
initialValues={levelData}
titleText={levelData ? 'Уровень: '+levelData.text : 'Новый уровень'}
submitText={levelData ? 'Изменить' : 'Добавить'}
/>
</>
);
};
export default Levels;
|
using CLASSES_HERENCIA_i_POLIMORFISME;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DAM_HERENCIA_i_POLIMORFISME_2.CLASSES
{
public class ClTriangle: ClPoligons
{
private int height;
private int width;
private Point Centre;
public ClTriangle(Form xfrmPare, int xCentre, int yCentre, Color xcolorContorn, float xgruixContorn, Color xcolorInterior, int xheight, int xwidth) : base(xfrmPare, xcolorContorn, xgruixContorn)
{
height = xheight;
width = xwidth;
Centre = new Point(xCentre, yCentre);
colorInterior = xcolorInterior; //Com que aquest constructor si que te un color, li donarem valor, si no no hauriem de donar valor
mostrar();
}
public ClTriangle(Form xfrmPare2, int xCentre, int yCentre, Color xcolorContorn2, float xgruixContorn, int xheight, int xwidth) : base(xfrmPare2, xcolorContorn2, xgruixContorn)
{
height = xheight;
width = xwidth;
Centre = new Point(xCentre, yCentre);
colorInterior = Color.Empty; //Com que aquest constructor si que un color, li donarem valor, si no no hauriem de donar valor
mostrar();
}
private void mostrar()
{
int xSupEsq, ySupEsq;
xSupEsq = (int)(Centre.X - (width / 2));
ySupEsq = (int)(Centre.Y - (height / 2));
pnl.Size = new Size(width, height);
pnl.Location = new Point(xSupEsq, ySupEsq);
pnl.Paint += new PaintEventHandler(ferTriangle);
frmPare.Controls.Add(pnl);
pnl.BringToFront();
}
private void ferTriangle(object sender, PaintEventArgs e)
{
Pen p = new Pen(colorContorn, gruixContorn); // Pen per a traçar el contorn
//e.Graphics.DrawRectangle(p, xSupEsq, ySupEsq, Mida, Mida); //Per que tenim aixo comentat?
Point[] punts = { new Point(width/2,0), new Point(width,height), new Point(0,height) };
Point[] punts2 = { new Point(width / 2, (int)(0 + gruixContorn)), new Point((int)(width - gruixContorn), (int)(height - gruixContorn)), new Point(0+(int)gruixContorn, height - (int)gruixContorn) };
e.Graphics.DrawPolygon(p,punts);
if (colorInterior != Color.Empty)
{
e.Graphics.FillPolygon(new SolidBrush(colorInterior), punts2);
}
}
public override Double Perimetre()
{
return (height * 2 + width * 2);
}
// retorna l'àrea de la figura mesurada en pixels
public override Double Area()
{
return (height * width);
}
public override void FerGran(int escalar)
{
if (escalar > 0)
{
this.height = height * escalar;
this.width = width * escalar;
this.Centre.X = this.Centre.X - (width * (escalar / 10));
this.Centre.Y = this.Centre.Y - (height * (escalar / 10));
this.mostrar();
this.pnl.Refresh();
}
else if (escalar < 0)
{
escalar = Math.Abs(escalar);
this.height = height * escalar;
this.width = width * escalar;
this.Centre.X = this.Centre.X - (width * (escalar / 10));
this.Centre.Y = this.Centre.Y - (height * (escalar / 10));
this.mostrar();
this.pnl.Refresh();
}
}
}
}
|
Question 1
'let' and "const" when we are declaring variables in javascript.
The 'let' keyword is used for variables that can be reassigned.
However,variables that are declared by the "let" keyword can be re-assigned which of course allows variables for alteration.
"const" creates "constant" variables that cannot be reassigned another value unless they are redeclared.
"let" creates variables tgat can be reassigned.
What distinquishes the 'let' and 'const' keywords from the var keyword are quiet are listed below;
a.'var' declarations are globally scoped or function scoped while 'let' and 'const' are block scoped.
b.'var' variables can be reassigned while 'let' and 'const' variables can not.
c. 'var' variables are declared using the var keyword while 'let' and 'const' variables are declared using the 'let' and 'const' keywords respectively.
d'const' variables are immutable while let and var variables are not.
Question 2
A variable can be used after defining it by referencing its variable name.
Question 3
A string can be declared by enclosing characters within single quotes ('') or double quotes ("").
Example;
let myString_a = "I am a good software developer";
let myString_b = 'Thank you Enyata for this great opportunity';
Question 4
Yes,We can create strings by using both single quotes and double quotes interchangeably.
However,it is advisable that we use one particular code style in your codes.
Question 5
"9" is a string data type because of the quotes(" ").
9 is a interger or number data type.
Question 6
Declaration means introducing a new variable.This is normally done using the keywords 'var','let' or 'const'
Example;
const myText = 'Fufu';
whilst redeclaration means declaring a variable again in the same scope.
Example; const myText = 'banku';
Assignment means assigning a value to a variable .This is normally done using the Assignment operator(=)
example ;
let grade = 9;
Whilst reassignment means assigning a new value to a variable that already holds a value.
example
let grade = 9;
let grade = 5;
|
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getData } from '../../redux/actions/Store';
import Header from '../components/Header';
import axios from 'axios';
import { Link } from 'react-router-dom';
import Footer from '../components/Footer';
const MyStore = () => {
const [loading, setLoading] = useState(true)
const [games, setGames] = useState([])
useEffect(() => {
axios.get('/my-store').then((res) => {
console.log(res.data)
setGames(res.data)
setLoading(false)
})
}, [])
return (
<div>
<Header tab='my-store' />
<div className='container mx-auto col-md-9 px-4'>
<div>
<p className='fs-2'>My Store</p>
<div className='my-2'>
<Link to={"/add-game"} className='btn shadow ms-auto rounded-circle d-flex align-items-center jsutify-content-center bg-primary' style={{ height: "4ch", width: "4ch" }}>
<p className='m-0 my-auto fw-bold text-center mx-auto fs-6 text-light'><i className='fa-solid fa-plus'></i></p>
</Link>
</div>
</div>
<div>
<div className='d-flex flex-wrap justify-content-start'>
{
!loading ?
<>
{
games.length > 0 ?
<>
{
games.map((val, ind) => {
return (
<Link to={`/game-details/${val._id}/${val.game.id}`} style={{ textDecoration: "none", color: "#3f3f3f" }}>
<div className='my-3' style={{ marginRight: "2ch" }}>
<div>
<img src={val.game.background_image} className='rounded poster' style={{ height: '25ch', width: "19ch", objectFit: "cover" }} alt="" />
</div>
<div className='' style={{ width: "100%" }}>
<p style={{ fontSize: '0.9rem', width: "18ch" }} className='fw-bold my-1'>{val.game.name}</p>
{
val.discount > 0 ?
<>
<small className='rounded bg-primary p-1 text-light' style={{ fontSize: "0.7rem" }}>-{val.discount}%</small>
<small className='fw-bold mx-3' style={{ color: "#797979", textDecoration: "line-through" }}>Rs. {val.price}</small>
<small className='fw-bold'>Rs. {(parseInt(val.price) - (val.price * (val.discount / 100))).toFixed(0)}</small>
</> :
<>
<small className='fw-bold'>Rs. {val.price}</small>
</>
}
</div>
</div>
</Link>
)
})
}
</> :
<>
<div className='mx-auto d-flex align-items-center' style={{ height: "50ch" }}>
<p className=''>You have not added any games yet.</p>
</div>
</>
}
</> :
<>
<div className='mx-auto d-flex align-items-center' style={{ height: "50ch" }}>
<div className="spinner-border text-secondary" style={{ height: "5ch", width: "5ch", fontSize: "1.5rem" }} role="status">
<span className="visually-hidden">Loading...</span>
</div>
</div>
</>
}
</div>
</div>
</div>
<Footer />
</div>
)
}
export default MyStore
|
import { useForm } from "react-hook-form";
import { Link, useNavigate } from "react-router-dom";
import { userSchema } from "../utils/validation";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRegisterUser } from "../react-query/queries";
import toast from "react-hot-toast";
export type TRegisterFormData = z.infer<typeof userSchema>;
const Register = () => {
const navigate = useNavigate();
const { mutateAsync: registerUser, error } = useRegisterUser();
const errorMessage = error?.message;
const {
register,
handleSubmit,
reset,
formState: { errors, isSubmitting },
} = useForm<TRegisterFormData>({ resolver: zodResolver(userSchema) });
const onSubmit = async (data: TRegisterFormData) => {
try {
const result = await registerUser(data);
console.log(result);
if (result?.statusCode === 200) {
toast.success("Registered successfully");
reset();
navigate("/auth/login");
}
} catch (error) {
toast.error(errorMessage || "something went wrong");
}
};
return (
<form
className="h-full w-full flex justify-center items-center"
onSubmit={handleSubmit(onSubmit)}
>
<div className="shadow-md rounded-lg flex px-6 md:px-10 flex-col border-[1px] border-rose-500 pb-4">
<div className="text-center w-full border-b-[1px] border-neutral-200 py-4">
<h3 className="text-2xl font-bold text-rose-500">Register</h3>
<p className="font-semibold text-lg text-black">
Create a new Account
</p>
</div>
<div className="flex flex-col gap-4 w-full pb-8">
<div className="flex gap-4 flex-col md:flex-row">
<div className="flex flex-col">
<label htmlFor="firstname" className="input_label">
firstname
</label>
<input
type="text"
id="firstname"
placeholder="firstname..."
className="input_filed"
{...register("firstname")}
></input>
{errors.firstname ? (
<p className="text-rose-500">{errors.firstname.message}</p>
) : null}
</div>
<div className="flex flex-col">
<label htmlFor="lastname" className="input_label">
lastname
</label>
<input
type="text"
id="lastname"
placeholder="lastname..."
className="input_filed"
{...register("lastname")}
></input>
{errors.lastname ? (
<p className="text-rose-500">{errors.lastname.message}</p>
) : null}
</div>
</div>
<div className="flex flex-col">
<label htmlFor="email" className="input_label">
email
</label>
<input
type="email"
id="email"
placeholder="enter a valid email..."
className="input_filed"
{...register("email")}
></input>
{errors.email ? (
<p className="text-rose-500">{errors.email.message}</p>
) : null}
</div>
<div className="flex flex-col">
<label htmlFor="password" className="input_label">
password
</label>
<input
type="password"
id="password"
placeholder="password"
className="input_filed"
{...register("password")}
></input>
{errors.password ? (
<p className="text-rose-500">{errors.password.message}</p>
) : null}
</div>
<div className="flex flex-col">
<label htmlFor="confirmPassword" className="input_label">
confirm password
</label>
<input
type="password"
id="confirmPassword"
placeholder="confirm password..."
className="input_filed"
{...register("confirmPassword")}
></input>
{errors.confirmPassword ? (
<p className="text-rose-500">{errors.confirmPassword.message}</p>
) : null}
</div>
</div>
<div className="flex justify-center w-full flex-col items-center gap-2">
<p className="text-lg">
already have an account?
<Link to="/auth/login" className="underline text-blue-400">
login here
</Link>
</p>
<button
className="bg-rose-500 text-white font-semibold text;lg p-4 w-full rounded-xl hover:bg-rose-700"
disabled={isSubmitting}
>
Signup
</button>
</div>
</div>
</form>
);
};
export default Register;
|
package com.design.factory.factorymethod.pizzastore.order;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import com.design.factory.factorymethod.pizzastore.pizza.Pizza;
public abstract class OrderPizza {
abstract Pizza createPizza(String orderType);
//订购披萨
public void setFactory(){
Pizza pizaa = null;
String orderType = "";
do {
orderType = getType();
Pizza pizza = createPizza(orderType);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
} while (true);
}
//订购的披萨类型
public String getType(){
try{
BufferedReader strin = new BufferedReader(new InputStreamReader(System.in));
return strin.readLine();
}catch(Exception e){
e.printStackTrace();
return "";
}
}
}
|
// flex
@mixin flex-middle() {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
@mixin flex-column() {
display: flex;
flex-direction: column;
}
@mixin flex-column-center() {
display: flex;
flex-direction: column;
align-items: center;
}
@mixin flex-column-end() {
display: flex;
flex-direction: column;
align-items: end;
}
@mixin flex-row() {
display: flex;
align-items: center;
}
@mixin flex-row-center() {
display: flex;
justify-content: center;
align-items: center;
}
@mixin flex-row-between() {
display: flex;
align-items: center;
justify-content: space-between;
}
@mixin flex-column-justify-between() {
display: flex;
flex-direction: column;
justify-content: space-between;
}
// positioning
@mixin absolute-horizontal-center() {
position: absolute;
left: 50%;
transform:translateX(-50%);
}
@mixin absolute-vertical-center() {
position: absolute;
top: 50%;
transform:translateY(-50%);
}
// screen-size
@mixin full-screen() {
width: 100vw;
height: 100vh;
}
@mixin full-spacing {
width: 100%;
height: 100%;
}
@mixin half-screen() {
width: 50vw;
height: 100vh;
background-size: cover;
}
// media queries
@mixin screen-sm {
@media (min-width: 481px) {
@content;
}
}
@mixin screen-md {
@media (min-width: 769px) {
@content;
}
}
@mixin screen-lg {
@media (min-width: 1025px) {
@content;
}
}
@mixin screen-xl {
@media (min-width: 1201px) {
@content;
}
}
@mixin wrapper() {
margin: 0 auto;
max-width: 90rem;
width: 100%;
}
@mixin wrapper-sm() {
margin: 0 auto;
max-width: 60rem;
width: 100%;
}
@mixin wrapper-md() {
margin: 0 auto;
max-width: 70rem;
width: 100%;
}
@mixin flex-center() {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
@mixin flex-between() {
display: flex;
justify-content: space-between;
align-items: center;
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>LinkedIn</title>
<link
href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet"
/>
<style>
body,
html {
height: 100%;
width: 100%;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
body {
background-color: #f3f2ef;
}
.navbar {
background-color: white;
width: 100vw;
height: 60px;
border-bottom: 1px solid #00000014;
position: fixed;
top: 0;
left: 0;
}
.nav-content {
display: flex;
align-items: center;
margin: 0 auto;
margin-top: 10px;
}
.nav-img {
margin-left: 18%;
color: #0a66c2;
}
.nav-search {
height: 35px;
width: 270px;
margin-left: 7px;
border: none;
border-radius: 4px;
background-color: #eef3f8;
text-indent: 12px;
}
.navigation {
margin-left: 12%;
display: flex;
align-items: center;
}
.nav-icon {
text-decoration: none;
color: #666;
display: flex;
flex-direction: column;
align-items: center;
margin-left: 20px;
margin-right: 7px;
font-size: 12px;
font-weight: 300;
}
.main {
height: 100%;
display: flex;
margin: 0 auto;
margin-top: 70px;
max-width: 80%;
}
.left {
/*border: 1px solid black;*/
width: 225px;
margin-top: 35px;
}
.center {
/*border: 1px solid black; */
flex-grow: 1;
margin-top: 35px;
margin-left: 25px;
}
.right {
/*border: 1px solid black;*/
width: 300px;
margin-top: 25px;
margin-left: 30px;
margin-right: 100px;
}
.create-posts {
background-color: white;
height: 120px;
width: 540px;
border: 1px solid #6e6e6e42;
border-radius: 5px;
}
.post-image {
height: 48px;
width: 48px;
border-radius: 50%;
margin-top: 10px;
margin-left: 10px;
}
.create-post-top {
display: flex;
}
.post-input {
height: 40px;
flex: 1;
border-radius: 25px;
border: 1px solid #aaa;
margin: 14px;
text-indent: 15px;
}
.create-post-bottom {
display: flex;
justify-content: space-around;
}
.post-button {
background-color: transparent;
border: none;
display: flex;
align-items: center;
padding: 5px;
color: #00000099;
}
.mr-10 {
margin-right: 10px;
}
.blue-button {
color: #70b5f9;
}
.green-button {
color: #7fc15e;
}
.orange-button {
color: #e7a33e;
}
.pink-button {
color: #f89295;
}
.posts-hr {
border-top: 1px solid #000000aa;
margin-top: 30px;
border-color: #00000033;
}
.post {
background-color: white;
border: 1px solid #6e6e6e;
border-color: #6e6e6e42;
margin-top: 15px;
border-radius: 10px;
display: flex;
flex-direction: column;
}
.post-info {
display: flex;
align-items: center;
}
.post-metadata {
display: flex;
flex-direction: column;
margin-left: 10px;
margin-top: 7px;
line-height: 1.3rem;
}
.post-creator {
font-size: 15px;
font-weight: 500;
}
.faded-text {
font-size: small;
color: #00000099;
}
.post-data {
font-size: 15px;
color: rgb(98, 97, 97);
margin-left: 15px;
margin-top: 10px;
}
.read-more {
margin-left: 447px;
margin-top: 12px;
color: #00000099;
}
.likes {
font-size: small;
color: #0a66c2;
margin-left: 15px;
}
.center-content {
display: flex;
align-items: center;
}
.no-likes {
font-size: small;
margin-left: 5px;
}
.interaction-button {
background-color: transparent;
border: none;
display: flex;
align-items: center;
margin-right: 12px;
margin-bottom: 10px;
color: #00000099;
margin-left: 7px;
}
.likes-hr {
border-top: 1px solid #000000aa;
margin-top: 12px;
margin-bottom: 10px;
border-color: #00000033;
}
.post-interactions {
display: flex;
}
.post-content-image {
margin-top: 10px;
width: 100%;
}
.news-posts {
background-color: white;
height: 120px;
width: 300px;
border: 1px solid #6e6e6e42;
border-radius: 5px;
}
.profile-pic {
display: flex;
height: 78px;
width: 78px;
border-radius: 50%;
margin-top: 0px;
margin-left: 60px;
}
.Name {
margin-left: 20px;
align-items: centre;
}
.bio {
margin-left: 50px;
align-items: centre;
font-weight: lighter;
}
.more-bio {
align-content: center;
margin-left: 5px;
}
.premium-button {
color: rgb(170, 145, 5);
margin-top: 5px;
}
.bookmark-button {
color: black;
margin-top: 5px;
}
.pre {
display: flex;
}
.news-top {
display: flex;
margin-left: 10px;
margin-top: 20px;
font-weight: normal;
}
</style>
</head>
<body>
<header class="navbar">
<div class="nav-content">
<div class="nav-img">
<svg
xmlns="http://www.w3.org/2000/svg"
width="34"
height="34"
viewBox="0 0 34 34"
class="nav-logo"
>
<g>
<path
d="M34,2.5v29A2.5,2.5,0,0,1,31.5,34H2.5A2.5,2.5,0,0,1,0,31.5V2.5A2.5,2.5,0,0,1,2.5,0h29A2.5,2.5,0,0,1,34,2.5ZM10,13H5V29h5Zm.45-5.5A2.88,2.88,0,0,0,7.59,4.6H7.5a2.9,2.9,0,0,0,0,5.8h0a2.88,2.88,0,0,0,2.95-2.81ZM29,19.28c0-4.81-3.06-6.68-6.1-6.68a5.7,5.7,0,0,0-5.06,2.58H17.7V13H13V29h5V20.49a3.32,3.32,0,0,1,3-3.58h.19c1.59,0,2.77,1,2.77,3.52V29h5Z"
fill="currentColor"
></path>
</g>
</svg>
</div>
<input class="nav-search" type="text" placeholder="Search" />
<nav class="navigation">
<a class="nav-icon">
<span class="material-icons"> home </span> Home
</a>
<a class="nav-icon">
<span class="material-icons"> people </span> My Network
</a>
<a class="nav-icon">
<span class="material-icons"> work </span> Jobs
</a>
<a class="nav-icon">
<span class="material-icons"> chat_bubble </span> Messaging
</a>
<a class="nav-icon">
<span class="material-icons"> notifications </span> Notifications
</a>
<a class="nav-icon">
<span class="material-icons"> person </span> Me
</a>
</nav>
</div>
</header>
<div class="main">
<div class="left">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2048 512" id="person-default" data-supported-dps="2048x512">
<path fill="none" d="M0 0h2048v512H0z" />
<path fill="#dbe7e9" d="M0 0h2048v512H0z" />
<path fill="#bfd3d6" d="M1408 0h640v512h-640z" />
<path d="M1236.29 0H0v512h1236.29a771.52 771.52 0 000-512z" fill="#a0b4b7" />
</svg>
<div class="profile-photo">
<img class="profile-pic" src = "./user.jpeg" />
</div>
<div class = "Name"> <b>Nishant Kumar Bhardwaj</b> </div>
<div class="bio"> B.tech , NIT Calicut </div>
<div class="posts-hr"></div>
<div class="more-bio">
<div>Connections</div>
<div>Grow your Network</div>
<div>Who viewd your Profile</div>
</div>
<div class="posts-hr"></div>
<div class="pre">
<div class="premium-button"><span class="material-icons">workspace_premium</span> </div>
<div class="more-bio">Try Premium for Free for 1 month</div>
</div>
<div class="posts-hr"></div>
<div class="pre">
<div class="bookmark-button"><span class="material-icons">bookmark</span> </div>
<div class="more-bio">My Items</div>
</div>
</div>
<div class="center">
<div class="create-posts">
<div class="create-post-top">
<img class="post-image" src="./user.jpeg" />
<input placeholder="Start a Post" class="post-input" type="text" />
</div>
<div class="create-post-bottom">
<button class="post-button">
<span class="material-icons blue-button mr-10"> image </span>
Photo
</button>
<button class="post-button">
<span class="material-icons green-button mr-10">
play_circle_filled
</span>
Video
</button>
<button class="post-button">
<span class="material-icons orange-button mr-10"> event </span>
Event
</button>
<button class="post-button">
<span class="material-icons pink-button mr-10"> article </span>
Write Article
</button>
</div>
<div class="posts-hr"></div>
<div class="post">
<div class="post-info">
<img class="post-image" src="./masailogo.jpeg" />
<div class="post-metadata">
<div class="post-creator">Masai School</div>
<div class="faded-text">7,123 followers</div>
<div class="faded-text">
2d • <span class="material-icons faded-text"> public </span>
</div>
</div>
</div>
<div class="post-data">
Here's to all the brilliant Engineers, Designers and Programmers
who made using social media so easy, even kids can do it
effortlessly.
</div>
<div class="read-more">...see more</div>
<div>
<img
class="post-content-image"
src="https://media-exp1.licdn.com/dms/image/C5622AQGV9_HzuD-QwQ/feedshare-shrink_800/0/1625043676570?e=1628121600&v=beta&t=hst84vpnp9U4GErEomeWJfLiAsPSCJXt_a8YNZMSdas"
alt=""
/>
</div>
<div class="center-content">
<span class="material-icons likes"> thumb_up </span>
<span class="no-likes">20</span>
</div>
<div class="likes-hr"></div>
<div class="post-interactions">
<button class="interaction-button">
<span class="material-icons mr-10"> thumb_up </span>Like
</button>
<button class="interaction-button">
<span class="material-icons mr-10"> chat </span>Comment
</button>
<button class="interaction-button">
<span class="material-icons mr-10"> share </span>Share
</button>
<button class="interaction-button">
<span class="material-icons mr-10"> send </span>Send
</button>
</div>
</div>
</div>
</div>
<div class="right">
<div class = "post">
<div class = "Post-info">
Linkedin News
</div>
<div class="post-metadata">
<div class="post-creator">• how to WFH with kids around ?</div>
<div class="faded-text">
2d ago • 1,862 readers
</div>
</div>
<div class="post-metadata">
<div class="post-creator">• Apple pushes back on remote work</div>
<div class="faded-text">
2d ago • 1,523 readers
</div>
</div>
<div class="post-metadata">
<div class="post-creator">• Latest recruiting perk: WFH forever</div>
<div class="faded-text">
1d ago • 523 readers
</div>
</div>
<div class="post-metadata">
<div class="post-creator">• Gates' $2.1B gift for gender equality</div>
<div class="faded-text">
1d ago • 456 readers
</div>
</div>
<div class="post-metadata">
<div class="post-creator">• When job interviews are endless</div>
<div class="faded-text">
1d go • 2,563 readers
</div>
</div>
</div>
<div class = "post">
<div class = "Post-info">
Today's top Courses
</div>
<div class="post-metadata">
<div class="post-creator">1. Speaking Confidently and Effectively</div>
<div class="faded-text">
Pete Mockaitis | How to Be Awsome at Your....
</div>
</div>
<div class="post-metadata">
<div class="post-creator">2. DevOps Foundations </div>
<div class="faded-text">
James Wickett and Ernest Mueller
</div>
</div>
<div class="post-metadata">
<div class="post-creator">3. Unconscious Bias</div>
<div class="faded-text">
Stacey Gordon
</div>
</div>
</div>
</div>
</div>
</body>
</html>
|
/******************************************************************************
*
* Author: Masa Prodanovic
* Copyright (c) 2009, The University of Texas at Austin. All rights reserved.
*
******************************************************************************/
#include <arpa/inet.h>
#define LENGTH 8
#define CSZ sizeof(char)
#define ISZ sizeof(int)
#define UCSZ sizeof(unsigned char)
#define ZIP(fn) "gzip -nf %s",fn
#define UNZIP(raw_fn,uncmp_fn) "gunzip -cf %s > %s",raw_fn,uncmp_fn
#define NO_ZIP 0
#define GZIP 1
#define BZIP2 2
#define Test_endian(test)\
{\
int i = 1;\
test = ( i == htonl(i) ) ? 'E' : 'e';\
}
#define Write_endian(fb)\
{\
char test;\
\
Test_endian(test)\
fwrite(&test,CSZ,1,fb);\
}
/*!
* checkUnzipFile() checks if file has .gz or .bz2 extention and
* uncompresses the file.
*
* Arguments:
* - file_name(in): name of the file
* - pzip_status(out): integer pointer that points to status of the
* file (NO_ZIP, GZIP, BZIP2)
* - pfile_base (out): pointer to string containing the file name base
* (file_name of the uncompressed file, same as the
* file name if there was no compression to begin with).
*
* Return value: none
*
* Notes:
* - There is no attempt to open the file.
* - file_base is allocated to 256 bytes within the function, and needs
* to be freed later on
*
*/
void checkUnzipFile(char *file_name,int *pzip_status,char **pfile_base);
/*! zipFile() compresses the file according to its status and frees
* file_base pointer.
*
* Arguments:
* - file_base(in): name of the uncompressed file
* - zip_status(in): integer compression status of the file
* (NO_ZIP,GZIP,BZIP2)
*
* Return value: none
*
* Notes: In case the status is NO_ZIP, function doesn't do anything.
*/
void zipFile(char *file_base,int zip_status);
/*! Bitpacked segmented volume file syntax
* endian - binary character, 'e': file written on little endian hardware
* 'E': file written on big endian hardware
* nx
* ny
* zs - starting z-slice (convention is to start from 1)
* ze - ending z-slice
* b_nxyz - number of full bytes to store the volume
* n_resid - number of bits used in the last byte of storage required
* b_nxyz + 1 unsigned char containing the bit-packed segmentation
* information for the volume
*/
/* utility functions for reading bitpacked segmented (volume) file
Each voxel information is stored in one bit (NOT byte) of data
*/
void bit2unchar(unsigned char *,unsigned char **,int,int,int *);
void bit2unchar_in_vol1(char *,unsigned char **,int *,int *,int *,int *,
int *,int *);
void bit_in_vol1(char *,int *,int *,int *,int *,int *,int *,unsigned char **);
void bit2unchar(unsigned char *,unsigned char **,int,int,int *);
void set_uncompressed_filename(int, char *,char *);
void cleanup_tmp_files(int,char *);
/* utility functions for writing bitpacked segmented (volume) file */
void bit_out_vol(char *,int,int,int,int,int,int,unsigned char *);
void unchar2bit(unsigned char *,unsigned char **,int,int *,int *);
void unchar2bit_out_vol(char *,unsigned char *,int,int,int,int);
/*! Unsigned array segmented volume file syntax
nx - binary integer (number of voxels in x dir)
ny - binary integer (number of voxels in y dir)
nz - binary integer (number of voxels in z dir)
array of nx*ny*nz unsigned characters (0 and 1)
Packing convention:
for k=1:nz
for j=1:ny
for i=1:nx
store (i,j,k) position information
*/
/* read/write functions for unsigned char segmented (volume) arrays
Note: unlike the segmented files above, these use 1 byte of data
per voxel stored */
void write_segfl_ubc(
unsigned char *seg_data,
int *n,
char *file_name,
int zip_status);
unsigned char *read_segfl_ubc(
char *file_name,
int *grid_dims_ghostbox);
|
package myCat.cat.controller;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import myCat.cat.domain.User;
import myCat.cat.domain.UserRole;
import javax.validation.constraints.NotEmpty;
import java.time.LocalDateTime;
@Getter
@Setter
@NoArgsConstructor
public class UserForm {
@NotEmpty(message = "아이디를 입력하세요")
private String loginId;
@NotEmpty(message = "비밀번호를 입력하세요.")
private String password;
private String passwordCheck;
@NotEmpty(message = "이름을 입력하세요")
private String name;
private String email;
private String nickname;
public User toEntity(String encodedPassword) {
return User.builder()
.loginId(this.loginId)
.password(encodedPassword)
.nickname(this.nickname)
.name(this.name)
.email(this.email)
.role(UserRole.USER)
.registerDate(LocalDateTime.now())
.build();
}
}
|
+++
title = '基环树'
date = 2021-11-16T15:38:25+08:00
draft = false
categories = ['算法']
tags = ['', '']
+++
## 定义
基环树指的是一个 $n$ 个节点,$n$ 条边的联通图。
叫基环树的原因是:给定一棵树,在这棵树上加上 **任意一条边**,就可以形成一个基环树了。
基环树的性质很优秀,比如:
1. 去掉环上的任意一条边,就可以转化为一棵树。
2. 基环树可以看作一个环上挂了很多棵子树,如果将环缩成一个点,那么得到的就是一棵树。
所以基环树的常用套路有:
1. 找环,然后删掉环上的任意一条边 $(u,v)$,对 $u$ 为根的树进行一次树形DP(并强制不选 $u$),再对 $v$ 为根的树进行一次树形DP(并强制不选 $v$)。
2. 将环缩成一个点,然后分类讨论答案是否经过环两种情况。
### 例1 [洛谷P2607 [ZJOI2008]骑士](https://www.luogu.com.cn/problem/P2607)
{{% question 题意 %}}
给定 $n$ 个骑士,每个骑士有一个能力值 $a_i$,和他的一个痛恨的人 $b_i$(痛恨的人不能是自己)。
从这些骑士中选出若干个,使得两两之间没有痛恨的人,求出最大的能力值总和。
其中,$n \leq 10^6$。
{{% /question %}}
{{% fold "题解" %}}
按照每个人 $i$ 与他痛恨的人 $b_i$ 连边,这就可以形成一个基环森林了(由多个基环树组成的森林)。
现在,只考虑一个基环树的话怎么办?
首先发现,如果断开一条边,在树上考虑这个问题的话,就是一个非常简单的树形DP了。
所以我们不妨断开环上的任意一条边 $(u,v)$。
然后以 $u$ 为根,在这个新的树上进行一次树形DP,并强制不选 $u$。
同理,以 $v$ 为根,在这个新的树上进行一次树形DP,并强制不选 $v$。
求两次树形DP得出的最大值即可。
最终答案就是每个基环树求出的最大值之和。
<hr>
找环的话,只要发现一个 backward edge,记录一下这个 edge 的编号 `E`,标记一下 `E` 和 `E^1`,在树形DP中避开这两条边,就可以达到断开边的效果了。这要求我们建图时,使用 `ecnt = 2`。
• 需要格外注意一下,在断边的时候,必须判断当前枚举的边 `e` 是否等于 `E` 或者 `E^1`,而不能判断边的两端端点,这是防止出现 $(1,2), (2,1)$ 这种情况,可以参考[这里](https://www.luogu.com.cn/discuss/39904)。
{{% /fold %}}
{{% fold "代码" %}}
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6+5;
int n, head[maxn], ecnt = 2;
ll a[maxn];
struct Edge {
int to, nxt;
} edges[maxn<<1];
void addEdge(int u, int v) {
Edge e = {v, head[u]};
head[u] = ecnt;
edges[ecnt++] = e;
}
int ed, dep[maxn], par[maxn], E;
void dfs1(int u) {
for (int e = head[u]; e; e = edges[e].nxt) {
int to = edges[e].to;
if (to == par[u]) continue;
if (dep[to]) {
E = e;
} else {
dep[to] = dep[u] + 1;
par[to] = u;
dfs1(to);
}
}
}
ll ans = 0, tot = 0;
ll dp[maxn][2];
void dfs2(int u, int p) {
dp[u][0] = 0;
dp[u][1] = a[u];
for (int e = head[u]; e; e = edges[e].nxt) {
int to = edges[e].to;
if (to == p || e == E || e == (E^1)) continue;
dfs2(to, u);
dp[u][0] += max(dp[to][0], dp[to][1]);
dp[u][1] += dp[to][0];
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
int v;
cin >> a[i] >> v;
addEdge(i,v); addEdge(v,i);
}
for (int u = 1; u <= n; u++) {
if (!dep[u]) {
ans = 0; E = 0;
dep[u] = 1;
dfs1(u);
int c1 = edges[E].to, c2 = edges[E^1].to;
dfs2(c1, 0);
ans = max(ans, dp[c1][0]);
dfs2(c2, 0);
ans = max(ans, dp[c2][0]);
tot += ans;
}
}
cout << tot << endl;
}
```
{{% /fold %}}
### 例2 [洛谷P4381 [IOI2008] Island](https://www.luogu.com.cn/problem/P4381)
{{% question 题意 %}}
给定一个基环树组成的森林,每条边上有边权,求出每个基环树的最长链的长度之和。
最长链的定义为:一条路径,不经过重复的节点。
其中,$n \leq 10^6$。
{{% /question %}}
{{% fold "题解" %}}
既然是基环森林,那就只考虑每个基环树怎么求最长链。
注意到一个基环树由一个环,以及每个环的子树组成,长这样:

所以我们可以讨论这个最长链的位置:
第一种情况:最长链不经过环
这说明最长链完全在一个子树内,那么这就是一个树的直径问题。
第二种情况:最长链经过环
如果经过了环,我们设它从环上的某个点 $u$ 的子树开始,到环上另外一个点 $v$ 的子树结束。
并且设 $dis(u,v)$ 为 $u,v$ 在环上的最长距离,设 $d(u)$ 为 $u$ 的子树最大深度。
所以答案就是
$$\max_{(u,v)}\\{d(u)+d(v)+dis(u,v)\\}$$
但找这样的 $(u,v)$ 是 $O(n^2)$ 的,考虑一下如何优化?
如果我们将一个环 $1,2,3,...,n$ 断开,并复制一份,得到 $1,2,3,...,n,1',2',3',...,n'$,则我们可以快速的算出 $dis(u,v)$。
不妨设 $u<v$,并且求一个距离的前缀和 $a[]$,其中 $a[i]=a[i-1]+w(i-1,i)$。
那么
$$\max_{(u,v)}\\{d(u)+d(v)+dis(u,v)\\}$$
就可以写成
$$\max_{(u,v)}\\{d(u)+d(v)+a[v]-a[u]\\}, u,v\in[1,n] \cup [1',n'], (v-u) \in [1, n-1]$$
当 $v$ 确定时,我们要求的实际上就是
$$\max_u \\{d(u) - a[u]\\}, u \in [v-n+1,v-1]$$
这就是个单调队列优化dp。
{{% /fold %}}
{{% fold "代码" %}}
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6+5;
struct Edge {
int from, to, nxt;
ll w;
} edges[maxn<<1];
int head[maxn], ecnt = 2, in[maxn];
void addEdge(int u, int v, ll w) {
Edge e = {u, v, head[u], w};
head[u] = ecnt;
edges[ecnt++] = e;
}
bool vis[maxn], ring[maxn];
ll ans = 0;
// solve the component containing u
vector<int> ver; // vertex in current component
void bfs(int u) {
vis[u] = 1;
ver.push_back(u);
int p = 0;
while (p < ver.size()) {
int v = ver[p];
for (int e = head[v]; e; e = edges[e].nxt) {
int to = edges[e].to;
if (vis[to]) continue;
vis[to] = 1;
ver.push_back(to);
}
p++;
}
}
ll dep[maxn], maxdep[maxn];
vector<int> tmp; // used for storing leaf
int maxi = 0, n;
int q[maxn<<1], hd, tail, par[maxn];
void bfs2(int u) {
int o = u;
hd = 1, tail = 0;
q[++tail] = u;
par[u] = 0;
dep[u] = 0;
while (hd <= tail) {
u = q[hd]; hd++;
if (dep[u] > dep[maxi]) maxi = u;
for (int e = head[u]; e; e = edges[e].nxt) {
int to = edges[e].to;
if (to == par[u] || ring[to]) continue;
par[to] = u;
q[++tail] = to;
dep[to] = dep[u] + edges[e].w;
}
}
maxdep[o] = dep[maxi];
}
ll md = 0;
void bfs3(int u, int v) {
hd = 1, tail = 0;
q[++tail] = u;
par[u] = 0;
dep[u] = 0;
while (hd <= tail) {
u = q[hd]; hd++;
md = max(md, dep[u]);
for (int e = head[u]; e; e = edges[e].nxt) {
int to = edges[e].to;
if (to == par[u] || (ring[to] && to != v)) continue;
par[to] = u;
q[++tail] = to;
dep[to] = dep[u] + edges[e].w;
}
}
}
vector<int> rings;
bool tag[maxn<<1];
struct Node {
ll a, d;
} nd[maxn<<1];
bool del[maxn];
void solve(int u) {
ver.clear();
tmp.clear();
bfs(u);
ll res = 0;
for (int v : ver) {
if (in[v] == 1) tmp.push_back(v);
}
while (!tmp.empty()) {
int v = tmp.back(); tmp.pop_back();
del[v] = 1;
for (int e = head[v]; e; e = edges[e].nxt) {
int to = edges[e].to;
if (!del[to]) {
in[v]--; in[to]--;
if (in[to] == 1) tmp.push_back(to);
}
}
}
for (int v : ver) {
if (in[v] >= 2) ring[v] = 1; // v is on the ring
}
rings.clear();
int cnt = 0;
for (int v : ver) {
if (ring[v]) {
cnt++;
if (!rings.size()) rings.push_back(v);
maxi = 0;
md = 0;
bfs2(v);
dep[maxi] = 0;
bfs3(maxi, v);
res = max(res, md);
hd = 1, tail = 0;
}
}
// get the ring
if (rings.size()) {
while (rings.size() < cnt) {
int v = rings.back();
for (int e = head[v]; e; e = edges[e].nxt) {
int to = edges[e].to;
if (!ring[to] || (rings.size() > 1 && to == rings[rings.size()-2])) continue;
if (to == rings[0]) {
goto done;
}
rings.push_back(to);
break;
}
}
}
done:;
int ptr = 0;
if (rings.size()) {
rings.push_back(rings.front());
nd[++ptr] = {0, maxdep[rings[0]]};
}
int m = rings.size();
for (int i = 0; i < m-1; i++) {
int v = rings[i];
int v2 = rings[i+1];
for (int e = head[v]; e; e = edges[e].nxt) {
if (edges[e].to == v2 && !tag[e]) {
ll w = edges[e].w;
nd[ptr+1].a = nd[ptr].a + w;
nd[ptr+1].d = maxdep[v2];
ptr++;
tag[e] = tag[e^1] = 1; // 标记边,防止有大小为2的环!
break;
}
}
}
for (int i = 0; i < m-2; i++) {
nd[ptr+1].a = nd[ptr].a + (nd[i+2].a - nd[i+1].a);
nd[ptr+1].d = maxdep[rings[i+1]];
ptr++;
}
hd = 1, tail = 0;
q[++tail] = 1;
m--; // now: m is the size of the ring
for (int i = 2; i <= ptr; i++) {
while (hd <= tail && i - q[hd] >= m) hd++;
if (hd <= tail) {
res = max(res, nd[i].a + nd[i].d + nd[q[hd]].d - nd[q[hd]].a);
}
while (hd <= tail && nd[i].d - nd[i].a >= nd[q[tail]].d - nd[q[tail]].a) tail--;
q[++tail] = i;
}
ans += res;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
int v; ll w; cin >> v >> w;
addEdge(i,v,w); addEdge(v,i,w);
in[i]++; in[v]++;
}
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
solve(i);
}
}
cout << ans << endl;
}
```
{{% /fold %}}
{{% info "注意点" %}}
1. 所有的树上/图上操作(包括找树的直径)都必须用 `bfs` 进行,因为 $n \leq 10^6$,`dfs` 会爆栈。
2. 找环的时候用拓扑排序,不过注意这个是无向图,所以写法略有不同。
3. 找出环以后,要按照**环的顺序**把环断开,不能只考虑哪些节点在环上而不考虑顺序。
4. 一定要注意 **大小为 $2$ 的环**,我们在断环为链的时候不能考虑节点之间的关系,而是要标记 **edge**,因为双向图的缘故,大小为 $2$ 的环之间会有重边,一定要注意!
{{% /info %}}
### 例3 [洛谷P1399 [NOI2013] 快餐店](https://www.luogu.com.cn/problem/P1399)
{{% question 题意 %}}
给定一个 $n$ 个节点,$n$ 条边的无向图(基环树),边上有权值。
现在要在树上找一个位置 $x$,这个位置 $x$ 可以位于**边上的任意一处**,也可以位于**节点**上。
如何选择 $x$ 的位置,使得它到 **所有节点的最短距离的最大值** 最小?输出这个最小值。
形式化的,求:
$$\min_x \\{\max_u\\{dis(x,u)\\}\\}$$
其中,$n \leq 10^5$。
{{% /question %}}
{{% fold "题解" %}}
先考虑,如果这是一棵树的话怎么办?
那我们只要求出这棵树的直径,然后答案就是 直径/2 了。
对于基环树,我们一般都是断环,得到一棵树,那么对于这个题我们有类似的想法:
猜想:环上必然存在一条边,使得这条边断开以后对整个答案没有任何影响。
证明:我们考虑 $x$ 的位置
1. $x$ 在环上
2. $x$ 在一棵子树中
对于第一种情况,我们注意到 $x$ 到所有节点的最短路径中,由环上路径和树内路径组成。
我们只考虑环上的路径(因为我们要证明的是环上的所有边不可能都被用到,至少有一个是用不上的)。
那么问题就相当于,$x$ 到环上所有节点的最短路径,是否存在一条边用不上?
确实如此,因为无论我们怎么画,都会有一条边被断开以后没有任何影响,如图:

• 对于第二种情况也完全一样,所以这个结论是正确的。
<hr>
所以问题就转化成了:
给定一棵基环树,我们现在要断开环上的一条边,求所有断开的方案中,树的直径最小的一个方案,求出最小值?
然后这题就和上一个例子差不多了,一样分类讨论直径在哪:
1. 断开后,树的直径在子树内
2. 断开后,树的直径在原先的环上
对于第一种情况,无论断开哪个都不影响答案,所以对于每个子树统计一下直径即可。
对于第二种情况,上一题的单调队列套路不好使了,我们形式化的描述一下这个问题:
给定一个环 $1,2,...,n$,对于每一种断环方案,都求出:
$$\max_{(u,v)}\\{d(u)+d(v)+dis(u,v)\\}$$
然后取所有断环方案对应的最小值。
这里有了个断环方案要讨论,就变得非常不友好,就算断环成链也没什么思路,我们考虑另外一种方法:

假设我们要断开 $(i,i+1)$,那么此时,这个所求的最大值对应的 $(u,v)$ 有几种情况呢?
1. $(u,v)$ 都在 $[1,i]$ 内。
2. $(u,v)$ 都在 $[i+1,n]$ 内。
3. $u$ 在 $[1,i]$,$v$ 在 $[i+1,n]$。
对于第一种,我们同样用前缀和的方式来看,因为 $dis(u,v) = sum(v) - sum(u)$,所以和上一题一样处理一个前缀和即可,本题甚至都不需要单调队列,维护一下前缀的 `-sum[u] + d[u]` 的最大值即可。
然后我们就可以处理出一个 `pre[]` 数组,`pre[i]` 的意思就是如果 $(u,v)$ 都在 $[1,i]$ 内,可以得到的最大值。
同理对于第二种我们用后缀处理一下即可,可以得到 `suf[]`。
对于第三种,我们可以发现我们所求的 $dis(u,v) + d(u) + d(v)$,等于
<div class='center'>
$u$ 的 **前缀链** + $v$ 的 **后缀链** + $w(n,1)$
</div>

所以我们只要把这个前缀链的最大值 `maxl[i]` 求出即可(同理后缀链最大值也求出 `maxr[]`)。
那么,当我们断开 $(i,i+1)$ 时,就有
$$\max_{(u,v)}\\{d(u)+d(v)+dis(u,v)\\} = \max\\{pre(i), suf(i+1), maxl(i) + maxr(i+1) + w(n,1)\\}$$
然后将 $i$ 从 $1$ 枚举到 $n$ 即可。
{{% /fold %}}
{{% fold "代码" %}}
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+5;
struct Edge {
int from, to, nxt;
ll w;
} edges[maxn<<1];
int head[maxn], ecnt = 2, in[maxn];
void addEdge(int u, int v, ll w) {
Edge e = {u, v, head[u], w};
head[u] = ecnt;
edges[ecnt++] = e;
}
bool ring[maxn];
ll ans = 0;
ll dep[maxn], maxdep[maxn];
vector<int> tmp; // used for storing leaf
int maxi = 0, n;
int q[maxn<<1], hd, tail, par[maxn];
void bfs2(int u) {
int o = u;
hd = 1, tail = 0;
q[++tail] = u;
par[u] = 0;
dep[u] = 0;
while (hd <= tail) {
u = q[hd]; hd++;
if (dep[u] > dep[maxi]) maxi = u;
for (int e = head[u]; e; e = edges[e].nxt) {
int to = edges[e].to;
if (to == par[u] || ring[to]) continue;
par[to] = u;
q[++tail] = to;
dep[to] = dep[u] + edges[e].w;
}
}
maxdep[o] = dep[maxi];
}
ll md = 0;
void bfs3(int u, int v) {
hd = 1, tail = 0;
q[++tail] = u;
par[u] = 0;
dep[u] = 0;
while (hd <= tail) {
u = q[hd]; hd++;
md = max(md, dep[u]);
for (int e = head[u]; e; e = edges[e].nxt) {
int to = edges[e].to;
if (to == par[u] || (ring[to] && to != v)) continue;
par[to] = u;
q[++tail] = to;
dep[to] = dep[u] + edges[e].w;
}
}
}
vector<int> rings;
bool tag[maxn<<1];
struct Node {
ll a, d;
} nd[maxn<<1];
bool del[maxn];
ll maxl[maxn], maxr[maxn], pre[maxn], suf[maxn];
void solve() {
ll res = 0;
for (int v = 1; v <= n; v++) {
if (in[v] == 1) tmp.push_back(v);
}
while (!tmp.empty()) {
int v = tmp.back(); tmp.pop_back();
del[v] = 1;
for (int e = head[v]; e; e = edges[e].nxt) {
int to = edges[e].to;
if (!del[to]) {
in[v]--; in[to]--;
if (in[to] == 1) tmp.push_back(to);
}
}
}
for (int v = 1; v <= n; v++) {
if (in[v] >= 2) ring[v] = 1; // v is on the ring
}
int cnt = 0;
for (int v = 1; v <= n; v++) {
if (ring[v]) {
cnt++;
if (!rings.size()) rings.push_back(v);
maxi = 0;
md = 0;
bfs2(v);
dep[maxi] = 0;
bfs3(maxi, v);
res = max(res, md);
hd = 1, tail = 0;
}
}
// get the ring
if (rings.size()) {
while (rings.size() < cnt) {
int v = rings.back();
for (int e = head[v]; e; e = edges[e].nxt) {
int to = edges[e].to;
if (!ring[to] || (rings.size() > 1 && to == rings[rings.size()-2])) continue;
if (to == rings[0]) {
goto done;
}
rings.push_back(to);
break;
}
}
}
done:;
int ptr = 0;
if (rings.size()) {
rings.push_back(rings.front());
nd[++ptr] = {0, maxdep[rings[0]]};
}
int m = rings.size();
for (int i = 0; i < m-1; i++) {
int v = rings[i];
int v2 = rings[i+1];
for (int e = head[v]; e; e = edges[e].nxt) {
if (edges[e].to == v2 && !tag[e]) {
ll w = edges[e].w;
nd[ptr+1].a = nd[ptr].a + w;
nd[ptr+1].d = maxdep[v2];
ptr++;
tag[e] = tag[e^1] = 1; // 标记边,防止有大小为2的环!
break;
}
}
}
for (int i = 0; i < m-2; i++) {
nd[ptr+1].a = nd[ptr].a + (nd[i+2].a - nd[i+1].a);
nd[ptr+1].d = maxdep[rings[i+1]];
ptr++;
}
hd = 1, tail = 0;
ll R = res;
res = 1e18;
m--; // now: m is the size of the ring
// maxl: record a+d
for (int i = 1; i <= m; i++) maxl[i] = max(maxl[i-1], nd[i].a + nd[i].d);
for (int i = m; i >= 1; i--) maxr[i] = max(maxr[i+1], nd[m+1].a - nd[i].a + nd[i].d);
// pre: record the maximum of two i,j <= pre, which dis(i,j) + d[i] + d[j] is maximum (just record minimum of -a + d)
ll mn = 0;
for (int i = 1; i <= m; i++) {
pre[i] = max(pre[i-1], mn + nd[i].a + nd[i].d);
mn = max(mn, -nd[i].a + nd[i].d);
}
mn = 0;
for (int i = m; i >= 1; i--) {
suf[i] = max(suf[i+1], mn + nd[m+1].a - nd[i].a + nd[i].d);
mn = max(mn, -(nd[m+1].a - nd[i].a) + nd[i].d);
}
for (int i = 1; i <= m; i++) { // break (i,i+1)
ll r1 = 0, r2 = 0;
r1 = max(pre[i], suf[i+1]);
r2 = maxl[i] + maxr[i+1];
res = min(res, max(r1,r2));
}
ans += max(R, res);
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
int u,v; ll w; cin >> u >> v >> w;
addEdge(u,v,w); addEdge(v,u,w);
in[u]++; in[v]++;
}
solve();
printf("%.1f\n",(double)(ans)*0.5);
}
```
{{% /fold %}}
### 例4 BAPC2022H. [House Numbering](https://codeforces.com/group/ItWAIIIbNw/contest/426004/problem/H)
{{% question 题意 %}}
给定一个 $n$ 个点,$n$ 条边的联通无向图。
每条边有一个权值 $w$,意味着这条边的两端需要分别标上 $1,w$ 或者 $w,1$。
问是否存在一种方案,使得所有点的边上没有被标上相同的元素。有,则输出方案。
其中,$n \leq 10^5$,所有边的 $w > 1$。

如图,这就是一种合理标号方式,其中 $w_{1,2}=2, w_{2,3}=9, w_{1,3}=3$。
{{% /question %}}
{{% fold "题解" %}}
首先注意这是一个基环树。所以要围绕环做文章。
经过一段时间的观察后可以发现,如果我们把这个看作一个有向图,箭头指向的点会获得这个边的 $1$,另外一个点获得 $w$,那么所有不在环上的,都应该是向外指的。
因为一旦有一个向内指的,环上一旦出现一个来自于树的 $1$,那么就不成立了。
所以不在环上的部分都可以决定了。
剩下的只有环了。
可以发现环要么是顺时针指,要么是逆时针指,所以只要判断这两个情况就行。

{{% /fold %}}
{{% fold "代码" %}}
```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+5;
int n;
struct Edge {
int to, nxt, w;
int idx;
} edges[maxn<<1];
int head[maxn], ecnt = 2;
void addEdge(int u, int v, int w, int idx) {
Edge e = {v, head[u], w, idx};
head[u] = ecnt;
edges[ecnt++] = e;
}
bool iscycle[maxn];
bool vis[maxn];
int cu, cv, cidx, pre[maxn];
bool found = 0;
void dfs(int u) {
vis[u] = 1;
for (int e = head[u]; e; e = edges[e].nxt) {
int v = edges[e].to, w = edges[e].w;
if (v == pre[u]) continue;
if (vis[v]) {
if (found) return;
found = 1;
int cur = u;
while (cur != v) {
iscycle[cur] = 1;
cur = pre[cur];
}
iscycle[v] = 1;
cu = u, cv = v;
cidx = edges[e].idx;
} else {
pre[v] = u;
dfs(v);
}
}
}
int ans[maxn];
void dfs2(int u, int p, int f) {
vis[u] = 1;
for (int e = head[u]; e; e = edges[e].nxt) {
int v = edges[e].to, w = edges[e].w, idx = edges[e].idx;
if (v == p) continue;
if (vis[v]) {
if (!found) ans[idx] = (f ? u : v), found = 1;
continue;
}
if (!iscycle[v]) { // then must point to v
ans[idx] = v;
} else {
assert(iscycle[u] && iscycle[v]);
if (f) {
ans[idx] = u;
} else {
ans[idx] = v;
}
}
dfs2(v, u, f);
}
}
bool check() {
for (int u = 1; u <= n; u++) {
set<int> se;
int cnt = 0;
for (int e = head[u]; e; e = edges[e].nxt) {
int v = edges[e].to, w = edges[e].w, idx = edges[e].idx;
if (ans[idx] == u) se.insert(1);
else se.insert(w);
cnt++;
}
if (se.size() != cnt) return 0;
}
return 1;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
int u,v,w; cin >> u >> v >> w;
addEdge(u,v,w,i);
addEdge(v,u,w,i);
}
dfs(1);
memset(vis, 0, sizeof(vis));
found = 0;
dfs2(cu, -1, 0); // start with any point on the cycle
if (check()) {
for (int i = 1; i <= n; i++) cout << ans[i] << " ";
cout << "\n";
return 0;
}
memset(vis, 0, sizeof(vis));
found = 0;
dfs2(cu, -1, 1); // start with any point on the cycle
if (check()) {
for (int i = 1; i <= n; i++) cout << ans[i] << " ";
cout << "\n";
return 0;
}
cout << "impossible\n";
}
```
{{% /fold %}}
|
use std::fs;
fn main() {
let input = fs::read_to_string("input.txt").unwrap();
let height = input.lines().count();
let width = input.lines().next().unwrap().chars().count();
let image = Image::new(height, width, &input);
let empty_cols = image
.cols()
.enumerate()
.filter_map(|(x, mut col)| {
if !col.any(|is_galaxy| is_galaxy) {
Some(x)
} else {
None
}
})
.collect::<Vec<_>>();
let empty_rows = image
.rows()
.enumerate()
.filter_map(|(y, mut row)| {
if !row.any(|is_galaxy| is_galaxy) {
Some(y)
} else {
None
}
})
.collect::<Vec<_>>();
let galaxies = image
.iter()
.filter(|(_pos, is_galaxy)| *is_galaxy)
.collect::<Vec<_>>();
let total_dist: usize = PairsIter::new(&galaxies)
.map(|((a, _), (b, _))| {
let x_range = if a.0 > b.0 { b.0..a.0 } else { a.0..b.0 };
let y_range = if a.1 > b.1 { b.1..a.1 } else { a.1..b.1 };
let x_num = empty_cols.iter().filter(|x| x_range.contains(*x)).count() * (1000000 - 1);
let y_num = empty_rows.iter().filter(|y| y_range.contains(*y)).count() * (1000000 - 1);
(x_range.end - x_range.start + x_num) + (y_range.end - y_range.start + y_num)
})
.sum();
dbg!(total_dist);
}
struct PairsIter<'a, T> {
slice: &'a [T],
current_index: usize,
sub_index: usize,
}
impl<'a, T> PairsIter<'a, T> {
fn new(slice: &'a [T]) -> Self {
Self {
slice,
current_index: 0,
sub_index: 1,
}
}
}
impl<'a, T> Iterator for PairsIter<'a, T> {
type Item = (&'a T, &'a T);
fn next(&mut self) -> Option<Self::Item> {
if self.current_index >= self.slice.len() - 1 {
return None;
}
let res = (&self.slice[self.current_index], &self.slice[self.sub_index]);
self.sub_index += 1;
if self.sub_index >= self.slice.len() {
self.current_index += 1;
self.sub_index = self.current_index + 1;
}
Some(res)
}
}
struct Image {
width: usize,
height: usize,
image: Vec<bool>,
}
struct ImageIter<'a> {
image: &'a Image,
x: usize,
y: usize,
}
impl<'a> Iterator for ImageIter<'a> {
type Item = ((usize, usize), bool);
fn next(&mut self) -> Option<Self::Item> {
if self.y >= self.image.height {
None
} else {
let res = ((self.x, self.y), self.image.get((self.x, self.y)));
self.x += 1;
if self.x >= self.image.width {
self.x = 0;
self.y += 1;
}
Some(res)
}
}
}
impl Image {
fn new(height: usize, width: usize, input: &str) -> Self {
Self {
width,
height,
image: input
.replace('\n', "")
.chars()
.map(|char| char == '#')
.collect(),
}
}
fn get(&self, (x, y): (usize, usize)) -> bool {
self.image[y * self.width + x]
}
fn rows(&self) -> ImageRowIter<'_> {
ImageRowIter { image: &self, y: 0 }
}
fn cols(&self) -> ImageColIter<'_> {
ImageColIter { image: &self, x: 0 }
}
fn iter(&self) -> ImageIter<'_> {
ImageIter {
image: &self,
x: 0,
y: 0,
}
}
}
pub struct ImageRowIter<'a> {
image: &'a Image,
y: usize,
}
pub struct ImageRowIterIndividual<'a> {
image: &'a Image,
y: usize,
x: usize,
}
impl<'a> Iterator for ImageRowIter<'a> {
type Item = ImageRowIterIndividual<'a>;
fn next(&mut self) -> Option<Self::Item> {
if self.y >= self.image.height {
None
} else {
let res = Some(ImageRowIterIndividual {
image: self.image,
y: self.y,
x: 0,
});
self.y += 1;
res
}
}
}
impl<'a> Iterator for ImageRowIterIndividual<'a> {
type Item = bool;
fn next(&mut self) -> Option<Self::Item> {
if self.x >= self.image.width {
None
} else {
let res = Some(self.image.get((self.x, self.y)));
self.x += 1;
res
}
}
}
pub struct ImageColIter<'a> {
image: &'a Image,
x: usize,
}
pub struct ImageColIterIndividual<'a> {
image: &'a Image,
y: usize,
x: usize,
}
impl<'a> Iterator for ImageColIter<'a> {
type Item = ImageColIterIndividual<'a>;
fn next(&mut self) -> Option<Self::Item> {
if self.x >= self.image.width {
None
} else {
let res = Some(ImageColIterIndividual {
image: self.image,
y: 0,
x: self.x,
});
self.x += 1;
res
}
}
}
impl<'a> Iterator for ImageColIterIndividual<'a> {
type Item = bool;
fn next(&mut self) -> Option<Self::Item> {
if self.y >= self.image.height {
None
} else {
let res = Some(self.image.get((self.x, self.y)));
self.y += 1;
res
}
}
}
|
package com.raw.scraper.service;
import com.raw.scraper.constant.NepalState;
import com.raw.scraper.model.GetRollRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
@Service
public class NepalVoterListClient {
public static final String INDEX_PROCESS_1_PHP = "/index_process_1.php";
public static final String VIEW_WARD_1_PHP = "/view_ward_1.php";
private final WebClient webClient;
NepalVoterListClient() {
this.webClient = createWebClient();
}
private WebClient createWebClient() {
final int size = 16 * 1024 * 1024;
final ExchangeStrategies strategies =
ExchangeStrategies.builder()
.codecs(codecs -> codecs.defaultCodecs().maxInMemorySize(size))
.build();
return WebClient.builder()
.baseUrl("https://voterlist.election.gov.np/bbvrs1")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.exchangeStrategies(strategies)
.build();
}
public String getDistrictsByState(NepalState nepalState) {
return webClient
.post()
.uri(uriBuilder -> uriBuilder.path(INDEX_PROCESS_1_PHP).build())
.accept(MediaType.APPLICATION_JSON)
.body(
BodyInserters.fromFormData("state", String.valueOf(nepalState.getKey()))
.with("list_type", "district"))
.retrieve()
.bodyToMono(String.class)
.block(Duration.of(10, ChronoUnit.SECONDS));
}
public String getVdcListByDistrict(int district) {
return webClient
.post()
.uri(uriBuilder -> uriBuilder.path(INDEX_PROCESS_1_PHP).build())
.accept(MediaType.APPLICATION_JSON)
.body(
BodyInserters.fromFormData("district", String.valueOf(district))
.with("list_type", "vdc"))
.retrieve()
.bodyToMono(String.class)
.block(Duration.of(10, ChronoUnit.SECONDS));
}
public String getWardsByVdc(int vdc) {
return webClient
.post()
.uri(uriBuilder -> uriBuilder.path(INDEX_PROCESS_1_PHP).build())
.accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromFormData("vdc", String.valueOf(vdc)).with("list_type", "ward"))
.retrieve()
.bodyToMono(String.class)
.block(Duration.of(10, ChronoUnit.SECONDS));
}
public String getRegistrationCentersByWardAndVdc(int vdc, int ward) {
return webClient
.post()
.uri(uriBuilder -> uriBuilder.path(INDEX_PROCESS_1_PHP).build())
.accept(MediaType.APPLICATION_JSON)
.body(
BodyInserters.fromFormData("vdc", String.valueOf(vdc))
.with("ward", String.valueOf(ward))
.with("list_type", "reg_centre"))
.retrieve()
.bodyToMono(String.class)
.block(Duration.of(10, ChronoUnit.SECONDS));
}
public String getVoterRoll(GetRollRequest getRollRequest) {
return webClient
.post()
.uri(uriBuilder -> uriBuilder.path(VIEW_WARD_1_PHP).build())
.accept(MediaType.TEXT_HTML)
.body(
BodyInserters.fromFormData("state", String.valueOf(getRollRequest.getState().getKey()))
.with("district", String.valueOf(getRollRequest.getDistrict().getKey()))
.with("vdc_mun", String.valueOf(getRollRequest.getVdc().getKey()))
.with("ward", String.valueOf(getRollRequest.getWard().getKey()))
.with("reg_centre", String.valueOf(getRollRequest.getRegCenter().getKey())))
.retrieve()
.bodyToMono(String.class)
.block(Duration.of(30, ChronoUnit.SECONDS));
}
}
|
<!DOCTYPE html>
<html lang="ko">
<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>Animation</title>
<style>
*{margin: 0; padding: 0;}
.box{
width: 300px;
height: 300px;
background-color: teal;
animation-name: move;
/* =>애니메이션 이름 */
animation-duration: 2s;
/* =>애니메이션 재생시간 */
animation-delay: 1s;
/* =>애니메이션 지연시간 */
animation-iteration-count: infinite;
/* =>반복횟수 (infinite는 무한으로 반복) */
animation-direction: alternate;
/* =>애니메이션 방향(alternate값을 제일 많이 사용) */
animation-fill-mode: forwards;
/* =>애니메이션 마지막 위치에서 멈춤*/
}
@keyframes move {
0%{
transform: translate(0,0);
}
50%{
transform: translate(300px,300px) rotate(360deg);
}
100%{
background-color: gold;
transform: translate(600px,0);
}
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
|
//package LoginScenario;
//
//import org.openqa.selenium.WebDriver;
//import org.openqa.selenium.WebElement;
//import org.openqa.selenium.support.FindBy;
//import org.openqa.selenium.support.PageFactory;
//
//public class NaukriHomepage {
//
// WebDriver driver;
//
// @FindBy(xpath = "//img[@alt='naukri user profile img']")
// WebElement profileImg;
//
// @FindBy(xpath = "//a[text()='View & Update Profile']")
// WebElement viewAndUpdate;
//
//
// public NaukriHomepage(WebDriver driver) {
// this.driver = driver;
// PageFactory.initElements(driver, this);
// }
//
//
// public void clickOnProfileimg() {
// profileImg.click();
// }
//
// public void clickOnViewAndUpdate() {
// viewAndUpdate.click();
// }
//
//
// public String verifyNaukriHomepageLink() {
// return driver.getCurrentUrl();
// }
//
//}
package LoginScenario;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class NaukriHomepage {
WebDriver driver;
@FindBy(xpath = "//img[@alt='naukri user profile img']")
WebElement profileImg;
@FindBy(xpath = "//a[text()='View & Update Profile']")
WebElement viewAndUpdate;
public NaukriHomepage(WebDriver driver) {
this.driver = driver; // Initialize the driver
PageFactory.initElements(driver, this);
}
public void clickOnProfileimg() {
profileImg.click();
}
public void clickOnViewAndUpdate() {
viewAndUpdate.click();
}
public String verifyNaukriHomepageLink() {
return driver.getCurrentUrl();
}
}
|
<?php
// URL Shortener prototype
// --------------------------------------------------------------------------
// Database Connection
// --------------------------------------------------------------------------
require_once('../config/db_info.php') ;
$db = new PDO("mysql:host={$db_host};dbname={$db_name}", $db_user, $db_password);
// URLからショートコードに該当する部分を抜き出す
// --------------------------------------------------------------------------
if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) {
$request_uri = $_SERVER['REQUEST_URI'];
if (preg_match('/^\/([a-zA-Z0-9]+)$/', $request_uri, $matches)) {
$short_code = $matches[1];
} else {
$error_message = "short code you specified is invalid.";
}
} else {
$error_message = "short code you specified is invalid.";
}
// exit program when short code is invalid.
if (isset($error_message)) {
header('HTTP/1.0 400 Bad Request');
echo $error_message;
exit();
}
// Insert Access Log
// --------------------------------------------------------------------------
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$ip_address = $_SERVER['REMOTE_ADDR'];
$stmt = $db->prepare("INSERT INTO access_logs (short_code, user_agent, ip_address) VALUES (:short_code, :user_agent, :ip_address)");
$stmt->bindParam(':short_code', $short_code);
$stmt->bindParam(':user_agent', $user_agent);
$stmt->bindParam(':ip_address', $ip_address);
$stmt->execute();
// Search short code from urls table
// --------------------------------------------------------------------------
$stmt = $db->prepare("SELECT * FROM urls WHERE short_code = :short_code");
$stmt->bindParam(":short_code", $short_code);
$stmt->execute();
$result = $stmt->fetchAll();
// Redirect URL
// --------------------------------------------------------------------------
if (count($result) >0 ) {
// EXIST:SHORT CODE
$url = $result[0]['url'];
header("Location: {$url}");
exit;
} else {
// MISS :SHORT CODE
header('HTTP/1.0 400 Bad Request');
echo "Short code you specified is missing";
exit;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using GymManegmentApplication.Contracts.Infrastructures;
using GymManegmentApplication.Contracts.Presistance;
using GymManegmentApplication.DTOs.MemberDTOs.Validation;
using GymManegmentApplication.Exceptions;
using GymManegmentApplication.Features.Member.Request.Command;
using GymManegmentApplication.Model;
using GymManegmentApplication.Response;
using Humanizer;
using MediatR;
namespace GymManegmentApplication.Features.Member.Handler.Command
{
public class CreateMemberCommandHandler : IRequestHandler<CreatememberCommand, BaseCommonResponse>
{
#region Constructor
private readonly IMemberRepository _memberRepository;
private readonly IMapper _mapper;
private readonly IEmailSender _emailSender;
public CreateMemberCommandHandler(IMemberRepository memberRepository, IMapper mapper, IEmailSender emailSender)
{
_memberRepository = memberRepository;
_mapper = mapper;
_emailSender = emailSender;
}
#endregion
public async Task<BaseCommonResponse> Handle(CreatememberCommand request, CancellationToken cancellationToken)
{
var response = new BaseCommonResponse();
var validation = new CreateMemberValidation(_memberRepository);
var validator = await validation.ValidateAsync(request.CreateMemberDto);
if (validator.IsValid == false)
{
response.IsSuccess = false;
response.Message = "Creation Filed";
response.Errors = validator.Errors.Select(q => q.ErrorMessage).ToList();
}
else
{
var member = _mapper.Map<GymManegmentSystemDomin.Entity.Member.Member>(request.CreateMemberDto);
member = await _memberRepository.Add(member);
//Sending email or SMS For client
var email = new Email()
{
To = "[email protected]",
Body = $"Dear {request.CreateMemberDto.FirstName} {request.CreateMemberDto.LastName} " +
$"Your are registered successfully . Your membership started from {DateTime.Now} ",
Subject = "You Are Registered successfully !!!"
};
response.Id = member.Id;
response.Message = "member Created Successfully";
response.IsSuccess = true;
}
return response;
}
}
}
|
<?php
namespace App\Transformers;
use App\Models\Admin;
use Flugg\Responder\Transformers\Transformer;
class AdminTransformer extends Transformer
{
/**
* List of available relations.
*
* @var string[]
*/
protected $relations = [];
/**
* List of autoloaded default relations.
*
* @var array
*/
protected $load = [];
/**
* Transform the model.
*
* @param \App\Models\Admin $admin
* @return array
*/
public function transform(Admin $admin)
{
return [
'id' => (int) $admin->id,
'name' => (string) $admin->name,
'email' => (string) $admin->email,
'role' => [
'key' => $admin->role->key,
'value' => $admin->role->value,
'description' => $admin->role->description,
'color' => $admin->role->color,
],
];
}
}
|
package com.project.credit;
import com.project.credit.card.entity.CreditCard;
import com.project.credit.card.entity.CreditCardRequest;
import com.project.credit.card.exception.CardException;
import com.project.credit.card.exception.CreditCardRequestException;
import com.project.credit.card.service.CreditCardService;
import com.project.credit.customer.entity.Customer;
import com.project.credit.customer.exception.CustomerException;
import com.project.credit.customer.service.CustomerService;
import com.project.credit.merchant.entity.Merchant;
import com.project.credit.merchant.exception.MerchantException;
import com.project.credit.merchant.service.MerchantService;
import com.project.credit.transaction.dto.TransactionRequestDto;
import com.project.credit.transaction.entity.Transaction;
import com.project.credit.transaction.exception.DateException;
import com.project.credit.transaction.exception.TransactionException;
import com.project.credit.transaction.service.TransactionService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Date;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@SpringBootTest
@Transactional
class TransactionServiceTests {
@Autowired
private CustomerService customerService;
@Autowired
private CreditCardService creditCardService;
@Autowired
private MerchantService merchantService;
@Autowired
private TransactionService transactionService;
Customer customer = new Customer("John Doe", "[email protected]", "Ninja@2002", "6234567890", "123 Main St", Date.valueOf(LocalDate.now().minusYears(20)), 2000000.0);
Merchant merchant = new Merchant("Amazon", "0000000000000000");
CreditCardRequest creditCardRequest = null;
CreditCard creditCard = null;
TransactionRequestDto transactionRequestDto = null;
@BeforeEach
public void init() throws CustomerException, MerchantException, CreditCardRequestException, CardException, DateException, TransactionException {
customerService.saveCustomer(customer);
merchantService.saveMerchant(merchant);
creditCardRequest = creditCardService.requestCard(customer.getCustomerId());
creditCard = creditCardService.validateCreditCardRequest(creditCardRequest.getCreditCardRequestId());
transactionRequestDto = new TransactionRequestDto(customer.getCreditCard().getCardNumber(), "John Doe", creditCard.getValidUpto(), customer.getCreditCard().getCvv(), "0000000000000000", "Amazon", "Test Transaction", "Test Transaction Description", 100.0);
}
@AfterEach
public void cleanUp() throws CustomerException, CardException, MerchantException, CreditCardRequestException {
creditCardService.deleteCreditCardByCardNumber(creditCard.getCardNumber());
creditCardService.deleteCreditCardRequestById(creditCardRequest.getCreditCardRequestId());
customerService.deleteCustomerById(customer.getCustomerId());
merchantService.deleteMerchantById(merchant.getMerchantId());
}
@Test
void testTransferAmount() throws MerchantException, TransactionException, CardException {
Transaction transaction = transactionService.transferAmount(transactionRequestDto);
Assertions.assertEquals(Transaction.class, transaction.getClass());
transactionService.deleteTransactionById(transaction.getTransactionId());
}
@Test
void testTransferAmountWithNullTransactionDto() {
TransactionRequestDto transactionRequestDto = this.transactionRequestDto;
this.transactionRequestDto = null;
Assertions.assertThrows(TransactionException.class, () -> transactionService.transferAmount(this.transactionRequestDto));
this.transactionRequestDto = transactionRequestDto;
}
@Test
void testTransferAmountWithNullFromCardNumber() {
String fromCardNumber = transactionRequestDto.getCustomerCreditCardNumber();
transactionRequestDto.setCustomerCreditCardNumber(null);
Assertions.assertThrows(TransactionException.class, () -> transactionService.transferAmount(transactionRequestDto));
transactionRequestDto.setCustomerCreditCardNumber(fromCardNumber);
}
@Test
void testTransferAmountWithNullToCardNumber() {
String toCardNumber = transactionRequestDto.getMerchantCardNumber();
transactionRequestDto.setMerchantCardNumber(null);
Assertions.assertThrows(TransactionException.class, () -> transactionService.transferAmount(transactionRequestDto));
transactionRequestDto.setMerchantCardNumber(toCardNumber);
}
@Test
void testTransferAmountWithNullAmount() {
Double amount = transactionRequestDto.getAmount();
transactionRequestDto.setAmount(null);
Assertions.assertThrows(TransactionException.class, () -> transactionService.transferAmount(transactionRequestDto));
transactionRequestDto.setAmount(amount);
}
@Test
void testTransferAmountWithNullCardHolderName() {
String fromCardHolderName = transactionRequestDto.getCustomerName();
transactionRequestDto.setCustomerName(null);
Assertions.assertThrows(TransactionException.class, () -> transactionService.transferAmount(transactionRequestDto));
transactionRequestDto.setCustomerName(fromCardHolderName);
}
@Test
void testTransferAmountWithNullExpiryDate() {
Date expiryDate = transactionRequestDto.getValidUpto();
transactionRequestDto.setExpiryDate((Date) null);
Assertions.assertThrows(TransactionException.class, () -> transactionService.transferAmount(transactionRequestDto));
transactionRequestDto.setExpiryDate(expiryDate);
}
@Test
void testTransferAmountWithNullCvv() {
Integer cvv = transactionRequestDto.getCvv();
transactionRequestDto.setCvv(null);
Assertions.assertThrows(TransactionException.class, () -> transactionService.transferAmount(transactionRequestDto));
transactionRequestDto.setCvv(cvv);
}
@Test
void testTransferAmountWithExpiredDate() {
Date expiryDate = transactionRequestDto.getValidUpto();
transactionRequestDto.setExpiryDate(Date.valueOf(LocalDate.now().minusYears(1)));
Assertions.assertThrows(CardException.class, () -> transactionService.transferAmount(transactionRequestDto));
transactionRequestDto.setExpiryDate(expiryDate);
}
@Test
void testTransferAmountWithExcessAmount() {
Double amount = transactionRequestDto.getAmount();
transactionRequestDto.setAmount(creditCard.getCurrentLimit() + 100);
Assertions.assertThrows(TransactionException.class, () -> transactionService.transferAmount(transactionRequestDto));
transactionRequestDto.setAmount(amount);
}
@Test
void testTransferAMountWithInvalidCustomerName() {
String fromCardHolderName = transactionRequestDto.getCustomerName();
transactionRequestDto.setCustomerName("Jane Doe");
Assertions.assertThrows(TransactionException.class, () -> transactionService.transferAmount(transactionRequestDto));
transactionRequestDto.setCustomerName(fromCardHolderName);
}
@Test
void testTransferAmountWithInvalidCvv() {
Integer cvv = transactionRequestDto.getCvv();
transactionRequestDto.setCvv(creditCard.getCvv() + 1);
Assertions.assertThrows(TransactionException.class, () -> transactionService.transferAmount(transactionRequestDto));
transactionRequestDto.setCvv(cvv);
}
@Test
void testTransferAmountWithInactiveCard() throws CardException {
creditCard.setCardCreatedOn(new Date(System.currentTimeMillis() + 100000));
creditCardService.updateCreditCard(creditCard);
Assertions.assertThrows(CardException.class, () -> transactionService.transferAmount(transactionRequestDto));
creditCard.setCardCreatedOn(Date.valueOf(LocalDate.now().minusYears(1)));
creditCardService.updateCreditCard(creditCard);
}
@Test
void testAddTransaction() throws MerchantException, TransactionException, CardException {
Transaction transaction = transactionService.transferAmount(transactionRequestDto);
Assertions.assertEquals(transaction, transactionService.addTransaction(transaction));
transactionService.deleteTransactionById(transaction.getTransactionId());
}
@Test
void testAddTransactionWithNullTransaction() {
Assertions.assertThrows(TransactionException.class, () -> transactionService.addTransaction(null));
}
@Test
void testGetTransactionById() throws MerchantException, TransactionException, CardException {
Transaction transaction = transactionService.transferAmount(transactionRequestDto);
Assertions.assertEquals(transaction, transactionService.getTransactionById(transaction.getTransactionId()));
transactionService.deleteTransactionById(transaction.getTransactionId());
}
@Test
void testGetTransactionByIdWithInvalidId() {
Assertions.assertThrows(TransactionException.class, () -> transactionService.getTransactionById(0L));
}
@Test
void testGetAllTransactions() throws MerchantException, TransactionException, CardException {
Transaction transaction1 = transactionService.transferAmount(transactionRequestDto);
Transaction transaction2 = transactionService.transferAmount(transactionRequestDto);
Assertions.assertEquals(ArrayList.class, transactionService.getAllTransactions().getClass());
transactionService.deleteTransactionById(transaction1.getTransactionId());
transactionService.deleteTransactionById(transaction2.getTransactionId());
}
@Test
void testGetAllTransactionsByCardNumber() throws MerchantException, TransactionException, CardException {
Transaction transaction1 = transactionService.transferAmount(transactionRequestDto);
Transaction transaction2 = transactionService.transferAmount(transactionRequestDto);
List<Transaction> expectedTransactions = Arrays.asList(transaction1, transaction2);
List<Transaction> actualTransactions = transactionService.getAllTransactionsByCustomerCreditCardNumber(transactionRequestDto.getCustomerCreditCardNumber());
Assertions.assertIterableEquals(expectedTransactions, actualTransactions);
transactionService.deleteTransactionById(transaction1.getTransactionId());
transactionService.deleteTransactionById(transaction2.getTransactionId());
}
@Test
void testGetAllTransactionsByCardNumberWithNoTransactions() {
Assertions.assertThrows(TransactionException.class, () -> transactionService.getAllTransactionsByCustomerCreditCardNumber(customer.getCreditCard().getCardNumber()));
}
@Test
void testGetAllTransactionsByCardNumberForParticularDuration() throws MerchantException, TransactionException, CardException, DateException {
Transaction transaction1 = transactionService.transferAmount(transactionRequestDto);
Transaction transaction2 = transactionService.transferAmount(transactionRequestDto);
List<Transaction> transactions = transactionService.getAllTransactionsByCustomerCreditCardNumberForParticularDuration(transactionRequestDto.getCustomerCreditCardNumber(), Date.valueOf(LocalDate.now()), Date.valueOf(LocalDate.now()));
Assertions.assertEquals(ArrayList.class, transactions.getClass());
transactionService.deleteTransactionById(transaction1.getTransactionId());
transactionService.deleteTransactionById(transaction2.getTransactionId());
}
@Test
void testGetAllTransactionsByCardNumberForParticularDurationWithNoTransactions() {
Assertions.assertThrows(TransactionException.class, () -> transactionService.getAllTransactionsByCustomerCreditCardNumberForParticularDuration(customer.getCreditCard().getCardNumber(), Date.valueOf(LocalDate.now()), Date.valueOf(LocalDate.now())));
}
@Test
void testGetAllTransactionsByCardNumberForParticularDurationWithNullDates() {
Assertions.assertThrows(DateException.class, () -> transactionService.getAllTransactionsByCustomerCreditCardNumberForParticularDuration(customer.getCreditCard().getCardNumber(), null, null));
}
@Test
void testGetAllTransactionsByCardNumberForParticularDurationWithInvalidDates() {
Assertions.assertThrows(DateException.class, () -> transactionService.getAllTransactionsByCustomerCreditCardNumberForParticularDuration(customer.getCreditCard().getCardNumber(), Date.valueOf(LocalDate.now()), Date.valueOf(LocalDate.now().minusDays(1))));
}
@Test
void testDeleteTransactionById() throws MerchantException, TransactionException, CardException {
Transaction transaction = transactionService.transferAmount(transactionRequestDto);
Assertions.assertEquals(transaction, transactionService.deleteTransactionById(transaction.getTransactionId()));
}
@Test
void testDeleteTransactionByIdWithInvalidId() {
Assertions.assertThrows(TransactionException.class, () -> transactionService.deleteTransactionById(0L));
}
}
|
import java.util.*;
/**
* Iterative solution
*
* This solution uses the exactly same idea sol1 does, but converting it to iterative version.
* In recursive, we can modify the temp list then reset it back to make temp list clean to next loop
* But in iterative solution, we couldn't do that. So we have to copy the temp list twice to make it clean to next loop.
* Therefore, even though the algorithm is exactly same, the speed of sol2 is slower than sol1
*
* @author hpPlayer
* @date Oct 14, 2015 1:43:57 PM
*/
public class Factor_Combinations_p254_sol2 {
private class MyNode{
int n;
int start;
List<Integer> list;
private MyNode(int n, int start, List<Integer> list){
this.n = n;
this.start = start;
this.list = list;
}
}
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Stack<MyNode> stack = new Stack<MyNode>();
stack.push( new MyNode(n, 2, new ArrayList<Integer>()) );
while(!stack.isEmpty()){
MyNode node = stack.pop();
List<Integer> temp = node.list;
int start = node.start;
int newN = node.n;
for(int i = start; i * i <= newN; i++){
if(newN%i != 0) continue;
List<Integer> curr = new ArrayList<Integer>(temp);
curr.add(i);
curr.add(newN/i);
result.add(curr);
//we have to fix the list, so we need a new list in each MyNode
List<Integer> newList = new ArrayList<Integer>(temp);
newList.add(i);
stack.push(new MyNode(newN/i, i, newList));
}
}
return result;
}
}
|
package com.babylon.wallet.android.data.transaction
import android.util.Log
import com.babylon.wallet.android.domain.usecases.transaction.SignRequest
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import rdx.works.core.blake2Hash
import rdx.works.core.decodeHex
import rdx.works.core.toHexString
import java.io.File
internal class ROLAPayloadTest {
private lateinit var testVectors: List<TestVector>
private val json = Json {
prettyPrint = true
}
/**
* make sure our code generates identical test vectors to iOS, see @see ROLAClientTests.omit_test_generate_rola_payload_hash_vectors
*/
@Before
fun setUp() {
val testVectorsFile = File("src/test/resources/raw/rola_challenge_payload_hash_vectors.json")
if (testVectorsFile.exists()) {
testVectors = json.decodeFromString(testVectorsFile.readText())
} else {
val origins = listOf("https://dashboard.rdx.works", "https://stella.swap", "https://rola.xrd")
val accounts = listOf(
"account_sim1cyvgx33089ukm2pl97pv4max0x40ruvfy4lt60yvya744cve475w0q",
"account_sim1cyzfj6p254jy6lhr237s7pcp8qqz6c8ahq9mn6nkdjxxxat5syrgz9",
"account_sim168gge5mvjmkc7q4suyt3yddgk0c7yd5z6g662z4yc548cumw8nztch"
)
testVectors = origins.flatMap { origin ->
accounts.flatMap { accountAddress ->
(0 until 10).map { seed ->
val challenge = (origin.toByteArray() + accountAddress.toByteArray() + seed.toUByte().toByte()).blake2Hash()
val payloadHex = SignRequest.SignAuthChallengeRequest(challenge.toHexString(), origin, accountAddress).payloadHex
val blakeHashOfPayload = payloadHex.decodeHex().blake2Hash().toHexString()
TestVector(payloadHex, blakeHashOfPayload, accountAddress, origin, challenge.toHexString())
}
}
}
testVectorsFile.writeText(json.encodeToString(testVectors))
}
}
@Test
fun `run tests for test vectors`() {
testVectors.forEach { testVector ->
Log.d("Test vector", testVector.toString())
val signRequest = SignRequest.SignAuthChallengeRequest(
challengeHex = testVector.challenge,
dAppDefinitionAddress = testVector.dAppDefinitionAddress,
origin = testVector.origin
)
Assert.assertEquals(testVector.payloadToHash, signRequest.payloadHex)
Assert.assertEquals(testVector.blakeHashOfPayload, signRequest.dataToSign.blake2Hash().toHexString())
}
}
}
@kotlinx.serialization.Serializable
data class TestVector(
@kotlinx.serialization.SerialName("payloadToHash")
val payloadToHash: String,
@kotlinx.serialization.SerialName("blakeHashOfPayload")
val blakeHashOfPayload: String,
@kotlinx.serialization.SerialName("dAppDefinitionAddress")
val dAppDefinitionAddress: String,
@kotlinx.serialization.SerialName("origin")
val origin: String,
@kotlinx.serialization.SerialName("challenge")
val challenge: String
)
|
# Copyright 2022 Sabana Technologies, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pathlib import Path
import numpy as np
from sabana import Instance, Program
def test_main():
"""
This is an example of how to deploy a
c_axi_array_add_constant instance.
This instance adds 100 to a vector of integers.
"""
# declare the data
dt = np.uint32
a = np.random.randint(255, size=(50,), dtype=dt)
start = np.ones([1], dt)
finish = np.array([14], dt)
# create program
program = Program()
program.mmio_alloc(name="c0", size=0x00010000, base_address=0xA0000000)
program.buffer_alloc(name="buff_a", size=a.nbytes, mmio_name="c0", mmio_offset=0x18)
# write the size of the input (50 is the max, see: sabana.cc)
program.mmio_write(np.array([50], dt), name="c0", offset=0x10)
program.buffer_write(a, name="buff_a", offset=0)
program.mmio_write(start, name="c0", offset=0x0)
program.mmio_wait(finish, name="c0", offset=0x0, timeout=4)
program.buffer_read(name="buff_a", offset=0, dtype=dt, shape=a.shape)
program.mmio_dealloc(name="c0")
program.buffer_dealloc(name="buff_a")
# deploy instance
image_file = Path(__file__).resolve().parent.parent.joinpath("sabana.json")
inst = Instance(image_file=image_file, verbose=True)
# if you want to test the image without building it
# uncomment the following line:
# inst = Instance(image="robot/c_axi_array_add_constant:0.1.0", verbose=True)
inst.up()
# run program
responses = inst.execute(program)
# terminate instance
inst.down()
# check results
assert np.array_equal(responses[1], a + 100)
print("Check OK!")
print("Adding 100 to a vector of random integers was successful in Sabana!")
if __name__ == "__main__":
test_main()
|
import { createSlice, configureStore } from '@reduxjs/toolkit';
// Counter.js에서 state.counter.counter인 이유:
const initialCounterState = {
counter: 0,
isCounterVisible: true,
};
const counterSlice = createSlice({
name: 'counter',
initialState: initialCounterState,
reducers: {
increment(state) {
// we can mutate the state:
state.counter++;
},
decrement(state) {
state.counter--;
},
increase(state, action) {
state.counter = state.counter + action.payload;
},
toggleCounter(state) {
state.isCounterVisible = !state.isCounterVisible;
},
},
});
export const counterActions = counterSlice.actions;
export default counterSlice.reducer;
// const counterReducer = (state = initialState, action) => {
// if (action.type === 'increment') {
// return {
// counter: state.counter + 1,
// isCounterVisible: state.isCounterVisible,
// };
// }
// if (action.type === 'increase') {
// return {
// counter: state.counter + action.amount,
// isCounterVisible: state.isCounterVisible,
// };
// }
// if (action.type === 'decrement') {
// return {
// counter: state.counter - 1,
// isCounterVisible: state.isCounterVisible,
// };
// }
// if (action.type === 'toggle') {
// return {
// isCounterVisible: !state.isCounterVisible,
// counter: state.counter,
// };
// }
// return state;
// };
|
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Aula 3 - Lua</title>
<link rel="stylesheet" href="/menu/main.css">
</head>
<body>
<div id="all">
<header>
<h1>
Aula 3 - Lua
</h1>
<h3>
writer: Daniel Matos
</h3>
</header>
<strong>
while
</strong>
<p>O while em Lua é bem parecido com o python. Usamos primeiramente o while (minúsculo) + condição + do + end no final.</p>
<p>Veja o exemplo a seguir: </p>
<img src="/images/while.PNG" alt="repetição while">
<p>No temos string4 recebendo bool, que não existe logo vai recebel nill, a = 100 e b = 10. Então a repetição começa com enquanto b for menor que a faça... Dentro da repetição temos b = b + 1, vai sempre aumentando 1. Então temos uma condição: se b == 50 então a string4 que antes recebial nill vai passar a receber true, depois temos um end mostrando que acabou a condição. Então vamos imprimir na tela o valor da string4 e o valor de b, e no final um end sinalizando o fim da repetição while. Antes de executar tente entender quais valores serão apresentados na tela, quantas repetições teremos e tudo mais. </p>
<p>Veja o outro exemplo: </p>
<img src="/images/while2.PNG" alt="outra repetição while">
<p>Na repetição acima temos b = 10 e c = 0. Então temos a repetição: enquanto verdadeiro faça (Esse true vai fazer ficar repetindo para Sempre a não ser que ocorra um break)... c = c + b, local b = c, nesse caso local b vai ser uma variável local que só vale dentro da repetição, fora da repetição o valor do b vai ser o mesmo que antes. Então imprime o valor do b, como está dentro da repetição vai receber local b. Então temos uma condição se b == 100 então break, o break quebra a repetição, saí da repetição. Depois temos um end finalizando a condição e um end finalizando a repetição. Depois, só para deixar claro imprimimos um b na tela mostrando que o valor de b vai voltar a ser o que era antes da repetição, não vai ser mais o local b. </p>
<p>Nessa repetição então vamos fazer com que o c receba seu valor mais o valor do b, vai sempre aumentando e é importante destacar que esse b como vem antes do local b = c vai receber o valor do b antes do parênteses, ou seja, 10, e criamos então a variável local b que vai receber c e imprimimos o b, que dentro da repetição é o local b. Se b == 100 então sai da repetição e no final vai imprimir o valor do b fora da repetição. Esse vai ser o resultado: </p>
<img src="/images/resultadowhile.PNG" alt="resultado do while">
<p></p>
<a href="/menu/articles/programming/luamaraton.html">Voltar para a página anterior</a>
</div>
</body>
</html>
|
<template>
<div class="story-item">
<header class="story-item__header">
<app-progressbar
v-if="loader"
:is-running="active"
:time="5000"
@loaded="$emit('change')"
/>
<div class="story-item__header__profile">
<app-avatar
class="story-item__header__profile__avatar"
:avatar-image="avatarImage"
without-line
/>
<span class="story-item__header__profile__name" >{{ username }}</span>
</div>
</header>
<div class="story-item__content">
<div v-if="readme" v-html="readme"/>
<div class="story-item__skeleton" v-else>
<content-loader
v-bind="createAttrs(136)"
>
<rect x="0" y="0" rx="3" ry="3" width="100%" height="136" />
</content-loader>
<content-loader
v-for="index in 2"
:key="index"
v-bind="createAttrs(64)"
>
<rect x="0" y="0" rx="2" ry="2" width="100%" height="16" />
<rect x="0" y="24" rx="3" ry="3" width="78%" height="16" />
<rect x="0" y="48" rx="3" ry="3" width="86%" height="16" />
</content-loader>
</div>
</div>
<footer class="story-item__footer">
<app-btn
:loading="followLoading"
:disabled="followLoading"
@click="$emit('follow')"
:gray="stared" >
{{ stared ? 'Unfollow' : 'Follow' }}
</app-btn>
</footer>
</div>
</template>
<script>
import AppProgressbar from '@/components/App/AppProgressbar';
import AppAvatar from '@/components/App/AppAvatar';
import { ContentLoader } from 'vue-content-loader';
import AppBtn from '@/components/App/AppBtn';
export default {
name: 'StoryItem',
components: {
AppBtn,
AppAvatar,
AppProgressbar,
ContentLoader,
},
emits: ['change', 'follow'],
props: {
avatarImage: { type: String, required: true },
username: { type: String, required: true },
active: { type: Boolean, required: false },
loader: { type: Boolean, default: false },
readme: { type: String, default: null },
stared: { type: Boolean, default: false },
followLoading: { type: Boolean, default: false },
},
methods: {
createAttrs(height) {
return {
class: 'svg-preserve',
speed: 2,
width: '100%',
height,
'view-box': `0 0 100 ${height}`,
'preserve-aspect-ratio': 'none',
'background-color': '#f3f3f3',
'foreground-color': '#ecebeb',
};
},
},
};
</script>
<style scoped lang="scss">
@import "src/assets/styles/colors";
.story-item {
width: 375px;
max-width: 100%;
height: 667px;
background-color: map-get($colors, white);
display: flex;
flex-direction: column;
border-radius: 8px;
overflow: hidden;
&__header {
padding: 8px 8px 13px 8px;
display: flex;
flex-direction: column;
row-gap: 12px;
&__profile {
display: flex;
height: 32px;
gap: 12px;
align-items: center;
}
}
&__content {
flex: 1;
padding: 18px;
font-size: 12px;
border-top: 1px solid map-get($colors, storyBorder);
border-bottom: 1px solid map-get($colors, storyBorder);
overflow: auto;
}
&__skeleton {
display: flex;
flex-direction: column;
gap: 25px;
}
&__footer {
padding: 32px 52px;
}
}
</style>
|
## 12.你是什么类型的父母?
各位朋友大家好,我是段鑫星老师。
今天我们要分享的话题是,你是什么样的父母,你是哪一种类型的父母。
其实一说这个话题,大家都会觉得这还用讲?但是实际上这个父母的分类有很多种。美国的学者通常把父母的类型分为控制型的、放任型的、溺爱型的、民主型的。那我们看看这四类,你是属于哪一类?
控制型的一个表现就是说孩子要不然是顺从型的,要不然是叛逆型的。民主型的,那么孩子表现为就是说可以表达自己的意见,但是呢我们家长要有一个监管。放任型的就是自由生长,野蛮生长。溺爱型的就是以孩子为中心。
美国的这种研究表明,就是说什么样的家庭对孩子的成长是更有利的。它追踪那些成绩优异、人格发展良好的孩子,得出的结论是:绝大多数民主加监管的家庭中长大的孩子,他更多地容易在学业成就、人际关系上取得更好的一种动力,这是国外的一个分类。
最近呢我看到一个报道,我觉得也很有趣,也跟各位家长分享。它把这个家长呢列为那种工程机械型的,一类家长是直升机式的家长,就是说我希望我孩子就是成为那种学霸,一直提拉着孩子向前走的,比如说海淀区的家长,顺义区的家长。
还有一类家长是那种推土机式的家长。啥叫推土机式的家长?就是说我要扫除孩子成长上的一切的障碍,我要帮孩子清路,然后这样的话,小孩子只做一件事,就是我学习好,这样的孩子在应试教育阶段可能会得到良好的发展,但是如果到了大学,甚至工作以后进入社会,那这个小孩他可能在和人的交往、人的成长方面可能就会面临别的其他的一些困难和问题。
那还有说搅拌机式的父母。啥叫搅拌机式的父母?就是这个父母就很难搞,我是听中学的班主任跟我聊的,说你知道吗,就说这个孩子家长太难搞了,说你如果说这孩子学习好,家长会认为学校如果尽力他会更拔尖儿,如果他学习不好,家长会认为孩子这么聪明,是学校没有尽到更重要的一种敦促的作用,所以有的时候可能使得学校里很难做。
还有一种分法,大家想想啊,一个直升机的父亲,再加上一个轧路机的母亲,这种工程机械的组合体,再看看你家是哪一类?
那我们可能中国的第三类分法,就中国的传统家庭呢可能更容易分这种,就是说严父慈母,就是虎爸猫妈或者虎妈猫爸,总之是一严一松、一个唱红脸,一个唱黑脸,这是我们中国传统家庭都认为比较好的。就是孩子当需要爱的时候,有一个人能接住情绪,但是孩子要出圈的时候知道前面有一个底线在那儿,我不能出去,这是一类。
中国家庭中还有一类就是双双溺爱的。双双溺爱的家庭可能往往都是说这样的一种状态,就是说可能家里几代单传呢,或者家里对性别有一个特别的期待,就这个家庭特期待男孩,结果来了个男孩,比如说晚年得子,比如说这个孩子怀得生得太不容易,这都特容易陷入那种双双溺爱型的。
那可能还有一类就是说双双严厉型的,就是严父严母,这样的家庭中长大的孩子,我们想想,想着都心累。这样的家庭多存在于比如说公务员、教师、医生这种知识分子家庭中,往往是不是比要求松,而是比谁比谁的要求更高。
这样的孩子可能在中小幼阶段都会有好的成绩,但这样的孩子在未来人生的发展中,他这种人生的限度,就是他更大限度的一个发展那个点,有可能父母在小时候过分地挖掘了孩子的潜力,就孩子很容易探到天花板。这一点呢也特别对家长有一个提醒。
那么还有第四类呢就是双方都是慈爱型的,都是柔软型的。如果父母双方对孩子只有爱,没有管,这样对一个男孩子来讲,要风险更大。
为什么这么说呢?如果说我们家长都是弱型的,都是溺爱型的、温和型的,女孩子,OK;如果是一个男孩子,大家想想,一个青春期的男孩子,这本身那么高的荷尔蒙,他走在路上,就是他要横冲直撞的时候,父母既没有防护网,也没有高压线,这个小孩大家可以想象,他很容易这种行为容易失控。
那还有一类父母,就是我们常说的放任型的。放任型的父母就是我啥也不管,双方都放弃自己的责任,就谁也不管这个小孩,这个小孩这不是自由生长,是野蛮生长,这样的孩子在青春期问题也会比较多。
所以我们看说,我给它分了这些类型,但是也绝不仅这些类型,但是我们想分门别类的时候呢,就让我们家长可能了解一下自己是哪一类,我们可能脑子里想想,自己家庭是哪一类家庭。
比如说我家,我是个女孩,我家就属于那种慈父严母,猫爸虎妈。在这种教育的过程中,因为女孩子本身比较胆小,其实我们有的时候老虎不发威,可能那些小动物都被吓着了。
我自己在反思养育孩子的过程中,某些时候特别是她小的时候表达得过于严厉一点,我想如果度在宽松一点点可能会更好,但是总体方向没有错。孩子小时候要管,大了要惯,而不是说小时候使劲惯,大了舍不得放。
所以我们看,这背后都和我们家庭的一个结构、家庭的一个系统和我们父母的人格特征,甚至父母的这种职业倾向都有关系。
探索家庭的类型,对我们了解我们自己的行为方式,要更好地帮助到孩子还是有帮助。
好,我们今天的课就给大家分享到这里,谢谢大家!
|
// To parse this JSON data, do
//
// final getSkillModel = getSkillModelFromJson(jsonString);
import 'dart:convert';
List<GetSkillModel> getSkillModelFromJson(String str) => List<GetSkillModel>.from(json.decode(str).map((x) => GetSkillModel.fromJson(x)));
String getSkillModelToJson(List<GetSkillModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class GetSkillModel {
GetSkillModel({
this.id,
this.uuid,
this.title,
this.status,
this.createdAt,
this.updatedAt,
});
int? id;
String? uuid;
String? title;
String? status;
DateTime? createdAt;
DateTime? updatedAt;
factory GetSkillModel.fromJson(Map<String, dynamic> json) => GetSkillModel(
id: json["id"],
uuid: json["uuid"],
title: json["title"],
status: json["status"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"uuid": uuid,
"title": title,
"status": status,
"created_at": createdAt!.toIso8601String(),
"updated_at": updatedAt!.toIso8601String(),
};
}
|
import React, { useEffect, useState } from "react";
import { Link, useNavigate } from 'react-router-dom';
import '../componentStyle/WatchList.css'; // Import the CSS file
import Axios from 'axios';
import { AiOutlineCloseCircle } from 'react-icons/ai';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
const ToWatchList = () => {
const [movies, setMovies] = useState([]);
const [loginStatus, setLoginStatus] = useState('')
const navigate = useNavigate();
const showToast = (message, type = 'info') => {
toast[type](message, {
position: 'top-right',
autoClose: 3000,
hideProgressBar: true,
closeOnClick: true,
});
};
const goToSignUpPage = () => {
navigate('/');
};
useEffect(() => {
Axios.get("http://localhost:3000/login", { withCredentials: true })
.then((response) => {
if (response.data.loggedIn === true) {
setLoginStatus(response.data.user[0].email);
} else if (response.data.loggedIn === false) {
setLoginStatus('User not logged in');
goToSignUpPage();
}
})
.catch((error) => {
console.error(error);
});
Axios.get('http://localhost:3000/loadWatchList', { withCredentials: true })
.then((response) => {
if (response.status === 200) {
setMovies(response.data);
}
})
.catch((error) => {
if (error.response.status === 401) {
showToast("User session isn't active", 'error');
}
else if (error.response.status === 500) {
showToast('Server Error', 'error');
}
else {
showToast('Unknown Error')
}
});
}, []);
const allMoviesWatchList = () => {
Axios.get('http://localhost:3000/loadWatchList', { withCredentials: true })
.then((response) => {
if (response.status === 200) {
setMovies(response.data);
}
})
.catch((error) => {
if (error.response.status === 401) {
showToast("User session isn't active", 'error');
}
else if (error.response.status === 500) {
showToast('Server Error', 'error');
}
else {
showToast('Unknown Error')
}
});
};
//when data needs passing as a param for server call, pass it as a param for a get request, for a post request you can send it through the body
const goToMoreInfo = (movieId) => {
// Use the movieId to fetch more information about the selected movie
Axios.get('http://localhost:3000/selectedMovie/' + movieId, { withCredentials: true })
.then((response) => {
if (response.status === 200) {
// Navigate to the MoreInfo page with the movieId as a parameter
navigate('/MoreInfo/' + movieId);
}
})
.catch((error) => {
if (error.response.status === 401) {
showToast("User session isn't active", 'error');
}
else if (error.response.status === 500) {
showToast('Server Error', 'error');
}
else {
showToast('Unknown Error', 'error');
}
});
};
//Remove from watch list
const removeFromWatchList = (movieId) => {
console.log(movieId)
// Use the movieId to fetch more information about the selected movie
Axios.delete('http://localhost:3000/removeFromWatchList',
{
withCredentials: true,
data: {
movieId: movieId
}
})
.then((response) => {
if (response.status === 200) {
showToast("Movie removed", 'success');
allMoviesWatchList()
}
})
.catch((error) => {
if (error.response.status === 401) {
showToast("User session isn't active", 'error');
}
else if (error.response.status === 500) {
showToast('Server Error', 'error');
}
else {
showToast('Unknown Error', 'error');
}
});
};
return (
<div className="watchlist-container">
<header className="watchlist-header">
<h1>My Watch List</h1>
</header>
<main className="watchlist-main">
<ToastContainer />
<div className="watchlist-movie-list">
{movies.map(movie => (
<div key={movie.movie_id}>
<button className="watchlist-movieTitleButton" onClick={() => goToMoreInfo(movie.movie_id)}> <h2 className="watchlist-movieTitle">{movie.movie_title}</h2></button>
<div className="watchlist-movie-image-container">
<img className="images" src={movie.movie_image} alt={movie.title} />
<button onClick={() => removeFromWatchList(movie.movie_id)} className="watchlist-removeOverlay"><AiOutlineCloseCircle className="remove" /></button>
</div>
</div>
))}
</div>
<Link to="/HomePage" className="btn"><p className="btn-text"> Explore Movies</p></Link>
</main>
<footer className="footer">
<p>© 2023 Movie Database. All rights reserved.</p>
</footer>
</div>
);
};
export default ToWatchList;
|
import { Request, Response } from "express";
import {userService} from "../services/UserService";
class UserController {
async create(request: Request, response: Response) {
const { name, lastName, username, email, phone, city, state,password } = request.body;
const createUserService = userService;
try {
await createUserService.create({
name,
lastName,
username,
email,
password,
phone,
city,
state
}).then(() => {
request.flash("success_msg","usuario agregado exitosamente");
response.redirect("./users")
});
} catch (err) {
request.flash("error_msg","fallo al agregar el usuario");
response.redirect("./addUser")
}
}
async delete(request: Request, response: Response) {
const { id } = request.body;
const deleteUserService = userService;
try {
await deleteUserService.delete(id).then(() => {
request.flash("success_msg","usuario eliminado exitosamente");
response.redirect("./users")
});
} catch (err) {
request.flash("error_msg","fallo al eliminar el usuario");
response.redirect("./users")
}
}
async get(request: Request, response: Response) {
let { id } = request.query;
id = id.toString();
const getUserDataService = userService;
const user = await getUserDataService.getData(id);
return response.render("User/edit", {
user: user
});
}
async list(request: Request, response: Response) {
const listUsersService = userService;
const users = await listUsersService.list();
return response.render("User/users", {
users: users
});
}
async search(request: Request, response: Response) {
let { search } = request.query;
search = search.toString();
const searchUserService = userService;
try {
const users = await searchUserService.search(search);
response.render("User/search", {
users: users,
search: search
});
} catch (err) {
request.flash("error_msg","fallo al buscar el usuario");
response.redirect("./users")
}
}
async update(request: Request, response: Response) {
const { id,name, lastName,username, email, phone, city, state,password } = request.body;
const updateUserService = userService;
try {
await updateUserService.update({ id, name, lastName, username, email, phone, city, state,password }).then(() => {
request.flash("success_msg","usuario actualizado exitosamente");
response.redirect("./users")
});
} catch (err) {
request.flash("error_msg","fallo al actualizar el usuario");
response.redirect("./editUser")
}
}
}
export default UserController;
|
import React from 'react';
import { useDispatch } from 'react-redux';
import PropTypes from 'prop-types';
import { cartActions } from '../store/cartSlice';
import './product.css';
const Product = ({
name, id, imgURL, price,
}) => {
const dispatch = useDispatch();
const addToCart = () => {
dispatch(cartActions.addToCart({
name,
id,
price,
}));
};
return (
<div className="card">
<img src={imgURL} alt={name} />
<h3>{name}</h3>
<p>
$
{' '}
{price}
</p>
<button type="button" className="buyBtn" onClick={addToCart}>Buy</button>
</div>
);
};
Product.propTypes = {
name: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
imgURL: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
};
export default Product;
|
import { useState, useEffect } from "react";
import { Link, useParams } from "react-router-dom";
// Link
import ReactPlayer from "react-player";
import { fetchFromAPI } from "../utils/fetchFrom";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCheckCircle } from "@fortawesome/free-solid-svg-icons";
import { Videos } from "./Videos";
export const VideoDetails = () => {
const [videoDetails, setVideoDetails] = useState(null);
const [videos, setVideos] = useState(null);
const { id } = useParams();
useEffect(() => {
fetchFromAPI(`videos?part=snippet,statistics&id=${id}`).then((data) => {
setVideoDetails(data.items[0]);
});
fetchFromAPI(`search?part=snippet&relatedToVideoId=${id}&type=video`).then(
(data) => {
setVideos(data.items);
},
);
}, [id]);
if (!videoDetails?.snippet) return "Loading...";
// console.log(videoDetails);
const {
snippet: { title, channelId, channelTitle },
statistics: { viewCount, likeCount },
} = videoDetails;
return (
<main className="flex flex-col px-2 pb-2 gap-4 bg-neutral-900 text-white relative md:flex-row">
<div
className="static top-16 w-full grid md:sticky md:w-3/4"
style={{
gridTemplateRows: `1fr 7rem`,
height: `calc(100vh - 6rem)`,
}}
>
<div className="w-full">
<ReactPlayer
url={`https://www.youtube.com/watch?v=${id}`}
className="react-player"
width={`100%`}
height={`100%`}
controls
/>
</div>
<div className="flex gap-4 flex-col mt-4">
<h1 className=" text-xl font-bold md:text-3xl">{title}</h1>
<div className="flex justify-between items-center text-sm md:text-m">
<Link
to={`/lozo-yt-site/channel/${channelId}`}
className="hover:underline transition-all"
>
{channelTitle}{" "}
<FontAwesomeIcon icon={faCheckCircle} className="text-sm" />
</Link>
<div className="flex gap-4">
<h2>{parseInt(viewCount).toLocaleString()} views</h2>
<h2>{parseInt(likeCount).toLocaleString()} likes</h2>
</div>
</div>
</div>
</div>
<div className="w-full md:w-1/4">
<Videos videos={videos} columns={1} recommended={1} />
</div>
</main>
);
};
// skoncz rekomendowne video i napraw niektore filym bo nie da sie ich odtworzyc
|
package com.hwapow.reservior.controller;
import java.util.List;
import com.hwapow.reservior.domain.ResSenor;
import com.hwapow.reservior.service.IResSenorService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hwapow.common.annotation.Log;
import com.hwapow.common.core.controller.BaseController;
import com.hwapow.common.core.domain.AjaxResult;
import com.hwapow.common.enums.BusinessType;
import com.hwapow.reservior.domain.ResMonitorData;
import com.hwapow.reservior.service.IResMonitorDataService;
import com.hwapow.common.utils.poi.ExcelUtil;
import com.hwapow.common.core.page.TableDataInfo;
/**
* 传感器监测数据Controller
*
* @author hwapow
* @date 2021-09-21
*/
@RestController
@RequestMapping("/reservior/data")
public class ResMonitorDataController extends BaseController
{
@Autowired
private IResMonitorDataService resMonitorDataService;
@Autowired
private IResSenorService resSenorService;
/**
* 查询传感器监测数据列表,如果当天数据不全,则取昨天数据补充,如果当天本身没有数据则全部显示
*/
@GetMapping("/getLastData")
public TableDataInfo getLastData(ResMonitorData resMonitorData)
{
List<ResMonitorData> list=resMonitorDataService.selectResMonitorDataListByDay(resMonitorData);
if(list!=null&&list.size()>0){
list= resMonitorDataService.selectLastDataByDay(resMonitorData);
}
return getDataTable(list);
}
/**
* 查询传感器监测数据列表
*/
@GetMapping("/list")
public TableDataInfo list(ResMonitorData resMonitorData)
{
startPage();
List<ResMonitorData> list = resMonitorDataService.selectResMonitorDataList(resMonitorData);
return getDataTable(list);
}
/**
* 导出传感器监测数据列表
*/
@PreAuthorize("@ss.hasPermi('reservior:data:export')")
@Log(title = "传感器监测数据", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(ResMonitorData resMonitorData)
{
List<ResMonitorData> list = resMonitorDataService.selectResMonitorDataList(resMonitorData);
ExcelUtil<ResMonitorData> util = new ExcelUtil<ResMonitorData>(ResMonitorData.class);
return util.exportExcel(list, "data");
}
/**
* 获取传感器监测数据详细信息
*/
@PreAuthorize("@ss.hasPermi('reservior:data:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id)
{
return AjaxResult.success(resMonitorDataService.selectResMonitorDataById(id));
}
/**
* 新增传感器监测数据
*/
@PreAuthorize("@ss.hasPermi('reservior:data:add')")
@Log(title = "传感器监测数据", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody ResMonitorData resMonitorData)
{
ResSenor resSenor =this.resSenorService.selectResSenorById(resMonitorData.getSenorId());
if (resSenor!=null){
resMonitorData.setSectionId(resSenor.getSectionId());
}
return toAjax(resMonitorDataService.insertResMonitorData(resMonitorData));
}
/**
* 修改传感器监测数据
*/
@PreAuthorize("@ss.hasPermi('reservior:data:edit')")
@Log(title = "传感器监测数据", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody ResMonitorData resMonitorData)
{
ResSenor resSenor =this.resSenorService.selectResSenorById(resMonitorData.getSenorId());
if (resSenor!=null){
resMonitorData.setSectionId(resSenor.getSectionId());
}
return toAjax(resMonitorDataService.updateResMonitorData(resMonitorData));
}
/**
* 删除传感器监测数据
*/
@PreAuthorize("@ss.hasPermi('reservior:data:remove')")
@Log(title = "传感器监测数据", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(resMonitorDataService.deleteResMonitorDataByIds(ids));
}
}
|
import { DbLoadSurveyResult } from "./db-load-survey-result";
import { type LoadSurveyResultRepository, type LoadSurveyByIdRepository } from "./db-load-survey-result-protocols";
import {
mockLoadSurveyByIdRepository,
mockLoadSurveyResultRepository,
mockSurveyResultModel,
throwError
} from "@/utils/tests";
import MockDate from "mockdate";
let db: DbLoadSurveyResult
let loadSurveyResultRepositoryStub: LoadSurveyResultRepository
let loadSurveyByIdRepositoryStub: LoadSurveyByIdRepository
const SURVEY_ID = "survey-id"
const ACCOUNT_ID = "account-id"
describe(DbLoadSurveyResult.name, () => {
beforeAll(() => { MockDate.set(new Date()); })
afterAll(() => { MockDate.reset(); })
beforeEach(() => {
loadSurveyResultRepositoryStub = mockLoadSurveyResultRepository()
loadSurveyByIdRepositoryStub = mockLoadSurveyByIdRepository(SURVEY_ID, "other-answer")
db = new DbLoadSurveyResult(loadSurveyResultRepositoryStub, loadSurveyByIdRepositoryStub)
})
it("Should call LoadSurveyResultRepository with correct values", async () => {
const loadBySurveyIdSpy = jest.spyOn(loadSurveyResultRepositoryStub, "loadBySurveyId")
await db.load(SURVEY_ID, ACCOUNT_ID)
expect(loadBySurveyIdSpy).toBeCalledWith(SURVEY_ID, ACCOUNT_ID)
})
it("Should throw if LoadSurveyResultRepository throws", async () => {
jest.spyOn(loadSurveyResultRepositoryStub, "loadBySurveyId").mockImplementationOnce(throwError)
const promise = db.load(SURVEY_ID, ACCOUNT_ID)
await expect(promise).rejects.toThrow()
})
it("Should call LoadSurveyByIdRepository if LoadSurveyResultRepository returns null", async () => {
jest.spyOn(loadSurveyResultRepositoryStub, "loadBySurveyId").mockReturnValueOnce(Promise.resolve(null))
const loadByIdSpy = jest.spyOn(loadSurveyByIdRepositoryStub, "loadById")
await db.load(SURVEY_ID, ACCOUNT_ID)
expect(loadByIdSpy).toBeCalledWith(SURVEY_ID)
})
it("Should return survey result model with all reset answers when LoadSurveyResultRepository returns null", async () => {
jest.spyOn(loadSurveyResultRepositoryStub, "loadBySurveyId").mockReturnValueOnce(Promise.resolve(null))
const result = await db.load(SURVEY_ID, ACCOUNT_ID)
expect(result).toEqual(mockSurveyResultModel(SURVEY_ID, true, false))
})
it("Should return survey result model when load was called with success", async () => {
const result = await db.load(SURVEY_ID, ACCOUNT_ID)
expect(result).toEqual(mockSurveyResultModel(SURVEY_ID))
})
})
|
/*
* Copyright (c) 2013, Pavel Lechev
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* 3) Neither the name of the Pavel Lechev nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jmockring.ri.rest.mocked;
import static java.lang.String.format;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.View;
import org.jmockring.ri.service.TestService;
/**
* @author Pavel Lechev
* @date 20/07/12
*/
@Controller
@RequestMapping("/mocked-repos")
public class ControllerWithMockedRepositories {
@Autowired
private TestService service;
@RequestMapping(
value = "/{mockedRepoClassName}",
method = RequestMethod.GET,
produces = "application/json"
)
public View getDefault(@PathVariable("mockedRepoClassName") final String mockedRepoClassName) throws ClassNotFoundException {
return new View() {
@Override
public String getContentType() {
return "applicaiton/json";
}
@Override
public void render(final Map<String, ?> model, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final String val = format("{\"value\":\"%s\"}", service.getString(Class.forName(mockedRepoClassName.replace("#", "."))));
response.getWriter().write(val);
response.flushBuffer();
}
};
}
}
|
import { BearerDid } from '@web5/dids';
import type {
JwtPayload,
JwtHeaderParams,
JwkParamsEcPublic,
JwkParamsOkpPublic,
} from '@web5/crypto';
import { Convert } from '@web5/common';
import { LocalKeyManager as CryptoApi } from '@web5/crypto';
import { DidDht, DidIon, DidKey, DidJwk, DidWeb, DidResolver, utils as didUtils } from '@web5/dids';
const crypto = new CryptoApi();
/**
* Result of parsing a JWT.
*/
export type JwtParseResult = {
decoded: JwtVerifyResult
encoded: {
header: string
payload: string
signature: string
}
}
/**
* Result of verifying a JWT.
*/
export interface JwtVerifyResult {
/** JWT Protected Header */
header: JwtHeaderParams;
/** JWT Claims Set */
payload: JwtPayload;
}
/**
* Parameters for parsing a JWT.
* used in {@link Jwt.parse}
*/
export type ParseJwtOptions = {
jwt: string
}
/**
* Parameters for signing a JWT.
*/
export type SignJwtOptions = {
signerDid: BearerDid
payload: JwtPayload
}
/**
* Parameters for verifying a JWT.
*/
export type VerifyJwtOptions = {
jwt: string
}
/**
* Class for handling Compact JSON Web Tokens (JWTs).
* This class provides methods to create, verify, and decode JWTs using various cryptographic algorithms.
* More information on JWTs can be found [here](https://datatracker.ietf.org/doc/html/rfc7519)
*/
export class Jwt {
/**
* DID Resolver instance for resolving decentralized identifiers.
*/
static didResolver: DidResolver = new DidResolver({ didResolvers: [DidDht, DidIon, DidKey, DidJwk, DidWeb] });
/**
* Creates a signed JWT.
*
* @example
* ```ts
* const jwt = await Jwt.sign({ signerDid: myDid, payload: myPayload });
* ```
*
* @param options - Parameters for JWT creation including signer DID and payload.
* @returns The compact JWT as a string.
*/
static async sign(options: SignJwtOptions): Promise<string> {
const { signerDid, payload } = options;
const signer = await signerDid.getSigner();
let vmId = signer.keyId;
if (vmId.charAt(0) === '#') {
vmId = `${signerDid.uri}${vmId}`;
}
const header: JwtHeaderParams = {
typ : 'JWT',
alg : signer.algorithm,
kid : vmId,
};
const base64UrlEncodedHeader = Convert.object(header).toBase64Url();
const base64UrlEncodedPayload = Convert.object(payload).toBase64Url();
const toSign = `${base64UrlEncodedHeader}.${base64UrlEncodedPayload}`;
const toSignBytes = Convert.string(toSign).toUint8Array();
const signatureBytes = await signer.sign({ data: toSignBytes });
const base64UrlEncodedSignature = Convert.uint8Array(signatureBytes).toBase64Url();
return `${toSign}.${base64UrlEncodedSignature}`;
}
/**
* Verifies a JWT.
*
* @example
* ```ts
* const verifiedJwt = await Jwt.verify({ jwt: myJwt });
* ```
*
* @param options - Parameters for JWT verification
* @returns Verified JWT information including signer DID, header, and payload.
*/
static async verify(options: VerifyJwtOptions): Promise<JwtVerifyResult> {
const { decoded: decodedJwt, encoded: encodedJwt } = Jwt.parse({ jwt: options.jwt });
if (decodedJwt.payload.exp && Math.floor(Date.now() / 1000) > decodedJwt.payload.exp) {
throw new Error(`Verification failed: JWT is expired`);
}
// TODO: should really be looking for verificationMethod with authentication verification relationship
const dereferenceResult = await Jwt.didResolver.dereference(decodedJwt.header.kid!);
if (dereferenceResult.dereferencingMetadata.error) {
throw new Error(`Failed to resolve ${decodedJwt.header.kid}`);
}
const verificationMethod = dereferenceResult.contentStream;
if (!verificationMethod || !didUtils.isDidVerificationMethod(verificationMethod)) { // ensure that appropriate verification method was found
throw new Error('Verification failed: Expected kid in JWT header to dereference a DID Document Verification Method');
}
// will be used to verify signature
const publicKeyJwk = verificationMethod.publicKeyJwk as JwkParamsEcPublic | JwkParamsOkpPublic;
if (!publicKeyJwk) { // ensure that Verification Method includes public key as a JWK.
throw new Error('Verification failed: Expected kid in JWT header to dereference to a DID Document Verification Method with publicKeyJwk');
}
if(publicKeyJwk.alg && (publicKeyJwk.alg !== decodedJwt.header.alg)) {
throw new Error('Verification failed: Expected alg in JWT header to match DID Document Verification Method alg');
}
const signedData = `${encodedJwt.header}.${encodedJwt.payload}`;
const signedDataBytes = Convert.string(signedData).toUint8Array();
const signatureBytes = Convert.base64Url(encodedJwt.signature).toUint8Array();
const isSignatureValid = await crypto.verify({
key : publicKeyJwk,
signature : signatureBytes,
data : signedDataBytes,
});
if (!isSignatureValid) {
throw new Error('Signature verification failed: Integrity mismatch');
}
return decodedJwt;
}
/**
* Parses a JWT without verifying its signature.
*
* @example
* ```ts
* const { encoded: encodedJwt, decoded: decodedJwt } = Jwt.parse({ jwt: myJwt });
* ```
*
* @param options - Parameters for JWT decoding, including the JWT string.
* @returns both encoded and decoded JWT parts
*/
static parse(options: ParseJwtOptions): JwtParseResult {
const splitJwt = options.jwt.split('.');
if (splitJwt.length !== 3) {
throw new Error(`Verification failed: Malformed JWT. expected 3 parts. got ${splitJwt.length}`);
}
const [base64urlEncodedJwtHeader, base64urlEncodedJwtPayload, base64urlEncodedSignature] = splitJwt;
let jwtHeader: JwtHeaderParams;
let jwtPayload: JwtPayload;
try {
jwtHeader = Convert.base64Url(base64urlEncodedJwtHeader).toObject() as JwtHeaderParams;
} catch(e) {
throw new Error('Verification failed: Malformed JWT. Invalid base64url encoding for JWT header');
}
if (!jwtHeader.typ || jwtHeader.typ !== 'JWT') {
throw new Error('Verification failed: Expected JWT header to contain typ property set to JWT');
}
if (!jwtHeader.alg || !jwtHeader.kid) { // ensure that JWT header has required properties
throw new Error('Verification failed: Expected JWT header to contain alg and kid');
}
// TODO: validate optional payload fields: https://datatracker.ietf.org/doc/html/rfc7519#section-4.1
try {
jwtPayload = Convert.base64Url(base64urlEncodedJwtPayload).toObject() as JwtPayload;
} catch(e) {
throw new Error('Verification failed: Malformed JWT. Invalid base64url encoding for JWT payload');
}
return {
decoded: {
header : jwtHeader,
payload : jwtPayload,
},
encoded: {
header : base64urlEncodedJwtHeader,
payload : base64urlEncodedJwtPayload,
signature : base64urlEncodedSignature
}
};
}
}
|
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
import 'package:logger/logger.dart';
class NetworkHandler {
// String baseurl = "http://10.0.2.2:5000";
String baseurl = "https://blog-server3.vercel.app";
var log = Logger();
FlutterSecureStorage storage = FlutterSecureStorage();
Future get(String url) async {
String token = await storage.read(key: "token");
url = formater(url);
print(url);
// /user/register
var response = await http.get(
Uri.parse(url),
headers: {
"Authorization": "Bearer $token",
"Allow-Control-Allow-Origin": "*",
},
);
if (response.statusCode == 200 || response.statusCode == 201) {
log.i(response.body);
return json.decode(response.body);
}
log.i(response.body);
log.i(response.statusCode);
}
Future<http.Response> post(String url, Map<String, String> body) async {
String token = await storage.read(key: "token");
print(token);
url = formater(url);
log.d(body);
var response = await http.post(
Uri.parse(url),
headers: {
"Content-type": "application/json",
"Authorization": "Bearer ${token}",
"Allow-Control-Allow-Origin": "*",
},
body: json.encode(body),
);
return response;
}
Future<http.Response> patch(String url, Map<String, String> body) async {
String token = await storage.read(key: "token");
url = formater(url);
log.d(body);
var response = await http.patch(
Uri.parse(url),
headers: {
"Content-type": "application/json",
"Authorization": "Bearer $token"
},
body: json.encode(body),
);
return response;
}
Future<http.Response> patchBlog(String url, var body) async {
String token = await storage.read(key: "token");
url = formater(url);
log.d(body);
var response = await http.patch(
Uri.parse(url),
headers: {
"Content-type": "application/json",
"Authorization": "Bearer $token"
},
body: json.encode(body),
);
return response;
}
Future<http.Response> postLikes(String url) async {
String token = await storage.read(key: "token");
url = formater(url);
log.d(url);
var response = await http.patch(
Uri.parse(url),
headers: {
"Content-type": "application/json",
"Authorization": "Bearer $token"
},
// body: json.encode(body),
);
return response;
}
Future<http.Response> deleteLikes(String url) async {
String token = await storage.read(key: "token");
url = formater(url);
log.d(url);
var response = await http.patch(
Uri.parse(url),
headers: {
"Content-type": "application/json",
"Authorization": "Bearer $token"
},
// body: json.encode(body),
);
return response;
}
// Future getLikedOrNot(String url) async {
// String token = await storage.read(key: "token");
// url = formater(url);
// print(url);
// // /user/register
// var response = await http.get(
// Uri.parse(url),
// headers: {
// "Authorization": "Bearer $token",
// "Allow-Control-Allow-Origin": "*",
// },
// );
// if (response.statusCode == 200 || response.statusCode == 201) {
// log.i(response.body);
// return json.decode(response.body);
// }
// log.i(response.body);
// log.i(response.statusCode);
// }
// Future updateLikedOrNot(String url, var body) async {
// String token = await storage.read(key: "token");
// url = formater(url);
// print(url);
// // /user/register
// var response = await http.post(
// Uri.parse(url),
// headers: {
// "Authorization": "Bearer $token",
// "Allow-Control-Allow-Origin": "*",
// },
// body: json.encode(body),
// );
// if (response.statusCode == 200 || response.statusCode == 201) {
// log.i(response.body);
// return json.decode(response.body);
// }
// log.i(response.body);
// log.i(response.statusCode);
// }
Map<String, String> data = {"like": ""};
Future getLikes(String url) async {
String token = await storage.read(key: "token");
url = formater(url);
print(url);
// /user/register
var response = await http.get(
Uri.parse(url),
headers: {
"Authorization": "Bearer $token",
"Allow-Control-Allow-Origin": "*",
},
);
if (response.statusCode == 200 || response.statusCode == 201) {
log.i(response.body);
return json.decode(response.body);
}
log.i(response.body);
log.i(response.statusCode);
}
Future<http.Response> post1(String url, var body) async {
String token = await storage.read(key: "token");
url = formater(url);
log.d(url);
log.d(body);
var response = await http.post(
Uri.parse(url),
headers: {
"Content-type": "application/json",
"Authorization": "Bearer $token"
},
body: json.encode(body),
);
return response;
}
Future<http.Response> delete(String url, var body) async {
String token = await storage.read(key: "token");
url = formater(url);
log.d(url);
log.d(body);
var response = await http.delete(
Uri.parse(url),
headers: {
"Content-type": "application/json",
"Authorization": "Bearer $token"
},
body: json.encode(body),
);
return response;
}
Future<http.StreamedResponse> patchImage(String url, String filepath) async {
url = formater(url);
String token = await storage.read(key: "token");
print("filepath : $filepath");
var request = http.MultipartRequest('PATCH', Uri.parse(url));
request.files.add(await http.MultipartFile.fromPath("img", filepath));
request.headers.addAll({
"Content-type": "multipart/form-data",
"Authorization": "Bearer $token"
});
var response = request.send();
log.i(response);
return response;
}
String formater(String url) {
return baseurl + url;
}
NetworkImage getImage(String imageName) {
String url = formater("/uploads/$imageName.jpg");
return NetworkImage(url);
}
}
|
Input format: arr1 = [1,4,7,10,12], arr2 = [2,3,6,15]
Output format : 6.00000
Explanation:
Merge both arrays. Final sorted array is [1,2,3,4,6,7,10,12,15].
We know that to find the median we find the mid element.
Since, the size of the element is odd.
By formula, the median will be at [(n+1)/2]th position of the final sorted array.
Thus, for this example, the median is at [(9+1)/2]th position which is [5]th = 6.
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if(nums1.size()>nums2.size()) return findMedianSortedArrays(nums2,nums1);
int m=nums1.size();
int n=nums2.size();
int low=0,high=m,medianPos=((m+n)+1)/2;
while(low<=high) {
int cut1 = (low+high)>>1;
int cut2 = medianPos - cut1;
int l1 = (cut1 == 0)? INT_MIN:nums1[cut1-1];
int l2 = (cut2 == 0)? INT_MIN:nums2[cut2-1];
int r1 = (cut1 == m)? INT_MAX:nums1[cut1];
int r2 = (cut2 == n)? INT_MAX:nums2[cut2];
if(l1<=r2 && l2<=r1) {
if((m+n)%2 != 0)
return max(l1,l2);
else
return (max(l1,l2)+min(r1,r2))/2.0;
}
else if(l1>r2) high = cut1-1;
else low = cut1+1;
}
return 0.0;
}
|
package com.mgvozdev.casino.service.impl;
import com.mgvozdev.casino.dto.PlayerCreateDto;
import com.mgvozdev.casino.dto.PlayerEditDto;
import com.mgvozdev.casino.dto.PlayerReadDto;
import com.mgvozdev.casino.util.ErrorMessage;
import com.mgvozdev.casino.exception.PlayerException;
import com.mgvozdev.casino.mapper.PlayerMapper;
import com.mgvozdev.casino.repository.PlayerRepository;
import com.mgvozdev.casino.service.PlayerService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.*;
@Service
@Transactional
@RequiredArgsConstructor
public class PlayerServiceImpl implements PlayerService {
private final PlayerRepository playerRepository;
private final PlayerMapper playerMapper;
@Override
public PlayerReadDto findById(UUID id) {
return playerRepository.findById(id)
.map(playerMapper::toDto)
.orElseThrow(() -> new PlayerException(ErrorMessage.NOT_FOUND));
}
@Override
public List<PlayerReadDto> findAll() {
return playerRepository.findAll().stream()
.map(playerMapper::toDto)
.toList();
}
@Override
public List<PlayerReadDto> findByOpenedAtBetween(LocalDateTime openedAtStart, LocalDateTime openedAtEnd) {
return playerRepository.findByOpenedAtBetween(openedAtStart, openedAtEnd).stream()
.map(playerMapper::toDto)
.toList();
}
@Override
public PlayerReadDto create(PlayerCreateDto playerCreateDto) {
return Optional.of(playerCreateDto)
.map(playerMapper::toEntity)
.map(playerRepository::save)
.map(playerMapper::toDto)
.orElseThrow(() -> new PlayerException(ErrorMessage.NOT_CREATED));
}
@Override
public PlayerReadDto update(UUID id, PlayerEditDto playerEditDto) {
var playerFromDB = playerRepository.findById(id);
if (playerFromDB.isPresent()) {
return playerFromDB.map(entity -> playerMapper.toEntity(playerEditDto, entity))
.map(playerRepository::saveAndFlush)
.map(playerMapper::toDto)
.orElseThrow(() -> new PlayerException(ErrorMessage.NOT_UPDATED));
} else {
throw new PlayerException(ErrorMessage.NOT_FOUND);
}
}
@Override
public boolean delete(UUID id) {
return playerRepository.findById(id)
.map(entity -> {
playerRepository.delete(entity);
playerRepository.flush();
return true;
})
.orElse(false);
}
}
|
This is the notes for OpenAddressingLinearProbing
Here is another strategy for handling collisions we call it open
addressing with this approach we do not store values in linked list
we store them directly in a cell or slots
just like in the last lecture lets say that we have a hash table with 5 slots and we
want to store key value pairs
first one 6 and A since the key is 6 we are going to get 1 from the hash function
so we store it at this slot with index 1
then there is 8 and B this one goes to index 3
But now what about 11 and C 11 should go to 1 but there is already a key value pair there
we have a collision
to solve this we need to look for another empty slot this is called probing which means searching
we need to search for another location and this is the reason why the approach is called open address because the address of a key value
pair is not determined by the hash function we have to search for another empty slot
we have 3 searching or probing algorithms.
the first one is called linear probing.
with this algorithm we start from the current slot if it is full
we go to the next slot if it is full again then we will go forward until
we get a empty one if we can not find a empty one then the table is full
this is one of the drawbacks of using the open addressing strategy
with the chaining strategy we do not have this problem because our linked list grows automatically
so back to the example 11 and c will be stored at index 2
here is the formula for linear probing: hash(key) + i
we start with the hash value and then increment by one at each step
so here i is like a loop variable that starts with zero and gets incremented until we find
the empty slot
because we are incrementing i at every step it is possible that i ends up being outside the boundary of
our array so we should apply the % operator and reduce the result to a range that can fit into the array
But there is a problem with this linear probing
the 3 items that are stored next to each other form a cluster
next time we want to store a new key value pair where the key falls in
this range our probing is going to take longer because we have to pass all of these items in the cluster and add the new item
at the end of the cluster as a result the cluster will get bigger and this will
make future probing slower
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 20 22:53:41 2024
@author: elpidabantra
"""
from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip, AudioFileClip
from pydub import AudioSegment, effects
import speech_recognition as sr
import os
from googletrans import Translator
from gtts import gTTS
def extract_audio_from_video(video_path, audio_path):
video = VideoFileClip(video_path)
video.audio.write_audiofile(audio_path)
def preprocess_audio(input_audio_path, output_audio_path):
audio = AudioSegment.from_file(input_audio_path)
normalized_audio = effects.normalize(audio)
filtered_audio = normalized_audio.low_pass_filter(3000)
filtered_audio.export(output_audio_path, format="wav")
def transcribe_audio(audio_path, language='el-GR'):
recognizer = sr.Recognizer()
with sr.AudioFile(audio_path) as source:
audio = recognizer.record(source)
try:
transcript = recognizer.recognize_google(audio, language=language)
return transcript
except sr.UnknownValueError:
return "Google Speech Recognition could not understand audio"
except sr.RequestError as e:
return f"Could not request results from Google Speech Recognition service; {e}"
def translate_text(text, src='el', dest='en'):
translator = Translator()
translation = translator.translate(text, src=src, dest=dest)
return translation.text
def synthesize_speech(text, language='en', output_audio_path='translated_audio.mp3'):
tts = gTTS(text=text, lang=language)
tts.save(output_audio_path)
def create_subtitled_video(video_path, translated_text, synthesized_audio_path, output_path):
video = VideoFileClip(video_path)
# Create a TextClip for subtitles
subtitles = TextClip(translated_text, fontsize=24, color='white', bg_color='black', size=video.size, method='caption').set_position(('center', 'bottom')).set_duration(video.duration)
# Load synthesized speech audio
synthesized_audio = AudioFileClip(synthesized_audio_path).set_duration(video.duration)
# Overlay the subtitles on the video and set the synthesized audio
result = CompositeVideoClip([video, subtitles]).set_audio(synthesized_audio)
result.write_videofile(output_path, codec='libx264', audio_codec='aac')
def transcribe_and_translate_video(video_path, language='el-GR', dest_languages=None):
if dest_languages is None:
dest_languages = ['es', 'de', 'ro', 'fr', 'zh-CN', 'hi', 'it', 'sv', 'sq'] # Spanish, German, Romanian, French, Chinese, Hindi, Italian, Swedish, Albanian
language_names = {
'es': 'Spanish',
'de': 'German',
'ro': 'Romanian',
'fr': 'French',
'zh-CN': 'Chinese',
'hi': 'Hindi',
'it': 'Italian',
'sv': 'Swedish',
'sq': 'Albanian'
}
audio_path = "extracted_audio.mp3"
wav_audio_path = "extracted_audio.wav"
print(f"Extracting audio from video: {video_path}")
extract_audio_from_video(video_path, audio_path)
print(f"Preprocessing audio: {audio_path}")
preprocess_audio(audio_path, wav_audio_path)
print(f"Transcribing audio: {wav_audio_path}")
transcript = transcribe_audio(wav_audio_path, language=language)
print(f"Transcript: {transcript}")
for dest_language in dest_languages:
print(f"Translating text to {language_names[dest_language]}")
translated_text = translate_text(transcript, src='el', dest=dest_language)
print(f"Translated Text ({language_names[dest_language]}): {translated_text}")
synthesized_audio_path = f"translated_audio_{dest_language}.mp3"
output_video_path = f"translated_video_{language_names[dest_language]}.mp4"
print(f"Synthesizing speech in {language_names[dest_language]}")
synthesize_speech(translated_text, language=dest_language, output_audio_path=synthesized_audio_path)
print(f"Creating subtitled video in {language_names[dest_language]}: {output_video_path}")
create_subtitled_video(video_path, translated_text, synthesized_audio_path, output_video_path)
# Clean up temporary audio files
os.remove(synthesized_audio_path)
os.remove(audio_path)
os.remove(wav_audio_path)
if __name__ == "__main__":
video_path = "/Users/elpidabantra/myenvgenAI/ds_testing_video_gr.mp4" # Change this to your video file path
transcribe_and_translate_video(video_path)
|
<script lang="ts">
import { ethers } from 'ethers';
import { onMount } from 'svelte';
const ERC20_ABI = [
{
constant: true,
inputs: [
{
name: '_owner',
type: 'address'
}
],
name: 'balanceOf',
outputs: [
{
name: 'balance',
type: 'uint256'
}
],
payable: false,
type: 'function'
}
];
const tokenAddress = '0x348B9EaA3350EC3EfDB731FAc13EA1De234d2DE6';
/**
* @type {ethers.providers.Web3Provider}
*/
let provider: ethers.providers.Web3Provider;
let signer;
/**
* @type {string | Promise<string>}
*/
let signerAddress = '';
let tokenContract;
let tokenBalance = 0;
let accountBalance = '0';
let isConnected = false;
let isUnlocked = false;
let initialized = false;
let isPermanentlyDisconnected = false;
let metamaskStatus = '...';
async function connectWallet() {
const { ethereum } = window;
if (typeof window.ethereum !== 'undefined') {
// connect
await ethereum.request({ method: 'eth_requestAccounts' }).catch((err: { code: number }) => {
if (err.code === 4001) {
// EIP-1193 userRejectedRequest
alert('You need to install MetaMask');
} else {
console.error(err);
}
});
// get provider
provider = new ethers.providers.Web3Provider(ethereum);
// get signer
signer = provider.getSigner();
// get connected wallet address
signerAddress = await signer.getAddress();
// get account balance
accountBalance = (await provider.getBalance(signerAddress)).toString();
// erc-20 token
// tokenContract = new ethers.Contract(tokenAddress, ERC20_ABI, provider);
// tokenBalance = await tokenContract.balanceOf(signerAddress);
// update on account change
ethereum.on('accountsChanged', function (accounts: string[]) {
signerAddress = accounts[0];
});
} else {
alert('MetaMask has not been detected in your browser!');
console.log('MetaMask has not been detected in your browser!');
}
}
onMount(() => {
// connectWallet();
var accountInterval = setInterval(function () {
if (provider) {
({ isConnected, isUnlocked, initialized, isPermanentlyDisconnected } =
window.ethereum._state);
if (isConnected && !isPermanentlyDisconnected && initialized) {
if (isUnlocked) {
metamaskStatus = `<span style="color: green;">MetaMask has been successfully detected in your browser, with external connectivity, and is unlocked.</span>`;
// get account balance
provider.getBalance(signerAddress).then((_accountBalance) => {
accountBalance = _accountBalance.toString();
});
// erc-20 token balance
// tokenContract.balanceOf(signerAddress).then((_tokenBalance) => {
// tokenBalance = _tokenBalance;
// });
} else {
metamaskStatus = `<span style="color: red;">Please unlock your MetaMask and reload.</span>`;
}
} else {
if (isUnlocked) {
metamaskStatus = `<span style="color: red;">MetaMask has been successfully detected in your browser, but without external connectivity.</span>`;
} else {
metamaskStatus = `<span style="color: red;">Please unlock your MetaMask and reload.</span>`;
}
}
}
}, 3000);
});
</script>
<main>
<h1>MetaMask Integration</h1>
<button on:click={connectWallet}>Connect Metamask</button>
<p><b>Connected Account</b>: {signerAddress}</p>
<p><b>ETH Balance</b>: {ethers.utils.formatEther(accountBalance)}</p>
<!-- <p><b>WHITTLE Balance</b>: {ethers.utils.formatEther(tokenBalance)}</p> -->
<br />
<p>{@html metamaskStatus}</p>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
h1 {
color: red;
text-transform: uppercase;
font-size: 4em;
font-weight: 100;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
|
#pragma once
#include "CoreMinimal.h"
DECLARE_DELEGATE_TwoParams(FEnumObjectBrowserDelegate, UWorld* /* InContext */, TArray<UObject*>& /* OutData */);
/**
* Represents a type of object that will be shown in browser
*/
struct OBJECTBROWSERPLUGIN_API FObjectCategoryBase : public TSharedFromThis<FObjectCategoryBase>
{
/* Category config identifier */
FName Name;
/* Category display title */
FText Label;
/* Sort weight for the category (with 0 being topmost, 1000 bottom last) */
int32 SortOrder = 0;
FObjectCategoryBase() = default;
FObjectCategoryBase(const FName& Name, const FText& Label, int32 SortOrder);
virtual ~FObjectCategoryBase() = default;
const FName& GetID() const { return Name; }
const FText& GetDisplayName() const { return Label; }
int32 GetSortOrder() const { return SortOrder; }
virtual bool IsVisibleByDefault() const { return true; }
/* Select objects for the respected category */
virtual void Select(UWorld* InContext, TArray<UObject*>& OutData) const = 0;
};
/**
* Basic implementation of category that take in delegate selector
*/
struct OBJECTBROWSERPLUGIN_API FSimpleObjectCategory : public FObjectCategoryBase
{
/* Data supplier function */
FEnumObjectBrowserDelegate Selector;
FSimpleObjectCategory() = default;
FSimpleObjectCategory(const FName& Name, const FText& Label, const FEnumObjectBrowserDelegate& Selector, int32 SortOrder);
virtual void Select(UWorld* InContext, TArray<UObject*>& OutData) const override;
};
|
### 4 team CFP simulation
# load libraries
library(tidyverse)
library(gt)
library(cfbfastR)
library(cfbplotR)
library(webshot2)
# Define teams and probabilities
teams <- c("Michigan", "Washington", "Texas", "Alabama")
probabilities <- matrix(c(NA, 0.69, 0.60, 0.52,
0.31, NA, 0.40, 0.33,
0.40, 0.60, NA, 0.42,
0.48, 0.67, 0.58, NA), nrow = 4)
# Number of simulations
n_simulations <- 10000
# Simulation code
# Initialize counters
finals_count <- setNames(rep(0, 4), teams)
championships_count <- setNames(rep(0, 4), teams)
# Simulation function
simulate_playoff <- function(teams, probabilities, finals_count, championships_count) {
# Semifinals
semi_finals_winners <- c(
ifelse(runif(1) < probabilities[1, 4], teams[4], teams[1]), # Team1 vs Team4
ifelse(runif(1) < probabilities[2, 3], teams[3], teams[2]) # Team2 vs Team3
)
# Update finals appearances
finals_count[semi_finals_winners] <- finals_count[semi_finals_winners] + 1
# Finals
champion_index <- ifelse(runif(1) < probabilities[which(teams == semi_finals_winners[1]), which(teams == semi_finals_winners[2])], 2, 1)
champion <- semi_finals_winners[champion_index]
# Update championships
championships_count[champion] <- championships_count[champion] + 1
# Return updated counts
return(list(finals = finals_count, championships = championships_count))
}
# Run simulations
set.seed(123)
for (i in 1:n_simulations) {
results <- simulate_playoff(teams, probabilities, finals_count, championships_count)
finals_count <- results$finals
championships_count <- results$championships
}
# Create a data frame for results
results_df <- data.frame(
Team = names(results$finals),
FinalsAppearances = results$finals,
Championships = results$championships
)
# Add team logos
results_df$Logo <- results_df$Team
# Create gt table with team logos
results_df %>% arrange(desc(Championships)) %>%
mutate(frac_semi = FinalsAppearances / n_simulations) %>%
mutate(frac_champ = Championships / n_simulations) %>%
select(-FinalsAppearances, -Championships) %>%
gt() %>%
gt_fmt_cfb_logo(columns = "Logo") %>%
cols_move_to_start(Logo) %>%
cols_label(Logo = "",
Team = "Team",
frac_semi = "Advance to Final",
frac_champ = "Win Championship") %>%
cols_align(align = "center", columns = c(frac_semi,frac_champ)) %>%
tab_options(column_labels.font.weight = "bold") %>%
fmt_percent(
columns = c(frac_semi,frac_champ),
decimals = 1)
|
//
// ContentView.swift
// ToDo
//
// Created by Pranav on 3/28/23.
//
import SwiftUI
import CoreData
struct TaskListView: View {
@Environment(\.managedObjectContext) private var viewContext
@EnvironmentObject var dateHolder: DateHolder
@State var selectedFilter = TaskFilter.NonCompleted
var body: some View {
NavigationView {
VStack{
DateScroller()
.padding()
.environmentObject(dateHolder)
ZStack{
List {
ForEach(filteredTaskItems()) { taskItem in
NavigationLink(destination:TaskEditView(passedTaskItem: taskItem, initialDate: Date()).environmentObject(dateHolder)) {
TaskCell(passedTaskItem: taskItem)
.environmentObject(dateHolder)
}
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Picker("",selection: $selectedFilter.animation() ){
ForEach(TaskFilter.allFilters, id: \.self){
filter in
Text(filter.rawValue)
}
}
}
}
FloatingButton().environmentObject(dateHolder)
}
}.navigationTitle("To Do List")
}
}
private func filteredTaskItems() -> [TaskItem]{
if selectedFilter == TaskFilter.Completed{
return dateHolder.taskItems.filter{$0.isCompleted()}
}
if selectedFilter == TaskFilter.NonCompleted{
return dateHolder.taskItems.filter{!$0.isCompleted()}
}
if selectedFilter == TaskFilter.Overdue{
return dateHolder.taskItems.filter{$0.isOverDue()}
}
return dateHolder.taskItems
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { filteredTaskItems()[$0] }.forEach(viewContext.delete)
dateHolder.saveContext(viewContext)
}
}
}
private let itemFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
TaskListView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
|
import React, { Suspense, useEffect, useState } from 'react';
import { useParams, NavLink, Outlet, useLocation } from 'react-router-dom';
import { getMovieDetails, BASE_IMAGE_URL } from '../../components/API/API';
import './MovieDatails.css';
import { GoBack } from '..//../components/ButtonBack/buttonBack';
const MovieDetails = () => {
const { id } = useParams();
const [movieDetails, setMovieDetails] = useState(null);
const [loading, setLoading] = useState(false);
const location = useLocation();
const formatReleaseDate = releaseDate => {
const parts = releaseDate.split('-');
const year = parts[0];
return year;
};
useEffect(() => {
const fetchMovieDetails = async () => {
try {
setLoading(true);
const details = await getMovieDetails(id);
setMovieDetails(details);
} catch (error) {
console.error(error.message);
} finally {
setLoading(false);
}
};
fetchMovieDetails();
}, [id]);
if (!movieDetails) {
return <div>Loading...</div>;
}
return (
<div className="movie-details-container">
<GoBack className="button_back" url={location.state?.from || '/'} />
<div className="movie-details-content">
<img
className="img_moviedetails"
src={`${BASE_IMAGE_URL}${movieDetails.poster_path}`}
onError={e => {
e.target.src = process.env.PUBLIC_URL + '/horse.jpg';
}}
alt={movieDetails.title}
width={320}
/>
<div className="text-details">
<h2 className="movie-details-title">
{movieDetails.original_title}
<span className="date">
{formatReleaseDate(movieDetails.release_date)}
</span>
</h2>
<p className="info">
<span className="info_view">Overview:</span> {movieDetails.overview}
</p>
<p className="info">
<span className="info_view">User score: </span>
{movieDetails.runtime}%
</p>
<p className="info">
<span className="info_view">Rating: </span>
{movieDetails.vote_average.toFixed(1)}
</p>
<p className="info">
<span className="info_view">Genres:</span>
</p>
<span className="info_view-genres">
{movieDetails.genres.map(({ name }) => name).join(', ') || 'None'}
</span>
<h2 className="add_information">Additional information</h2>
<ul className="cast-info-review">
<li className="cast-add-info">
<NavLink
to="cast"
className="add-info"
activeClassName="active"
exact={true}
>
Cast
</NavLink>
</li>
<li className="cast-add-info">
<NavLink
to="reviews"
className="add-info"
activeClassName="active"
exact={true}
>
Reviews
</NavLink>
</li>
<li className="cast-add-info">
<NavLink
to="movie"
className="add-info"
activeClassName="active"
exact={true}
>
Trailer
</NavLink>
</li>
</ul>
</div>
</div>
{loading && <div>Loading...</div>}
<Suspense fallback={<div>Loading...</div>}>
<Outlet />
</Suspense>
</div>
);
};
export default MovieDetails;
|
import Icon from "@mdi/react";
import { mdiAccountCircle } from "@mdi/js";
import { IComment } from "../../types";
import { Link } from "react-router-dom";
import formatDistance from "date-fns/formatDistance";
import { useAppDispatch, useAppSelector } from "../../hooks/useField";
import {
handleRemoveLikeComment,
handleLikeComment,
} from "../../reducers/currentPostReducer";
const Comment = ({
comment,
createdAt,
id,
likes,
user,
postId,
}: IComment): JSX.Element => {
const dateStr = formatDistance(new Date(createdAt), new Date());
const auth = useAppSelector((state) => state.auth);
const dispatch = useAppDispatch();
const handleCommentLike = () => {
if (likes.find((id) => id === auth.id)) {
dispatch(handleRemoveLikeComment(id, postId, auth.id));
return;
}
dispatch(handleLikeComment(id, postId, auth.id));
};
return (
<div className="mb-2 flex-col">
<section className="flex gap-2">
{user.profilePicture === undefined ? (
<Icon path={mdiAccountCircle} size={1} />
) : (
<img
src={user.profilePicture}
alt="custom user profile picture"
className="w-4 h-4"
/>
)}
<p>
<Link to={`/profile/${user.id}`}>{user.fullName}</Link> {comment}
</p>
</section>
<div className="flex gap-2 pl-1">
<p className="text-slate-600">{dateStr}</p>
<button className="text-blue-600" onClick={handleCommentLike}>
like
</button>
<p>{likes.length}</p>
</div>
</div>
);
};
export default Comment;
|
<!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">
<title></title>
<link rel="stylesheet" href="${cdnUrl}/exts/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="${cdnUrl}/exts/datatables/jquery.dataTables.min.css">
<link rel="stylesheet" href="${cdnUrl}/css/footer.css">
<style type="text/css">
tr td:nth-child(1) {
width: 12%;
}
tr td:nth-child(2) {
width: 20%;
}
tr td:nth-child(3) {
width: 56%;
}
tr td:nth-child(4) {
width: 12%;
}
</style>
</head>
<body>
<%@ include file="/WEB-INF/views/include/header.jsp" %>
<div id="main-content" class="container">
<div class="page-header">
<h3>实体列表页面</h3>
</div>
<div class="row">
<%@ include file="/WEB-INF/views/include/sidebar.jsp" %>
<div class="col-md-9" role="main">
<div class="bs-docs-section">
<form id="dataForm" class="form-horizontal" method="POST" onsubmit="onSubmit(); return false;">
<div class="form-group">
<label class="col-sm-2 control-label">实体类型</label>
<div class="col-sm-4">
<select name="typeId" id="typeId" class="form-control">
<option value="0">所有类型</option>
<c:forEach items="${types}" var="item" varStatus="status">
<option value="${item.typeId}">${item.description}</option>
</c:forEach>
</select>
</div>
<label class="col-sm-2 control-label">实体名称</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="name" id="name">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-6 col-sm-8">
<button type="submit" class="btn btn-success">查询</button>
</div>
</div>
</form>
</div>
<div class="bs-docs-section">
<table id="example" class="table table-striped" style="display:none;">
<thead>
<th>实体编号</th>
<th>实体类型</th>
<th>实体名</th>
<th>操作</th>
</thead>
</table>
</div>
</div>
</div>
</div>
<%@ include file="/WEB-INF/views/include/footer.jsp" %>
<script type="text/javascript" src="${cdnUrl}/exts/jquery/jquery.min.js"></script>
<script type="text/javascript" src="${cdnUrl}/exts/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="${cdnUrl}/exts/datatables/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$('#infomgr').addClass('active');
$('#entity-list').addClass('active');
</script>
<script type="text/javascript">
$.extend( true, $.fn.dataTable.defaults, {
pagingType : "simple_numbers", // 设置分页控件的模式 simple_numbers, full_numbers
lengthMenu : [ 10, 50, 100 ], //设置一页展示10条记录
//lengthChange : false, //屏蔽tables的一页展示多少条记录的下拉列表
searching: false, // 屏蔽datatales的查询框
ordering: false, // 屏蔽排序功能
processing : true, // 打开数据加载时的等待效果
serverSide : true, // 打开后台分页
language: {
url: "${cdnUrl}/exts/datatables/Chinese.json"
},
} );
var table = null;
function loadTable() {
table = $('#example').DataTable({
ajax : {
type: "POST",
url : '<c:url value="/entity/queryEntity.action" />',
dataSrc : "aaData",
data : function(data) {
console.log("-----origin data------");
console.log(JSON.stringify(data));
// var formData = new Object();
// formData = new Object();
// formData.draw = data.draw; // 请求次数
// formData.start = data.start; // 分页参数
// formData.length = data.length; // 每页显示的条数
// formData.title = $('#title').val();
var formData = {
'draw': data.draw,
'start': data.start,
'length': data.length,
'params': {
'typeId': $('#typeId').val(),
'name': $('#name').val()
}
}
console.log("-----form data------");
console.log(JSON.stringify(formData));
return formData;
}
},
columns: [
{ data: "entityId" },
{ data: "type.description" },
{ data: "name" },
{
data: "entityId",
render: function ( data, type, row, meta ) {
return '<a class="btn btn-success" href="<c:url value="/entity/mention-list?entityId=' + data + '" />">相关网页</a>';
}
}
]
});
}
function initTable() {
loadTable();
$("#example").css('display', 'block');
}
initTable();
function onSubmit() {
table.ajax.reload();
return false;
}
</script>
</body>
</html>
|
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Order } from './order.entity';
import { CreateOrderDto } from './dto/create-order.dto';
import { UpdateOrderDto } from './dto/update-order.dto';
@Injectable()
export class OrderService {
constructor(
@InjectRepository(Order)
private orderRepository: Repository<Order>,
) {}
create(createOrderDto: CreateOrderDto): Promise<Order> {
const order = this.orderRepository.create(createOrderDto);
return this.orderRepository.save(order);
}
findAll(): Promise<Order[]> {
return this.orderRepository.find();
}
findOne(id: string): Promise<Order> {
return this.orderRepository.findOne({ where: { id } });
}
async update(id: string, updateOrderDto: UpdateOrderDto): Promise<Order> {
await this.orderRepository.update(id, updateOrderDto);
return this.orderRepository.findOne({ where: { id } });
}
async remove(id: string): Promise<void> {
await this.orderRepository.delete(id);
}
}
|
/*
* Q5. High to Low - II
Problem Description
You are given uppercase string (S) and you have to return a string that is the lower case form of S.
Uppercase strings are those which have all letters in uppercase (Example: MACHINE)
Lowercase strings are those which have all letters in lowercase (Example: machine)
Problem Constraints
1 <= S.size() <= 1000
Input Format
First and only argument containing a uppercase string **S**.
Output Format
You have to return lowercase form of input string.
Example Input
Input 1:
INTERVIEWBIT
Input 2:
SCALER
Example Output
Output 1:
interviewbit
Output 2:
scaler
Example Explanation
Explanation 1:
Clearly, lowercase of INTERVIEWBIT is interviewbit.
Explanation 2:
Clearly, lowercase of SCALER is scaler.
*/
public class Q5_HighToLow_II {
public static String solve(String A) {
char[] str = A.toCharArray();
for(int i=0;i<str.length;i++)
{
if(str[i]>=65 && str[i]<=90){
str[i] = (char)(str[i] + 32);
}
}
return String.valueOf(str);
}
public static void main(String[] args) {
System.out.println(solve("INTERVIEWBIT"));
}
}
|
import pytest
from sklearn.ensemble import RandomForestClassifier
from src.models.train import load_dataset, encode_labels, train_model, evaluate_model
import mlflow
def test_load_dataset():
X_train, X_test, y_train, y_test = load_dataset()
assert X_train is not None
assert X_test is not None
assert y_train is not None
assert y_test is not None
assert len(X_train) > 0
assert len(X_test) > 0
assert len(y_train) > 0
assert len(y_test) > 0
def test_encode_labels():
_, _, y_train, _ = load_dataset()
y_encoded = encode_labels(y_train)
assert y_encoded is not None
assert len(y_encoded) == len(y_train)
def test_train_model():
X_train, _, y_train, _ = load_dataset()
y_train = encode_labels(y_train)
with mlflow.start_run():
model = train_model(X_train, y_train)
assert isinstance(model, RandomForestClassifier)
def test_evaluate_model():
X_train, X_test, y_train, y_test = load_dataset()
y_train = encode_labels(y_train)
y_test = encode_labels(y_test)
with mlflow.start_run():
model = train_model(X_train, y_train)
evaluate_model(model, X_test, y_test)
def test_end_to_end():
X_train, X_test, y_train, y_test = load_dataset()
y_train = encode_labels(y_train)
y_test = encode_labels(y_test)
with mlflow.start_run():
model = train_model(X_train, y_train)
evaluate_model(model, X_test, y_test)
assert isinstance(model, RandomForestClassifier)
assert model.n_estimators > 0
|
namespace AquaShop.Models.Aquariums
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AquaShop.Models.Aquariums.Contracts;
using AquaShop.Models.Decorations.Contracts;
using AquaShop.Models.Fish.Contracts;
using AquaShop.Utilities.Messages;
public abstract class Aquarium : IAquarium
{
private string name;
protected Aquarium(string name, int capacity)
{
Name = name;
Capacity = capacity;
Decorations = new List<IDecoration>();
Fish = new List<IFish>();
}
public string Name
{
get => this.name;
private set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(ExceptionMessages.InvalidAquariumName);
}
this.name = value;
}
}
public int Capacity { get; }
public int Comfort => Decorations.Sum(x => x.Comfort);
public ICollection<IDecoration> Decorations { get; }
public ICollection<IFish> Fish { get; }
public void AddDecoration(IDecoration decoration)
{
this.Decorations.Add(decoration);
}
public void AddFish(IFish fish)
{
if (this.Capacity == this.Fish.Count)
{
throw new InvalidOperationException(ExceptionMessages.NotEnoughCapacity);
}
this.Fish.Add(fish);
}
public void Feed()
{
foreach (IFish fish in this.Fish)
{
fish.Eat();
}
}
public string GetInfo()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"{Name} ({GetType().Name}):");
sb.AppendLine($"Fish: {(Fish.Any() ? string.Join(", ", GetFishNames()) : "none")}");
sb.AppendLine($"Decorations: {Decorations.Count}");
sb.AppendLine($"Comfort: {Comfort}");
return sb.ToString().TrimEnd();
}
public bool RemoveFish(IFish fish)
{
return this.Fish.Remove(fish);
}
private List<string> GetFishNames()
{
List<string> list = new List<string>();
foreach (var fish in Fish)
{
list.Add(fish.Name);
}
return list;
}
}
}
|
import { Star } from "@mui/icons-material";
import { Rating, Stack, Typography } from "@mui/material";
export const Card = ({ name, description, review, image }) => {
return (
<Stack
spacing={3}
p={4}
borderRadius={2}
border="1px solid #ffffff20"
bgcolor="#ffffff05"
alignItems="start"
>
<Stack direction="row" spacing={2} alignItems="center">
<img
style={{ borderRadius: "100%", aspectRatio: "1/1" }}
src={image}
width="64px"
height="64px"
alt=""
/>
<Stack>
<Typography variant="h6" fontWeight={600}>
{name}
</Typography>
<Typography variant="body2" color="secondary">
{description}
</Typography>
</Stack>
</Stack>
<Rating
defaultValue={5}
emptyIcon={<Star style={{ zIndex: -1 }} fontSize="inherit" />}
readOnly
/>
<Typography variant="body2" color="secondary">
{review}
</Typography>
</Stack>
);
};
|
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Tests\TestCase;
class RecipientTest extends TestCase
{
use RefreshDatabase;
public function test_file_has_not_recipient_and_200_response(): void
{
$user = User::factory()->create();
$response = $this
->actingAs($user)
->post(
route('api.v1.file-upload'),
[
'file' => UploadedFile::fake()
->createWithContent(
'test1.json',
file_get_contents(public_path('sample-file/recipient-test/testInvalidRecipient.json'))
)
]
);
$response
->assertJsonPath('data.result','invalid_recipient')
->assertStatus(200);
}
public function test_recipient_has_not_email_and_200_response()
{
$user = User::factory()->create();
$response = $this
->actingAs($user)
->post(
route('api.v1.file-upload'),
[
'file' => UploadedFile::fake()
->createWithContent(
'test1.json',
file_get_contents(public_path('sample-file/recipient-test/testInvalidRecipientEmail.json'))
)
]
);
$response
->assertJsonPath('data.result','invalid_recipient')
->assertStatus(200);
}
public function test_recipient_has_not_name_and_200_response()
{
$user = User::factory()->create();
$response = $this
->actingAs($user)
->post(
route('api.v1.file-upload'),
[
'file' => UploadedFile::fake()
->createWithContent(
'test1.json',
file_get_contents(public_path('sample-file/recipient-test/testInvalidRecipientName.json'))
)
]
);
$response
->assertJsonPath('data.result','invalid_recipient')
->assertStatus(200);
}
/*public function test_json_has_not_valid_invalid_issuer()
{
$user = User::factory()->create();
$response = $this
->actingAs($user)
->post(
route('api.v1.file-upload'),
[
'file' => UploadedFile::fake()
->createWithContent(
'test1.json',
file_get_contents(public_path('sample-file/testInvalidIssuer.json'))
)
]
);
$response->assertJsonPath('data.result','invalid_issuer');
}*/
}
|
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <algorithm>
// BEGIN CUT HERE
#include <iostream>
#include "cout.h"
// END CUT HERE
#include <sstream>
#include <cmath>
using namespace std;
#define sz(a) int((a).size())
#define pb push_back
#define all(c) (c).begin(),(c).end()
#define tr(c,i) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); i++)
#define rep(var,n) for(int var=0;var<(n);var++)
bool greater_by_length(const string& s1, const string& s2 )
{
return s1.length() > s2.length();
}
template <typename T> struct better : binary_function<T,T,bool> {
bool operator()(const T& X, const T& Y) const{
// at, score
if (X.first >= Y.first) return X.second < Y.second;
return false;
}
};
class SentenceDecomposition {
private:
bool abc[26];
bool usable(const string &str) {
rep(i,str.length()) if (!abc[str[i]-'a']) return false;
return true;
}
string strsort(const string &str) {
vector<char> buf(all(str));
sort(all(buf));
string sorted(all(buf));
return sorted;
}
int score(string orig, string word) {
int d = orig.length();
for (int i=d-1; i>=0; i--) if (orig[i] == word[i]) d--;
return d;
}
public:
int decompose(string sentence, vector<string> validWords) {
int l=sentence.length();
rep(i,26) abc[i] = false;
rep(i,l) abc[sentence[i]-'a'] = true;
set<string> s;
tr(validWords,wt) if (usable(*wt)) s.insert(*wt);
vector<string> valids(all(s));
sort(all(valids),greater_by_length);
int n=valids.size();
vector<string> words(n);
rep(i,n) {
words[i] = strsort(valids[i]);
}
priority_queue<pair<int,int>, vector<pair<int,int> >, better<pair<int,int> > > pq;
vector<int> said(l+1,INT_MAX);
rep(i,n) {
int wl = words[i].length();
if (0+wl <= l) {
string ss = sentence.substr(0,wl);
if (strsort(ss) == words[i]) {
int sc = score(valids[i],ss);
if (sc < said[wl]) {
pair<int,int> p = make_pair(wl,sc);
pq.push(p);
said[wl] = sc;
}
}
}
}
int topscore = INT_MAX;
while (!pq.empty()) {
int at = pq.top().first, pt = pq.top().second;
pq.pop();
if (at == l) {
topscore = min(topscore,pt);
continue;
}
rep(i,n) {
int wl = words[i].length();
if (at+wl <= l) {
string ss = sentence.substr(at,wl);
if (strsort(ss) == words[i]) {
int newscore = pt+score(valids[i],ss);
if (newscore < topscore) {
if (newscore < said[at+wl]) {
pair<int,int> p = make_pair(at+wl,newscore);
pq.push(p);
said[at+wl] = newscore;
}
}
}
}
}
}
return (topscore == INT_MAX)? -1 : topscore;
}
};
|
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
enum platforma { Zoom, Skype, Teams, Empty };
class Participanti
{
public:
string nume;
int grupa;
int varsta;
Participanti()
{
nume = "Anonim";
varsta = 18;
grupa = 1000;
}
};
class Videoconferinta
{
private:
const int idConferinta;
bool ok = false;
protected:
char* denumire;
platforma platfomarUtilizata;
string oraIncepere; //formatul 00:00
public:
int data[2]; //zilele lunii
int nrParticipanti;
Participanti* participanti;
static int capacitateMaxima;
static int numarator;
Videoconferinta() : idConferinta(numarator++)
{
this->data[0] = 1;
this->data[1] = 1;
this->denumire = new char[strlen("") + 1];
strcpy_s(this->denumire, strlen("") + 1, "");
this->platfomarUtilizata = Empty;
this->oraIncepere = "Necunoscuta";
this->nrParticipanti = 1;
this->participanti = new Participanti[nrParticipanti];
Participanti p;
this->participanti[0] = p;
}
Videoconferinta(const char* denumire, platforma platformaUtilizata, string oraIncepere, int nrParticipanti, Participanti* participanti, int zi, int luna) :idConferinta(numarator++)
{
if (zi > 0 && zi < 31 && luna>0 && luna < 13)
{
this->data[0] = zi;
this->data[1] = luna;
}
else
{
this->data[0] = 1;
this->data[1] = 1;
}
if (strlen(denumire) > 2)
{
this->denumire = new char[strlen(denumire) + 1];
strcpy_s(this->denumire, strlen(denumire) + 1, denumire);
}
else
{
this->denumire = new char[strlen("") + 1];
strcpy_s(this->denumire, 2, "");
}
if (oraIncepere.size() == 5)
{
this->oraIncepere = oraIncepere;
}
else
{
this->oraIncepere = "Necunoscuta";
}
if (nrParticipanti > 0 && participanti != NULL)
{
delete[] this->participanti;
this->nrParticipanti = nrParticipanti;
this->participanti = new Participanti[nrParticipanti];
for (int i = 0; i < nrParticipanti; i++)
{
this->participanti[i] = participanti[i];
}
}
this->platfomarUtilizata = platfomarUtilizata;
}
~Videoconferinta()
{
if (this->denumire != NULL)
{
delete[] this->denumire;
}
if (this->participanti != nullptr)
{
delete[] this->participanti;
}
}
Videoconferinta(const Videoconferinta& v) :idConferinta(v.idConferinta)
{
if (v.data[0] > 0 && v.data[0] < 31 && data[1]>0 && data[1] < 13)
{
this->data[0] = v.data[0];
this->data[1] = v.data[1];
}
else
{
this->data[0] = 1;
this->data[1] = 1;
}
if (strlen(v.denumire) > 2)
{
this->denumire = new char[strlen(v.denumire) + 1];
strcpy_s(this->denumire, strlen(v.denumire) + 1, v.denumire);
}
else
{
this->denumire = new char[strlen("") + 1];
strcpy_s(this->denumire, 2, "");
}
if (v.oraIncepere.size() == 5)
{
this->oraIncepere = v.oraIncepere;
}
else
{
this->oraIncepere = "Necunoscuta";
}
if (v.nrParticipanti > 0 && v.participanti != nullptr)
{
this->nrParticipanti = v.nrParticipanti;
this->participanti = new Participanti[v.nrParticipanti];
for (int i = 0; i < v.nrParticipanti; i++)
{
this->participanti[i] = v.participanti[i];
}
}
else
{
this->nrParticipanti = 1;
this->participanti = new Participanti[nrParticipanti];
Participanti p;
this->participanti[0] = p;
}
this->platfomarUtilizata = v.platfomarUtilizata;
}
Videoconferinta& operator= (const Videoconferinta& v)
{
if (this != &v)
{
if (this->participanti != nullptr)
{
delete[] this->participanti;
}
if (this->denumire != NULL)
{
delete[] this->denumire;
}
if (strlen(v.denumire) > 2)
{
this->denumire = new char[strlen(v.denumire) + 1];
strcpy_s(this->denumire, strlen(v.denumire) + 1, v.denumire);
}
else
{
this->denumire = new char[strlen("") + 1];
strcpy_s(this->denumire, 2, "");
}
if (v.oraIncepere.size() == 5)
{
this->oraIncepere = v.oraIncepere;
}
else
{
this->oraIncepere = "Necunoscuta";
}
if (v.nrParticipanti > 0 && v.participanti != nullptr)
{
this->nrParticipanti = v.nrParticipanti;
this->participanti = new Participanti[v.nrParticipanti];
for (int i = 0; i < v.nrParticipanti; i++)
{
this->participanti[i] = v.participanti[i];
}
}
else
{
this->nrParticipanti = 1;
this->participanti = new Participanti[nrParticipanti];
Participanti p;
this->participanti[0] = p;
}
if (v.data[0] > 0 && v.data[0] < 31 && data[1]>0 && data[1] < 13)
{
this->data[0] = v.data[0];
this->data[1] = v.data[1];
}
else
{
this->data[0] = 1;
this->data[1] = 1;
}
this->platfomarUtilizata = v.platfomarUtilizata;
return *this;
}
}
bool operator <(Videoconferinta v)
{
if (data[1] == v.data[1])
{
return data[0] < v.data[0];
}
else
{
return data[1] < v.data[1];
}
}
bool operator== (Videoconferinta v)
{
return data[0] == v.data[0] && data[1] == v.data[1];
}
Videoconferinta& operator += (Videoconferinta v)
{
this->nrParticipanti += v.nrParticipanti;
return *this;
}
Videoconferinta& operator ++(int)
{
Videoconferinta copie = *this;
this->data[0]++;
return copie;
}
operator int()
{
return nrParticipanti;
}
Participanti& operator[](int pos)
{
if (pos >= 0 && pos < nrParticipanti)
{
return this->participanti[pos];
}
}
char* operator()()
{
return getDenumire();
}
char* getDenumire()
{
return this->denumire;
}
bool operator !()
{
return !ok;
}
bool operator != (Videoconferinta v)
{
return ok != v.ok;
}
friend ostream& operator << (ostream& out, const Videoconferinta& v)
{
out << "Denumire: "<< v.denumire << endl;
return out;
}
friend ofstream& operator << (ofstream& out, const Videoconferinta& v)
{
out << "Denumire: " << v.denumire << endl;
return out;
}
friend istream& operator >> (istream& in, Videoconferinta& v)
{
if (v.denumire != NULL)
{
delete[] v.denumire;
}
char aux[100];
in.getline(aux, 99);
v.denumire = new char[strlen(aux) + 1];
strcpy_s(v.denumire, strlen(aux) + 1, aux);
return in;
}
friend ifstream& operator >> (ifstream& in, Videoconferinta& v)
{
if (v.denumire != NULL)
{
delete[] v.denumire;
}
char aux[100];
in.getline(aux, 99);
v.denumire = new char[strlen(aux) + 1];
strcpy_s(v.denumire, strlen(aux) + 1, aux);
return in;
}
void setDenumire(const char* denumire)
{
if (strlen(denumire) > 2)
{
if (this->denumire != NULL)
{
delete[] this->denumire;
}
this->denumire = new char[strlen(denumire) + 1];
strcpy_s(this->denumire, strlen(denumire), denumire);
}
}
};
int Videoconferinta::numarator = 1;
int Videoconferinta::capacitateMaxima = 50;
class VideoconferintaScoala : public Videoconferinta
{
public:
int nrElevi;
string* elevi;
VideoconferintaScoala()
{
nrElevi = 1;
elevi = new string[nrElevi];
elevi[0] = "Gigel";
}
VideoconferintaScoala(const char* denumire, platforma platformaUtilizata, string oraIncepere, int nrParticipanti, Participanti* participanti, int zi, int luna, int nrElevi, string* elevi) : Videoconferinta(denumire, platformaUtilizata, oraIncepere, nrParticipanti, participanti, zi, luna)
{
if (nrElevi > 0 && elevi != NULL)
{
this->nrElevi = nrElevi;
this->elevi = new string[nrElevi];
for (int i = 0; i < nrElevi; i++)
{
this->elevi[i] = elevi[i];
}
}
}
};
Videoconferinta& operator++(Videoconferinta& v)
{
Videoconferinta::capacitateMaxima++;
return v;
}
int main()
{
Participanti p1;
Participanti p2;
Participanti p3;
Participanti participanti[] = { p1, p2, p3 };
string nume[] = { "Ion", "Gigea", "Sandu" };
Videoconferinta v;
Videoconferinta v2("POO", Zoom, "14:43", 3, participanti, 1, 1);
VideoconferintaScoala vS("POO", Zoom, "14:43", 3, participanti, 1, 1, 3, nume);
v = v2;
//cout << v.getDenumire()<<endl;
//cout<< (v == v2)<<endl;
//cout << Videoconferinta::capacitateMaxima<<endl;
v++;
//cout << Videoconferinta::capacitateMaxima<<endl;
v += v2;
v[0].grupa = 1054;
VideoconferintaScoala a;
cout << v[0].grupa;
cout << vS.nrElevi << endl << vS.data[1] << endl << vS.elevi[1];
ifstream in("input.txt");
in >> v;
ofstream out("output.txt");
out << v;
}
|
function [w,u_mat,d_in_g] = selforgmapi(d,g,w,n_iter)
% diego domenzain
% Boise State University
% ---------------------------------------------------------------------------
% builds self-organizing map from:
% data points d and graph g.
% ---------
% g -> is an incidence relation, e.g. (but not limited to):
% g = graph_grid(ny,nx);
% that is, a cube (ny x nx x 5) where:
% the first (ny x nx) plane labels of the nodes,
% the second (ny x nx) plane labels the right neighbors,
% etc.
% g has to be of size (#of-nodes by max-#of-neighbors)
% d -> is data where rows are attributes and
% columns are data points.
% w -> are initial weights on graph g, e.g. geometrical coordinates in R^n.
% Rows are entries of R^n, columns are nodes in the grid.
% For example,
% w = w_in_grid(v,u,ny,nx);
% where v and u are the vectors spanning a plane in R^n.
% ----------
% u_mat -> is a u-matrix: a matrix in form of a list
% of size (#of-nodes by 1) where rows are nodes indexed
% by their number and entry of row i is the average distance
% of node #i to its neighbors. For example,
% u_mat = u_matrix(g,w);
% d_in_g -> is a matrix of size (#of-data-pts by 1)
% where each entry answers:
% "which data points are near which graph points?", that is
% entry of row i is the graph node closest to data point i (euclid).
% For example,
% d_in_g = data_in_g(g,d,w);
% ------------------------------------------------------------------------------
% data points are columns, attributes are rows,
% like a boring excel sheet transposed.
[n_atributes,nd] = size(d);
n_nodes = size(g,1);
% -----------
std_ = 8;
amp = 2;
tau = 1;
% ------------------------------------------------------------------------------
%
% main loop
%
% ------------------------------------------------------------------------------
iter = 0;
choose_list = randperm(nd);
while iter<n_iter
% choose data point
if numel(choose_list)==0
choose_list = randperm(nd);
end
d_ = d(:,choose_list(1));
choose_list(1) = [];
% initialize "best matching unit" (bmu)
bmu = zeros(n_nodes,1);
for i_=1:n_nodes % parforable
bmu(i_) = norm(d_-w(:,i_));
end
% get bmu: bmu has to be w(:,bmu)
[~,bmu] = min(bmu);
% get neighbors of bmu,
% non-zero entries of g at node bmu
nei = find(g(bmu,:));
% these are the actual neighboors
nei = g(bmu,nei);
% AND bmu itself
nei = [nei bmu];
n_nei = numel(nei);
% update neighbors
for i_=1:n_nei % parforable
% w(:,nei(i_)) = w(:,nei(i_)) +...
% thet(w(:,bmu),w(:,nei(i_)),std_,iter)*alp(iter,amp,tau)*(d_-w(:,nei(i_)));
% r=rand(n_atributes,1);
% w(:,nei(i_)) = w(:,nei(i_)) + 0.4*(d_-w(:,nei(i_))) + 0.01*(2*(r-mean(r)));
w(:,nei(i_)) = w(:,nei(i_)) + 0.4*(d_-w(:,nei(i_)));
end
iter = iter+1;
end
% --------------
% now that the main loop is done,
% we have all nodes in the graph covering the data points in data space:
% node i is in position w(:,i).
% ---------------
% now get cute bw plot of distances between neighboring weights,
% aka u-matrix.
u_mat = u_matrix(g,w);
% ---------------
% which data points are near which graph points?
d_in_g = data_in_g(g,d,w);
end
% ------------------------------------------------------------------------------
% ------------------------------------------------------------------------------
% ------------------------------------------------------------------------------
function t = thet(u,v,std_,iter)
dist = norm(u-v);
t = exp(-dist/(2*std_^2) );
end
function a = alp(iter,amp,tau)
a = amp*exp(- iter );
end
|
<template>
<div id="box">
<p v-ellipsis:200>{{text}}</p>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
function ellipsis (el, binding) {
el.style.width = (binding.arg || 100) + 'px'
el.style.whiteSpace = 'nowrap'
el.style.overflow = 'hidden';
el.style.textOverflow = 'ellipsis';
}
const vEllipsis = {
created: function(el, binding) {
console.log(getComputedStyle(el).width, 'created')
ellipsis(el, binding)
},
mounted: function(el, binding) {
console.log(getComputedStyle(el).width, 'mounted')
ellipsis(el, binding)
},
updated: function(el, binding) {
console.log(getComputedStyle(el).width, 'update')
ellipsis(el, binding)
}
}
onMounted(() => {
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
console.log(Array.from(arrayLike))
})
const text = ref('')
setTimeout(() => {
text.value = '今天是星期六, 今天是星期六今天是星期六今天是星期六'
}, 200)
//----------------------------------------------------------------------------------------------------------------------
</script>
|
//
// CustomItemsList.swift
// MealJournal
//
// Created by Jim Ciaston on 9/28/22.
//
import SwiftUI
import SwiftUIX
import FirebaseFirestore
import Firebase
struct CustomItemsList: View {
@EnvironmentObject var mealEntryObj: MealEntrys
@StateObject private var foodApi = FoodApiSearch()
@ObservedObject var logic = CustomFoodLogic()
@State var mealTimingToggle = false
@State var sheetMode: SheetMode = .none // << communicates with mealtimings
@State var MealObject = Meal()
@Binding var isViewSearching: Bool
@Binding var userSearch: Bool
@State var resultsShowing = 5
@State var addCustomFoodToggle = false
@Binding var hideTitleRows: Bool
@State var showDeleteItemView = false
var screensize = UIScreen.main.bounds.height
var body: some View {
VStack{
List{
ForEach (logic.customFoodItems.prefix(resultsShowing), id: \.self ) { item in
CustomItemListRow(mealTimingToggle: $mealTimingToggle,sheetMode: $sheetMode, MealObject: $MealObject, isViewSearching: $isViewSearching, userSearch: $userSearch, resultsShowing: $resultsShowing, showDeleteItemView: $showDeleteItemView, item: .constant(item), mealName: item.mealName ?? "Invalid Name", customMealID: item.id, dismissResultsView: $hideTitleRows)
}
Button(action: {
withAnimation(.linear(duration: 0.25)){
addCustomFoodToggle.toggle()
}
}){
//return nothing if no custom items for user
if logic.customFoodItems.count > 0{
Text("Add Custom Food Item")
.foregroundColor(.white)
.frame(maxWidth: .infinity, alignment: .center)
.padding([.top, .bottom], 15)
.background(RoundedRectangle(
cornerRadius:20).fill(Color("UserProfileCard2")))
.foregroundColor(.black)
}
else{
VStack{
Text("Currently no custom food items")
.font(.title2)
Button(action: {
addCustomFoodToggle.toggle()
}){
Image(systemName:"plus")
.resizable()
.frame(width:30, height: 30)
}
}
}
}
.frame(maxWidth: .infinity)
.padding([.top, .bottom], 15)
.multilineTextAlignment(.center)
Text("View More")
.padding(.top, 10)
.onTapGesture {
resultsShowing += 5
}
.frame(maxWidth: .infinity, alignment: .center)
Button(action: {
isViewSearching = false
userSearch = false
}){
if logic.customFoodItems.count > 0{
Text("Cancel Search")
.frame(maxWidth: .infinity, alignment: .trailing)
}
}
.foregroundColor(.red)
.font(.caption)
.frame(maxWidth: .infinity)
.padding(.top, -10)
.listRowSeparator(.hidden)
//using windowOverlay from swiftUIX to hide TabBar
.windowOverlay(isKeyAndVisible: self.$addCustomFoodToggle, {
GeometryReader { geometry in {
BottomSheetView(
isOpen: self.$addCustomFoodToggle,
maxHeight: screensize - 200, minHeight: 300
) {
CustomFoodItemView(showing: $addCustomFoodToggle, isViewSearching: $isViewSearching, userSearch: $userSearch)
.environmentObject(mealEntryObj)
.animation(.easeInOut)
.background(.white)
.transition(AnyTransition.move(edge: .bottom).combined(with: .opacity))
}
.frame(maxHeight: .infinity)
.transition(AnyTransition.move(edge: .bottom).combined(with: .opacity))
}().edgesIgnoringSafeArea(.all)
}
})
}
}
.opacity(!showDeleteItemView ? 1 : 0.4)
.opacity(!mealTimingToggle ? 1 : 0.4)
.opacity(!addCustomFoodToggle ? 1 : 0.4)
if(mealTimingToggle){
FlexibleSheet(sheetMode: $sheetMode) {
MealTimingSelectorView(meal: $MealObject, isViewSearching: $isViewSearching, userSearch: $userSearch, mealTimingToggle: $mealTimingToggle, extendedViewOpen: .constant(false), mealSelected: .constant(true))
}
.padding(.top, -150)
///when adjusting frame height for sheet, must adjust heights on flexible sheet and meal timing selector view or will display weird
.frame(height:240)
.animation(.easeInOut)
}
}
}
//struct CustomItemsList_Previews: PreviewProvider {
// static var previews: some View {
// CustomItemsList()
// }
//}
|
<div id="top"></div>
<!-- https://github.com/othneildrew/Best-README-Template >
<!-- PROJECT SHIELDS -->
<!--
*** I'm using markdown "reference style" links for readability.
*** Reference links are enclosed in brackets [ ] instead of parentheses ( ).
*** See the bottom of this document for the declaration of the reference variables
*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.
*** https://www.markdownguide.org/basic-syntax/#reference-style-links
-->
[![Contributors][contributors-shield]][contributors-url]
[![Forks][forks-shield]][forks-url]
[![Stargazers][stars-shield]][stars-url]
[![Issues][issues-shield]][issues-url]
[![MIT License][license-shield]][license-url]
[![LinkedIn][linkedin-shield]][linkedin-url]
<!-- PROJECT LOGO -->
<div align="center">
<h1 align="center">Astro Template</h1>
<p align="center">
Basic react template with typescript, vite and tailwind css
<br />
<a href="https://github.com/jesusvallez/astro-tailwind-eslint-prettier"><strong>Explore the docs »</strong></a>
<br />
<br />
<a href="https://react-ts-eslint-tailwind.netlify.app/">View Demo</a>
-
<a href="https://github.com/jesusvallez/astro-tailwind-eslint-prettier/issues">Report Bug</a>
·
<a href="https://github.com/jesusvallez/astro-tailwind-eslint-prettier/issues">Request Feature</a>
</p>
</div>
<!-- Features -->
## Features
This starter template contains:
- ⚛️ [Astro 4](https://astro.build/)
- 🎐 [Tailwind CSS 3](https://tailwindcss.com/)
- 💎 [Typescript](https://www.typescriptlang.org/) strongly typed programming language
- 🪄 [Prettier 3](https://prettier.io/) — Format your code automatically, this will also run **on save**
- 🧼 [ESLint](https://eslint.org/) — Find & fix problems in your code, and **removing** your unused variables
- 🐶 [Husky](https://www.npmjs.com/package/husky) — Git hooks to impreve your commits
- 📜 [Commit Lint](https://github.com/conventional-changelog/commitlint) — Make sure the commit message follows the conventional commit
- 🔗 [Absolute Import](./tsconfig.json) — Import modules using `@/` prefix
<p align="right">(<a href="#top">back to top</a>)</p>
## 🧞 Commands
All commands are run from the root of the project, from a terminal:
| Command | Action |
| :------------------------- | :----------------------------------------------- |
| `pnpm install` | Installs dependencies |
| `pnpm run dev` | Starts local dev server at `localhost:4321` |
| `pnpm run build` | Build your production site to `./dist/` |
| `pnpm run preview` | Preview your build locally, before deploying |
| `pnpm run astro ...` | Run CLI commands like `astro add`, `astro check` |
| `pnpm run astro -- --help` | Get help using the Astro CLI |
## 👀 Want to learn more?
Feel free to check [our documentation](https://docs.astro.build) or jump into our [Discord server](https://astro.build/chat).
<!-- MARKDOWN LINKS & IMAGES -->
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[contributors-shield]: https://img.shields.io/github/contributors/jesusvallez/astro-tailwind-eslint-prettier.svg?style=for-the-badge
[contributors-url]: https://github.com/jesusvallez/astro-tailwind-eslint-prettier/graphs/contributors
[forks-shield]: https://img.shields.io/github/forks/jesusvallez/astro-tailwind-eslint-prettier.svg?style=for-the-badge
[forks-url]: https://github.com/jesusvallez/astro-tailwind-eslint-prettier/network/members
[stars-shield]: https://img.shields.io/github/stars/jesusvallez/astro-tailwind-eslint-prettier.svg?style=for-the-badge
[stars-url]: https://github.com/jesusvallez/astro-tailwind-eslint-prettier/stargazers
[issues-shield]: https://img.shields.io/github/issues/jesusvallez/astro-tailwind-eslint-prettier.svg?style=for-the-badge
[issues-url]: https://github.com/jesusvallez/astro-tailwind-eslint-prettier/issues
[license-shield]: https://img.shields.io/github/license/jesusvallez/astro-tailwind-eslint-prettier.svg?style=for-the-badge
[license-url]: https://github.com/jesusvallez/astro-tailwind-eslint-prettier/blob/master/LICENSE.txt
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555
[linkedin-url]: https://linkedin.com/in/jesusvallez
[product-screenshot]: images/screenshot.png
|
/*
* hmi.c
*
* Created: Apr 2021
* Author: Arjan te Marvelde
*
* This file contains the HMI driver, processing user inputs.
* It will also do the logic behind these, and write feedback to the display.
*
* The 4 auxiliary buttons have the following functions:
* GP6 - Enter, confirm : Used to select menu items or make choices from a list
* GP7 - Escape, cancel : Used to exit a (sub)menu or cancel the current action
* GP8 - Left : Used to move left, e.g. to select a digit
* GP9 - Right : Used to move right, e.g. to select a digit
*
* The rotary encoder (GP2, GP3) controls an up/down counter connected to some field.
* It may be that the encoder has a bushbutton as well, this can be connected to GP4.
* ___ ___
* ___| |___| |___ A
* ___ ___ _
* _| |___| |___| B
*
* Encoder channel A triggers on falling edge.
* Depending on B level, count is incremented or decremented.
*
* The PTT is connected to GP15 and will be active, except when VOX is used.
*
*/
#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "hardware/timer.h"
#include "hardware/clocks.h"
#include "hardware/gpio.h"
#include "n3b_rx_main.h"
#include "ili9341.h"
#include "adf4360.h"
#include "hmi.h"
#include "dsp.h"
static int old_sdr_freq = 0;
static uint16_t waterfall_buffer[300][40];
static uint8_t waterfall_active_row = 0;
/*
* GPIO masks
*/
#define GP_MASK_IN ((1<<GP_ENC_A)|(1<<GP_ENC_B)|(1<<GP_AUX_0)|(1<<GP_AUX_1)|(1<<GP_AUX_2)|(1<<GP_AUX_3)|(1<<GP_PTT))
#define GP_MASK_PTT (1<<GP_PTT)
/*
* Event flags
*/
#define GPIO_IRQ_ALL (GPIO_IRQ_LEVEL_LOW|GPIO_IRQ_LEVEL_HIGH|GPIO_IRQ_EDGE_FALL|GPIO_IRQ_EDGE_RISE)
#define GPIO_IRQ_EDGE_ALL (GPIO_IRQ_EDGE_FALL|GPIO_IRQ_EDGE_RISE)
/*
* Display layout:
* +----------------+
* |USB 14074.0 R920| --> mode=USB, freq=14074.0kHz, state=Rx,S9+20dB
* | Fast -10dB| --> ..., AGC=Fast, Pre=-10dB
* +----------------+
* In this HMI state only tuning is possible,
* using Left/Right for digit and ENC for value, Enter to commit change.
* Press ESC to enter the submenu states (there is only one sub menu level):
*
* Submenu Values ENC Enter Escape Left Right
* -----------------------------------------------------------------------------------------------
* Mode USB, LSB, AM, CW change commit exit prev next
* AGC Fast, Slow, Off change commit exit prev next
* Pre +10dB, 0, -10dB, -20dB, -30dB change commit exit prev next
* Vox NoVOX, Low, Medium, High change commit exit prev next
*
* --will be extended--
*/
/* State definitions */
#define HMI_S_TUNE 0
#define HMI_S_MODE 1
#define HMI_S_AGC 2
#define HMI_S_PRE 3
#define HMI_S_VOX 4
#define HMI_S_BPF 5
#define HMI_NSTATES 6
/* Event definitions */
#define HMI_E_NOEVENT 0
#define HMI_E_INCREMENT 1
#define HMI_E_DECREMENT 2
#define HMI_E_ENTER 3
#define HMI_E_ESCAPE 4
#define HMI_E_LEFT 5
#define HMI_E_RIGHT 6
#define HMI_E_PTTON 7
#define HMI_E_PTTOFF 8
#define HMI_NEVENTS 9
/* Sub menu option string sets */
#define HMI_NTUNE 6
#define HMI_NMODE 4
#define HMI_NAGC 3
#define HMI_NPRE 5
#define HMI_NVOX 4
#define HMI_NBPF 5
char hmi_noption[HMI_NSTATES] = {HMI_NTUNE, HMI_NMODE, HMI_NAGC, HMI_NPRE, HMI_NVOX, HMI_NBPF};
const char* hmi_o_menu[HMI_NSTATES] = {"Tune","Mode","AGC","Pre","VOX"}; // Indexed by hmi_state
const char* hmi_o_mode[HMI_NMODE] = {"USB","LSB","AM ","CW "}; // Indexed by hmi_sub[HMI_S_MODE]
const char* hmi_o_agc [HMI_NAGC] = {"NoGC","Slow","Fast"}; // Indexed by hmi_sub[HMI_S_AGC]
const char* hmi_o_pre [HMI_NPRE] = {"-30dB","-20dB","-10dB"," 0dB","+10dB"}; // Indexed by hmi_sub[HMI_S_PRE]
const char* hmi_o_vox [HMI_NVOX] = {"NoVOX","VOX-L","VOX-M","VOX-H"}; // Indexed by hmi_sub[HMI_S_VOX]
const char* hmi_o_bpf [HMI_NBPF] = {"<2.5","2-6","5-12","10-24","20-40"}; // Indexed by hmi_sub[HMI_S_BPF]
// Map option to setting
int hmi_mode[HMI_NMODE] = {MODE_USB, MODE_LSB, MODE_AM, MODE_CW};
int hmi_agc[HMI_NAGC] = {AGC_NONE, AGC_SLOW, AGC_FAST};
int hmi_vox[HMI_NVOX] = {VOX_OFF, VOX_LOW, VOX_MEDIUM, VOX_HIGH};
int hmi_state, hmi_option; // Current state and menu option selection
int hmi_sub[HMI_NSTATES] = {4,0,0,3,0,2}; // Stored option selection per state
bool hmi_update; // display needs update
uint32_t hmi_freq; // Frequency from Tune state
uint32_t hmi_step[6] = {1000000, 100000, 10000, 1000, 100, 10}; // Frequency digit increments
#define HMI_MAXFREQ 30000000
#define HMI_MINFREQ 100
#define HMI_MULFREQ 1 // Factor between HMI and actual frequency
// Set to 2 for certain types of mixer
#define PTT_DEBOUNCE 3 // Nr of cycles for debounce
int ptt_state; // Debounce counter
bool ptt_active; // Resulting state
/*
* Some macros
*/
#ifndef MIN
#define MIN(x, y) ((x)<(y)?(x):(y)) // Get min value
#endif
#ifndef MAX
#define MAX(x, y) ((x)>(y)?(x):(y)) // Get max value
#endif
/*
* GPIO IRQ callback routine
* Sets the detected event and invokes the HMI state machine
*/
void hmi_callback(uint gpio, uint32_t events)
{
uint8_t evt=HMI_E_NOEVENT;
// Decide what the event was
switch (gpio)
{
case GP_ENC_A: // Encoder
if (events&GPIO_IRQ_EDGE_FALL)
evt = gpio_get(GP_ENC_B)?HMI_E_INCREMENT:HMI_E_DECREMENT;
break;
case GP_AUX_0: // Enter
if (events&GPIO_IRQ_EDGE_FALL)
evt = HMI_E_ENTER;
break;
case GP_AUX_1: // Escape
if (events&GPIO_IRQ_EDGE_FALL)
evt = HMI_E_ESCAPE;
break;
case GP_AUX_2: // Previous
if (events&GPIO_IRQ_EDGE_FALL)
evt = HMI_E_LEFT;
break;
case GP_AUX_3: // Next
if (events&GPIO_IRQ_EDGE_FALL)
evt = HMI_E_RIGHT;
break;
default: // Stray...
return;
}
/** HMI State Machine **/
// Special case for TUNE state
if (hmi_state == HMI_S_TUNE)
{
switch (evt)
{
case HMI_E_ENTER: // Commit current value
// To be defined action
break;
case HMI_E_ESCAPE: // Enter submenus
hmi_sub[hmi_state] = hmi_option; // Store selection (i.e. digit)
hmi_state = HMI_S_MODE; // Should remember last one
hmi_option = hmi_sub[hmi_state]; // Restore selection of new state
break;
case HMI_E_INCREMENT:
if (hmi_freq < (HMI_MAXFREQ - hmi_step[hmi_option])) // Boundary check
hmi_freq += hmi_step[hmi_option]; // Increment selected digit
break;
case HMI_E_DECREMENT:
if (hmi_freq > (HMI_MINFREQ + hmi_step[hmi_option])) // Boundary check
hmi_freq -= hmi_step[hmi_option]; // Decrement selected digit
break;
case HMI_E_RIGHT:
hmi_option = (hmi_option<5)?hmi_option+1:5; // Digit to the right
break;
case HMI_E_LEFT:
hmi_option = (hmi_option>0)?hmi_option-1:0; // Digit to the left
break;
}
return; // Early bail-out
}
// Actions for other states
switch (evt)
{
case HMI_E_ENTER:
hmi_sub[hmi_state] = hmi_option; // Store value for selected option
hmi_update = true; // Mark HMI updated: activate value
break;
case HMI_E_ESCAPE:
hmi_state = HMI_S_TUNE; // Leave submenus
hmi_option = hmi_sub[hmi_state]; // Restore selection of new state
break;
case HMI_E_RIGHT:
hmi_state = (hmi_state<HMI_NSTATES-1)?(hmi_state+1):1; // Change submenu
hmi_option = hmi_sub[hmi_state]; // Restore selection of new state
break;
case HMI_E_LEFT:
hmi_state = (hmi_state>1)?(hmi_state-1):HMI_NSTATES-1; // Change submenu
hmi_option = hmi_sub[hmi_state]; // Restore selection of new state
break;
case HMI_E_INCREMENT:
hmi_option = (hmi_option<hmi_noption[hmi_state]-1)?hmi_option+1:hmi_noption[hmi_state]-1;
break;
case HMI_E_DECREMENT:
hmi_option = (hmi_option>0)?hmi_option-1:0;
break;
}
}
#define SPECTRUM_WIDTH 300
#define SPECTRUM_HEIGHT 40
/*
* Draw Spectrum
* TODO: add logaritmic scale
* if valus is same don't draw
* delete in length of old level
* replace 300 with a define
*/
void hmi_draw_spectrum(void)
{
int16_t* fft_buffer = get_fft_buffer_address();
if (waterfall_active_row == SPECTRUM_HEIGHT) waterfall_active_row = 0; //go to next buffer for net call
uint16_t* wf_act_p = &waterfall_buffer[waterfall_active_row][0]; //target memory is the first element of active waterfall buffer
int imm = 0;
for (int spectrum_pos = 0; spectrum_pos<SPECTRUM_WIDTH; spectrum_pos++)
{
//printf("%d\n",*fft_buffer++ >> 8);
// ili9341_draw_pixel(aa,150, *fft_buffer++);
//spectrum
//BD ili9341_draw_line(spectrum_pos+10,100,spectrum_pos+10,160, ILI9341_BLACK);//*fft_buffer++);
GFX_drawFastVLine(spectrum_pos+10, 100, 100, ILI9341_BLACK);
uint16_t signal_strength = abs(*fft_buffer++ + *fft_buffer++ + *fft_buffer++);
signal_strength = signal_strength>>10;
//BD ili9341_draw_line(spectrum_pos+10,160,spectrum_pos+10,160-signal_strength, ILI9341_GREEN);//*fft_buffer++);
GFX_drawFastVLine(spectrum_pos+10, 160, signal_strength, ILI9341_GREEN);
//waterfall
uint16_t waterfall_color = signal_strength << 11 | signal_strength << 5 | signal_strength;
*wf_act_p = signal_strength; // waterfall_active_row * 300 + imm;//
imm++;
wf_act_p++;
//BD ili9341_draw_pixel(spectrum_pos+10,168+waterfall_active_row, signal_strength<<10);//*fft_buffer++);
GFX_drawPixel(spectrum_pos+10,168+waterfall_active_row, signal_strength<<10);
//printf("[%d] %d %x\n", waterfall_active_row, signal_strength, waterfall_color);
}
waterfall_active_row++;
//BD ILI9341_setAddrWindow(10, 190, 310, 219);
// ILI9341_copyFrameBufferToDisplay(&waterfall_buffer[0][0], 300, 40); //redraw the waterfall
}
/*
* Draw bandwidth
* TODO: add bandwidth parameter
* add mod type
* add Cnter frequency
*/
void hmi_draw_bandwidth(void)
{
int sdr_freq = ((vfo[0].freq/100) % 30) ;
// ili9341_draw_line(sdr_freq*10,220,sdr_freq*10,200, ILI9341_RED);//*fft_buffer++);
//BD ili9341_draw_line(old_sdr_freq,167,old_sdr_freq+5,162, ILI9341_BLACK);
//BD ili9341_draw_line(old_sdr_freq+5,162,old_sdr_freq+50,162, ILI9341_BLACK);
//BD ili9341_draw_line(old_sdr_freq+50,162,old_sdr_freq+55,167, ILI9341_BLACK);
//BD ili9341_draw_line(sdr_freq,167,sdr_freq+5,162, ILI9341_CYAN);
//BD ili9341_draw_line(sdr_freq+5,162,sdr_freq+50,162, ILI9341_CYAN);
//BD ili9341_draw_line(sdr_freq+50,162,sdr_freq+55,167, ILI9341_CYAN);
// printf("%d-------------%d------------\n", sdr_freq, old_sdr_freq);
old_sdr_freq = sdr_freq;
}
/*
* Redraw the display, representing current state
* This function is invoked regularly from the main loop.
*/
void hmi_evaluate(void)
{
char s[32];
// Print top line of display
GFX_setCursor(10,75);
if (tx_enabled)
GFX_printf("10489,%6.2f %c %-2d", (double)hmi_freq/1000.0, 0x07, 0);
// sprintf(s, "10489,%6.2f %c %-2d", (double)hmi_freq/1000.0, 0x07, 0);
else
GFX_printf("10489,%6.2f %cS%-2d", (double)hmi_freq/1000.0, 0x06, get_sval());
// sprintf(s, "10489,%6.2f %cS%-2d", (double)hmi_freq/1000.0, 0x06, get_sval());
//BD ili9341_draw_string(10,40,s, ILI9341_YELLOW, ILI9341_BLACK,3);
GFX_setCursor(10,100);
GFX_printf("%s", hmi_o_mode[hmi_sub[HMI_S_MODE]]);
//BD sprintf(s, "%s", hmi_o_mode[hmi_sub[HMI_S_MODE]]);
//BD ili9341_draw_string(10,70,s, ILI9341_LIGHTGREY, ILI9341_BLACK,3);
if (is_fft_completed())
{
hmi_draw_spectrum();
hmi_draw_bandwidth();
}
// Print bottom line of display, depending on state
GFX_setCursor(10,30);
switch (hmi_state)
{
case HMI_S_TUNE:
GFX_printf("%s %s %s", hmi_o_vox[hmi_sub[HMI_S_VOX]], hmi_o_agc[hmi_sub[HMI_S_AGC]], hmi_o_pre[hmi_sub[HMI_S_PRE]]);
// sprintf(s, "%s %s %s", hmi_o_vox[hmi_sub[HMI_S_VOX]], hmi_o_agc[hmi_sub[HMI_S_AGC]], hmi_o_pre[hmi_sub[HMI_S_PRE]]);
//BD ili9341_draw_string(10,10,s, ILI9341_YELLOW, ILI9341_BLACK,3);
//BD ili9341_draw_rect(105+(hmi_option>3?hmi_option*16+20:hmi_option*16), 40, 20, 20, ILI9341_RED);
break;
case HMI_S_MODE:
GFX_printf("Set Mode: %s ", hmi_o_mode[hmi_option]);
// sprintf(s, "Set Mode: %s ", hmi_o_mode[hmi_option]);
//BD ili9341_draw_string(10,10,s, ILI9341_YELLOW, ILI9341_BLACK,3);
//BD ili9341_draw_rect(90, 10, 20, 20, ILI9341_RED);
break;
case HMI_S_AGC:
GFX_printf("Set AGC: %s ", hmi_o_agc[hmi_option]);
// sprintf(s, "Set AGC: %s ", hmi_o_agc[hmi_option]);
//BD ili9341_draw_string(10,10,s, ILI9341_YELLOW, ILI9341_BLACK,3);
//BD ili9341_draw_rect(80, 10, 20, 20, ILI9341_RED);
break;
case HMI_S_PRE:
GFX_printf("Set Pre: %s ", hmi_o_pre[hmi_option]);
// sprintf(s, "Set Pre: %s ", hmi_o_pre[hmi_option]);
//BD ili9341_draw_string(10,10,s, ILI9341_YELLOW, ILI9341_BLACK,3);
//BD ili9341_draw_rect(80, 10, 20, 20, ILI9341_RED);
break;
case HMI_S_VOX:
GFX_printf(s, "Set VOX: %s ", hmi_o_vox[hmi_option]);
// sprintf(s, "Set VOX: %s ", hmi_o_vox[hmi_option]);
//BD ili9341_draw_string(10,10,s, ILI9341_YELLOW, ILI9341_BLACK,3);
//BD ili9341_draw_rect(80, 10, 20, 20, ILI9341_RED);
break;
case HMI_S_BPF:
GFX_printf(s, "Band: %d %s ", hmi_option, hmi_o_bpf[hmi_option]);
// sprintf(s, "Band: %d %s ", hmi_option, hmi_o_bpf[hmi_option]);
//BD ili9341_draw_string(10,10,s, ILI9341_YELLOW, ILI9341_BLACK,3);
//BD ili9341_draw_rect(80, 10, 20, 20, ILI9341_RED);
default:
break;
}
/* PTT debouncing */
if (gpio_get(GP_PTT)) // Get PTT level
{
if (ptt_state<PTT_DEBOUNCE) // Increment debounce counter when high
ptt_state++;
}
else
{
if (ptt_state>0) // Decrement debounce counter when low
ptt_state--;
}
if (ptt_state == PTT_DEBOUNCE) // Reset PTT when debounced level high
ptt_active = false;
if (ptt_state == 0) // Set PTT when debounced level low
ptt_active = true;
/* Set parameters corresponding to latest entered option value */
// See if VFO needs update
adf4360_evaluate(HMI_MULFREQ*(hmi_freq-FC_OFFSET));
// Update peripherals according to menu setting
// For frequency si5351 is set directly, HMI top line follows
if (hmi_update)
{
dsp_setmode(hmi_sub[HMI_S_MODE]);
dsp_setvox(hmi_sub[HMI_S_VOX]);
dsp_setagc(hmi_sub[HMI_S_AGC]);
hmi_update = false;
}
GFX_flush();
}
void hmi_drawBackgroundBitmap()
{
}
/*
* Initialize the User interface
*/
void hmi_init(void)
{
/*
* Notes on using GPIO interrupts:
* The callback handles interrupts for all GPIOs with IRQ enabled.
* Level interrupts don't seem to work properly.
* For debouncing, the GPIO pins should be pulled-up and connected to gnd with 100nF.
* PTT has separate debouncing logic
*/
// Init input GPIOs
gpio_init_mask(GP_MASK_IN);
// Enable pull-ups
gpio_pull_up(GP_ENC_A);
gpio_pull_up(GP_ENC_B);
gpio_pull_up(GP_AUX_0);
gpio_pull_up(GP_AUX_1);
gpio_pull_up(GP_AUX_2);
gpio_pull_up(GP_AUX_3);
gpio_pull_up(GP_PTT);
gpio_set_oeover(GP_PTT, GPIO_OVERRIDE_HIGH); // Enable output on PTT GPIO; bidirectional
// Enable interrupt on level low
gpio_set_irq_enabled(GP_ENC_A, GPIO_IRQ_EDGE_ALL, true);
gpio_set_irq_enabled(GP_AUX_0, GPIO_IRQ_EDGE_ALL, true);
gpio_set_irq_enabled(GP_AUX_1, GPIO_IRQ_EDGE_ALL, true);
gpio_set_irq_enabled(GP_AUX_2, GPIO_IRQ_EDGE_ALL, true);
gpio_set_irq_enabled(GP_AUX_3, GPIO_IRQ_EDGE_ALL, true);
gpio_set_irq_enabled(GP_PTT, GPIO_IRQ_EDGE_ALL, false);
// Set callback, one for all GPIO, not sure about correctness!
gpio_set_irq_enabled_with_callback(GP_ENC_A, GPIO_IRQ_EDGE_ALL, true, hmi_callback);
// Initialize display and set VFO
hmi_state = HMI_S_TUNE;
hmi_option = 4; // Active kHz digit
hmi_freq = 823000UL; // Initial frequency
adf4360_evaluate(HMI_MULFREQ*(hmi_freq-FC_OFFSET)); // Set freq to 7074 kHz (depends on mixer type)
ptt_state = PTT_DEBOUNCE;
ptt_active = false;
dsp_setmode(hmi_sub[HMI_S_MODE]);
dsp_setvox(hmi_sub[HMI_S_VOX]);
dsp_setagc(hmi_sub[HMI_S_AGC]);
hmi_update = false;
}
|
import java.util.Comparator;
import java.util.Arrays;
class Person {
String firstName;
String lastName;
int age;
Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
@Override
public String toString() {
return firstName + " " + lastName + ", Wiek: " + age;
}
}
public class PersonSorter {
public static void main(String[] args) {
Person[] people = {
new Person("Jan", "Kowalski", 30),
new Person("Anna", "Nowak", 25),
new Person("Piotr", "Zieliński", 35)
};
System.out.println("Przed sortowaniem:");
printArray(people);
System.out.println("\nSortowanie wg imienia:");
sort(people, Comparator.comparing(person -> person.firstName));
printArray(people);
System.out.println("\nSortowanie wg nazwiska:");
sort(people, Comparator.comparing(person -> person.lastName));
printArray(people);
System.out.println("\nSortowanie wg wieku:");
sort(people, Comparator.comparing(person -> person.age));
printArray(people);
}
static void printArray(Person[] array) {
for (Person person : array) {
System.out.println(person);
}
}
static void sort(Person[] array, Comparator<Person> comparator) {
Arrays.sort(array, comparator);
}
}
|
import { ChangeEvent, useState } from "react";
import { useQuery } from "react-query";
import { HotelCardType } from "../../../backend/src/shared/types";
import * as apiClient from "../api-client";
import HotelResultCard from "../components/HotelResultCard";
import SortOptions from "../components/SortOptions";
import FilterByFacilities from "../components/filters/FilterByFacilities";
import FilterByMaxPrice from "../components/filters/FilterByMaxPrice";
import FilterByRating from "../components/filters/FilterByRating";
import FilterByTypes from "../components/filters/FilterByTypes";
import HotelCardSkeleton from "../components/skeletons/HotelCardSkeleton";
import { useSearchContext } from "../contexts/UseContexts";
import { SearchParams } from "../shared/Types";
const FindHotels = () => {
const search = useSearchContext();
const [page, setPage] = useState<number>();
const [selectedStars, setSelectedStars] = useState<string[]>([]);
const [selectedHotelTypes, setSelectedHotelTypes] = useState<string[]>([]);
const [selectedFacilities, setSelectedFacilities] = useState<string[]>([]);
const [selectedPrice, setSelectedPrice] = useState<number | undefined>();
const [sortOptions, setSortOptions] = useState<string>("");
const searchParams: SearchParams = {
destination: search.destination,
adultCount: search.adultCount.toString(),
childCount: search.childCount.toString(),
page: page?.toString(),
stars: selectedStars,
types: selectedHotelTypes,
facilities: selectedFacilities,
maxPrice: selectedPrice?.toString(),
sortOptions,
};
const { data, isLoading } = useQuery(["fetchAllHotels", searchParams], () =>
apiClient.fetchSearchHotels(searchParams)
);
let hotels: HotelCardType[] = [];
if (data) {
hotels = data?.data;
}
const handleStarChange = (event: ChangeEvent<HTMLInputElement>) => {
const starRating = event.target.value;
setSelectedStars((prevStars) =>
event.target.checked
? [...prevStars, starRating]
: prevStars?.filter((star) => star !== starRating)
);
};
const handleTypeChange = (event: ChangeEvent<HTMLInputElement>) => {
const type = event.target.value;
setSelectedHotelTypes((prevTypes) =>
event.target.checked
? [...prevTypes, type]
: prevTypes?.filter((prevType) => prevType !== type)
);
};
const handleFacilityChange = (event: ChangeEvent<HTMLInputElement>) => {
const facility = event.target.value;
setSelectedFacilities((prev) =>
event.target.checked
? [...prev, facility]
: prev?.filter((p) => p !== facility)
);
};
const handleMaxPriceChange = (event: ChangeEvent<HTMLSelectElement>) => {
const maxPrice = event.target.value;
setSelectedPrice(parseInt(maxPrice));
};
return (
<div className="custom-container min-h-screen">
<div className="flex md:flex-row flex-col gap-4 py-4">
<div className="border border-zinc-300 md:w-1/5 p-4 md:sticky top-2 h-fit rounded">
<h2 className="text-xl font-bold border-b border-zinc-300 pb-4 mb-4">
Filter By :
</h2>
<div className="grid md:grid-cols-1 grid-cols-2 gap-4 text-sm h-40 overflow-y-scroll md:h-fit md:overflow-hidden">
<FilterByRating
selectedStars={selectedStars}
onChange={handleStarChange}
/>
<FilterByTypes
selectedTypes={selectedHotelTypes}
onChange={handleTypeChange}
/>
<FilterByFacilities
selectedFacilities={selectedFacilities}
onChange={handleFacilityChange}
/>
<FilterByMaxPrice
selectedPrice={selectedPrice as number}
onChange={handleMaxPriceChange}
/>
</div>
</div>
<div className="md:w-4/5">
<div className="flex md:items-center justify-between mb-4 gap-2 md:flex-row flex-col">
<h4 className="text-xl font-bold">
{data?.pagination?.total} Hotels found
{search.destination ? ` in ${search.destination}` : ""}
</h4>
<SortOptions
sortOptions={sortOptions}
onChange={(e) => setSortOptions(e.target.value)}
/>
</div>
<div className="flex flex-col gap-4">
{isLoading ? (
<>
<HotelCardSkeleton />
<HotelCardSkeleton />
<HotelCardSkeleton />
<HotelCardSkeleton />
<HotelCardSkeleton />
</>
) : (
hotels?.map((hotel) => (
<div className="md:h-72" key={hotel._id}>
<HotelResultCard hotel={hotel} key={hotel._id} />
</div>
))
)}
</div>
</div>
</div>
{/* pagination */}
<div className="flex items-center justify-center">
<div className="join gap-2 my-4">
{Array(data?.pagination?.pages || 0)
.fill(undefined)
.map((_, i) => {
const value = i + 1;
return (
<button
key={value}
onClick={(e) => setPage(parseInt(e.currentTarget.innerText))}
className={`h-8 w-8 text-lg flex-center font-bold rounded ${data?.pagination?.page === value ? "bg-[var(--main-color)] text-white" : "bg-slate-300 "}`}
>
{value}
</button>
);
})}
</div>
</div>
</div>
);
};
export default FindHotels;
|
import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { StepDialogComponent } from '../components/step-dialog/step-dialog.component';
import { StepDialogData } from '../components/step-dialog/step-dialog.interface';
import { OperationMode } from '../components/step/step.interfaces';
import { IRecipeStep } from '../model/recipe-step.model';
import { RecipeStepService } from './recipe-step.service';
@Injectable()
export class RecipeStepDialogService {
constructor(
private readonly matDialog: MatDialog,
private readonly recipeStepService: RecipeStepService
) {}
public openAddStepDialog(recipeId: string): void {
const recipeStep: IRecipeStep = {
recipeId: +recipeId,
recipeStepId: '',
stepInstruction: '',
stepNumber: 1000,
};
this.matDialog.open<StepDialogComponent, StepDialogData>(
StepDialogComponent,
{
panelClass: ['dialog-overlay'],
maxWidth: '95vw',
data: {
operationMode: OperationMode.create,
recipeStep,
},
}
);
}
public openEditStepDialog(recipeStep: IRecipeStep): void {
this.matDialog.open<StepDialogComponent, StepDialogData>(
StepDialogComponent,
{
panelClass: ['dialog-overlay'],
maxWidth: '95vw',
data: {
operationMode: OperationMode.edit,
recipeStep,
},
}
);
}
}
|
import React, {MouseEventHandler} from "react"
/**
* TopBar.
*/
type TopBar = {
label : string
backCta? : string
backLink? : string
forwardCta? : string
forwardLink? : string
doBackAction? : MouseEventHandler<HTMLButtonElement>
doForwardAction?: MouseEventHandler<HTMLButtonElement>
}
/**
* TopBar.
*
* @param {string} label
* The label to display in the top bar.
* @param {string} backCta
* The back CTA.
* @param {string} backLink
* The back link.
* @param {string} forwardCta
* The forward CTA.
* @param {string} forwardLink
* The forward link.
* @param {Function} doBackAction
* A callback to handle the back action
* @param {Function} doForwardAction
* A callback to handle the forward action
*
* @constructor
*/
export const TopBar = ({label, backCta, backLink, forwardCta, forwardLink, doBackAction, doForwardAction}: TopBar) => {
return (
<div className={'a-top-bar'}>
<h3>{label}</h3>
{
backLink ? <a className={'a-top-bar__back-link'} href={backLink}>{backCta ? backCta : 'Back'}</a> :
doBackAction ? <button className={'a-top-bar__back-link'} onClick={doBackAction}>{backCta ? backCta : 'Back'}</button> : null
}
{
forwardLink ? <a className={'a-top-bar__forward-link'} href={forwardLink}>{forwardCta ? forwardCta : 'Forward'}</a> :
doForwardAction ? <button className={'a-top-bar__forward-link'} onClick={doForwardAction}>{forwardCta ? forwardCta : 'Forward'}</button> : null
}
</div>
)
}
|
import type { Meta, StoryObj } from "@storybook/react";
import ProfileDiariesList from "./ProfileDiariesList";
const meta: Meta<typeof ProfileDiariesList> = {
title: "Organisms/ProfileDiariesList",
component: ProfileDiariesList,
parameters: {
layout: "centered",
nextjs: {
appDirectory: true,
},
},
};
export default meta;
type Story = StoryObj<typeof ProfileDiariesList>;
const sampleDiary = {
id: 1,
userId: "user1",
title: "Sample Diary",
content: "This is a sample diary content.",
isPublic: true,
createdAt: new Date("2023-06-01"),
updatedAt: new Date("2023-06-01"),
};
export const Default: Story = {
args: {
diary: sampleDiary,
},
};
export const LongTitle: Story = {
args: {
diary: {
...sampleDiary,
title: "This is a very long diary title that spans multiple lines.",
},
},
};
export const PrivateDiary: Story = {
args: {
diary: {
...sampleDiary,
isPublic: false,
},
},
};
|
from shutil import which
from os.path import exists, isdir
from os import mkdir, path, chdir, scandir
from subprocess import run
import argparse
dry_run = False
def is_empty(dir_name: str) -> bool:
"""
Returns True if the directory exists and contains item(s) else False
"""
try:
if any(scandir(dir_name)):
return False
except (NotADirectoryError, FileNotFoundError):
pass
return True
def program_in_path(program_name: str) -> bool:
return which(program_name) is not None
def assert_in_path(program_name: str) -> str:
assert program_in_path(program_name), "{} not in path".format(program_name)
return which(program_name)
def try_make_dir(dir_path: str) -> bool:
actual_path = path.abspath(dir_path)
if dry_run:
return actual_path
if exists(dir_path):
return actual_path
mkdir(dir_path)
return actual_path
def build_rlc(
execution_dir: str,
cmake_path,
rlc_source_dir,
install_dir,
build_shared: bool,
build_type: str,
llvm_install_dir,
clang_path: str,
python_path: str
):
assert_run_program(
execution_dir,
cmake_path,
"{}".format(rlc_source_dir),
"-DCMAKE_BUILD_TYPE={}".format(build_type),
"-DCMAKE_INSTALL_PREFIX={}".format(install_dir),
"-DCMAKE_EXPORT_COMPILE_COMMANDS=True",
"-G",
"Ninja",
"-DMLIR_DIR={}/lib/cmake/mlir".format(llvm_install_dir),
"-DLLVM_DIR={}/lib/cmake/llvm".format(llvm_install_dir),
f"-DCMAKE_C_COMPILER={path.abspath(clang_path)}",
f"-DCMAKE_CXX_COMPILER={path.abspath(clang_path)}++",
"-DBUILD_SHARED_LIBS={}".format("ON" if build_shared else "OFF"),
"-DCMAKE_BUILD_WITH_INSTALL_RPATH={}".format("OFF" if build_shared else "ON"),
"-DHAVE_STD_REGEX=ON",
"-DRUN_HAVE_STD_REGEX=1",
"-DPython_EXECUTABLE:FILEPATH={}".format(python_path),
"-DCMAKE_EXE_LINKER_FLAGS=-static-libgcc -static-libstdc++" if build_type == "Release" else "",
)
def build_llvm(
execution_dir: str,
cmake_path,
llvm_source_dir,
install_dir,
build_shared: bool,
build_type: str,
clang: str,
clang_plus_plus: str,
use_lld: bool,
):
assert_run_program(
execution_dir,
cmake_path,
"{}/llvm".format(llvm_source_dir),
"-DLLVM_INSTALL_UTILS=True",
"-DCMAKE_BUILD_TYPE={}".format(build_type),
"-DCMAKE_INSTALL_PREFIX={}".format(install_dir),
"-DLLVM_ENABLE_PROJECTS=clang;clang-tools-extra;mlir;compiler-rt;lld;",
"-DLLVM_USE_LINKER=lld" if use_lld else "",
"-DCMAKE_EXPORT_COMPILE_COMMANDS=True",
"-DLLVM_ENABLE_RUNTIMES=libcxx;libunwind",
f"-DCMAKE_C_COMPILER={clang}",
f"-DCMAKE_CXX_COMPILER={clang_plus_plus}",
"-G",
"Ninja",
"-DBUILD_SHARED_LIBS={}".format("ON" if build_shared else "OFF"),
)
def install(execution_dir: str, ninja_path, run_tests=False):
assert_run_program(execution_dir, ninja_path, "all")
assert_run_program(execution_dir, ninja_path, "install")
if run_tests:
assert_run_program(execution_dir, ninja_path, "test")
def assert_run_program(execution_dir: str, command: str, *args: str):
print("cd {}".format(execution_dir))
print("{} {}".format(command, " ".join(args)))
if dry_run:
return
filtered_args = [arg for arg in args if arg != ""]
chdir(execution_dir)
result = run([command] + filtered_args)
assert result.returncode == 0
def main():
parser = argparse.ArgumentParser(
"run", description="runs a action of the simulation"
)
parser.add_argument(
"--no-debug-llvm",
help="does not build debug llvm",
action="store_true",
)
parser.add_argument(
"--dry-run",
help="only prints the command that would be executing",
action="store_true",
)
parser.add_argument(
"--no-use-lld",
help="do not set up rlc",
action="store_true",
)
parser.add_argument(
"--llvm-only",
help="do not set up rlc",
action="store_true",
)
parser.add_argument(
"--llvm-dir",
help="use the provided LLVM installation and skip other LLVM steps",
type=str,
default="",
)
parser.add_argument(
"--cxx-compiler", help="path to cxx compiler", type=str, default="clang++"
)
parser.add_argument(
"--c-compiler", help="path to c compiler", type=str, default="clang"
)
parser.add_argument(
"--rlc-shared",
help="if LLVM is provided by command line, this option allow to decide if rlc should be built as a shared or static libray. This is needed if LLVM is itself shared or static. Defaults to false. ",
action="store_true",
)
args = parser.parse_args()
global dry_run
dry_run = args.dry_run
debug_llvm = not args.no_debug_llvm
if args.llvm_dir != "":
args.llvm_dir = path.abspath(args.llvm_dir)
assert exists(args.llvm_dir), "provided a non existing llvm dir"
# check needed programs are in path
cmake = assert_in_path("cmake")
if args.no_use_lld == False:
ldd = assert_in_path("lld")
ninja = assert_in_path("ninja")
git = assert_in_path("git")
python = assert_in_path("python")
# create root dir
rlc_infrastructure = path.abspath("./")
# create dirs
rlc_dir = path.abspath("rlc")
assert isdir(
rlc_dir
), "could not find rlc folder, did you executed this script from the wrong folder?"
llvm_source_dir = path.abspath("llvm-project")
rlc_build_dir = try_make_dir("rlc-debug")
rlc_release_dir = try_make_dir("rlc-release")
# build debug llvm
llvm_install_debug_dir = path.abspath("llvm-install-debug")
llvm_install_release_dir = path.abspath("llvm-install-release")
# clone llvm
if not exists(llvm_source_dir) and args.llvm_dir == "":
assert_run_program(
rlc_infrastructure,
git,
"clone",
"https://github.com/llvm/llvm-project.git",
"--depth",
"1",
"-b",
"release/18.x",
)
if debug_llvm and not exists(llvm_install_debug_dir) and args.llvm_dir == "":
llvm_build_debug_dir = try_make_dir(rlc_infrastructure + "/llvm-debug")
build_llvm(
execution_dir=llvm_build_debug_dir,
cmake_path=cmake,
llvm_source_dir=llvm_source_dir,
install_dir=llvm_install_debug_dir,
build_shared=True,
build_type="Debug",
clang=args.c_compiler,
clang_plus_plus=args.cxx_compiler,
use_lld=not args.no_use_lld,
)
install(execution_dir=llvm_build_debug_dir, ninja_path=ninja)
# build release llvm
if not exists(llvm_install_release_dir) and args.llvm_dir == "":
llvm_build_release_dir = try_make_dir(rlc_infrastructure + "/llvm-release")
build_llvm(
execution_dir=llvm_build_release_dir,
cmake_path=cmake,
llvm_source_dir=llvm_source_dir,
install_dir=llvm_install_release_dir,
build_shared=False,
build_type="Release",
clang=args.c_compiler,
clang_plus_plus=args.cxx_compiler,
use_lld=not args.no_use_lld,
)
install(execution_dir=llvm_build_release_dir, ninja_path=ninja)
if args.llvm_only:
return
llvm_dir = args.llvm_dir
build_shared = debug_llvm
if llvm_dir == "":
llvm_dir = llvm_install_debug_dir if debug_llvm else llvm_install_release_dir
else:
build_shared = args.rlc_shared
# build debug
build_rlc(
execution_dir=rlc_build_dir,
cmake_path=cmake,
rlc_source_dir=rlc_dir,
install_dir="./install",
build_shared=build_shared,
build_type="Debug",
llvm_install_dir=llvm_dir,
clang_path=f"{llvm_install_release_dir}/bin/clang",
python_path=python
)
install(execution_dir=rlc_build_dir, ninja_path=ninja, run_tests=True)
build_rlc(
execution_dir=rlc_release_dir,
cmake_path=cmake,
rlc_source_dir=rlc_dir,
install_dir="./install",
build_shared=False,
build_type="Release",
llvm_install_dir=llvm_install_release_dir,
clang_path=f"{llvm_install_release_dir}/bin/clang",
python_path=python
)
install(execution_dir=rlc_release_dir, ninja_path=ninja, run_tests=True)
assert_run_program(
rlc_dir,
python,
"python/solve.py",
"./tool/rlc/test/tic_tac_toe.rl",
"--rlc",
"{}/install/bin/rlc".format(rlc_build_dir),
)
if __name__ == "__main__":
main()
|
package com.bluepig.alarm.ui.media.music
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bluepig.alarm.domain.entity.music.MusicInfo
import com.bluepig.alarm.domain.result.resultLoading
import com.bluepig.alarm.domain.usecase.SearchFile
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MusicSearchViewModel @Inject constructor(
private val _searchFile: SearchFile,
) : ViewModel() {
private val _musicInfoList: MutableStateFlow<Result<List<MusicInfo>>> =
MutableStateFlow(Result.success(emptyList()))
val musicInfoList = _musicInfoList.asStateFlow()
fun search(query: String = "") {
viewModelScope.launch {
_musicInfoList.emit(resultLoading())
_musicInfoList.emit(_searchFile.invoke(query))
}
}
}
|
const Web3= require('web3')
//transcation crafting dependency
const Tx= require('ethereumjs-tx').Transaction
require('dotenv').config()
// loading my environment variables
infuraToken = process.env.INFURA_TOKEN
contractAddress=process.env.CONTRACT_ADDRESS
ownerAddress=process.env.OWNER_ADDRESS
privateKey=Buffer.from(process.env.SUPER_SECRET_PRIVATE_KEY , 'hex')
// get the ABI (interface) for our contract
const abi = [
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "from",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "to",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
},
{
"inputs": [],
"name": "_totalSupply",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"internalType": "address",
"name": "spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "account",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "decimals",
"outputs": [
{
"internalType": "uint8",
"name": "",
"type": "uint8"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "name",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "symbol",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "tokenOwner",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "recipient",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "sender",
"type": "address"
},
{
"internalType": "address",
"name": "recipient",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
}
]
// instantiate web3
const rpcURL= "https://ropsten.infura.io/v3/" + infuraToken;
const web3 = new Web3(rpcURL);
//get our address
const address =contractAddress;
const owner =ownerAddress;
// connect to our contract
const contract = new web3.eth.Contract(abi, address);
//setup a send transcation method
const sendTx = async(raw) => {
return await web3.eth.sendSignedTransaction(raw);
}
const transferToken = async(toAccount, amount) => {
//generate a nonce
let txCount= await web3.eth.getTransactionCount(owner);
console.log("tx count is "+ txCount);
//generate tx data
const txObject= {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(500000),
gasPrice: web3.utils.toHex(web3.utils.toWei('100', 'gwei')),
to: contractAddress,
data: contract.methods.transfer(toAccount, amount).encodeABI()
}
//assign a chain id (ropsten: 3)
const tx = new Tx(txObject, {chain: 'ropsten', hardfork: 'petersburg'})
//sign the tx
tx.sign(privateKey);
console.log('Signed transaction with super secret private key');
//serialize the raw tx
const serializedTx= tx.serialize();
const raw ='0x' + serializedTx.toString('hex');
console.log('About to send transaction: ' + raw)
let txResponse = await sendTx(raw);
console.log("tx response is: "+ txResponse .toString());
console.log("Transcation hash: "+ txResponse .transactionHash);
console.log("Transcation in block: "+ txResponse .blockNumber);
}
// create a transaction to execute a method on the contract
// sign the transaction with our private key
// broadcast the transaction
//transferToken('0x677d0A16a55fd52195Eb53C733899f691af79882', 123000000)
module.exports = { transferToken }
|
/*
* Copyright 2023 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { PalantirApiError } from "../../errors";
import type { FoundryApiError } from "../../errors";
import type { Result } from "../../Result";
import { createErrorResponse, createOkResponse } from "./ResponseCreators";
export async function* wrapIterator<T, E extends FoundryApiError>(
lambda: () => AsyncGenerator<T, any, unknown>,
errorHandler: (palantirApiError: PalantirApiError) => E,
): AsyncGenerator<Result<T, E>> {
try {
for await (const element of lambda()) {
yield createOkResponse(element);
}
} catch (e) {
if (e instanceof PalantirApiError) {
yield createErrorResponse(errorHandler(e));
} else {
// TODO this unknown used to be an UnknownError but it had casting problems
yield createErrorResponse(e as unknown as E);
}
}
}
|
<?php
use App\Http\Controllers\AbsensiController;
use App\Http\Controllers\DataPendudukController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Auth::routes();
Route::get('/home', function() {
return view('home');
})->name('home')->middleware('auth');
Route::middleware(['auth'])->group(function () {
Route::resource('data-penduduk', DataPendudukController::class);
Route::resource('absensi',AbsensiController::class);
});
|
import pandas as pd
import networkx as nx
import pickle
import numpy as np
train_data = pd.read_csv(r'/Users/hiteshchowdarysuryadevara/Downloads/champs-scalar-coupling/train.csv')
test_data = pd.read_csv(r'/Users/hiteshchowdarysuryadevara/Downloads/champs-scalar-coupling/test.csv')
structures = pd.read_csv(r'/Users/hiteshchowdarysuryadevara/Downloads/champs-scalar-coupling/structures.csv')
# dipole_moments = pd.read_csv(r'/Users/hiteshchowdarysuryadevara/Downloads/champs-scalar-coupling/dipole_moments.csv')
# magnetic_tensors = pd.read_csv(r'/Users/hiteshchowdarysuryadevara/Downloads/champs-scalar-coupling/magnetic_shielding_tensors.csv')
# mulliken_charges = pd.read_csv(r'/Users/hiteshchowdarysuryadevara/Downloads/champs-scalar-coupling/mulliken_charges.csv')
# potential_energy = pd.read_csv(r'/Users/hiteshchowdarysuryadevara/Downloads/champs-scalar-coupling/potential_energy.csv')
# scalar_coupling_contributions = pd.read_csv(r'/Users/hiteshchowdarysuryadevara/Downloads/champs-scalar-coupling/scalar_coupling_contributions.csv')
print('Train_data:')
print(train_data.head())
print('structures_data:')
print(structures.head())
print("null values in train_data:")
print(train_data.isna().sum())
def create_molecule_graph(molecule_name):
# Extract structure data for the molecule
molecule_data = structures[structures['molecule_name'] == molecule_name]
coupling_constant_data = train_data[train_data['molecule_name'] == molecule_name]
# Create a graph
G = nx.Graph()
# Add nodes (atoms)
for idx, atom in molecule_data.iterrows(): #idx is the index and atom will be the panadas series of the row
G.add_node(atom['atom_index'],
atom_type=atom['atom'],
molecule_name=molecule_name,
x=atom['x'],
y=atom['y'],
z=atom['z'])
# Add edges (bonds)
for idx, atom in molecule_data.iterrows():
for idx2, atom2 in molecule_data.iterrows():
if idx != idx2: # Avoid self-loops
distance = ((atom['x'] - atom2['x'])**2 +
(atom['y'] - atom2['y'])**2 +
(atom['z'] - atom2['z'])**2) ** 0.5
# Example: Add an edge if the distance is below a threshold
# if distance < 1.5:
G.add_edge(atom['atom_index'], atom2['atom_index'], distance=distance)
# adding coupling type and coupling constants to these edges
for u, v, data in G.edges(data=True):
#SCC = scalar_coupling_constant Ctype =coupling type
result = coupling_constant_data.loc[(coupling_constant_data[['atom_index_0', 'atom_index_1']].isin([u, v])).all(axis=1), ['scalar_coupling_constant', 'type']]
if not result.empty:
G[u][v]['SCC'] = result['scalar_coupling_constant'].iloc[0]
G[u][v]['Ctype'] = result['type'].iloc[0]
else :
G[u][v]['SCC'] = np.nan
G[u][v]['Ctype'] = np.nan
return G
# creating a list of molecule names in train data to fect graphs structure from structures data of only training molecules
unique_molecule_names = train_data['molecule_name'].unique()
unique_molecule_names_list = list(unique_molecule_names)
unique_molecule_names_list = unique_molecule_names_list[0:1000] #TOTAL 85012
print('lenght of unique molecule names:',len(unique_molecule_names_list))
#graps list to save all the graphs of training data molecules
graphs_train = []
n=0
for molecule_name in unique_molecule_names_list:
graph = create_molecule_graph(molecule_name)
graphs_train.append(graph)
n+=1
if n%100 == 0:
print('loading graphs:',round(n/10000*100,2),'%')
if n == 10000:
break
print('number of graphs :',len(graphs_train))
# Save the list of graphs in the current working directory
with open('graphs_train.pkl', 'wb') as file:
pickle.dump(graphs_train, file)
# Print node and edge data (for demonstration purposes)
# print("Nodes:")
# for node, data in graph_example.nodes(data=True):
# print(f"Node {node}: {data}")
# print("\nEdges:")
# for edge in graph_example.edges(data=True):
# node1, node2, data = edge
# print(f"Edge ({node1}, {node2}): {data}")
|
import classNames from "classnames";
type Color = "red" | "green" | "indigo" | "blue" | "gray";
export const Badge: React.FC<{
text: string;
color: Color;
className?: string;
}> = ({ text, color, className }) => {
return (
<>
{color === "green" && (
<span
className={
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 " +
className
}
>
{text}
</span>
)}
{color === "red" && (
<span
className={
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 " +
className
}
>
{text}
</span>
)}
{color === "blue" && (
<span
className={
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 " +
className
}
>
{text}
</span>
)}
{color === "indigo" && (
<span
className={
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800 " +
className
}
>
{text}
</span>
)}
{color === "gray" && (
<span
className={
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-200 text-gray-900 " +
className
}
>
{text}
</span>
)}
</>
);
};
|
-- Minesweeper Milestone 2
-- 4x4 Grid of Cells
-- Cell ( row , column )
type Cell = (Int,Int)
-- S [Robot's position] [List of Postions of Mines]
-- [The parent state is the last state the robot was in before doing the last performed action]
data MyState = Null | S Cell [Cell] String MyState deriving (Show,Ord,Eq)
---------------------------------------------------------------
-- Higher Order Functions
-------------------------
-- Direction [ up , down , left , right ]
-- Type
direction :: String -> MyState -> MyState
-- Body
direction str (S (x,y) l ls state) | str == "up" = S (x-1,y) l ("up") (S (x,y) l ls state)
| str == "down" = S (x+1,y) l ("down") (S (x,y) l ls state)
| str == "left" = S (x,y-1) l ("left") (S (x,y) l ls state)
| str == "right"= S (x,y+1) l ("right") (S (x,y) l ls state)
---------------------------
---------------------------------------------------------------
-- Helper Functions
-------------------
-- remove [remove element from a list]
-- Type
remove :: Eq a => a -> [a] -> [a]
-- Body
remove e (h:t) = [ x | x <- (h:t) , e /= x ]
---------------------------
-- searchH
-- Type
searchH :: [MyState] -> MyState
-- Body
searchH [] = Null
searchH ((S (x,y) l ls state):t) = if isGoal (S (x,y) l ls state) then (S (x,y) l ls state)
else searchH t
---------------------------
---------------------------------------------------------------
-- UP
-- Type
up :: MyState -> MyState
-- Body
up state = direction "up" state
---------------------------
-- DOWN
-- Type
down :: MyState -> MyState
-- Body
down state = direction "down" state
---------------------------
-- LEFT
-- Type
left :: MyState -> MyState
-- Body
left state = direction "left" state
---------------------------
-- RIGHT
--Type
right :: MyState -> MyState
-- Body
right state = direction "right" state
---------------------------
-- COLLECT
-- Type
collect :: MyState -> MyState
-- Body
collect (S (x,y) l ls state) | elem (x,y) l = (S (x,y) (remove (x,y) l) "collect" (S (x,y) l ls state))
| otherwise = Null
---------------------------
-- Next MyStates
-- Type
nextMyStates:: MyState -> [MyState]
-- Body
nextMyStates (S (x,y) l ls state) = list
where {
(c,d) = manhattanCheck l (x,y) (1000000,1000000);
list | (c>x) = [down (S (x,y) l ls state)]
| (d>y) = [right (S (x,y) l ls state)]
| (c<x) = [up (S (x,y) l ls state)]
| (d<y) = [left (S (x,y) l ls state)]
| otherwise = [collect (S (x,y) l ls state)]
};
manhattan:: Cell -> Cell -> Int
manhattan (a,b) (c,d) = (abs (a-c)) + (abs (b-d))
manhattanCheck:: [Cell] -> Cell -> Cell -> Cell
manhattanCheck [] (a,b) closest = closest
manhattanCheck ((x,y):t) (a,b) closest | manhattan (x,y) (a,b) < manhattan (x,y) closest = manhattanCheck t (a,b) (x,y)
| otherwise = manhattanCheck t (a,b) closest
---------------------------
-- isGoal
-- Type
isGoal :: MyState -> Bool
-- Body
isGoal (S (x,y) l ls state) | l == [] = True
| otherwise = False
---------------------------
-- Search
-- Type
search :: [MyState] -> MyState
-- Body
search [] = error "Empty List" -- PS : This must not happen
search (h:t) | isGoal h = h
| otherwise = search (t ++ (nextMyStates h))
---------------------------
-- Construct Solution
-- Type
constructSolution:: MyState ->[String]
-- Body
constructSolution (S (x,y) l ls state) | flag = constructSolution state ++ [ls]
| otherwise = []
where {
flag = ls == "collect" || ls == "up" || ls == "down" || ls == "left" || ls == "right";
};
---------------------------
-- Solve
-- Type
solve :: Cell -> [Cell] -> [String]
-- Body
solve cell (h:t) = solution
where{
initialState = (S cell (h:t) "" Null);
goalState = search [initialState];
solution = constructSolution goalState;
};
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>编写位置</title>
<!-- 可以将js代码编写到外部js文件中,然后通过script标签引入
写到外部文件中可以在不同的页面中同时引用,也可以利用到浏览器的缓存机制,推荐使用方式 -->
<script type="text/javascript" src="js/script.js"></script>
<!-- script标签一旦用于引入外部文件了,就不能再编写代码了,即使编写了浏览器也会忽略
如果需要则可以再创建一个新的script标签用于编写内部代码
js代码是按照从上到下的顺序一行一行执行
-->
<!-- 可以将js代码编写到script标签 -->
<script>
alert("我是script标签中的代码");
</script>
</head>
<body>
<!-- 虽然可以写在标签的属性中,但是他们属于结构与行为耦合,不方便维护,不推荐使用 -->
<!-- 可以将js代码编写到标签的onclick属性中 当我们点击按钮时,js代码才会执行 -->
<button onclick="alert('点个锤子点')">别点我!</button>
<!-- 可以将js代码写在超链接的href属性中,这样当点击超链接时,会执行js代码 -->
<a href="javascript:alert('让你点你就点')">点我一下</a>
<!-- 希望超链接点完以后没有任何反应 通过js处理一些功能-->
<a href="javascript:;">点我一下</a>
</body>
</html>
|
import { Scene, SequenceElement } from '../../../../scene/scene';
import { PlaceOfActionProvider } from './placeOfAction.provider';
import { DescriptionProvider } from './descriptionProvider';
import { Section } from './section';
import { TestProvider } from './test.provider';
import { PlaceOfAction } from '../../../../scene/placeOfAction';
export class SectionsProvider {
constructor(
private readonly placeOfActionProvider: PlaceOfActionProvider,
private readonly descriptionProvider: DescriptionProvider,
private readonly testProvider: TestProvider,
) {
}
async get(scene: Scene): Promise<Array<Section>> {
return (await Promise.all([
this.placeOfActionProvider.get(scene),
...this.getSequence(scene),
])).flatMap<Section>(x => x);
}
getSequence(scene: Scene): Array<Promise<Section>> {
return scene.sequence
.map(sequenceElement => this.getSection(sequenceElement, scene.placeOfAction));
}
async getSection(sequenceElement: SequenceElement, placeOfAction: PlaceOfAction) {
const steps = await this.descriptionProvider.get(sequenceElement, placeOfAction);
const test = await this.testProvider.get(sequenceElement);
return new Section(
steps,
test,
);
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdopterPetsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('adopterPets', function (Blueprint $table) {
$table->increments('id');
$table->integer('adopterId', false, true);
$table->string('species');
$table->integer('age');
$table->integer('usedToCats');
$table->integer('personality');
$table->timestamps();
$table->foreign('adopterId')->references('id')->on('adopters')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('adopterPets');
}
}
|
package com.app.main.Filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
public class CorsCheckFilter implements Filter{ //extends OncePerRequestFilter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("Cors Filter In");
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods","*");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization");
if("OPTIONS".equalsIgnoreCase(req.getMethod())) {
res.setStatus(HttpServletResponse.SC_OK);
}
chain.doFilter(request, response);
System.out.println("Cors Filter out");
}
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
// throws ServletException, IOException {
// System.out.println("Cors Check Filter");
// // TODO Auto-generated method stub
// HttpServletRequest req = (HttpServletRequest) request;
// HttpServletResponse res = (HttpServletResponse) response;
//
// res.setHeader("Access-Control-Allow-Origin", "*");
// res.setHeader("Access-Control-Allow-Credentials", "true");
// res.setHeader("Access-Control-Allow-Methods","*");
// res.setHeader("Access-Control-Max-Age", "3600");
// res.setHeader("Access-Control-Allow-Headers",
// "Origin, X-Requested-With, Content-Type, Accept, Authorization");
//
// if("OPTIONS".equalsIgnoreCase(req.getMethod())) {
// res.setStatus(HttpServletResponse.SC_OK);
// }else {
// filterChain.doFilter(request, response);
// }
// filterChain.doFilter(request, response);
// // TODO Auto-generated method stub
//
// }
}
|
package tengblogging.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* @author JunHan
*
*/
@Entity
@Table(name = "BLOGS")
public class Blog {
@Id
@Column(name = "BLOG_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private java.sql.Timestamp timestamp;
@ManyToOne
@JoinColumn(name="USER_ID")
private User user;
private String content;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public java.sql.Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(java.sql.Timestamp timestamp) {
this.timestamp = timestamp;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
user.getBlogs().add(this);
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Blog [id=" + id + ", timestamp=" + timestamp + ", user=" + user
+ ", content=" + content + "]";
}
}
|
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws 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 3 of the License, or
(at your option) any later version.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gettemplaterequest.h"
#include "gettemplaterequest_p.h"
#include "gettemplateresponse.h"
#include "sesrequest_p.h"
namespace QtAws {
namespace SES {
/*!
* \class QtAws::SES::GetTemplateRequest
* \brief The GetTemplateRequest class provides an interface for SES GetTemplate requests.
*
* \inmodule QtAwsSES
*
* <fullname>Amazon Simple Email Service</fullname>
*
* This document contains reference information for the <a href="https://aws.amazon.com/ses/">Amazon Simple Email
* Service</a> (Amazon SES) API, version 2010-12-01. This document is best used in conjunction with the <a
* href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/Welcome.html">Amazon SES Developer Guide</a>.
*
* </p <note>
*
* For a list of Amazon SES endpoints to use in service requests, see <a
* href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html">Regions and Amazon SES</a> in the <a
* href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/Welcome.html">Amazon SES Developer
*
* \sa SesClient::getTemplate
*/
/*!
* Constructs a copy of \a other.
*/
GetTemplateRequest::GetTemplateRequest(const GetTemplateRequest &other)
: SesRequest(new GetTemplateRequestPrivate(*other.d_func(), this))
{
}
/*!
* Constructs a GetTemplateRequest object.
*/
GetTemplateRequest::GetTemplateRequest()
: SesRequest(new GetTemplateRequestPrivate(SesRequest::GetTemplateAction, this))
{
}
/*!
* \reimp
*/
bool GetTemplateRequest::isValid() const
{
return false;
}
/*!
* Returns a GetTemplateResponse object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * GetTemplateRequest::response(QNetworkReply * const reply) const
{
return new GetTemplateResponse(*this, reply);
}
/*!
* \class QtAws::SES::GetTemplateRequestPrivate
* \brief The GetTemplateRequestPrivate class provides private implementation for GetTemplateRequest.
* \internal
*
* \inmodule QtAwsSES
*/
/*!
* Constructs a GetTemplateRequestPrivate object for Ses \a action,
* with public implementation \a q.
*/
GetTemplateRequestPrivate::GetTemplateRequestPrivate(
const SesRequest::Action action, GetTemplateRequest * const q)
: SesRequestPrivate(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the GetTemplateRequest
* class' copy constructor.
*/
GetTemplateRequestPrivate::GetTemplateRequestPrivate(
const GetTemplateRequestPrivate &other, GetTemplateRequest * const q)
: SesRequestPrivate(other, q)
{
}
} // namespace SES
} // namespace QtAws
|
import brownie
from brownie import *
def test_minter_deployed(minter):
assert hasattr(minter, "mint")
def test_token_balance_updates_on_mint(token, minter, accounts):
quantity = 10 ** 18
init_bal = token.balanceOf(accounts[0])
minter.mint(quantity, {"from": accounts[0]})
assert token.balanceOf(accounts[0]) == init_bal + quantity
def test_token_total_supply_updates_on_mint(token, minter, accounts):
quantity = 10 ** 18
init_supply = token.totalSupply()
minter.mint(quantity, {"from": accounts[0]})
assert token.totalSupply() == init_supply + quantity
def test_owner_can_set_minter(token, accounts):
assert token.minter() != accounts[1]
token.set_minter(accounts[1], {"from": token.owner()})
assert token.minter() == accounts[1]
def test_nonowner_cannot_set_minter(token, accounts):
hacker = accounts[1]
assert hacker != token.owner()
with brownie.reverts():
token.set_minter(hacker, {"from": hacker})
def test_nonminter_cannot_mint(token, accounts):
hacker = accounts[1]
assert hacker != token.minter()
with brownie.reverts():
token.mint(hacker, 10 ** 18, {"from": hacker})
def test_crv_transfers_on_mint(token, crv, accounts, minter):
init_bal = crv.balanceOf(accounts[0])
minter.mint(10 ** 18, {"from": accounts[0]})
assert crv.balanceOf(accounts[0]) < init_bal
|
<p-toast position="top-right" key="emailResponse"></p-toast>
<h1> {{contactMe}}</h1>
<hr>
<form [formGroup]="myForm" (ngSubmit)="sendEmail()" class="mb-5">
<!-- Name -->
<div class="mb-3 row">
<label class="col-sm-3 col-form-label">{{name}}</label>
<div class="col-sm-9">
<input type="text" class="form-control" [placeholder]="namePlaceHolder" formControlName="name">
<span class="form-text text-danger" error-msg [valid]="hasError('name')">
</span>
</div>
</div>
<!-- Email -->
<div class="mb-3 row">
<label class="col-sm-3 col-form-label">{{email}}</label>
<div class="col-sm-9">
<input type="text" class="form-control" [placeholder]="emailPlaceHolder" formControlName="email">
<span class="form-text text-danger" error-msg [msg]="emailErrorMsg" [valid]="hasError('email')">
</span>
</div>
</div>
<!-- Subject -->
<div class="mb-3 row">
<label class="col-sm-3 col-form-label">{{subject}}</label>
<div class="col-sm-9">
<input type="text" class="form-control" [placeholder]="subjectPlaceHolder" formControlName="subject">
<span class="form-text text-danger" error-msg [valid]="hasError('subject')">
</span>
</div>
</div>
<!-- Message -->
<div class="mb-3 row">
<label class="col-sm-3 col-form-label">{{message}}</label>
<div class="col-sm-9">
<textarea pInputTextarea class="form-control" [placeholder]="messagePlaceHolder" [autoResize]=true
formControlName="message"></textarea>
<span class="form-text text-danger" error-msg [valid]="hasError('message')">
</span>
</div>
</div>
<p-captcha siteKey="6Ld-mEkdAAAAAE0oC04-3IuqCxDbeTnK2WS_bDS1" (onResponse)="showResponse()" initCallback="loadCaptcha"></p-captcha>
<button pButton type="submit" class="p-button-raised p-button-rounded float-end mb-5 "
[label]="textButton" [disabled]="myForm.invalid || !recaptcha" >
</button>
</form>
<p-dialog [modal]="true" [draggable]="false" [closable]="false" [visible]="loading">
<p-progressSpinner></p-progressSpinner>
</p-dialog>
|
# TODO 递归函数
# 在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
# 举个例子,我们来计算阶乘n! = 1 x 2 x 3 x ... x n,用函数fact(n)表示,可以看出:
# fact(n)=n!=1×2×3×⋅⋅⋅×(n−1)×n=(n−1)!×n=fact(n−1)×n
# 所以,fact(n)可以表示为n x fact(n-1),只有n=1时需要特殊处理。
# 于是,fact(n)用递归的方式写出来就是:
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
print(fact(5))
# 递归函数的优点是定义简单,逻辑清晰。理论上,所有的递归函数都可以写成循环的方式,但循环的逻辑不如递归清晰。
# 使用递归函数需要注意防止栈溢出。在计算机中,函数调用是通过栈(stack)这种数据结构实现的,
# 每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出
# 解决递归调用栈溢出的方法是通过尾递归优化,事实上尾递归和循环的效果是一样的,所以,把循环看成是一种特殊的尾递归函数也是可以的。
# 尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。这样,编译器或者解释器就可以把尾递归做优化,使递归本身无论调用多少次,都只占用一个栈帧,不会出现栈溢出的情况。
# 上面的fact(n)函数由于return n * fact(n - 1)引入了乘法表达式,所以就不是尾递归了。要改成尾递归方式,需要多一点代码,主要是要把每一步的乘积传入到递归函数中:
def fact(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num - 1, num * product)
# 尾递归调用时,如果做了优化,栈不会增长,因此,无论多少次调用也不会导致栈溢出。
# 遗憾的是,大多数编程语言没有针对尾递归做优化,Python解释器也没有做优化,所以,即使把上面的fact(n)函数改成尾递归方式,也会导致栈溢出。
# 汉诺塔的移动可以用递归函数非常简单地实现。
# 期待输出:
# A --> C
# A --> B
# C --> B
# A --> C
# B --> A
# B --> C
# A --> C
# 请编写move(n, a, b, c)函数,它接收参数n,表示3个柱子A、B、C中第1个柱子A的盘子数量,然后打印出把所有盘子从A借助B移动到C的方法,例如:
def move(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
move(n - 1, a, c, b)
print(a, '-->', c)
move(n - 1, b, a, c)
move(3, 'A', 'B', 'C')
|
import React, { memo, useEffect, useMemo, useState } from 'react';
import {
StyleSheet,
Text,
View,
ActivityIndicator,
FlatList,
} from 'react-native';
import { Colors } from '../constants';
import { wp } from '../utils/Responsive_layout';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import Writer from './Writer';
const WriterDisplay = ({ title, DATA, loading }) => {
const [topWriters, setTopWriters] = useState([]);
const sortedWriters = useMemo(() => {
const copy = [...DATA];
return copy.sort((a, b) => {
const aPublishedArticles =
a?.publishedArticles?.filter(Boolean)?.length || 0;
const bPublishedArticles =
b?.publishedArticles?.filter(Boolean)?.length || 0;
// Sort in descending order based on the number of published articles
return bPublishedArticles - aPublishedArticles;
});
}, [DATA]);
useEffect(() => {
const timer = setTimeout(() => {
setTopWriters(sortedWriters);
}, 1000);
return () => clearTimeout(timer);
}, [sortedWriters]);
return (
<View style={styles.display}>
<View style={styles.header}>
<Text style={styles.title}>{title}</Text>
<MaterialCommunityIcons
name='arrow-right-thin'
size={30}
color={Colors.primary900}
/>
</View>
{loading ? (
<ActivityIndicator size='small' color={Colors.primary900} />
) : (
<FlatList
data={topWriters}
horizontal
keyExtractor={(item) => item.id}
showsHorizontalScrollIndicator={false}
renderItem={({ item }) => <Writer item={item} />}
contentContainerStyle={styles.flatListContent}
ListEmptyComponent={
<View style={styles.emptyListComponent}>
<Text style={styles.emptyListText}>No Writers Found!</Text>
</View>
}
/>
)}
</View>
);
};
export default memo(WriterDisplay);
const styles = StyleSheet.create({
display: {},
header: {
flexDirection: 'row',
marginHorizontal: 10,
marginVertical: 5,
},
title: {
fontFamily: 'Bold',
fontSize: 20,
flex: 1,
},
flatListContent: {
paddingHorizontal: wp(15),
},
emptyListComponent: {
marginVertical: 5,
flex: 1,
alignSelf: 'center',
alignItems: 'center',
justifyContent: 'center',
marginLeft: 50,
},
emptyListText: {
fontFamily: 'Regular',
fontSize: wp(15),
color: Colors.greyScale400,
},
});
|
import { Field, InputType, Int } from '@nestjs/graphql';
import { IsDefined, IsInt, IsNotEmpty, IsNumber, IsString } from 'class-validator';
/* 문항 생성 DTO */
@InputType()
export class CreateQuestion {
@Field()
@IsNotEmpty({ message: '문항번호는 숫자로만 가능합니다.' })
@IsNumber()
question_number: number;
@Field()
@IsNotEmpty({ message: '문항을 작성해주세요.' })
@IsString()
question_text: string;
@Field()
@IsNotEmpty({ message: '설문 ID는 필수로 작성해주세요.' })
@IsNumber()
surveyId: number;
}
/* 문항 수정 DTO */
@InputType()
export class UpdateQuestion {
@Field(() => Int)
@IsInt({ message: '아이디는 숫자형식 입니다.' })
@IsDefined({ message: '아이디를 입력해주세요.' })
id: number;
@Field({ nullable: true })
@IsNumber()
@IsNotEmpty({ message: '문항 번호를 작성해주세요.' })
question_number: number;
@Field({ nullable: true })
@IsNotEmpty({ message: '문항을 입력해주세요.' })
@IsString()
question_text: string;
}
|
// import React from 'react'
// import { Routes, Route } from "react-router-dom"
// import MainLayout from '../Components/MainLayout'
// import HomePage from './Pages/HomePage'
// import ReservationPage from './Pages/ReservatonPage'
// export default function App() {
// return (
// <div>
// <Routes>
// <Route path='/' element={<MainLayout />}>
// <Route index element={<HomePage />} />
// <Route path='reserve' element={<ReservationPage />}/>
// </Route>
// </Routes>
// </div>
// )
// }
import React from 'react'
import { BrowserRouter } from "react-router-dom";
import {Routes, Route} from "react-router-dom"
import MainLayout from '../Components/MainLayout'
import HomePage from './Pages/HomePage'
import ReservationPage from './Pages/ReservatonPage'
export default function App() {
return (
<div>
<BrowserRouter>
<Routes>
<Route path='/' element={<MainLayout />}>
<Route index element={<HomePage />} />
<Route path='reserve' element={<ReservationPage />} />
</Route>
</Routes>
</BrowserRouter>
</div>
)
}
|
import 'dart:convert';
import 'package:coodesh/failures.dart';
import 'package:coodesh/modules/list/data/list_file_data_source.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
setUpAll(() {
WidgetsFlutterBinding.ensureInitialized(); // Ensure Flutter is initialized once for all tests
});
group('ListFileDataSource', () {
late ListFileDataSource dataSource;
setUp(() {
dataSource = ListFileDataSource();
});
test('getLines returns lines within the specified range', () async {
const startLine = 1;
const endLine = 3;
final lines = await dataSource.getLines(startLine, endLine);
expect(lines, hasLength(endLine - startLine + 1));
expect(lines[0], 'about');
expect(lines[1], 'search');
expect(lines[2], 'other');
});
test('getLines throws ArgumentFailure if startLine > endLine', () async {
const startLine = 3;
const endLine = 1;
try {
await dataSource.getLines(startLine, endLine);
// The line above should throw an ArgumentFailure, so this line should not be reached.
fail('Expected ArgumentFailure, but no exception was thrown.');
} catch (e) {
expect(e, isA<ArgumentFailure>());
expect((e as ArgumentFailure).message, 'Start line must be less than or equal to end line');
}
});
test('getLines reads lines from the file', () async {
// You should have a test file (e.g., 'test_assets/test_data.txt') with sample data for this test.
const startLine = 1;
const endLine = 5;
// Load a test file from the 'test_assets' directory for this test.
final ByteData data = await rootBundle.load('test_assets/test_list.csv');
final List<String> expectedLines = utf8.decode(data.buffer.asUint8List()).split(',');
final lines = await dataSource.getLines(startLine, endLine);
expect(lines, hasLength(endLine - startLine + 1));
expect(lines, equals(expectedLines.sublist(startLine - 1, endLine)));
});
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.