Skip to main content

Posts

Showing posts from August, 2021

Can you onblur a set of checkboxes?

I have a set of checkboxes, and validation such that at least one of those checkboxes need to be checked on submit. But I want to be able to set a validation error if the user blurs out of the set of checkboxes. The problem is that if I do a blur for the last one it doesn't work because they could be shift-tabbing to the second from last checkbox. I've tried to but the onblur in the fieldset tag, but that didn't trigger a blur at all. Is this just a limitation that can't be overcome with plain html and vanilla JS? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

custom donation amount in stripe (php)

i am trying to make a donation page using stripe with a custom amount. the code works perfect with fixed amount, but when i change it to variable amount it return 0, please help i tried many ways but nothing work. this is a snippet of the code checkout.html <body> <section> <div class="panel"> <h3>Donate Now</h3> <input type="number" id="amount" value="100"/> </div> <button type="button" id="checkout-button">Checkout</button> </section> </body> <script type="text/javascript" charset="utf-8"> // Create an instance of the Stripe object with your publishable API key var stripe = Stripe("pk_test_51J2BvHLTS6YsumlzTSoJwjdzJpMt5zUhcBcJo16SQnmOs1EJKLwW5CThE2qud0xMDZFq5q1b6ezNc29Q7Hc2nQaa00uAjNryX3"); var checkoutButton = document.getElementById(...

Convert ISO 639-1 into a language name in local language with PHP

Stack Overflow offers some "similar" questions but none of them is suitable unfortunately. Or I am a bad searcher. There is the language column in MySQL database which stores different ISO 639-1 codes depending on the user settings. Then I grab the user's ISO 631-1 code into the $lang variable and can output it with echo . No problem. Is there a PHP 7 compatible technique to convert en into English, es into Español, fr into Français, etc? I'm currently using the following code to achieve this if($lang == 'en'){$userlang = 'English';} if($lang == 'es'){$userlang = 'Español';} if($lang == 'fr'){$userlang = 'Français';} which I don't find optimal as there is a huge list of ISO 639-1 codes and I definitely don't want to put them all into the code. Found locale_get_display_script manual at php.net but it returns nothing even copypasted from a given example - may be my ISP doesn't provide all required l...

Ajax returned an undefined php index error while the other one don't

I have a problem with ajax, when I call it, i get the undefined index error on my variables. I have other ajax call on all my website, and no problem, but this one give me an error. I search in my code and I don't see where my mistake is :(. Here is my HTML : <script type="text/javascript"> $('#btnDispo').click(function() { var service = document.getElementById("serviceTest").value; var date = document.getElementById("DateReservation").value; var heure = document.getElementById("heureTest").value; if( service && date && heure) { $.ajax({ type:"POST", url: "check-table.php", dataType: "json", data: { service: service, date: date, heure: heure }, success: function(output_string) { $("#result_table").html(output_string); } // End of success function...

Ordering in a foreach loop

I trying to order a query inside a foreach loop. After looking around reasoning why its not displaying the results correctly I've read that the foreach will only run once for every user its found so its basically just ordering that one users updates. $AllFriend = explode(",", $UserInfo['friends']); array_push($AllFriend, $Username); foreach ($AllFriend as $FriendSel) { $sql5 = "SELECT * FROM updates WHERE username = :username ORDER BY id DESC LIMIT 20"; $DoQuery = $pdo->prepare($sql5); $DoQuery->bindValue(':username', $FriendSel); $DoQuery->execute(); while ($Updates = $DoQuery->fetch(PDO::FETCH_ASSOC)){ I have the friends in the database like "friend1, friend2, friend3" etc so I'm using array_push to add the use...

Quickbooks php curl authenticated GET request fails

I have set up a company in the QuickBooks developer portal, and have successfully created an OAuth token (which I can refresh as specified in this answer ). So, unlike the majority of these questions, this is not about OAuth... I'm using bare PHP here, as I cannot use the SDK for technical reasons. After getting the OAuth token, I am trying to perform the next API call from the API playground, getting the company information. I effectively call the QB API with this code: ( $query is /v3/company/<companyID>/companyinfo/<companyID> (companyID is the "Realm ID" from the API playground), $base is the sandbox-URL (same as "Sandbox Base URL" in the header), $access_tokens["access"] is the OAuth access token; $url is https://${base}${query} ) $headers = array( "GET " . $query . " HTTP/2", "Host: " . $base, "Accept: application/json", "Authorization: Bearer " . $access_token...

Avoiding n queries on API list call for database-calculated model attributes

I am cleaning up a quite messy php laravel 8 project right now. Currently my ressource looks like this: class MyModelSimpleResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'my_calculated_attribute' => MyModel::whereRaw('fk_id = ? AND model_type = "xyz"', [$this->id])->count(), ]; } } My problem is that on calling the API endpoint, for every record of MyModel it creates a separate query to calculate my_calculated_attribute . I know that you can define foreign key constrains in the model like and query like this: MyModel::with('myFkModel')->get() This works great for foreign keys. But how can I avoid n queries when I need this my_calculated_attribute . Thanks a lot! PS: I know that raw queries are a bad idea and I know that the resource is supposed to transform data and not...

GuzzleHttp\Exception\ConnectException: Connection refused for URI

I try to scrape a websites HTML code with a guzzle http-request. In the browser (chrome) everything works fine, but when I try to execute the PHP script with the console (windows) I get the following error: GuzzleHttp\Exception\ConnectException: Connection refused for URI https://example.com $httpClient = new \GuzzleHttp\Client(); $response = $httpClient->get("https://example.com"); $htmlString = (string) $response->getBody(); I downloaded "php-7.4.23-nts-Win32-vc15-x64.zip" and extracted it I navigated to the folder where I extracted php I ran php c:\myproject\index.php source https://stackoverflow.com/questions/69003782/guzzlehttp-exception-connectexception-connection-refused-for-uri

Error using an Iframe in unload with JS and PHP

I have a web page where I want to capture the event when the browser closes, apparently everything works on the other pages I have, but on the page called personal, I have an iframe where it contains a video. At the moment of loading the page with F5 or Ctrl + F the event is not activated, but if I reload with the browser button it detects the event. Configure my JS so that events such as clicking on a link, submitting a form, this event is not activated, but having an iFrame does activate me. Any idea how to solve this? I thank you in advance. This is my code: close.js: var es_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; var es_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; if(es_chrome){ $(document).ready(function(){ var validNavigations = false; $(document).bind('keypress', function(e) { if (e.keyCode == 116){ validNavigations = true; } ...

How to select columns from different rows that share a common column value? [closed]

Given the following table setup, how do I select the meta_values from both rows that have a common post_id? I'm looking to return something like: Bob is married to Jane Pete is married to Amanda Rick is married to Sally +-----------+------------+--------------+ | post_id | meta_key | meta_value | +-----------+------------+--------------+ | 10 | 'key_1' | 'Bob" | +-----------+------------+--------------+ | 10 | 'key_2' | 'Jane' | +-----------+------------+--------------+ | 20 | 'key_1' | 'Pete" | +-----------+------------+--------------+ | 20 | 'key_2' | 'Amanda' | +-----------+------------+--------------+ | 30 | 'key_1' | 'Rick" | +-----------+------------+--------------+ | 30 | 'key_2' | 'Sally' | +-----------+------------+--------------+ Thanks in advance for your help. sou...

Parse through SOAP response

I am a beginner at SOAP and have been trying to figure how to parse through XML response when I call the SOAP API.I have already tried similar questions like this on stackoverflow but somehow they are not working for me. I want to access Village and VillageName tag in a loop . <dsVillages> <xs:schema id="dsVillages" targetNamespace="http://app.in/wsror/dsVillages.xsd" attributeFormDefault="qualified" elementFormDefault="qualified"> <xs:element name="dsVillages" msdata:IsDataSet="true" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="VILLAGES"> <xs:complexType> <xs:sequence> <xs:element name="taluka" minOccurs="0"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="8"/> </xs:restriction...

Wp All Import Function Editor

I'm trying to import a csv file with wp all import set specific functions to set the sale price and the offer price. Now I would need to call the function that forms the regular price, inside the function of the offer price, to work on the result and maybe apply a percentage discount. <?php $GLOBALS['$commissione_paypal_lm'] = 4; $GLOBALS['$spese_spedizione_moto_lm'] = 10; $GLOBALS['$spese_spedizione_autocarro_lm'] = 10; $GLOBALS['$spese_spedizione_varie_lm'] = 7; $GLOBALS['$pfu_moto_lm'] = 1.50; $GLOBALS['$pfu_autocarro_lm'] = 4.90; $GLOBALS['$pfu_varie_lm'] = 2.90; // First function for regular price,i take variables from csv and global variables function prezzo_finale( $price = null, $pfu = null, $diametro = null ) { if ( !empty( $price ) ) { // strip any extra characters from price $price = preg_replace("/[^0-9,.]/", "", $price); $pfu = preg_replace("/[^0-9,.]/...

Get latest file in dir including subdirectory php

i found out that i can use $files = scandir('c:\myfolder', SCANDIR_SORT_DESCENDING); $newest_file = $files[0]; to get the latest file in the given directory ('myfolder'). is there an easy way to get the latest file including subdirectorys? like: myfolder> dir1 > file_older1.txt myfolder> dir2 > dir3 > newest_file_in_maindir.txt myfolder> dir4 > file_older2.txt Thanks in advance source https://stackoverflow.com/questions/69003206/get-latest-file-in-dir-including-subdirectory-php

Twig - tables side by side

Hi i have a question: how can i put two arrays side by side using twig ?? I'm trying and can't find a solution :( my array the effect that i want to get table,td{ border: 1px solid black; padding: 1px; } <table> <tr> <td> last.val1 </td> <td> last.val2 </td> <td> last.val3 </td> <td> #### </td> <td> primary.val1 </td> <td> primary.val2 </td> <td> primary.val3 </td> </tr> <tr> <td> ... </td> <td> ... </td> <td> ... </td> <td> ... </td> <td> ... </td> <td> ... </td> <td> ... </td> </tr> <table> Thank you for answering! source https://stackoverflow.com/questions/69003296/twig-tables-side-by-side

PHP compression error when migrating installatron application from one server to another

I am trying to migrate a Yourls installation from server 1 to server 2. Plesk Obsidian is installed on both servers as is the Installatron Plesk plugin. I'm using SSH from server 2 to server 1 and the connection is made correctly but then i get this error when Installatron tries to install the application... Importing: Error: Compression failed: [1] -: php: command not found I've checked the server Apache settings and deflate and brotli are both installed. Now I am stuck. There is nothing in the web about this. The reason I am using Installatron to perform the migration is because the original application on server 1 was installed using it. I've successfully transferred an application from a CPanel server to a Plesk server in the past using the same method. source https://stackoverflow.com/questions/69002799/php-compression-error-when-migrating-installatron-application-from-one-server-to

Can't send email with attachment and content

I am trying to implement a candidature submission to my website, using the website as example, but it seems to corrupt the attached files and doesn't post the message in the email. not quite sure what's happening though, once i'm new to php. https://codeconia.com/2021/05/28/html-form-to-email-with-attachment-using-php/ <?php if(isset($_POST['submit'])){ $filenameee = $_FILES['file']['name']; $fileName = $_FILES['file']['tmp_name']; $name = $_POST['name']; $email = $_POST['email']; $usermessage = $_POST['message']; $message ="Recebeu uma candidatura de ". $name . " com a seguinte mensagem:\r\n" . $usermessage; $subject ='=?UTF-8?B?' . base64_encode("Candidatura de ".$name).'?='; $fromname ='=?UTF-8?B?' . base64_encode($_POST['name']).'?='; $fromemail = $_POST['email']; //if ...

How to access phpbb3 through an iframe without getting logged out

Due to new security settings implemented in most browsers (though not Firefox as of 8/21), users were getting logged out of phpbb3 when looking at messages or pressing "New Topic". The relevant phpbb feature request is low priority and hasn't seen activity for about a year. source https://stackoverflow.com/questions/69003336/how-to-access-phpbb3-through-an-iframe-without-getting-logged-out

Failed to load plugin Tinymce

Suddenly my TinyMCE classic editor shows this error: Failed to load plugin url: https://www.example.com/wp-includes/js/tinymce/langs/pt.js I’ve switched off plugins one by one, nothing I’ve reinstalled WordPress core files, nothing But when i switch from my theme to a default one, it works… But how a theme can affect this plugin? The problem occurred after upgrading Wordpress to 4.8. Is there any way to understand where it comes from? Thanks! source https://stackoverflow.com/questions/69003232/failed-to-load-plugin-tinymce

Relate the indixes (keys) of an Array object to the indixes (keys) of an array (PHP)

I have a doubt in which I didn't get a solution. I have an Array values ​​object and a status array, where I want to relate the indixes of the Array values ​​object to the indixes of the status array. So that I can write a logical test where: If the Array values ​​object's index 0 is different from null (that is, it contains value), then the status array's index 0 will get the value "1". OR If the Array values ​​object's index 1 is different from null (that is, it contains value), then the status array's index 1 will receive the value "1". For example, before the logic test: values:[ 0 => Array1:[ 0 => "1,023" 1 => "0,023" 2 => "5,023" 3 => "1" ] 1 => Array2:[ 0 => "null" 1 => "null" 2 => "5" 3 => "1,365" ] 2 => Array3:[ 0 => "null" 1 => "null" 2 => "null...

Contributing to Nextcloud - How to understand code structure?

I would like to contribute to Nextcloud because there are some issues that are quite easily fixed but aren't by the developers. Now this might sound like a stupid question, but I can't find ANY information on how the code is structured. There is no documentation I could find whatsoever. I also can't find any information of other people developing with Nextcloud as issues on Github are not answered. Is there any information available or is it only Open Source in the sense that all structure is kept private by Nextcloud GmbH and only the code is made public? Specifically I am looking for information on which Vue.js component does what and where I would have to look to find the functions that are doing what I'm searching for. source https://stackoverflow.com/questions/69003224/contributing-to-nextcloud-how-to-understand-code-structure

Limit number of words in Woocommerce description (using php)

I edited my Child Theme's functions.php to display the short description of my WooCommerce products under the product title. I had this code that works fine and limits the number of characters to 165, then adds "..." at the end of the excerpt. However, I don't want the words to break after 165 characters. Therefore, I was wondering if there was a way to either limit the number of words instead of character, or simply keep the words from breaking? function woocommerce_after_shop_loop_item_title_short_description() { global $product; if ( ! $product->post->post_excerpt ) return; ?> <div itemprop="description"> <?php echo substr(apply_filters( 'woocommerce_short_description', $product->post->post_excerpt ),0,165); echo '...' ?> </div> <?php } source https://stackoverflow.com/questions/69002775/limit-number-of-words-in-woocommerce-description-using-php

Printing Web Hosted PHP using Thermal Printer

I have XPrinter XP-318B model. I've created my PHP Application on web-hosted. When I tried to print on my Epson printer, it works fine, but when I tried to print on XPrinter (thermal printer) it shows random Chinese characters. Is there anyone who has the same problem as me? ==edit I've tried using Recta host to set up the printer, but still not working. source https://stackoverflow.com/questions/69003189/printing-web-hosted-php-using-thermal-printer

rails 6 dynamic bootstrap modal using js.erb error

I'm trying to display bootstrap modal with dynamically, so every time user click on record it shows modal with that record information. I don't want to show modal for all record every time I reload the page. I got this error in browser console. SyntaxError: Unexpected token '===' Controller events_controller.rb def pay @event = Event.find(params[:id]) respond_to do |format| format.js{} end end View index.html.erb <%= link_to pay_path(id: event.id), remote: true, class: "", method: :patch do %> Paid <i class="fe fe-dollar-sign"></i> <% end %> Pay view _pay.html.erb <!-- Modal: pay invoice --> <div class="modal fade show" id="pay_invoice" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-dialog-vertical" role="document"> <div class="modal-content"...

How to filter and sort nested objects? ReactJS

Data sample: const people = [ 1:{ id : 1, name: 'James', age: 31, toBeDeleted: false, position: 2 }, 2:{ id : 2, name: 'John', age: 45, toBeDeleted: true, position: 3 }, 3:{ id : 3, name: 'Paul', age: 65, toBeDeleted: false, position: 1 } ]; I try this way, but it doesn't work : const sorted = Object.values(people) .filter((people) => people.toBeDeleted !== true) .sort((a, b) => a.position - b.position); If I delete the id keys, then my code works. In result must be array like this : const people = [ { id : 3, name: 'Paul', age: 65, toBeDeleted: false, position: 1 }, { id : 1, name: 'Jame...

How to tilt hover in CSS

I use this css style for hover: .hvr-link{display:inline-block;vertical-align: middle; -webkit-transform: perspective(1px) translateZ(0); transform: perspective(1px) translateZ(0); box-shadow: 0 0 1px rgba(0, 0, 0, 0); position: relative; -webkit-transition-property: color; transition-property: color; -webkit-transition-duration: 0.3s; transition-duration: 0.3s; } .hvr-link:before { content: ""; position: absolute; z-index: -1; top: 0; bottom: 0; left: 0; right: 0; background: #424141; -webkit-transform: scaleY(0); transform: scaleY(0); -webkit-transform-origin: 50%; transform-origin: 50%; -webkit-transition-property: transform; transition-property: transform; -webkit-transition-duration: 0.3s; transition-duration: 0.3s; -webkit-transition-timing-function: ease-out; transition-timing-function: ease-out; } .hvr-link:hover, .hvr-link:focus, .hvr-link:active{color: white;} .hvr-link:hover:before, .hvr-link:focus:before, .hvr-l...

How to destroy Ionic Component on redirect

I have Ionic 4 Angular app. It has a three-tab structure. The tabs router module looks like this: { path: 'tab1', loadChildren: () => import('../tab1/tab1.module').then((m) => m.Tab1PageModule), }, { path: 'tab2', loadChildren: () => import('../tab2/tab2.module').then((m) => m.Tab2PageModule), }, { path: 'tab3', loadChildren: () => import('../tab3/tab3.module').then((m) => m.Tab3PageModule), } On each tab I have different components which I want to be destroyed by a redirect to another tab. But the Component destroy event doesn't happen. In my case Tab1 has this list: <ion-list> <ion-item routerLink="invites">Invites</ion-item> <ion-item>Friend Requests</ion-item> </ion-list> 'Invites' click takes me to the InvitesComponent . After that, if I click Tab2 InvitesComponent will stay there in its l...

Download CSV with formatted date

In Google Sheets Script I have the following array data.forEach(function(row){ if(row[0]==""){ results.push([row[1],row[4].toString(Utilities.formatDate(row[4],"GMT-5","yyyy-MM-dd"))); row[0] = "Exported"; } }); //Use SetValues to set results[] to sheet //Download file as CSV The problem I'm having is that the date still shows in Long format in the CSV file instead of the format I have set. The sheet shows it in the correct format. Thanks for your help. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Variable from ajax via get no longer there [duplicate]

I'm currently working on a webbased QR code scanner and i use html5QrcodeScanner for it. The scanning progress works fine, except for this few lines: This SQL statement works fine with $abc as the variable I get via GET from ajax : $sql = "UPDATE `registered` SET scan = current_timestamp() WHERE `id`='$abc'"; $result = mysqli_query($conn, $sql); Next line, my variable $abc doesn't work anymore... $key_ar = array_search($abc, array_column($userinfo, 'id')); This is ( i would say ) all in all the important part for the Problem // on the top of the class, i put the whole table in a array $result_rs = mysqli_query($conn, "select `id`,`pname`,`name`,`date` from `registered`"); $userinfo = array(); while ($row_user = mysqli_fetch_assoc($result_rs)) { $userinfo[] = $row_user; } function onScanSuccess(decodedText, decodedResult) { if (decodedText !== lastResult) { ++countResults; lastResult = decodedText; ...

JavaScript to TypeScript type/interface mapping

I'm using this library in a TypeScript project. And this is how my class looks like: import OnvifManager from 'onvif-nvt' Class OnvifApi { // device: any = undefined device = {} as OnvifDevice constructor (...params) { // definition } connect (): Promise<any> { OnvifManager.connect(...params).then((response: OnvifDevice) => { this.device = response resolve(response) } } coreService(): Promise<Type[]> { this.device.add('core') } } And this this interface I created for the response from onvif-nvt interface OnvifDevice { address: string // type // type // type add(name: string): void } This class is always giving an error in coreService saying that this.device.add is not a function. EDIT: This is the return of the connect method, which returns the whole Camera object. Things are working when device is defined to any . How can I do this interface mapping from JavaScript to TypeScript? Via Active questions tagged j...

why is live-server injecting these javascript codes

I'm trying to create grid layout but live-server is injecting these codes in webpage... // <![CDATA[ <-- For SVG support if ('WebSocket' in window) { (function() { function refreshCSS() { var sheets = [].slice.call(document.getElementsByTagName("link")); var head = document.getElementsByTagName("head")[0]; for (var i = 0; i < sheets.length; ++i) { var elem = sheets[i]; head.removeChild(elem); var rel = elem.rel; if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") { var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, ''); elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf()); } head.appendChild(elem); } } var protocol = window.location.protocol === 'http:' ? ...

How to build a price filter with checkbox in react [closed]

How do I build a filter using checkbox with react similar to the image below: Thank You Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How can I display a message or loading animation while flask.send_from_directory is processing?

I have a simple web application that calls the Spotify API, and, among other things, allows a user to download their "Liked Songs". The 'download' view writes a csv file of the 'Liked Songs' to a tmp directory and then downloads that file using flask.send_from_directory. @bp.route('/download', methods=['GET']) @login_required def download(): ... # Edited with more details below return send_from_directory( temp_dir, target[0], as_attachment=True, attachment_filename=file_name ) It all works as intended but can take a while if a user has many thousands of Liked Songs. During that 20+ seconds I would like to give the user some feedback that the task is processing -- a message or loading animation. I have written a loading animation used elsewhere in my site, but in those cases the view ends with a redirect. I also can reveal a modal with javascript. However, a modal or animation will not automatically...

Problem with showing correct delivery date

I have a website which shows the delivery date when you search product P.S as an example, I use today's order which was created 30.08.2021 14:12 Delivery date on the search result page show this code: if(time_to_exe == 7) { var orderDateTime = moment(); // Get Monday (first day) of this week and add 3 days (to get to Thursday) and set the time to 11:59am var cutOffDate = moment().startOf('week').add(3,'days').set({'hour': 11, 'minute': 59, 'second': 59}); // Initialize delivery date from order date var deliveryDate = orderDateTime.clone(); if (orderDateTime.isSameOrBefore(cutOffDate)) { deliveryDate = deliveryDate.add(1,'week').startOf('week'); // Monday next week } else { deliveryDate = deliveryDate.add(2,'week').startOf('week'); // Monday the week after next } if (deliveryDate) { time_to_exe = deliveryDate.format("D. MMMM"); } else { time_to_exe = ti...

Linking two elements of an object together

I asked this yesterday, but I didn't really get a solution, and after thinking more, I'm still unsure about what I can do to get by this issue. <script> var input = document.querySelector('input[name=tags-outside]'); let guildRoles = [] let guildIds = [] guild_roles = ; guild_roles.map(e => { guildRoles.push(e["name"]) guildIds.push(e["id"]) }) new Tagify(input, { whitelist: guildRoles, userInput: false }) </script> I was originally thinking of having two arrays, one for ID, one for names, but this isn't really a good solution. I have a dropdown list using tagify, and the user needs to select a discord role from this dropdown. Each role has a unique identifier in the array of objects, it resembers something like this: 0: {color: 0, hoist: false, icon: null, id: "754852776550596638", managed: false, name: "role5"} 1: {color: 0, hoist: false, icon: null, ...

How to avoid input value copying on click of button

Everything works fine but it also copies the value inside input button e.g if i write 1st in the input, 1st will also be copied on click of the button, does anyone has any resolution ? $(function(){ $(".btn-copy").on('click', function(){ var ele = $(this).closest('.example-2').clone(true); $(this).closest('.example-2').after(ele); }) }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-header"> <h5 class="card-title">Add Class</h5> </div> <div class="card-body"> <form action="#"> <div class="ex...

Remove object property from the nested object in the array

I have the following array of books. I want a write a function that receives the target book and the language, removes that book (key, value) from the nested object and returns the new array. let books = [ { language: 'spanish', books: { book_1: 'book1_spanish', book_2: 'book2_spanish', book_3: 'book3_spanish' } }, { language: 'italian', books: { book_1: 'book1_italian', book_2: 'book2_italian', book_3: 'book3_italian' } } ]; let targetBook = { book_1: 'book1_spanish' }; let language = 'spanish'; I am stuck at looping over the nested object. function removeTargetBook(lan, target) { return books.map(book => { if (book.language == lan) { Object.values(book).map(value => {}); } }); } It should return the same array without book_1: 'book1_spanish'. This is my stackblitz: https://stackblitz.com/edit/js-yxcrbq...

Next.js multi zones with i18n and shared components

I am using Next.js' multi zone feature with a blog and web app so I can develop and deploy both apps independently. It was easy to set up by following their with zones example and I have set up a blog app at port 4200 and a web app at port 3000 , which is working fine. Unfortunately I am encountering some problems that aren't described anywhere in their documentation (as far as I can tell). First of all, I am also using their internationalised routing which is working fine, however when going to my blog app it appends the locale to the end of the URL. Imagine I am on localhost:3000/en and navigate to the blog app, then it will show localhost:4200/blog/en instead of localhost:4200/en/blog . Is there any way around this (e.g. by using rewrites)? Secondly, I am working in a monorepo and have shared components between both apps, such as the header and footer, which obviously includes navigation. When I am on the blog and want to navigate to e.g. the /about page, then it wil...

Tasks restores after deletion

I added 3 tasks, for example "Task1", "Task2", "Task3", then remove one of them, pushing on recyckle bin, task will be removed, BUT! When I add new task "Task4", removed task will be restored too. How to fix it please, than removed item will not be restored, with an explanation if possible? Thank you. 'use strict'; const headerInput = document.querySelector('.header-input'); const todoControl = document.querySelector('.todo-control'); const todoList = document.querySelector('.todo-list'); const todoCompleted = document.querySelector('.todo-completed'); const todoData = []; const render = function() { todoList.textContent = ''; todoCompleted.textContent = ''; todoData.forEach(function(item){ const li = document.createElement('li'); li.classList.add('todo-item'); li.innerHTML = '<span class="text-todo">' + item.v...

Collect link within an attribute with CheerioGS

In my attempt the return was null , I would like some help to try to understand what I am doing wrong or if it is really impossible to get this attribute from the page CheerioGS documentation: https://github.com/tani/cheeriogs Google App Script Library ID for CheerioGS : 1ReeQ6WO8kKNxoaA_O0XEQ589cIrRvEBA9qcWpNqdOP17i47u6N9M5Xh0 Link to colect image: https://t.me/ZoeiraFC/14043 Link I want to collect: https://cdn4.telesco.pe/file/Rmk5riA7iHYT59OoAOG3afISAZEthDoUkZXPmjxGEA1edhlm0eoWda62pM72yfBplB6ifJhyjykRiScihGiA_Lu_Aj4DTUqGauvdC4G8tjqNo0qeykvBBzXq5vaWOiMR3NSoCPPK9Z7q5CsllofpWzC6TV1DCpbbfIh-4qTAw2Kotf2nogMmD2KQTmhchqxPLYU-GqqwT82ypCFZKWA7NSw-AHL4BVtVzpwYbyTB421yxu4vWbJAWITrK-3EXbQARp6Ni9VDTMDAE3BdH4hFWOftmvlHmFiJlGcltX_ma46K5ancpKnKh8x4xH8GxYBScjAVCgvgd3ozsB000sgoYw.jpg Code I tried to use to scrape the attribute: function urltelegram() { var url = 'https://t.me/mattosxperiences/16122'; const contentText = UrlFetchApp.fetch(url).getContentText(); const $ ...

my state change when I set it, but my other component which use this state value through the react context don't show the state with the new result

I have a state being declared inside a context provider and one component A set this state and other component B just read... but when I change the state with the component A, the component B doesn't show the new value, keep showing the initial value! how I solve that, please? context file: export const SearchContext = React.createContext(); export const SearchProvider = (props) => { const [searchInput, setSearchInput] = useState({ content: "Matrix", }); return ( <SearchContext.Provider value=> {props.children} </SearchContext.Provider> ); }; form component(component A in the question): export default () => { const history = useHistory() **const {searchInput, setSearchInput} = React.useContext(SearchContext);** function search (e) { e.preventDefault(); history.push('/resultado-de-busca') const searchContent = document.querySelector(`[data-input-search]`).value; setSearchInp...

Spawning top with arguments and parsing with grep

I want to spawn top with a few arguments to get the current cpu load & usage. If I type the full command on my ssh session top -bn1 | grep "Cpu(s)\|top -" , I get the complete and working response. But how is the correct way to spawn this command with execFile ? This is what I want to do: import childProcess from 'child_process' import util from 'util' const execFile = util.promisify(childProcess.execFile) async function getData() { // Not working const command = 'top -bn1 | grep "Cpu(s)\|top -"' const args = [] // Also tried this const command = 'top' const args = ['-bn1 | grep "Cpu(s)\|top -"'] const { stdout } = await execFile(command, args, { maxBuffer: 1000 * 1000 * 10 }) console.log(stdout) } getData() But the spawn will fail with the following error: Error: spawn top -bn1 | grep "Cpu(s)|top -" ENOENT at Process.ChildProcess._handle.onexit (no...

How can I solve login error on discord.js

const {Client, Intents} = require('discord.js'); const { token } = require('./config.json'); const client = new Client({ intents: [Intents.FLAGS.GUILDS] }); client.once('ready', () => { console.log('Ready!'); }); client.login(token); I have this code, every time i try to run it returns me the same error: (node:13284) UnhandledPromiseRejectionWarning: ReferenceError: AbortController is not defined at RequestHandler.execute (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\rest\RequestHandler.js:172:15) at RequestHandler.execute (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\rest\RequestHandler.js:176:19) at RequestHandler.push (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\rest\RequestHandler.js:50:25) at async WebSocketManager.connect (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\client\websocket\WebSocketManager.js:128:9) at async Client.login (C:\Users\Luis\Vaina...