please help me review it . this is my project. i tried my best .thanks you Posted: 28 Jul 2021 08:18 AM PDT |
How to connect google-cloud-firestore to swift? Posted: 28 Jul 2021 08:17 AM PDT I was unable to connect Firestore-cloud to xcode using Firestore-CLI, but was unable to do so. So, Now, I am trying to connect Firestore to serverless - https://firebase.google.com/docs/firestore/extend-with-functions , which in console is - https://console.cloud.google.com . I have the following 3 functions - 1). the function in the given example is - "helloWorld" , the code is - exports.helloWorld = (req, res) => { let message = req.query.message || req.body.message || 'Hello World!'; res.status(200).send(message); }; -- It gets deployed as - https://myregion-testpro-92351.cloudfunctions.net/function-1 2). I have also tested another function "helloHttp", the code is - exports.helloHttp = (req, res) => { res.send(`Hello ${escapeHtml(req.query.name || req.body.name || 'World')}!`); }; -- It gets deployed as - https://myregion-testpro-92351.cloudfunctions.net/function-5 The above functions gets deployed successfully. 3). Though both the above get deployed successfully, the function "myFunctionName" does NOT get deployed successfully, the code is - exports.myFunctionName = (req, res) => { res.send(`Function is $myFunctionName(req.query.name || req.body.name || 'isNOTDeployed')}!`); }; does NOT get deployed - https://asia-south1-testpro-92351.cloudfunctions.net/myFunctionName Also, my swift Viewcontroller code is - import UIKit import Firebase class TestViewController: UIViewController { @IBAction func Test(_ sender: Any) { } } I have the following questions - i) Am I doing the right thing (as I told you I was unable to do so using CLI). ii) what should I put inside the button - "@IBAction func Test(_ sender: Any) { } }" in "TestViewController" above to make both functions, 1). "function-1", i.e. "helloWorld" and 2). "function-5", i.e. "helloHttp" print "HelloWorld" in xcode console. iii) What should be the code for the function "myFunctionName" to get deployed. |
How can I summarize splits and regex into less lines in Python? Posted: 28 Jul 2021 08:17 AM PDT if len(re.findall('\\bim\\b', message.lower())) > 0: new_list = message.lower() x = new_list.split("im ") elif len(re.findall("\\bi'm\\b", message.lower())) > 0: new_list = message.lower() x = new_list.split("i'm ") I found this code of mine from ages ago and I'm awful in Regex, I know that you can use the (a|b) filter probably though, it's obviously very inefficient and I'm sure it can be tidied up a lot. |
Cannot execute freshclam from .NET Lambda Posted: 28 Jul 2021 08:17 AM PDT I need to implement the AWS Lambda function using .net core 3.1 which will download ClamAV definitions and upload them to the S3 bucket on Amazon. I've created a .net core solution in Visual Studio and created a script file which downloads freshclam via apt-get install clamav-freshclam , copies it, and all its dependencies to the target folder, and packages all the code into the zip archive. As a result, I get a zip archive with structure: - bin (contains files: freshclam, freshclam.config)
- lib (contains all needed libraries to run freshclam)
- .net code dlls and other files
Then I use this archive as a source code to deploy Lambda on Amazon. The problem is, I need to run the freshclam file inside my function. I use the following code: File.Copy("./bin/freshclam", "/tmp/freshclam", true); File.Copy("./bin/freshclam.conf", "/tmp/freshclam.conf", true); var result = await ExecuteBashCommand("/tmp/freshclam", "--config-file=/tmp/freshclam.conf --datadir=/tmp/"); I copy "./bin/freshclam" and "./bin/freshclam.conf" files to the temp folder because files inside /var/task is read only (source) And ExecuteBashCommand method: private Task<int> ExecuteBashCommand(string fileName, string arguments) { _log.LogInformation($"Processing command {fileName} {arguments}"); var source = new TaskCompletionSource<int>(); var escapedArgs = arguments.Replace("\"", "\\\""); var process = new Process { StartInfo = new ProcessStartInfo { FileName = fileName, Arguments = escapedArgs, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }, EnableRaisingEvents = true, }; process.Exited += (sender, args) => { _log.LogInformation("Exited"); if (process.ExitCode == 0) { source.SetResult(0); } else { _log.LogError($"Command failed with exit code `{process.ExitCode}`"); source.SetException(new Exception($"Command failed with exit code `{process.ExitCode}`")); } process.Dispose(); }; process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { _log.LogInformation("OutputDataReceived: {@e}", e); }; process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { _log.LogError("ErrorDataReceived: {@e}", e); }; try { process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); // wait for the process to finish process.WaitForExit(); } catch (Exception e) { _log.LogError(e, $"Command failed"); source.SetException(e); } return source.Task; } As a result, I get an error (ErrorDataReceived event from code): "*** stack smashing detected ***: <unknown> terminated" And exit code is 134 And I cannot understand, why I get this error because freshclam file is not my code and it runs successfully from online Linux terminal, for example. Maybe anyone faced the same issue? Another thing is there is a Node.js function with the same purpose (source) and it works correctly. Looks like the reason is in the way how I run the freshclam file. And also I'm wondering why I cannot execute any bash command from this code as well (ls, help, etc.), the exit code is 139 |
Feign jackson cannot decode String with leading 0 Posted: 28 Jul 2021 08:17 AM PDT I have a feign client with configured JacksonDencoder which looks like that: protected Feign.Builder resilience4JFeignBuilder(ObjectMapper objectMapper, ClientProperties props, Class<?> clazz) { return Resilience4jFeign.builder(createDefaultDecorators(props)) .logger(new Slf4jLogger(clazz)) .logLevel(Logger.Level.FULL) .decoder(new JacksonDecoder(objectMapper)) and feign client: public interface SomeServiceFeignClient { @RequestLine(value = "GET somepath/{value}/convert") String translate(@Param("value") String value); } The problem is when endpoint GET somepath/{value}/convert returns String with '0' at the begining e.g "0254" then following exception is thrown: feign.FeignException: Invalid numeric value: Leading zeroes not allowed. I know that i can set objectMapper.enable(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS); property and exception is not thrown but still '0' is removed and "254" is produced. Is it possible to configure JacksonEncoder to handle String return types without removing '0' from the beginning ? |
I can find an element by ID but, I cannot find a partial id using css selectors or xpath using python & selenium Posted: 28 Jul 2021 08:17 AM PDT I have attached an example of my code below FIRST_INPUT = (By.XPATH, "//*[contains(@id, 'firstName')]") LAST_INPUT = (By.ID, 'lookLastName') firstName = self.browser.find_element(*self.FIRST_INPUT) firstName.send_keys(first) lastName = self.browser.find_element(*self.LAST_INPUT) lastName.send_keys(last) |
How to use both update and join in a single lambda expression Posted: 28 Jul 2021 08:17 AM PDT I want to convert my SQL query to lambda expression.Below is the SQL query.I tried but failing to get expected result UPDATE Sales SET SI.ACP= SD.ACP FROM Sales SI INNER JOIN SaleDesc SD ON SI.GroupID= SD.GroupID; |
How to make Telescope ignore files inside node_modules? Posted: 28 Jul 2021 08:17 AM PDT I'm new in the VIM / NEOVIM world so I probably am doing something else wrong, but from the docs it says that Telescope will ignore all the files registered in the .gitignore file, which is definitively there but it still searches in node_modules So this is what I do: - I
cd into my project folder - Hit
nvim - hit
<leader>ff - Telescope opens and I start typing, but searches are really slow because they are including
node_modules These are the plugins that I have for setting up telescope " Telescope Plug 'nvim:solua/popup.nvim' Plug 'nvim-lua/plenary.nvim' Plug 'nvim-telescope/telescope.nvim' And then my remaps right from the docs: " Find files using Telescope command-line sugar. nnoremap <leader>ff <cmd>Telescope find_files<cr> nnoremap <leader>fg <cmd>Telescope live_grep<cr> nnoremap <leader>fb <cmd>Telescope buffers<cr> nnoremap <leader>fh <cmd>Telescope help_tags<cr> All this is running in a WSL terminal with Ubuntu. What am I missing? |
Sinon capturing incorrect array arguments Posted: 28 Jul 2021 08:16 AM PDT I have a test set up like this: const test = require('ava'); const sinon = require('sinon'); const myServcie = require('../myservice'); const stub = sinon.stub(myServcie, 'myFunctionCall'); test.serial( 'will do a thing', async (assert) => { stub.onCall(0).returns({... an object ...}); stub.onCall(1).returns({... another object...}); stub.onCall(2).returns({... a final object...}); //... call module that uses myDependency here... //Verify the results console.log(stub.getCall(0).args); console.log(stub.getCall(1).args); console.log(stub.getCall(2).args); }, ); I have added a log statement right before myDependency is called in the module I'm testing to see exactly what is being sent. The first call shows this as being sent to myDependency : //Logged before stub is called [ 'Arg1', 'Art2', {obj: 'objVal', objArr: [ 'arrValue' ] } ] However, Sinon shows this as the arguments sent to myDependency on the first call: //Captured by using stub.GetCall(0).args [ 'Arg1', 'Arg2', { obj: 'objVal', objArr: [] } ] It always shows objArr as an empty array.. so when i try to verify the value that the array holds, the assertion always fails (because for some reason it is empty). Am I missing something, or doing something wrong? I am able to verify the other args, just not the array args. |
angular material sort not working on angular 10 Posted: 28 Jul 2021 08:16 AM PDT I've read multiple questions here in SO but I can't make it work. I call a service to retrieve data. Everything works fine -> Filter, paginator and the data rendered. But I don't know why sorting is not working This is a view from my table: And this is my code: displayedColumns: string[] = ['fecha', 'horaexamen', 'rut', 'nombre', 'tipoexamen', 'correo', 'telefono', 'epivigila', 'codigo', 'valor', 'verdetalles']; dataSource: MatTableDataSource<ExamenModel>; @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; constructor(private es: ExamenesService) { } ngOnInit(): void { this.es.getExamenes().subscribe( data => { this.examenes = data; this.dataSource = new MatTableDataSource(this.examenes); this.dataSource.paginator = this.paginator; }); } ngAfterViewInit() { this.dataSource.sort = this.sort; } Almost everyone suggest to put this.dataSource.sort = this.sort; inside ngAfterViewInit. I did this the first time because I saw it in Material documentation. Please help, I'm running out of ideas. Thanks ! |
Acessing object inside a fucntion in python Posted: 28 Jul 2021 08:16 AM PDT jira_formatting.py from .xml_parsing import xml2jira from ._utility import * from .get_global_constants import get_global_constants import os def get_tables_IOs(__filename, lang): if not os.path.exists(__filename): print("File not found!") exit(1) pkg_name = get_pkg_name(__filename) obj = xml2jira(lang) return pkg_name test_jira_formatting.py import unittest import sys import os from unittest.mock import patch from modules.jira_formatting import * from pathlib import Path pcakge_path = 'C:/TEMP/020_Tests/CCN-4679.pkg' path = Path(pcakge_path) lang = "en_US" class TestJiraFormatting(unittest.TestCase): def test_get_description_in_lines(self): pkg_name, descriptions = get_description_in_lines(path, lang) self.assertEqual(pkg_name, "CCN-4679") @patch("modules.xml_parsing") def test_get_tables_IOs(self, mock_xmlparsing_constructor): mock_parsing = mock_xmlparsing_constructor(lang).return_value self.assertIs(get_tables_IOs(path, lang).obj, mock_parsing) Why I am not able to access this get_tables_IOs(path, lang).obj |
Force Maven to Fail if Java Runtime is Above A Given Version Posted: 28 Jul 2021 08:17 AM PDT I have a unique situation with a legacy project, where I need a project to fail if Maven is invoked with a JDK runtime above 1.8 or 1.9. This is distinct from specifying source and target versions for the maven-plugin compiler (which are currently set at 8.) I need this to fail if someone attempts to run this with JDK 11 (reason being that the current project has dependencies that were part of the JDK once, but not anymore starting with JDK 11.) The build already fails, complaining about unresolvable dependencies, but I would like it to fail with a message saying "you need to use a JDK 8/9 runtime" instead (clarity is always king.) This is just a stop-gag measure to avoid people sending panic emails about things not compiling because they used JDK 11+, and where I cannot rely on everybody setting their own jdks in their toolchains.xml. At some point, we'll migrate properly to JDK 11, but at this time, I simply want Maven to die if someone calls it with anything other than JDK 8 or 9. And please, to reiterate, this is distinct from setting target and source versions for the maven plugin compiler. Thanks. |
Firebase Auth: How to unsubscribe from Auth observer after user creation and then subscribe again? Posted: 28 Jul 2021 08:17 AM PDT I am using the createUserWithEmailAndPassword() method for signing up new users. Immediately after this user creation process, I am sending an email verification. Then, in my onAuthStateChanged() I have a condition to check whether the user has verified their email. The problem is that the Auth observer is logging out the user BEFORE the email sendEmailVerification() method is complete. Based on the below code, where is the best place to succuessfully unsubscribe the observer ? And, how to do it with Firebase JS SDK v9? Let me explain my use case and show my code: pages/sign-up : async signUp() { const auth = getAuth() const batch = writeBatch(db) try { const UserCredential = await createUserWithEmailAndPassword( auth, this.formValues.email, this.formValues.password ) const userDocRef = doc(db, 'users', UserCredential.user.uid) batch.set(userDocRef, { uid: UserCredential.user.uid, displayName: this.formValues.displayName, photoURL: `https://gravatar.com/avatar/${md5( this.formValues.email )}?d=identicon` }) const usernameDocRef = doc(db, 'usernames', this.formValues.displayName) batch.set(usernameDocRef, { uid: UserCredential.user.uid }) // Commit batch await batch.commit() console.log('batch committed, user is:', UserCredential.user.uid) await this.verifyEmail() // <-- user is logged out before this has a chance to fire! verifyEmail() : async verifyEmail() { const auth = getAuth() const actionCodeSettings = { url: `${this.$config.baseUrl}/email-confirmation/success` } try { await sendEmailVerification(auth.currentUser, actionCodeSettings) } catch (error) { console.error('An email verification error happened', error) this.errorMessage = error.message } }, In my onAuthStateChanged() method, I am immediately logging out the user IF their email is not yet verified. This causes the following error: And here is how I have my onAuthStateChanged observer set up (it runs before the page is rendered): ~/plugins/auth.js : onAuthStateChanged(auth, (user) => { if (user) { if (!user.emailVerified) { // User has not verified the email yet store.dispatch('logOutUser') } // TO DO: finish up rest of user logic Should the unsubscribe be in the auth.js or the pages/sign-up page? I am unsure how to unsubscribe. |
How Best to Unpack a Pandas Dataframe of Tuples? Posted: 28 Jul 2021 08:18 AM PDT Probably really straightforward but I'm having no luck with Google. I have a 2 column dataframe of tuples, and I'm looking to unpack each tuple then pair up the contents from the same position in each column. For example: Col1 Col2 (a,b,c) (d,e,f) my desired output is a d b e c f I have a solution using loops but I would like to know a better way to do it - firstly because I am trying to eradicate loops from my life and secondly because it's potentially not as flexible as I may need it to be. l1=[('a','b'),('c','d'),('e','f','g'),('h','i')] l2=[('j','k'),('l','m'),('n','o','p'),('q','r')] df = pd.DataFrame(list(zip(l1,l2)),columns=['Col1','Col2']) df Out[547]: Col1 Col2 0 (a, b) (j, k) 1 (c, d) (l, m) 2 (e, f, g) (n, o, p) 3 (h, i) (q, r) for i in range(len(df)): for j in range(len(df.iloc[i][1])): print(df.iloc[i][0][j], df.iloc[i][1][j]) a j b k c l d m e n f o g p h q i r All pythonic suggestions and guidance hugely appreciated. Many thanks. |
Pute the callback-console.log from epic-games-api in express js Posted: 28 Jul 2021 08:17 AM PDT I want to put the epic games output in the express js get. I have 0 experience with js, so please no hate if it doesn't make sense. XD const EpicGamesAPI = require('epicgames-status'); const express = require('express') const app = express() const port = 3000 EpicGamesAPI().then(callback => { const epicgames = console.log(callback); }) app.get('/', (req, res) => { res.send(epicgames) }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) }) |
Flutter>Hive: type 'Null' is not a subtype of type 'bool' Posted: 28 Jul 2021 08:17 AM PDT in my app i want to detect in the splashscreen if this app is started for the first time. For that i want to use the hive nosql package. After that if the app is started for the first time it will open the welcome page and if not the login page. main.dart import 'package:flutter_config/flutter_config.dart'; import 'package:flutter/material.dart'; import 'package:app/pages/splash/splash_page.dart'; import 'package:hive/hive.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'config/theme/theme.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await FlutterConfig.loadEnvVariables(); await Hive.initFlutter(); await Hive.openBox('settings'); runApp(const App()); } class App extends StatefulWidget { const App({Key? key}) : super(key: key); @override State<App> createState() => _AppState(); } class _AppState extends State<App> { @override void dispose() async { Hive.close(); super.dispose(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'App', debugShowCheckedModeBanner: false, theme: lightThemeData(context), darkTheme: darkThemeData(context), home: const SplashPage(), ); } } splash_page.dart import 'package:flutter/material.dart'; import 'package:app/pages/login/login_page.dart'; import 'package:app/pages/welcome/welchome_page.dart'; import 'package:app/services/settings_service.dart'; class SplashPage extends StatefulWidget { const SplashPage({Key? key}) : super(key: key); @override State<SplashPage> createState() => _SplashPageState(); } class _SplashPageState extends State<SplashPage> { @override Widget build(BuildContext context) { Navigator.pushReplacement( context, MaterialPageRoute( builder: (_) => Settings().isFirstTime ? const WelcomePage() : const LoginPage(), ), ); return const Scaffold( body: Center( child: SizedBox( width: 125, height: 125, child: Icon(Icons.clear), ), ), ); } } there i call the function "var _isFirstTime = Settings().isFirstTime;" it should return me a bool settings_service.dart import 'package:hive/hive.dart'; import 'package:hive_flutter/hive_flutter.dart'; class Settings { final Box _settingsStorage = Hive.box('settings'); get isFirstTime { if (_settingsStorage.get('firstRun')) { return true; } else { _settingsStorage.put('firstRun', true); } return false; } } i got this error: ════════ Exception caught by widgets library ═══════════════════════════════════ The following _TypeError was thrown building SplashPage(dirty, state: _SplashPageState#261ae): type 'Null' is not a subtype of type 'bool' how can i solve this? later i would like to use the settings service for other settings as well ... |
clearInterval and resolve() not working if executed from class Posted: 28 Jul 2021 08:17 AM PDT My class: var indexedDBInitInterval; // clearInterval Doesnt work when done from within class for some reason.. var coumter = 1; class IndexedDBWrapper { constructor() { this._db = undefined this._dbInitInterval = undefined this.dbInitRequest = indexedDB.open("someDB", 1) this.dbInitRequest.onerror = (event) => { this.dbInitRequestOnError(event) } this.dbInitRequest.onsuccess = (event) => { this.dbInitRequestOnSuccess(event) } this.dbInitRequest.onupgradeneeded = (event) => { this.dbInitRequestOnUpgradedeNeeded(event) } } isDBInitalized() { return new Promise((resolve) => { indexedDBInitInterval = setInterval(() => { log(this.dbInitRequest) log(this.dbInitRequest.readyState) log(indexedDBInitInterval) coumter = coumter + 1 if (this.dbInitRequest.readyState == "done") { log("mutants") log(coumter) log(clearInterval(indexedDBInitInterval)) resolve() } }, 300) }) } dbInitRequestOnError(event) { log("Error initializing IndexedDB: ") log(event) } And calling with: indexedDBWrapper.isDBInitalized().then(() => { Neither clearInterval or resolve gets fired, even tho log("mutants") gets fired. What a puzzle.. |
How to run docker-compose automatically on startup lubuntu? Posted: 28 Jul 2021 08:17 AM PDT I have lubuntu 21.04 on my old PC. All is up to date. I install docker and docker-compose: sudo apt install docker docker-compose sudo systemctl enable --now docker After that in home dir create folder web with my project. The structure of folder ~/web below: . ├── docker-compose.yml ├── dockerfiles │ ├── lg4 │ ├── test │ └── test2 └── www ├── lg4 ├── test └── test2 All services have restart derictive in docker-compose.yml : version: '3.7' volumes: mysql-volume: networks: app-shared: driver: bridge web_app-shared: external: true services: php-httpd-lg4: restart: always build: args: user: lg4 uid: 1000 context: ./dockerfiles/lg4/ ports: - 80:80 volumes: - "./www/lg4:/var/www/html" links: - database networks: - app-shared - web_app-shared php-httpd-test: restart: always build: args: user: test uid: 1000 context: ./dockerfiles/test/ ports: - 82:80 volumes: - "./www/test:/var/www/html" links: - database networks: - app-shared - web_app-shared php-httpd-test2: restart: always build: args: user: test uid: 1000 context: ./dockerfiles/test2/ ports: - 81:80 volumes: - "./www/test2:/var/www/html" links: - database networks: - app-shared - web_app-shared database: restart: always image: mysql:5.7 restart: always volumes: - mysql-volume:/var/lib/mysql ports: - 3306:3306 networks: - app-shared - web_app-shared environment: TZ: "Europe/Moskow" MYSQL_ALLOW_EMPTY_PASSWORD: "no" MYSQL_ROOT_PASSWORD: "root" MYSQL_USER: 'admin' MYSQL_PASSWORD: 'admin' MYSQL_DATABASE: 'lg4' phpmyadmin: restart: always image: phpmyadmin/phpmyadmin links: - 'database:db' ports: - 8081:80 environment: UPLOAD_LIMIT: 300M networks: - app-shared - web_app-shared All works fine when I run comand sudo docker-compose up -d from ~/web dir. But how can I start all this automatically on startup system without typing any commands in terminal every time? |
Excel - Formula / Macro to auto increment values Posted: 28 Jul 2021 08:16 AM PDT I want to auto-increment a value by 1 each time the name column matches the same value. What's the best way to output the below in excel - i.e. via formula or macro? I have tried to use an excel IF formula but can't seem to get it work quite right! Many Thanks in advance Name | Reference | Desired Output | First | 1234 | N/A | First | 1256 | 1234.1 | First | 12567 | 1234.2 | Second | 666 | N/A | Third | 4321 | N/A | Third | 43211 | 4321.1 | Third | 43212 | 4321.2 | Third | 43213 | 4321.3 | |
How to track user location in background, react native? Posted: 28 Jul 2021 08:16 AM PDT I am using the react-native-geolocation-service package, and everything works like a charm. But now I am required to track a users location both in the foreground and in the background. I was wandering if the watchPosition method supports background location watching or is it just when in the app? and if it doesn't support it, what would be the alternative? Thanks |
Angular Lifecycle Interface OnChanges should be implemented for method ngOnChanges Posted: 28 Jul 2021 08:17 AM PDT Tslint is sending a warning indicating that OnChanges should be implemented for method ngOnChagnes lifecycle hooks. If I change ngOnChanges to OnChanges then the warning is not there. import { Component, Input, OnInit, Output, EventEmitter, SimpleChange, OnChanges } from '@angular/core'; import { Order } from '../../../../core/orders'; import { CartItem } from '../../../../core/orders'; import { User } from '../../../../core/auth/_models/user.model'; declare var $: any; @Component({ selector: 'app-order-summary', templateUrl: './order-summary.component.html', styleUrls: ['./order-summary.component.scss'] }) export class OrderSummaryComponent implements OnInit, OnChanges { @Input() cartDetails: Order; @Input() sellerDetail: User; @Input() productCost: number; @Output() closeOrderSummary = new EventEmitter<string>(); @Output() checkoutCart = new EventEmitter<string>(); @Output() updateItemQty = new EventEmitter<string>(); @Output() updateProductSelected = new EventEmitter<string>(); cartList: CartItem[] = []; isCartEmpty: boolean; constructor() {} ngOnChanges(changes: SimpleChange) { for (const propName in changes) { if (propName === 'cartDetails') { const change = changes[propName]; this.cartList = change.currentValue; this.isCartEmpty = (change.currentValue.length === 0); } } } ngOnInit(): void { } onUpdateItemCount(item, direc) { const payload = { item, direc }; this.updateItemQty.emit(payload); } onUpdateProductSelected(value, item) { const payload = { value, item}; this.updateProductSelected.emit(payload); } goBackToMain() { this.closeOrderSummary.emit(); } onCheckoutCart() { this.checkoutCart.emit(); } } |
Jenkins Kubernetes Plugin PodTemplate fails to map workspace from master to pod, works in pipeline instead Posted: 28 Jul 2021 08:17 AM PDT I declared the following podTemplate to run a packer ami build in my project, podTemplate(label: "ami-builds", serviceAccount: "default", containers: [ containerTemplate(name: 'packer-builder', image: 'anadimisra/python-hashicorp:1.0', ttyEnabled: true, command: 'sleep', args: '99d'), ]) { node('ami-builds') { stage('Build AMI') { container('packer-builder') { stage('Packer Build') { sh ''' export AWS_ACCESS_KEY_ID="${AWS_SECRET_ACCESS_KEY}" export AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY}" export AWS_SESSION_TOKEN=${AWS_SESSION_TOKEN} packer init amis/registry/. packer build -var="nifi_registry_version=${NIFI_RELEASE_VERSION}" \ -var="ami_version=${AMI_VERSION}" -var="vpc_id=${VPC_ID}" \ -var="subnet_id=${SUBNET_ID}" amis/registry/. ''' } } } } } When I run the jenkins build, it fails at the step packer init . because packer cannot find any hcl files, when I observe the pods from kubectl by putting a sleep in the sh block, I notice that the pod workspace is empty; while on master we have the git branch checked-out at /var/jenkins_home/workspace ..... Hence, concluding that the mapping doesn't happen somehow. But when I change this syntax to pipeline with agent, it works: pipeline { agent { kubernetes { label 'ami-builds' yamlFile 'amis/registry/PythonHashicorpPod.yaml' } } stages { stage('Packer Build') { steps { container('packer-builder') { sh ''' export AWS_ACCESS_KEY_ID="${AWS_SECRET_ACCESS_KEY}" export AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY}" export AWS_SESSION_TOKEN=${AWS_SESSION_TOKEN} packer init amis/registry/. packer build -var="nifi_registry_version=${NIFI_RELEASE_VERSION}" \ -var="ami_version=${AMI_VERSION}" -var="vpc_id=${VPC_ID}" \ -var="subnet_id=${SUBNET_ID}" amis/registry/. ''' } } } } } and the Pod YAML apiVersion: v1 kind: Pod spec: containers: - name: packer-builder image: anadimisra/python-hashicorp:1.1 tty: true In both cases the Job type is Pipeline and the build step is Pipeline Scm Script . Makes me wonder do we use podTemplates and pipelines for inherently different purposes? |
I need to get the list of users who have previously been sent message (MySQL) Posted: 28 Jul 2021 08:17 AM PDT I am making an instant messaging web page, I have assembled the entire database and made 100% of the front-end of the entire page, I only have to do the start menu ... So in the start menu I just want to show users that ** a message has been sent to before **, I haven't managed to do this, and right now I'm showing a list of ** all registered users ** .. Something like the following is what I am showing PROFILE PHOTO 1 - User Nº1 - Last message sent - Status (Offline / Online) PROFILE PHOTO 2 - User Nº2 - No messages have been sent - Status (Offline / Online) PROFILE PHOTO 3 - User Nº3 - Last message sent - Status (Offline / Online) PROFILE PHOTO 4 - User Nº4 - Last message sent - Status (Offline / Online) When what I want to show is something like the following: PROFILE PHOTO 1 - User Nº1 - Last message sent - Status (Offline / Online) PROFILE PHOTO 3 - User Nº3 - Last message sent - Status (Offline / Online) PROFILE PHOTO 4 - User Nº4 - Last message sent - Status (Offline / Online) Currently the design of my table is as follows: > messages msg_id | incoming_msg_id | incoming_msg_id | outgoing_msg_id | msg > users user_id | unique_id | fname | lname | email | password | img | status Clarification, the incoming_msg_id field is the ID of the user who receives the message, and the outgoing_msg_id is the one that sends it, which in this case matches the user_id field of the users table. Currently my code is the following, which, as I have told you, shows what I leave below. <?php session_start(); include_once "config.php"; $outgoing_id = $_SESSION['unique_id']; $sql = "SELECT * FROM users WHERE NOT unique_id = {$outgoing_id} ORDER BY user_id DESC"; $query = mysqli_query($conn, $sql); $output = ""; if(mysqli_num_rows($query) == 0){ $output .= "No users are available to chat"; }elseif(mysqli_num_rows($query) > 0){ include_once "data.php"; } echo $output; ?> PROFILE PHOTO 1 - User Nº1 - Last message sent - Status (Offline / Online) PROFILE PHOTO 2 - User Nº2 - No messages have been sent - Status (Offline / Online) PROFILE PHOTO 3 - User Nº3 - Last message sent - Status (Offline / Online) PROFILE PHOTO 4 - User Nº4 - Last message sent - Status (Offline / Online) Finally I leave you two real and current photos of my boards: EDITED |
Reversing digits in 2D array Posted: 28 Jul 2021 08:17 AM PDT I was trying to reverse the numbers in this 2D array, but I happened to be reversing only first and the last numbers. So far I have done this, but don't know where is the mistake and how to fix it, so that every digits are being reversed, not just first and the last: int [][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int x = 0, y = array.length - 1; int a = 0, b = array[y - 2].length - 1; int temp; while(x < y && a < b) { temp = array[x][a]; array[x][a] = array[y][b]; array[y][b] = temp; a++; b--; if(a == 3 && b == 0) { a = 0; x++; y--; } } for(int i=0; i<array.length; i++) { for(int j=0; j<array[i].length; j++) { System.out.println(array[i][j]); } } |
SwiftUI: VideoPlayer to display different videos stored locally (back and forward buttons) Posted: 28 Jul 2021 08:17 AM PDT I'm still new to SwiftUI and have run into a problem. I need to use back and forward buttons to make the Video Player go to the previous/next video (stored locally). The following code works for one video only, the one declared into the init(), but I can't manage to change the video by clicking the back and forward buttons. I'm using an array of String called videoNames to pass all the video names from the previous View. Also, I'm using a custom Video Player for this and I'm gonna include the relevant parts of the code. This is my View: struct WorkingOutSessionView: View { let videoNames: [String] @State var customPlayer : AVPlayer @State var isplaying = false @State var showcontrols = false init(videoNames: [String]) { self.videoNames = videoNames self._customPlayer = State(initialValue: AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: videoNames[0], ofType: "mov")!))) } var body: some View { VStack { CustomVideoPlayer(player: $customPlayer) .frame(width: 390, height: 219) .onTapGesture { self.showcontrols = true } GeometryReader {_ in // BUTTONS HStack { // BACK BUTTON Button(action: { // code }, label: { Image(systemName: "lessthan") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 60, height: 60) .foregroundColor((Color(red: 243/255, green: 189/255, blue: 126/255))) .padding() }) // FORWARD BUTTON Button(action: { // code }, label: { Image(systemName: "greaterthan") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 60, height: 60) .foregroundColor((Color(red: 243/255, green: 189/255, blue: 126/255))) .padding() }) } } } .offset(y: 35) .edgesIgnoringSafeArea(.all) } This is my custom Video Player: struct CustomVideoPlayer : UIViewControllerRepresentable { @Binding var player: AVPlayer func makeUIViewController(context: UIViewControllerRepresentableContext<CustomVideoPlayer>) -> AVPlayerViewController { let controller = AVPlayerViewController() controller.player = player controller.showsPlaybackControls = false return controller } func updateUIViewController(_ uiViewController: AVPlayerViewController, context: UIViewControllerRepresentableContext<CustomVideoPlayer>) { } } I've researched for solutions but couldn't find anything relevant. I've tried to modify my CustomVideoPlayer and not pass a @Binding variable... As well, the init() gave me a lot of headaches as it comes back to errors every time I change something... Any solution would help guys. I really appreciate your time. |
p-table filter not working with 'contains' in some cases Posted: 28 Jul 2021 08:17 AM PDT Global filter of p-table has an issue? I have some records and when I search 'test.txt'(full name) it filters properly but if I search'test' it does not filter the content instead it includes some records that don't have matching search term. my code: <p-table #dt [columns]="selectedColumns" [value]="jobList" [(selection)]="selectedJob" (onRowSelect)="onRowSelect($event)" columnResizeMode="expand" [resizableColumns]="true" [autoLayout]="true" [rows]="10" selectionMode="single" [paginator]="true" [pageLinks]="3" [rowsPerPageOptions]="[5,10,15,20,50,100]" [metaKeySelection]="true" (sortFunction)="sortColumn($event)" [customSort]="true" sortField="createdOn" [sortOrder]="-1" [style]="{'padding-right':'13px','padding-bottom':'13px' }" > <ng-template pTemplate="caption"> <div class="table"> <div class="row"> <div class="leftcell"> <i class="fa fa-search" style="margin:4px 4px 0 0"></i> <input type="text" pInputText [(ngModel)]="dtinput" size="25" placeholder="Search" (input)="dt.filterGlobal($event.target.value, 'contains')" class="search-style" > <button pButton type="button" (click)="resetfilter()" label="Clear Filter" ></button> </div> <div class="rightcell"> ... </div> </div> </div> .... |
Convert UTC time_t to UTC tm Posted: 28 Jul 2021 08:17 AM PDT All my internal times are UTC stored in time_t . I need to convert them to struct tm . If I use localtime the time is correct, except that tm_isdst may be set resulting in the time being off an hour. If I use gmtime it gets the wrong time, off by the time zone difference. Edit I am looking for a cross platform solution that works in Windows and Linux |
Upgrade typo3 7.6.32 on Virtual Machine, website broken After changing Symlink, and any idea how to update typo3 7 to 10 Posted: 28 Jul 2021 08:16 AM PDT How to change symlink and update to version 10 in the right way ? I made backup for DB and the whole typo3 file, then I upgraded wizard. Everything was good, but when I set up symlink manually, everything broke. So back to update file, got an error code 500 on backend and frontend. Anyone has idea how to do update from 7 to 10 and how to change symlink properly. |
I am new to Kubernetes and want to understand if this agent will be able to mess up my cluster somehow Posted: 28 Jul 2021 08:18 AM PDT Recently I was searching for ways to reduce cloud bill and came up to a company named CAST.AI So to run a savings report you need to install their agent to your cluster and they claim it is read-only How do I check if this is true? This comes from the yaml file they provide: https://pastebin.com/pLbYAEGP (too long to paste here) |
Flutter increase height of TextFormField Posted: 28 Jul 2021 08:17 AM PDT I am creating a Flutter app. i made the design like this. My TextFormField form field for email and password heights are small. I want it to be the same size of the button. final email = TextFormField( keyboardType: TextInputType.emailAddress, autofocus: false, initialValue: 'sathyabaman@gmail.com', style: new TextStyle(fontWeight: FontWeight.normal, color: Colors.white), decoration: InputDecoration( hintText: 'Email', contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(32.0) ), ), ); Whats the syntax for the height in text form field. |
No comments:
Post a Comment