Sunday, December 5, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Typeerror: 1 positional argument but 2 were given, torch.nn.linear takes

Posted: 05 Dec 2021 02:24 PM PST

I am using EfficientNet to extract features and trying to add a fully connected layer to pre-trained model to reduce the dimension of the out-features from efficientnet to 512. I encountered the following error when the features pass through the layer or the function that I defined.

"Typeerror: 1 positional argument but 2 were given"

Here are the code that I tried:

# define a function to reduce the dimension to 512  # def block_dim_red():  #     block_dim_red = Sequential(OrderedDict([  #         ('fc', Linear(1280, 512)),  #     ]))  #     return block_dim_red    def fc():      fc = Linear(in_features = 1280, out_feaures = 512)      return fc  

The following codes show how I defined the Class BaseModel(object).

Thank you very much in advance.

class BaseModel(object):

def __init__(self):      self.image_size = 224      self.dimision = 1280      self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")      self.load_model()    def load_model(self):      self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")      self.model = EfficientNet.from_pretrained('efficientnet-b0').to(self.device)        self.model = self.model.eval()      self.PIXEL_MEANS = torch.tensor((0.485, 0.456, 0.406)).to(self.device)      self.PIXEL_STDS = torch.tensor((0.229, 0.224, 0.225)).to(self.device)      self.num = torch.tensor(255.0).to(self.device)    def preprocess_input(self, image):      image = cv2.resize(image, (self.image_size, self.image_size))      # gpu version      image_tensor = torch.from_numpy(image.copy()).to(self.device).float()      image_tensor /= self.num      image_tensor -= self.PIXEL_MEANS      image_tensor /= self.PIXEL_STDS      image_tensor = image_tensor.permute(2, 0, 1)      return image_tensor    # define a function to reduce the dimension to 512  # def block_dim_red():  #     block_dim_red = Sequential(OrderedDict([  #         ('fc', Linear(1280, 512)),  #     ]))  #     return block_dim_red    def fc():      fc = Linear(in_features = 1280, out_feaures = 512)      return fc    def forward(self, x):      x = self.preprocess_input(x).unsqueeze(0)      # extraccted feature shape torch.Size([1, 1280, 7, 7])      x = self.model.extract_features(x)      x = F.max_pool2d(x, kernel_size=(7, 7))      x = x.view(x.size(0),-1)      x = torch.reshape(x,(-1,1))      x = self.fc(x) # fully connecte layer to reduce dimension        return self.torch2list(x)      def torch2list(self, torch_data):      return torch_data.cpu().detach().numpy().tolist()  

def load_model(): return BaseModel()

I'm getting error code "Syntax error: Expected ")" but got "(" at [7:27]" on Bigquery

Posted: 05 Dec 2021 02:24 PM PST

I'm learning to write sub-queries on Bigquery and keep getting error "Syntax error: Expected ")" but got "(" at [7:27]". I have searched here and rechecked my code multiple times, but can't seem to resolve this issue. Here is my code :

  station_id,    name,    num_of_rides AS num_of_rides_starting_at_station  FROM (    SELECT      start_station_id COUNT(*) number_of_rides    FROM      bigquery-public-data.new_york.citibike_trips    GROUP BY      start_station_id ) AS station_num_trips  INNER JOIN    bigquery-public-data.new_york.citibike_stations  ON    station_id = start_station_id  ORDER BY    number_of_rides DESC)```  

How to play a sound on a checkbox in html css

Posted: 05 Dec 2021 02:24 PM PST

        <audio id="myaudio" src="img/toggle.mp3" ></audio>              <div class="buttonpos">          <input class="toggle" onchange="myfunction" type="checkbox" id="switch">          <label onchange="document.getElementById('myaudio').play();" for="switch" class="switchLabel">            <span class="switchLabelBg"></span>          </label>        </div>  

Why does this not work? I am trying to make a sound play when i click on my checkbox!

Image On Hover Play Video And Reset the div with image on completion

Posted: 05 Dec 2021 02:24 PM PST

I would like to show thumbnails for videos on load and on hover or touch I want to play the video inside the parent div of the image. On mouseout and video ends, the div should show the image automatically. How can I do it?

Javascript per second calculation

Posted: 05 Dec 2021 02:24 PM PST

I am currently wracking my brain to work out what should probably be a relatively simple per second calculation. I have a loading bar increase and at the end of that, it adds 1 to the total. The loading bar consists of:

wId = setInterval(worker_identify_call, wIdSpeed);  

and

function worker_identify_call(){      worker_identify_amount++;      wElem.style.width = worker_identify_amount + '%';  }  

wIdSpeed = 250.

I am trying to calculate how long, in seconds, it will take to reach the top of the loading bar (100%).

I currently have ((1000/wIdSpeed).toFixed(2)) but that just calculates how long a cycle of setInterval takes.

CodePen with example here.

Any help is appreciated!

ggplot visual of the convex hull - shiny

Posted: 05 Dec 2021 02:23 PM PST

I want to create a ggplot visual of the convex hull for any numeric variables the user provides while allowing the hull to split into several hulls for a chosen categorical input variable.

Something like this in shiny where users can pick as many x variables they want

library(datasets)  library(ggplot2)  library(ggpubr)    df<- iris  str(df)    b <- ggplot(df, aes(x = Sepal.Length+Sepal.Width, y = Petal.Width))     # Convex hull of groups  b + geom_point(aes(color = Species, shape = Species)) +    stat_chull(aes(color = Species, fill = Species),                alpha = 0.1, geom = "polygon") +    scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07")) +    scale_fill_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))  

Here is my shiny code so far, which, needless to say does not work.Any help will be greatly appreciated

library(shiny)  library(dplyr)  library(ggplot2)  library(ggpubr)  df<- mtcars  numeric_cols <- df %>% select(where(is.numeric))  categorical_cols <- df %>% select(where(is.factor))  ui <- fluidPage(    titlePanel("MTCARS"),    selectInput("Columns","Numeric Columns",                names(numeric_cols), multiple = TRUE),    selectInput("Columns","Categorical Columns",                names(categorical_cols), multiple = TRUE),    plotOutput("myplot")  )    server <- function(input, output) {    Dataframe2 <- reactive({      mtcars[,input$Columns]     })        my_plot<- reactive({ggplot(Dataframe2(), aes(mpg, cyl))+geom_point()})    output$myplot <- renderPlot({      my_plot()    })  }    shinyApp(ui, server)  

CSS: Show the last 3 elements before a specific class

Posted: 05 Dec 2021 02:23 PM PST

So I have no idea whether CSS has any calculations that will give me my desired result but I want to show the last three elements before a specific class, in my code below I have been playing with nth-child but I can only get this to remove elements before, in my current example I can show the last three records before the "CurrentYear" class but I have to remove the first nine, my issue is this number is always changing, there might only be 6 records so I only want to hide 3 of the 6.

FIDDLE

.eaKeyDate { width:30px; height:20px; line-height:20px; text-align:center; border:solid 1px #ccc; display:none }    .eaKeyDate:nth-child(n+9) { background-color:green; color:white; display:block; }    .eaKeyDate.CurrentYear { background-color:red !important; color:white !important; display:block !important; }    <div class="eaKeyDate">1</div>  <div class="eaKeyDate">2</div>  <div class="eaKeyDate">3</div>  <div class="eaKeyDate">4</div>  <div class="eaKeyDate">5</div>  <div class="eaKeyDate">6</div>  <div class="eaKeyDate">7</div>  <div class="eaKeyDate">8</div>  <div class="eaKeyDate">9</div>  <div class="eaKeyDate">10</div>  <div class="eaKeyDate">11</div>  <div class="eaKeyDate CurrentYear">12</div>  <div class="eaKeyDate CurrentYear">1</div>  <div class="eaKeyDate CurrentYear">2</div>  <div class="eaKeyDate CurrentYear">3</div>  <div class="eaKeyDate CurrentYear">4</div>  <div class="eaKeyDate CurrentYear">5</div>  <div class="eaKeyDate CurrentYear">6</div>  <div class="eaKeyDate CurrentYear">7</div>  <div class="eaKeyDate CurrentYear">8</div>  <div class="eaKeyDate CurrentYear">9</div>  <div class="eaKeyDate CurrentYear">10</div>  <div class="eaKeyDate CurrentYear">11</div>  

Is there anyway in CSS I can just say "show the last three records before the first instance of CurrentYear".

P.S. I am only trying to resolve this in CSS, I know its easy done in JS but currently that's not an option.

Thanks

How can added any Serial number in Contact Form 7

Posted: 05 Dec 2021 02:23 PM PST

How can added in Contact Form 7 Auto Gernated serial number 15 digit ? Any plugin or code embed ?

How to plot the values of a groupby on multiple columns

Posted: 05 Dec 2021 02:23 PM PST

I have a dataset similar to the following:

Country Date Sales
Spain Jan 2020 20000
Italy Jan 2020 30000
France Jan 2020 10000
Germany Jan 2020 10000
Portugal Jan 2020 30000
Greece Jan 2020 10000
UK Jan 2020 10000
Spain Feb 2020 50000
Italy Feb 2020 40000
France Feb 2020 30000
Germany Feb 2020 20000
Portugal Feb 2020 30000
Greece Feb 2020 10000
UK Feb 2020 10000
... ... ...
Spain Dec 2020 60000
Italy Dec 2020 70000
France Dec 2020 80000
Germany Dec 2020 10000
Portugal Dec 2020 30000
Greece Dec 2020 10000
UK Dec 2020 10000

I would like to visualize how the Sales varied over the year by Country therefore I would like to show 7 histograms (one for each Country). For each plot, the 'Date' will be on the x-axis and the 'Sales' values on the y-axis. Also, a title to identify the Country is required as well as the x-label, y-label.

I have tried several options found in previous discussions but none of those works with what I want to achieve. I have tried the following:

df.groupby('Country').hist(column='Sales', grid= False, figsize=(2,2))  
df['Sales'].hist(grid=True, by=one_year_df['Country'])  
df.groupby('Country').hist(grid= False, figsize=(2,2))  
df.reset_index().pivot('index','Country','Sales').hist(grid=False, bins=12)  
grouped = df.groupby('Country')    ncols=2  nrows = int(np.ceil(grouped.ngroups/ncols))    fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,12), sharey=False)    for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):      grouped.get_group(key).plot(ax=ax)    ax.legend()  plt.show()  

However, none of these options gives me the possibility to set the 'Date' column, also it seems that it is not possible to set the x-axis, y-axis as I wish and as a result, the plots are meaningless.

I have also found another piece of code that seems to consider all the variables but the result still is not as expected:

fig, ax = plt.subplots(figsize=(15,7))  df.groupby(['Country']).sum()['Sales'].plot(ax=ax)  ax.set_xlabel('Date')  ax.set_ylabel('Sales')  

Any comments or suggestions are welcome. Thank you.

Passing javascript variable to spring MVC controller with request param

Posted: 05 Dec 2021 02:23 PM PST

Is it possible to send a javascript variable to a controller endpoint, and then have the controller return a new view? I've tried using a requestbody and ajax to do it, which passes the variable correctly, but is unable to load a new view.

Maybe there's a way to do it with thymeleaf?

Syntax error using sed for a find and replace

Posted: 05 Dec 2021 02:22 PM PST

I am trying to do a find and replace using sed. I am trying to find that : purge: [], to replace by purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"], but it does not work, here is my commande :

sed -i -e 's/purge: [],/purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],/g' myfile.txt  

Could you help me please ?

Thank you very much !

Text Goes Wrong On Mobile & Size Widget

Posted: 05 Dec 2021 02:22 PM PST

This is photo for problem

any one can help me?

Insertion sort algorithm doesn't bother about last number in list

Posted: 05 Dec 2021 02:24 PM PST

I'd like to write a insertion sort algorithm. I've almost finished it, but the function itself seems to not even bothering about last number. What could be wrong here?

def insertion_sort(user_list):      sorted_list = []      sorted_list.append(user_list[0])      for index in range(0, len(user_list)):          if user_list[index] < user_list[-1]:              for reversed_index in range(index, 0, -1):                  if user_list[reversed_index] < user_list[reversed_index-1]:                      user_list[reversed_index], user_list[reversed_index-1] = user_list[reversed_index-1], user_list[reversed_index]                      print(user_list)        print("\n\n", user_list)      if __name__ == '__main__':      user_list = [4, 3, 2, 10, 12, 1, 5, 6]      insertion_sort(user_list)  

How to check if class from vector is a derived class?

Posted: 05 Dec 2021 02:23 PM PST

Consider the code:

class BaseClass { /* ... */ };  class DerivedClass : public BaseClass { /* ... */ };    std::vector<BaseClass> vClasses;    int main() {        BaseClass foo1;      vClasses.push_back(foo1);        BaseClass foo2;      vClasses.push_back(foo2);        DerivedClass bar;      vClasses.push_back(bar);        for (BaseClass& el : vClasses)      {          if (DerivedClass* d_el = dynamic_cast<CPremiumHero*>(&el)) {                d_el.CallMethodsFoundInDerivedClass();          }          else {                el.CallDefaultMethods();          }      }  }  

How do I check that one of the elements from the vector is a DerivedClass, then using it further on? The if (DerivedClass* d_el = dynamic_cast<CPremiumHero*>(&el)) statement throws an error the operand of a runtime dynamic_cast must have a polymorphic class type . I don't know what that means, neither do I know what other methods I should use.

How to flip the video without flipping the captions?

Posted: 05 Dec 2021 02:22 PM PST

So, I have the code below that will add a caption to the video.

video.addEventListener("loadedmetadata", () => {          video.play();          track = video.addTextTrack("captions", "English", "en");          track.mode = "showing";          track.addCue(new VTTCue(0, 100, username));                });  

I am rotating it to mirror the video with this css:

#video-grid > video {      transform: rotateY(180deg);      -webkit-transform: rotateY(180deg);      -moz-transform: rotateY(180deg);      height: 300px;      width: 400px;  }  

However, the caption is also getting flipped. How can I avoid it to flip the caption or how to flip it back?

enter image description here

SQL Querying a Database Using The Current Date and Date associated with an Attribute

Posted: 05 Dec 2021 02:23 PM PST

I am trying to query a from scratch database I created. For each job posting in my database, I store the date of which it was posted in the 'date' datatype, which is in the format of "DD-MON-YY". I want to know which job postings haven't been filled after one month after its posted date.

So far I can query my database and find which jobs haven't been filled, due to a particular attribute being null in my table. But I don't know how to add the condition that it has been at least one month.

SELECT JOBID  FROM JOB  WHERE HIRED IS NULL;  

For reference I have created this database in Oracle, and am using SQL developer.

Dataframe manipulation bioinformatics [closed]

Posted: 05 Dec 2021 02:24 PM PST

ref_1 A_1 C_1 G_1 T_1
G 0.168 0.232 0.028 0.07

Bioinformatics problem: I have a dataframe that I want to add a new column to. In this new column, I am trying to scan the row and identify the column with the highest integer. Upon identifying the highest integer, I am trying to pull the column name (Only the first letter). In this example, C_1 has the highest integer so for my expected output: Expected output:

ref_1 A_1 C_1 G_1 T_1 CALL
G 0.168 0.232 0.028 0.07 C

Why is my transition time not being applied?

Posted: 05 Dec 2021 02:23 PM PST

I am pushing each raindrop into rainDropArray, then I thought to call a function within the rainDropInterval, hmm(), and Im getting the transformation, just not the timed transition.

var rainDropArray = [];  var rainDrop;  var randomDrop;  var yourTankOverThere;  var a = 0;  var rainDropInterval = setInterval(function() {      randomDrop = Math.floor(Math.random() * 1000);    rainDrop = document.createElement('div');    document.body.appendChild(rainDrop);    rainDrop.style = 'box-sizing:border-box;border:1px solid green;height:7px;width:7px;background-color:green;position:absolute;top:0px;left:' + randomDrop + 'px;transition:transform 10s';    rainDrop.setAttribute('id', 'drop' + a);    yourTankOverThere = document.querySelector("#drop" + a);    rainDropArray.push(yourTankOverThere);      hmm();  }, 100);    function hmm() {    rainDropArray[a].style.transform = "matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,1000,0,1)";    a++  }

How do I convert List<String?> to List<String> in .NET 6 / C# 10?

Posted: 05 Dec 2021 02:24 PM PST

Using .NET 6 I have the following:

List<String> values = new List<String?> { null, "", "value" }    .Where(x => !String.IsNullOrEmpty(x))    .Select(y => y)    .ToList();  

But I am getting the warning:

Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'.  

I thought that using

.Where(x => !String.IsNullOrEmpty(x))  

would solve the problem but it doesn't. How to fix this?

Android show no output from Inputstream reader and Procees return exit code 1

Posted: 05 Dec 2021 02:23 PM PST

i am trying to run a process and to read it's data from InputStreamReader, but it fails in a weird way.

The executable is "ip neigh show"

When trying to run the command from connected device via adb shell the command executes OK and also displays data correctly.

But when trying to execute it from kotlin code it exit with exit code 1 and InputStreamReader show empty data also.

This is how i am trying it :

val p = Runtime.getRuntime().exec("ip neigh show")  InputStreamReader(p!!.inputStream).forEachLine fori@{ line ->                      val teDhenat = line.split("\\s+".toRegex())                      if (teDhenat[0] == ip) {                          if (teDhenat.size < 4) {                              return@fori                          } else {                              uGjet = true                              macAddress = teDhenat[4]                              return@fori                          }                      }                  }  

The problem seems to happen in that line : val p = Runtime.getRuntime().exec("ip neigh show") but i don't understand why.

Also tried with val p = Runtime.getRuntime().exec("/system/bin/ip neigh show") and it's still the same.

Also i have tried using ProcessBuilder() and it doesn't work too.

The Compile and Target SDK is 31 The phone is Xiaomi running Android 11 (SDK 30)

PS: Also i am using same logic for other executables and they work very fine like "ping", "top" etc...

Documentation says "default operator == implementation only considers objects equal if they are identical",why isnt it applied here?

Posted: 05 Dec 2021 02:24 PM PST

    import 'dart:core';        void main() {      String characters = 'World';      String a = 'Hello $characters';      String b = 'Hello $characters';      print(a == b);  

Outputs true for equality operator

    double x = 3.5;      double y = 3.5;      print(identical(x, y));      print(identical(a, b));  

Outputs true in dartpad but false in VS code

    List eq3 = const [1, 2, 3];      List eq4 = [1, 2, 3];      print(eq3 == eq4);      print(identical(eq3, eq4));      }  

Balancing a System of Non-Linear equations for Chemical Reactions

Posted: 05 Dec 2021 02:24 PM PST

I am trying to compute the final composition and temperature of a mixture of syn-gas and air. They enter in at 300 K and 600 K respectively. The syn-gas is a mixture of CO and H2 the proportions of which I am varying from 3:1 to 1:3. Later on, this ratio is fixed and additional nitrogen gas is introduced. Lastly, heat loss is accounted for and its effect on temperature/composition is calculated. Focusing on the first part, I am having a hard time balancing the system of non-linear equations. The general equation for the chemical reaction is as follows:

aCO + bH2 + c*(O2 + 79/21 * N2) + dN2 = eCO + fH2 + gO2 + hN2 + jCO2 + kH2O + lNO

From conservation of species:

Carbon: a = e + j

Oxygen: a + 2c = e + 2g + 2*j + k + l

Hydrogen: 2b = 2f + 2*k

Nitrogen: 2*(79/21)c + 2d = 2*h + l

Since there are three compounds, there are three partial pressure equilibrium values called K_p. K_p is a function of temperature and from empirical data is a known constant.

K_p_NO = (X_NO * P) / (sqrt(X_N2*P)*sqrt(X_O2 * P))

K_p_H2O = (X_H2O * P) / (sqrt(P*X_O2)X_H2P)

K_p_CO2 = (X_CO2 * P) / (sqrt(P*X_O2)X_COP)

Where X is the mole fraction. E.G. X_H2O = k/(e+f+g+h+j+k+l)

The variables e,f,g,h,j,k,l are 7 unknowns and there are 7 equations. Variables a, b, c, and d are varied manually and are treated as known values. Using scipy, I implemented fsolve() as shown below:

from scipy.optimize import fsolve  # required library  import sympy as sp  import scipy  # known values hard coded for testing  a = 0.25  b = 0.75  c = a + b  d = 0  kp_NO = 0.00051621  kp_H2O = 0.0000000127  kp_CO2 = 0.00000001733  p = 5 # pressure  dec = 10 # decimal point precision    # Solving the system of equations  def equations(vars):      (e, f, g, h, j, k, l) = vars      f1 = e + j - a      f2 = e + 2*g + 2*j + k + l - a - 2*c      f3 = f + k - b      f4 = 2*h + l - 2*d - (2*79/21)*c      f5 = kp_NO - (l/sp.sqrt(c*(79/21)*c))      f6 = kp_H2O - (k/(b*sp.sqrt((c*p)/(e + f + g + h + j + k + l))))      f7 = kp_CO2 - (j/(a*sp.sqrt((c*p)/(e + f + g + h + j + k + l))))      return[f1, f2, f3, f4, f5, f6, f7]  e, f, g, h, j, k, l = scipy.optimize.fsolve(equations, (0.00004, 0.00004, 0.49, 3.76, 0.25, 0.75, 0.01))  # CO, H2, O2, N2, CO2, H2O, NO  print(e, f, g, h, j, k, l)  

The results are

0.2499999959640893 0.7499999911270915 0.999499382628763 3.761404150987935 4.0359107126181326e-09 8.872908576472292e-09 0.001001221833654118  

Notice that e = 0.24999995 but a = 0.25. It seems that the chemical reaction is progressing little if at all. Why am I getting my inputs back as results? I know something is wrong because in some cases, the chemical coefficients are negative.

Things I've tried: Triple checked my math/definitions. Used nsolve() from sympy, nonlinsolve() from scipy, other misc. solvers.

Unable to extract MCC details from PDF file

Posted: 05 Dec 2021 02:24 PM PST

I am unable to extract MCC details from PDF. I am able to extract other data with my code.

import tabula.io as tb  from tabula.io import read_pdf  pdf_path = "IR21_SVNMT_Telekom Slovenije d.d._20210506142456.pdf"  for df in df_list:      if 'MSRN Number Range(s)' in df.columns:           df = df.drop(df.index[0])           df.columns = df.columns.str.replace('\r', '')           df.columns = df.columns.str.replace(' ', '')           df.columns = df.columns.str.replace('Unnamed:0', 'CountryCode(CC)')           df.columns = df.columns.str.replace('Unnamed:1', 'NationalDestinationCode(NDC)')           df.columns = df.columns.str.replace('Unnamed:2', 'SNRangeStart')           df.columns = df.columns.str.replace('Unnamed:3', 'SNRangeStop')           break  msrn_table = (df[['CountryCode(CC)','NationalDestinationCode(NDC)','SNRangeStart','SNRangeStop']])  print (msrn_table)  

The same logic I am trying to retrieve "Mobile Country Code (MCC)" details. But Pandas data frame is showing different data instead of what is there in PDF.

for df in df_list:      if 'Mobile Country Code (MCC)' in df.columns:          break  print (df)  

Pandas output is given in this: pandas_output

The actual content in pdf file is: actual_pdf

Check if user existed in cognito as federated user by using only email/username

Posted: 05 Dec 2021 02:24 PM PST

I'm having trouble implementing a feature where I need check if a user does not exist or is existing in cognito but as federated user. The prior is done without trouble but I'm stuck on the latter without any clue. I went through the cognito and amplify documents but couldn't find any clue. Could there be a work-around or a function that I don't know about, any suggest is welcomed.

Drawing collaboration diagram using piece of code in Java

Posted: 05 Dec 2021 02:24 PM PST

I have to write collaboration diagram for this piece of code:

public static void main(String[] args){  Playlist list = new Playlist();  list.add(new mp3("song1",5));  list.add(new wav("song2",6));  list.add(new mp3("song3",7));    list.play();  

Where mp3 and wav are classes inherited from class Track and they have constructor with two arguments. Also, function "add" takes one argument which is type Track. So, what I think is that we should have 3 self calls(for every call of method add) because that is function from class list, and then one(also self call) for function play. But not sure how to include objects of class mp3 and class wav because we are only calling functions from class Playlist. So, I am not sure why are we calling function play from class mp3(wav) and not from class playlist. And from the other side we are calling function play from playlist.

nvim_treesitter installation on windows

Posted: 05 Dec 2021 02:23 PM PST

bad English (sorry). I'm trying to get nvim_treesitter to work on my windows machine, on my Linux one it worked great but now when I try on windows the :checkhealth nvim_treesitter gives:

health#nvim_treesitter#check

Installation

  • ERROR: tree-sitter executable not found
  • OK: git executable found.
  • ERROR: cc executable not found.
    • ADVICE:
      • Check that either gcc or clang is in your $PATH

Parser/Features H L F I

Legend: H[ighlight], L[ocals], F[olds], I[ndents] *) multiple parsers found, only one will be used x) errors found in the query, try to run :TSUpdate {lang}

and I'm totally new to this thing, any advice would help:)

How do I reference a local image in React?

Posted: 05 Dec 2021 02:23 PM PST

How can I load image from local directory and include it in reactjs img src tag?

I have an image called one.jpeg inside the same folder as my component and I tried both <img src="one.jpeg" /> and <img src={"one.jpeg"} /> inside my renderfunction but the image does not show up. Also, I do not have access to webpack config file since the project is created with the official create-react-app command line util.

Update: This works if I first import the image with import img from './one.jpeg' and use it inside img src={img}, but I have so many image files to import and therefore, I want to use them in the form, img src={'image_name.jpeg'}.

SPARK dataframe error: cannot be cast to scala.Function2 while using a UDF to split strings in column

Posted: 05 Dec 2021 02:24 PM PST

I keep getting a error when I use udf to split string in a column by a delimiter. I am using Scala

Error: java.lang.ClassCastException: $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1 cannot be cast to scala.Function2  

Don't know what this is and how to fix it.

This is my udf and data frame:

val rsplit = udf((refsplit: String) => refsplit.split(":"))      +---------+--------------------+--------------------+  |     user|              jsites|             jsites1|  +---------+--------------------+--------------------+  |123ashish|m.mangahere.co:m....|m.mangahere.co:m....|  |456ashish|m.mangahere2.co:m...|m.mangahere2.co:m...|  |   ashish|m.mangahere.co:m....|m.mangahere.co:m....|  +---------+--------------------+--------------------+  

the column jsites look like m.manghere.co:m.facebook.com:.msn.com. And I am trying to use the udf to split m.manghere.co:m.facebook.com:.msn.com by :.

I keep getting that error

Derby db connectivity problems

Posted: 05 Dec 2021 02:23 PM PST

I receive the following error msg when attempting to connect to a derby network server:

java.sql.SQLException: No suitable driver found for jdbc:derby://localhost/studentdb;create=true

Derby is properly installed and all environment variables set. I am able to start the derby NetworkServerControl from a Windows command prompt with the following command:

java org.apache.derby.drda.NetworkServerControl start -h localhost

,and I can do this from any location within my system's directory tree.

I can start the derby ij client from within a Windows command prompt with the command:

java org.apache.derby.tools.ij

,again, from any location within my system's directory tree.

But the code snippet below is unable to make this connection:

    public static void main(String[] args) {      Connection conn = null;            String url = "jdbc:derby://localhost/studentdb;create=true";        //the error happens here, the program executes no further          conn = DriverManager.getConnection(url,null);            Statement stmt = conn.createStatement();    }  

Placing the port value in the url string makes no difference. Any suggestions would be much appreciated.

Localhost not working in Chrome, 127.0.0.1 does work

Posted: 05 Dec 2021 02:23 PM PST

I'm trying to run a local node server, but for whatever reason localhost:3000 does not work. The error page states This webpage is not available ERR_CONNECTION_CLOSED However, 127.0.0.1:3000 does work. I have tried making changes to my hosts file, but to no avail. Does anyone have any idea what's causing the problem?

Chrome version is 46.0.2490.80 m

No comments:

Post a Comment