Wednesday, May 5, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Which is the benefit of the delegate in this example?

Posted: 05 May 2021 08:17 AM PDT

I am reading about delegates and I show this example, but I don't see the benefit of the delegates in this case. The code of the example is this:

delegate void PrintDelegate(string prompt);    static void PrintSomewhere(PrintDelegate print, string prompt)  {      print(prompt);  }    static void PrintOnConsole(string prompt)  {      Console.WriteLine(prompt);  }    static void PrintOnScreen(string prompt)  {      MessageBox.Show(prompt);  }    static void Main()  {      PrintSomewhere(PrintOnConsole, "Press a key to get a message");      Console.Read();      PrintSomewhere(PrintOnScreen, "Hello world");  }  

In the main, why is this better than call directly to the methods PrintOnConsole and PrintSomewhere?

I get the example from this question. Pass Method as Parameter using C#

Thanks.

Error : MediaPlayer.setVolume(float, float) on a null object reference

Posted: 05 May 2021 08:17 AM PDT

I am coding in Android Studio (Mac), and I keep having the same mistake repeatedly.

Attempt to invoke virtual method 'void android.media.MediaPlayer.setVolume(float, float)' on a null object reference

This is where the error occurs :

MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.speechfall);              //mp.start();              mp.setVolume((float) 1.0, (float) 1.0);  

Even when I'm adding "mp.start();" I get the same exception :

Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference

I don't understand what I need to do because the same code (without the mp.start()) works properly on my teammate's computer (Windows). Is there a package that I need to download? or a plugin that I need to update?

Thank you for your answers.

What's the python syntax for assigning scalar coordinates in xarray?

Posted: 05 May 2021 08:17 AM PDT

I'm working with a netCDF file that has both logical (1,2,3...) and physical coordinates (lat, on).

I know that I have to assign multidimensional coordinates in xarray, but I can't find the syntax.

The goal is to produce an array dataset like this:

import numpy as np  import pandas as pd  import xarray as xr  import cartopy.crs as ccrs  from matplotlib import pyplot as plt    ds = xr.tutorial.open_dataset('rasm').load()  ds  

Where xc and yc are my physical coordinates. This is where I am so far (it's obviously unfinished):

no2_da = xr.DataArray(no2[0],                        dims=("x",                              "y"),                        coords={                            "lat": ("x",scanline)                            "lon": ()                        }                         )    

Thank you!

shell command to remove file/remove all files

Posted: 05 May 2021 08:17 AM PDT

I'm doing a program where I create/delete files based on if an user has enough credits to do it.

So far I got the creation of the files and the deduction of the respective credit when they do so.

Now i'm trying do do a command like this:

cancel [-a] nameofthefile

Where if I do cancel [-a] it removes all the files that the user has created till that point or else cancel nameofthefile removes that specific file and then adds the credits back to the user.

I understand that i will use rm -i filename and rm *ext but I dont't understand how do I put that into the command itself like so it knows that when i put an [-a] it is to delete all the files.

Hope I made myself clear!

Thank you!

How to validate arangements(sequence) of <p> tag or text inside the div?

Posted: 05 May 2021 08:16 AM PDT

I want to check the arrangements to validate if it is in the right position after drag and drop event

<div class="container" id="con">      <p class="draggable" draggable="true" id="p1">1</p>      <p class="draggable" draggable="true" id="p2">2</p>      <p class="draggable" draggable="true" id="p3">3</p>      <p class="draggable" draggable="true" id="p4">4</p>  </div>  

Conditional union and conditional fields

Posted: 05 May 2021 08:16 AM PDT

I have the following tables :

Appt :

ApptId ResourceId
12345 abcde
12345 bcdef
23456 defgh
34567 cdefg

Resource:

ResourceId ResourceType
abcde Person
bcdef Place
cdefg Place
defgh Person

Place :

PlaceId ResourceId PlaceName
zzzzz bcdef Boston
yyyyy cdefg Dallas

Person:

PersonId ResourceId PersonName
wwwww abcde Smith
xxxxx defgh Doe

and I try to have this :

ApptId ResourceName PlaceName
12345 Smith Boston
23456 Doe
34567 Dallas

So for the moment I am able to have this :

ApptId ResourceName PlaceName
12345 Smith
12345 Boston
23456 Doe
34567 Dallas

But I failed to aggregate Resource and Place if they are about the same Appointment.

Hope this is clear

Angular/Typescript - Easy way to append items to every array in a list

Posted: 05 May 2021 08:16 AM PDT

I have a formTemplate array which contains list of fields. I want to append few default item to each fields list. I was able to achieve it with the following code. But I want to know whether we have any easy way or Linq expression to do the same.

    AppendDefaultFields(){         for (var i = 0; i < this.formTemplate.length; i++) {            this.formTemplate[i].fields = [this.renderDefaultFields('EmployeeId'), this.renderDefaultFields('HireDate'), ...this.formTemplate[i].fields];          }       }    renderDefaultFields(fieldName: string) {      return {        id: 1,        title: fieldName,        type: 'string',        mandatory: false,      }    }  

_.throttle executing API more than once

Posted: 05 May 2021 08:16 AM PDT

I have a TimeLine component that renders posts 5 at a time

and when the user scrolls to the end of the page the throttle function is called.

I am trying to throttle the request to a maximum of once per second but The API is called multiple times

I tried several solutions like:

  • making a global flag that won't let you use the function unless a certain timeout has passed "It doesn't make sense because I am using the throttle to do that but I tried to check if my implementation is wrong"

  • declaring the throttle function alone outside the component

TimeLine.js

export default function TimeLine() {      const dispatch = useDispatch();      const posts = useSelector(state => state.postReducer.posts);      const loaded = useSelector(state => state.postReducer.loaded);      const TIMEOUT = 1000;          // Loaded keeps track of loaded posts      if(loaded === 0){          API.Post.getAllPosts(loaded)(dispatch);      }        if(loaded > 5){          if(loaded % 5 === 0) window.scrollTo(0, document.body.scrollHeight * 0.6)                }        window.addEventListener('scroll', () => throttledReq(loaded, TIMEOUT, dispatch));            const classes = useStyle();      return (          <div>              <NewPost  />                {(posts && posts.length > 0)?posts.map((post, index) => (                  <div key={post._id} className={classes.post}>                      <Post                          currentIndex={index}                          {...post.user}                          dispatch={dispatch}                          postID={post._id}                          postContent={post.text}                      />                  </div>              )): false}          </div>      );  };      

the Throttle function

const throttledReq = (loaded, TIMEOUT, dispatch) => _.throttle(e => {      const bottomLimit = document.documentElement.offsetHeight - window.innerHeight;      if(document.documentElement.scrollTop === bottomLimit){              API.Post.getAllPosts(loaded)(dispatch);      }  }, TIMEOUT)();    

My requests

enter image description here

Default get way Goes away

Posted: 05 May 2021 08:16 AM PDT

I'm using Debian 10. in my networking setting after I set the default network its works fine, after reboot its goes away and I should set it again. the code that I use to set default gateway :

$ sudo route add default gw  10.0.2.20  

I copied a file on unix from say directory 1 to 2, and now im trying to rename said file but i keep getting an error ''no such file or directory''

Posted: 05 May 2021 08:16 AM PDT

I had initially copied the file from my school directory to tmp, but now I cant find it in /tmp and I'm really confused cause it showed me that the file was copied

jQuery Flot in bootstrap modal with legend in container

Posted: 05 May 2021 08:16 AM PDT

I want to put the legend beside the Flot plot as follows:

<div class="row">    <div class="col-9">      <div class="height300px" id="flot_plot"></div>    </div>    <div class="col-3">      <p>Legend</p>      <div id="legendContainer"></div>    </div>  </div>  

I then define the Flot options as follows:

var options = {    legend: {      container: $('#legendContainer')    },  };  

Everything works fine when the Flot plot is placed in the main document:

enter image description here

But when the Flot plot is placed in a bootstrap modal, the following happens:

enter image description here

When inspecting the legendContainer, the legend is there, but with:

style="display: none;"  

I could remove the style and the legend would be shown correctly. But then I still have the additional legend on top of the Flot plot.

Any workaround to make this work would be appreciated!

AppBar component of material-ui package not working in my react js application

Posted: 05 May 2021 08:16 AM PDT

i am creating my first React Application (WebApp) and I have following issue. I want a Navigation Bar and therefore I am using the AppBar component of the material-ui lib. I used the the example Simple App Bar explained on the official material-ui page.

If I compile and run the app I get the following result: enter image description here

Why it doesn't look like the example on the website, althought I used the same code. What am I doing wrong?

Thanks in advance.

Machine Learning Euclidian Distance Classifier

Posted: 05 May 2021 08:16 AM PDT

I'm doing an elective subject at university which mainly focuses on UI and doing an exercise - this task should be done practically in any language (I've chosen Python). Our teacher doesn't explain well and so it's hard for all of us to follow along - so I decided to post this question here. I don't want anyone to give me a solution, I just don't understand what he wants - maybe someone can give an example to me.

I understand that I should generate random points with two features which are belonging to one of the three classes - okay. But I don't get the second part of the sentence. The classes are normally distributes with a mean(?)-vector of [0, 1, 2], [0, 0, 1] and [1, 0, 0]?

  • What is the second parameter I there?
  • Why the mean vector has 3 entries when we only have 2 features?

Here is the full exercise:

Euclidean distance classifier

  1. Develop an Euclidian distance classifier as below (warm up!): Generate 1000 random points corresponding to each class out of 3 classes with feature size 2 for a 3-class classification problem. For the simplicity consider the classes following N([0 1 2], I), N([0 0 1], I) and N([1 0 0],I) respectively.
  2. Generate the output an 1000-dimensional vector whose ith component contains the class where the corresponding vector is assigned, according to the minimum Euclidean distance classifier.

Writing a function to input a binary tree from a txt file

Posted: 05 May 2021 08:16 AM PDT

I wrote this but in only adds elements in the left side of the tree, i don't really know how to properly fill the tree..

btree inputBtree(FILE *in){      btree T1, T2;      item el;        if(fscanf(in, "%d", &el) != 1)          return newBtree();        T1 = inputBtree(in);        T2 = inputBtree(in);        return consBtree(el, T1, T2);  }  

could you help me?

Fixing character count, decimal count, and "0" character count in swift

Posted: 05 May 2021 08:16 AM PDT

When I run this code, I can only insert the "." once. If it is already in one of the text fields I can't use another "." in another text field, this is the same with the character count. If 8 characters are entered in one text field no characters can be entered in any of the other text fields.

func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {                  // cost of materials          if (costOfMaterialsTXT.text?.contains("."))! && string == "." {                  return false          }              // tech hours          if (techHoursTXT.text?.contains("."))! && string == "." {              return false          }              // helper hours          if (helperHoursTXT.text?.contains("."))! && string == "." {                  return false          }          //Prevent "0" characters as the first characters                        // cost of materials          if (costOfMaterialsTXT.text == "0" && string.isEmpty)  {                    return true          } else if (costOfMaterialsTXT.text == "0" && string != ".") {                  return false          }              // tech hours          if (techHoursTXT.text == "0" && string.isEmpty)  {              return true                    } else if (techHoursTXT.text == "0" && string != ".") {              return false          }              // helper hours          if (helperHoursTXT.text == "0" && string.isEmpty)  {                    return true          } else if (helperHoursTXT.text == "0" && string != ".") {                      return false          }            //Limit the character count to 8                            // cost of materials          if ((costOfMaterialsTXT.text!) + string).count > 8 {                  return false          }              // tech hours          if ((techHoursTXT.text!) + string).count > 8 {              return false          }              // helper hours          if ((helperHoursTXT.text!) + string).count > 8 {                  return false          }            // Only Numbers And Decimal-Point Allowed          let allowedCharacters = "0123456789."          let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)          let typedCharactersSet = CharacterSet(charactersIn: string)            return allowedCharacterSet.isSuperset(of: typedCharactersSet)      }  

Push results to a builder and get a notification when builder is done

Posted: 05 May 2021 08:16 AM PDT

I'm trying to use observables for the first time, with System.Reactive.

I wish to push the results of 3 features as they are produced to a same ReportBuilder that would then notify the caller when it is done so the caller can pass the resulting Report to another service.

I am facing a few issues :

  1. If I have an observer implementing IObserver of multiple types, OnCompleted method would be called for the first observed sequence to finish, isnt it ? How can I observe multiple sequence of different types until all are finished ?

  2. After registering my subscriptions, does the execution flow returns to caller object or is it only after OnCompleted is called ? This is not too clear to me.

  3. Since the builder is both an observable and an observer, my implementation seems awkward to me, what is the proper way to implement an object that is both an observable and an observer ?

  4. Should I merge my 3 observables and make the feature async to consume the result as they are produced ? The below implementation doesn't seem to have too much benefits compared to straightforward calls and deferred execution.

Here is an attempt to put my ideas to code

public interface IFeatureC  {      IEnumerable<ModelC> ExecuteFeature();  }    public interface IFeatureB  {      IEnumerable<ModelB> ExecuteFeature();  }    public interface IFeatureA  {      IEnumerable<ModelA> ExecuteFeature();  }      public class ModelA { }   public class ModelB { }   public class ModelC { }      public class Report  {      public Report()      {          ReportElements = new List<ReportElement>();      }      public List<ReportElement> ReportElements { get; }  }        public class ReportElement  {      public ReportElement(ModelA item)      {          // DoSomething      }        public ReportElement(ModelB item)      {          // DoSomething      }        public ReportElement(ModelC item)      {          // DoSomething      }  }    public interface IOtherService  {      void DoSomething(Report report);  }        public class Orchestrator : IObserver<Report>  {      private readonly ReportBuilder _builder;      private readonly IOtherService _otherService;      private readonly IFeatureA _featureA;      private readonly IFeatureB _featureB;      private readonly IFeatureC _featureC;      private readonly ILogger _logger        public Orchestrator(IFeatureA featureA, IFeatureB featureB, IFeatureC featureC, ReportBuilder builder, IOtherService otherService, ILogger logger)      {          _featureA = featureA;          _featureB = featureB;          _featureC = featureC;          _builder = builder;          _otherService = otherService;          _logger = logger;      }        public void Run()      {          IObservable<ModelA> resultAObservable = _featureA.ExecuteFeature().ToObservable();            IObservable<ModelB> resultBObservable = _featureB.ExecuteFeature().ToObservable();          IObservable<ModelC> resultCObservable = _featureC.ExecuteFeature().ToObservable();            resultAObservable.Subscribe(_builder);          resultBObservable.Subscribe(_builder);          resultCObservable.Subscribe(_builder);            // Do I need to wait until OnCompleted is called ?      }        public void OnCompleted()      {          _logger.Information("Report pushed");      }        public void OnError(Exception error)      {          logger.Error(error);          throw error;      }        public void OnNext(Report report)      {          _otherService.DoSomething(report);      }  }    public class ReportBuilder : IObserver<ModelA>, IObserver<ModelB>, IObserver<ModelC>  {      private readonly IObserver<Report> _reportObserver;      private Report Report { get; } = new Report();      private readonly IObservable<Report> _observableReport;        public ReportBuilder(IObserver<Report> reportObserver)   // Is there a better than passing the caller ?      {          _reportObserver = reportObserver;          _observableReport = Observable.Return(Report);        }      public void OnCompleted()  // This will get called by the first finished sequence and I will miss some observed elements ?      {          _observableReport.Subscribe(_reportObserver);      }        public void OnError(Exception error)      {          throw error;      }        public void OnNext(ModelA value)      {          Report.ReportElements.Add(new ReportElement(value));      }        public void OnNext(ModelB value)      {          Report.ReportElements.Add(new ReportElement(value));      }        public void OnNext(ModelC value)      {          Report.ReportElements.Add(new ReportElement(value));      }  }  

How to assign icon after add a list (which are added using JS)?

Posted: 05 May 2021 08:16 AM PDT

I actually want to add delete icon after adding the list item. I'm adding list items using JS. So I want to see delete icon after adding list.

const viewList = () => {    const listItem = document.getElementById('list-item');    listItem.innerHTML = '';      todoList.forEach((list) => {      const listEl = document.createElement('li');      const { toDo } = list;            let title = list.toDo.text;        listEl.textContent = title;      listItem.append(listEl);    });  }
<div class="show">    <ul id="list-item"></ul>  </div>

how can I change id in URL but keep URL from a childcomponent

Posted: 05 May 2021 08:16 AM PDT

I have a have a list of links inside a childcomponent which is integrated in different pages and if I click on a link, I need to get an id back, but I need to keep the current URL with the new id to call another method.

this.$router.push({path: '/page/', params: {id:id}})  this.$router.push({path: '/otherpage/', params: {id:id}})  

I tried several things which are not working, like

this.$router.push({path: this.$router.currentRoute, params: {id:id}})  

to get the following on different pages

http://domain/page/1  

or

http://domain/otherpage/1  

Handle Unauthorized request in Django Rest [duplicate]

Posted: 05 May 2021 08:16 AM PDT

error page

If any request failed to authenticate this view, the user is getting the default Django-Rest page. How I can customize this response in case of an unauthorised request.

@api_view(['GET'])  @authentication_classes([JWTTokenUserAuthentication])  @permission_classes([IsAuthenticated])  def home_view(request):  -----  

Custom TextView alignment

Posted: 05 May 2021 08:17 AM PDT

I wrote a small custom text view in order to use it on a list. There are three States depending on which i want to have this:

State 1 -> just the text, for example TEST_TEXT

State 2 -> a drawable start, a color background and the same text TEST_TEXT

State 3 -> a different drawable start, different color background and the same text TEST_TEXT

The text has always the same value (TEST_TEXT)

But with my implementation i lost the alignment and as a result the text on the state that i do not have a drawable start is not align with the others that have drawable as you can see on the image below. I want all of them to be start align.

lost start alignmnet

Is there a way to achieve it?

My custom text view class is :

enum class State {      STATE_ONE,      STATE_TWO,      STATE_THREE  }    class CustomTextView @JvmOverloads constructor(      context: Context,      attrs: AttributeSet? = null,      defStyleAttr: Int = 0  ): TextView(context, attrs, defStyleAttr) {        private val PADDING = 4 * resources.displayMetrics.density      private val ZERO_PADDING = 0 * resources.displayMetrics.density        var state: State = State.STATE_ONE          set(value) {              field = value              updateTextView()              invalidate()          }        private fun updateTextView() {          when(state) {              State.STATE_TWO -> {                  this.setBackgroundResource(R.color.light_red)                  this.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_baseline_message_24, 0, 0, 0)                  this.compoundDrawablePadding = PADDING.toInt()                  this.setPadding(PADDING.toInt(), PADDING.toInt(), PADDING.toInt(), PADDING.toInt())              }              State.STATE_THREE -> {                  this.setBackgroundResource(R.color.colorGreenBright)                  this.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_baseline_message_24, 0, 0, 0)                  this.compoundDrawablePadding = PADDING.toInt()                  this.setPadding(PADDING.toInt(), PADDING.toInt(), PADDING.toInt(), PADDING.toInt())              }              else -> {                  this.setBackgroundResource(R.color.transparent)                  this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)                  this.compoundDrawablePadding = PADDING.toInt()                  this.setPadding(ZERO_PADDING.toInt(), ZERO_PADDING.toInt(), ZERO_PADDING.toInt(), ZERO_PADDING.toInt())                }          }      }  }  

The layout where i add them is this:

<?xml version="1.0" encoding="utf-8"?>  <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="match_parent"      android:layout_height="match_parent"      xmlns:tools="http://schemas.android.com/tools"      xmlns:app="http://schemas.android.com/apk/res-auto">          <custom.textView.CustomTextView          android:id="@+id/textViewOne"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="TEST_TEXT"          android:textSize="12sp"          android:textColor="@color/black"          android:background="@drawable/drawable_rounded_text_bg"          app:layout_constraintStart_toStartOf="parent"          app:layout_constraintEnd_toEndOf="parent"          app:layout_constraintTop_toTopOf="parent"          android:layout_marginTop="30dp"/>        <custom.textView.CustomTextView          android:id="@+id/textViewTwo"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="TEST_TEXT"          android:textSize="12sp"          android:textColor="@color/black"          android:background="@drawable/drawable_rounded_text_bg"          app:layout_constraintStart_toStartOf="parent"          app:layout_constraintEnd_toEndOf="parent"          app:layout_constraintTop_toBottomOf="@+id/textViewOne"          android:layout_marginTop="10dp"/>        <custom.textView.CustomTextView          android:id="@+id/textViewThree"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="TEST_TEXT"          android:textSize="12sp"          android:textColor="@color/black"          android:background="@drawable/drawable_rounded_text_bg"          app:layout_constraintStart_toStartOf="parent"          app:layout_constraintEnd_toEndOf="parent"          app:layout_constraintTop_toBottomOf="@+id/textViewTwo"          android:layout_marginTop="10dp"/>    </androidx.constraintlayout.widget.ConstraintLayout>  

and finally my activity is simple like this:

class CustomTextActivity: BaseActivity() {        private lateinit var binding: ActivityCustomTextBinding        override fun onCreate(savedInstanceState: Bundle?) {          super.onCreate(savedInstanceState)          setContentView(getView())          initLayout()      }        override fun getView(): View {          binding = ActivityCustomTextBinding.inflate(layoutInflater)          return binding.root      }        private fun initLayout() {          binding.textViewOne.state = State.STATE_ONE          binding.textViewTwo.state = State.STATE_TWO          binding.textViewThree.state = State.STATE_THREE      }  }  

Getting an array from a json object into a list

Posted: 05 May 2021 08:17 AM PDT

I have the following code:

y=list()  y.extend(args.get("vars"))  y.extend({("var_last","2")})  print(y)  

While args supposed to look like:

args = {      .      .      .  "vars": [   {   "name": "str"    "value": "str"   }]   }  

However I get: {{O, b, j, c, t, o, b, j, e, c, t} {("last_var", "2")}}

Instead of: {{"Str","str"},{("last_var", "2")}}

What am I doing wrong?

Consider defining a bean of type 'reactor.core.publisher.Mono' in your configuration

Posted: 05 May 2021 08:17 AM PDT

Anyone knows how to solve this?

import reactor.core.publisher.Flux;  import reactor.core.publisher.Mono;    @RestController  @RequestMapping("product")  @CrossOrigin(origins= "*", methods = {RequestMethod.GET, RequestMethod.POST})  public class ProductController {            private final Mono<RSocketRequester> requester;      private final ProductService service;                  public ProductController(ProductService service, Mono<RSocketRequester> requester) {          this.service = service;          this.requester = requester;   }              @GetMapping(value = "/socket/all", produces = MediaType.TEXT_EVENT_STREAM_VALUE)      public Flux<ProductDto> allBySocket(){          return this.requester.flatMapMany(r -> r.route("todos")                  .data(new ProductRequestDto())                  .retrieveFlux(ProductDto.class));      }  

Error

Description:

Parameter 1 of constructor in com.example.productservice.controller.ProductController required a bean of type 'reactor.core.publisher.Mono' that could not be found.

Action:

Consider defining a bean of type 'reactor.core.publisher.Mono' in your configuration.

This is the bean of my RSocketRequester

public class RSocketConfiguration {      @LocalServerPort      private int port;            @Bean      public Mono<RSocketRequester> rSocketRequester(              RSocketStrategies rSocketStrategies,              RSocketProperties rSocketProps,              ServerProperties serverProps){                  return RSocketRequester.builder()                          .rsocketStrategies(rSocketStrategies)                          .connectWebSocket(getURI(rSocketProps, serverProps));      }        private URI getURI(RSocketProperties rSocketProps, ServerProperties serverProps) {          String protocol = serverProps.getSsl() != null ? "wss" : "ws";            return URI.create(String.format("%s://localhost:%d%s", protocol,                   port, rSocketProps.getServer().getMappingPath()));      }  }  

Unix sendmail command sending attachment both as file and in the body of message

Posted: 05 May 2021 08:15 AM PDT

I'm trying to send an XLS file attachment with sendmail command on Unix (I can't use any other command, apart from mail and mailx, these are the only ones available - but I should stick to sendmail).

Problem is: the receiver gets an email which has the file as attachment (which is OK), but also the binary file content in the body of the mail. For example:

Dear XYZ,    please find attached the file    ** here it starts a long series of random symbols **  

I need to avoid the file content to appear in the mail body.

Here's what I do to send the email with attachment:

(echo "To: MyRecipient@domain.com"   echo "From: MySender@domain.com"   echo "Subject: Mail subject"   echo "mime-version: 1.0"   echo "content-type: multipart/related; boundary=MessageBoundary"   echo ""   echo "--MessageBoundary"   echo "content-type: text; charset=\"UTF-8\""   echo ""   echo "Dear XYZ,"   echo ""   echo "please find attached the file"   echo ""   echo "--MessageBoundary"   echo "content-type: text; charset=\"UTF-8\"; name=MyAttachment.xls"   openssl base64 < "MyAttachment.xls" ) | sendmail -tv  

Is there anything wrong?

Thanks in advance.

SQL Error [22P02] does not recognise varchar converted to integer in the where clause

Posted: 05 May 2021 08:17 AM PDT

I have table TROQ which does have a field named cod defined as Varchar(13) (Postgres 11.8)

When the first four characters of cod are numeric it means it is "special troq". Special Troqs, according to this numeric first four characters can be "Production" when this four numeric characters form a code that is less than 5000 and "Development" when the code is over 5000. This is just for the example, in the real problem there are many more cathegories to special troqs, but each of them forming a numeric range as for the example

So I tried the following query:

select cod, pref  from   (select cod, substr(cod, 1, 4)::integer pref  from troq  where isnumeric(substr(cod,1, 4))) CT  where pref < 5000  

Implementation for function isnumeric:

CREATE OR REPLACE FUNCTION public.isnumeric(text)   RETURNS boolean   LANGUAGE plpgsql  AS $function$  DECLARE x NUMERIC;  BEGIN         x = $1::NUMERIC;         RETURN TRUE;  EXCEPTION WHEN others THEN         RETURN FALSE;  END;  $function$  ;  

And I got error:

    SQL Error [22P02]: ERROR: la sintaxis de entrada no es válida para integer: «INFD»   ... Meaning about: Input sintax not valid for integer <<INFD>>  

If I take off the where from the outer query:

select cod, pref  from   (select cod, substr(cod, 1, 4)::int pref  from troq  where isnumeric(substr(cod,1, 4))) CT  

Then it throws no error message. It shows all TROQ's whose first four characters have a numeric code. But I find no way to apply any condition on this pref casted field.

Next thing I tried was all kind of castings on the where, some making sense others not, but with no improvement on the result... Meaning things like:

... where pref::varchar < '5000'  ... where pref::numeric < 5000  

Just in case the matter was about the casting, I tried to_number with same result (The query works with no error if I remove the where clause and gives this 22P02 error when I try to add a condition on casted field pref):

select cod, pref  from   (select cod, to_number(substr(cod, 1, 4), '0000') pref  from troq  where isnumeric(substr(cod,1, 4))) CT  where pref < 5000  

Any explanation or help on the matter would be highly appreciated. Thank you in advance

Script to reproduce the exercise with just four records:

CREATE TABLE public.troq (      cod varchar(13) NOT NULL  );    INSERT INTO public.troq (cod) VALUES   ('1234Trala')  ,('Tururu')  ,('4532Vargas')  ,('n4567Titi')  ;  

how to create a hierarchy on the page object model classes?

Posted: 05 May 2021 08:16 AM PDT

This might be a very strange question, but I am not even sure how to title this question. I am quite new to C# and Selenium. I have done some coding on it and I'm quite comfortable creating a (quitemessy) test that runs how I want to. I would like to organize my tests a bit better.

I will use this as an example to what I want to achieve:

On a login page lets say I have a button "Log In" and that button opens a page that let's me put my credentials "Username" and "Password".

Lets say i would like to program it like this: have the landing page with the login with all the elements of that page, and one only for the elements of the login page.

And the test would be something like this:

LandingPage.Login.Click();  LandingPage.Login.Username("username");  LandingPage.Login.Password("password";  LandingPage.Login.LoginBtn.Click();  

and then after the Log In is completed i could have something like:

Database. (everything in the database page). (actions or areas i can navigate to)  

There would be some hierarchy on this classes. Username belongs to login, login belongs to LandingPage, and so on. I have seen this type of coding being used. I'm starting to create a "page object model" for my test and would like to separate it so then i can use the way I showed above. The "LandinPage.cs" would have the login link as well as other elements and the "Login.cs" would have the username field and the password and the login button, along side other elements not relevant now.

I also understand that this is not really for unit testing but more integration testing.

My question is, is there a name for this kind of formatting? I am struggling to find such so I can start my studying there.

How do I edit a Tensorflow dataset in a Pandas DataFrame?

Posted: 05 May 2021 08:16 AM PDT

I am trying to build a transformer model for abstractive text summarization task. My dataset is the CNN DM and I am trying to put the features on pandas DataFrame.

My code:

pip install tensorflow_datasets  import tensorflow_datasets as tfds    cnn_builder = tfds.summarization.cnn_dailymail.CnnDailymail()  cnn_info = cnn_builder.info  cnn_builder.download_and_prepare()  datasets = cnn_builder.as_dataset()  train_dataset, test_dataset = datasets["train"], datasets["test"]    reviews = pd.DataFrame({'Text':train_dataset['article'] ,'Summary':train_dataset['highlights'] })   reviews.head()  

But the output is :

'PrefetchDataset' object is not subscriptable

Xcode git commit fails when running git hooks

Posted: 05 May 2021 08:15 AM PDT

Recently I've started using git hooks for my project, to run a script before committing, and I usually commit from Xcode's git client when reviewing the changes, but now with the pre-commit hooks Xcode thinks the commit failed, when my scripts are executing correctly.

enter image description here

Is there a way to tell Xcode that the scripts finished successfully, or just mute it and let the commit go through? Committing with the hooks works through the terminal and through Fork (GUI git client)

P.S.: The commit still succeeds, its just Xcode thinks it doesn't. Checking the repo again shows the files as committed.

Get all collections from one device in SCCM

Posted: 05 May 2021 08:16 AM PDT

I am currently writing a small program to interact with SCCM and query device collections. But because I am using Asp.Net 5 it seems that the SCCM dlls' AdminUI.WqlQueryEngine and Microsoft.ConfigurationManagement.ManagementProvider are incompatible because when I tried to connect:

//' Connect to SMS Provider                  SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();                  WqlConnectionManager connection = new WqlConnectionManager(namedValues);                  connection.Connect(serverName);  

I received following error:

System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified.'  

My work around so far is just using WMI:

public static List<CollectionSccmCM> GetCMDeviceCollections(string hostname, string siteCode, string siteServer= null){            List<CollectionSccmCM> collectionList = new List<CollectionSccmCM>();            try{              string Namespace;                if(string.IsNullOrEmpty(siteServer)){                  Namespace = @"Root\SMS\Site_" + siteCode;              } else {                  Namespace = (@"\\" + siteServer + @"\root\SMS\Site_" + siteCode);              }                            ManagementScope scope = new ManagementScope(Namespace);                scope.Connect();                ObjectQuery query = new ObjectQuery(String.Format("SELECT SMS_Collection.Name, SMS_Collection.CollectionID, SMS_Collection.CollectionType FROM SMS_FullCollectionMembership, SMS_Collection where name = '{0}' and SMS_FullCollectionMembership.CollectionID = SMS_Collection.CollectionID", hostname));                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);                ManagementObjectCollection queryCollection = searcher.Get();                if (queryCollection != null)              {                  foreach (ManagementObject obj in queryCollection)                  {                      CollectionSccmCM coll = new CollectionSccmCM()                          {                              Name = obj["Name"].ToString(),                              CollectionID = obj["CollectionID"].ToString()                          };                          collectionList.Add(coll);                  }              }          }          catch (ManagementException ex)          {              if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)){                  EventService.WriteEventLog(String.Format("Unathorized access exception thrown: {0}", ex.Message), EventLogEntryType.Error);              }          }          catch (Exception ex)          {              if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)){                  EventService.WriteEventLog(String.Format("Unhandled expection thrown: {0}", ex.Message), EventLogEntryType.Error);              }          }            return collectionList;        }  

Anyways, someone experienced a similar problem when using these dlls'? or is it the best way just to use ManagementObjectSearcher ?

Thanks

Plotly performance when updating many charts

Posted: 05 May 2021 08:16 AM PDT

I'm trying to build a real-time dashboard utilising Python/Flask and Plotly JS. I've set up a web socket (SocketIO) to pump data to plotly and am updating the plot data based on this. What I'd like to achieve is real-time plotting at >5 Hz (can sort of bin the point into batches every 200 ms).

The problem is that it currently seems to completely cripple my browser when I do this with more than ~5 plots. Please see below what I'm trying to achieve.

Plot Dashboard

I have set it up in JS as follows: (9x)

<script>                      Plotly.plot('X_AXIS',                                  [{x:[0],                                    y:[0],                                    type:'scatter'}],                                  {                                      width: document.getElementById("col").offsetWidth,                                      height:0.33 * document.getElementById("DataContent").offsetHeight,                                      plot_bgcolor:"white",                                      paper_bgcolor:("#ecc060"),                                      margin:{l:15,r:15,t:30,b:30},                                      xaxis: {range:[0,100]},                                      yaxis: {range:[-10,10]},                                      title: {text:'X-Axis'}                                  }                                  );                  </script>  

With a function to update the data using updateTraces:

socket.on('UpdateTelemetry',function(Data){          Plotly.extendTraces('X_AXIS',{x:[[Data[0][0]]],y:[[Data[0][1]]]},[0],100);          Plotly.extendTraces('Y_AXIS',{x:[[Data[1][0]]],y:[[Data[1][1]]]},[0],100);          Plotly.extendTraces('Z_AXIS',{x:[[Data[2][0]]],y:[[Data[2][1]]]},[0],100);          Plotly.extendTraces('X_AXIS2',{x:[[Data[0][0]]],y:[[Data[0][1]]]},[0],100);          Plotly.extendTraces('Y_AXIS2',{x:[[Data[1][0]]],y:[[Data[1][1]]]},[0],100);          Plotly.extendTraces('Z_AXIS2',{x:[[Data[2][0]]],y:[[Data[2][1]]]},[0],100);          Plotly.extendTraces('X_AXIS3',{x:[[Data[0][0]]],y:[[Data[0][1]]]},[0],100);          Plotly.extendTraces('Y_AXIS3',{x:[[Data[1][0]]],y:[[Data[1][1]]]},[0],100);          Plotly.extendTraces('Z_AXIS3',{x:[[Data[2][0]]],y:[[Data[2][1]]]},[0],100);          });  

I have tried going to scattergl, but honestly performance seems worse than just scatter. It seems like plotly is just hogging all the CPU time the browser gets for JS code, meaning the rest of the page becomes almost completely unresponsive. (can't even open dropdown menus anymore)

Is there any more performant way of doing this?

jquery form not working as expected. ajaxForm is not a function

Posted: 05 May 2021 08:17 AM PDT

I am trying to use jquery form but it sais in the concole ajaxForm is not a function. The jquery.form.js is properly included and the code is in a document ready function...

This is the script:

$("#apply-form").ajaxForm({                    beforeSend: function()                  {                      $("#progress").show();                      //clear everything                      $("#bar").width('0%');                      $("#message").html("");                      $("#percent").html("0%");                  },                  uploadProgress: function(event, position, total, percentComplete)                  {                      $("#bar").width(percentComplete+'%');                      $("#percent").html(percentComplete+'%');                    },                  success: function()                  {                      $("#bar").width('100%');                      $("#percent").html('100%');                    },                  complete: function(response)                  {                      $("#message").html("<font color='green'>"+response.responseText+"</font>");                  },                  error: function()                  {                      $("#message").html("<font color='red'> ERROR: unable to upload files</font>");                    }              });  

And here is the HTML form

<form id="apply-form" enctype="multipart/form-data" method="post" action="">          <table>                  <tr><td>CV:</td>                      <td>                          <input type="file" name="cover">                      </td>                  </tr>                  <tr><td>Cover Letter:</td>                      <td>                          <input type="file" name="curriculum">                      </td>                  </tr>                  <tr>                      <td colspan="2">                          <div id="progress">                              <div id="bar"></div>                              <div id="percent">0%</div >                          </div>                      </td>                  </tr>                  <tr>                      <td colspan="2">                          <div id="message"></div>                      </td>                  </tr>              </table>          </form>  

i am making the site in codeigniter and i have a header template that is included o every page. and in the head section i am including all my scripts in this order:

<script src="/jobs/public/js/jquery.js"></script>  <script src="/jobs/public/js/jquery.form.js"></script>  <script src="/jobs/public/js/javascript.js"></script>  <link href="/jobs/public/js/jquery-ui-1.10.3.custom/css/custom-theme/jquery-ui-1.10.3.custom.css" rel="stylesheet">  <script src="/jobs/public/js/jquery-ui-1.10.3.custom/js/jquery-1.9.1.js"></script>  <script src="/jobs/public/js/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.js"></script>  

I am also using jQuery UI. Could that be the problem?

No comments:

Post a Comment