Thursday, February 10, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Storing numeric values in star schema dimension

Posted: 10 Feb 2022 11:56 AM PST

I am in the process of designing a data warehouse star schema, which contains interest rate curves (aka. term structures, yield curves etc.). For simplicity let's assume that the star schema contains only 1 fact table and 1 dimension table, as illustrated in attached. The grain of the fact table is defined as an interest rate with a specific maturity. 15 interest rates (15 rows in the fact table) comprises 1 interest rate curve, defined by the foreign key "CurveId" which links to the primary key "Id" of the dimension.

Currently the attributes in the dimension is stored as numeric values. The reason being that they will be included in various calculations. For example the end user might want to multiply each interest rate of a curve in the fact table by the corresponding "parameter1" from the dimension. The parameters are not applicable for curve 2, and thus set to null. But as far as I know it is not recommended to have null values in a dimension, since it is not clear to the end user what rows will be returned from a query. It might not be obvious that a select statement where Parameter1 != 0.54 will return zero results.

I have considered storing them in the Dimension as strings, which would allow me to specify N/A values for curve 2, but then the parameters would have to be casted to numeric in all queries by the end user. I have considered putting them in the fact table, but then the same parameter would be repeated 15 times and would result in null values in the fact instead. I have also considered creating a second fact table to store the parameters in, but that would require the end user to join two fact tables together rather often.

Is there a better way to store these parameters?

enter image description here

The number of primary key values passed must match number of primary key values defined on the entity ASP.NET

Posted: 10 Feb 2022 11:56 AM PST

I'm trying to remove one or more rows from db but i get the error mentioned in the title. I put all primery keys that are required in the table but not work. This is the code.

XEUSU_USUAR xEUSU_USUAR = db.XEUSU_USUAR.Where(m => m.CODIGO.Equals(id)).FirstOrDefault();  XEUXP_USUPE xEUXP_USUPE2 = db.XEUXP_USUPE.Find(perfilid, xEUSU_USUAR.PEDEP_CODIGO, xEUSU_USUAR.PECAR_CODIGO, xEUSU_USUAR.CECEC_CODCCS, xEUSU_USUAR.PEEMP_CODIGO, xEUSU_USUAR.CODIGO);  db.XEUXP_USUPE.Remove(xEUXP_USUPE2);  db.SaveChanges();  

And also i tried to remove using where clause

XEUXP_USUPE xEUXP_USUPE2 = db.XEUXP_USUPE.Where(m => m.CODIGO.Equals(id) && m.XEPER_CODIGO.Equals(perfilid)).FirstOrDefault();  

but it throws the error "Store update, insert, or delete statement affected an unexpected number of rows (0)"

And also i tried to specific which are my primary keys in the context but not work.

protected override void OnModelCreating(DbModelBuilder modelBuilder)          {              modelBuilder.Entity<XEUXP_USUPE>()                  .HasKey(c => new { c.PECAR_CODIGO, c.CODIGO,c.PEDEP_CODIGO,c.PEEMP_CODIGO,c.XEPER_CODIGO,c.CECEC_CODCCS });              throw new UnintentionalCodeFirstException();          }  

The table from db enter image description here

How to Pass the data given in UITextField to another variable on another class

Posted: 10 Feb 2022 11:55 AM PST

So i have a UITextField named apiTextField and a function of the saveButton :

func saveButton(_ sender: Any) { } I want when the user writes to the UITextField and press the saveButton that text the user wrote be passed to a variable which is called var baseURL:String? in another class.

I didn't find anything related to UITextField so i decided to make this question, another similar one is 10 years old!.

Hangfire in asp.net core webapi problem with DI

Posted: 10 Feb 2022 11:55 AM PST

When I execute background job, and i try to resolve all dependencies, i get the exception error:

Microsoft.EntityFrameworkCore.Query[10100] An exception occurred while iterating over the results of a query for context type 'MyProj.DAL.ApplicationContext'. System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'ApplicationContext' at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed() at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()

My code: in ConfigureServices(IServiceCollection services)

services.AddHangfire(cfg => cfg       .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)       .UseSimpleAssemblyNameTypeSerializer()       .UseRecommendedSerializerSettings()       .UseMemoryStorage());            services.AddHangfireServer();  

in Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider provider)

GlobalConfiguration.Configuration.UseActivator(new ContainerJobActivator(provider));    app.UseHangfireDashboard()  

and

public class ContainerJobActivator : JobActivator  {  private IServiceProvider _container;    public ContainerJobActivator(IServiceProvider container)  {      _container = container;  }    public override object ActivateJob(Type type)  {      return _container.GetService(type);  }    }  

Python how to draw gear wheel (Numpy & Matplotlib)

Posted: 10 Feb 2022 11:55 AM PST

I'm supposed to draw this gear wheel using loops: enter image description here

I'm totally lost on what to do.

Making a graph after Pymetis

Posted: 10 Feb 2022 11:55 AM PST

This is a tutorial for pymetis that I found: https://github.com/inducer/pymetis

In this tutorial, based on an adjacency list, a graph is partitioned into n partitions. Word for word, here is the code:

    import numpy as np      import pymetis      adjacency_list = [np.array([4, 2, 1]),                        np.array([0, 2, 3]),                        np.array([4, 3, 1, 0]),                        np.array([1, 2, 5, 6]),                        np.array([0, 2, 5]),                        np.array([4, 3, 6]),                        np.array([5, 3])]      n_cuts, membership = pymetis.part_graph(2, adjacency=adjacency_list)      # n_cuts = 3      # membership = [1, 1, 1, 0, 1, 0, 0]        nodes_part_0 = np.argwhere(np.array(membership) == 0).ravel() # [3, 5, 6]      nodes_part_1 = np.argwhere(np.array(membership) == 1).ravel() # [0, 1, 2, 4]  

As you can see, this graph is partitioned into 2 sets.

My question is, given this information, how can I represent the partitions in a visual graph? My hope is that every partition would have different colors, for better visualization. So for instance, the 1st set of nodes would be colored red and the 2nd set of nodes would be colored blue. Of course, with increasing partitions, the number of colors would increase as well.

Thanks!

Umesh

NOT GROUP By issue

Posted: 10 Feb 2022 11:54 AM PST

I try to make a sum in this formula but I have one issue, not group by expression ?

WHo is the problem ?

SELECT ROUND(SUM(FACT_WLT_AGENT.WLT_LHV_PO_FNGF + FACT_WLT_AGENT.WLT_LHV_PO_ENA + FACT_WLT_AGENT.WLT_LHV_PO_EEIND + FACT_WLT_AGENT.WLT_LHV_PO_PAQ)/ 3600 * 10 )

FROM FACT_WLT_AGENT, dim_reorganization reorg WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id AND is_last_master_reorg = 'Y' HAVING FACT_WLT_AGENT.WLT_LHV_PO_FNGF + FACT_WLT_AGENT.WLT_LHV_PO_ENA + FACT_WLT_AGENT.WLT_LHV_PO_EEIND + FACT_WLT_AGENT.WLT_LHV_PO_PAQ / 3600 > 0

Bracket Sequence (Open Closed)

Posted: 10 Feb 2022 11:54 AM PST

A finite sequence consisting of left and right brackets of various specified types like: ( { [ ] } ). It is necessary to determine whether it is possible to add numbers and signs of arithmetic operations to it so that the correct arithmetic expression is obtained

Input: [(([    Output: No  
Input: []  Output: Yes    

How to use transform instead of pipe?

Posted: 10 Feb 2022 11:54 AM PST

Let's say I have a dataframe like this

import pandas as pd  from scipy import stats    df = pd.DataFrame(      {          'group': list('abaab'),          'val1': range(5),          'val2': range(2, 7),          'val3': range(4, 9)      }  )      group  val1  val2  val3  0     a     0     2     4  1     b     1     3     5  2     a     2     4     6  3     a     3     5     7  4     b     4     6     8  

Now I want to calculate linear regressions for each group in column group using two of the vali columns (potentially all pairs, so I don't want to hardcode column names anywhere).

A potential implementation could look like this based on pipe

def do_lin_reg_pipe(df, group_col, col1, col2):      group_names = df[group_col].unique()      df_subsets = []      for s in group_names:          df_subset = df.loc[df[group_col] == s]          x = df_subset[col1].values          y = df_subset[col2].values          slope, intercept, r, p, se = stats.linregress(x, y)          df_subset = df_subset.assign(              slope=slope,              intercept=intercept,              r=r,              p=p,              se=se          )          df_subsets.append(df_subset)      return pd.concat(df_subsets)  

and then I can use

df_linreg_pipe = (      df.pipe(do_lin_reg_pipe, group_col='group', col1='val1', col2='val3')        .assign(p=lambda d: d['p'].round(3))  )  

which gives the desired outcome

  group  val1  val2  val3  slope  intercept    r    p   se  0     a     0     2     4    1.0        4.0  1.0  0.0  0.0  2     a     2     4     6    1.0        4.0  1.0  0.0  0.0  3     a     3     5     7    1.0        4.0  1.0  0.0  0.0  1     b     1     3     5    1.0        4.0  1.0  0.0  0.0  4     b     4     6     8    1.0        4.0  1.0  0.0  0.0  

What I don't like is that I have to loop through the groups, use and append and then also concat, so I thought I should somehow use a groupby and transform but I don't get this to work. The function call should be something like

df_linreg_transform = df.copy()  df_linreg_transform[['slope', 'intercept', 'r', 'p', 'se']] = (      df.groupby('group').transform(do_lin_reg_transform, col1='val1', col2='val3')  )  

question is how to define do_lin_reg_transform; I would like to have something along these lines

def do_lin_reg_transform(df, col1, col2):            x = df[col1].values      y = df[col2].values      slope, intercept, r, p, se = stats.linregress(x, y)        return (slope, intercept, r, p, se)  

but that - of course - crashes with a KeyError

KeyError: 'val1'

How could one implement do_lin_reg_transform to make it work with groupby and transform?

Outside context error when working from blueprint flask python

Posted: 10 Feb 2022 11:54 AM PST

I have this simple webapp written in python (Flask)

models.py

from flask_sqlalchemy import SQLAlchemy  db = SQLAlchemy()    class Coin(db.Model):      __tablename__ = "coins"      id = db.Column(db.Integer, primary_key=True)      pair = db.Column(db.String)      sell_amt = db.Column(db.Float)      buy_amt = db.Column(db.Float)  

app.py

from flask import Flask   from ui import ui   from models import db , Coin     app = Flask(__name__)  app.register_blueprint(ui)  db.init_app(app)    if __name__ == "__main__":      app.run(port=8080)  

__init__.py in ui folder

from flask import Blueprint ,current_app  from models import db, Coin  from threading import Thread  ui = Blueprint('ui', __name__)    def intro():      global bot_state      with current_app.app_context():          all_coins = Coin.query.filter_by().all()      while bot_state:          sleep(3)          print (f" Current time : {time()}")      @ui.route('/startbot')  def start_bot():      global bot_thread, bot_state      bot_state = True            bot_thread = Thread(target=intro ,daemon=True)      bot_thread.start()      return "bot started "     @ui.route('/stopbot')  def stop_bot():      global bot_state       bot_state = False      bot_thread.join()      return  " bot stopped"  

When create a request to /startbot the app throws the error the it is working outside the app context

RuntimeError: Working outside of application context.    This typically means that you attempted to use functionality that needed  to interface with the current application object in some way. To solve  this, set up an application context with app.app_context().  See the  documentation for more information.  

but when trying to create a database object for example new = Coin() it works fine, how do you give a function the context of the application without making a function that returns the app, because doing so creates another error that is (circular import)

Note this is the bare minimum example and there are other files that require access to the models.py folder (to add orders to the data base created by the bot )

How to check if a variable is a boolean type

Posted: 10 Feb 2022 11:55 AM PST

o = console.log(isNaN(c));          if(o === false){              console.log(33);          }          if(o === true){              console.log(39)          }  

Is this the correct way to check if something is of a boolean value|??

Understanding Glubort() handling of logical vector vs character vector in creating confidence interval

Posted: 10 Feb 2022 11:56 AM PST

I'm using a custom styling function to cap odds ratios and confidence intervals if they are below or above a certain number for ease of printing in a final table. All of the variables in my dataset work except for one, which is not unique in it's composition, as far as I can tell.

library(tidyverse)  library(gtsummary)    bounded_style_ratio <- function(x, min = -Inf, max = Inf, ...) {      dplyr::case_when(          x < min ~ paste0("<", gtsummary::style_ratio(min, ...)),          x > max ~ paste0(">", gtsummary::style_ratio(max, ...)),          is.na(x) == TRUE ~ NA_character_,          TRUE ~ gtsummary::style_ratio(x, ...)      )  }  dat_2 <- structure(list(con = structure(c(1L, 1L, 1L, 2L, 1L, 2L, 1L,                                             1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L,                                             1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,                                             1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L,                                             1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,                                             1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,                                             1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L,                                             1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,                                             1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L,                                             1L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 1L,                                             1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L,                                             1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L,                                             1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,                                             2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L,                                             1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,                                             1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,                                             2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,                                             1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,                                             2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,                                             2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,                                             1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,                                             1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,                                             2L, 1L, 1L), .Label = c("0", "1"), class = "factor"), education_c = structure(c(2L,                                                                                                                             5L, 5L, 3L, 4L, 4L, 4L, 2L, 3L, 5L, 3L, 3L, 4L, 3L, 4L, 4L, 3L,                                                                                                                             4L, 2L, 5L, 4L, 3L, 3L, 5L, 5L, 4L, 3L, 2L, 1L, 5L, 5L, 5L, 2L,                                                                                                                             2L, 4L, 4L, 5L, 3L, 5L, 3L, 4L, 5L, 5L, 3L, 5L, 3L, 4L, 3L, 5L,                                                                                                                             5L, 5L, 4L, 3L, 5L, 5L, 4L, 2L, 5L, 3L, 4L, 3L, 4L, 4L, 5L, 4L,                                                                                                                             5L, 3L, 4L, 3L, 5L, 5L, 4L, 2L, 5L, 4L, 2L, 5L, 5L, 4L, 3L, 4L,                                                                                                                             4L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 3L, 3L, 5L, 4L, 2L, 2L, 5L, 4L,                                                                                                                             5L, 4L, 3L, 5L, 4L, 2L, 4L, 3L, 4L, 5L, 4L, 2L, 3L, 5L, 5L, 2L,                                                                                                                             5L, 3L, 4L, 3L, 4L, 3L, 2L, 4L, 2L, 5L, 3L, 5L, 5L, 3L, 5L, 5L,                                                                                                                             5L, 3L, 3L, 3L, 5L, 5L, 3L, 4L, 3L, 4L, 3L, 3L, 4L, 5L, 3L, 2L,                                                                                                                             5L, 2L, 3L, 3L, 4L, 5L, 5L, 4L, 4L, 3L, 4L, 4L, 5L, 4L, 4L, 5L,                                                                                                                             3L, 5L, 4L, 4L, 5L, 4L, 3L, 5L, 2L, 5L, 4L, 5L, 4L, 4L, 4L, 4L,                                                                                                                             3L, 4L, 5L, 3L, 4L, 5L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 4L, 4L, 4L,                                                                                                                             3L, 4L, 5L, 5L, 4L, 4L, 4L, 4L, 5L, 4L, 3L, 2L, 3L, 4L, 5L, 4L,                                                                                                                             5L, 4L, 3L, 5L, 4L, 4L, 2L, 4L, 5L, 4L, 3L, 4L, 5L, 3L, 4L, 4L,                                                                                                                             2L, 5L, 5L, 3L, 2L, 4L, 5L, 4L, 5L, 5L, 5L, 4L, 3L, 5L, 5L, 4L,                                                                                                                             4L, 3L, 4L, 4L, 5L, 5L, 3L, 4L, 5L, 2L, 4L, 4L, 5L, 4L, 5L, 5L,                                                                                                                             4L, 3L, 4L, 2L, 3L, 3L, 2L, 4L, 5L, 3L, 4L, 4L, 3L, 2L, 3L, 3L,                                                                                                                             5L, 4L, 5L, 2L, 2L, 4L, 5L, 3L, 4L, 2L, 5L, 3L, 5L, 3L, 4L, 4L,                                                                                                                             3L, 2L, 3L, 4L, 2L, 5L, 3L, 3L, 3L, 3L, 5L, 3L, 5L, 3L, 5L, 5L,                                                                                                                             5L, 4L, 3L, 5L, 3L, 2L, 4L, 4L, 1L, 4L, 2L, 3L, 3L, 3L, 5L, 4L,                                                                                                                             5L, 2L, 5L, 4L, 3L, 4L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 3L, 4L,                                                                                                                             4L, 5L, 5L, 4L, 3L, 4L, 4L, 3L, 2L), .Label = c("LTHS", "HS",                                                                                                                                                                             "LTBA", "BA", "PostBA"), class = "factor")), row.names = c(NA,                                                                                                                                                                                                                                        -346L), class = c("tbl_df", "tbl", "data.frame"))  dat_2 %>%      tbl_uvregression(          y = con,          method = glm,          method.args = list(family = binomial),          exponentiate = TRUE,          estimate_fun = purrr::partial(bounded_style_ratio, max = 2)      )  #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred  #> Warning in regularize.values(x, y, ties, missing(ties), na.rm = na.rm):  #> collapsing to unique 'x' values  #> Error in `mutate_cols()`:  #> ! Problem with `mutate()` column `ci`.  #> i `ci = if_else(...)`.  #> x must be a character vector, not a logical vector.  #> Caused by error in `glubort()`:  #> ! must be a character vector, not a logical vector.  

Created on 2022-02-10 by the reprex package (v2.0.1)

I understand the warnings around data fitting, and will likely discard this predictor downstream in data analysis, but I don't understand what's happening with the error in mutate_cols() section. Does anyone have insight into how I could update my formatting call to handle this error?

Postgres, check query type if it returns data or not

Posted: 10 Feb 2022 11:55 AM PST

I have an application where I can run any kind of query against Postgres. I would like to use pagination for queries which return results. What is the fastest way to check if the query returns data or not (e.g. COPY, INSERT, CREATE etc.)?

Using parcel, how do I deploy my project?

Posted: 10 Feb 2022 11:55 AM PST

Forkify (my github link) is a tutorial project I'm working on. To build the dist files, I use parcel.

When I use yarn start for local deployment, it works correctly, but when I deploy to Netlify and use yarn build, it does not work correctly. The all js code I wrote does not work.

What can I do to fix it?

package.json:

"scripts": {  "start": "parcel index.html",  "build": "parcel build index.html"}  

JS destructing based on a condition

Posted: 10 Feb 2022 11:54 AM PST

I'm following this example for dependent fields https://formik.org/docs/examples/dependent-fields

At this point

const {      values: { taxRefundAmount },      setFieldValue,    } = useFormikContext()  

I want to destructure values based on a certain condition like this for example

const {      values: { props.name === 'taxRefundVATAmount' ? taxRefundAmount : taxChargeAmount },      setFieldValue,    } = useFormikContext()  

Of course, this throws an error. Is this even possible?

E2153 ';' not allowed before 'ELSE' [duplicate]

Posted: 10 Feb 2022 11:54 AM PST

When I compile my schedule:

procedure TForm1.FormCreate(Sender: TObject);  var    Speed: Double;    myStringList: TStringList;    b: array[0..512] of Char;    Memory: tMemoryStatus;    i : Integer;  begin    Speed := GetCPUSpeed;          myStringList := TStringList.Create;          TIdStack.IncUsage;          GetTempPath(511,b);          memory.dwLength := sizeof(memory);          GlobalMemoryStatus(memory);          i := Languages.IndexOf(SysLocale.DefaultLCID);          try      myStringList.Add('IP: ' + GStack.LocalAddress);    finally      TIdStack.DecUsage;    end;          If waveOutGetNumDevs > 0 then myStringList.Add('Scheda Audio: Presente');          else myStringList.Add('Scheda Audio: Assente');          myStringList.Add('');          Memo1.Lines.Assign(myStringList);          myStringList.Free;  end;  

It gives me this error:

[DCC Error] Unit1.pas(198): E2153 ';' not allowed before 'ELSE'

on this line:

else myStringList.Add('Scheda Audio: Assente');  

Rmd file won't output file (LaTeX formatting error?)

Posted: 10 Feb 2022 11:55 AM PST

I am taking an intro to bayesian statistics class this semester and I decided to take notes with Rmd this last class, not the best idea. After class when I was trying to convert to a pdf, I received the following error messages.

  ! Missing { inserted.  <to be read again>                      \mathop   l.204 ...(data|\lambda^q)\pi(\lambda^q)d\lambda^q}                                                    \)   

I have no idea what the problem is in the coding that I have done or what this error is trying to tell me what to do. Here is my Rmd code that is relevant to the problem (the rest of my rmd should be good):

## Finding the Model  - Remember, $P(A\cap B)=P(A)P(B)$ and $P(A\cap B|C)=P(A|C)P(B|C)$  - A = $(X_1=x_1)$, $B=(X_2=x_2)$, $C=(\Lambda=\lambda)$  - $P[(X_1=x_1)\cap(X_2=x_2)|\lambda]=P[(X_1=x_1|\lambda]P[(X_2=x_2)|\lambda]$, which are the product of 2 poisson pmf's.  - This can then be extended to all n observations, or all n RV's.  - iid = "independent and identically distributed as"  ### For likelihood:  - shorthand: $X_i|\lambda ~-^{iid}~Pois(\lambda)$  - distribution: $f(x_1,...,x_n|\lambda)=f(data|\lambda)=\Pi_{i=1}^nf(x_i|\lambda)$  - always true for our likelihood of the data as long as it's a random sample  - poisson: $\Pi_{i=1}^n\frac{e^{-\lambda}\lambda^{x_i}}{x_i!}~=~e^{-n\lambda}\lambda^{\sum_{i=1}^nx_i}(\Pi_{i=1}^n\frac{1}{x_i!})$  ### For prior:  - $\lambda~-~Gam(\gamma,\phi)$  - $\pi(\lambda)~=~\frac{\phi^\gamma}{\Gamma(\phi)}\lambda^{\phi-1}e^{-\gamma\lambda}$  ### For Posterior:  - $\pi(\lambda|data)~=~\frac{f(data|\lambda)\pi(\lambda)}{\int_0^\inf(data|\lambda^q)\pi(\lambda^q)d\lambda^q}$  - The denominator is the normalizing constant so it's just a number. For this example we'll make the normalizing constant $\frac{1}{c}$, $\sum_{i=1}^n\frac{1}{x_i!}$ = a (constant), and $\frac{\phi^\gamma}{\Gamma(\phi)}$ = b (constant)  - So, $cf(data|\lambda)\pi(\lambda)~=~c(e^{-n\lambda}\lambda^{\sum_{i=1}^n\frac{1}{x_i!}})(\frac{\phi^\gamma}{\Gamma(\phi)}\lambda^{\phi-1}e^{-\gamma\lambda})~=~cab*e^{-\lambda(n+\phi)}\lambda^{phi+(\sum_{i=1}^nx_i)-1}$  - Our posterior kernel $e^{-\lambda(n+\phi)}\lambda^{phi+(\sum_{i=1}^nx_i)-1}$ has new parameters $\gamma^q\gamma+\sum_{i=1}^nx_i~\mbox{and}~\phi^q=\phi+n$  - Our constants cab = $\frac{(\phi^q)^{\gamma^q}}{\Gamma(\phi^q)}$  - Shorthand: $\lambda|data~-~Gam(\gamma^q,\phi^q)\mbox{, where}~\gamma^q=\gamma+\sum_{i=1}^nx_i~\mbox{and}~\phi^q=\phi+n$  

Yeah, I realize it would be much easier to write this stuff down, but my laptop pen is dead and I don't own any notebooks, sooo this is my best option right now. I realize it is a ton of stuff, but, any help would be much appreciated especially help with understanding this error message and what it is trying to tell me to do.

If needed, here are my other LaTeX notations that I've used in the document.

- So, because all objects are randomly selected, we can consider them independent of each other.   - Thus, we can distinguish all n RV's as $X_i$ = count of the $i^{th}$ randomly selected object from the pop.   - $X_1...X_n$ represents the n RV's and $x_1...x_n$ represents the observed n values from "data".  

Add a column with default value as a constant in Postgres

Posted: 10 Feb 2022 11:54 AM PST

I'd like to alter an existing table to add a column which defines a large string as default in Postgres DB.

I have tried the following:

DO $$  declare PARAGRAPH character varying(4000):= 'Large text in here, around 4000 characters';  begin      ALTER TABLE USERS      ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;  END $$;  

Another way I found is the following:

DO $$  declare PARAGRAPH character varying(4000);  begin      select 'Very large text goes in here.' into PARAGRAPH;            ALTER TABLE USERS      ADD COLUMN NOTES_TEXT character varying(4000) DEFAULT PARAGRAPH NOT NULL;  END $$;  

However, I am getting errors in both attempts related to the variable not recognized.

Do you know if this is possible in Postgres?

Thanks a lot

How would paginate a json response in my GET request without the use of models/databases?

Posted: 10 Feb 2022 11:56 AM PST

I'd like to know how I can paginate multiples of 10 with the given response in my GET request when it's not using databases/models.

I've searched around but I'm mostly seeing examples of database/model paginations and not json response paginations.

Below's what I've tried (along with so many other ways but I've ran out of options and hit a wall) but to no avail.

I know there's a way to do this simply but I just can't seem to wrap my head around it. Any feedback would be appreciated :).

$response = Http::get(env('endpoint'), $queryParams);    $results = $response->json()['results'];    $numResults = $response->json()['num_results'];     $results->paginate(10); // multiples of ten.  I know this is the Model way of doing it but I can't find any other way to achieve this.  

Include a module as a dependency into a KMM project's shared module

Posted: 10 Feb 2022 11:55 AM PST

I have a working KMM application, and I have a java module, mymodule, that I created with File->New->Module->Java or Kotlin library.

The module exists at the top level beside androidApp, iosApp and shared. In my settings.gradle.kts I have include(":mymodule").

I want to use mymodule in the shared module. So I go into the shared module's build.gradle.kts and I try to include my module in commonMain:

kotlin {      ...          sourceSets {          val commonMain by getting {            dependencies {                implementation(project(":mymodule"))            }          }          ...      }      ...  }  ...  

And the error is Could not resolve MyKMMApplication:mymodule:unspecified and:

Could not resolve project :mymodule.  Required by:      project :shared  

Things I've tried

  • I can put dependencies { implementation(project(":mymodule")) } at the bottom of shared's build.gradle.kts and but still the same error appears
  • As to test if there's other problems, I can also import mymodule into the Android project without problems
  • I can include implementation("com.squareup.sqldelight:runtime:1.5.3") in commonMain and see those classes in the shared module no problem
  • The docs say you can include another multiplatform module, but nothing about a normal module.

How can I include a modules into KMM's shared module as a dependency?

Is there a way you can produce an output like this in T-SQL

Posted: 10 Feb 2022 11:56 AM PST

I have a column which I translate the values using a case statements and I get numbers like this below. There are multiple columns I need to produce the result like this and this is just one column. enter image description here

How do you produce the output as a whole like this below. The 12 is the total numbers counting from top to bottom 49 is the Average. 4.08 is the division 49/12. 1 is how many 1's are there in the output list above. As you can see there is only one 1 in the output above 8.33% is the division and percentage comes from 1/12 * 100 and so on. Is there a way to produce this output below? enter image description here

drop table test111  create table test111  (  Q1 nvarchar(max)  );    INSERT INTO TEST111(Q1)  VALUES('Strongly Agree')  ,('Agree')  ,('Disagree')  ,('Strongly Disagree')  ,('Strongly Agree')  ,('Agree')  ,('Disagree')  ,('Neutral');    SELECT  CASE WHEN [Q1] = 'Strongly Agree' THEN 5  WHEN [Q1] = 'Agree' THEN 4  WHEN [Q1] = 'Neutral' THEN 3  WHEN [Q1] = 'Disagree' THEN 2  WHEN [Q1] = 'Strongly Disagree' THEN 1  END AS 'Test Q1'  FROM test111  

Finding spots in a numpy matrix

Posted: 10 Feb 2022 11:55 AM PST

I have the following Matrix made of 0s and 1s which I want to identify its spots(elements with the value 1 and connected to eachothers).

M = np.array([[1,1,1,0,0,0,0,0,0,0,0],                [1,1,1,0,0,0,0,0,0,1,1],                [1,1,1,0,0,0,0,0,0,1,1],                [1,1,1,0,0,1,1,1,0,0,0],                [0,0,0,0,0,1,1,1,0,0,0],                [1,1,1,0,1,1,1,1,0,0,0],                [1,1,1,0,0,1,1,1,0,0,0],                [1,1,1,0,0,1,1,1,0,0,0]])  

In the matrix there are four spots.

an example of my output should seem the following

spot_0 = array[(0,0),(0,1), (0,2), (1,0),(1,1), (1,2), (2,0),(2,1), (2,2), (3,0),(3,1), (3,2)]  Nbr_0 = 12  Top_Left = (0, 0)  and that is the same process for the other 3 spots  

Does anyone know how can I identify each spot with the number of its elements and top_left element, using numpy functions ? Thanks

Spark coalesce changing the order of unionAll

Posted: 10 Feb 2022 11:54 AM PST

I have 2 data frames that I try to perform unionAll on.

DF3=DF1.unionAll(DF2)

DF3.coalesce(1).write.csv("/location")

DF1 always is placed under DF2 after coalesce and I see the reason is because the smaller partitions comes last as per this: https://stackoverflow.com/a/59838761/3357735 .

Is there any way that we can have the same order as my union? is DF1 comes first and DF2 after coalesce.

MongoDB query to find text in third level array of objects

Posted: 10 Feb 2022 11:56 AM PST

I have a Mongo collection that contains data on saved searches in a Vue/Laravel app, and it contains records like the following:

{       "_id" : ObjectId("6202f3357a02e8740039f343"),       "q" : null,       "name" : "FCA last 3 years",       "frequency" : "Daily",       "scope" : "FederalContractAwardModel",       "filters" : {          "condition" : "AND",           "rules" : [              {                  "id" : "awardDate",                   "operator" : "between_relative_backward",                   "value" : [                      "now-3.5y/d",                       "now/d"                  ]              },               {                  "id" : "subtypes.extentCompeted",                   "operator" : "in",                   "value" : [                      "Full and Open Competition"                  ]              }          ]      },   

The problem is the value in the item in the rules array that has the decimal.

"value" : [      "now-3.5y/d",       "now/d"  ]  

in particular the decimal. Because of a UI error, the user was allowed to enter a decimal value, and so this needs to be fixed to remove the decimal like so.

"value" : [      "now-3y/d",       "now/d"  ]  

My problem is writing a Mongo query to identify these records (I'm a Mongo noob). What I need is to identify records in this collection that have an item in the filters.rules array with an item in the 'value` array that contains a decimal.

Piece of cake, right?

Here's as far as I've gotten.

myCollection.find({"filters.rules": })  

but I'm not sure where to go from here.

UPDATE: After running the regex provided by @R2D2, I found that it also brings up records with a valid date string , e.g.

        "rules" : [              {                  "id" : "dueDate",                   "operator" : "between",                   "value" : [                      "2018-09-10T19:04:00.000Z",                       null                  ]              },   

so what I need to do is filter out cases where the period has a double 0 on either side (i.e. 00.00). If I read the regex correctly, this part

[^\.]  

is excluding characters, so I would want something like

[^00\.00]  

but running this query

db.collection.find( {           "filters.rules.value": { $regex:  /\.[^00\.00]*/ }            } )  

still returns the same records, even though it works as expected in a regex tester. What am I missing?

unzip -j -o not working through Ansible, but working directly on host

Posted: 10 Feb 2022 11:55 AM PST

I am trying to grab one file from app.war called test.properties, this command works perfectly on a RHEL host when I run it directly on it:

unzip -j -o /home/test/app.war "*test.properties*"  

But, when I run the same thing in Ansible, it does not work, it does not extract anything, there is no change:

- name: Extract test.properties file    shell: 'unzip -j -o /home/test/app.war "*test.properties*"'  

Am I doing anything wrong Ansible side? Maybe I am missing something extra like sudo or quotes?

why the original web page did not show the google chrome extension inserted html image

Posted: 10 Feb 2022 11:56 AM PST

I am tried to insert a vue 3 component into the original web from google chrome extension v3 script, now the css and html was insert successfully. What make me confusing is that the inserted html did not show the images from google chrome extension, this is the css define the image path in the vue 3 componnet:

<style lang="scss" scoped>    .reddwarf-btn-icon{    width: 18px;    height: 28px;    background-image: url('chrome-extension://__MSG_@@extension_id__/resource/image/logo.png');    background-size: contain;  }    </style>  

and this is the output of the css when showing in the original web:

.reddwarf-btn-icon[data-v-6bc385e0] {      width: 18px;      height: 28px;      background-image: url(chrome-extension://alepiijaddmmflnaibdpolcgglgmkpdm/resource/image/logo.png);      background-size: contain;  }  

to my surprise, the original web did not show the google chrome extension insert html background image which was specify in the inserted html css. I could successfully open the image in google chrome browser from the css background image link, means that the css specified image path was right, why did not shows the image specified by the inserted html css? I have already add the image resource path config like this in the google chrome extension manifest v3 json config:

"web_accessible_resources" : [{      "resources": [        "/bundle/*.woff" ,        "/content-scripts/web/embed/*",        "/pdf-viewer/*",        "/resource/*"      ],        "matches": ["<all_urls>"]    }]  

what should I do to fix this problem? Am I missing something? this is the view:

enter image description here

I tried to set the background color, it works.

why the active tabs was undefined when send message from backend to content script in google chrome extension v3

Posted: 10 Feb 2022 11:56 AM PST

I am tried to send message from background in google chrome extension v3, this is the background message send code looks like:

export function sendMessageToContent(message: MessageBase) {      debugger      chrome.tabs.query({active:true,currentWindow:true},function(tabs){          var activeTab = tabs[0];          if(activeTab && activeTab.id !== undefined){              chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});          }      });  }  

when I get the current active tab, the tabs was return undefined, why did this happen? I am sure there contains active tabs in google chrome broswer, what should I do to fix this problem? This is the debug view:

enter image description here

what is the right way to create a component instance in vue 3 in google chrome extension v3

Posted: 10 Feb 2022 11:55 AM PST

I want to create a component instance and append to the web page body with vue 3 in google chrome extension v3. This is my vue 3 component define:

<template>      <div>I am a pop</div>  </template>    <script>  import { defineComponent } from "vue"    export default defineComponent({      setup() {                },  })  </script>    <style scoped>      </style>  

the next step I tried to create an instance and tried to append the vue 3 component to the original web page body in google chrome extension content script. this is the code looks like:

let instance = new TranslatorPop()  instance.$mount();  document.querySelector('body')?.appendChild(instance.$el)  

when run this app, shows error like this:

Uncaught (in promise) TypeError: _public_widget_translator_TranslatorPop_vue__WEBPACK_IMPORTED_MODULE_0__.default is not a constructor      at HTMLDocument.firstMouseUp (content.js:17199:24)  

Am I missing something? what should I do to avoid this problem? I tried to do it like this:

const app = createApp(TranslatorPop);  app.use(store);  const vm = app.mount("#app");  document.querySelector('body')?.appendChild(vm.$el)  

the app tell me error:

content.js:17410 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '$el')      at HTMLDocument.firstMouseUp (content.js:17410:56)  

is it possible to append vue 3 component after the html body in google chrome extension

Posted: 10 Feb 2022 11:56 AM PST

I am developing a google chrome extension v3, now I want to append a Vue 3 component after the original web page body. First, I am tried to capture the user selection event in the content script index like this:

document.addEventListener(MOUSE_UP, firstMouseUp);  

the next step, I want to insert a popup component into the original web page that I could show to user some custom content. what I am tried to do like this right now:

import TranslatorPop from '@/public/widget/translator/TranslatorPop.vue';    const selection = getSelection();    export async function firstMouseUp(e: MouseEvent){      if(selection && selection.toString().trim().length>0){                  document.querySelector('body')?.appendChild(TranslatorPop.$el)      }  }  

I want to append the vue 3 component content after the original web html page body element. Seems did not work as expect.Show the error like this:

Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'  

what should I do to append the Vue 3 component to the original web page? is it possible? or any better way to do this? And this is the vue 3 component define:

<template>      <div>I am a pop</div>  </template>    <script>  import { defineComponent } from "vue"    export default defineComponent({      setup() {                },  })  </script>    <style scoped>      </style>  

I have tried to define element like this and append the element:

var z = document.createElement('p');  z.innerHTML = 'test satu dua tiga';  

it works. seems the vue 3 TranslatorPop.$el not right.

Tried 1: I tried to new the component like this:

let instance = new TranslatorPop()  document.querySelector('body')?.appendChild(instance.$el)  

still did not work.

Tried 2: I also tried like this:

const app = createApp(TranslatorPop);  app.use(store);  app.mount("#app");  document.querySelector('body')?.appendChild(app.$el)  

but the compiler shows error like this:

  TS2339: Property '$el' does not exist on type 'App<Element>'.  

Tried 3: I also tried like this:

const app = createApp(TranslatorPop);          app.use(store);          let vm = app.mount("#app");          document.querySelector('body')?.appendChild(vm.$el)  

this compile success, but shows error like this when run the app:

content.js:17410 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '$el')      at HTMLDocument.firstMouseUp (content.js:17410:56)  

tried 4: I tried to use ref to get the dom:

<template>      <div id="app" ref="app">I am a pop</div>  </template>    const app = createApp(TranslatorPop);          app.use(store);          let vm = app.mount("#app");          document.querySelector('body')?.appendChild(vm.$refs.app)  

seems did not work.

How do I add 1 day to an NSDate?

Posted: 10 Feb 2022 11:56 AM PST

Basically, as the title says. I'm wondering how I could add 1 day to an NSDate.

So if it were:

21st February 2011  

It would become:

22nd February 2011  

Or if it were:

31st December 2011  

It would become:

1st January 2012.  

No comments:

Post a Comment