Posts

Showing posts from May, 2021

Throttle function won't run without interval constant

class Neuron { fire() { console.log("Firing!"); } Function.prototype.myThrottle = function(interval) { // declare a variable outside of the returned function let tooSoon = false; return (...args) => { // the function only gets invoked if tooSoon is false // it sets tooSoon to true, and uses setTimeout to set it back to // false after interval ms // any invocation within this interval will skip the if // statement and do nothing if (!tooSoon) { tooSoon = true; setTimeout(() => tooSoon = false, interval); this(...args); // confused what this piece of code does. } } function printFire(){ return neuron.fire()} const neuron = new Neuron(); neuron.fire = neuron.fire.myThrottle(500); const interval = setInterval(printFire, 10); This piece of code will output "Firing!, once every 500ms". My confusion is when I comment "const interval = setInterval(printFire, 10) ", The code does not run at all. I feel const interval should no...

Bottom of Pop Up Form is not fully showing the back ground color

I have been struggling to get the CSS to do what I would like to see in the pop up (which displays a form ) that I am using but the bottom of the pop up form is still not showing all the white background. The CSS is below with the form that sits inside the pop up. What am I doing wrong and how do I correct this annoyance? <style> * { box-sizing: border-box; } .openBtn { display: flex; justify-content: left; } .openButton { border: none; border-radius: 5px; background-color: #1c87c9; color: white; padding: 14px 20px; cursor: pointer; position: fixed; } .loginPopup { position: relative; text-align: center; width: 100%; } .formPopup { display: none; max-height: 340px; position: absolute; left: 45%; top: 5%; transform: translate(-50%, 10%); border: 3px sol...

macOS Blue icons

Image
I'm using Storyboard's to develop a macOS Big Sur application, when I noticed that apps such as Xcode and App Store used nice little blue icons: I could not find these in Xcode's interface builder anywhere. Does anybody know how to get those icons? (More specifically Xcode's blue plus button, next to "Create a new Xcode project") from Recent Questions - Stack Overflow https://ift.tt/3fx9jp4 https://ift.tt/2Tv7Uab

Implicit conversion on type alias does not seem to work ont his code

trait TriIndexable[M[_,_,_,_]] { def get[A,B,C,D](m: M[A,B,C,D])(a: A, b: B, c: C): Unit } implicit object TriMapTriIndexable extends TriIndexable[TriMap] { def get[A,B,C,D](m: TriMap[A,B,C,D])(a: A, b: B, c: C): Unit = { println("Tri indexable get") } } type TriIntMap[D] = TriMap[Int,Int,Int,D] trait TupleIntIndexable[M[_]] { def get[D](m: M[D])(a: (Int, Int, Int)): Unit } implicit object TriIntMapTupleIntIndexable extends TupleIntIndexable[TriIntMap] { def get[D](m: TriIntMap[D])(a: (Int, Int, Int)): Unit = { println("Tri Int indexable get") } } class TriMap[A,B,C,D]() { } implicit class TriIndexableOps[A,B,C,D,M[_,_,_,_]]( val tri: M[A,B,C,D] )(implicit ev: TriIndexable[M]) { def get(a: A, b: B, c: C) = { ev.get(tri)(a,b,c) } } implicit class TupleIntIndexableOps[D,M[_]]( val tri: M[D] )(implicit ev: TupleIntIndexable[M]) { def get(a: (Int,Int,Int)) = { ev.get(tri)(a) } } val test: TriIntMap[String] = new TriM...

Using same X and Y axis for all par() plots

I have a loop generating 15 plots, one for each of my factor variables. This is my first time using par() to set up the plot space (I usually use ggplot or lattice, which I probably should have done here). Anyway, I'm generally okay with this, but I would like each graph to have the same X and Y range (1,5) and (0,120), respectively. I've read the par documentation but haven't figured out how to accomplish this. Here is my code: par(mar=c(2,2,2,2),mfrow = c(4, 4)) for (i in 2:16) { plot(df[,i], main=colnames(df)[i], ylab = "Count", col="steelblue", las = 2) } Thank you! from Recent Questions - Stack Overflow https://ift.tt/2SBiN9T https://ift.tt/eA8V8J

Unable to open/use file unless i use Directory path. Pycharm

Just started python and GUIs. it seems that everytime i need to use a file like a picture or music wav file i have to use the directory path and i have to separate my directories with 2\ or i get a unicode error.in the screenshot u can see that in my iconbitmap its normal because it reads the directory normally but in but in mixer or tkinter i have to use the D path with double \ error Ive tried moving my desired files to other locations like scripts and include but it doesnt open them. it reconizes the filles name because it goes to autofill but when comes times to load or to activate my function no luck from Recent Questions - Stack Overflow https://ift.tt/2SItV4Z https://ift.tt/eA8V8J

How to mock the image response in cypress

Image
My problem I'm trying to simulate a response from the server containing an image with cy.intercept however, the browser won't display my mocked image. The browser just can't interpret my response as a proper image for <img> tag. I can still copy the response in debug tools and it seems to be the image I need but probably encoded in the wrong way. My approach cy.readFile('src/assets/logo.png', 'binary').then((imgContent) => { cy.intercept('/uploads/test.png', { headers: { 'Content-Type': 'image/jpg' }, body: imgContent, }) }); I've also tried to return base64 image string like this: cy.intercept( '/uploads/test.png', { headers: {"Content-Type": "image/jpg"}, body: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAARCUlEQVR4Xu1deXQURRr... But it didn't work as well. from Recent Quest...

syntax error: missing ';' before '}' but im sure im not missing any semicolons C++

the title pretty much explains and i've been looking on google for a while and cant find a working answer here is my code: #include <SDL.h> #include <stdio.h> //Screen dimensions: 1280×720 const int SCREEN_WIDTH = 1280; const int SCREEN_HEIGHT = 720; int main(int argc, char* args[]) { SDL_Window* window = NULL; SDL_Surface* screenSurface = NULL; if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); } } from Recent Questions - Stack Overflow https://ift.tt/34wGfaZ https://ift.tt/eA8V8J

sqldf only returning one row, same query used in SQL

For some reason I'm only returning one row when it comes to R while at SQL Server, I'm returning the correct number of rows. SQLDF: CustomerCodingChangesT <- sqldf(" SELECT c.CustID as ID, c.ReverseSupplier as Supplier, c.ReverseCustomerCode as Code, c.Name, c.Address, c.[From PostCode], c.[From Outlet], c.[From OutletName], o.FullAddress AS [From Address], c.[To PostCode], c.[To Outlet], c.[To OutletName], o1.FullAddress AS [To Address], Max(Cast( c.TotalUnits as varchar)) as [Total Units], '$'+Max(cast(c.TotalValue as varchar)) as [Total Value], '' AS Checked, c.CustRecActive as Active FROM CustomerCorrectionSummaryT AS c LEFT JOIN OutletMasterT AS o ON c.[From PostCode] = o.Postcode AND c.[From Outlet] = o.Outlet LEFT JOIN OutletMasterT AS o1 ON c.[To PostCode] = o1.Postcode AND c.[To Outlet] = o1.Outlet ORDER BY c.totalvalue DESC;") SQL: if object_id ('tempdb..#C...

How to make Kotlin use field instead of setter in non-primary constructors too

If I use a primary constructor to initialize a property, its setter won't be called: open class Foo(open var bar: Any) open class Baz(bar: Any) : Foo(bar) { override var bar: Any get() = super.bar set(_) = throw UnsupportedOperationException() } ... Baz(1) // works, no setter is called This works too: open class Foo(bar: Any) { open var bar: Any = bar // no exception in Baz(1) } But this doesn't: open class Foo { open var bar: Any constructor(bar: Any) { this.bar = bar // UnsupportedOperationException in Baz(1) } } This can't even be compiled: open class Foo(bar: Any) { open var bar: Any // Property must be initialized or be abstract init { this.bar = bar } } I'm asking because I need to make bar lateinit to be able doing this: Baz(1) // works Foo(2) // this too Foo().bar = 3 // should work too But this doesn't work in Kotlin: // 'lateinit' modifier is not allowed on primary constr...

I want the searchbox to disappear from all pages except product page with React.js

When i do this ternay operator the result is that the searchbox desappear from every page. The idea is only to show in /products. Thank you if you could help me with this, very much appreciated. function Header() { let location = useLocation(); {location === "/products" ? ( <li> <form action="#" class="form-box f-right"> <input type="text" name="Search" placeholder="Search products" /> <div class="search-icon"> <i class="ti-search"></i> </div> </form> </li> ) : null}``` from Recent Questions - Stack Overflow https://ift.tt/...

Pandas Window functions to calculate percentage for groupby

For each Location and Acquisition channel I would like to calculate the percentage. For example: The Digital acquisition channel in Milan makes up 33% of all customers in Milan and 24% of total spend across all acquisition channels in Milan DF city acquisition_channel customers spend Milan Digital 23 120 Milan Organic 35 324 Milan Email 12 53 Paris Digital 44 135 Paris Organic 24 252 Paris Email 10 47 Desired Output DF city acquisition_channel customers spend Milan Digital 33% 24% Milan Organic 50% 65% Milan Email 17% 11% Paris Digital 56% 31% Paris Organic 31% 58% Paris Email 13% 11% This is what I have tried so far, but this is not giving me the desired result df.groupby(["acquisition_channel","city...

How to programmatically upload a file to input[type=file]

My problem is, I had image srcs I converted to dataUrls. I am now trying to convert the dataUrl to a file and programmatically upload the file to an input[type='file']. I was able to successfully get the dataUrls of the images, however, I am now creating the function that downloads the dataUrl. The dataUrl downloads, however, in addition to downloading the dataUrl, I want it to also be uploaded to that input[type=file] section. The code seems to work fine, however, the image never actually uploads. I included a picture of the terminal for when the program runs. It says the input section has the file I added('product_image.png'). But for website I am trying to upload the photo, when a png file is uploaded it displays the image in the same section. However, that is not happening. Am I not properly providing a source for the file? is the code wrong? If anyone sees the problem, please let me know! Terminal Page function downloadURI(uri, name) { var lin...

How do I drop system versioned tables in a sql server database project

We’re using a .net sql server database project to define our database, and it’s not deleting tables from the server even though we have deleted them in the database project. There is an option in the publish profile to drop objects that are in the target but not in the source. However, this doesn’t work for temporal tables as I get an error saying it can’t drop temporal tables as the standard sql drop command is not supported on the temporal table. Is there a way to drop temporal tables using a SQL server data base project? from Recent Questions - Stack Overflow https://ift.tt/3yPY9U3 https://ift.tt/eA8V8J

Scene 1, Layer 'Actions', Frame 1, 1084: Syntax error: expecting rightparen before colon

I'm new to ActionScript and I'm confused about these two errors. I already have some prior coding experience from other languages. Scene 1, Layer 'Actions', Frame 1, Line 78, Column 20 1084: Syntax error: expecting rightparen before colon. Scene 1, Layer 'Actions', Frame 1, Line 85, Column 20 1084: Syntax error: expecting rightparen before colon. This is my code. { timeStep += 1; //increment counter if (run) { //only if run = true is shift key has been pressed moveCharacter(evt:KeyboardEvent) { timeStep = 0; //reset the counter } } else if (timeStep == 2) { moveCharacter(evt:KeyboardEvent) { timeStep = 0; //reset the counter } } } I'm not sure where the problem is, I can't see one. Unless I'm blind. from Recent Questions - Stack Overflow https://ift.tt/34uay24 https://ift.tt/eA8V8J

Python sort_values (inplace=True) but not really?

So I am trying to write a loop in python as I have to compare rows to each other in a table. I have to sort the data, which I do by 'sort_values', the dataframe seems to sort, yet when I step through it with a 'for loop' it is still unsorted? So I'm clearly not understanding how pandas memory allocation works. I have tried sorting to another dataframe and I get the same problem import pandas as pd data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'], 'date1': ['2000-04-18', '2000-04-16', '2000-04-15', '2000-04-25', '2000-04-16', '2000-04-17'], 'stat1': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]} frame = pd.DataFrame(data) frame output original unsorted: state date1 stat1 0 Ohio 2000-04-18 1.5 1 Ohio 2000-04-16 1.7 2 Ohio 2000-04-15 3.6 3 Nevada 2000-04-25 2.4 4 Nevada 2000-04-16 2.9 5 Ne...

Do I have to deallocate gcnew System::EventHandler?

So I'm making my first windows application in windows forms and I have noticed that when I press a button multiple times in a row RAM usage rises. I thought I had memory leaks and I found this: this->button_to_decompress->Click += gcnew System::EventHandler(this, &MyForm::button_to_decompress_Click); Do I have to manually deallocate this? And if so how do I do that? My whole code: #pragma once #include <msclr/marshal_cppstd.h> #include "tree.h" using namespace msclr::interop; namespace CompressionTool { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::IO; /// <summary> /// /// </summary> public ref class MyForm : public System::Windows::Forms::Form { public: MyForm(void) { Initiali...

How to refer with a Foreign Key to a Primary key that has a specific value in some columns?

Let's say I have a site user table and they have an account type (client, master, and so on). Create table user_info( userId int not null, userPassword varchar(60), userEmail varchar(30), userLogin varchar(25), userType enum ('client','master','administrator'), Constraint Pk_userId Primary Key(userId)); And there is a table that describes the masters, in which the identifier refers only to those identifiers in the users table that are of the master type. Create table masters( masterId int not null, serviceId int, Constraint Fk_masterId Foreign Key(masterId)references user_info(userId)); How can I do this and is it possible? from Recent Questions - Stack Overflow https://ift.tt/3hZudyW https://ift.tt/eA8V8J

Access the second item in Collection [Map]

I'm making a discord bot, and fetching some messages. I got this object //This parameters changue every time i fetch Collection(3) [Map] { '848689862764789770' => Message {... } '848689552410804234' => Message {... } '848689534485004319' => Message {... } I can access the first and third entry using .first() and .last() . I've been trying to use Object.keys() but it returns undefined . const mensajes = await message.channel.messages.fetch({ limit: 3 }); console.log(mensajes[Object.keys(mensajes)[1]]) from Recent Questions - Stack Overflow https://ift.tt/34xbGCg https://ift.tt/eA8V8J

Parse Android Room Generated Schema to Actual SQLite Script

I want to create a .db file to pre populate my Android Room database but the database/schema is huge so I am trying to find a way not to do it manually. Basically I want to do the following: Generate the database schema for Room (done!) Generate the SQLite commands from the schema without needing to be reading the schema and copying and pasting all the scripts found in it Create the database on some SQL client Populate the database with the default data and generate a .db file from it to add into my app to be used by Room. I need help on step 2. Thanks a lot! from Recent Questions - Stack Overflow https://ift.tt/3wOWQmF https://ift.tt/eA8V8J

Late Binding: Expecting error but not getting it

I wrote the below code to understand Late Binding with Option Strict ON. With OPTION STRICT ON, I was expecting an error in the statement: o = New Car() . But not getting any error. Isn't that strange? Its clearly mentioned in the MSDN documentation on Option Strict that when ON it prevents late binding - gives a compile time error. So what is happening here....can someone pls help? Option Strict On Module Module1 Sub Main() Dim o As Object o = New Car() 'Expecting error here but not getting Console.ReadLine() End Sub End Module Class Car Public Property Make As String Public Property price As Integer End Class from Recent Questions - Stack Overflow https://ift.tt/2SBiSud https://ift.tt/eA8V8J

Axios - Prevent sending JWT token on external api calls

I'm building a fullstack app with nuxt + express and I have finally managed to include an authentication between my frontend/backend with passport and jwt. I want to make additional api requests to my own github repo for fetching the latest releases (so a user gets a information that an update exists). This requets failed with a "Bad credentials" messages. I think this happens because my jwt token is sent with it (I can see my token in the request header). My question is, is it possible to prevent axios from sending my JWT token in only this call? First, to make my request work and second, I don't want the token to be sent in external requests. Example: const url = 'https://api.github.com/repos/xxx/releases/latest' this.$axios.get(url) .then((res) => { this.latestRelease = res.data }).catch((error) => { console.error(error) }) from Recent Questions - Stack Overflow https://ift.tt/3uAJ5qa https://ift.tt/eA8V8J

Are amazon workspaces connected to the same network?

Any one knows if two stations created with the same amazon aws workspaces account share the same network ? Are they linked in any way ? Should I use vpn on each one if I want that they stay independent ? Thanks from Recent Questions - Stack Overflow https://ift.tt/3vDRrOZ https://ift.tt/eA8V8J

Handle "Slice Struct" properly? (golang)

I have created a Slice Struct. But why can't I append or output values? package main import "fmt" type Slicestruct []struct { num []int emptynum []int } func main() { slicestruct := &Slicestruct{ {[]int{1, 2, 3}, []int{}}, {[]int{4, 5, 6}, []int{}}, } // is working: fmt.Println(slicestruct) // isn't working: fmt.Println(slicestruct[0].num[0]) // isn't working: slicestruct[0].emptynum = append(slicestruct[0].emptynum, 99) } The error message is: "invalid operation: slicestruct[0] (type *Slicestruct does not support indexing)" from Recent Questions - Stack Overflow https://ift.tt/3yYjR8C https://ift.tt/eA8V8J

multiple images to one byte array? Array of byte arrays?

I have many images in a folder , I want to make one byte array for all of the images (array of byte arrays),but I only managed to make an array for one image . File file = new File("D:\\swim\\swim99.png"); //init array with file length byte[] bytesArray = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(bytesArray); //read file into bytes[] fis.close(); System.out.print(Arrays.toString(bytesArray)); So can I access multiple of images in a folder at once and get each one's byte array then put them into a 2D array of arrays array where the [Number of image[byte array image one]]? from Recent Questions - Stack Overflow https://ift.tt/3fvUz9V https://ift.tt/eA8V8J

How to intercept network calls in android and ios apps?

I have a chrome extension that works on a specific website by intercepting its network calls (xhr calls) performing some background processing and autofills the form for them and saves its users time. Doing it on a chrome extension is pretty easy as we have XMLHttpRequest https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest The website that my extension works has also launched a mobile app, and a lot of customers have migrated to the app instead of the desktop site. I am interested in building an android/ios app that could do the same things. Intercept the network calls made by the app. And overlay the information on the that app. I have tried to look into android/ios development docs for approaching this but couldn't get anything concrete. I believe my usecase is similar to what a VPN app does and I also know that drawing over other apps is also possible in mobile. Just want to get some of input from mobile developers how can I go about building this, my prima...

Yii2 adding an extra field to the form to add to database

On an existing project where there is a table with 3 fields (ID, name, label) `id` int(11) NOT NULL, `name` varchar(32) DEFAULT NULL, `label` varchar(1) DEFAULT 'A' Currently on the page where to add new record to the above table there is the form with only one field for the 'name', and works fine, and I need to add another field for the 'label' field; so I go to the related model (models/Products.php) and I have: public function attributeLabels() class Products extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'products'; } /** * {@inheritdoc} */ public function rules() { return [ [['name'], 'string', 'max' => 32], [['name'], 'unique'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ ...

js canvas ctx clip not working with forEach

In the beginning, there is for loop to generate colors and push them to an array. after that I want to print 50 circles with colors but when I use the ctx clip it did not print only one of them when I don't use ctx clip its print 50 of them var arr= [] for (var i = 1; i < 50; i++) { var color = "#"+ Array.from({length: 6},()=> Math.floor(Math.random()*16).toString(16)).join(""); arr.push({ color:color, name:i }) } var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); canvas.width = 35 * 10; canvas.height = (arr.length /10) *35; var x = 0,y = 10; arr.filter(role => !isNaN(role.name)).sort((b1, b2) => b1.name - b2.name).forEach(role => { x += 30; if (x > 40 * 8) { x = 30; y += 30; } ctx.arc(x+12.5, y+12.5, 12, 0, Math.PI* 2 , false); c...

how to get data using google sheets?

Sorry I'm a beginner I tried to get data from a web with google sheets Title and Pricing were successful but for Image Url, Description and highlights didn't work ( Imported content is blank. ) any idea ? this is the url https://www.lazada.co.id/products/gp-mall-penggaruk-punggung-alat-garuk-dan-pijat-punggung-garukan-energy-i1612070759-s3106188545.html?mp=1 from Recent Questions - Stack Overflow https://ift.tt/2TtC1yL https://ift.tt/eA8V8J

How do I access the onTextLayout event within a React Native Text component?

I have a React Native Text component that contains a user profile's information and has a max NumberOfLines at 2. I also have a TouchableOppacity button that says "Read More.." on it that clears the max NumberOfLines of the component. I don't want the "Read More" button to show if there the NumberOfLine is already 2 or less. In the documentation it says that the onTextLayout event would return an array with a TextLayout objects for each line but when I try to access it I never have anything returned. I've tried to access the onLayout event and I can get info from that event but it doesn't have the info that I need. Has anyone had this problem? <Text numberOfLines={2} onTextLayout={onInfoLayout}> test text test text test text test text test text test text test text test text </Text> } const onInfoLayout = React.useCallback((e:any) =>{ console.log("this is how long the text is", e); }, []); The c...

C++ static creator function that returns a null pointer if the parameter is invalid [closed]

I'm writing a class that doesn't provide a public constructor. Instead the user must create object through a creator function that takes some arguments. The creator function returns a pointer to the object if the passed arguments are valid and 'new' works, and a null pointer if the passed arguments are invalid or 'new' doesn't work. I know I can use a static creator function, but this way I wouldn't be able to initialize the fields from the passed arguments. What are some possible ways? from Recent Questions - Stack Overflow https://ift.tt/3hXUnlE https://ift.tt/eA8V8J

How to work with continious overdispered data

I have troubles with analysis of my data. I analyze cross-sectional data about users activities and spendings from mobile game . I have paying and non-paying users, I need to explain what independent varibles (such as time spend in the game, session lenght, clan (binary), number of messages in chat and etc.) can explain higher spendings in group of paying users. The data was pre-transformed, so instead of spendings in $ I can analyze only variables from 0 to 1 (1 is max spendings for sample, other variables vere divided by max value). I filtered dataset and got 12k observations with paying users. But, the data is overdispersed, and generally looks like negative exponential. I`ve tried to apply log transformation for my dependent variable (spendings) and for indepenent(time spend, session lenght and chat messages because they were skewd) and run linear regression, but R2 was only 0.09, which is quite low. Also, I tried to rond my data and multiply in order to use negative binomial regre...

How could I fs.unlink() a file that caused the error?

So, I'm working with files that all send POST requests to different URLs. However, if a POST request receives a 404 response it will error the entire network instead of just that file. Is there a way I would be able to fs.unlink() the file that caused the error? If not, is there another solution to this? As I don't want the entire server network to go offline just because of a 404 error on just one of the POST requests. onShoutEvent.on('data', async shout => { let embed = embedMaker(`New Shout!`, `\n"${shout.body}"`); embed.setAuthor(`${shout.poster.username}`); embed.setThumbnail(`http://www.roblox.com/Thumbs/Avatar.ashx?x=150&y=150&Format=Png&username=${shout.poster.username}`); embed.setURL(`https://www.roblox.com/groups/${group}`) embed.setFooter(`${customFooter}`) WebHookClient.send(embed); saveData(shout.body); }); It will check for new "shouts" and will send a request to that Webhook by POST, howe...

Python built-in assert

What is the main difference between assertEqual() and assertLogs()? I am using assertLogs() in a unittest and it works fine as I am using strings, but when I use assertEqual(), it fails the unittest. Unsure why. Thanks! from Recent Questions - Stack Overflow https://ift.tt/3c5NfzN https://ift.tt/eA8V8J

Calculation from a column from a dataframe to another dataframe based on matching index

I have 2 sets of stock data, I want to do a simple calculation to find the ratio between the close price of them. Here is my current code. The problem with this code is that the holidays are different and there for they don't always match so the dataset become desynchronized. How do I do this calculation using their index instead? australia['SP500_ratio'] = australia["Close"]/SP500["Close"] Example of data: SPY: Date Open High Low Close Adj Close Volume 4/22/2021 4170.459961 4179.569824 4123.689941 4134.97998 4134.97998 4235040000 4/26/2021 4185.029785 4194.189941 4182.359863 4187.620117 4187.620117 3738920000 4/27/2021 4188.25 4193.350098 4176.220215 4186.720215 4186.720215 3703240000 4/28/2021 4185.140137 4201.529785 4181.779785 4183.180176 4183.180176 3772390000 4/29/2021 4206.140137 4218.779785 4176.810059 4211.470215 4211.470215 4288940000 4/30/2021 4198.100098 4198.100098 4174.850098 4181.169922 4181.169922 4273680000...

Is there a reason for why I am getting the output as 0, 0, 0, 0?

I have the following code, which is suppose to print out roach values after the respective functions have been executed (roach.breed & roach.spray). However, I am getting values of zero. code for constructor: public class Roach { private int roach; /**@param roaches variables for number of roaches */ public void RoachPopulation(int roaches) { roach = roaches; } /** The population of roach doubles */ public void breed() { roach = roach * 2; } /** The population of the roach decreases by a percentage */ public void spray(double percent) { roach = roach -(int)(roach * (percent/100)); } /**@return Gets the population of the roach */ public int getRoaches() { return roach; } } The constructor: public class HelloWorld { public static void main(String[] args) { Roach roach = new Roach(); roach.breed(); roach.spray(10);; System.out.printl...

How to map observable object with inner observables?

How to map observable object with inner observables? Following is how I fetch details of an item. I want to map the received object with a property unwrapped. this.fetchData.getItemData().pipe( mergeMap((item: any) => { return { ...item, images: item.images.map(id => this.http.get(baseUrl + link)) -->> I want to unwrap here. (it is an observable; that's why!) } }) ) Here I'm mapping the inner property images which is an array to an array of observables!!! This is what I've tried: this.fetchData.getItemData().pipe( forkJoin((item: any) => { return { ...item, images: item.images.map(id => this.http.get(baseUrl + link)) } }) ) this.fetchData.getI...

RIP register doesn't change

Why stack and instruction pointer register dont change when i keep printing them using c and inline assembly , because logically others programs are running at the same time so they should keep changing while im printing from Recent Questions - Stack Overflow https://ift.tt/3wGYw1f https://ift.tt/eA8V8J

Accessing a JS variable from a different

I need to access a js variable declared in one block of a html page into another block of the same html page just so I can stop a ajax call that is being made, but I don't know how can I access a variable that was declared into another block. I can't merge the two blocks, everything else is on the table. <script> $(function() { var term = new Terminal('#input-line .cmdline', '#container output'); term.init(); }); </script> <script> term.ajaxHandler.abort();//but how can I access the variable term from the block above,this will be inside a button later </script> Thanks in advance from Recent Questions - Stack Overflow https://ift.tt/3yRp8Pk https://ift.tt/eA8V8J

How to get the updated entry string from a toplevel window before the tkinter main loop ends?

I have a toplevel window that pops up and asks you for your name. When you enter your name and click ok it should put the name in the entry1_value and close itself. Then I print the variable while keeping the empty (in this snippet of code) main window running. The problem is that it prints the 'Empty String' on the first print and then only the input on the second one. Here I'm just printing the information so I see if it registers it but I will use it somewhere later. Also, in reality I just need the updated information placed outside in any way without the main window closing. Here is the code: import tkinter as tk from tkinter import ttk BUTTON_FONT = ('Lato', 16) class NameInputBox: entry1_value = 'Empty String' def __init__(self, text): self.window = tk.Toplevel() self.window.wm_title("Input Name.") self.label_message = tk.Label(self.window, text = text, font = (BUTTON_FONT, 20)) self...

JS use video frame as canvas background

I'm attempting to use a the first frame of a video as the background of a canvas, as you probably guessed from the title of the question. I can set a background, I can get a frame from a video, but I can't make the frame be the background. It looks like I need a url for the frame to set as the background in the CSS style. For that, I need a blob on which I can call createObjURL() (although I'm discovering now that that method may be deprecated/ing). Here's some code: <!DOCTYPE html> <html lang="en"> <canvas id="back" style="background-image: url('path/to/.png')";></canvas> <input type="file" accept="video/*" /> <script> document.querySelector('input').addEventListener('change', extractFrame, false); var canvas = document.getElementById('back'); var context = canvas.getContext('2d'); var imageObj = new Image(); var image; ima...

Rails refactoring a method

im a new developer and i need some help to refactor this code So, I have a Rails App with a controller called subscription_signups. There i have a New method, that helps me create a Subscription, and it executes a private method called add_plan_to_cookies . This is my controller def new @subscription_signup = SubscriptionSignup.new(account_id: current_account.id) add_plan_to_cookies end private def add_plan_to_cookies plan = current_account.base_plans.find_by(id: params[:base_plan])&.current_plan remember_plan(plan.id) if plan.present? @plan = current_account.base_plans.find_by(id: cookies.signed[:plan])&.current_plan end def remember_plan(plan) cookies.signed[:plan] = plan end In the add_plan_to_cookies method, the plan is obtained through the base_plan_id and then another method called remember_plan is executed and saves the plan in a cookie. What i have to do is using the plan that was saved in the cookie. & I can obtain t...

How do I "sharpen" the edge of the path in the image with Stroke Path?

Image
I'm trying to use the stroke path function on a jagged path as shown in the image. I'd prefer to keep the line width, cap style, join style the same. I've tried adjusting the miter limit, going all the way to 100, but i'm still getting that rounded edge at the bottom left corner of the path. Compared to the right side, it is noticeably different. I've already tried adjusting all the settings in the stroke path section, even changing my path, increasing the angle of the corner, etc but nothing works. Any ideas? from Recent Questions - Stack Overflow https://ift.tt/2RXSqen https://ift.tt/2SCVFbc

Terraform split subnets between 2 route tables

I have created a large amount of azure subnets with terraform, but i need to split them all between 2 route tables. Currently i have my code like this, but of course the output from the resource is not a list, but objects. resource "azurerm_subnet_route_table_association" "subnet-to-rt1" { for_each = tolist(chunklist(azurerm_subnet.subnets, 255)[0]) subnet_id = (chunklist(azurerm_subnet.subnets, 20)[0])[each.key].id route_table_id = module.spoke.route_table_1 } resource "azurerm_subnet_route_table_association" "subnet-to-rt2" { for_each = tolist(chunklist(azurerm_subnet.subnets, 20)[1]) subnet_id = (chunklist(azurerm_subnet.subnets, 20)[1])[each.key].id route_table_id = module.spoke.route_table_2 } Edit: Code to generate the subnets for clarity of the problem. I provide the var.spoke_cidr in an slash /18 range to get /27's resource "azurerm_subnet" "subnets" { for_each =...

SQL unpivot of multiple columns

I would like the following wide table to be unpivotted but only where a user has a true value against the field, along with the appropriate date (please see image for a cleaner version: https://i.stack.imgur.com/9utkN.png ). Current State: CUSTOMER_ID First_Party_Email Third_Party_Email First_Party_Email_Date Third_Party_Email_Date 40011111 1 1 2021-01-22 04:38:00.000 2021-01-17 06:38:00.000 50022222 NULL 1 NULL 2021-01-18 04:38:00.000 80066666 1 NULL 2021-01-24 05:38:00.000 NULL _______________ _______________________ _______________________ _______________________________ _______________________________ Required State: Customer_ID Type Value Date 40011111 First_Party_Email 1 22/01/2021 04:38 40011111 Third_Party_Email 1 17/01/2021 06:38 50022222 Third_Party_Email 1 18/01/2021 04:38 80066666 First_Party_Email 1 24/01/2021 05:38 _______________________________________________________________________ ...

Edit and save shared preferences in Android Studio

I can access shared preferences in Android Studio from Device file explorer, but after editing the file, the changed values aren't saved. How can I save the changes? from Recent Questions - Stack Overflow https://ift.tt/3wLBTsu https://ift.tt/eA8V8J

Power BI - Prior Month Values and % Change for a existing measure which aggregates from daily to monthly

I have a table with daily observations. I have an existing measure (Total_Visits_Sum) that provides the data on a monthly or quarterly basis based on the date I use for the axis. If I use a custom column in the calendar for MMM-YY the data automatically gets aggregated. SUMMARIZE ( 'Data', 'Data'[Date]), CALCULATE ( SUM ( 'Data'[Visits]))) My question is how do I get the prior month's value to compare, so I could do a month-over-month change? I have seen the examples that do this but only when the underlying frequency of the data is monthly, not aggregated like I am doing. from Recent Questions - Stack Overflow https://ift.tt/3oYxhN8 https://ift.tt/eA8V8J

How to select using CONTAINS instead of LIKE with JPA

I'm developing small java applications to school projects with PostgreSQL. Using the JDBC driver I could select a field using the ~ operator to act as CONTAINING instead of concatenating the filter using LIKE . Let me give you an example: SELECT * FROM USERS WHERE NAME ~ ? ORDER BY NAME Since we started using the JPA framework to ease the development, I noticed that the same sample using JPA throws an error when I use the ~ operator... Error thrown: An exception occurred while creating a query in EntityManager: Exception Description: Syntax error parsing [select u from Users u where u.name ~ ?1 order by u.name]. [30, 41] The expression is not a valid conditional expression. All code samples I could find on google are made using LIKE instead of CONTAINING . My question is, does JPA support the containing operator when working with PostgreSQL? Some info: JDK 15 Netbeans 12.3 JPA 2.1 PostgreSQL 13.2 from Recent Questions - Stack Overflow https://ift.tt/3fTLtTx http...

Using Content-Security-Policy to allow ws connections on https website

I have a HTTPS website which needs to communicate with a backend securely. I also need it to be able to interface with some hardware that only accepts ws connections (NOT wss). I am wondering whether it is possible (and if so, exactly how) to connect with this hardware. I read here that setting the Content-Security-Policy header to certain values can help enable this. I was wondering if anyone knows whether this approach will work, or if they have suggestions for any other approaches. from Recent Questions - Stack Overflow https://ift.tt/3p0xJKJ https://ift.tt/eA8V8J

Forcing bandwidth from one router to another

So I have an two internet providers in two different locations. One is much better than the other with unlimited data and lightning fast speed while the other has unlimited data until it hits a wall at 15GB where the bandwidth is severely throttled back. It got me thinking... is it possible to force bandwidth from one router to another, and to be more specific, from one router to another not in the same location as each other. I know it’s possible to do when hardwired and a little knowhow as well as removing the throttle put in place on one that is throttled, but has anyone ever tried something like this? from Recent Questions - Stack Overflow https://ift.tt/3wFpFBR https://ift.tt/eA8V8J

Can I allow users to delete my Slack bot messages?

I created a Slack bot that allows coworkers to report issues to certain channels, but occasionally someone misclicks or wants their report (reported in Slack by the bot via chat.postmessage ) deleted. As far as I can tell, this can only be done by the bot itself through a message shortcut or an interactive message with chat.delete . I would like it to be deletable by users in the same way they would delete their own messages, by clicking the ellipses on the post and choosing delete message in the context menu. Is there a way, either by OAuth scopes or maybe Slack/Workspace/Channel admin permissions this can be done? from Recent Questions - Stack Overflow https://ift.tt/3c1X3dY https://ift.tt/eA8V8J

Undefined references when linking libpng

I'm compiling a planet map generator that requires libpng. While I successfully fixed other errors, this was impossible to remove: png_utils.o:png_utils.c:(.text+0x91): undefined reference to `png_create_write_struct' png_utils.o:png_utils.c:(.text+0xa4): undefined reference to `png_create_info_struct' png_utils.o:png_utils.c:(.text+0xca): undefined reference to `png_set_longjmp_fn' png_utils.o:png_utils.c:(.text+0x135): undefined reference to `png_set_IHDR' png_utils.o:png_utils.c:(.text+0x14e): undefined reference to `png_malloc' png_utils.o:png_utils.c:(.text+0x19e): undefined reference to `png_malloc' png_utils.o:png_utils.c:(.text+0x217): undefined reference to `png_init_io' png_utils.o:png_utils.c:(.text+0x230): undefined reference to `png_set_rows' png_utils.o:png_utils.c:(.text+0x252): undefined reference to `png_write_png' png_utils.o:png_utils.c:(.text+0x281): undefined reference to `png_free' png_utils.o:png_utils.c:(.text+0x297):...

RHEL 8.3: Toggle Top Icons Plus Gnome extension in Tweak Tool with script

Is there a way to toggle the Gnome Extension Top Icons Plus in Tweak Tool in a script? Currently I am unable to find any APIs provided by Tweak Tool or Top Icons Plus. from Recent Questions - Stack Overflow https://ift.tt/3fw1L5X https://ift.tt/eA8V8J

Nginx URL rewrite for language parameters

I have recently localized my php webpage with Gettext in a VPS running LEMP Debian 10 (PHP 7.3.27-1~deb10u1). The localized versions of the pages have the following URLs: example.com/index.php?lang=es_ES and example.com/index.php?lang=en_GB and so on. I am trying get Nginx to rewrite the URL requests to fake folders in the following way: example.com/en/index.php to=> example.com/index.php?lang=en_GB example.com/es/index.php to=> example.com/index.php?lang=es_ES and example.com/en/manage/index.php to=> example.com/manage/index.php?lang=en_EN example.com/es/manage/index.php to=> example.com/manage/index.php?lang=es_ES And so on. I have tried other solutions with no success. My Nginx server block configuration is as follows: server { root /var/www/example.com; index index.html index.htm index.php; server_name example.com; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf...

SQL Finding Order ID and Total Price of Each Order

I have a database where I have to determine the OrderID and total price of each order. The issue is finding the price on the specific day of the order. Every product has a price on a particular day using the "from" attribute. I need to get only the price of the product where the "from" attribute is less than the current "date" attribute. This is what I have been trying. SELECT O.orderId, (P.price + S.price) AS total_price FROM Price P INNER JOIN PO ON PO.prodId = P.prodId INNER JOIN [Order] O ON PO.orderId = O.orderId INNER JOIN Shipping S ON S.shipId = O.shipId GROUP BY O.orderId, O.[date], P.price, S.price HAVING O.[date] IN ( SELECT O.[date] FROM [Order] WHERE MAX(P.[from]) <= O.date ) ORDER BY orderId; I still get some duplicates from this and it is not giving me every orderId. from Recent Questions - Stack Overflow https://ift.tt/3wH5nYJ http...

Return true if the array contains duplicate elements (which need not be adjacent)

When I execute this, even if there are no duplicates, it displays true. Basically, it displays true for every array that I put in. I have no idea why it's showing me that. I would appreciate some help in this problem! Thanks! public static boolean Duplicate() { int [] duplicateArray = new int[5]; System.out.print("Enter your array numbers:"); System.out.println(); for(int i = 0; i < duplicateArray.length; i++) { Scanner in = new Scanner(System.in); duplicateArray[i] = in.nextInt(); } boolean same = false; for(int i = 0; i < duplicateArray.length-1; i++) { for(int j = 0; j < duplicateArray.length; j++) { if(i==j) { same = true; } } } return same; } from Recent Questions - Stack Overflow https://ift.tt/3yOmBFx https://ift.tt/eA8V8J

three.js, How do I get a CSS3DObject to show up? (what am I doing wrong)

I set up a CSS3DRenderer, a scene, a camera, in my HTML document I have an element that I am trying to turn into a CSS3DObject, and I have my CSS3DRenderer using .render in a game loop. I created a CSS3D object, put the HTML element as the argument, added it to my scene, and nothing happened. I must add that I do have a WebGL renderer using the same camera and a different scene, that renderer is working just fine. Here are my import statements: import * as THREE from 'https://threejs.org/build/three.module.js'; import { GLTFLoader } from 'https://threejs.org/examples/jsm/loaders/GLTFLoader.js'; import { CSS3DRenderer } from 'https://threejs.org/examples/jsm/renderers/CSS3DRenderer.js'; import { CSS3DObject } from 'https://threejs.org/examples/jsm/renderers/CSS3DRenderer.js'; Here is how I initialized the renderers: const renderer = new THREE.WebGLRenderer({canvas: document.querySelector('#bg')}); const cssRenderer = new CSS3DRenderer(); this ...

How do I write this in SQL view?

Image
create a view called StudentListByCourse. The view should contain these columns from the following ER model and the output should be sorted by the course name: Course name Student name Student age This is what I have but im not sure if this is correct CREATE VIEW StudentListByCourse SELECT * FROM student AS s WHERE courses AS c SORT BY c.coursename, s.studentname, s.studentage from Recent Questions - Stack Overflow https://ift.tt/34sH5Wi https://ift.tt/34sH6tk

Registering a “typed” gRPC client with the ASP.NET Core DI container

I have a GrpcService class the takes in gRPC client in its constructor, like so: public class GrpcService : IService { private readonly GrpcClient grpcClient; public GrpcService(GrpcClient grpcClient) { this.grpcClient = grpcClient; } //... } I have registered the gRPC client in the Startup class by using the generic AddGrpcClient extension method: services.AddGrpcClient<GrpcClient>(o => { o.Address = new Uri("https://localhost:5001"); }); Now I want to inject the GrpcService class into a API controller. My question is; what's is the correct way to register the GrpcService in the Startup class? I did try the following, which did not work: services.AddGrpcClient<GrpcService>(); At the moment I have the following code, which works fine: services.AddSingleton<IService, GrpcService>(); However, I'm not certain using a singleton is the correct lifetime to use, in particular as the gRPC client uses HttpC...

How to read a file in utf8 encoding and output in Windows 10?

Image
What is proper procedure to read and output utf8 encoded data in Windows 10? My attempt to read utf8 encoded file in Windows 10 and output lines into terminal does not reproduce symbols of some languages. OS: Windows 10 Native codepage: 437 Switched codepage: 65001 In cmd window issued command chcp 65001 . Following ruby code reads utf8 encoded file and outputs lines with puts . fname = 'hello_world.dat' File.open(fname,'r:UTF-8') do |f| puts f.read end hello_world.dat content Afrikaans: Hello Wêreld! Albanian: Përshendetje Botë! Amharic: ሰላም ልዑል! Arabic: مرحبا بالعالم! Armenian: Բարեւ աշխարհ! Basque: Kaixo Mundua! Belarussian: Прывітанне Сусвет! Bengali: ওহে বিশ্ব! Bulgarian: Здравей свят! Catalan: Hola món! Chichewa: Moni Dziko Lapansi! Chinese: 你好世界! Croatian: Pozdrav svijete! Czech: Ahoj světe! Danish: Hej Verden! Dutch: Hallo Wereld! English: Hello World! Estonian: ...

Show / hide element based on which option was selected [closed]

What would be the JavaScript code to display the input field if I choose the second <option> tag and reverse (do not display input) if I choose the first <option> ? <div id="bmi"> <p id="head"> BMI Calculator </p> <p><b>Select the Measure <select id="method" onchange="standard()"> <option id="metric">Metric</option> <option id="standard">Standard</option> </select> </b></p> <p><b>Input your Height Below:</b></p> <br> <input type="text" id="height" /> <p><b>Input your Weight Below:</b></p> <input type="text" id="weight" /> <br> <button id="onSubmit">Calculate</button> <br> <h1 id="result"></h1> </div> from Recent Ques...

Quick search for an object in an array

The task is to quickly find an object in the array. There is an array containing data about users. During the course of the program, the data of individual users will change. What is the most efficient way to search for a user in an array? I've read about hash functions and hash tables, but I don't fully understand how I need to use them. I should create a dictionary like: {'name of user': index} from Recent Questions - Stack Overflow https://ift.tt/3wLDZsF https://ift.tt/eA8V8J

how to open all links in a file and ignore comments using firefox?

so the file contains data like # entertainment youtube.com twitch.tv # research google.com wikipedia.com ... and I would like to pass that file as an argument in a script that would open all lines if they doesn't start with an #. Any clues on how to ? so far what i have: for Line in $Lines do case "# " in $Line start firefox $Line;; esac done some code that could be useful (?): while read line; do chmod 755 "$line"; done < file.txt from Recent Questions - Stack Overflow https://ift.tt/3wHULIW https://ift.tt/eA8V8J

How do I pass the value of a variable in C to an argument of an instruction in inline assembly? [duplicate]

I am trying to use the value of a variable I've declared in C as the argument of a mov instruction in assembly. I've tried using a conversion character like this (where ptr is the variable): asm("mov x9, %p\n\t" : : "r"(ptr)); But it doesn't compile and outputs an error of: error: invalid % escape in inline assembly string asm("mov x9, %p\n\t" : : "r"(ptr)); ~~~~~~~~~~~^~~~~ I've also tried it without the \n\t and it gives the same error. It's not really specific as to what's wrong with it so I'm not sure how to deal with this. How can I get it to compile or achieve the same outcome in a different way? from Recent Questions - Stack Overflow https://ift.tt/34pA88m https://ift.tt/eA8V8J

Is it even possible to filter a JsonField tuple or list? (Filtering only works for dictionaries?)

The documentation has info on querying JsonFields for dictionaries but not for lists or tuples. # models.py class Item(model): numbers = JSONField() # tests.py a = Item.objects.create(numbers=(1, 2, 3)) b = Item.objects.create(numbers=(4, 5, 6)) Item.objects.filter(numbers=a.numbers).count() # returns 0 Item.objects.filter(numbers__0=a.numbers[0]).count() # returns 0 Item.objects.all().count() # correctly returns 2 a.numbers # correctly returns (1, 2, 3) a.numbers[0] # correctly returns 1 How can I query or filter by a JsonField if that field is a tuple or list? from Recent Questions - Stack Overflow https://ift.tt/3vwiOut https://ift.tt/eA8V8J

How to use both MFRC522 and RDM6300 using a NODEMCU

I want to use both MFRC522 and RDM6300 readers on a single NodeMCU, the two separate codes for each readers are respectively : /* * -------------------------------------------------------------------------------------------------------------------- * Example sketch/program showing how to read data from a PICC to serial. * -------------------------------------------------------------------------------------------------------------------- * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid * * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID * Reader on the Arduino SPI interface. * * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When * you present a PICC (that is:...