Tuesday, January 4, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


getting timeout error in sending email from php

Posted: 04 Jan 2022 10:42 AM PST

i was trying to send email from php here is the script and the error i am getting is shown in the link below help me to resolve it

require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';  require 'vendor/phpmailer/phpmailer/src/SMTP.php';  use PHPMailer\PHPMailer\PHPMailer;  use PHPMailer\PHPMailer\Exception;  use PHPMailer\PHPMailer\SMTP;  include('vendor/autoload.php');  $mail = new PHPMailer(true);  $mail->SMTPDebug = 3;                     $mail->isSMTP();                        $mail->Mailer = "smtp";  $mail->Host       = 'smtp.google.com;';     $mail->SMTPAuth   = true;                 $mail->Username   = '************@gmail.com';     $mail->Password   = '********';           $mail->SMTPSecure = 'tls';                // $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;  $mail->Port       = 587;                  $mail->setFrom('abc@gmail.com');       $mail->isHTML(true); ```  https://i.stack.imgur.com/FQqbX.png  

Yet another... Functions are not valid as a React child

Posted: 04 Jan 2022 10:42 AM PST

Ok so I load the root url. A post list should be rendered, instead I get the infamous React error...

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.  

index.js and app.js appear to render properly. I believe the malfunction is in the PostList component, perhaps the render method? I know the solution is probably pretty simple, but I cannot see it.

index.js

  7    8 ReactDOM.render(    9     <React.StrictMode>   10         <HashRouter>   11             <App />   12         </HashRouter>   13     </React.StrictMode>,   14     document.getElementById('root')   15 );   16   17    18    19    20 reportWebVitals();  

app.js

  8    9 class App extends React.Component {   10   11     constructor() {   12         super();   13         this.state = {   14             posts: []   15         };   16     }   17   18     componentDidMount() {}   19   20     render() {   21         return (   22             <div className="container">   23                 <h1>hello world</h1>   24                 <Routes>   25                     <Route exact path='/' element={PostList} />   26                     <Route path='/post/:id' element={Post} />   27                 </Routes>   28             </div>   29         );   30     }   31 }   32   33 export default App;  

post-list.js

  5    6 class Post extends React.Component {    7     constructor() {    8         super();    9         this.state = {   10             title: '',   11             content: ''   12         };   13     }   14   15     componentDidMount() {   16         let api = new Api();   17   18         api.posts(this.props.match.params.id).then(data => {   19             this.setState({   20                 title: data.title.rendered,   21                 content: data.content.rendered   22             });   23         });   24     }   25   26     render() {   27         let post = this.state;   28         return (   29             <div className='row'>   30                 <h3>{post.title}</h3>   31                 <div dangerouslySetInnerHTML={{__html: post.content}} />   32             </div>   33         );   34     }   35 }   36   37 class PostList extends React.Component {   38     constructor() {   39         super();   40         this.state = {   41             posts: []   42         };   43     }   44   45     componentDidMount() {   46         let api = new Api();   47   48         api.posts().then(data => {   49             this.setState({   50                 posts: data   51             });   52         });   53     }   54   55     render() {   56         let posts = this.state.posts.map((post, index) =>   57             <h3 key={index}>   58                 <Link to={`/post/${post.id}`}>{post.title.rendered}</Link>   59             </h3>   60         );   61   62         return (   63             <div>{posts}</div>   64         );   65     }   66 }   67   68 export {Post, PostList}  

Yolov5 custom dataset :dataset.yaml file issue

Posted: 04 Jan 2022 10:41 AM PST

1)Is it necessary to clone the Yolov5 git repo in the same drive and folder where we save our train/test images? 2)I have cloned the yolov5 git repo in C drive [C/yol5/yolov5] and my train/test images are in E drive under img_data folder (Train= E/img_data/train Test= E/img_data/test) Here, how should I specify the path in dataset.yaml for train: and test:

P.S :I'm using anaconda prompt for running the training command for yolov5

The instance of entity type 'x' cannot be tracked because another instance with the key value '{Id: 6}' is already being tracked

Posted: 04 Jan 2022 10:41 AM PST

I am working a asp .netcore 6.0 clean architecture project.

When I try to update a site, I got this error,

System.InvalidOperationException: The instance of entity type 'SiteCode' cannot be tracked because another instance with the key value '{Id: 6}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

Before We use services, in there this same code worked fine. Now we move to clean architecture(CQRS and Mediatr). I used same update code but I got this error.

I tried with var result = await _DbContext.SiteCodes.FindAsync(request.Id).AsNoTracking(); this line, But got error as, 'ValueTask<SiteCode?>' does not contain a definition for 'AsNoTracking' and no accessible extension method 'AsNoTracking' accepting a first argument of type 'ValueTask<SiteCode?>' could be found (are you missing a using directive or an assembly reference?) [Application]

Here is my codes

UpdateSiteCommandHandler.cs

public async Task<SiteCode> Handle(UpdateSiteCommand request, CancellationToken cancellationToken)      {          var result = _mapper.Map<SiteCode>(request);            _DbContext.SiteCodes.Update(result);  // goes to exception after this line            await _DbContext.SaveChangesAsync(cancellationToken);            return result;      }  

GetSiteByIdQueryHandler.cs

public async Task<SiteCode> Handle(GetSiteByIdQuery request, CancellationToken cancellationToken)      {                    var result = await _DbContext.SiteCodes.FindAsync(request.Id);            if (result == null)          {              throw new NotFoundException(nameof(SiteCode), request.Id);          }            return result;        }  

controller

public async Task<IActionResult> Update(int id, [FromBody] UpdateSiteCommand command)          {              command.Id = id;                var siteCode = await _mediator.Send(new GetSiteByIdQuery(Id: id));                var result = await _mediator.Send(command);                            return Ok(result);            }  

DependencyInjection.cs

public static class DependencyInjection  {      public static IServiceCollection AddApplication(this IServiceCollection services)      {          services.AddAutoMapper(Assembly.GetExecutingAssembly());          services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());          services.AddMediatR(Assembly.GetExecutingAssembly());          services.AddTransient(typeof(IPipelineBehavior<,>), typeof(PerformanceBehaviour<,>));  // I tried with AddScoped() But not work                   return services;      }    }  

in DbContext

public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))          {              var entries = ChangeTracker                  .Entries()                  .Where(e => e.Entity is AuditableEntity && (                          e.State == EntityState.Added                          || e.State == EntityState.Modified));                foreach (var entityEntry in entries)              {                  if (entityEntry.State == EntityState.Added)                  {                      ((AuditableEntity)entityEntry.Entity).CreatedAt = DateTime.UtcNow;                      ((AuditableEntity)entityEntry.Entity).CreatedBy = _httpContextAccessor?.HttpContext?.User?.Identity?.Name ?? null;                  }                  else                  {                      Entry((AuditableEntity)entityEntry.Entity).Property(p => p.CreatedAt).IsModified = false;                      Entry((AuditableEntity)entityEntry.Entity).Property(p => p.CreatedBy).IsModified = false;                  }                    ((AuditableEntity)entityEntry.Entity).ModifiedAt = DateTime.UtcNow;                  ((AuditableEntity)entityEntry.Entity).ModifiedBy = _httpContextAccessor?.HttpContext?.User?.Identity?.Name ?? null;              }                var result = await base.SaveChangesAsync(cancellationToken)             return result;          }  

Anyone has idea how can solve this issue?

Manual Trigger of TeamCity Build Chains

Posted: 04 Jan 2022 10:41 AM PST

I have 3 major build chain configurations.

  • Health Check
  • E2E Tests
  • API Tests

E2E Tests and API Tests depend on Health Check. I have used snapshot dependency in E2E Tests and API Tests with Health Check where E2E Tests and API Tests run parallelly.

In our current project, we don't require any auto triggers like VCS triggers. I want the entire build chain to get triggered manually from another dummy build configuration. I mean

  • Health Check
  • E2E Tests / API Tests in parallel

Is there a way?

testing code with a "real" Thymeleaf template engine and nothing else

Posted: 04 Jan 2022 10:41 AM PST

In my Spring Boot project (v2.6), one of my components is using a Thymeleaf template engine to generate content.

I want to unit test my component, but I am struggling because it has a TemplateEngine as a constructor dependency :

public EmailNotifier(JavaMailSender emailSender,TemplateEngine templateEngine) {    this.emailSender = emailSender;    this.templateEngine=templateEngine;  }    

I don't want to mock the TemplateEngine (the test would not have great value), I would prefer to use a "real" (and configured) templateEngine, and make sure that the content is generated as I expect. But I would like my test to be as "low-level" as possible, ie without loading the full application with Spring.

Spring Boot doesn't have a Thymeleaf "slice" like it has for Jpa or Web tests, but I guess I need something similar to that.

How can I get the minimum Spring magic in my test, so that it's both a realistic and fast test ?

Does BLE device generates new LTK, CSRK, and IRK every time it bonds with new device?

Posted: 04 Jan 2022 10:41 AM PST

I have a conceptual question, for BLE experts, regarding the keys generated and exchanged when bonding occurs between two BLE devices. I might be wrong or my question might be naive, so please bear with me.

Consider the following example, let's call it Case-1.

Let's say we have a peripheral device (P1) and a central device (C1).

P1 sends advertisements to connect to a nearby device. C1 initiates the connection and both devices start the connection procedure in which both devices exchange their I/O capabilities, pairing method, and some keys. Eventually, once the bonding is complete, both devices have LTK, IRK, and CSRK for encrypting the connection, resolving random addresses, and resolving signatures. Now both P1 and C1 can communicate while using these keys for their respective purposes.

I have the following question:

Q1. The connection is terminated between P1 and C1. Later, when both P1 and C1 connect again, will the two devices use the same LTK, IRK, and CSRK keys that they used in Case-1?

Q2. Let's say a new central (C2) comes into the picture. P1 is no longer connected to C1. P1 now wants to connect (with bonding) with C2. Will the P1 use the same LTK, IRK, and CSRK that it had used(generated) earlier to connect with C1 in Case-1?

Q3. Do the BLE devices use different keys (LTK, IRK, and CSRK) with every new device they connect with?

Q4. If I take the keys (LTK, IRK, and CSRK) stored in the C1 and store them in C2, can P1 connect to C2 using the same keys? Is it possible to make this work or it is incorrect logically and from the security point of view?

It would be a lifesaver if someone can clarify these points. Thanks

PS: I am consulting core-spec v5.3 and some online resources for my reading.

how to use transformer in huggingface without tokenization?

Posted: 04 Jan 2022 10:41 AM PST

I have the following code:

from transformers import AutoTokenizer, AutoModelForTokenClassification, pipeline  tokenizer = AutoTokenizer.from_pretrained("sagorsarker/codeswitch-spaeng-lid-lince")  model = AutoModelForTokenClassification.from_pretrained("sagorsarker/codeswitch-spaeng-lid-lince")  pipeline = pipeline('ner', model=model, tokenizer=tokenizer)  sentence = "some example sentence here"  results = pipeline(sentence)  

this works fine. But instead of a str, I wan't to pass a list of tokens. How do I do that?

The reason I want to do that is, my sentences are already tokenized and simple " ".join() does not reproduce the sentence correctly. For example, isn't has been tokenized into is and n't. But a simple " ".join() will produce is n't

How can I extend cases in reducers with Redux ToolKit?

Posted: 04 Jan 2022 10:41 AM PST

I am making a plugin where there are some universal actions that can be handled in a reducer. I am unsure how to make it so someone can extend for additional cases with the same action. I have some code like this:

export default function createStore() {    return configureStore({      preloadedState: initialStoreState,      reducer: {        workingStores: workingStoreReducer,      },    });  }  

The reducer is what you would expect:

export default createReducer(initialWorkingStoreState, (builder) => {    builder      // chained for a number of actions      .addCase(anImportedAction, (state, { payload }) => {});   

Essentially someone using my plugin may have additional actions to modify the state of workingStores.

I am thinking of solving the problem in a seemingly complicated way where createStore could take a callback, and then my workingStoreReducer becomes a method of getWorkingStoreReducer which would take that callback...

export default function getWorkingStoreReducer(extensions) {    return createReducer(initialWorkingStoreState, (builder) => {      exensions(builder); // method would add cases to builder      builder.addCase(anImportedAction, (state, { payload }) => {});       });  }  

This seems convoluted so hoping there is a simpler thing I have missed in the docs

How do i make an update to my database in ASP.NET MVC

Posted: 04 Jan 2022 10:40 AM PST

i'm making a webbapplication with ASP.NET MVC and im trying to edit my list of objects. If i for example add a product to the site and then click on edit for that product to change the prize i just get a new object with the new prize instead of changing the prize to the product.

So the problem is that instead of updating the products it just adds a new one.

this is how my controller for the products looks like:

using auktioner_MarcusR91.Data;  using auktioner_MarcusR91.Models;  using Microsoft.AspNetCore.Mvc;  using System;  using System.Collections.Generic;  using System.Linq;  using System.Threading.Tasks;    namespace auktioner_MarcusR91.Controllers  {      public class InventoryController : Controller      {          private readonly AppDbContext _db;            public InventoryController(AppDbContext db)          {              _db = db;          }          public IActionResult Index()          {              IEnumerable<Inventory> objInventoryList = _db.Inventories;              return View(objInventoryList);          }            //GET          public IActionResult Create()          {              return View();          }          //Post          [HttpPost]          [ValidateAntiForgeryToken]          public IActionResult Create(Inventory inventory)          {              _db.Inventories.Add(inventory);              _db.SaveChanges();              return RedirectToAction("index");          }            //GET          public IActionResult Edit(int? id)          {              if (id == 0 || id == 5)               {                  return NotFound();              }              var inventoryFromDb = _db.Inventories.Find(id);                if (inventoryFromDb == null)              {                  return NotFound();              }              return View(inventoryFromDb);          }          //Post          [HttpPost]          [ValidateAntiForgeryToken]          public IActionResult Edit(Inventory inventory)          {              if (ModelState.IsValid)               {                  _db.Inventories.Update(inventory);                  _db.SaveChanges();                  return RedirectToAction("index");              }              return View(inventory);                        }      }  }  

I think there is something wrong in my controller.

However here is also my view for when i edit a product:

@model Inventory    <form method = "post" asp-action = "Edit">      <div class = "border p-3 mt-4">          <div class = "row pb-2">              <h2 class = "text-primary">Edit Inventory</h2>              <hr />          </div>          <div class = "mb-3">              <label asp-for ="inventoryName"></label>              <input asp-for = "inventoryName" />              <label asp-for ="finalPrize"></label>              <input asp-for = "finalPrize" />              <label asp-for ="inventoryDesc"></label>              <input asp-for = "inventoryDesc" />              <p>1 för "Transport</p>              <p>2 för "Smycken"</p>              <p>3 för "Hushåll"</p>              <p>4 för "Dekoration"</p>              <select asp-for = "categoryId">                  <option>1</option>                  <option>2</option>                  <option>3</option>                  <option>4</option>              </select>          </div>          <button type = "submit" class = "btn btn-primary" width = "100px">Update</button>          <a asp-controller = "Inventory" asp-action = "index" class = "btn btn-secondary" style = "width: 100px">Back to products</a>       </div>    </form>  

How to find Specific pattern in a paragraph in python

Posted: 04 Jan 2022 10:41 AM PST

I want to find a specific pattern in a paragraph. The pattern must contain a-zA-Z and 0-9 and length is 5 or more than 5. how to implement it on Python

the valid pattern is like-- 9aacbe aver23893dk asdf897

Create a dictionary from two lists in a one-liner

Posted: 04 Jan 2022 10:41 AM PST

From these lists,

lst1 = ['a','b','c']  lst2 = [[1,2],[3,4,5],[6,7]]  

I want to create:

{1: 'a', 3: 'b', 6: 'c', 2: 'a', 4: 'b', 7: 'c', 5: 'b'}  

I can create it using a for loop:

d = {}  for l, nums in zip(lst1, lst2):      for num in nums:          d[num] = l  

I figured I need to use map and zip, so I tried,

dict(map(lambda x: dict(x), zip(lst2,lst1)))  

but this gives

ValueError: dictionary update sequence element #1 has length 1; 2 is required.  

I think the issue is the lst2 is a list of lists but I just don't know how to proceed.

I can't run it I'm not sure if I'm making a sytax error or I've misspelled my function [closed]

Posted: 04 Jan 2022 10:41 AM PST

i'm also getting some errors in my code and so I can't run it I'm not sure if I'm making a sytax error or I've misspelled my function.

orderedArrayListType.h:9:49: error: expected '{' before '<' token

orderedArrayListType.h:22:68: error: invalid use of incomplete type 'class orderedArrayListType'

22 | void orderedArrayListType::insertOrd(const elemType& item) |
^ orderedArrayListType.h:9:7: note: declaration of 'class orderedArrayListType'

9 | class orderedArrayListType: public arrayListType<elemType>    |       ^~~~~~~~~~~~~~~~~~~~  

orderedArrayListType.h:61:91: error: invalid use of incomplete type 'class orderedArrayListType'

61 | int orderedArrayListType::binarySearch(const elemType& item,int left,int right) const | ^~~~~

orderedArrayListType.h:9:7: note: declaration of 'class orderedArrayListType'

9 | class orderedArrayListType: public arrayListType<elemType>    |       ^~~~~~~~~~~~~~~~~~~~  

main.cpp: In function 'int main()': main.cpp:23:18: error: 'binarySearch' was not declared in this scope

23 |     int location=binarySearch(intList,first,last);        |                  ^~~~~~~~~~~~      template <class elemType>  class orderedArrayListType: public arrayListType<elemType> //line 9 orderedArraylistType    template <class elemType>  void orderedArrayListType<elemType>::insertOrd(const elemType& item) //line 22 orderedArraylistType    template<class elemType>  int orderedArrayListType<elemType>::binarySearch(const elemType& item,int left,int right) const //line 61 orderedArraylistType        int location=binarySearch(intList,first,last); //line 23 main  

Formatting Duration in Correct Format `HH:MM`

Posted: 04 Jan 2022 10:41 AM PST

I have some logic designed to generate a formatted duration based on an inputted start and stop time:

  getFormattedDuration = async (stopValue, startValue) => {      const durValue = moment(stopValue, "H:mm").diff(moment(startValue, "H:mm"));      const t = moment.duration(durValue);        const duration = {        hours: t.hours(),        minutes: t.minutes()      }        const formattedDuration = `0${duration.hours}:${duration.minutes}`;      return formattedDuration;        // I'm prepending a `0` here because I know the duration will never be above a certain limit - i.e. it will never get to a double digit number for hours.      }   

This works for the most part. But on occasion I will end up with something like this for output:

duration:  Object {    "hours": 0,    "minutes": 8,  }    formattedDuration:  00:8  

What I want here is 00:08. How can I pad with zeroes, as necessary, to ensure I get a correctly formatted duration value - which should be in this format hh:mm. Does moment.js have a function I can use to handle this?

Image is not showing up on my website (django)

Posted: 04 Jan 2022 10:41 AM PST

I am new to django. I wanted to upload an image but it doesn't show up on website. Instead, it shows a broken image icon. I tried to use load static block but it still doesn't work.

My html file:

<!DOCTYPE html>  <html lang="en">  <head>     <meta charset="UTF-8">     <title>Website</title>  </head>  <body>     <h1>Hello</h1>     {% load static %}     <img src="{% static 'webdev/static/webdev/images/images.jpg' %}">  </body>  

urls.py file:

from django.contrib import admin  from django.urls import path  from homepage import views    urlpatterns = [      path('', views.home_page, name='home'),      path('admin/', admin.site.urls),  ]  

views.py file:

from django.shortcuts import render  from django.http import HttpResponse      def home_page(request, *args, **kwargs):      return render(request, 'home.html', {})  

file tree: https://i.stack.imgur.com/jtZ8t.png

Why can't I mutate an NSObject allocated as mutable, referenced as immutable, then cast back to mutable?

Posted: 04 Jan 2022 10:41 AM PST

I'm allocating an NSMutableAttributedString, then assigning it to the attributedString property of an SKLabelNode. That property is an (NSAttributedString *), but I figured that I could cast it to an (NSMutableAttributedString *) since it was allocated as such. And then access its mutableString property, update it, and not have to do another allocation every time I want to change the string.

But after the cast, the object is immutable and an exception is thrown when I try to mutate it.

Is it true that I can't mutate an NSObject that was allocated as mutable just because it was referenced as immutable?

Trying Brute Force technique to solve a leetcode question but gives an error

Posted: 04 Jan 2022 10:42 AM PST

Here is the link to the problem statement: https://leetcode.com/problems/container-with-most-water/

I am trying to solve this question using brute force technique. The code works fine for most of the test cases but is giving an error for the following test case: [2,3,4,5,18,17,6]

This is the code implementation

    public int maxArea(int[] height) {          int Area = 0;          int maxArea = 0;          for(int i = 0 ; i < height.length ; i++)         {             for(int j = 1 ; j < height.length ; j++)             {                 if(height[i] > height[j])                     maxArea = height[j] * (j-i);                 else                     maxArea = height[i] * (j-i);             }             Area = Math.max(maxArea,Area);         }          return Area;      }  }    Any help will be appreciated  Thanks in advance  

A value of type 'Future<bool>' can't be returned from the function because it has a return type of 'Future<void>'

Posted: 04 Jan 2022 10:41 AM PST

I have:

Future<bool> foo() async => true;  

This is allowed:

Future<void> bar()  {    return foo(); // Works  }  

but this is not:

Future<void> baz() async {    return foo(); // Error  }  

In both bar and baz I'm returning a Future<bool>, but why first works but second fails?


Note: This question isn't about HOW to make it work but rather WHY one works and the other doesn't.

Add CSS based on Button Activated Ionic/Angular 8

Posted: 04 Jan 2022 10:42 AM PST

I have buttons which are dynamically generated. On click of any one of the buttons, I want the css of the button to be changed, based on which button is activated.

My code:

HTML:

 <div class="container">  <div class="scroll" scrollX="true">    <span *ngFor="let item of buttons; let i = index" (click)="genreSelect(item)"      ><ion-button shape="round" [ngClass]="{activated: buttonActive}">{{item.catName}}</ion-button></span    >  </div>  

TS:

this.buttons = [{        id: 1,        catName:'Electronics'      },{        id: 2,        catName:'Books'      },{        id: 3,        catName:'Furniture'      },{        id: 4,        catName:'Laptops'      }];          genreSelect(item){      console.log(item);            this.buttonActive = true;    }  

CSS:

.activated:active{      background-color: red;    }  

The CSS flashes for a second and then goes away.

How can I make the CSS be there if the button is activated.

Unable to Send List Of Array via ajax to Controller

Posted: 04 Jan 2022 10:41 AM PST

I have list of array Generated from dynamically created textbox values .The Issue Is while passing data to controller using ajax ,the count of list is showing in jsonresult but unable to get the list.Its showing Like [object,Object],[object,Object] like the image I added. What I want to retrieve data from list.

My Data Binding Code

     $('#tbl tbody tr').each(function () {          var objlist = [];                   var count = 0;          var row = $(this).closest('tr');          var rowIndex = $(this).closest('tr').index();          row.find('input[type=text]').each(function () {                           count += 1;                  var id    = $(this).attr('id');                  var value = $(this).val();                  var field = $(this).attr('name');                  objlist.push({                      "Id": id,                      "field": field,                      "value": value                  });                  });                   tblList.push(objlist);          });  

My Ajax Sending Method

        $.ajax({          type: 'POST',          url: '@Url.Action("Action", "Controller")',          data:  {tableData: tblList},          global: false,          dataType: "json",          traditional: true,          async: false,          success: function (data) {            ///              }          }      });  

The List Of arrays
data After Sending to controller

Thank you.

Coloured Box Plot With Precomputed Quartiles

Posted: 04 Jan 2022 10:41 AM PST

I'm trying to colour a boxplot with custom values, but it remains in the default blue colour.

For example - see the code in the official tutorial: https://plotly.com/r/box-plots/#box-plot-with-precomputed-quartiles. When I add the code for coloring, nothing happens with the colours:

fig <- plot_ly(y = list(1,2,3,4,5,6,7,8,9), type = "box", q1=list(1, 2, 3), median=list(4, 5, 6),                 q3=list(7, 8, 9 ), lowerfence=list(-1, 0, 1),                 upperfence=list(5, 6, 7), mean=list(2.2, 2.8, 3.2 ),                 sd=list(0.2, 0.4, 0.6), notchspan=list(0.2, 0.4, 0.6),                 color = list(1,1,2),                 colors = list("red2", "grey"))  fig  

What am I doing wrong?

Why is Azure APIM redirecting to the backend service URL?

Posted: 04 Jan 2022 10:40 AM PST

Calls to APIM have suddenly started redirecting to the backend service.

In my test environments, I get a 301 Moved Permanently, whereas for the exact same code deployed to prod, I just get a 200.

Why is my APIM returning a 301?

Here's the HTTP request (the first request is the pre-flight request):

enter image description here

Here're the settings in APIM:

enter image description here enter image description here

Cut string of numbers at letter in bash

Posted: 04 Jan 2022 10:40 AM PST

I have a string such as plantford1775.274.284b63.11.

I have been using identity=$( echo "$identity" | cut -d'.' -f3) to cut at each dot, and then choose the third section. I am left with 284b63.

The format of this part is always a letter, sandwiched by varying amounts of numbers. I would like to take the first few numbers before the letter. An example code line would be this:

identity=$( echo "$identity" | cut -d'anyletter' -f1)  

What do I replace anyletter with to cut at whatever letter is listed there, so that I end with a string of 284?

Configure imports relative to root directory in create-react-library library

Posted: 04 Jan 2022 10:40 AM PST

I am trying to setup a react component library with create-react-library (which uses rollup under the hood) and port over our application's existing component library so that we can share it between applications. I am able to create the library, publish to a private git registry, and consume it in other applications. The issue is that I have had to change all of my imports to relative imports which is rather annoying as I am planning on porting over a large amount of components, hocs and utils.

The entry point of the package is the src dir. Say I have a component in src/components/Text.js and a hoc in src/hoc/auth.js. If I want to import withAuthentication from src/hoc/auth.js into my Text component, I have to import it like import { withAuthentication } from "../hoc/auth" but I'd like to be able to import with the same paths I have in my existing application so it's easy to port over components, like import { withAuthentication } from "hoc/auth"

I have tried a lot of config options, jsconfig.json the same as my create-react-app application, manually building my library with rollup rather then using create-react-library so I'd have more config options but to no avail.

Below are the relevant bits from my package.json as well as my jsconfig.json, any help would be greatly appreciated, I am sure I am not the only person who's had this issue.

Here's the package.json

{    "main": "dist/index.js",    "module": "dist/index.modern.js",    "source": "src/index.js",    "files": [      "dist"    ],    "engines": {      "node": ">=10"    },    "scripts": {      "build": "microbundle-crl --no-compress --format modern,cjs",      "start": "microbundle-crl watch --no-compress --format modern,cjs",      "prepare": "run-s build",      "test": "run-s test:unit test:lint test:build",      "test:build": "run-s build",      "test:lint": "eslint .",      "test:unit": "cross-env CI=1 react-scripts test --env=jsdom",      "test:watch": "react-scripts test --env=jsdom",      "predeploy": "cd example && npm install && npm run build",      "deploy": "gh-pages -d example/build"    },    "peerDependencies": {      "react": "^16.0.0",      "react-html-parser": "^2.0.2",      "lodash": "^4.17.19",      "@material-ui/core": "^4.11.0",      "react-redux": "^7.1.1",      "redux": "^4.0.1",      "redux-localstorage": "^0.4.1",      "redux-logger": "^3.0.6",      "redux-thunk": "^2.3.0",      "react-router-dom": "^5.1.1",      "react-dom": "^16.13.1",      "react-scripts": "^3.4.1",      "react-svg": "^12.0.0",      "reselect": "^4.0.0"    },    "devDependencies": {      "microbundle-crl": "^0.13.10",      "babel-eslint": "^10.0.3",      "cross-env": "^7.0.2",      "eslint": "^6.8.0",      "eslint-config-prettier": "^6.7.0",      "eslint-config-standard": "^14.1.0",      "eslint-config-standard-react": "^9.2.0",      "eslint-plugin-import": "^2.18.2",      "eslint-plugin-node": "^11.0.0",      "eslint-plugin-prettier": "^3.1.1",      "eslint-plugin-promise": "^4.2.1",      "eslint-plugin-react": "^7.17.0",      "eslint-plugin-standard": "^4.0.1",      "gh-pages": "^2.2.0",      "npm-run-all": "^4.1.5",      "prettier": "^2.0.4"    },    "dependencies": {      "node-sass": "^7.0.0"    }  }  

and here's the jsconfig:

{    "compilerOptions": {      "baseUrl": "src"    },    "include": ["src"]  }  

Power Bi - Autorefresh the PowerBi report with import Query

Posted: 04 Jan 2022 10:42 AM PST

I have a Power BI report that is using the Import query method (Source - getData - Azure Data Explorer Kusto)

I have completed couple of reports with Import Query mode and I could not setup Auto refresh. Then I modified the report to Direct Query mode and still I could not see the Auto refresh Option. Could you please clarify How do I set up Scheule Autorefresh in Power Bi reports.

I am using Power BI desktop, Should I start a fresh report from Direct query mode instead of modifying the existing report. Thanks.

Database creation Failed in Genexus Offline android app

Posted: 04 Jan 2022 10:40 AM PST

I have a couple issues with an Offline Android app developed in Genexus 16 U11 in C# Environment and SQL 2017.

First of all, when I press Build All to any changes to the OfflineDatabase object, Genexus' Navigation View marks it has an error, but it doesn't specify where it is or in what consist the error (and the build log doesn't mention any error either). I also tried to quote or straight remove all the code in said object, so it can be built clean, and still get an error without any clue about what may be going on.

On the other hand, the app also throws an "Database creation Failed" error before the app starts and also I can't find any message regarding this specifically in the ADB monitor, but for some reason Genexus still manages to build.

Any ideas about what may be happening? do you guys need more information about this issue?

thanks beforehand

Using a method reverse to sorted list gives error

Posted: 04 Jan 2022 10:40 AM PST

Hi I have a list of places

>>> places = ['NYC','PA', 'SF', 'Vienna', 'Berlin', 'Amsterdam']  

I temporarily sort it with

>>> sorted(places)  

And finally I want to sort the sorted(places) list in reverse alphabetical order.

Is this ever correct?

>>> sorted(places).reverse()  

I thought it was but Python3 says the list is none.

Thank you

Vue 3 template refs dynamic name

Posted: 04 Jan 2022 10:40 AM PST

I noticed that to make a template ref in Vue 3 composition api <script setup>, I should make a variable name with the exact same as the ref value.

For example in Vue 3 documentation:

<template>    <div ref="root">This is a root element</div>   <--- notice the ref name "root"  </template>    <script>    import { ref, onMounted } from 'vue'      export default {      setup() {        const root = ref(null)   <---- and the variable name should be "root" too          onMounted(() => {          console.log(root.value)         })          return {          root        }      }    }  </script>  

I was wondering if I can use the ref the way as Vue 2 do, because I have elements whose ref is random string, and it works on Vue 2 by just passing the name on $refs object.

<div ref="myCustomRefName"></div>    <script>  let myRef = this.$refs["myCustomRefName"]  </script>  

But I can't do that since in Vue3, I should similarize the variable name and the ref prop value. Any help will be appreciated.

ERROR: Could not find a version that satisfies the requirement sys (from versions: none) ERROR: No matching distribution found for sys

Posted: 04 Jan 2022 10:41 AM PST

On trying to install sys package in Python 3.7.4 version using IDLE, I am getting the below error:

Input : C:\Users\UserName\Downloads>pip install sys

Output : Collecting sys ERROR: Could not find a version that satisfies the requirement sys (from versions: none) ERROR: No matching distribution found for sys

RxJS operator waitUntil

Posted: 04 Jan 2022 10:40 AM PST

a: 1---2-3-4--5---6  b: ------T---------    o: ------1234-5---6  

Using RxJS, is there some operator that can accomplish the diagram above? I have stream A which is a random stream of events, given a stream B which has a single true event, can I have an output stream that doesn't emit anything until that true event, and then sends everything is had saved up until then and afterwards emits normally?

I thought maybe I could use buffer(), but it seems like there is no way to do a one time buffer like this with that operator.

No comments:

Post a Comment