Which mechanism was first introduced: clear_refs or userfaultfd Posted: 29 Oct 2021 08:20 AM PDT I am wondering which of the below mechanisms was the first to be introduced in Linux. The 2 of them are dirty bit tracking mechanisms. The first is done via the /proc/clear_refs fs as follows: once the user writes "4" to /proc/$pid/clear_refs the kernel unset the dirty bit of all the pages of the process and at the next attempt to access those pages, a page fault is triggered and the dirty bit is reset (by the kernel) and then the user can go through the /proc/pagemap to collect the pages that have been accessed. The second allows the user to handle the page fault himself: the user first asks the kernel to protect a given region in memory allocated via mmap; after what any attempt to access a page in that region generates a page fault for which the handling is transferred to the user who may, for example, ask the kernel to allow the access or deny it. So by this way, one does no longer need to go through the pagemap to know which pages have been accessed or not. |
How to upload files to Google Cloud using JavaScript only? Posted: 29 Oct 2021 08:20 AM PDT I am wondering if it is possible to use JavaScript to upload files directly to Google Cloud without having to use Node.js or anything else. I keep searching online but all I find are tutorials with Node.js. |
How to set the xticks on the graph Posted: 29 Oct 2021 08:20 AM PDT I have the following code for a plot. I want the last axis in the plot to not touch the edge of the graph line it should be in the graph line not on the graph line as shown in red in the plot. x = np.array([1,2,3,4,5,6,7,8,9]) y=[83.742,83.572,80.446,85.960,85.031,84.605,85.348,86.910,83.572] z=[83.9901, 83.6721,80.2542,86.2601,84.9232,84.3019,85.4232,86.7565,84.5207] plt.bar(x-0.2, y, width=0.4,label='Actual', color='g', align='center') plt.bar(x+0.2, z, width=0.4,label='Predicted', color='b', align='center') plt.ylim(60,95) plt.legend(loc=2, prop={'size': 6.5}) labels=[1,2,3,4,5,6,7,8,9,10] plt.xticks(labels,labels,rotation=60) str_x = [l for l in labels if not l in x] for s_x in str_x: plt.text(s_x, 70, 'x', ha='center', fontsize=16,color='r') plt.xlabel("Node no") plt.ylabel("Accuracy (%)") plt.show() |
run my R script on different files (list.files is not working in my case) Posted: 29 Oct 2021 08:19 AM PDT I have create a R script that analyse and manipulate 2 different data frame extension, for exemple one task is to extract certain values from data and export it as a .txt file, here is part of my script and the data files that i use: setwd('C:\\Users\\Zack\\Documents\\RScripts\\data\\data1') heat_data="data1.heat" time ="data1.timestamp" ts_heat = read.table(heat_data) ts_heat = ts_heat[-1,] rownames(ts_heat) <- NULL ts_time = read.table(time) back_heat = subset(ts_heat, V3 == 'H') back_time = ts_time$V1 library(data.table) datDT[, newcol := fcoalesce( nafill(fifelse(track == "H", back_time, NA_real_), type = "locf"), 0)] last_heat = subset(ts_heat, V3 == 'H') last_time = last_heat$newcol x = back_time - last_heat dataest = data.frame(back_time , x) write_tsv(dataestimation, file="dataestimation.txt") what i am looking for is to process my code to all my data files. For example here i am working in the path "C:\Users\Zack\Documents\RScripts\data\blabladata1" where data1 contain a .heat and . timestammp file. I want (if it exist) a way to process my script on blabladata2 (that contain also .heat and .timestamp), blabladata3 (that contain also .heat and .timestamp), blabladata4 ...etc So each files in the file : "data" contains this 2 .heat and .timestamp that i will use to export my dataestimation.txt. So at the end each blabladata** should contain **.heat, **.timestamp and dataestimation.txt that is filtered and calculated from the **.heat, **.timestamp files. I don't now if this problem is treatble with R or should i change my script to an 'argument' script and excute it using commande lines by applying it to 'path'/data/*/.heat 'path'/data/*/.timestamp Note : even if my code is in R language if a solution in python exist i would rewrite my code in python. |
big delay using odoo 13 with postgreSQL 12.8 Posted: 29 Oct 2021 08:19 AM PDT Testing from empty db, it works fine(within 1 second) first but when product record comes to around 1k rows, reading and writing both having big delay(several seconds). All application are in same PC. The hardware is enough for so little data. PostgreSQL is 12.8 and no any customized setting. Not like other software I know before, the default cfg file "postgresql.conf" has no any default value in use. Everything is commented with "#". Is there any possible bottleneck of the default setting values for the data amount around 1k? Thanks a lot. |
showing image only works on first load, not after changing the image Posted: 29 Oct 2021 08:19 AM PDT I am trying to make something like an image viewer. I call a method to load the next image into the UI. The space (grid) is still taken, everything doesnt collapse but the image is not shown. anyone know, what could be the reason? from tkinter import * from PIL import Image, ImageTk import glob import os root = Tk(className='logo classify') def draw_image(i): fNem = filenames[i] image_ = Image.open(fNem) x , y = image_.size image_ = image_.reduce(factor=3, box=(0, 1000, x , y)) tkImage = ImageTk.PhotoImage(image_) global imagelabel1 imagelabel1.grid_forget() imagelabel1 = Label(image=tkImage) imagelabel1.grid(row = 0, column = 0, rowspan = 8) def enter(): global i i += 1 draw_image(i) e1.get() if e1.get() == '': print('error no name') e2.get() e3.get() e4.get() i=0 myLabel1 = Label(root, text="company name for logo1") myLabel2 = Label(root, text="company name for logo2") myLabel3 = Label(root, text="company name for logo3") myLabel4 = Label(root, text="company name for logo4") myButton1 = Button(root, text = 'ENTER', command = enter) e1 = Entry(root, width = 50, borderwidth = 3) e2 = Entry(root, width = 50, borderwidth = 3) e3 = Entry(root, width = 50, borderwidth = 3) e4 = Entry(root, width = 50, borderwidth = 3) myLabel1.grid(row = 1, column = 1) myLabel2.grid(row = 2, column = 1) myLabel3.grid(row = 3, column = 1) myLabel4.grid(row = 4, column = 1) e1.grid(row= 1, column = 2) e2.grid(row= 2, column = 2) e3.grid(row= 3, column = 2) e4.grid(row= 4, column = 2) myButton1.grid(row = 5, column = 2) buffer_ = Label(root, text = ' ').grid(row = 6, column = 2) filenames = [] for filename in glob.glob('./resources/logo_images/*.jpg'): filenames.append(filename) id = os.path.split(filename)[1] fNem = filenames[0] print('filename: ', fNem) image_ = Image.open(fNem) print(image_.size) image_ = image_.reduce(factor=3, box=(0, 1000, 3008, 4112)) tkImage = ImageTk.PhotoImage(image_) imagelabel1 = Label(root, image=tkImage) imagelabel1.grid(row = 0, column = 0, rowspan = 8) root.mainloop() #save session csv The important part (I guess) would be the functions enter(), (which get activated from button) and draw_image(), which gets activated in enter. Thanks guys ! |
Can I filter rows by date in Oracle SQL Loader? Posted: 29 Oct 2021 08:19 AM PDT Everyday I receive a big interface file and I'm loading all the rows, but I'm only using the most recent information, (much less rows). Can I filter by the .ctl file so as to insert only the newest rows? This is my ctl file: LOAD DATA INSERT INTO TABLE SCHEMA.TBL_INTERFACE ( "ID" POSITION(001:008), --varchar2(08), "FIRSTNAME" POSITION(009:028), --varchar2(20), "LASTNAME" POSITION(029:048), --varchar2(20), "DATE" POSITION(049:058), --varchar2(10) FORMAT YYYYMMDD 20211029 ) This is a sample of the interface I load: 12345678JUAN CARLOS0 PEREZ0 20211029 23456789JUAN CARLOS1 PEREZ1 20201029 34567890JUAN CARLOS2 PEREZ2 20181029 45678901JUAN CARLOS3 PEREZ3 20171029 |
Remove quotation marks around a key when storing it into a list Posted: 29 Oct 2021 08:20 AM PDT So I am using defaultdict(int) to store the occurrence of items in my table. The key of the dict is the item being counted and the value for the key is the count. After getting the counts, I iterate through the dict to prune the keys that don't reach my count threshold. The rows that do reach my threshold, I am converting it into a str and appending it to a new list. My problem is with the quotation marks that are around the keys and if anyone knows how to remove the quotation marks. Here is my pruning function that appends the keys that reach the count threshold. # count is my dictionary storing count def prune(count, minsupport): itemset = [] for i in count: if count[i] >= minsupport: #i = i.split() i = str(i) itemset.append(i) return sorted(itemset) |
Swiftui Verify with Twilio Posted: 29 Oct 2021 08:19 AM PDT i want to phone number verify my app project.Twilio documantation not include swiftui example,And i m try Swiftui framework but not couldn't create button action. import UIKit class StartVerificationViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBOutlet weak var countryCodeField: UITextField! @IBOutlet weak var phoneNumberField: UITextField! @IBAction func sendVerification(_ sender: Any) { // send verification SMS if let phoneNumber = phoneNumberField.text, let countryCode = countryCodeField.text { VerifyAPI.sendVerificationCode(countryCode, phoneNumber) } } } *** VerifyApi is here import Foundation import SwiftUI struct VerifyAPI { static func sendVerificationCode(_ countryCode: String, _ phoneNumber: String) { let parameters = [ "via": "sms", "country_code": countryCode, "phone_number": phoneNumber ] RequestHelper.createRequest("start", parameters) { json in return .success(DataResult(data: json)) } } } |
How we can dynamically change this @ClientIDCode with @CodeMask string in SQL server Posted: 29 Oct 2021 08:20 AM PDT How we can dynamically change this @ClientIDCode with @CodeMask string in SQL server DECLARE @ClientIDCode varchar(20) = '1000003351', @CodeMask VARCHAR(50) = 'XXX-XXX' DECLARE @ClientIDCode varchar(20) = '1000003351', @CodeMask VARCHAR(50) = 'XX-XXXX' DECLARE @ClientIDCode varchar(20) = '1000003351', @CodeMask VARCHAR(50) = 'XX&XXXX' --I want output like this 1000003-351 100000-3351 100000&3351 |
How do I make a C program display a website in a window? [closed] Posted: 29 Oct 2021 08:20 AM PDT I would like to know how I can display a webpage in a window in the C language. I have tried popping up an alert box like this : #include<windows.h> int main(){ //message box MessageBox(0, "hi", "messagebox", 1); return 0; } So is there any way to display a webpage like that???? |
I want to take in using the user's input, then call a function using a case statement Posted: 29 Oct 2021 08:19 AM PDT I'm working within bash and I'm struggling to take the user's input then move them into a function. I'm using a case statement to get it to work and this is the code I'm currently working with: read -n1 -p "Save to log? [y,n] " choice \n case $choice in y|Y) echo yes ;; n|N) echo no ;; *) echo dont know ;; esac function saveToLog(){ echo Saving to log } And i've tried what I thought would work here: read -n1 -p "Save to log? [y,n] " choice \n case $choice in y|Y) saveToLog() ;; n|N) echo no ;; *) echo dont know ;; esac function saveToLog(){ echo Saving to log } But that doesn't work, I've done some googling and I can't find a solution using a case statement as I'd like to keep using this system. Thank you. :) |
Postman - extracting value from HTML description list Posted: 29 Oct 2021 08:19 AM PDT I've searched for a while trying to find a way in Postman to extract a HTML description list value from the response body where the description list contains multiple values. Example of response body: <dl> <dd>Fruit</dd> <dt>Apple</dt> <dd>Vegetable</dd> <dt>Carrot</dt> </dl> How do I just get just the Vegetable value? I've tried using the following const $ = cheerio.load(pm.response.text()) console.log('Vegetable', $('dt').text()) This then returns both values "Vegetable" "AppleCarrot" The Fruit & Vegetable values will change once the request is rerun, this means I'm unable to go just based off their names. I'm probably over thinking this, thanks in advance. |
Why is object key pair with null value not passed from server to client? Posted: 29 Oct 2021 08:20 AM PDT I have a Google application script web application where I use google.script.run.withSuccessHandler . Server side function returns an object where all the values are null. MaterializeCSS autocomplete requires nulls My customer today reported that the GAS web stopped working. It was 10000000% working before. I found out that the reason is a null as a value. Working sample applicatin is here https://script.google.com/macros/s/AKfycbzbg4YLndZ0zORBzgDc3ETLUdJeToUS1nKjORUa5fNxQt9syXmLlX1gDHzgS4w8iCBM9A/exec https://script.google.com/d/1Uba73PIetb9fmrO44nwsmAd_epZTHy4lwz5bG3bURK3jqpd161JT0pf5/edit?usp=sharing HTML code <!DOCTYPE html> <html> <head> <base target="_top"> </head> <body> Test <script type="text/javascript"> console.log("test") document.addEventListener("DOMContentLoaded", function(event) { google.script.run.withSuccessHandler(afterDataReceived) .returnObject() }); function afterDataReceived(receivedData){ console.log(receivedData) } </script> </body> </html> GS code function doGet(e) { var htmlTemplate = HtmlService.createTemplateFromFile("index").evaluate() return htmlTemplate } function returnObject(){ var object = {} object.a = "123" object.b = null object.c = 123 console.log(object) return object } Is someone experiencing the same error? How to fix this? |
merge and remove elements in nested arrays Posted: 29 Oct 2021 08:19 AM PDT i have this array, i want to merge all elements inside the objects in the nested arrays and remove the duplicates.. the array is the output of mongo db populate so answers from there or just js will be amazing :) "visitors": [ [ { "name": "matan", "id": "61793e6a0e08cdcaf213c0b1" }, { "name": "shani", "id": "61793e910e08cdcaf213c0b5" } ], [ { "name": "david", "id": "6179869cb4944c6b19b05a23" }, { "name": "orit", "id": "617986e535fdf4942ef659bd" } ], [ { "name": "david", "id": "6179869cb4944c6b19b05a23" }, { "name": "orit", "id": "617986e535fdf4942ef659bd" } ] ] would like this output - "visitors": [ { "name": "matan", "id": "61793e6a0e08cdcaf213c0b1" }, { "name": "shani", "id": "61793e910e08cdcaf213c0b5" }, { "name": "david", "id": "6179869cb4944c6b19b05a23" }, { "name": "orit", "id": "617986e535fdf4942ef659bd" }, ] |
Is it possible to call Class member constructor inside class constructor? Posted: 29 Oct 2021 08:20 AM PDT I would like to be able to initialize a class member in one of N ways (in this examples N=2) based on a condition that is recieved via the class constructor as in the code that follows, but the MainObject's initialization seems to be only local to the (container) class' constructor. I wonder what are the best-practices for this particular pattern. // in ContainerObject.hpp class ContainerObject { public: MainClass MainObject; ContainerObject(int type); } // in ContainerObject.cpp ContainerObject::ContainerObject(int type);{ if (type == 0){ MainObject("something", 1, 2); } else if (type == 1){ MainObject(4, "another thing", "yet another thing"); } } I have so-far thought about - putting the main object in the heap
- defining N class constructors and call the appropiate one recursively inside the "main"/"first" class constructor.
please note that the "0" and "1" initialization is only an example and it could be drastically different. EDIT1: added ";" required for compiling EDIT2: Changed the original //... if (type == 0){ MainObject(0); } else if (type == 1){ MainObject(1); } //... for the current one //... if (type == 0){ MainObject("something", 1, 2); } else if (type == 1){ MainObject(4, "another thing", "yet another thing"); } //... as it was called a duplicate by being misinterpreted for a case that could be solved by adding the following. //... ContainerObject(int type): MainObject(type); //... |
R - Efficiently insert multiple strings Posted: 29 Oct 2021 08:20 AM PDT I would like to insert a list of sub strings (word_list ) into a string (text ) at specific positions (idx_list ) text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." idx_list = c(5,16,30,50) word_list = c("AAA", "BBB", "CCC", "DDD") I know there are multiple possibilites functions (gsub, stri_sub etc.) which I can use in a loop. This gets however quite slow on large corpora. Is there a more efficient solution? Maybe vectorized? |
How can I use TypeScript Partials to test AWS Lambda? Posted: 29 Oct 2021 08:19 AM PDT Very similar to Using partial shape for unit testing with typescript but I'm failing to understand why the Partial type is seen as being incompatible with the full version. I have a unit test which check if a lambda returns 400 if the body in an AWS lambda event isn't valid. To avoid creating noise for my colleagues, I don't want to create invalidEvent with all the properties of a full APIGatewayProxyEvent . Hence using a Partial<APIGatewayProxyEvent> . it("should return 400 when request event is invalid", async () => { const invalidEvent: Partial<APIGatewayProxyEvent> = { body: JSON.stringify({ foo: "bar" }), }; const { statusCode } = await handler(invalidEvent); expect(statusCode).toBe(400); }); The const { statusCode } = await handler(invalidEvent); line fails compilation with: Argument of type 'Partial<APIGatewayProxyEvent>' is not assignable to parameter of type 'APIGatewayProxyEvent'. Types of property 'body' are incompatible. Type 'string | null | undefined' is not assignable to type 'string | null'. Type 'undefined' is not assignable to type 'string | null'.ts(2345) I understand APIGatewayProxyEvent body can be string | null (from looking at the types) but where did string | null | undefined come from? Why isn't my body - which is a string - a valid body for APIGatewayProxyEvent How can I use TypeScript Partials to test AWS Lambda? I could use as to do type assertions but I find Partials more explicit. The following code works though: const invalidEvent = { body: JSON.stringify({ foo: "bar" }) } as APIGatewayProxyEvent; Update: using Omit and Pick to make a new type type TestingEventWithBody = Omit<Partial<APIGatewayProxyEvent>, "body"> & Pick<APIGatewayProxyEvent, "body">; it("should return 400 when request event is invalid", async () => { const invalidEvent: TestingEventWithBody = { body: JSON.stringify({ foo: "bar" }) }; const { statusCode } = await handler(invalidEvent); expect(statusCode).toBe(400); }); Fails with: Argument of type 'TestingEventWithBody' is not assignable to parameter of type 'APIGatewayProxyEvent'. Types of property 'headers' are incompatible. Type 'APIGatewayProxyEventHeaders | undefined' is not assignable to type 'APIGatewayProxyEventHeaders'. Type 'undefined' is not assignable to type 'APIGatewayProxyEventHeaders'.ts(2345) |
How the code will be run in ASYNC function when we have several call in a low amount of time? Posted: 29 Oct 2021 08:19 AM PDT We have an Async Function that needs at least 10 seconds runtime to return a value. what will happen if we call this function and again run this function after 2 seconds while the first call has not ended yet? Does this make a problem with my data? how it will be executed? it is what I have tried out: based on the async function on WebSocket I want to run a function fully, then when the function has returned the value again that function becomes avalable. socket.on('ok',async function(data) { let promise = new Promise((res, rej) => { setOkData(page,socket, function(res) { res(res) }); }); let res = await promise; }); |
Flutter SliverGrid Flip Axis Posted: 29 Oct 2021 08:19 AM PDT tl;dr How do I flip the X axis in a SliverGrid? I have to display a long list in a grid (every cell is equal in size). I can request the list from a server with pagination. Now the user should be able to open that list at any index in the grid and should be able to scroll in both direction. I am trying to create a GridView in Flutter and lazy load its content in both directions (upwards and downwards) while scrolling. My first attempt was to modify infinite_listview to become an gridview. It looked really promising at first but the problem was that the min and maxExtend was overridden to be always negative and positive infinite. I changed that back to the normal behavior but then only the maxExtend was working the minExtend was always 0 and therefore I was not able to scroll the grid upwards. My second attempt was a Scrollable with a Viewport. Inside the Viewport I put two SliverGrids (one growing upwards and one growing downwards). I set the center key of the Viewport to the key of the second SliverGrid so the first Item of the downwards growing SliverGrid was the first Cell on screen and the user could scroll to see the cells above and below. With that approach the scrolling extends were kept intact. So the user could only scroll until he reached the end of the list (or the end of the already received cells). class BidirectionalGridView extends StatelessWidget { static const Key centerKey = ValueKey("CENTER"); final SliverGridDelegate gridDelegate; final IndexedWidgetBuilder itemBuilder; final int upperItemCount; final int lowerItemCount; const BidirectionalGridView({ required this.gridDelegate, required this.itemBuilder, required this.upperItemCount, required this.lowerItemCount, Key? key, }) : super(key: key); int get totalItemCount => upperItemCount + lowerItemCount; @override Widget build(BuildContext context) { return Scrollable( axisDirection: AxisDirection.down, viewportBuilder: (context, position) { return Builder(builder: (context) { return Viewport( center: centerKey, offset: position, anchor: 0, slivers: [ SliverGrid( gridDelegate: gridDelegate, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return itemBuilder(context, upperItemCount - 1 - index); }, childCount: upperItemCount), ), SliverGrid( key: centerKey, gridDelegate: gridDelegate, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return itemBuilder(context, upperItemCount + index); }, childCount: lowerItemCount), ), ]); }); }, ); } } With this setup I am facing the problem that I have to flip the X axis for the upper SliverGrid to get the order on the upper half right. But I do not know how. How do I flip the X axis in a SliverGrid? or achieve increasing order from left to right in the upper half? (I do not know the number of cells per row, so as far as I know I can not manipulate the order by translating the index in the builder). Demo Code: var items = <int>[]; for (var i = 0; i < 300; ++i) { items.add(i - 100); } /* * ... */ BidirectionalGridView( upperItemCount: 100, lowerItemCount: 200, itemBuilder: (context, index) { return SizedBox.square( dimension: 72, child: Align( alignment: Alignment.center, child: Text("${items[index]}"), ), ); }, gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 72, crossAxisSpacing: 4, mainAxisSpacing: 4, childAspectRatio: 1, ), ), |
React: "Can't perform a React state update on an unmounted component" without useEffect function Posted: 29 Oct 2021 08:20 AM PDT (I'm using Next.js + Styled Components and i'm totally a beginner, please help me :)) I'm working on a kind of "Netflix" page, with a different type of catalog components. Each content in the page's grid is a very complex component, with a lot of interactions, called ContentItem.js, that repeats in ContentList.js. So, I'm getting this error: Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. at ContentItem (webpack-internal:///./ltds/components/Shelf/ContentItem.js:104:62) at ul at O (webpack-internal:///./node_modules/styled-components/dist/styled-components.browser.esm.js:31:19797) at ContentList (webpack-internal:///./ltds/components/Shelf/ContentList.js:52:23) at div at O (webpack-internal:///./node_modules/styled-components/dist/styled-components.browser.esm.js:31:19797) at Shelf (webpack-internal:///./ltds/components/Shelf/Shelf.js:57:66) at div at SearchResult (webpack-internal:///./pages/search/[term].js:32:70) But, in this component, I'm not using useEffect: import Image from 'next/image'; import { Paragraph } from '../../styles/Typography'; import styled from 'styled-components'; import { gridUnit } from '../../styles/GlobalStyle'; import { useEffect, useState } from 'react'; import { Transition } from 'react-transition-group'; import React from 'react'; import Icon from '../Icon'; const ContentItemContainer = styled.li` margin-bottom: 16px; text-decoration: none; transition: all 0.2s; position: relative; border-radius: ${(props => props.theme.radius.lg.value)}${gridUnit}; overflow: hidden; height: auto; &:hover { cursor: pointer; transform: ${props => (props.isClicking ? "scale(0.98)" : "scale(1.04)")}; } `; const ItemCover = styled(Image)` border-radius: ${(props => props.theme.radius.lg.value)}${gridUnit}; border: 1px solid #504F4E; overflow: visible; position: relative; transition: 0.2s; opacity: ${({ state }) => (state === "entering" ? 0 : 1)}; `; const ItemHoverContainer = styled.div` position: absolute; z-index: 10; top: 0; left: 0; right: 0; padding: 0px; margin: 0px; height: auto; &:hover{ border: 0.8px solid ${props => (props.theme.alias.image.border.value)}; border-radius: ${(props => props.theme.radius.lg.value)}${gridUnit}; } `; const ItemHoverImage = styled(Image)` border-radius: 15px; //15px not 16px: hack to avoid a "phantom line" at the bottom of image transition: 0.4s; display: ${({ state }) => (state === "exited" ? "none" : "block")}; opacity: ${({ state }) => (state === "entered" ? 1 : 0)}; `; const IconContainer = styled.div` position: absolute; left: 41.84%; right: 41.13%; top: 42.58%; bottom: 42.11%; `; const DetailsContainer = styled(Paragraph)` padding-top: ${({ state }) => (state === "entered" ? props => props.theme.spacing[1].value+gridUnit : 0)}; transition: 0.4s; opacity: ${({ state }) => (state === "entered" ? 1 : 0)}; height: ${({ state }) => (state === "entered" ? 1 : 0)}; display: ${({ state }) => (state === "exited" ? "none" : "block")}; `; function ContentItem(props) { const nodeRef = React.useRef(null); const [isHovering, setIsHovering] = useState(false); const [isClicking, setIsClicking] = useState(false); const [isLoaded, setIsLoaded] = useState(false); const coverSizes = { wide:{ width: 236, height:139 }, poster:{ width: 144, height: 192 } } function handleMouseOver(event) { setIsHovering(!isHovering) } function handleMouseOut(event) { setIsHovering(!isHovering) } function handleMouseDown(event) { setIsClicking(!isClicking) } function handleMouseUp(event) { setIsClicking(!isClicking) } function handleLoadingComplete(event) { !isLoaded && (setIsLoaded(true)) } return ( <ContentItemContainer isClicking={isClicking} onMouseOver={handleMouseOver} onMouseOut={handleMouseOut} onMouseDown={handleMouseDown} onMouseUp={handleMouseUp}> <Transition in={isLoaded} timeout={0} nodeRef={nodeRef}> {(state) => ( <div> <ItemCover src={props.coverType == "wide" ? props.wideCover : props.posterCover } alt={props.alt} layout={'responsive'} width={props.coverType == "wide" ? coverSizes.wide.width : coverSizes.poster.width} height={props.coverType == "wide" ? coverSizes.wide.height+1 : coverSizes.poster.height}//+1: hack to avoid cut at the bottom of image placeholder='blur' blurDataURL={props.coverPlaceholder} onLoadingComplete={handleLoadingComplete} /> </div>)} </Transition> <ItemHoverContainer> <Transition in={isHovering} timeout={0} nodeRef={nodeRef} mountOnEnter unmountOnExit> {(state) => ( <div> <ItemHoverImage src={props.coverType == "wide" ? props.wideLoopVideo : props.posterLoopVideo } layout={'responsive'} width={props.coverType == "wide" ? coverSizes.wide.width : coverSizes.poster.width} height={props.coverType == "wide" ? coverSizes.wide.height : coverSizes.poster.height+1} //+1: hack to avoid a "phantom line" at the bottom of image state={state} /> <IconContainer> <Icon preserveAspectRatio="xMinYMin meet" name="coverPlay"/> </IconContainer> </div> )} </Transition> </ItemHoverContainer> <Transition in={props.isDetailed} timeout={100} nodeRef={nodeRef}> {(state) => ( <DetailsContainer state={state} isDetailed={props.isDetailed}>{props.content.details}</DetailsContainer> )} </Transition> </ContentItemContainer> ); } export default ContentItem How can I solve this? Update I tried using useEffect based on @MB_ answer, but the memory leak error still happens: import React, { useState, useRef, useEffect } from 'react'; import Image from 'next/image'; import { Transition } from 'react-transition-group'; import styled from 'styled-components'; import { Paragraph } from '../../styles/Typography'; import { gridUnit } from '../../styles/GlobalStyle'; import Icon from '../Icon'; function ContentItem(props) { const [isHovering, setIsHovering] = useState(false); const [isClicking, setIsClicking] = useState(false); const [isLoaded, setIsLoaded] = useState(false); const nodeRef = useRef(null); const mouseRef = useRef(null); const imgRef = useRef(null); useEffect(() => { const currentMouseRef = mouseRef.current; if (currentMouseRef) { currentMouseRef.addEventListener('mouseover', handleMouseOver); currentMouseRef.addEventListener('mouseout', handleMouseOut); currentMouseRef.addEventListener('mousedown', handleMouseDown); currentMouseRef.addEventListener('mouseup', handleMouseUp); return () => { currentMouseRef.removeEventListener('mouseover', handleMouseOver); currentMouseRef.removeEventListener('mouseout', handleMouseOut); currentMouseRef.removeEventListener('mousedown', handleMouseDown); currentMouseRef.removeEventListener('mouseup', handleMouseUp); }; } }, []); const handleMouseOver = () => setIsHovering(true); const handleMouseOut = () => setIsHovering(false); const handleMouseDown = () => setIsClicking(true); const handleMouseUp = () => setIsClicking(false); const handleLoadingComplete = () => !isLoaded && setIsLoaded(true); const coverSizes = { wide:{ width: 236, height:139 }, poster:{ width: 144, height: 192 } } return ( <ContentItemContainer ref={mouseRef} onMouseOver={handleMouseOver} onMouseOut={handleMouseOut} onMouseDown={handleMouseDown} onMouseUp={handleMouseUp} isClicking={isClicking} > <Transition in={isLoaded} timeout={0} nodeRef={nodeRef}> {(state) => ( <div> <ItemCover src={props.coverType == "wide" ? props.wideCover : props.posterCover } alt={props.alt} layout={'responsive'} width={props.coverType == "wide" ? coverSizes.wide.width : coverSizes.poster.width} height={props.coverType == "wide" ? coverSizes.wide.height+1 : coverSizes.poster.height}//+1: hack to avoid cut at the bottom of image placeholder='blur' blurDataURL={props.coverPlaceholder} onLoadingComplete={handleLoadingComplete} /> </div>)} </Transition> <ItemHoverContainer> <Transition in={isHovering} timeout={0} nodeRef={nodeRef} mountOnEnter unmountOnExit> {(state) => ( <div> <ItemHoverImage src={props.coverType == "wide" ? props.wideLoopVideo : props.posterLoopVideo } layout={'responsive'} width={props.coverType == "wide" ? coverSizes.wide.width : coverSizes.poster.width} height={props.coverType == "wide" ? coverSizes.wide.height : coverSizes.poster.height+1} //+1: hack to avoid a "phantom line" at the bottom of image state={state} /> <IconContainer> <Icon preserveAspectRatio="xMinYMin meet" name="coverPlay"/> </IconContainer> </div> )} </Transition> </ItemHoverContainer> <Transition in={props.isDetailed} timeout={100} nodeRef={nodeRef}> {(state) => ( <DetailsContainer state={state} isDetailed={props.isDetailed}>{props.content.details}</DetailsContainer> )} </Transition> </ContentItemContainer> ); } export default ContentItem const ContentItemContainer = styled.li` margin-bottom: 16px; text-decoration: none; transition: all 0.2s; position: relative; border-radius: ${(props => props.theme.radius.lg.value)}${gridUnit}; overflow: hidden; height: auto; &:hover { cursor: pointer; transform: ${props => (props.isClicking ? "scale(0.98)" : "scale(1.04)")}; } `; const ItemCover = styled(Image)` border-radius: ${(props => props.theme.radius.lg.value)}${gridUnit}; border: 1px solid #504F4E; overflow: visible; position: relative; transition: 0.2s; opacity: ${({ state }) => (state === "entering" ? 0 : 1)}; `; const ItemHoverContainer = styled.div` position: absolute; z-index: 10; top: 0; left: 0; right: 0; padding: 0px; margin: 0px; height: auto; &:hover{ border: 0.8px solid ${props => (props.theme.alias.image.border.value)}; border-radius: ${(props => props.theme.radius.lg.value)}${gridUnit}; } `; const ItemHoverImage = styled(Image)` border-radius: 15px; //15px not 16px: hack to avoid a "phantom line" at the bottom of image transition: 0.4s; display: ${({ state }) => (state === "exited" ? "none" : "block")}; opacity: ${({ state }) => (state === "entered" ? 1 : 0)}; `; const IconContainer = styled.div` position: absolute; left: 41.84%; right: 41.13%; top: 42.58%; bottom: 42.11%; `; const DetailsContainer = styled(Paragraph)` padding-top: ${({ state }) => (state === "entered" ? props => props.theme.spacing[1].value+gridUnit : 0)}; transition: 0.4s; opacity: ${({ state }) => (state === "entered" ? 1 : 0)}; height: ${({ state }) => (state === "entered" ? 1 : 0)}; display: ${({ state }) => (state === "exited" ? "none" : "block")}; `; |
Update bool value in a jsonb column - jsonb_set Posted: 29 Oct 2021 08:19 AM PDT With the following json exemple: { "red": false, "blue": false, "yellow": false } I have to update one of the elements to true and the expected result is: { "red": false, "blue": false, "yellow": true } First, i tried to update this way: UPDATE table_name SET jsonb_column_name = jsonb_set(jsonb_column_name, '{yellow}', ('"true"')::jsonb, true) But the result was { "red": false, "blue": false, "yellow": "true" } not what i want, its a string, not bool Also tried: UPDATE table_name SET jsonb_column_name = jsonb_set(jsonb_column_name, '{yellow}', true, true) But i got an error, that makes sense, the 3rd parameter has to be jsonb SQL Error [42883]: ERROR: function jsonb_set(jsonb, unknown, boolean, boolean) does not exist Hint: No function matches the given name and argument types. You might need to add explicit type casts. And i cannot make true::jsonb because bool cant be cast to jsonb: SQL Error [42846]: ERROR: cannot cast type boolean to jsonb Ther is another way to do this? no need to use jsonb_set, i think i can user str_replace an then convert to jsonb but i don't know if its safe |
Cannot use user commands in Dyalog APL Posted: 29 Oct 2021 08:19 AM PDT I just installed Dyalog-APL 18.0 on my windows(Windows 10) machine and when I tried using ]box on -style=max on the IDE I got the following error: FILE ACCESS ERROR: C:/Users/<User>/Documents/: Unable to read directory status Then I noticed that there was a previous error when opening Dyalog which I had blatantly ignored: SALT initialization failed: C:/Users/<User>/Documents/: Unable to read directory status Furthermore, I realized that all user commands give the first error. Some details: I installed it as an administrator privilege with Avast Antivirus installed. Things I tried: - Adding the documents folder as an exception in the antivirus setting and also adding it in the allowed apps list(from Ransomware Shield). It was followed by a restart after the change.
- Reinstalling
- Starting Dyalog as administrator
|
Toast doesn't recognize context Posted: 29 Oct 2021 08:20 AM PDT I'm new to Android development and Java and I'm having troubles with Toast: I have a MainActivity with several buttons. Each one of this starts another Activity with typical setOnclickListener method like this: btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setClass(getApplicationContext(), secondaryActivity.class); startActivity(intent); } }); Then, inside this secondaryActivity.class I have another button that make some stuff. Inside this Activity I wanna display a Toast on button's click but it doesn't work: secondaryActivityBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Toast.makeText(view.getContext(),"text",Toast.LENGTH_LONG).show(); } }); As Toast's context I've tried: getApplicationContext() , getBasecontext() , view.getContext() , mySecondaryActivityClass.this ... No one of this display the Toast, I don't know where's the mistake. Supposedly, view.getContext() might work but it doesn't display anything... MainActivity extends AppCompactActivity and mySecondaryActivity extends Activity. |
How can I pass a value to init methods on import? Posted: 29 Oct 2021 08:19 AM PDT Let's assume I have component like this: 'use strict'; export default () => ({ selected: false, init(selectedIndex: -1) { } }); and I import it like this (using AlpineJS 3): import Alpine from 'alpinejs' window.Alpine = Alpine window.Components = {}; import Tab from "./components/Tab"; window.Components.Tab = Tab; Alpine.start(); How can I now pass value to init method? When I have: <div x-data="Components.Tab(0)">...</div> value is obviously not passed to init method. Although there is info in docs how to register component from a bundle and info how to pass initial parameters, there is no info how to pass initial parameters to component registered from a bundle |
i want to create Search box for JSON data Using Javascript and get a popup if content exists or not Posted: 29 Oct 2021 08:19 AM PDT I have this code to search through my JSON data but want When I search, I get a popup saying if it exists or not in my json file . Could anyone please analyse it? I basically need a HTML search box to search through corresponding JSON data and return resultat in popup var data = [ { "id":198, "name":"Aaron Garo", }, { "id":345, "name":"Michael Stines", }, { "id":545, "name":"Ully Heiz", }, { "id":678, "name":"Asgaf Torino", } ] output = ""; $.each(data, function(key, val){ output += "<div class='values'>"; output += '<h5 class="value-id">' + val.id + '</h5>'; output += '<p class="value-name">' + val.name + '</p>' output += "</div>"; }); $('#content').html(output); /* SEEKER FUNCTION */ if (!RegExp.escape) { RegExp.escape = function (s) { return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") }; } jQuery(function(){ var $rows = $('.values'); $('#seeker').keyup(function () { var regex = new RegExp(RegExp.escape($.trim(this.value).replace(/\s+/g, ' ')), 'i') $rows.hide().filter(function () { var text = $(this).children(".value-name").text().replace(/\s+/g, ' '); return regex.test(text) }).show(); }); }); .values{ background: #FFFFAA; } .search-bar{ width: 100%; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="search-bar"> <input type="text" id="seeker"> </div> <div id="content"></div> |
Angular material Could not find Angular Material core theme Posted: 29 Oct 2021 08:19 AM PDT In my Angular2 project I install lastest material plugin from https://material.angular.io/guide/getting-started. Next I add @import '~@angular/material/prebuilt-themes/deeppurple-amber.css'; to my css file for my component. But in my console Angular shows this error: material.es5.js:148 Could not find Angular Material core theme. Most Material components may not work as expected. For more info refer to the theming guide: https://material.angular.io/guide/theming` The material components not working. Whats wrong? |
Why Go can lower GC pauses to sub 1ms and JVM has not? Posted: 29 Oct 2021 08:19 AM PDT So there's that: https://groups.google.com/forum/?fromgroups#!topic/golang-dev/Ab1sFeoZg_8: Today I submitted changes to the garbage collector that make typical worst-case stop-the-world times less than 100 microseconds. This should particularly improve pauses for applications with many active goroutines, which could previously inflate pause times significantly. High GC pauses are one of the things JVM users struggle with for a long time. What are the (architectural?) constraints which prevent JVM from lowering GC pauses to Go levels, but are not affecting Go? |
Add two sections in recyclerview android Posted: 29 Oct 2021 08:20 AM PDT In my application i am using recyclerview to display all contact list. I want two section in recyclerview. Like one section is my application contact list and second section is my phone contact list. Like this Is there any method to do it? Does anybody know how to do it? |
Find own origin in JavaScript [duplicate] Posted: 29 Oct 2021 08:19 AM PDT Is there a way to find the origin of the current running script? I would like to add a different behavior depending where the script was loaded from. e.g. was loaded from: http://localhost:8080/js/myscript.js vs http://www.myhost.com/js/myscript.js I'm not the one who loads is so I can't add some info in load time, and the script is loaded dynamically using $.getScript() , so I can't look for the element. |
No comments:
Post a Comment