2023-05-31

Is it possible to modify input function to echo uppercase letters?

Let's say that I have an input("> "), and if you try to input a lowercase "Hello, world!" it will look like this:

> HELLO WORLD!


How to get the value type from a record in Typescript

I have a function which returns a record: ReturnType: Record<string, {...<SOME_BIG_TYPE>...}>, and another function that I would like to accept {...<SOME_BIG_TYPE>...} as an argument. How can I grab that type from the record?

I would like something like the following where ExtractedValueOf grabs that value I mentioned earlier.

const function = ({ bigObject }: { bigObject: ExtractedValueOf<ReturnType> }) => null;

I was thinking something like ReturnType<keyof ReturnType> but this does not work.

Edit: Added a basic example that illustrates my issue.

I have here a function that returns Record<string, SomeType>, which is used to call my other function, which takes an argument of SomeType. This is all typesafe and how I would expect it to work:

type SomeType = {
  field: string;
  another: string;
};

function sample(): Record<string, SomeType> {
  return {
    object: {
      field: "Hello",
      another: "World",
    },
  };
}

function myFunction() {
  return myOtherFunction(sample().object);
}

function myOtherFunction(sampleObject: SomeType) {
  // something in here
  return sampleObject;
}

The problem is, in the place I have defined myOtherFunction, I don't have access to SomeType directly. I have access to the return type from sample, but I can't figure out how to get SomeType out of Record<string, SomeType>



If I use a String as argument on a Provider the return of a Provider work But If I use a List

just like instagram my application has a feature that are the saved. One person can save post. For this I added a field in the users collection "save", this field is an array of "post id". This "post id" is used to fetch recipes (another collection) A user, if you want to see the posts you saved, click on a button and you are directed to this widget: ("getReceitaGuardadosProvider"-> this is the provider that I m talking about) receita=ref.read(getReceitaGuardadosProvider(user.guardados)); So if I give this provider a String as a argument It will return AsyncData(), but If I give a List as a argument It will return AsyncLoading()

import 'package:chefapp/features/auth/controleer/auth_controller.dart';
import 'package:chefapp/features/receita/receitas_controller/receitas_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:chefapp/core/common/loader.dart';
import 'package:chefapp/core/common/error.dart';

import '../../models/teste.dart';
import '../receita/receita_screen.dart';

class GuardadosPerfil extends ConsumerWidget {
  const GuardadosPerfil({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final user = ref.watch(userProvider)!;
//final receitaa = //ref.read(getReceitaGuardadosProvider(user.guardados));
//print('receita');
    //print(receitaa);
    //print(user.guardados);
    return Scaffold(
      appBar: AppBar(
        title: const Text('Receitas Guardadas'),
      ),
      
      body: ref.read(getReceitaGuardadosProvider(user.guardados)).when(
            data: (data) {
              return ListView.builder(
                itemCount: data.length,
                itemBuilder: (BuildContext context, int index) {
                  final receita = data[index];
                  return ReceitaScreen(
                      receita: receita, usermodel: user, aux: true);
                },
              );
            },
            error: (error, StackTrace) {
              return ErrorText(error: error.toString());
            },
            loading: () => const Loader(),
          ),
    );
  }
}

Here is a controller Controller.dart

    import 'package:chefapp/core/providers/storage_repository_provider.dart';
import 'package:chefapp/features/auth/controleer/auth_controller.dart';
import 'package:chefapp/models/receita_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:routemaster/routemaster.dart';
import 'package:uuid/uuid.dart';
import 'dart:io';
import '../../../core/utils.dart';
import '../../../models/coment_model.dart';
import '../../../models/teste.dart';
import '../../../models/usermodel.dart';
import '../receita_repository/receita_repository.dart';

final receitaControllerProvider =
    StateNotifierProvider<ReceitaController, bool>((ref) {
  final receitaRepository = ref.watch(receitaRepositoryProvider);
  final storageRepository = ref.watch(storageRepositoryProvider);
  return ReceitaController(
      receitaRepository: receitaRepository,
      ref: ref,
      storageRepository: storageRepository);
});

  final getReceitaGuardadosProvider = StreamProvider.family<List<Receita>, List<String>>(
  (ref, guardados) {
    print('ola');
    final receitaController = ref.watch(receitaControllerProvider.notifier);
    return receitaController.getReceitaGuardados(guardados);
  },
);


class ReceitaController extends StateNotifier<bool> {
  final ReceitaRepository _receitaRepository;
  final Ref _ref;
  final StorageRepository _storageRepository;
  ReceitaController({
    required ReceitaRepository receitaRepository,
    required Ref ref,
    required StorageRepository storageRepository,
  })  : _receitaRepository = receitaRepository,
        _ref = ref,
        _storageRepository = storageRepository,
        super(false);
  
  Stream<List<Receita>> getReceitaGuardados(List<String> guardados) {
    print('controller');
    print(_receitaRepository.getReceitaGuardados(guardados));
    return _receitaRepository.getReceitaGuardados(guardados);
  }
} 

Here is a repository.dart

import 'package:chefapp/core/constants/firebase_constants.dart';
import 'package:chefapp/core/failure.dart';
import 'package:chefapp/models/usermodel.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fpdart/fpdart.dart';
import '../../../core/providers/firebase_providers.dart';
import '../../../core/type_defs.dart';
import '../../../models/coment_model.dart';
import '../../../models/receita_model.dart';

final receitaRepositoryProvider = Provider((ref) {
  return ReceitaRepository(
    firestore: ref.watch(firestoreProvider),
  );
});

class ReceitaRepository {
  final FirebaseFirestore _firestore;

  ReceitaRepository({required FirebaseFirestore firestore})
      : _firestore = firestore;

  CollectionReference get _receitas =>
   _firestore.collection(FirebaseConstants.receitasCollection);

  CollectionReference get _users =>
      _firestore.collection(FirebaseConstants.usersCollection);

  CollectionReference get _comments =>
   _firestore.collection(FirebaseConstants.commentsCollection);

  Stream<List<Receita>> getReceitaGuardados(List<String> guardados) {
    return _receitas
        .where('id', whereIn: guardados)
        .orderBy('datacriacao', descending: true)
        .snapshots()
        .map(
          (event) => event.docs
              .map(
                (e) => Receita.fromMap(
                  e.data() as Map<String, dynamic>,
                ),
              )
              .toList(),
        )
       .map((list) {
        print('repository');
        print(list); // Adicione este print para imprimir a lista
     return list;
      });
  }
}

All the print that I use seems to be alright. I really don't know what can I do. If I change the function to accept a String I can print the recipe but only one, If I use a List the loading: () => const Loader() is the only thing I see.

some output of the prints Instance of '_MapStream<List, List>'

AsyncLoading<List>()

[Receita(id: 1197ddb0-fe44-11ed-ab9c-f3074e6ebbf2, name: rece, uidusuario: 9Fb0QHEtdjXUX4JsahQ7urcYI333, tempo: 32, calorias: 32, refeicoes: [Bebidas], categorias: [Peixe], ingredientes: 321, comofazer: 213123, likes: [], datacriacao: 2023-05-29 19:13:04.415, countcomentarios: 0, image: https://ift.tt/8KaCLw1]



Wrap a paragraph around an image in bootstrap

I want the paragraph to go around the image and wrap it so I don't waste space. My code:

<div class="container">
  <div class="row">
    <div class="col-6">
      <h1 class="display-4">Lorem ipsum</h1>
      <p class="lead">Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.</p>
      <a href="#" class="btn btn-outline-dark rounded-pill">התחל לכתוב</a>
    </div>
    <div class="col-6">
      <img src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.YrOgCeeTMGooIg3gpMz8qgHaHa%26pid%3DApi&f=1&ipt=8172a3c985e7c4343b252d0ccaa06f7c36f146a5f6ce4f20fc7c801bf5ce2974&ipo=images" alt="Round Image" class="rounded-circle">
    </div>
  </div>
</div>

I tried having the image below the paragraph but it doesn't work.



How do I implement timeOuts in TestNG? They don't appear to be working

@Test(dataProvider="TestDataSets", dataProviderClass = TestData.class, groups = { "SmokeTests", "Regression" }, timeOut = 120000)
public void MyTestCase(String scenario, String formName) throws Exception {

Am I implementing the timeOut incorrectly? This should timeout after 120 seconds, correct? Some of my test cases run too long and should be terminating at 120 seconds but they are never terminated by TestNG.

I'm running Java 17 with TestNG 7.8.0

Upon further investigation TestNG did determine that my test case hit the timeOut:

[ERROR] testCaseClassFile.methodName » ThreadTimeout Method tests.testCaseClassFile.methodName() didn't finish within the time-out 120000

Apparently it hit the timeOut and kept on going. The TestNG documentation made me think that it would stop execution:

Section 5.11.2 of the TestNG documentation states,

Additionally, a time-out of ten seconds guarantees that none of the threads will block on this thread forever.

Assuming the documentation is in fact true then this would seem like a bug to me.



mplfinance: 'secondary_y=True' not working. Not plot multiple lines/candles due to very wide Y-Axis data ranges

I want to compare price movement of two scrips with Stock Indices in one chart object (single panel) using mplfinance in python 3.11.3.

Tried code from snippet: https://github.com/matplotlib/mplfinance/blob/master/examples/addplot.ipynb

I have data in 3 excel csv files that are to be plotted (line or candle) in one chart:

Indeces data

Data of scrip1

Data of scrip2

Comparison of two tables is generating chart below:

Chart comparing data in two tables

I tried the mplfinance method given in

Plot multiple mplfinance plots sharing x axis

This method exits the console.

Then, the following code has been tried:

import mplfinance as mpf
import pandas as pd

idc = pd.read_csv(r'D:\NUVAMA_STOCK_DATA\CHARTING-BANKNIFTY-25 MAY 2023\Nifty Bank_03March2023-25 MAY 2023_CHART.csv')
idc['Date'] = pd.to_datetime(idc['Date'], format = "mixed")
idc.set_index('Date', inplace=True)
intraday = idc
intraday.index.name = 'Date'
intraday.shape
intraday.head(3)
intraday.tail(3)

iday = intraday.loc['22-05-2023  09:16:00':'25-05-2023  15:29:00',:]


ce = pd.read_csv(r'D:\NUVAMA_STOCK_DATA\CHARTING-BANKNIFTY-25 MAY 2023\BANKNIFTY 25MAY 2023 CE 46500_CHART.csv')
ce['Date'] = pd.to_datetime(ce['Date'], format = "mixed")
ce.set_index('Date', inplace=True)
intraday2 = ce
intraday2.index.name = 'Date'
intraday2.shape
intraday2.head(3)
intraday2.tail(3)

iday2 = intraday2.loc['22-05-2023  09:16:00':'25-05-2023  15:29:00',:]



pe = pd.read_csv(r'D:\NUVAMA_STOCK_DATA\CHARTING-BANKNIFTY-25 MAY 2023\BANKNIFTY 25 May 2023 PE 43600_CHART.csv')
pe['Date'] = pd.to_datetime(pe['Date'], format = "mixed")
pe.set_index('Date', inplace=True)
intraday1 = pe
intraday1.index.name = 'Date'
intraday1.shape
intraday1.head(3)
intraday1.tail(3)

iday1 = intraday1.loc['22-05-2023  09:16:00':'25-05-2023  15:29:00',:]

ap = [mpf.make_addplot(iday1, type='line', y_on_right=True), mpf.make_addplot(iday2, type='candle', y_on_right=True),]

mpf.plot(
    iday,
    volume=True,
    title='BANKNIFTY&PE 43600', ylabel='Price ($)', ylabel_lower='Volumes', #figratio=(12,4),
    type="line",
    style="sas",
    addplot=ap, 
    )

This code gives following error message:

"D:\PYTHON_3.11.3\Lib\site-packages\mplfinance\plotting.py:694: UserWarning: Attempting to set identical low and high ylims makes transformation singular; automatically expanding.
  volumeAxes.set_ylim(vymin,vymax)
Traceback (most recent call last):
  File "D:\PyProgFiles\ChatGPT\CS_Mpf\TEST_MULTI_BNPECE_StackOverFlow.py", line 44, in <module>
    mpf.plot(
  File "D:\PYTHON_3.11.3\Lib\site-packages\mplfinance\plotting.py", line 780, in plot
    ax = _addplot_columns(panid,panels,ydata,apdict,xdates,config)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\PYTHON_3.11.3\Lib\site-packages\mplfinance\plotting.py", line 1075, in _addplot_columns
    ymhi = math.log(max(math.fabs(np.nanmax(yd)),1e-7),10)
                                  ^^^^^^^^^^^^^
  File "<__array_function__ internals>", line 200, in nanmax
  File "D:\PYTHON_3.11.3\Lib\site-packages\numpy\lib\nanfunctions.py", line 483, in nanmax
    res = np.amax(a, axis=axis, out=out, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<__array_function__ internals>", line 200, in amax
  File "D:\PYTHON_3.11.3\Lib\site-packages\numpy\core\fromnumeric.py", line 2820, in amax
    return _wrapreduction(a, np.maximum, 'max', axis, None, out,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\PYTHON_3.11.3\Lib\site-packages\numpy\core\fromnumeric.py", line 86, in _wrapreduction
    return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: zero-size array to reduction operation maximum which has no identity"

Unable to understand what's going wrong.

DATA:

BANKNIFTY 25MAY 2023 CE 46500_CHART.csv

BANKNIFTY 25 May 2023 PE 43600_CHART

Nifty Bank_03March2023-25 MAY 2023_CHART.csv



Problem with using self-built GDAL in Docker

I am trying to prepare an Ubuntu 22.04 Docker image with GDAL 3.2.2. This GDAL installation needs to have ECW support, which means I cannot use the pre-built gdal-bin package that can be installed using apt.

I can build and install GDAL with these specs in the Docker container. But when running a simple test command on a simple tiff file I get an error that I have no idea how to debug.

$ gdalinfo --version
GDAL 3.2.2, released 2021/03/05
$ gdalinfo test.tif
Driver: GTiff/GeoTIFF
Files: test.tif
Size is 572, 577
Aborted (core dumped)

The steps I took was starting with a regular Ubuntu 22.04 Docker image. Installing prerequisites (gcc and stuff). Downloading the ECW SDK. Install that. Download the source of gdal 3.2.2. Configure the build to include ECW. Use the make file to build and then install.

If I do not use a self-built GDAL but rather install gdal-bin using apt directly, it works for the tiff file, but it would mean I have no ECW support.

I have also successfully built and used GDAL with ECW directly on Ubuntu 22.04 without Docker.

Does anyone know a solution for this or have any idea in which direction I could look to potentially debug it?



2023-05-30

Error while doing a POST call from Angular to Firebase Cloud Function

I've created a Firebase Cloud Function and it's working;

export const deleteUser = functions.https.onRequest(async (request, response) => {
  const userEmail = request.body.userEmail;
  await admin.auth().getUserByEmail(userEmail)
    .then(function (userRecord:any) {
      const uid = userRecord.uid;
      admin.auth().deleteUser(uid)
        .then( () => {
          console.log('User deleted');
          response.status(200).send('User deleted');
        })
        .catch(() => {
          console.log('Error deleting user');
          response.status(500).send('Failed to delete user');
        });
    })
    .catch(() => {
      console.log('Error fetching user');
      response.status(500).send('Failed while fetching user');
    })
})

I've checked with Postman and everythings is ok, it deletes the user from Firebase as expected. Screenshot of the call from Postman

I call my service from my component, and works fine.

removeUser(userUid:any, userEmail:any){
    userEmail = {'userEmail': userEmail};
    this.authService.gdelete(userEmail).subscribe();
    // this.usersService.removeUser(userUid);
  }

The problem is when I call the Cloud Funtcion from my Angular Service.

  gdelete(userEmail:any) {
    //no consigo conectar el post con la cloud function 
    const httpOptions = {
      headers: new HttpHeaders({
          'Content-Type': 'application/json', 
          'Access-Control-Allow-Origin': '*'
      })
    };
    return this.http.post('https://myfirebaseserver.cloudfunctions.net/deleteUser', {body: userEmail}, httpOptions);
  }

It displays the following error: Screenshot of the error in the browser console

I think the problem is when I call the cloud function. I've serched on SO lots of posts related and implemented the solutions but nothing worked.



Auto-refetch a mutation by invalidating its tag from another mutation

Can I auto-refetch getEmployees mutation by invalidating its tag from another mutation called deleteEmployee in the code below?

import { createApi } from '@reduxjs/toolkit/query/react'
import customFetchBase from './customFetchBase.js'

export const publicApi = createApi({
  reducerPath: 'publicApi',
  baseQuery: customFetchBase,
  tagTypes: ['employees'],
  endpoints: builder => ({
    getEmployees: builder.mutation({
      query: ({
        formData = "defaultHashedDataString",
        salt = "xyz",
        pageIndex = 1
      }) => ({
        url: '/Hafez/Employee/Data',
        method: 'POST',
        body: {
          RequestVerificationToken: salt,
          FormData: formData,
          currentPage: pageIndex + 1
        }
      }),
      providesTags: ['employees']
    }),
    deleteEmployee: builder.mutation({
      query: ({ formData, salt }) => ({
        url: '/Hafez/Employee/Delete',
        method: 'POST',
        body: { RequestVerificationToken: salt, FormData: formData }
      }),
      invalidatesTags: ['employees']
    })
  })
})

export const { useGetEmployeesMutation, useDeleteEmployeeMutation } = publicApi

Now when I call deleteEmployee mutation the getEmployees mutation does not run.

I know that I should use a GET request for getting data from server but for some security it can't be changed.



How can I configure the log of grpc Java client to output all levels of grpc logs?

I have a server and a client using logback as log framework, client and server use grpc Java to communicate with each other. Now I want to output all level of grpc logs, I change the log level to trace on logback.xml, but there are not all grpc logs output to the log file.

I add logging.properties and add -Djava.util.logging.config.file=logging.properties, It seems not work at all.

# Create a file called logging.properties with the following contents.
handlers=java.util.logging.ConsoleHandler
io.grpc.level=FINE
java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter

I want to output the logs of grpc re-connection attempts and all connect and re-connect actions. How to config the grpc logs?

add JAVA_OPTS=-Djava.util.logging.config.file=logging.properties


What will be the time and space complexity for vertical order traversal of a binary tree?

I have written the following c++ function to traverse a binary tree in vertical order. For nodes on the same vertical level, I want to store them in the order they will appear in the level order traversal.

Example: If we have the tree like this:

    1
  /   \
 2     3
/ \   /  \
4  5 6   7

I want to return a vector of vectors as:

{
{4}
{2}
{1 5 6}
{3}
{7}
}
void traversal(TreeNode* node, int x, int y, map<int,map<int,vector<int>>> &m){
    if(node == NULL){
        return;
    }
    if(m[x].find(y) == m[x].end()){
        vector<int> temp;
        m[x][y] = temp;
    }
    m[x][y].push_back(node->val);
    traversal(node->left,x-1,y+1,m);
    traversal(node->right,x+1,y+1,m);
    return;
    
} 
vector<vector<int>> verticalOrderTraversal(TreeNode* A) {
    map<int,map<int,vector<int>>> m;
    traversal(A,0,0,m);
    vector<vector<int>> ans;
    for(auto itr:m){
        vector<int> temp;
        for(auto itr2:itr.second){
            for(auto i:itr2.second){
                temp.push_back(i);
            }
        }
        ans.push_back(temp);
    }
    return ans;
}

How do I calculate its time complexity and space complexity in big O notation?

I read somewhere that the optimized code is of O(NlogN) time complexity. But it uses level order traversal. How do I calculate time complexity for my code that uses pre-order traversal?



Laravel mysql order by with wherehas

I have 2 tables :-

  1. users - id,name,email, mobile

  2. user_info - id,user_id, store_name, startup_date

  3. User Model

    class EloquentUser extends Model { protected $table = 'users';

     /**
      * The attributes that are mass assignable.
      *
      * @var array
      */
     protected $fillable = [
         'name',
          'email',
        'mobile'
     ];
    

    }

  4. User Info Model

    class UserInfo extends Model { use HasFactory, SoftDeletes; public $table = 'user_info';

    }

Below is relationship on above 2 tables :-

public function info() {
        return $this->hasOne(UserInfo::class,'user_id','id');
    }

I want to order on base of startup_date but it is giving error column not found. Below is the query :-

$reponse = EloquentUser::with('info')->has('info')->orderBy('info.startup_date')->get();


2023-05-29

Training a BARTForSequenceClassification returns data with ununiform dimentsions

I am trying to fine-tune a BART-base model on a dataset that I have. The dataset looks like this: It has columns "id", "text", "label" and "dataset_id". The "text" column is what I want to use as inputs to the model, and it is plain text. "label" is a value of either 0 or 1.

I've already written the code for Training, using transfomers==4.28.0.

This is the code for the dataset class:

class TextDataset(Dataset):
    def __init__(self, encodings):
        self.encodings = encodings

    def __getitem__(self, idx):
        return {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}

    def __len__(self):
        return len(self.encodings['input_ids'])

This is the code for loading and encoding of the data:

def load_data(directory):
    files = os.listdir(directory)
    dfs = []
    for file in files:
        if file.endswith('train.csv'):
            df = pd.read_csv(os.path.join(directory, file))
            dfs.append(df)
    return pd.concat(dfs, ignore_index=True)
print(len(load_data("splitted_data/gender-bias")))

def encode_data(tokenizer, text, labels):
    inputs = tokenizer(text, padding="max_length", truncation=True, max_length=128, return_tensors="pt")
    inputs['labels'] = torch.tensor(labels)
    return inputs

This is the code for the metrics for evaluation. I use the f1_score function from scikit.

def compute_metrics(eval_pred):
    logits = eval_pred.predictions
    labels = eval_pred.label_ids
    predictions = np.argmax(logits, axis=-1)
    return {"f1": f1_score(labels, predictions)}

This is the training function:

def train_model(train_dataset, eval_dataset):
    # Define the training arguments
    training_args = TrainingArguments(
        output_dir='./baseline/results',           # output directory
        num_train_epochs=5,               # total number of training epochs
        per_device_train_batch_size=32,   # batch size per device during training
        per_device_eval_batch_size=64,    # batch size for evaluation
        warmup_steps=500,                 # number of warmup steps for learning rate scheduler
        weight_decay=0.01,                # strength of weight decay
        evaluation_strategy="steps",      # evaluation is done at each training step
        eval_steps=50,                    # number of training steps between evaluations
        load_best_model_at_end=True,      # load the best model when finished training (defaults to `False`)
        save_strategy='steps',            # save the model after each training step
        save_steps=500,                   # number of training steps between saves
        metric_for_best_model='f1',       # metric to use to compare models
        greater_is_better=True            # whether a larger metric value is better
    )

    # Define the trainer
    trainer = Trainer(
        model=model,
        args=training_args,
        train_dataset=train_dataset,
        eval_dataset=eval_dataset,
        compute_metrics=compute_metrics
    )

    # Train the model
    trainer.train()

    return trainer

This is how I defined the model and etc.

model = BartForSequenceClassification.from_pretrained('facebook/bart-base', num_labels=2)
tokenizer = BartTokenizer.from_pretrained('facebook/bart-base')

train_df = load_data("splitted_data/gender-bias")
train_encodings = encode_data(tokenizer, train_df['text'].tolist(), train_df['label'].tolist())

# For simplicity, let's split our training data to create a pseudo-evaluation set
train_size = int(0.9 * len(train_encodings['input_ids']))  # 90% for training
train_dataset = {k: v[:train_size] for k, v in train_encodings.items()}
print(train_dataset)
print(len(train_dataset))

eval_dataset = {k: v[train_size:] for k, v in train_encodings.items()}  # 10% for evaluation

# Convert the dictionary data to PyTorch Dataset
train_dataset = TextDataset(train_dataset)
eval_dataset = TextDataset(eval_dataset)

trainer = train_model(train_dataset, eval_dataset)

The training looks just fine. However, when it comes to evaluation during training, an error is raised from my compute_metrics function, which takes a parameter as the output of the model. The model should be a binary classification model, returning the probabilistic of each label in its output I believe.

np.argmax(np.array(logits), axis=-1) 21 
ValueError: could not broadcast input array from shape (3208,2) into shape (3208,)

I've tried to output the type of the logits, and it turns out that type(logits) return Tuple. Considering that this might be caused the fact that evaluation dataset might be split into batches, and the returned Tuple is a number of separate numpy arrays, I've also tried to concatenate the tuple.

def compute_metrics(eval_pred):
    logits = eval_pred.predictions
    labels = eval_pred.label_ids
    logits = np.concatenate(logits, axis=0)
    predictions = np.argmax(logits, axis=-1)
    return {"f1": f1_score(labels, predictions)}

But this raised a new error:

packages/numpy/core/overrides.py in concatenate(*args, **kwargs) 

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 3 dimension(s)

How can I solve this issue?



Can you use the activeElement property to see if an element with a specific class name has focus?

Im trying to get the Boolean true if elements with a certain class name are focused on. But it seems Document.activeElement only works with either ID or Tag name, which wont help since they're elements of the same type. Heres the situation:

var test2 = document.getElementsByClassName('test2')
var test3 = document.getElementsByClassName('test3')

test3[1].focus()

isFocused2 = (document.activeElement === test2)
isFocused3 = (document.activeElement === test3)

document.getElementById('test').innerHTML = isFocused3
<input type="text" class="test2">
<input type="text" class="test3">
<input type="text" class="test2">
<input type="text" class="test3">

<div id="test"></div>

@Michael It works ONLY if the focus () is set to the input as you'll see below, but clicking on the input doesn't seem to make it active hence making the isFocused variable stay on false (my mistake in giving you the idea that i wanted to use that method to focus instead of clicking)

const prev = document.getElementsByClassName('prev');
const curr = document.getElementsByClassName('curr');

// curr[1].focus()

var isFocused1 = document.activeElement.classList.contains("prev");
var isFocused2 = document.activeElement.classList.contains("curr");


function fx2 () {
document.getElementById('test').innerHTML += isFocused1 + ' ' + isFocused2 + ' '
}
<table>
    <tr>
   <td><input type="text" name="" class="prev" onclick="fx2()"></td>
   <td><input type="text" name="" class="curr" onclick="fx2()"></td>
   <td><p class="Mtr-result"></p></td>
    </tr>
    <tr>
<td><input type="text" name="" class="prev" onclick="fx2()"></td>
<td><input type="text" name="" class="curr" onclick="fx2()"></td>
<td><p class="Mtr-result"></p></td>
    </tr>


<div  id="test"></div>

as you can see the focus method has been commented out, and the onclick event attribute on the input calls the fx2() function that changes the innerHTML value of the 'test' div to the value of isFocused 1 and 2, which both show false.



Inserting Overlay Content Into Header Of Jekyll Theme

I want to add overlay content to the header, specifically to overlay on top of the Header Image.

Details

I have written the HTML/Liquid and SCSS and it all works when I test it outside of the site build, but I wanted to know how to add this overlay content into the header of all pages using the _masthead.html. The goal is to insert a widget of sorts with variable content. This is what the header currently looks like on the site image of website header This is what it is supposed to look like image of website header

What it Looks Like Now

After I implemented what Christian told me it looks like this now What it looks like now

The Files

The repository can be found here, and the components are:

This is the _masthead.html



  <div id="masthead-no-image-header">
    <div class="row">
      <div class="small-12 columns"><!-- <a id="logo" href="/" title=" – ">
        <img src="/assets/img/" alt=" – ">
        </a> -->
      </div>
      <!-- /.small-12.columns -->
    </div>
    <!-- /.row -->
  </div>
  <!-- /#masthead -->

  




This is the header-widget.scss

@import "/assets/fonts/imports.css";
// @import url(https://raw.githubusercontent.com/NewSpectrum/Technovine-Site/main/_sass/foundation-components/_header-button.scss)

//▸ Widget Properties
$header-color:      hsl(0deg, 0%, 100%);
$txt-color:         hsl(0deg, 0%, 100%);
$inner-shadow:      inset 2px 2px 5px hsla(0deg, 0%, 0%, 0.5);
$txt-shadow:        0.5px 0.5px 5px hsla(0deg, 0%, 0%, 0.5);
$widget-bg-color:   hsla(0deg, 0%, 0%, 0.5);
$widget-padding:    1rem 2.5rem 2rem 2.5rem;


//▸ Button Properties
$sr-bg:             hsl(
                          18deg,
                          100%,
                          62%
                        );
$button-text:       hsl(0deg, 0%, 100%);
$button-gr1:        hsl(18deg,
                          100%, 62%);
                    // #ff773d
$button-gr2:        hsl(18deg, 80%, 45%);
                    // #cf4e17
$box-shadow:        1px 1px 3px hsla(0, 0%, 0%, 50%);
$text-shadow:       0.5px 0.5px 1.5px hsla(0, 0%, 0%, 50%);

$button-gradient:   linear-gradient(
                        135deg,
                        $button-gr1 0%,
                        $button-gr2 100%
                    );


.header-widget {
    position: relative;
    align-items: left;
    max-width: 1000px;
    margin-left: auto;
    margin-right: auto;

    .widget-container {
        background-color: $widget-bg-color;
        padding: $widget-padding;
        border-radius: 20px;
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        box-shadow: $inner-shadow;

        h1,
        h2,
        h3,
        h4,
        h5,
        h6 {
            font-family: "Libre Baskerville", serif;
            color: $header-color;
        }


        p {
            font-family: "Lato", sans-serif;
            font-size: 1rem;
            color: $txt-color;
        }
    }

}




.button-container {
    position: relative;
    max-width: 200px;
    font-family: "Lato", sans-serif;
    text-shadow: $text-shadow;
    background: $button-gradient;
    color: $button-text;
    border: 0;
    box-shadow: $box-shadow;
    border-color: hsla(0, 0%, 0%, 0%);
    border-radius: 20px;
    padding: 10px 20px;
    a {
        color: inherit;
        text-decoration: none;
    }
}

This is the header-widget-button.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Button Test</title>

    <link rel="stylesheet" href="../css/_header-button.css">
    <script id="service-request_script"
     src="../js/service-request_button.js"></script>
    <script id="slideshow">
        // JavaScript
        // Change 'background-image' in 'body' (css)
        // Change <section> content
    </script>
</head>
<body>
    <section id="header-widget" class="header-widget">
        <div id="sales-widget" class="widget-container">
            <h1>
                Worry-Free Professional IT Services
            </h1>
            <p>
                No need to worry about amateur service. Get the IT professionals your business needs.
            </p>
            <!--BUTTON-->
            <br /><br />
            <div id="button-container" class="sales-request button">
                <button id="sales_button" onclick="requestService()">
                    Get&nbsp;Quote
                </button>
            </div>
        </div>

<br><br>

        <div id="service-request_widget" class="widget-container">
            <h1>
                Worry-Free Professional IT Services
            </h1>
            <p>
                No need to worry about amateur service. Get the IT professionals your business needs.
            </p>
            <!--BUTTON-->
            <br /><br />
            <div id="button-container" class="sales-request button">
                <button id="sales_button" onclick="requestService()">
                    Submit&nbsp;Ticket
                </button>
            </div>
        </div>
    </section>
</body>
</html>

This is the header-widget.liquid

<section id="header-widget" class="widget-container">
    <div id="sales-widget" class="header-widget">
        
            <code>widget_title is not set</code>
        
        <p>
            
        </p>
        <!--BUTTON-->
        <br /><br />
        <div id="button-container" class="button-container">
            <button id="sales_button" onclick="requestService()">
                <a href="">
                    
                </a>
            </button>
        </div>
    </div>
</section>

This is index.md

header:
  image_fullwidth: networking-connections-004.jpeg
header_widget:
  widget_title: "Worry-Free Professional IT Services"
  widget_text: |
    No need to worry about amateur service. Get the IT professionals your business needs.
  button_text: "Request a Quote"
  button_url: "/contact"


How to Update user data with patch and react native

I have a react native app and I try to update the user data. Like firstname, lastname, etc.

And I am calling a api call. And I try to update a logged in user through passing arguments in the header of the api call. But apparently that doesn't work untill now. Only when I pass the arguments hardcoded then it works.

So this is the service:

export const AccountUpdateRequest = async (
    first_name,
    last_name,
    email,
    username,
    password,
    password2
) => {
    const token = await retrieveToken();
    console.log("response");
    try {
        if (token) {
            const response = await fetch("http://192.168.1.65:8000/api/user/me/", {
                method: "PATCH",
                headers: {
                    Authorization: `Token ${token}`,
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    first_name: first_name,
                    last_name: last_name,
                    email: email,
                    username: username,
                    password: password,
                    password2: password2,
                }),
            });

            return await response.json();
        } else {
            throw new Error(token);
        }
    } catch (error) {
        //console.log(error);
        error("can't retrieve data");
    }
};

And so this doens't work.

The old values are not updated:

Object {
  "email": "n@n.nl",
  "first_name": "helloThere",
  "last_name": "jooh",
  "username": "username999",
}

But I entered for firstName: helloTherejjj

But if I pass the properties hardcoded:

    body: JSON.stringify({
                    first_name: "helloThere",
                    last_name: "jooh",
                    email: "hello@email.nl",
                    username: "username999",
                    password: "1234567890",
                    password2: "1234567890",
                }),

Then it works.

And I have the context:

const UpdateUserProfileRequest = async (
        first_name,
        last_name,
        email,
        username,
        password,
        password2
    ) => {
        setIsLoading(true);
        AccountUpdateRequest(first_name, last_name, email, username, password, password2)
            .then((u) => {
                console.log(u);
                setUser(u);
                setIsLoading(false);
            })
            .catch((e) => {
                setIsLoading(false);
                setError(e.toString());
            });
    };

And the view with the input fields:

export const SetScreen = ({ navigation }) => {
    const [username, setUsername] = useState("");
    const [firstName, setFirstName] = useState("");
    const [lastName, setLastName] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [password2, setPassword2] = useState("");
    const {
        isLoading,
        onLogout,
        error,      
        passwordValidError,
        UpdateUserProfileRequest,
    } = useContext(AuthContext);

    const changedText = (evt) => {
        console.log("changed", firstName);
    };

    useEffect(() => {
        AccountRequest().then((data) => {
            setFirstName(data.first_name);
            setLastName(data.last_name);
            setEmail(data.email);
            setUsername(data.username);
            setPassword(data.password);
            setPassword2(data.password2);
        });
    }, []);

    return (
        <>
            <ScrollView style={styles.scrollView}>
                <AccountBackground>
                    <AccountCover />
                    <Title>Instellingen</Title>
                    <AccountContainer>
                        <AuthInput
                            label="Voornaam"
                            value={firstName}
                            autoCapitalize="none"
                            onChange={changedText}
                            onChangeText={(fn) => setFirstName(fn)}
                        />
                        <Spacer size="large">
                            <AuthInput
                                label="Achternaam"
                                value={lastName}
                                autoCapitalize="none"
                                textContentType="Achternaam"
                                onChangeText={(ln) => setLastName(ln)}
                            />
                        </Spacer>
                        <Spacer size="large">
                            <AuthInput
                                label="E-mail"
                                value={email}
                                textContentType="emailAddress"
                                keyboardType="email-address"
                                autoCapitalize="none"
                                onChangeText={(em) => setEmail(em)}
                            />
                        </Spacer>

                        <Spacer size="large">
                            <AuthInput
                                label="Username"
                                value={username}
                                textContentType="username"
                                keyboardType="username"
                                autoCapitalize="none"
                                onChangeText={(un) => setUsername(un)}
                            />
                        </Spacer>
                        <Spacer size="large">
                            <AuthInput
                                label="Wachtwoord"
                                value={password}
                                textContentType="password"
                                secureTextEntry
                                autoCapitalize="none"
                                onChangeText={(p) => {
                                    setPassword(p);
                                }}
                                error={passwordValidError}
                            />
                        </Spacer>
                        <Spacer size="large">
                            <AuthInput
                                label="Herhaal wachtwoord"
                                value={password2}
                                textContentType="password2"
                                secureTextEntry
                                autoCapitalize="none"
                                onChangeText={(pas) => setPassword2(pas)}
                            />
                        </Spacer>
                        {error && (
                            <ErrorContainer size="large">
                                <Text variant="error">{error}</Text>
                            </ErrorContainer>
                        )}

                        <Spacer size="large">
                            {!isLoading ? (
                                <AuthButton
                                    ion-icon
                                    name="log-out-outline"
                                    mode="contained"
                                    onPress={() => onLogout()}>
                                    uitloggen
                                </AuthButton>
                            ) : (
                                <ActivityIndicator animating={false} />
                            )}
                        </Spacer>
                        <Spacer size="large">
                            <AuthButton icon="email" mode="contained" onPress={() => UpdateUserProfileRequest()}>
                                save
                            </AuthButton>
                        </Spacer>
                    </AccountContainer>
                    <Spacer size="large">
                        <AuthButton mode="contained" onPress={() => navigation.goBack()}>
                            Back
                        </AuthButton>
                    </Spacer>
                </AccountBackground>
            </ScrollView>
        </>
    );
};

and AuthInput:

export const AuthInput = styled(TextInput)`
    width: 200px;
    background-color: #c6daf7;
`;

Question: how to update the user data with the given parameters?



Dynamic sub Select using Expression with FromSqlRaw in .Net Core (v7) with cast to Entity EF (Ex: The required column not present of 'FromSql')

This is simplified example of what is needed.
Could this somehow be made to work?

Entity:

public class Entry
{
    public int EntryId { get; set; }
    public string Name { get; set; } = null!;
    public string? Description { get; set; }
}

DbContext:

public DbSet<Entry> Entries { get; set; } = null!;

Code:

public void RunTest(DbContext context)
{
    // direct linq Select two column into Entity
    var list = context.Entries.Select(a => new Entry { EntryId = a.EntryId, Name = a.Name }).ToList();
    // Generated Sql (seen in profiler): SELECT [e].[EntryId], [e].[Name] FROM [Entry] AS [e]

    var type = typeof(Entry);

    // dynamic Select with Expression (result should be same as direct above)

    // does NOT Work for subSelect
    // Exception: 'The required column 'Description' was not present in the results of a 'FromSql' operation.'
    var sqlQuery2 = "SELECT [EntryId], [Name] FROM [dbo].[Entry]";
    var selectProps2 = new List<string> { "EntryId", "Name" };
    var listExp2 = QueryTable(context, type, sqlQuery2, selectProps2).Cast<object>().ToList();
    // generated Sql: SELECT 1 FROM ( SELECT [EntryId], [Name] FROM [dbo].[Entry] ) AS [e]

    // but works if all columns are selected
    var sqlQueryAll = "SELECT [EntryId], [Name], [Description] FROM [dbo].[Entry]";
    var selectPropsAll = new List<string> { "EntryId", "Name", "Description" };
    var listExpAll = QueryTable(context, type, sqlQueryAll, selectPropsAll).Cast<object>().ToList();
}

Helper methods:

protected IEnumerable QueryTable(DbContext context, System.Type entityType, string sqlQuery, List<string> selectProps)
{
    var parameter = Expression.Parameter(typeof(DbContext));
    var expression = Expression.Call(parameter, "Set", new System.Type[] { entityType });

    expression = Expression.Call(typeof(RelationalQueryableExtensions), "FromSqlRaw", new System.Type[] { entityType }, expression,
                                 Expression.Constant(sqlQuery), Expression.Constant(Array.Empty<object>()));

    expression = Select(entityType, expression, selectProps);

    var expressionResult = Expression.Lambda<Func<DbContext, IEnumerable>>(expression, parameter);

    var compiled = EF.CompileQuery(expressionResult);
    var result = compiled(context);
    return result;
}

protected static MethodCallExpression Select(System.Type entityType, Expression source, List<string> selectProps)
{
    Dictionary<string, PropertyInfo> sourceProperties = selectProps.ToDictionary(name => name, name => entityType.GetProperty(name)!);
    var dynamicType = entityType;

    var expression = (MethodCallExpression)source;
    ParameterExpression parameter = Expression.Parameter(entityType);

    IEnumerable<MemberBinding> bindings = dynamicType.GetFields().Select(p =>
        Expression.Bind(p, Expression.Property(parameter, sourceProperties[p.Name]))).OfType<MemberBinding>();

    var constrType = dynamicType.GetConstructor(new System.Type[] { entityType });
    if (constrType != null)
    {
        var constrTypeExp = Expression.New(constrType);
        Expression selector = Expression.Lambda(Expression.MemberInit(constrTypeExp, bindings), parameter);

        var typeArgs = new System.Type[] { entityType, dynamicType };
        expression = Expression.Call(typeof(Queryable), "Select", typeArgs, expression, selector);
    }
    return expression;
}

One more remark, following code (when expression not used) works fine:

var listRaw = context.Set<Entry>().FromSqlRaw(sqlQuery2).Select(a => new Entry { EntryId = a.EntryId, Name = a.Name }).ToList();

UPDATE
Have found a way to get dynamic List without Cast to entity but that is not the solution to the issue of asked Question.
v1 - select only one Property
v2 - Select more then one
Still is somebody would have that usecase code sample is in post below.

PS
If method QueryTable does not have to be dynamic then Select Expressions can be build on top of IQueryable like here: LINQ : Dynamic select Sample:

var set = context.Set<Entry>();
var selectExp = Helpers.DynamicSelectGenerator<Entry>("EntryId, Name");

// works but loads all columns into memory and for efficiency not what is needed
var result = set.AsQueryable().Select(selectExp).ToList();

// throws the same error
var resultRaw = set.FromSqlRaw(sqlQuery2).Select(selectExp).ToList();


Mocking data with nock in playwright test

I'm writing my first Playwright Screenshot-test for a node application. The application makes serverside api requests and I want to mock the api responses so that my test becomes stable, predictable and can be run offline.

I will use nock to setup mocked data, because I've used nock in my old existing test suite (built on mocha + supertest) with great success.

But in my new Playwright-test I can't get nock to apply to my node app, probably because the node app is started as a separate process.

An old successful test file that uses supertest

const supertest = require("supertest");
const app = setupMyEntireNodeExpressApp();
nock("https://my-api.com").get("/").reply(200, { fakeData:true };
supertest(app).get("/").expect(200).end((err, response) => { doSomething(); }) //let supertest start the node app and make a request

The new playwright-test (myTest.spec.js) where the nock does not apply

const { test, expect } = require("@playwright/test");
const http = require("http");
const app = setupMyEntireNodeExpressApp();
test("My test", async ({ page, context }) => {
  nock("https://my-api.com").get("/").reply(200, { fakeData:true };
  http.createServer(app).listen(); //start node app
  await page.goto("/"); //make a request via playwright
  await expect(page).toHaveScreenshot("myTest.png", { fullPage: true }); //take screenshot via playwright
}

When I run the playwright test, the nock is not being applied to my node app. The app calls https://my-api.com and receives a response from the actual api rather than my mock data.

My GUESS is that the problem is that nock is running within the myTest.spec.js process but createServer starts my app as a separate process.

PS: in my playwright.config.js I've set webServer.reuseExistingServer:false since I'm starting my node app from the test file.

I tried removing http.createServer(app).listen(); and instead using webServer.reuseExistingServer:true and webServer.command: "node app.js". This is a way to let Playwright start the server via the command. But that caused the same problem. In that case I guess the problem is that myTest.spec.js is a separate process while node app.js starts a new process that doesn't have access to the nocks.

With my old successful test I guess the nock works because I can pass my node app object into supertest(app).request so the app is not started as a separate process, but is running within the same process as the test code where the nock is also running.

I wish there was a way to pass my app object to playwright in a similar way, but after reading their docs it doesn't seem like that's an option.

Is there an easy way to solve this?

Perhaps an alternative way of starting my node app using variants of createServer



2023-05-28

How can the cookie value not be the same in the dynamic route?

I implemented a program with next js , i want to use cookies on dynamic pages , the problem is that the cookie value is inherited in other pages , this happens while each page should have its own cookie.

I want to have a button to set cookie and a Link for navigation between dynamic blog routes , when i set the cookie for example in this path /blog/2 and click the Link to go to next blog or previous blog , the cookie is inherited in other dynamic blog routes.

  • In this example , the js-cookie module is used.

Example :

// /blog/[blogId]

import Cookies from 'js-cookie';
import Link from 'next/link';
import { useRouter } from 'next/router';
import dynamic from 'next/dynamic';

function SingleBlog() {
    const router = useRouter();
    const { blogId } = router.query;

    return (
        <>
            <Link href={`/blog/${Number(blogId) + 1}`}> next blog </Link>
            <button onClick={() => Cookies.set('name', `blog${blogId}`, { path: `/blog/${blogId}` })}> set </button>
            {Cookies.get('name') && <p>cookie : {Cookies.get('name')}</p>}
        </>
    )
}

export default dynamic(() => Promise.resolve(SingleBlog), { ssr: false });

  • If the page is refreshed, we see the cookie value and if the navigation between the blog pages is inside the program, the cookie value that is displayed is a fixed value in any case.

What is the solution ?



Using spacebar to check a Check Box, perform a DCount(), with focus remaining on the check box?

I have a form with a datasheet subform, where one of the controls is a Check Box (Chk1).

I want it to behave such that: If the check box is checked using mouse click, a DCount(...) on the same Check Box field is performed in the VBA straight away. I have this part working, by navigating away from the record in the Check Box AfterUpdate Sub:

Public fromSpace As Boolean

Private Sub Chk1_AfterUpdate()
    If Not fromSpace Then 'mouse click, so it's necessary to fire Form_AfterUpdate by navigating away
        Form_Main.cboSelector.SetFocus
    Else 'Spacebar used with SendKeys so navigating away is not necessary
        fromSpace = False 'reset for next time
    End If
End Sub

Then the AfterUpdate of the datasheet subform has the DCount(...)

Private Sub Form_AfterUpdate()
    If DCount(...) = x Then 'This DCount looks at the yes/no (Check Box) field in question
        'Do some stuff
    End If
End Sub

However, I also want it to behave such that: If the check box is checked using the spacebar key, I would like the same DCount(...) to happen, BUT while keeping focus on the Check Box in the subform (this is so the user can continue to navigate using keyboard).

I actually have it working, but this is using SendKeys ("{F9}")

Private Sub chk1_KeyUp(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeySpace Then
        fromSpace = True
        SendKeys ("{F9}") 'This WORKS (DCount(...) is performed, and focus remains on the Check Box). However, I understand using SendKeys is bad practice, so looking for a different solution

        'DoCmd.RunCommand (acCmdSaveRecord) (I have also tried this, which doesn't work)
        'DoCmd.RunCommand (acCmdSave) (This doesn't work either)
        
        'also tried doing the DCount(...) here, which doesn't fire until navigating away from the record
        'EDIT: Sorry, I think it does fire, but it doesn't use the new checkbox value in the DCount
    End If
End Sub

I also found this: https://www.reddit.com/r/vba/comments/tysrn7/click_a_button_on_the_ribbon/ (which programmatically does a Ribbon button click), which I tested, and it works, BUT is very slow. There is a 0.5 - 1 second delay every time spacebar is used to check or un-check the Check Box.

Surely there's a way to do this?

Thanks for reading.

EDIT: For anyone who is interested, I have elaborated on the code a bit, to show how the SendKeys method is working properly.



Build a dictionary from an object's explicitly declared fields

My table definition:

class AppProperties(base):
    __tablename__ = "app_properties"
    key = Column(String, primary_key=True, unique=True)
    value = Column(String)

Code for updating an app property:

session = Session()
query = session.query(AppProperties).filter(AppProperties.key == "memory")
new_setting = AppProperties(key="memory", value="1 GB")
query.update(new_setting)

The line query.update(new_setting) fails because the update method requires an iterable. If I use query.update(vars(new_setting)), it includes some extra values, which are not there in the underlying table and hence fails.

How can I build this dictionary: {"key": "memory", "value": "1 GB"} using the object new_setting, so that I can call the update method using this dictionary?

For example:

query.update({"key": "memory", "value": "1 GB"})

Because I already have everything in new_setting, I just need to convert it into a dictionary with only those keys which are explicitly declared in the class definition of AppProperties, without inheriting the fields from the base class or any other scope.



beforeLoad suitescript netsuite

i create an script beforeLoad if status Pending Fulfillment or approval

function beforeLoad(context) {
    

    var currRec = context.newRecord;
        var status = currRec.getValue('status')
        var mem = currRec.getValue('memo')
        var idSo = currRec.getValue('id')
        // log.debug('status', status)
        if (status === 'Pending Fulfillment') {
            record.submitFields({
                type: record.Type.SALES_ORDER,
                id: idSo,
                values: {
                    trandate: null
                },
                
            });
        } else if(status === 'Pending Approval'){
            record.submitFields({
                type: record.Type.SALES_ORDER,
                id: idSo,
                values: {
                    trandate: null
                },
                
            });
        }
    
    }

but when view an sales order that trandate not response. only when once refresh, the script worked



Learning Electron, trying to send data to renderer from main but appearing as undefined in renderer. Any help much appreciated

Am working with electron and encountering and issue that I cannot for the life of me fix despite it being so simple, where my received data is showing as undefined in renderer, yet shows correctly when console.log(the data) in main.

All I am trying to do is have main read a .JSON file and send the contents of it to the renderer to be stored and used.

Here is renderer code:

let table_data

ipcRenderer.send('request_data');

ipcRenderer.on('activity_data', (event, activityData) => {
  console.log('Data received');
  console.log(activityData);
//This returns undefined
});

ipcRenderer.on('activity_data_error', (event, error) => {
  console.error('Error fetching activity data:', error);
});

Here is main code:


// Respond to ipc Renderer request activity_data
ipcMain.on('request_data', (event, data) => {
    try {
      const rawData = fs.readFileSync('renderer/js/activity_data.json', 'utf8');
      const activityData = JSON.parse(rawData);
      console.log('activity_data', activityData);
      //This returns correct JSON data
      event.reply('activity_data', activityData);
    } catch (error) {
      console.error('Error reading or parsing JSON file:', error);
      event.reply('activity_data_error', error);
    }
  });


flutter floor floor_generator There are no entities added to the database annotation

I have created the floor entities and DAOs but when i run

flutter packages pub run build_runner build --delete-conflicting-outputs  

i got the following error

There are no entities added to the database annotation. package:storeapp/database/myAppDatabase.dart:74:16 ╷ 74 │ abstract class MyAppDatabase extends FloorDatabase {} │

but i added the entities as following

@Database(version: 1, entities: [
  Account,
  AccountingClass,
  LocalizedProperty,
  PointOfSale,
  StoreCurrencyMapping,
  User,
  InventoryTransaction,
  JournalVoucher,
  JournalVoucherEntry,
  JournalVoucherEntryDetail,
  BaseObject,
  StoreCustomer,
  StoreEmployee,
  StoreVendor,
  Store,
  Warehouse,
  Category,
  Product,
  ProductCategory,
  StoreProductMapping,
  Order
])


2023-05-27

Call a API synchronously inside For Each loop in android Kotlin Coroutines with Flow getting Error

Call a API synchronously inside For-each loop in android Kotlin Coroutines using Flow.

Also i need to wait all the API calls need to complete without blocking the Main Thread.

fun getLatesData(): Flow<Model> = flow {
        emit(getFirstList())
    }.flatMapLatest { data ->
        flow {
            val responseList = mutableListOf<String>()

            data.items?.forEach { datalist ->

                val response = getCreatedDate(datalist.Id)


                response.collect{count->
                    responseList.add(count.check)
                }
                val countData = Model(
                    datalist = data,
                    responseListCount = responseList
                )
            }
            emit(countData)
            
        }
    }
  
     private fun getCreatedDate(Id: String?)= flow {
            try {
                val response =  repoApi.getCount(Id)
                emit(response)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }.flowOn(Dispatchers.IO)

 @Headers(
        "Content-Type: application/json"
    )
    @GET("getCount/{Id}")
    suspend fun getCount(@Path("Id")Id: String?): response

ERROR-kotlinx.coroutines.flow.internal.AbortFlowException: Flow was aborted, no more elements needed

For the first iteration Data is emitting properly, but second time onwards getting above mentioned error.

Run a API call without blocking the UI thread inside for loop with Flow. Thank in advance.



Hide button while model is running in Streamlit

Hide button while model is running in Streamlit.

Hi,

I am developing an application, which infer an stable diffusion model when RUN button is pressed. How can i disable/hide this RUN button while model is running, and enable/show it again when done.

Thanks.



How do I use path the to my VS Code extension's directory in a contributed setting's default value?

I am developing a VS Code extension for Vale style linting. It includes a styles sub-directory with files for individual style rules. Inside the extension, I'm overriding a config option from another extension in its package.json file:

"contributes": {
    "configurationDefaults": {
        "vale.valeCLI.config": ".vale.ini"
    }
 }

The .vale.ini file is included in the root directory of the extension itself. Is there a variable that points to the root directory of the current extension? Or a way derive it from an extension ID? The above code does not work for me...



How to run a function in a singleton file only when electron main process is ready

I am using electron + vue, in my vue files, there is a file called globals.ts which is a file that exports global variables for all my vue files to use, it is a singleton file, I am trying to get it to communicate with electrons main process to fetch the user's machine IP address, however, there are errors occuring because apparently the main process is not finished loading before globals.ts function runs, meaning the ipcRenderer function is invoked before the main has the API available. How do i get it to wait for the main process to finish loading first so i can safely invoke a function and get a result?

//electron/main/main.ts
async function createWindow() {//...code to create window here}
    
ipcMain.handle("getMachineIPv4", (e, arg) => {
  console.log("getting ipv4");
  const interfaces = os.networkInterfaces();
  for (const interfaceName in interfaces) {
    const interfaceInfo = interfaces[interfaceName];
    for (const info of interfaceInfo) {
      if (info.family === "IPv4" && !info.internal) {
        return info.address;
      }
    }
  }
});

.

//electron/preload/preload.ts
    contextBridge.exposeInMainWorld("ipcRenderer", {
  send: (channel: string, data: string) => {
    // whitelist channels
    let validChannels = ["OpenFolder"];
    if (validChannels.includes(channel)) {
      ipcRenderer.send(channel, data);
    }
  },
  receive: (channel, func) => {
    let validChannels = ["fromMain"];
    if (validChannels.includes(channel)) {
      // Deliberately strip event as it includes `sender`
      ipcRenderer.on(channel, (event, ...args) => func(...args));
    }
  },
  invoke: (channel, arg) => {
    //invoke is an async function with a promise
    console.log(channel + " invoked");
    let validChannels = ["asyncFunc", "getMachineIPv4"];
    if (validChannels.includes(channel)) {
      // Deliberately strip event as it includes `sender`
      return ipcRenderer.invoke(channel, arg);
    }
  },
});

.

//inside src folder /assets/globals.ts

 export const address: Promise<string> = (async () => {
  try {
    const hostname: string = await window.ipcRenderer.invoke("getMachineIPv4", "please work");
    const firstThreeNumbers = hostname.split(".")[0];
    const portNumber = "3000";
    const subnet = "10";
    if (firstThreeNumbers === "123") {
      return `123.123.1111.${subnet}:${portNumber}`;
    } else if (firstThreeNumbers === "101") {
      return `123.123.111.${subnet}:${portNumber}`;
    } else if (hostname == "localhost") {
      // Default, usually localhost
      return `123.123.111.${subnet}:${portNumber}`;
    } else {
      console.error("ip address not found");
      return "error";
    }
  } catch (error) {
    console.error("Failed to get address:", error);
    return "error";
  }
})();


Calculating Fraction in power bi

I have a table with multiple columns which comes from different data sources. in which 2 columns are Actual Number and Expected Number(both measures). I have to create a new column in the table which just shows Actual Number/Expected Number.

Few rows have blanks for both Actual and Expected, for which i have to show "N/A". I was able to acheive the first part where we just show actual/expected, But challenge is when changing the logic to show N/A for blank values of actual and expected columns.

what i tried:

Created a measure,This works perfectly for non-blanks

IF([Actual] >0,[Actual]&"/"&[Expected])

I changed the measure to this to show N/A for blanks:

IF(ISBLANK([Actual]) ||ISBLANK([Expected]),"N/A",IF([Actual] >0,[Actual]&"/"&[Expected]))

when i try the above, the no of rows in the table drastically increases creating duplicates and i get many records with "N/A", where i only have 1 row which has blank actual/expected. Im unsure what is causing the issue and want to know what is the best way to approach this. Thanks in advance



Cannot create a Cloud Build trigger with Cloud Build repositories 2nd gen - permissions error

I have been following the instructions at https://cloud.google.com/build/docs/automating-builds/github/connect-repo-github?generation=2nd-gen to create a Cloud Build Trigger from a GitHub repo connected to Cloud Build repositories 2nd gen.

Whether I use gcloud as in the instructions, use the Google Cloud Console UI or even try programmatically via Terraform, I get the same error.

I cannot work out if I need to set permissions somewhere or if it is just a misleading error and something is wrong with the GitHub permissions. My user account has the roles/cloudbuild.connectionAdmin role. I cannot see why the mentioned permission would not be there.

connection of repository projects/my-project/locations/us-central1/connections/my-app-github-connection/repositories/MyApp cannot be fetched: generic::permission_denied: Permission 'cloudbuild.connections.get' denied on 'projects/my-project-number/locations/us-central1/connections/my-app-github-connection'

Here is the roles the Cloud Build service account has granted:

enter image description here

Any ideas?



2023-05-26

How can I make environment variables available during Docker build for a Rails 7 app with MRSK?

I'm trying to build and deploy a rails 7 app with MRSK. The docker build process needs different environment variables for bundling gems, installing yarn packages, etc.

My deploy.yml contains following information:

env:
  secret:
    - GITLAB_TOKEN

builder:
  secrets:
    - GITLAB_TOKEN
  args:
    RUBY_VERSION: 3.2.2
  multiarch: false

The .env-file:

GITLAB_TOKEN='test'

In my Dockerfile I've tried following:

RUN echo  "$GITLAB_TOKEN"

RUN --mount=type=secret,id=GITLAB_TOKEN
RUN cat /run/secrets/GITLAB_TOKEN

But the environment is in both cases empty.


I've found a workaround by using args instead of environments in the deploy.yml:

builder:
  args:
    GITLAB_TOKEN: "<%= ENV['GITLAB_TOKEN'] %>"

But args are not masked secret and using erb-text in a yml-file seems very ugly. This also may not work for non rails-applications.



why doesn't navigator.setAppBadge() in Safari on iOS work without a number argument?

According to the spec:

(https://www.w3.org/TR/badging/#example-showing-ready-status-on-the-app-icon)

navigator.setAppBadge() with no arg should alert the user with a badge containing no number, but it does not do so in Safari on iOS. You can try it yourself directly from the web inspector for the service worker (BTW, why can't I get a web inspector for the web app when it's installed on the home page?). EDIT: I can now get the developer tools to work with both the service worker and the web page; perhaps a Safari update? The windows will sometimes just disappear, however.

Why is this not to spec? Is this by Apple's design, or a bug?

If I put in a number:

navigator.setAppBadge(23)

...it works fine. (BTW, numbers up to 999,999 seem to display on my iPhone 13 mini without being clipped.) This is all in the context of trying to use the Web Push API to display notifications and badges for my web app, with the sole purpose of telling the user it's xer turn in the game. So I don't particularly want to put a number up, but it seems like I may end up having to use a badge with a '1' in it. Please let me know if anyone can get a badge with no number in Safari on iOS.



How can I implement basic authentication between Next.JS and DRF using JWT?

I am trying to recode the website for my student club and would need some assistance regarding authentication. I do have a Django Backend setup with all the necessary data (e.g. Member infos, etc.) and would like to display them on the frontend (name + position) and on the Backend (email, phone number, etc.). Now to achieve that I would need basic authentication where I can give out login credentials to the members and they can login (no sign up from the website). Now I am wondering how to do that; coming from Django I would generate a credential pair and the authentication would go via JWT, but I cant find a suitable example (everything is very old). Right now my setup looks like this:

  • Django Backend with JWT
  • Next.JS frontend (typescript, tailwind css) with seperate login page

I was looking at next-auth which seems promising but I am afraid that login via Socials is not my usecase. Can anyone provide more information how to setup Django with Next.JS with authentication? Cheers

I already tried using Next-Auth with some examples provided on the internet but none of them worked/ were deprecated.



Splitting Text to Two Columns Using a Separator in R

I am trying to split the column using a separator "|" but unfortunately the suggestions in Stack Overflow which recommended using separator() is not working in my situation.

Can someone help me out here.

The data frame, I am using is given below:

structure(list(UniqueID = c("12M-MA | X1", "12M-MA | X2", 
"12M-MA | X3", "12M-MA | X4", "12M-MA | X5"
), Cost = c(0.2, 0.3, 0.2, 0.2, 412.86), Actuals = c(0, 
0, 0, 0, 32), Forecast = c(0, 0, 0, 0, 21), Value_Actuals = c(0, 
0, 0, 0, 28341), Value_Forecast = c(0, 0, 0, 0, 652431
), `Forecast Accuracy` = c(0, 0, 0, 0, 8.51), `Max (Act vs Cons)` = c(0, 
0, 0, 0, 652431)), row.names = c(NA, -5L), class = c("tbl_df", 
"tbl", "data.frame"))

The code which I have used and the one which is working is this:

library(readxl)
library(dplyr)
library(writexl)
library(stringr)
Df<- read_excel("C:/X/X/X/X/YXZ-2023.xlsx"skip = 1)

Df <- Df %>% 
  separate(UniqueID,c("ABC","XYZ"),sep = "|")

The expectation is to get keep the column as is and get two more columns one with the name of "ABC" and the other with "XYZ".

12-MA should go into the column "ABC" and the other value such as X1,X2,X3,X4,X5 should go into column "XYZ".

Can someone help me out and let me now what is it that I am doing wrong. This was the suggestion in stack over flow and everywhere but isn't working for me.



Python - Count all combinations of K numbers from 1-N whose sum is equal to N

How do i count all combinations of k numbers from 1-n whose sum is equal to n? Like for n = 10, k = 3, we have (1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5)

I've tried using itertools.combination but it grows really fast for big numbers



2023-05-25

Elasticbeanstalk application deployed but not showing in AWS console

I manage to run eb deploy successfully from the command prompt and get the following:

2023-05-21 21:27:31    INFO    Environment update completed successfully.

And when I run eb list I get as result the name of my environment * simply-dev.

I can run eb status --verbose and see everything looks healthy/green.

Environment details for: simply-dev
  Application name: simply
  Region: us-east-2
  Deployed Version: app-230523_221320835290
  Environment ID: e-rdyf63m2dr
  Platform: arn:aws:elasticbeanstalk:us-east-2::platform/Python 3.8 running on 64bit Amazon Linux 2/3.5.2
  Tier: WebServer-Standard-1.0
  CNAME: exit.us-east-2.elasticbeanstalk.com
  Updated: 2023-05-23 21:17:44.717000+00:00
  Status: Ready
  Health: Green
  Running instances: 1
           i-034a7471b6b368e1b: healthy

However, when I run eb console, the console opened in the internet browser keeps loading endlessly and I cannot see any application or environment. I also checked I am in the same region and both show the same Account ID.

AWS EB Error

Any idea of why I cannot see the environment in the AWS console?



How can i, in flutter scrap data from a random website on the internet and interact with it

How can i, in flutter (or other language) scrap data from a random website on the internet (like Youtube) and interact with it (Clicking on a video) and getting the content. For exemple, login on a website by inserting an email and a password and clicking on submit(All of this in the flutter app) and then getting the data of the profil and using it inside my flutter (or other) app



Find all numbers in a set of maxima that sum to a given number

I am struggling to think of an algorithm which matches my needs. I have a list of integers in a set, each integer represents a maximum value, the list can contain >= 1 entries. I would like to find all the combinations of integers within these maxima that sum to a given value.

For example for a list of 4 maxima = [2, 3, 0, 5] and given value = 5, solutions are:

[2, 3, 0, 0]
[2, 2, 0, 1]
[2, 1, 0, 2]
[2, 0, 0, 3]
[1, 3, 0, 1]
[1, 2, 0, 2]
[1, 1, 0, 3]
[1, 0, 0, 4]
[0, 3, 0, 2]
[0, 2, 0, 3]
[0, 1, 0, 4]
[0, 0, 0, 5]

I have found some great algorithms related to this but they only address the combinations of the integers in the list which sum to the given value (i.e. in above example, would generate [2, 3] and [5] but not all the other combinations that I am interested in.

I have built a solution (in Swift) that solves this with blunt force (see below), but I am looking for something far more efficient.

import UIKit

let avail = [2, 3, 0, 5]
let sol = [0, 0, 0, 0]
var solList = [[Int]]()
let target = 5
let inc = 1
var calls = 0

generate(soln: sol, idx: 0)

print("calls : \(calls) solutions \(solList.count)")
for entry in solList {
    print(entry)
}

func generate(soln: [Int], idx: Int) -> Void {
    calls += 1
    
    let solnTotal = soln.reduce(0, +)
    
    if solnTotal > target {return}
    
    if solnTotal == target {
        solList.append(soln)
        //print(soln)
        return
    }
    
    if idx == soln.count {return}
    
    var tmp = soln[idx]
    while tmp <= avail[idx] {
        var solNext = soln
        solNext[idx] = tmp
        let solnTotal = solNext.reduce(0, +)
        if solnTotal > target {break}
        generate(soln: solNext, idx: idx + 1)
        tmp += inc
    }
    
}


Can I create separate a mouse cursor/keyboard for my Python bot to exclusively use? [closed]

I am using Python3, pynput and pyautogui to perform few mundane operations in an application on my second monitor by using mouse and keyboard.

However, I would like my Python script to control a separate mouse/keyboard operating on my second monitor so it can perform its operations without interfering with my activity on the first monitor.

Is this even possible to do? If so, are there any packages/libraries that do this?



.NET MAUI Blazor Desktop Application | How do I retrieve arguments passed into application

I have created a brand new .NET MAUI Blazor application using the standard template. There is a Program.cs file that has been created. As the title suggests, how do I retrieve arguments passed into application using C#?



Visual Studio 2022 Typescript Intellisense

I have a medium size React app hosted inside an ASP.NET Core WebApi project. I have about 100 ts/tsx, and a handful of js files created using the OOB React template. For 6 months, the development experience was great. Intellisense, reference navigation, and error resolution suggestion all near instant. Last week, I patched VS2022 Pro 2022 (64-bit) to V17.5.5. Initellicode 2.2, TypeScript Tools, 17.0.20105.2003. Now VS2022 is almost unusable. Apparently, a language service spins up a separate Node instance to handle JS/TS work. That Node process seems to be pegging the CPU, eating ~0.7GB of memory. Not while debugging but simply having the solution open. I created a new sandbox project from the same template. Added some ts files, nothing exotic, just simple type definitions and the npm packages I need. Same thing. It takes 13-15 seconds to hover over a type for Intellisense to recognize it. Compilation errors take at least that long. I get a progress bar when 'Go to Definition'. All of this was instant on this same machine for months. Oddly, running the solution is the same speed as always. Only the text editing experience. Things I've tried:

  • Deleted node_modules + package-lock.json, multiple times, reboot
  • Deleted hidden .vs folder, reboot
  • Fresh sandbox with the same template, all JS -works fine. Add TS -issue returns
  • Uninstalled and reinstalled VS2022, reboot
  • Tweaked VS options found online, disabled linting, etc
  • Deleted local repo, rebuilt from remote
  • Updated typescript (NPM), Node, etc

One thing I notice, in tsconfig, if I define an empty include: [], I get the performance returned, but of course, it can't find the types in node_modules so that's not going to work. Any suggestions?

{
      "compilerOptions": {
        "target": "es5",
        "lib": [
          "dom",
          "dom.iterable",
          "esnext"
        ],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "strictPropertyInitialization": false,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react-jsx"
      },
      "include": [
        "src"  // if I leave this empty, all the performance returns, but no package resoltion
      ],
      "exclude": [
        "node_modules"
      ]
    }

package.json

    {
      "name": "omitted",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "@babel/eslint-parser": "^7.21.8",
        "@reduxjs/toolkit": "^1.9.2",
        "@types/lodash": "^4.14.191",
        "@types/react": "^18.0.27",
        "agentkeepalive": "^4.2.0",
        "antd": "^5.4.6",
        "axios": "^0.26.0",
        "dayjs": "^1.10.7",
        "http-proxy-middleware": "^0.19.1",
        "lodash": "^4.17.21",
        "query-string": "^7.1.1",
        "react": "^18.2.0",
        "react-device-detect": "^2.1.2",
        "react-dom": "^18.2.0",
        "react-input-mask": "^2.0.4",
        "react-quill": "^2.0.0",
        "react-redux": "^8.0.5",
        "react-router-dom": "^6.8.0",
        "react-scripts": "^5.0.1",
        "recharts": "^2.1.14",
        "redux": "^4.2.1",
        "rimraf": "^2.6.2",
        "swagger-ui-react": "^4.15.5",
        "web-vitals": "^0.2.4",
        "workbox-background-sync": "^5.1.3",
        "workbox-broadcast-update": "^5.1.3",
        "workbox-cacheable-response": "^5.1.3",
        "workbox-core": "^5.1.3",
        "workbox-expiration": "^5.1.3",
        "workbox-google-analytics": "^5.1.3",
        "workbox-navigation-preload": "^5.1.3",
        "workbox-precaching": "^5.1.3",
        "workbox-range-requests": "^5.1.3",
        "workbox-routing": "^5.1.3",
        "workbox-strategies": "^5.1.3",
        "workbox-streams": "^5.1.3"
      },
      "devDependencies": {
        "@types/node": "^20.1.7",
        "@types/react-redux": "^7.1.25",
        "@types/react-router-dom": "^5.3.3",
        "ajv": "^6.9.1",
        "cross-env": "^7.0.3",
        "eslint": "^7.25.0",
        "eslint-config-react-app": "^6.0.0",
        "eslint-plugin-flowtype": "^5.7.2",
        "eslint-plugin-import": "^2.22.1",
        "eslint-plugin-jsx-a11y": "^6.4.1",
        "eslint-plugin-react": "^7.23.2",
        "nan": "^2.14.2",
        "typescript": "^5.0.4"
      },
      "scripts": {
        "prestart": "node aspnetcore-https && node aspnetcore-react",
        "start": "rimraf ./build && react-scripts start",
        "build": "react-scripts build",
        "test": "cross-env CI=true react-scripts test --env=jsdom",
        "eject": "react-scripts eject",
        "lint": "eslint ./src/"
      },
      "eslintConfig": {
        "extends": [
          "react-app"
        ]
      },
      "browserslist": {
        "production": [
          ">0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }
    }


2023-05-24

"CMAKE" doesn't create "Debug" or "Release" output folders

My .vcxproj file had this segment, which includes x64/Debug and x64/Release for Configuration and Platform. I am working on Windows machine

  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|x64">
      <Configuration>Debug</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|x64">
      <Configuration>Release</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
..........
      </ItemGroup>

I now tried to create CMakeLists.txt

cmake_minimum_required(VERSION 3.5)

project(LogMsg)

# Set the project source files
set(SOURCES
    LogMsgMain.rc
    LogMsg.h
)

# Add executable target
add_executable(LogMsg ${SOURCES})

# Set the configuration-specific outputs
set_target_properties(LogMsg PROPERTIES
    RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_CURRENT_SOURCE_DIR}/Debug"
    RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_CURRENT_SOURCE_DIR}/Release"
)

# Add include directories
target_include_directories(LogMsg PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})

# Specify custom build commands
add_custom_command(TARGET LogMsg POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/LogMsg.rc" "$<TARGET_FILE_DIR:LogMsg>"
    COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/LogMsg.h" "$<TARGET_FILE_DIR:LogMsg>"
    COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_BINARY_DIR}/MSG00001.bin" "$<TARGET_FILE_DIR:LogMsg>"
)

After that I run cmake command: Tried two approaches:

cmake -S . -B . -G "Visual Studio 17 2022" 
cmake -S . -B . -G "Visual Studio 17 2022" -DCMAKE_BUILD_TYPE=Debug

But in both cases I am not getting x64/Debug and Release folders with my .lib file.

Can someone take a look what I am missing in configuration of the CMakeLists?

UPDATE My new CMakeLists.txt file is the following:

cmake_minimum_required(VERSION 3.5)

project(FALogMsg)

# Set the project source files
set(SOURCES
    FALogMsg.cpp
    FALogMsgMain.rc
    FALogMsg.h
    resource.h
    stdafx.h
)

# Add executable target
add_library(FALogMsg ${SOURCES})

# Set the configuration-specific outputs
set_target_properties(FALogMsg PROPERTIES
    RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_CURRENT_SOURCE_DIR}/x64/Debug"
    RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_CURRENT_SOURCE_DIR}/x64/Release"
)

# Add include directories
target_include_directories(FALogMsg PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})

# Specify custom build commands
add_custom_command(TARGET FALogMsg POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/FALogMsg.rc" "$<TARGET_FILE_DIR:FALogMsg>"
    COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/FALogMsg.h" "$<TARGET_FILE_DIR:FALogMsg>"
    COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_BINARY_DIR}/MSG00001.bin" "$<TARGET_FILE_DIR:FALogMsg>"
)

Error:

C:\Projects..\base\LogMsg>cmake --build build --config Release MSBuild version 17.6.3+07e294721 for .NET Framework

Building Custom Rule C:/Projects/../base/LogMsg/CMakeLists.txt
LogMsg.cpp LogMsg.vcxproj -> C:\Projects\AccurevMigration\Projects\workspace\OTM_PlaceHolder_Work_v2\base\LogMsg\build\Release\LogMsg.lib Error copying file (if different) from "C:/Projects/AccurevMigration/Projects/workspace/OTM_PlaceHolder_Work_v2/base/LogMsg/build/MSG00001.bin" to "C:/Projects/AccurevMigration/Projects/workspace/OTM_PlaceH
older_Work_v2/base/LogMsg/build/Release". C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: The command "setlocal [C:\Projects\AccurevMigration\Projects\workspace\OTM _PlaceHolder_Work_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: "C:\Program Files\CMake\bin\cmake.exe" -E copy_if_different C:/Projects/Ac curevMigration/Projects/workspace/OTM_PlaceHolder_Work_v2/base/LogMsg/LogMsg.rc C:/Projects/AccurevMigration/Projects/workspace/OTM_PlaceHolder_Work_v2/base/LogMsg/build/Release [C:\Projects\AccurevMigrat ion\Projects\workspace\OTM_PlaceHolder_Work_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: if %errorlevel% neq 0 goto :cmEnd [C:\Projects\AccurevMigration\Projects\w orkspace\OTM_PlaceHolder_Work_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: "C:\Program Files\CMake\bin\cmake.exe" -E copy_if_different C:/Projects/Ac curevMigration/Projects/workspace/OTM_PlaceHolder_Work_v2/base/LogMsg/LogMsg.h C:/Projects/AccurevMigration/Projects/workspace/OTM_PlaceHolder_Work_v2/base/LogMsg/build/Release [C:\Projects\AccurevMigrati on\Projects\workspace\OTM_PlaceHolder_Work_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: if %errorlevel% neq 0 goto :cmEnd [C:\Projects\AccurevMigration\Projects\w orkspace\OTM_PlaceHolder_Work_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: "C:\Program Files\CMake\bin\cmake.exe" -E copy_if_different C:/Projects/Ac curevMigration/Projects/workspace/OTM_PlaceHolder_Work_v2/base/LogMsg/build/MSG00001.bin C:/Projects/AccurevMigration/Projects/workspace/OTM_PlaceHolder_Work_v2/base/LogMsg/build/Release [C:\Projects\Accure vMigration\Projects\workspace\OTM_PlaceHolder_Work_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: if %errorlevel% neq 0 goto :cmEnd [C:\Projects\AccurevMigration\Projects\w orkspace\OTM_PlaceHolder_Work_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: :cmEnd [C:\Projects\AccurevMigration\Projects\workspace\OTM_PlaceHolder_Wo rk_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone [C:\Projects\Acc urevMigration\Projects\workspace\OTM_PlaceHolder_Work_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: :cmErrorLevel [C:\Projects\AccurevMigration\Projects\workspace\OTM_PlaceHo lder_Work_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: exit /b %1 [C:\Projects\AccurevMigration\Projects\workspace\OTM_PlaceHolde r_Work_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: :cmDone [C:\Projects\AccurevMigration\Projects\workspace\OTM_PlaceHolder_W ork_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: if %errorlevel% neq 0 goto :VCEnd [C:\Projects\AccurevMigration\Projects\w orkspace\OTM_PlaceHolder_Work_v2\base\LogMsg\build\LogMsg.vcxproj] C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(160,5): error MSB3073: :VCEnd" exited with code 1. [C:\Projects\AccurevMigration\Projects\workspa ce\OTM_PlaceHolder_Work_v2\base\LogMsg\build\LogMsg.vcxproj]



What steps should I follow to enable PayPal Advanced Credit Card Payment integration in Spring Boot app for non-PayPal account holders?

I am trying to integrate paypal advanced credit card payment, for customers who do not have a paypal account to be able to pay using their card. And I'm facing issues doing that.

I succesfuly integrated Paypal into my Spring Boot app, but only for customers with a paypal account (They are redirected and required to log into paypal before paying).

The issue here is I want get a response from Paypal and beign able to process it alongside the user's session information,

I followed tutorials leading to creating a PaymentSource instance and then setting into my orderRequest :

Card card = new Card();
        card.number(creditCard.getNumber())
            .expiry("YYYY-MM")
            .securityCode("CVV");
PaymentSource paymentSource = new PaymentSource().card(card);

But OrderRequest has no property as PaymetSource. I provide source code below, can you please help me fix this issue, or just provide me with a guide for the integration from scratch.

Thank you.


import java.net.URI;
import java.util.Arrays;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.nicanor.shakt.web.entities.CreatedOrder;
import com.paypal.api.payments.CreditCard;
import com.paypal.core.PayPalEnvironment;
import com.paypal.core.PayPalHttpClient;
import com.paypal.http.HttpResponse;
import com.paypal.orders.AmountWithBreakdown;
import com.paypal.orders.ApplicationContext;
import com.paypal.orders.Card;
import com.paypal.orders.LinkDescription;
import com.paypal.orders.Money;
import com.paypal.orders.Order;
import com.paypal.orders.OrderRequest;
import com.paypal.orders.OrdersCaptureRequest;
import com.paypal.orders.OrdersCreateRequest;
import com.paypal.orders.PaymentInstruction;
import com.paypal.orders.PaymentSource;
import com.paypal.orders.PurchaseUnitRequest;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.util.NoSuchElementException;

@Service
public class PayPalPaymentService implements PaymentService {

    private final String APPROVE_LINK_REL = "approve";

    private final PayPalHttpClient payPalHttpClient;

    public PayPalPaymentService(@Value("${paypal.clientId}") String clientId, @Value("${paypal.clientSecret}") String clientSecret) {
        payPalHttpClient = new PayPalHttpClient(new PayPalEnvironment.Sandbox(clientId, clientSecret));
    }

    @Override
    @SneakyThrows
    public CreatedOrder createOrder(Double totalAmount, URI returnUrl) {
        //STEP4 CREATE ORDER REQUEST
        final OrderRequest orderRequest = createOrderRequest(totalAmount, returnUrl);
        final OrdersCreateRequest ordersCreateRequest = new OrdersCreateRequest().requestBody(orderRequest);
        final HttpResponse<Order> orderHttpResponse = payPalHttpClient.execute(ordersCreateRequest);
        
        //STEP6 ON RECUPERE L'ORDRE, approve uri c'est l'url pour valider l'ordre sur paypal
        final Order order = orderHttpResponse.result();
        LinkDescription approveUri = extractApprovalLink(order);
        return new CreatedOrder(order.id(),URI.create(approveUri.href()));
    }

    @Override
    @SneakyThrows
    //public void captureOrder(String orderId) {
    public HttpResponse<Order> captureOrder(String orderId) {
        final OrdersCaptureRequest ordersCaptureRequest = new OrdersCaptureRequest(orderId);
        final HttpResponse<Order> httpResponse = payPalHttpClient.execute(ordersCaptureRequest);
        return httpResponse;
    }

    private OrderRequest createOrderRequest(Double totalAmount, URI returnUrl) {
        
        // Create a credit card object with the card details
        CreditCard creditCard = new CreditCard();
        creditCard.setNumber("card number");
        creditCard.setExpireMonth(1);
        creditCard.setExpireYear(2025);
        creditCard.setCvv2(123);
        creditCard.setFirstName("first name");
        creditCard.setLastName("last name");
        
        Card card = new Card();
        card.number(creditCard.getNumber())
            .expiry("YYYY-MM")
            .securityCode("CVV");
        PaymentSource paymentSource = new PaymentSource().card(card);
        
      
        
        //STEP5 TOUTES LES CONFIGS
        // Add the purchase unit to the order request object
        OrderRequest orderRequest = new OrderRequest();
        setCheckoutIntent(orderRequest);
        setPurchaseUnits(totalAmount, orderRequest, paymentSource);
        setApplicationContext(returnUrl, orderRequest);
        return orderRequest;
    }

    private OrderRequest setApplicationContext(URI returnUrl, OrderRequest orderRequest) {
        return orderRequest.applicationContext(new ApplicationContext().returnUrl(returnUrl.toString()));
    }

    private void setPurchaseUnits(Double totalAmount, OrderRequest orderRequest, PaymentSource paymentSource) {
        
        
        final PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest()
                .amountWithBreakdown(new AmountWithBreakdown().currencyCode("CAD").value(totalAmount.toString()));
        orderRequest.purchaseUnits(Arrays.asList(purchaseUnitRequest));
    }

    private void setCheckoutIntent(OrderRequest orderRequest) {
        orderRequest.checkoutPaymentIntent("CAPTURE");
    }

    private LinkDescription extractApprovalLink(Order order) {
        LinkDescription approveUri = order.links().stream()
                .filter(link -> APPROVE_LINK_REL.equals(link.rel()))
                .findFirst()
                .orElseThrow(NoSuchElementException::new);
        return approveUri;
    }
    
}