Saturday, November 6, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


vb net navigate each link and get a specific url

Posted: 06 Nov 2021 08:47 AM PDT

I'm having trouble using web browser in VB .NET to navigate a list of URL's inside a multiline textbox, wait them for load and get a specific URL (should contain a specific word).

What I have until now:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click        Dim webClient As New System.Net.WebClient          'Dim htmlDoc As New HtmlAgilityPack.HtmlDocument()      For Each strLine As String In TextBox4.Text.Split(vbCrLf)          Console.WriteLine("Turning False")          Console.WriteLine("----")          WebBrowser1.Navigate(strLine)          Console.WriteLine("Waiting for navigation - " & strLine)          Console.WriteLine("Navigated")        Next      For Each link In links          TextBox6.Text = TextBox6.Text & link & vbCrLf      Next      Dim lines As New List(Of String)(TextBox6.Lines)      For i As Integer = lines.Count - 1 To 1 Step -1          If lines(i) = lines(i - 1) Then              lines.RemoveAt(i)          End If      Next      TextBox6.Lines = lines.ToArray  End Sub    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted      For Each ele As HtmlElement In WebBrowser1.Document.Links          'Get whatever text there is in the 'href' attribute          Dim eletarget As String = ele.GetAttribute("href")          'Add it to the listbox          If eletarget.Contains("cfsecure") Then              links.Add(eletarget)              'Carry on to the next link          End If      Next  End Sub  

First of all, it seems it doesn't wait until fully loaded. After that, I don't get any link from what I asked (don't know if it's related to the first problem I have or any mistake in my code getting href with the word "cfsecure").

Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted      For Each ele As HtmlElement In WebBrowser1.Document.Links          'Get whatever text there is in the 'href' attribute          Dim eletarget As String = ele.GetAttribute("href")          'Add it to the listbox          If eletarget.Contains("cfsecure") Then              links.Add(eletarget)              'Carry on to the next link          End If      Next  End Sub  

What I'm missing here?

Why must a struct member always have an identifier?

Posted: 06 Nov 2021 08:47 AM PDT

Why must a struct member always have an Identifier? The answer of course is because that is how the language is defined, but I'd like to understand the reason behind it.

typedef union u {      int a;      struct {          int a; //Why is an identifier necessary here?          int b;      } s;  } u;  

How to add new row in csv using Python panda

Posted: 06 Nov 2021 08:46 AM PDT

Hello this is my csv data

        Age      Name  0       22  George  1       33  lucas  2       22  Nick  3       12  Leo  4       32 Adriano  5       53  Bram  6       11  David  7       32  Andrei  8       22 Sergio  

i want to use if else statement , for example if George is adult create new row and insert + i mean

Age      Name       Adul  22       George    +  

What is best way?

This is my code Which i am using to read data from csv

import pandas as pd  produtos = pd.read_csv('User.csv', nrows=9)  print(produtos)  for i, produto in produtos.iterrows():      print(i,produto['Age'],produto['Name'])  

Using separate and mutate functions

Posted: 06 Nov 2021 08:47 AM PDT

I am new to R and trying to mutate the following character variable "Tax.Rate..." into four different columns (i.e., CGST, SGST, UTGST, and IGST) with tax rates applicable to that head under that column. Example of dataset shown below:

df # A tibble: 3 x 1 Tax.Rate....

1 "CGST 2.5% + SGST 2.5%" 2 "CGST 6% + UTGST 6%"
3 "IGST 12% "

I have tried using 'separate' and 'mutate' functions with little success

Any guidance would be appreciated

R Data wrangling questions

Posted: 06 Nov 2021 08:46 AM PDT

I have this sheep.df dataset from dmm package. I need to convert the data format like that:

original data:

  1. 2a4242 9a4003 9a4123 1984 T M 4.4 19.2 40

New format:

  • 1 2a4242 9a4003 9a4123 1984 T M 4.4
  • 2 2a4242 9a4003 9a4123 1984 T M19.2
  • 3 2a4242 9a4003 9a4123 1984 T M 40

So for each of the last 3 columns there will be new rows numbered like 1 2 3 .

recursion function recurring too often

Posted: 06 Nov 2021 08:46 AM PDT

Relatively early in my python journey and coding in general. I've come across an example question that asks that should flatten a list of lists. Now how many lists of lists exist I wouldn't know. Which leads me to doing my first recursion attempt:

array = [[1,2,3,['a','b','c'],4],'d', [5,6],[7],8,9]

def flattenme (iteritem):    for item in iteritem:      if isinstance(item, Iterable, bytes, str)):          flattenme(item)      else:          flattened.append(item)  

When I run this with

print(f"flatten method: {list(flattenme(array))}")  

I get the error:

RecursionError: maximum recursion depth exceeded in comparison

Shouldn't

flattenme(item)  

at the last time it's called just return the non-list item? I'm not sure what is going wrong and where my understanding of recursion is failing.

Promise {<pending>} when i try to fetch

Posted: 06 Nov 2021 08:45 AM PDT

Why does it say Promise {<pending>} when i try to fetch a player outfits list

fetch(`https://avatar.roblox.com/v1/users/93414699/outfits`)   .then(res => res.json())    .then(data => {                        for (var name in data.data) {          for (var i = 0; i < data.data[name].length; i++) {                         var outfits = data.data[i].name;              console.log(outfits)                          }      } })  

All im trying to do is get a list of all the player outfits name and console log them but it doesn't work i keep getting Promise {<pending>}

discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

Posted: 06 Nov 2021 08:45 AM PDT

So I've been looking at this for a while now and I just can't seem to figure it out. The program bugs out on the 2nd to last line, and I'm not sure why. I have a lot of similar code that works just fine, but this command just doesn't want to work.

@slash.slash(name='poll-create', description='Start a poll', guild_ids=guild_id, options=[create_option(name='message',               description='Message', option_type=3, required=True), create_option(name='choice1', description='First choice',               option_type=3, required=True), create_option(name='choice2', description='Second choice',               option_type=3, required=True), create_option(name='choice3', description='Third choice',               option_type=3, required=False), create_option(name='choice4', description='Fourth choice',               option_type=3, required=False), create_option(name='choice5', description='Fifth choice',               option_type=3, required=False), create_option(name='choice6', description='Sixth choice',               option_type=3, required=False), create_option(name='choice7', description='Seventh choice',               option_type=3, required=False), create_option(name='choice8', description='Eighth choice',               option_type=3, required=False), create_option(name='choice9', description='Ninth choice',               option_type=3, required=False), create_option(name='choice10', description='Tenth choice',               option_type=3, required=False)])  async def poll_create(ctx, message, choice1, choice2, choice3=None, choice4=None, choice5=None,                        choice6=None, choice7=None, choice8=None, choice9=None, choice10=None):      my_embed = discord.Embed(title=message)      my_embed.add_field(name="_ _", value=choice1, inline=False)      msg = await ctx.send(embeds=[my_embed])      await msg.add_reaction('1️⃣')  

Unity - Startup errors

Posted: 06 Nov 2021 08:45 AM PDT

I was using unity 2019.2 and from nothing, it started to have errors from the built-in packages (In brand new projects too!). I tried reinstalling all packages from which the errors came from and it didn't help. At this point, I gave up and uninstalled 2019.2, and I installed 2021.1.26f, but the errors didn't disappear (again in new projects!). I tried reinstalling all packages, but it didn't help. I looked over it on the internet, but I didn't find anything helpful. I have no idea how I should fix it. If you have a solution please share it with me.

A bunch of errors

another bunch of errors

Consuming REST API on the same site

Posted: 06 Nov 2021 08:45 AM PDT

I have a REST API deployed in my website which is in PHP. What is the best approach to consume the API among the two scenarios shown in the picture?

Does the first scenario have a high impact on the performance?
I am using the task.php file to create CURL and sending back the API response as it is.

Scenario 1: All requests send to a PHP page (task.php) and then from the task.php, we use CURL to access the API (No validation required in the task.php as we have implemented tight validation in the API side.

Scenario 2: I call the API from the task.js itself instead of routing through a PHP page in the website. (in the expectation of avoiding overhead and performance issues)

enter image description here

Expected slice but got interface

Posted: 06 Nov 2021 08:44 AM PDT

I'm using sqlx package to make my database queries. I'm trying to create a global SELECT * for all my models in my database package

func FindAll(model interface{}, table string, db *sqlx.DB) error {      err := db.Select(&model, "SELECT * FROM "+table)      if err != nil {          return fmt.Errorf("FindAll: %v", err)      }      return nil  }  

And I'm using it like this

albums := []Album{}  err := database.FindAll(albums, "album", a.DB)  

But I got this error : expected slice but got interface

I don't know how can I manage the first model parameter to make it works for any models

Selenium/Python Unable to use `:contains()` in CSS_SELECTOR

Posted: 06 Nov 2021 08:45 AM PDT

When I try to use :contains in Selenium's By.CSS_SELECTOR, such as

presence = EC.presence_of_element_located((By.CSS_SELECTOR, ".btn:contains('Continue Shopping')"))  

or

presence = EC.presence_of_element_located((By.CSS_SELECTOR, ".btn\:contains('Continue Shopping')"))  

or

presence = EC.presence_of_element_located((By.CSS_SELECTOR, ".btn\\:contains('Continue Shopping')"))  

the Python program crashes with the error

Exception: Message: invalid selector: An invalid or illegal selector was specified    (Session info: chrome=95.0.4638.54)  

Is it possible to use :contains in Selenium? The CSS selector

$('.btn:contains("Continue Shopping")')  

works fine in Chrome's JS console.

Using Chrome 95.0.4638.54, ChromeDriver 95.0.4638.54, Python 3.10 on Ubuntu 20.04.

How to refer to a static property of the child class from a non-static method in the parent class?

Posted: 06 Nov 2021 08:44 AM PDT

I am trying to refer to a static property defined in my child class, from a non-static method in my parent class, but can't figure a way to achieve this. Is this possible in any case?

class Parent {      static staticList: {          a: number      } = {          a: 1      };        public test<TParent extends Parent>(this: TParent, key: keyof TParent['constructor']['staticList']) { /** can't figure out how to refer to the constructor class of the this parameter here */          console.log(this.constructor.staticList[key]); /** while this logs out the correct information, why is typescript complaining about this line? */      }  }    class Child extends Parent {      static staticList: {          a: number          b: number      } = {          a: 2,          b: 2      }  }    const childInstance = new Child();  childInstance.test('a'); /** this correctly logs out 2, and it should type hint me to "a" or "b", instead of the "never" */  

Here's a fiddle for my problem also: TS Playground

Redirect from query string to clean path in firebase

Posted: 06 Nov 2021 08:46 AM PDT

I changed the url structure of my website and i want to do 301 permanent redirect, but it doesn't seem to work, i want to redirect from example.com/?p=MJvb9ZO1y6Q to example/p/MJvb9ZO1y6Q.html

here's the redirects section in my firebase.json file

 "redirects": [{    "regex": "/?p=(.*)",    "destination": "/p/:1.html",    "type": 301  }]  

Assigning a predicate variable instead of a lambda expression

Posted: 06 Nov 2021 08:45 AM PDT

The following textbook Join query runs fine:

var list = from family in db.Families.Where(f => !f.isDeleted)    join member in db.Members.Where(m => !m.isDeleted)    on family.Id equals member.FamilyID    select new { family = family.LastName, member = member.DisplayName };  

list is a IQueryable: {Microsoft.FrameworkCore.Query.Internal.EntityQueryable<<>f__AnonymousType0<string, string>>} and I can call list.ToList().

However, instead of using a lambda, if I use a predicate in the first Where as follows:

Predicate<Family> query = f => !f.isDeleted;  var list = from family in db.Families.Where(new Func<Family, bool>(query))    join member in db.Members.Where(m => !m.isDeleted)    on family.Id equals member.FamilyID    select new { family = family.LastName, member = member.DisplayName };  

then list becomes a [IEnumerable]: {System.Linq.Enumerable.<JoinIterator>d__105<Family, Member, short, <>f__AnonymousType0<string, string>>} and the Results View throws a "There is already an open DataReader associated with this Connection which must be closed first.".

I couldn't reproduce it anymore but I am certain sometimes the Results View throws a "Data is null" exception.

I need to make my query a variable as the exact query required depends on some other conditions. Why does using a Predicate assignment cause the type of list to be different, and how do I fix the error?

Offset CFrame Math

Posted: 06 Nov 2021 08:44 AM PDT

So, for my FPS Framework, I want to make automated Aim Downs Sights, i.e., without using an animation.

The issue is that I have to move the:-

  • Arms
  • Weapon But I can't do that without welding the arms to the weapon, but I need the arms welded to the RootPart instead.

So I took a rig and started experimenting, and I came up with a solution!

  • An anchored part will be taken as the camera(this is just for testing purposes)
  • The RootPart will be welded to the CameraPart
  • There will be a AimPart which defines where the camera should be in order to make the player feel like they are aiming down sights.

And I came up with this

local AimPartPosition = (Camera.CFrame:inverse() * AimPart.CFrame).Position  CamWeld.C0 = CamWeld.C0 * CFrame.new(Vector3.new(-AimPartPosition.X,-AimPartPosition.Y,-AimPartPosition.Z))  

Here, I get the offset of the AimPart from the CameraPart, and then reverse the position and finally apply that to the offset of RootPart to CameraPart.(The reason I put .Position is because I only want to reverse the Position and not the Rotation, just to be safe).

This works very well and I am proud I did it, but I feel like not using that extra CameraPart. I want to use RAW CFrame values instead of Motor6Ds.

This obviously wouldn't work...

local AimPartPosition = (Camera.CFrame:inverse() * AimPart.CFrame).Position  RootPart.CFrame = Camera.CFrame:inverse() * RootPart.CFrame * CFrame.new(Vector3.new(-AimPartPosition.X,-AimPartPosition.Y,-AimPartPosition.Z))  

Because

RootPart.CFrame ~= Camera.CFrame:inverse() * RootPart.CFrame  

I have the offset I need to apply to the RootPart, I just do not know how.

AWS Api Gateway does not respond with CORS headers only on OPTIONS call

Posted: 06 Nov 2021 08:47 AM PDT

I tried to add CORS to my API and it does work for GET, POST, etc. but not for OPTIONS calls. What could be the reason?

It is a completely new API. I added some hello world lambda function as a route and * as an allowed origin. I thought the whole point of OPTIONS calls is to send these headers...

Here is Postman requesting POST With POST

And here with OPTIONS enter image description here

(Swoole) How to get client IP adress when using Laravel Octane?

Posted: 06 Nov 2021 08:47 AM PDT

I want to get information about incoming request such as ip adress, headers,etc in Laravel Octane. But the $_SERVER variable doesnt have REMOTE_ADDR key:

Route::get('/test', function (){      array_key_exists('REMOTE_ADDR', $_SERVER); //false      dd(getallheaders()); // []  });  

Looks like because i dont have apache on my server, But what about swoole it self ?

How can i combine 2 data in 1 array with different value?

Posted: 06 Nov 2021 08:44 AM PDT

Currently, I have a function where will join 2 data with the same weight in 1 array. My target is how I can join them with a different value? I have a default value that is equal to 15 for the difference. Additional: I need to put a restriction. Only less than or greater than 15 weight differences should be in the array. If it exceeds, then it shouldn't be in the same array.

For example:

entryID:1 weight:1900 and entryID:2 1915 will be in array 1... entryID:3 weight:1915 and entryID:4 1920 will be in array 2.

//This current snippet joins 2 data in 1 array if they have the same weight. My target is to join 2 data also in 1 array but with different weights.

const source = [{      entryID: 1,      entryName: 'player1',      weight: 1900,          },    {      entryID: 2,      entryName: 'player2',      weight: 1915,         },    {      entryID: 3,      entryName: 'player3',      weight: 1915,        },    {      entryID: 4,      entryName: 'player4',      weight: 1920,        },    {      entryID: 5,      entryName: 'player5',      weight: 1950,          },    {      entryID: 6,      entryName: 'player6',      weight: 1965,         },            ]        const combine = (source) => {      return source.reduce((acc, curr) => {        if (acc[curr.weight]) {          const levelArr = acc[curr.weight];          const last = levelArr[levelArr.length - 1];          if (last.length === 2) {            levelArr.push([curr])          } else {            last.push(curr)          }        } else {          acc[curr.weight] = [            [curr]          ];        }        return acc;      }, {})    };        var result = combine(source)    var html = ""    var keys = Object.keys(result) //if there are more than one keys i.e : 2..      for (var i = 0; i < keys.length; i++) {    result[keys[i]].forEach(function(val) {        val.forEach(function(value, index) {                   var entryIDs = index == 0 ? "entryIDM[]" : "entryIDW[]"          var handlers = index == 0 ? "handlerM[]" : "handlerW[]"          var weights = index == 0 ? "weightM[]" : "weightW[]"          html += `<input type="text" name="${entryIDs}" value="${value.entryID}">                    <input type="text" name="${handlers}" value="${value.entryName}">                   <input type="text" name="${weights}" value="${value.weight}">                   `      })      })                }    document.getElementById("result").innerHTML = html     console.log(result);
<div id="result">  </div>

My expected output:

{    1900_1915: [[{    entryID: 1,    entryName: "player1",    weight: 1900  }, {    entryID: 2,    entryName: "player2",    weight: 1915  {    1915_1920: [[{    entryID: 3,    entryName: "player3",    weight: 1915  }, {    entryID: 4,    entryName: "player4",    weight: 1920  }  

Update tensor using randomly generated column index and another tensor

Posted: 06 Nov 2021 08:45 AM PDT

I need a tensor with shape [3136, 512] where i update random value where the column is inside a list of randomly generated column index.

What i mean is that i create a tensor with all 0 and shape [3136, 512], create a list with 410 elements that rappresent the column indices of the tensor created before, then i have a tensor with shape [3136, 410] that contain the values i want to update the first tensor. The problem is that i need to map the first value of the indices list to column 0 of the tensor update.

Example:

  1. Generate 410 random columns index, done.

  2. Convert them to tensor, done.

  3. Update tensor_testing[row][col] with value initial_weight[row][colonna] where colonna is not the index of the
    initial_weights(so, it's not 0,1,2,3,4....) but associate the indices to the value randomly generated before. Let's say the random generated the values (6,7,9) then i need to update tensor_testing[row][6] with value initial_weights[row][0] and so on for each row until the end of the generated indices.

    import tensorflow as tf    if __name__ == '__main__':      import random    # Shape of the tensors  shape_for_layer = [3136, 512]  subshape = [3136, 410]  # Create a random tensor with the shape above  initial_weight = tf.random.uniform(subshape, minval=0, maxval=None, dtype=tf.dtypes.float32, seed=None,                                     name=None)  # Create a 0s tensor with the shape above  tensor_testing = tf.zeros(shape_for_layer, tf.float32)  # Generate 410 random value for the column index where i will take the values  layer_456_col = random.sample(range(512), 410)  # Later on set them in order  # Convert to Tensor for tf.gather use  indices_col = tf.convert_to_tensor(layer_456_col)      # Result to print  random = ...    # Reshape back to [3136, 512] i don't know if it's really needed since it was the original shape.  random = tf.reshape(random, shape_for_layer)    print(tf.shape(random))  

How I can add additional fees to different products in woocommerce

Posted: 06 Nov 2021 08:46 AM PDT

I use this code to add additional fee to a specific product id's. The problem is that I can add only one fee to a different products id's.

add_action('woocommerce_cart_calculate_fees', 'add_fees_on_ids');   function add_fees_on_ids() {      if (is_admin() && !defined    ('DOING_AJAX')) {return;}      foreach( WC()->cart->get_cart() as $item_keys => $item ) {        if( in_array( $item['product_id'],     fee_ids() )) {        WC()->cart->add_fee(__('ADDITIONAL FEE:'), 5);        }      }   }   function fee_ids() {      return array( 2179 );   }  

I need to add different fees to different products - for example: Product 1 with product ID 1234 will have "xx" additional fee. Product 2 with product ID 5678 will have "xx" additional fee.

With this code I can set only one fee for a different products. How i can add different fees to different products in woocommerce?

Thank you in advance!

How to diagnose SQL errors?

Posted: 06 Nov 2021 08:45 AM PDT

I'm self-learning SQL and after finishing the basics in SQLbolt, I discovered HackerRank and got stuck with this problem suing MySQL.

I tried the following code below, but it returns an error:

SELECT ROUND(LAT_N,4) FROM STATION  ORDER BY LAT_N DESC  LIMIT 1 OFFSET (SELECT FLOOR(COUNT(LAT_N)/2) FROM STATION)  

The error is as follows:

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT FLOOR(COUNT(LAT_N)/2) FROM STATION)' at line 3  

What seems to be the problem with the code above? The flow of thought supposedly was to sort the LAT_N in descending manner and get only one value using LIMIT. Now, to get the median, we offset the limit by (SELECT FLOOR(COUNT(LAT_N)/2) FROM STATION). When I only run that query, it returns a value of 249. When I use OFFSET 249 instead of the subquery, the result is correct. Why does it not work with the subquery?

Also, is there a diagnosis tool in SQL that runs you through the step-by-step process of the code, so you would pinpoint on what step the code is returning an error?

Want to plot a graph [duplicate]

Posted: 06 Nov 2021 08:46 AM PDT

import matplotlib.pyplot as plt  loans.boxplot(column="RevolvingUtilizationOfUnsecuredLines")  

on running the above i am getting the below error

                                  KeyError: "None of [Index(['RevolvingUtilizationOfUnsecuredLines'], dtype='object')] are in the [columns]"  

How to detect changes in a prefilled Angular Reactive Form in Edit Mode

Posted: 06 Nov 2021 08:45 AM PDT

I want to detect changes on a Reactive Form while working in Edit Mode. I tried using valueChanges but the issue is when I am loading an already submitted form for editing it, it is triggering events for each prefilled control. While my requirement is to only trigger when user made any changes to the form. Anyone can please suggest

Primefaces remove NotificationBar after closing it

Posted: 06 Nov 2021 08:46 AM PDT

I have a notifictionBar on my application and I don't just want to "hide" it after close icon pressed where the hide happens on client side. My aim is to not render it again.

so I have below code. My expectation is that the "update" property of commandLink should rerender the entire notification component where it will be unrendered. As this is written here, I failed :)

Can someone help please ?

<h:form id="announcement-form">      <p:notificationBar id="id-announcement"              position="top" effect="slide"              autoDisplay="true" styleClass="top"              widgetVar="announcement"              rendered="#{announcementSupport.shouldDisplayAnnouncement()}">          <p:commandLink title="Close" class="ui-notificationbar-close"                          action="#{announcementSupport.announcementClosed}"                          update=":announcement-form:id-announcement">              <i class="fa fa-times fa-2x" />          </p:commandLink>          <div class="announcement">              <div class="logo">              </div>              <div class="content">                  <div class="title">                      <h:outputText value="#{messages['main.announcement.title']}"/>                  </div>                  <div class="body">                      <h:outputText value="#{announcementSupport.announcement}"/>                  </div>              </div>          </div>      </p:notificationBar>  </h:form>  

Plotly Dash- Using For Loop to Generate Multiple Headers Dynamically Inside a Tab

Posted: 06 Nov 2021 08:47 AM PDT

I am creating an application using Plotly/Dash and I am trying to dynamically update the number of inputs that show up in my application, based on the user input from the dropdown. All of this happens inside a tab. However, when I try to do a for loop through the callback to get a fixed number(2) headers, I get this error saying:

The children property of a component is a list of lists, instead of just a list.

In the layout I defined:

[dcc.Input(type= 'number', id='input %i'%i) for i in range(2)]    

And the corresponding decorator is

[app.callback(Output('input %i' % i, 'value'),Input('dropdown-profile-specific', 'value'))(lambda value: None) for i in range(2)]     

How would I unnest this to get rid of this error. Additionally, how can I make the number of iterations dependent on the length of a list that is provided as the output from another callback?

Module not found: Error: Can't resolve '@angular/flex-layout' in '/app'

Posted: 06 Nov 2021 08:47 AM PDT

I suddenly got this error

Module not found: Error: Can't resolve '@angular/flex-layout' in '\src\app'  

This error occurred After I have install @angular/cdk,

After this error I have again installed flex-layout using

 npm install @angular/flex-layout  

But now there is error for

Module not found: Error: Can't resolve '@angular/http' in '\src\app'  

If I Install a http, then some other module is getting missed. How to stop this situation? What has gone wrong?

If I install @angular/http then again it starts with

Module not found: Error: Can't resolve '@angular/flex-layout' in '\src\app'  

Let's encrypt SSL couldn't start by "Error: EACCES: permission denied, open '/etc/letsencrypt/live/domain.net/privkey.pem'"

Posted: 06 Nov 2021 08:46 AM PDT

I tried to use SSL by Node.js but it doesn't work because permission denied.

try {  var TLSoptions = {      key: fs.readFileSync("/etc/letsencrypt/live/domain.work/privkey.pem"),      cert: fs.readFileSync("/etc/letsencrypt/live/domain.work/cert.pem")  };    https.createServer(TLSoptions, app).listen(port, host, function() {     console.log("TLS Website started.")  }); catch(e) {      console.log(e)  }  

=>

{ Error: EACCES: permission denied, open '/etc/letsencrypt/live/domain.work/privkey.pem'  at Object.fs.openSync (fs.js:663:18)  ... (Librarys dump)  errno: -13,  code: 'EACCES',  syscall: 'open',  path: '/etc/letsencrypt/live/domain.work/privkey.pem' }  

So I tried re-make files of *.pem.

rm -f /etc/letsencrypt/live  rm -f /etc/letsencrypt/archive      rm -f /etc/letsencrypt/renewal  sudo ./letsencrypt-auto certonly -a standalone -d domain.work  

and check file authority.

/etc/letsencrypt/live/domain.work$ ls -lsa  total 12  4 drwxr-xr-x 2 root root 4096 Jan  3 21:56 .  4 drwx------ 3 root root 4096 Jan  3 21:56 ..  0 lrwxrwxrwx 1 root root   37 Jan  3 21:56 cert.pem ->   ../../archive/domain.work/cert1.pem  0 lrwxrwxrwx 1 root root   38 Jan  3 21:56 chain.pem ->   ../../archive/domain.work/chain1.pem  0 lrwxrwxrwx 1 root root   42 Jan  3 21:56 fullchain.pem ->   ../../archive/domain.work/fullchain1.pem  0 lrwxrwxrwx 1 root root   40 Jan  3 21:56 privkey.pem ->   ../../archive/domain.work/privkey1.pem    /etc/letsencrypt/archive/domain.work$ ls -lsa  total 24  4 drwxr-xr-x 2 root root 4096 Jan  3 21:56 .  4 drwx------ 3 root root 4096 Jan  3 21:56 ..  4 -rw-r--r-- 1 root root 1789 Jan  3 21:56 cert1.pem  4 -rw-r--r-- 1 root root 1647 Jan  3 21:56 chain1.pem  4 -rw-r--r-- 1 root root 3436 Jan  3 21:56 fullchain1.pem  4 -rw-r--r-- 1 root root 1708 Jan  3 21:56 privkey1.pem  

but It is not resolved and I cannot find any mistakes and problems.
How to resolve this problem?

How to read connection string from data access layer in asp.net 5

Posted: 06 Nov 2021 08:45 AM PDT

With the new ASP.NET 5 doing away with web.config, and thus the ConfigurationManagement namespace, I was trying to figure out how to read the connection string from my data access layer project in my MVC application.

Researching this issue, everything I've found says to just read the config value from the project.json configuration file in the Startup.cs file like this:

var configuration = new Configuration();  configuration.AddJsonFile("config.json");  configuration.AddEnvironmentVariables();    //////    var connString = configuration.Get("Data:DefaultConnection:ConnectionString");  

But I don't want my web project having anything to do with the data access. So, how does my data access layer project retrieve the connection string in this setup?

Update: Here's my startup.cs file and the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)  {      // Add Identity services to the services container.      services.AddIdentity<ApplicationUser, IdentityRole>()          .AddEntityFrameworkStores<ApplicationDbContext>()          .AddDefaultTokenProviders();        // Add MVC services to the services container.      services.AddMvc();        // Register application services.      services.Configure<ApplicationOptions>(options =>      {          options.ConnectionString = "Data:DefaultConnection:ConnectionString";      });  }  

And here's my DataAccessLayer project, and my RepoBase.cs class

public class RepoBase  {      //private readonly string _connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;      //private readonly string _connectionString = Environment.GetEnvironmentVariable("ConnectionString");      private readonly string _connectionString;        public RepoBase(IOptions<ApplicationOptions> appOptions)      {          this._connectionString = appOptions.ConnectionString;            // or just read directly from System.Configuration.Get("");      }        protected SqlConnection GetConnection()      {          var conn = new SqlConnection(_connectionString);          conn.OpenAsync();            return conn;      }  }  

This is where I'm drawing a blank as to how to retrieve my ApplicationOptions object in my DAL project, or just read the connectionstring value that is set in the Startup.cs

configuration.AddEnvironmentVariables()  

method call.

Update 2: Oh, is this what I need to use from my Data Access Layer to access the environment variables: https://github.com/aspnet/configuration/blob/master/src/Microsoft.Extensions.Configuration.EnvironmentVariables/EnvironmentVariablesConfigurationProvider.cs

unresolved symbol with only dlmopen and not dlopen

Posted: 06 Nov 2021 08:46 AM PDT

I am using a shared library which has quite a few global variables, used in almost all the exported functions so the library functions are not thread safe. My application creates multiple threads and each threads dynamically open this library and to avoid using any synchronization between parallel calls to the exported functions, I copied the library multiple times with different names on disk with each thread opening its own copy. To avoid this, now I am looking to use dlmopen instead but I am facing an issue.

When I use dlopen in my application to open a library, the application works fine

libHandle = dlopen(ip->pathname, (RTLD_LAZY |RTLD_LOCAL|RTLD_DEEPBIND|RTLD_NODELETE));  

When I use dlmopen instead in the application, I am getting error:

ip->libHandle = dlmopen(LM_ID_NEWLM, ip->pathname,                  (RTLD_LAZY |RTLD_LOCAL|RTLD_DEEPBIND|RTLD_NODELETE));  

The dlerror is:

error(libfoo.so.0: undefined symbol: _ZTIN6google8protobuf11MessageLiteE)  

Doing an nm does show the symbol undefined U _ZTIN6google8protobuf11MessageLiteE

Question1: I am wondering how can I resolve this issue so I can use dlmopen.

The reason is because when one uses LM_ID_NEWLM a new empty namespace is created in the libc without any symbols. So the library should be self contained or relinked with any dependencies.

Question2: My main application exports some symbols which libfoo will use. Due to opening libfoo in new namespace, the symbols of main application are not visible to libfoo and hence it is not able to resolve them. Is there any way to tell linker to create a new namespace NEWLM, by making replica of existing base namespace and than use dlmopen + lmid of newly created namespace to open libfoo with all other required symbols being already present?

Question3: Can I myself mmap the different section of libfoo and provide a pointer to the mmaped sections to libc. Means take the job of opening file and mmaping it out of libc and let it do the job of symbol resolution? That way I don't need to call dlopen at all and the multiple text section issue would be solved.

No comments:

Post a Comment