How do I fix reviews not showing on my website? Posted: 16 Dec 2021 10:54 AM PST I need to show reviews on products on my website. Due to a theme issue I need to add php code to my functions.php to achieve this. The problem is the file will not save and returns an error. However the reviews will show. The error is "Your PHP code changes were rolled back due to an error on line 120 of file wp-content/themes/oceanwp-child-theme-master/functions.php. Please fix and try saving again. syntax error, unexpected '<', expecting end of file" When I fix it by removing "<?php" the file saves but the reviews stop showing. Any ideas on what to do? Please treat me as a total noob!! this is the code function add_contact_form() { global $product; if(!$product->is_in_stock( )) { echo do_shortcode('[wpforms id="3244"]'); } } <?php /** * Enable reviews for all WC Products. */ add_action('admin_init', function() { $updated = 0; $query = new \WP_Query([ 'post_type' => 'product', 'posts_per_page' => -1, 'comment_status' => 'closed', ]); if($query->have_posts()) { while($query->have_posts()) { $query->the_post(); if(wp_update_post([ 'ID' => get_the_ID(), 'comment_status' => 'open', ])) { $updated++; } } wp_reset_postdata(); } add_action('admin_notices', function() use ($updated) { printf( '<div class="notice notice-info is-dismissible"><p>Enabled reviews for %d products.</p></div>', (int)$updated ); }); }); It starts at <?php, the lines before that are the end of the previous function which is working fine. |
Replacing / Swapping a Java class in Java agent instrumentation Posted: 16 Dec 2021 10:54 AM PST I've read this post which does the bytecode instrumentation in a "line by line" approach. It's clumsy and bug-prone. I wonder if Javassit supports "replacing" or "swapping" a class with an instrumented class. I see the redefineClasses method but I'm not sure it's used for that purposes, plus I can't find any examples around that. I appreciate if anyone in SO can give me an example on using redefineClasses in Javassist My goal is to use Java instrumentation to extract some meaningful data inside multiple Java classes and methods, much more than just printing start/end time in those examples. That's why I think "swapping a Java class" approach is more efficient during development. What do you guys think and recommend? Thank you. |
How can I use GCP project from environment variable in gcp_compute dynamic inventory? Posted: 16 Dec 2021 10:53 AM PST For my ansible playbooks I use dynamic invenotory gcp_compute. But I don't want define projectID and region in this file, I want read it from environment variables. In ansible-playbook I can use lookup('env', 'FOO_BAR') , and it works. But in invetory - do not. This guide says, that is possible to use some variables. I tryed it - it works, but there are not variables for project and region. (I also tryed use somethink like GCP_PROJECT or GCP_PROJECT_ID , but this is not work). |
(PYTHON) How do I solve this? I need a counter for each time my function is repeated Posted: 16 Dec 2021 10:54 AM PST I'm new to python, I'm building code for my project and I need that every time my iniciobot() function is repeated, it's counted and shown on my tkinter screen. I tried to do it using a global variable contagem, but nothing happens. How do I solve this? If anyone can help me I appreciate it. contagem = 0 def iniciobot(): global contagem contagem += 1 class InitBot1v: # a partir dessa classe pode começar a repetição for InitBot1v in range(3): driver.get('https://conta.olx.com.br/anuncios/publicados') time.sleep(3) driver.find_element_by_xpath('//*[@id="main-page-content"]/div[1]/div[1]/header/div[3]/div[2]/a').click() try: element = WebDriverWait(driver, 15).until( ec.presence_of_element_located((By.XPATH, '//*[@id="input_subject"]')) ) finally: driver.find_element_by_xpath('//*[@id="input_subject"]').send_keys(random.choice(olxlist.lista_compras)) driver.find_element_by_xpath('//*[@id="input_body"]').send_keys(olxdescricao.lista_venda) driver.find_element_by_xpath('//*[@id="category_item-1000"]').click() driver.find_element_by_xpath('//*[@id="category_item-1100"]').click() time.sleep(2) driver.find_element_by_xpath( '//*[@id="root"]/div[3]/form/div[1]/div/div[1]/div[3]/div[1]/div/div[1]/label/span').click() driver.find_element_by_xpath('//*[@id="size"]').send_keys('1000') driver.find_element_by_xpath('//*[@id="re_land_type"]').click() driver.find_element_by_xpath('//*[@id="re_land_type"]/option[2]').click() driver.find_element_by_xpath('//*[@id="price"]').send_keys('40000') time.sleep(4) pyautogui.click(1380, 447) # 1600x900 - x,y (1380, 447) click na tela da olx para fazer scroll pyautogui.scroll(-2000) time.sleep(2) class pegar_pasta: pyautogui.click(89, 879) # click no gerenciador de arquivos para ir na foto 1600x900 - x,y (89, 879) time.sleep(0.2) pyautogui.click(269, 801) # click na foto para fazer a seleção e os dois 'down' aqui dbaixo é pra n repetir as fotos 1600x900 - x,y (269, 801) pyautogui.keyDown('down') pyautogui.keyDown('down') time.sleep(0.1) pyautogui.keyDown('Shift') # segurar para selecionar as 3 fotos time.sleep(0.5) pyautogui.keyDown('down') # esses 2 'down' é pra selecionar as fotos pyautogui.keyDown('down') pyautogui.keyUp('Shift') # soltar o shift da seleção das fotos time.sleep(1) class enviar_foto: pyautogui.mouseDown() pyautogui.moveTo(212, 879) # 1600x900 - x,y (212, 879) time.sleep(0.5) pyautogui.moveTo(212, 870, 0.2) # 1600x900 - x,y (212, 870, 0.2) time.sleep(0.2) pyautogui.moveTo(190, 231, 1) # 1600x900 - x,y (190, 231, 1) time.sleep(0.2) pyautogui.mouseUp() time.sleep(0.2) driver.find_element_by_xpath('//*[@id="zipcode"]').send_keys(random.choice(olxcep.lista_cep)) time.sleep(0.3) driver.find_element_by_xpath('//*[@id="ad_insertion_submit_button"]').click() time.sleep(3) driver.find_element_by_xpath('//*[@id="ad_insertion_submit_button"]').click() time.sleep(10) def mostrar_quantidade(): print(contagem) janela = Tk() janela.configure(border=40, background='white') janela.title('Olx Bot Anúncio') texto_espaco = Label(janela, text=contagem) texto_espaco.pack(side=TOP) janela.mainloop() |
Configuring VSCode to debug tools nested in a TypeScript app Posted: 16 Dec 2021 10:53 AM PST I'm trying to use VSCode to debug TypeScript files found within a larger app having dependencies on modules of that larger app, but I'm encountering errors such as: - SyntaxError: Cannot use import statement outside a module; OR
- TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"
I've written an Electron/Svelte/TypeScript app for which I've partitioned core backend code into its own modules having no dependencies on Electron or Svelte. I've put all those modules in a directory I call 'kernel'. I also have a set of tools that run standalone from the app that depend on these core modules. I've put these in a directory called 'tools'. I can easily compile and run all my tools from the command line, but I have not been able to figure out how to run the tools from within the VSCode debugger. My directory structure is basically this: .vscode/ launch.json build/ node_modules/ public/ src/ backend/ frontend/ tsconfig.json kernel/ tools/ tool-a.ts tool-b.ts electron.ts package.json rollup.config.js tsconfig.json I want to pull one of the tools (e.g. 'tool-a.ts') into VSCode, set breakpoints, and debug it. I have not yet found a way to do that. The error I get depends on the configuration I try. But first, here's the configuration that I don't believe I should be changing, as the Electron app works just fine. // package.json { "name": "ut-spectool", "version": "0.1.0", "private": true, "main": "./build/electron.js", "scripts": { "build": "tsc && rollup -c", "build-client": "run-s build client", "build-backend": "tsc", "check": "svelte-check --tsconfig ./tsconfig.json", "server": "kill $(lsof -ti:5000) 2>/dev/null; rollup -c -w", "start": "sirv public --no-clear --single", "client": "tsc && cross-env NODE_ENV=development electron .", "dist:mac": "tsc && rollup -c && electron-builder build --mac --publish never", "test": "jest", "prettier": "prettier --config .prettierrc 'src/**/*.ts' --write" }, "devDependencies": { ... }, "dependencies": { ... }, "build": { ... } } // top-level tsconfig.json { "compilerOptions": { "sourceMap": true, "sourceRoot": "build", "target": "ESNext", "module": "commonjs", "outDir": "build", "stripInternal": true, "strict": true, "pretty": true, "moduleResolution": "node", "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "noEmitOnError": true, "allowSyntheticDefaultImports": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "esModuleInterop": true, "isolatedModules": true }, "include": [ "src/**/*" ], "exclude": [ "node_modules/*", "build/*", "public/*", "src/frontend/*" ] } Here is one of the versions of launch.json I've tried, but "Launch Current Tool" gives me the exception, SyntaxError: Cannot use import statement outside a module , and the warning, (node:75650) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension : { "configurations": [ { "name": "Launch Current Tool", "program": "${file}", "request": "launch", "env": { "NODE_ENV": "development" }, "console": "integratedTerminal", "preLaunchTask": "npm: build-backend", "outFiles": ["${workspaceFolder}/build/**/*.js"], "sourceMaps": true, "resolveSourceMapLocations": [ "${workspaceFolder}/build/**", "!**/node_modules/**" ], "skipFiles": [ "${workspaceFolder}/node_modules/**/*.js", "<node_internals>/**" ], "smartStep": true, "type": "pwa-node" }, { "type": "node", "name": "vscode-jest-tests", "request": "launch", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "disableOptimisticBPs": true, "program": "${workspaceFolder}/node_modules/jest/bin/jest", "cwd": "${workspaceFolder}", "args": [ "--runInBand", "--watchAll=false" ], "sourceMaps": true, "skipFiles": [ "${workspaceFolder}/node_modules/**/*.js", "<node_internals>/**/*.js" ], "smartStep": true } ] } (Mind you, debugging jest tests from within VSCode works just fine.) Adding "type": "module" to package.json breaks Electron, so that's not an option. If I drop the following package.json into the tools folder... { "type": "module" } ... then attempting to debug tool-a.ts yields the error, TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/joe/repos/ut-spectool/src/tools/tool-a.ts . Hardcoding a "build" property in package.json for just one tool yields the same error. If I change the value of program in launch.json to the following... "program": "${workspaceFolder}/build/tools/${fileBasenameNoExtension}.js", ... then when I debug via "Launch Current Tool", the program runs just fine in VSCode, displaying output in the VSCode terminal, but it ignores my breakpoints. Other experiments I've done with launch.json have had no significant effect. For example, changing "type": "pwa-node" to "type": "node" (as used to debug with jest), does not change anything. I've also tried dropping a tsconfig.json into the tools folder and setting the "module" compiler option to "ESNext" and "ES6". How do I get my nested tools running in the VSCode debugger? |
Adding a different value to a list based on number of iteration in a for loop. [Website parsing] Posted: 16 Dec 2021 10:52 AM PST i'm new to Python and I am having trouble with a website parsing project. This is the code I managed to write: import requests from bs4 import BeautifulSoup import pandas as pd pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.width', None) pd.set_option('display.max_colwidth', -1) import json #necessary lists url_list = [ "https://warframe.market/items/melee_riven_mod_(veiled)", "https://warframe.market/items/zaw_riven_mod_(veiled)" ] item_list = [] items_name = [] combined_data = [] iteration = 1 #looping for every url found in url_list for url in url_list: #requesting data r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") #splitting the last part of the url which has the name of the item that I want to insert in the dataframe name = url.split("/")[4] items_name.append(name) #Finding in the parsed HTML code where the JSON file starts ( it start from <script> n°2) results = soup.find_all('script')[2].text.strip() data = json.loads(results) combined_data.append(data) #combining all the data into one list #filtering only the users who sell the items and are either "ingame" or "online" for payload in combined_data[iteration]["payload"]["orders"]: if payload["order_type"] == "sell" and (payload["user"]["status"] == "online" or payload["user"]["status"] == "ingame"): p = payload item_list.append(p) #adding the items names to the item list ???? PROBLEM ????? item_list = [dict(item, **{'name':items_name[iteration]}) for item in item_list] #trying to change the list from where the data gets taken from and the items name ????? PROBLEM ???? iteration += 1 #creating a dataframe with all the values df = pd.DataFrame(item_list).sort_values(by=["platinum"]) What I'm trying to do and can't find a solution to, is to add to item_list the name of the item which the url refers to. e.g. | index | platinum | quantity| ... | items name (problematic column) | | -------- | -------------- |-----| ----|---- | 1 | 10 |1| ...| melee_riven_mod_(veiled)| | 2 | 11 |1|...|zaw_riven_mod_(veiled)| | 3 | 12 |2|...|melee_riven_mod_(veiled)| | 4 | ... |...|...|zaw_riven_mod_(veiled)| But items name column has the same name for all the rows like this: index | platinum | quantity | ... | items name (problematic column) | 1 | 10 | 1 | ... | melee_riven_mod_(veiled) | 2 | 11 | 1 | ... | melee_riven_mod_(veiled) | 3 | 12 | 2 | ... | melee_riven_mod_(veiled) | 4 | ... | ... | ... | melee_riven_mod_(veiled) | So i wanted to ask what am I doing wrong in the for loop? It iterates 2 times which is the amount of urls in the url_list but it doesn't change the name of the item. What am i not seeing? Thank you in advance. |
find object if attribute not exists and add that attribute with value Posted: 16 Dec 2021 10:54 AM PST I have array of objects like below: checklist= [ { "participantId": 13, "rankStatus": "participated", "rank": 3, "comment": "my comment", "horse_name": "test232 fdfgdg", "country": "Afghanistan", "life_number": null }, { "participantId": 12, "rankStatus": "eliminated", "comment": null, "horse_name": "test horse", "country": "Algeria", "life_number": "234234" }, { "participantId": 11, "rankStatus": null, "rank": null, "comment": null, "horse_name": "tesdfs", "country": "Afghanistan", "life_number": null }, { "participantId": 10, "rankStatus": null, "comment": null, "horse_name": "nam horse", "country": "India", "life_number": "fh345" } ]; In above array of objects, I need to add rank=0 to the objects where rank is not present. I tried like below, but its not working. checklist.filter(x => !x.hasOwnProperty('rank') ).map(x => x.rank == 0); What is right way of doing this? Please help and guide. Thanks |
refresh data after an insert with tkinter, python Posted: 16 Dec 2021 10:53 AM PST newbie here, im afraid too new to even search properly about it. i made a gui in tkinter to enter people extra hours and display last registers as i was asked to do. (we had a excel file to do it but it was giving too much trouble) [it looks like this] what i want to add now is that, when an entry is added (1) the table shown is refreshed inmediatly after (2) as a way to check the last entry. but i have no idea how! been searching a while and i couldnt figure it out... code looks like this import tkinter as tk from tkinter import * from tkinter import ttk, messagebox from tkcalendar import * import pyodbc import pandas as pd import numpy from datetime import datetime conn = pyodbc.connect('Driver={SQL Server};''Server=RCL-SUP034\SQLXLAB;''Database=Marcaciones;''username=admin;''password:admin;') cursor = conn.cursor() root = Tk() root.title("Carga de horas extras") root.geometry("780x600") root.resizable(False,False) cal = Calendar(root, locale='en_US', date_pattern='dd.mm.y',selectmode="day", year=2021) cal.place(x=330, y=50) def obtener_fecha(): my_label.config(text=cal.get_date()) boton_calendario = ttk.Button(root, text="Seleccionar Fecha", command=obtener_fecha) boton_calendario.place(x=150 ,y=50) my_label = Label(root, text="") my_label.place(x=165 ,y=82) codigo_entry = Entry(root, width=20) codigo_entry.place(x=115, y=10) # OK lista_desplegable = ttk.Combobox(root,width=10, state="readonly") lista_desplegable.place(x= 290, y=10) horas_opcion = [0,0.50,1,1.50,2,2.50,3,3.50,4,4.50,5,5.50,6,6.50,7,7.50,8,8.50,9,9.50,9.99] lista_desplegable['values']=horas_opcion codigo_entry_label = Label(root, text="Codigo Trabajador").place(height=20, width=100, x= 10,y=10) # OK horas_entry_label = Label(root, text="Horas extras") horas_entry_label.place(height=20, width=75, x= 200,y=10) # OK insert_hhee = '''INSERT INTO tbl_marcas (codigo,fecha,hhee) VALUES (?,?,?)''' consulta_horas= '''SELECT top 10 codigo, operario, hhee, fecha FROM registros where hhee <> 0 order by id desc''' todos_operarios = '''SELECT codigo from tbl_operarios''' respaldo_hhee = '''EXEC tabla_respaldo''' def agrega_cal(): cursor.execute(insert_hhee, (codigo_entry.get(),cal.get_date(), lista_desplegable.get())) conn.commit() codigo_entry.delete(0, END) refresco() def respaldo(): try: validacion = messagebox.askyesno(message="Se respaldaran todos los datos ingresados a la fecha",title="respaldo") if validacion == True: cursor.execute(respaldo_hhee) conn.commit() messagebox.showinfo(message="Respaldo exitoso") else: messagebox.showerror(message="Respaldo cancelado", title="aviso") except: messagebox.showerror(message="Respaldo cancelado", title="aviso") agrega_cal_boton = ttk.Button(root, text="Agregar registro", command=agrega_cal).place(height=30, width=105, x=15 ,y=50) respaldo_boton = ttk.Button(root, text="Respaldar datos",command=respaldo).place(height=30, width=110, x=620,y=10) frame1 = tk.LabelFrame(root, text="Ultimos registros con horas extras") frame1.place(height=200, width=750, rely=0.40, relx=0) df1 = pd.read_sql_query(consulta_horas, conn) tv1 = ttk.Treeview(frame1) tv1.place(relheight=1, relwidth=1) treescrolly = tk.Scrollbar(frame1, orient="vertical", command=tv1.yview) treescrollx = tk.Scrollbar(frame1, orient="horizontal", command=tv1.xview) tv1.configure(yscrollcommand=treescrolly.set) treescrollx.pack(side="bottom", fill="x") treescrolly.pack(side="right", fill="y") tv1["column"] = list(df1.columns) tv1["show"] = "headings" for column in tv1["columns"]: tv1.heading(column, text=column) df_rows = df1.to_numpy().tolist() for row in df_rows: tv1.insert("", "end",values=row) s = ttk.Style(root) s.theme_use('clam') root.mainloop() no idea how to refresh data shown it tbh btw i know the very basics of python.. im aware my path has just begun :d |
Searching for specific characters then appending Posted: 16 Dec 2021 10:53 AM PST I basically want my code to be able to search for a specific character in a list and then append it to another list depending on whether the letter were found. this is my code so far but the lists aren't appending properly list2=[apple,bannana,lychee,pear,red] list3=[] list4=[] j=0 for word in list2[:]: if 'R'or'Y'or'I' in word: list3.append(list2[j]) j+=1 else: list4.append(list2[j]) j+=1 print(list3) print(list4) |
How to close modal window after clicking a link Posted: 16 Dec 2021 10:53 AM PST My website uses a full screen popup for the navigation. (Currently I'm using ReactModal but I had the same issue with a home-made modal component I was previously using). When a user clicks a link in the navigation using the NextJS Link component, the popup doesn't automatically close—they have to close it manually to show the new page. I made an onClick event to close the navigation popup, but there is often a brief moment after the nav closes and before the next page loads which is confusing to the user. I think the issue is that when the app updates to the new page, it doesn't re-mount the navigation component, so the nav component keeps the "open" state. Is there a way to make it close the popup at the moment that the next page has loaded? Or maybe there is a more elegant solution to this that I'm not thinking of. |
Lifecycle OnLifecycleEven tis deprecated Posted: 16 Dec 2021 10:53 AM PST After updating lifecycle library to 2.4.0 Android studio marked all Lifecycle events as deprecated. @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun create() { tts = TextToSpeech(context, this) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun stopTTS() { tts?.stop() } Is there any equivalent replacement such as DefaultLifecycleObserver ? |
How to detect TCP Port Scan using python Posted: 16 Dec 2021 10:53 AM PST I am a newbie to network programming in python. I would like to know if there is any way that we can code in python to detect this kind of scan. I would like to build a open source project by using the method that you might suggest. Thanks in advance !! |
Is it possible to create an enum class which contains objects of another non-enum class in Java? Posted: 16 Dec 2021 10:53 AM PST For example, I have Subscriber class and its objects subscriber1 , subscriber2 , subscriber3 . Is it possible to create an enum that contains these objects? I'm trying to do this enum Subscribers{ subscriber1,subscriber2,subscriber3; } But I'm getting strings subscriber1 ,subscriber2 ,subscriber3 instead. I would appreciate any feedback |
Aggregate list on each lambda async execution [duplicate] Posted: 16 Dec 2021 10:54 AM PST To get the list of people in all de classrooms in different sections I use the following: public async Task<IEnumerable<Peeople>> GetAll() { var _sections= new List<string>() {"101", "102"}; var people = _sections.Select(async section => { var response = await SendRequestAsync<Classroom>(HttpMethods.GET, $"{section}/{_sectionUrl}"); return response?.PeopleList; //issue }); return await Task.WhenAll(people); } The object Classroom contains a property PeopleList that contains the list of people of the classroom. Can't compile this code: error CS0266: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable[]' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?) I need to be able to gather the list of people in the select in a way that I can aggregate the list with each iteration of the section. |
Databricks pyspark parallelize unzipping multiple files Posted: 16 Dec 2021 10:53 AM PST I'm trying to parallelize unzipping files stored in s3 in pyspark on Databricks. Unzipping in a for loop works as so: file_list = [(file.path, file.name) for file in dbutils.fs.ls(data_path) if os.path.basename(file.path).endswith(".zip")] # data_path is taken as a parameter file_names = [ff[1] for ff in file_list] for ff in file_list: dbutils.fs.cp(ff[0], "/FileStore/tmp/" + ff[1]) cmd = 'unzip /dbfs/FileStore/tmp/' + ff[1] os.system(cmd) dbutils.fs.cp("file:/databricks/driver/" + ff[1], data_path) dbutils.fs.rm("file:/databricks/driver/" + ff[1]) I'm trying to parallelize the unzip part. So after copying the files to "/FileStore/tmp/" I'm running: unzips = [file[1] for file in file_list] def f(x): os.system('unzip /dbfs/FileStore/tmp/' + x) sc.parallelize(unzips).foreach(f) The job runs but the files are not unzipped anywhere. |
Is it possible to change the sent file in discord python? Posted: 16 Dec 2021 10:53 AM PST I need to change embed with local file (photo) from my machine. To send embed, you need to send the file along with it, but it cannot be changed. When i try to do this: My Code: embed = discord.Embed(title = "Title here", description = "", timestamp = datetime.utcnow(), color = 0x26ad00) file = discord.File(f"images/{msg.id}.png") embed.set_image(url = f"attachment://{msg.id}.png") await msg.edit(file = file, embed = embed) I get the following error: TypeError: Object of type File is not JSON serializable There is no such error when using a link from the internet directly (without file from link). I think I need to upload my photos to the internet with a photo API or something else but it is very slow, is there a solution to this problem? |
How do you return a string? Posted: 16 Dec 2021 10:52 AM PST I am trying to return a string from a array with 4 hexadecimal values. I have a huge list of hex arrays and need to use it in multiple functions. That's why I want to create a function of comparing the hex arrays and return a string. int comparehex(byte hex[]){ char * buffer = new char [16]; byte hex1[4] = {0x4C, 0x79, 0x52, 0xA8}; byte hex2[4] = {0xC5, 0x86, 0xA4, 0xB5}; for (byte i = 0; i <=3; i++){ if (hex1[i] != hex[i]){ break; } if (i == 3){ return "string"; } } return false; } The code that I wrote won't even compile: main.cpp: In function 'int comparehex()': main.cpp:46:14: error: invalid conversion from 'const char*' to 'int' [-fpermissive] 46 | return "string"; | ^~~~~~~~ | | | const char* How can I return a string? |
Excel Power query removing rows took forever and intense memory usage Posted: 16 Dec 2021 10:52 AM PST Good day Friends, I have a Excel file, that I used Power query editor to pull multiple excel files (same format/columns) into one. I would like to create a new column to calculate the time different ( duration ) between a "FAULT" row and the "MSG" row that is below the "FAULT" row. to reduce data size, removing all the "MSG" rows that are not under "FAULT" rows. only keeping the "Fault" rows and the "MSG" that is directly underneath it. attached picture here so i did the following Step 1 : I added a Index column Step 2 : use M language to add another column to label the unwanted row. try if [alarm class] = #"Added Index" {[Index] - 1} [alarm class] then "delete" else "keep" otherwise null my query: let Source = Csv.Document(File.Contents("Y:\powerBI\Feng\RMG\ASC07L_20211123_1336.csv"),[Delimiter=",", Columns=7, Encoding=1252, QuoteStyle=QuoteStyle.None]), #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}, {"Column2", type datetime}, {"Column3", type text}, {"Column4", type text}, {"Column5", type text}, {"Column6", Int64.Type}, {"Column7", type text}}), #"Inserted Date" = Table.AddColumn(#"Changed Type", "Date", each Date.From([Column2]), type date), #"Renamed Columns" = Table.RenameColumns(#"Inserted Date",{{"Column3", "alarm ID"}, {"Column4", "alarm class"}}), #"Added Custom" = Table.AddColumn(#"Renamed Columns", "Custom", each if [alarm ID] = "CRN_ATOEXEINS" then 1 else if [alarm class] = "FAULT" then 1 else 0), #"Filtered Rows" = Table.SelectRows(#"Added Custom", each ([Custom] = 1)), #"Added Index" = Table.AddIndexColumn(#"Filtered Rows", "Index", 0, 1), #"Added Custom1" = Table.AddColumn(#"Added Index", "Custom.1", each try if [alarm class] = #"Added Index" {[Index] - 1} [alarm class] then "delete" else "keep" otherwise null), #"Filtered Rows1" = Table.SelectRows(#"Added Custom1", each ([Custom.1] = "keep")) in #"Filtered Rows1" However when i hit close and Load, the file size increases 100x, and the load time is unbearable. when it did finishes the render, the file size did shrink to its actual size, which is small then original because the removed columns. my question is, am I doing something wrong? is there a better way to do this to increase the querying speed? here i attach the link of the excel files, as well as the one that query them together(Book1.xlsx) for the purpose of fast turnaround, i only query 1 csv file into the book1.xlsx but i actually needed to query all csv file into book1.xlsx |
extract structured data from text files (awk ?) : missing fields must get default value Posted: 16 Dec 2021 10:53 AM PST I have 70k text files in subfolders I want to extract some data from, recursively, then – if possible – have output written in one tab delimited file for later spreadsheet processing. Files, coming from my wiki (I use PmWiki, which saves data in text files) are formatted this way when complete (unwanted data deleted for readability) : version= agent= author= charset= csum= ctime=1041379201 description= host= name=Name.12 rev=3 targets=Target.1,OtherTarget.23,Target.90 text= time= title=My title author: csum: diff: host: author: csum: diff: I would like to extract data delimited with = for fields named ctime name rev targets title (5 fields). My main issue is how to get data (keys ctime= rev= targets= name= title= ), plus having default values when some are missing ? I believe one has to test if each of the targeted key exists ; create it with default value if missing ; then extract the wanted fields values and finally tabulate the data. Expected output would be tab delimited ; missing data would be named something easy to catch later on. i.e., for full file given in example (tabs in place of spaces), output would give something like (ctime, rev, name, title, targets) : 1041379201 3 Name.12 my title Target.1,OtherTarget.23,Target.90 and, for not complete file (missing field, in line 1, is rev ; in line 2, rev and title) : 1041379201 XXX Name.12 my title Target.1,OtherTarget.23,Target.90 1041379201 XXX Name.12 XXX Target.1,OtherTarget.23,Target.90 Final project is to be able to extract data once a month, then have text file easy to use in spreadsheet, monthly updated. My less worst attempt is something like that (yet doesn't work at all, lacking if/else condition) : awk 'BEGIN { FS = "=" ;} /^ctime=/ { print $2 next } /^rev=/ { print $2 next} /^name=/ { print $2 next} /^title=/ { print $2 next} /^targets=/ { print $2 next}' Here it is an original PmWiki file (in that case I still would like to extract ctime name rev targets title (and have default values for missing fields, ctime and title ) : version=pmwiki-2.2.64 ordered=1 urlencoded=1 author=simon charset=UTF-8 csum=add summary name=Main.HomePage rev=203 targets=PmWiki.DocumentationIndex,PmWiki.InitialSetupTasks,PmWiki.BasicEditing,Main.WikiSandbox text=(:Summary:The default home page for the PmWiki distribution:)%0aWelcome to PmWiki!%0a%0aA local copy of PmWiki's%0adocumentation has been installed along with the software,%0aand is available via the [[PmWiki/documentation index]]. %0a%0aTo continue setting up PmWiki, see [[PmWiki/initial setup tasks]].%0a%0aThe [[PmWiki/basic editing]] page describes how to create pages%0ain PmWiki. You can practice editing in the [[wiki sandbox]].%0a%0aMore information about PmWiki is available from [[http://www.pmwiki.org]].%0a time=1400472661 |
How to deal with [a,b|c] format lists? Posted: 16 Dec 2021 10:53 AM PST I created a simple parser for subset of Clojure language. For some reason it returns me a list in format [a,b,c|d], not in format [a,b,c,d]. Morover member(X, List) doesn't work with such format of list properly, i.e. member(X, [a,b,c|d]). X = a ; X = b ; X = c. The question is how should I improve my code to fix this problem and get list in usual format ? Or maybe there is a way to transform [a,b,c|d] -> [a,b,c,d] ? You can call e.g. main. [(concat x) (lambda x (inc (inc x)))] And get: expr([expr([expr(at(id([c,o,n,c,a,t])))|expr(at(id([x])))])|expr([expr(at(id([l,a,m,b,d,a]))),expr(at(id([x])))|expr([expr(at(id([i,n,c])))|expr([expr(at(id([i,n,c])))|expr(at(id([x])))])])])]) Code: mydelimiter --> delimiter. mydelimiter --> delimiter, mydelimiter. delimiter --> [',']. delimiter --> ['\n']. delimiter --> ['\t']. delimiter --> ['\s']. specsymbol('+') --> ['+']. specsymbol('-') --> ['-']. specsymbol('>') --> ['>']. specsymbol('<') --> ['<']. specsymbol('=') --> ['=']. specsymbol('*') --> ['*']. specsymbol('_') --> ['_']. snum(0) --> ['0']. snum(1) --> ['1']. snum(2) --> ['2']. snum(3) --> ['3']. snum(4) --> ['4']. snum(5) --> ['5']. snum(6) --> ['6']. snum(7) --> ['7']. snum(8) --> ['8']. snum(9) --> ['9']. numb([A]) --> snum(A). numb([A|B]) --> snum(A), numb(B). mynumber(num(X)) --> numb(X). mystring(str([])) --> quotesymbol, quotesymbol. mystring(str(S)) --> quotesymbol, anychars(S), quotesymbol. quotesymbol --> ['\"']. anychar(A) --> [A], {A \== '\"'}. anychars([A]) --> anychar(A). anychars([A|B]) --> anychar(A), anychars(B). identifier(id(I)) --> id_start_spec(I); id_start_letter(I). letter(L) --> [L], {is_alpha(L)}. id_start_letter([L]) --> letter(L). id_start_letter([L|I]) --> letter(L), ids_l(I). ids_l([I]) --> letter(I); snum(I); specsymbol(I). ids_l([I|Is]) --> (letter(I); snum(I); specsymbol(I)), ids_l(Is). id_start_spec([S]) --> specsymbol(S). id_start_spec([S|I]) --> specsymbol(S), ids_s(I). ids_s([I]) --> snum(I); specsymbol(I). ids_s([I|Is]) --> (snum(I); specsymbol(I)), ids_s(Is). keyword(kw([C|K])) --> mycolonsymbol(C), id_start_letter(K). mycolonsymbol(':') --> [':']. myatom(at(A)) --> mynumber(A); mystring(A); identifier(A); keyword(A). expression(expr(S)) --> myatom(S). expression(expr(S)) --> r_br_expression(S). expression(expr(S)) --> s_br_expression(S). expression(expr(S)) --> f_br_expression(S). r_br_expression(S) --> r_openbracketsymbol, expressions(S), r_closedbracketsymbol. expressions(S) --> expression(S). expressions([S|SS]) --> expression(S), mydelimiter, expressions(SS). r_openbracketsymbol --> ['(']. r_closedbracketsymbol --> [')']. s_br_expression(S) --> s_openbracketsymbol, expressions(S), s_closedbracketsymbol. s_openbracketsymbol --> ['[']. s_closedbracketsymbol --> [']']. f_br_expression(S) --> f_openbracketsymbol, expressions(S), f_closedbracketsymbol. f_openbracketsymbol --> ['{']. f_closedbracketsymbol --> ['}']. main :- read_string(user_input, "\n", "", _, StrIn), atom_chars(StrIn, L), phrase(expression(T), L), writeln(T), !. |
Winston@3.3.3 not logging to my logfiles when I terminate the node process in case an uncaught exception arises Posted: 16 Dec 2021 10:52 AM PST terminating the node process stops winston@3.3.3 from logging to my log files, but it logs in the console. Without terminating the process (process.exit(1)), winston works fine. const { createLogger, format, transports } = require("winston"); require("winston-mongodb"); const logger = createLogger({ level: "info", // ... transports: [ new transports.File({ filename: "errorLogs.log", level: "error" }), new transports.File({ filename: "logfile.log" }), new transports.Console(), ], }); module.exports = function () { process.on("uncaughtException", (ex) => { console.log("WE GOT AN UNCAUGHT EXCEPTION"); logger.log("error", ex.message, ex); process.exit(1) }); process.on("unhandledRejection", (ex) => { console.log("WE GOT AN UNHANDLED REJECTION"); logger.log("error", ex.message, ex); process.exit(1) }); }; module.exports.logger = logger; |
Filter(search) from parent table and child table at the same time Posted: 16 Dec 2021 10:53 AM PST I have two tables posts as a parent and 'posts_tags' as a child, I want to search by two fields year from the post table and also tag_id from posts_tags , how to add search query for child table in our query. My Models Post.php <?php namespace App\Models\Posts; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { use HasFactory; protected $table="posts"; /** * The attributes that are mass assignable. * * @var string[] */ protected $guarded = []; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = []; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = []; //---Get Post Tags public function PostTags() { return $this->hasMany('App\Models\Posts\PostTag'); }//---End of Function PostTags } PostTag.php <?php namespace App\Models\Posts; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class PostTag extends Model { use HasFactory; protected $table="posts_tags"; //protected $primaryKey = 'post_tag_id'; /** * The attributes that are mass assignable. * * @var string[] */ protected $guarded = []; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = []; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = []; //---Get The Post public function GetPost() { return $this->belongsTo('App\Models\Posts\Post'); }//---End of Function GetPost } My View <form action="{{ route('movies.movie_search') }}" method="GET"> @csrf <select name="tag" class="select"> <option value="" selected="selected"> @lang('movies.movie_all') </option> @if ($tags) @foreach ($tags AS $tag) <option value="{{ $tag->id }}">{{ $tag->name }}</option> @endforeach @endif </select> <select name="year" class="select"> <option value="" selected="selected"> @lang('public.public_year') </option> @php $date = date('Y'); for ($i = $date; $i > 1970; $i--) { echo "<option value=".$i.">".$i."</option>"; } @endphp </select> <button type="submit" name="" class="filter"> @lang('public.public_filter') </button> </form> web.php Route::prefix('/movies')->group(function (){ Route::get('/search', [MovieController::class, 'MoviesDataSearch'])->name('movies.movie_search'); }); MovieController.php <?php namespace App\Http\Controllers\Movies; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Crypt; use App\Models\Posts\Post; use App\Models\Posts\PostTag; class MovieController extends Controller { //---Filter Movies By Tags & Year public function MoviesDataSearch(Request $request) { if (empty($request)) { return Post::where('post_type', "movie")->where('is_delete', "0")->orderBy('id', 'DESC')->Paginate(12); } else { $movies = Post::where('post_type', "movie") ->where('is_delete', "0") ->where('year', 'like', '%'.$request->year.'%') //---How to add a query for posts_tags /*->whereHas('posts_tags', function ($posts_tags) use ($request) { $posts_tags->where('tag_id', 'like', '%'.$request->tag.'%'); })*/ ->orderBy('id', 'DESC') ->Paginate(2); return $movies->appends($request->all()); } }//---End of Function MoviesDataSearch } |
Svelte bubble sort visualization wont update dom Posted: 16 Dec 2021 10:53 AM PST I want to make a bar visualisation of many sorting algorithms, I started will bubble sort for simplicity sake. I need to update the dom as it switches the items, but it only updates it after all the elements are sorted. I looked this up and everything said to use tick, but I still can't get it to work, here is my code: <script> import { tick } from 'svelte'; let arr = []; async function bubbleSort () { let len = arr.length; for (let i = 0; i < len; i++) { for (let j = 0; j < len; j++) { if (arr[j] > arr[j + 1]) { let tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; await tick(); setTimeout(() => { console.log("World!"); }, 2000); } } } console.log(arr) } function shuffle () { arr = []; for (let i = 0; i < 100; i++) { let num = Math.random()*10+1; arr.push(Math.floor(num)); } console.log(arr) } console.log(bubbleSort(shuffle())) </script> <main> <button on:click={shuffle}>Shuffle</button> <button on:click={bubbleSort}>Sort</button> {#each arr as el, i} <div id={i} style="position: relative;height: {el*100}px;"></div> {/each} </main> <style> div { background: #000000; width: 5px; display: inline-block; margin: 0 1px; } </style> I am sorry if this is simple but I am very new to svelte, js and web dev as a whole. Thank you! |
Page does not load properly but only in Firefox Posted: 16 Dec 2021 10:53 AM PST When this page is loaded in Firefox, it takes an absurdly long time for most of the content to appear whereas it is almost instantaneous in Chrome and Safari. I have never seen anything like this so I am not sure what specific code issue to look for. Any thoughts? |
AvalonDock: Binding to LayoutAnchorablePane position? Posted: 16 Dec 2021 10:53 AM PST I am creating a custom theme for my WPF application that uses the AvalonDock docking framework. I have already opened a GitHub issue for my question on the AvalonDock repo but I'm hoping I can get an answer faster here (and ready to put a bounty on this ASAP). In my custom theme I have moved the tab items for the LayoutAnchorablePane to stack vertically on the left side, and the pane uses a Grid with column sizes Auto, *, Auto . I would like to write a Trigger for the style that moves the tabs from the left column to the right column when the LayoutAnchorablePane is attached to the right side of the root layout panel. (So that the tabs are always on the outside) Here is the relevant section of my theme's XAML that I am trying to put the trigger on. This is almost identical to the LayoutAnchorablePaneControl template from the generic.xaml style in AvalonDock: <Grid ClipToBounds="true" KeyboardNavigation.TabNavigation="Local" SnapsToDevicePixels="true"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <!-- Following border is required to catch mouse events --> <Border Grid.ColumnSpan="3" Background="Transparent" /> <StackPanel x:Name="HeaderPanel" Width="40" Grid.Column="0" Panel.ZIndex="1" IsItemsHost="true" KeyboardNavigation.TabIndex="1" /> <Border x:Name="ContentPanel" Grid.Column="1" Background="Transparent" BorderThickness="2" BorderBrush="{StaticResource PrimaryBrush}" KeyboardNavigation.DirectionalNavigation="Contained" KeyboardNavigation.TabIndex="2" KeyboardNavigation.TabNavigation="Cycle"> <ContentPresenter x:Name="PART_SelectedContentHost" ContentSource="SelectedContent" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /> </Border> </Grid> <ControlTemplate.Triggers> <DataTrigger Binding="{Binding ??? }"> <Setter TargetName="HeaderPanel" Property="Grid.Column" Value="2"/> </DataTrigger> </ControlTemplate.Triggers> As far as I can tell, there is no property on LayoutAnchorablePane or any of its interfaces that exposes which side of the layout the pane is on. So I'm lost for what I can put in {Binding ??? } in my DataTrigger. It seems like I need to implement the property myself and use my own builds of AvalonDock. I would like to avoid this if it's at all possible; So maybe there's some clever MarkupExtension or Converter idea I could implement in my own code? Maybe my assumption that this can be done with DataTrigger can be challenged too. I would be happy to use a completely code-behind solution for this. |
How can I display Gdiplus bitmap in PixtureBox? Posted: 16 Dec 2021 10:53 AM PST How does one display Gdiplus Bitmap with PixtureBox? Is it possible? If so, how? Here's my code to show what I've tried so far: Gdiplus::Bitmap* m_pBitmap; IStream* istream; HRESULT res = CreateStreamOnHGlobal(NULL, true, &istream); GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); { HDC scrdc, memdc; HBITMAP hBitmap; scrdc = ::GetDC(0); int Height = GetSystemMetrics(SM_CYSCREEN); int Width = GetSystemMetrics(SM_CXSCREEN); memdc = CreateCompatibleDC(scrdc); hBitmap = CreateCompatibleBitmap(scrdc, Width, Height); HBITMAP hOldBitmap = (HBITMAP)SelectObject(memdc, hBitmap); BitBlt(memdc, 0, 0, Width, Height, scrdc, 0, 0, SRCCOPY); Gdiplus::Bitmap bitmap(hBitmap, NULL); CLSID clsid; GetEncoderClsid(L"image/jpeg", &clsid); bitmap.Save(L"screen.jpeg", &clsid, NULL); bitmap.Save(istream, &clsid, NULL); Gdiplus::Bitmap bmp(istream, NULL); bmp.Save(L"test.jpeg", &clsid, NULL); Gdiplus::Graphics::FromImage(m_pBitmap); pictureBox1->Image = bmp; //here, I dont know how to show in picturbox Gdiplus bitmap DeleteObject(memdc); DeleteObject(hBitmap); ::ReleaseDC(0, scrdc); } GdiplusShutdown(gdiplusToken); |
How to get Hikvision DeepinViews license plate number from URL? Posted: 16 Dec 2021 10:52 AM PST I cant find the solution anywhere and mine doesn't seem to work. I just want to see the last plate string in the browser,or the few last plates,doesn't matter. http://login:password@MY.IP/ISAPI/Traffic/channels/1/vehicleDetect/plates/ <AfterTime><picTime>2021-12-09T09:07:15Z</picTime></AfterTime> I do have a plate taken exactly at the time im using in pictime,but the result im getting is; This XML file does not appear to have any style information associated with it. The document tree is shown below. <ResponseStatus xmlns=" http://www.hikvision.com/ver20/XMLSchema " version="2.0"> <requestURL> /ISAPI/Traffic/channels/1/vehicleDetect/plates/ <AfterTime> <picTime>2021-12-09T09:01:15Z</picTime> </AfterTime> </requestURL> <statusCode>4</statusCode> <statusString>Invalid Operation</statusString> <subStatusCode>invalidOperation</subStatusCode> </ResponseStatus> |
Using selenium and python to visit multiple sites Posted: 16 Dec 2021 10:53 AM PST I'm new to programming and I was just messing around with selenium. I started simple by using it to visit a website. It got me thinking, how would one visit multiple sites, specifically one after the other? How would I go about doing that in Python? I guess what I'm asking is how would I use selenium to visit a list of sites one after another, waiting about 10 seconds in between going to the sites. Here's what I have so far: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox(executable_path='PATH_TO_WEBDRIVER') url = "http://www.google.com" driver.get(url) print(driver.title) |
How to select a property inside a span, using XPath selectors? Posted: 16 Dec 2021 10:53 AM PST I am trying to select the address of a company using XPath selectors, so that I can later insert it in my Spider in Scrapy. So, my goal is to extract the address, in this case only 'Address 123'. I now have to following XPath selector: > response.xpath('//span[@property="streetAddress"]').get() The output I get is as follows: '<span class="partners__info-value" property="streetAddress">Address 123</span>' Can anybody help me to select only 'Address 213'?? The html code is can be seen in the picture below. HTML code |
How to change a label of AuthenticationForm called in the LoginView and how to use another form in LoginView ? (Django 3.0) Posted: 16 Dec 2021 10:53 AM PST I'm learning Django 3.0 and I'm actually using the django.contrib.auth.views.LoginView Here is my views.py file: from django.contrib.auth.views import LoginView class CustomLoginView(LoginView): template_name = "blog/loginview.html" And here is my urls.py file: from django.contrib.auth.views import LoginView from django.conf.urls import url urlpattenrs = [ url(r'^login/$', views.CustomLoginView.as_view(), name='login') ] I know I could put everything in the url without making my own view but I wanted to test it. Here is my template: <h1>Connection with LoginView</h1> <form method="POST" action="."> {% csrf_token %} {{ form.as_p }} <input type="hidden" name="next" value="{{ next }}" /> <input type="submit" value="Connect" /> </form> Everything works perfectly, but on my page, I can see the default labels from the AuthenticationForm used by default by the LoginView . These are Username: and Password: . Now here are my questions: Is it possible to change the labels to foo instead of Username: and bar instead of Password: from the template and keep the {{ form.as_p }} in the template? Or even better, changing the labels from the CustomLoginView ? Is it possible to use a custom form for the CustomLoginView ? Or even better, directly in the LoginView ? Thank you for your help. Update: So here is what I tried to do, according to Regnald Terry's (https://stackoverflow.com/a/61033596/10830699) answer: In my forms.py , I created this one: from django.contrib.auth.forms import AuthenticationForm class CustomAuthenticationForm(AuthenticationForm): class Meta: form = AuthenticationForm fields = "__all__" labels = { "username": "foo", "password": "bar" } And in y views.py file: from django.contrib.auth.views import LoginView from .forms import CustomAuthenticationForm class CustomLoginView(LoginView): template_name = "blog/loginview.html" authentication_form = CustomAuthenticationForm This still doesn't work. Am I doing it wrong ? |
No comments:
Post a Comment