Sunday, July 3, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Gitlab generate Not found URL for user and repository

Posted: 03 Jul 2022 07:49 PM PDT

I installed Gitlab on my own Server(CentOS7) and I create one user. everything seems okay but when I clicked on the user URL I see this message:

enter image description here

I don't know why but it generates http://0de09c2e3bc1/Parisa_hr randomly. means 0de09c2e3bc1

on the other hand, when I want to clone my repo I have problems too. the URL that it generates is git@0de09c2e3bc1:groupname/projectname.git and http://0de09c2e3bc1/groupname/projectname.git

I got this error as I want to clone it :

ssh: Could not resolve hostname 0de09c2e3bc1: Temporary failure in name resolution fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

I don't know which things make it create 0de09c2e3bc1 , I think I should have seen my IP address.

StateNotifier's state

Posted: 03 Jul 2022 07:49 PM PDT

I'm a newbie in Riverpod and currently I'm trying to use StateNotifierProvider for my cart screen and I wonder is there any way while incrementing or decrementing cart items I can change the specific quantity variable in CartModel and update state to show changes in quantity in cart screen

How to render expo-av video taking biggest size while preserving aspect ratio inside a flatlist possible?

Posted: 03 Jul 2022 07:49 PM PDT

I am developing an instagram-like app where I needed to render images/videos. I am using flatlist to prevent memory lost, and using expo-av package to render the video.

Here is a screenshot of what I want to achieve: Goal Image

So my goal here is to render videos with dynamic sizes. Expand all videos to fit the width of the screen, while preserving its dynamic aspect ratio, and crop rounded edges,

However, I am struggling to "expand" the renderItem in a flatlist, but it just doesn't render the component at all but I can still hear the video playing.

This is my FlatList:

<FlatList          style={{ width: "100%", height: "100%", backgroundColor: "yellow" }}          data={[0, 1, 2, 3, 4]}          keyExtractor={item => item}          renderItem={renderItem}  />  

And my renderItem callback:

const renderItem = ({ item }) => {      return <Post post={item} />;  }  

Post item code:

export default ({ post }) => {      const videoRef = useRef(null);      const [status, setStatus] = useState({});        return (      <View style={{ width: "100%", height: "100%", backgroundColor: "blue" }}>          <Video          ref={videoRef}          source={{              uri: 'http://commondatastorage.googleapis.com/gtv-videosbucket/sample/VolkswagenGTIReview.mp4',          }}          style={{ width: "100%", height: "100%", backgroundColor: "blue" }}          resizeMode="contain"          autoplay          isLooping          shouldPlay={true}          onPlaybackStatusUpdate={status => setStatus(() => status)}          />      </View>      );  }  

Result (yellow background: flatlist area, post item should appear blue but not showing up): Result Image

How to do cleanup in useEffect React?

Posted: 03 Jul 2022 07:49 PM PDT

Usually I do useEffect cleanups like this:

useEffect(() => {      if (!openModal) {        let controller = new AbortController();        const getEvents = async () => {          try {            const response = await fetch(`/api/groups/`, {              signal: controller.signal,            });            const jsonData = await response.json();            setGroupEvents(jsonData);            controller = null;          } catch (err) {            console.error(err.message);          }        };        getEvents();        return () => controller?.abort();      }    }, [openModal]);  

But I don't know how to do in this situation:

I have useEffect in Events.js file that get events from function and function in helpers.js file that create events on given dates except holidays (holiday dates fetch from database).

Events.js

useEffect(() => {      if (groupEvents.length > 0) {        const getGroupEvents = async () => {          const passed = await passEvents(groupEvents); // function in helpers.js (return array of events)          if (passed) {             setEvents(passed.concat(userEvents));          } else {            setEvents(userEvents);          }        };        getGroupEvents();      }    }, [groupEvents, userEvents]);  

helpers.js

const passEvents = async (e) => {    try {      const response = await fetch(`/api/misc/holidays`, {        credentials: 'same-origin',      });      const jsonData = await response.json();      const holidays = jsonData.map((x) => x.date.split('T')[0]); // holiday dates      return getEvents(e, holidays); // create events    } catch (err) {      console.error(err.message);    }  };  

websocket messages appears at once rather than individual messages

Posted: 03 Jul 2022 07:48 PM PDT

I want my backend send progress message to UI via websocket. My problem is all messages,which produced by calling

automate_algorithm()

function appear together at once at the end of process, instead of appear one by one. Is there any wrong with my code.

This class create a dictionary which key is project id, and value is the opened websocket

class ConnectionManager:      def __init__(              self      ):          self.connections: dict[str, WebSocket] = {}        async def connect(              self,              id: str,              websocket: WebSocket      ):          """To add new open socket to memory storage            Args:              id:(str)the          """          await websocket.accept()          self.connections[id] = websocket            async def disconnect(self, id: str):          if id in self.connections:              await self.connections[id].close(code=100,reason=None)              del self.connections[id]        async def send_response(              self,              id: str,              data: str,              status:str='running'      ):          print(              f"tries to send response for client with id :{id}. Response is {data}")          try:              await self.connections[id].send_json(data=dict(                  timestamp=time.strftime("%H:%M:%S", time.localtime()),                  message=data,                  id=id,                  status=status              )              )              if status=="completed":                  await self.disconnect(id)          except Exception as e:              print(str(e))              self.disconnect(id)          manager = ConnectionManager()#create a context for web socket manager  

This method get user HTTP request, and start process

@router.websocket("/auto_algo/{client_id}")  async def auto_algo(          websocket: WebSocket,          client_id: str,  ):            await manager.connect(client_id, websocket)            # HANDLE FUNCTION*****      await automate_algorithm(idt=client_id)  

This is the main method which produce the messages,that should write in websocket.

async def send_message_to_socket(          client_id: str,          what: str,          status:str='running'  ):      global manager        await manager.send_response(client_id, what,status)        # automate to algorithm ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  async def automate_algorithm(idt,language='en'):      from controllers.dispatcher_controller import send_message_to_socket            await  send_message_to_socket(client_id=idt,what="process starting")#This message appear at start correctly            mds2 = create_mds(idt,mapper=False)      await  send_message_to_socket(client_id=idt,what="main_data_structure 2 created...")#the rest of message appear together at the end of process            sample_data = create_sample_data(idt,mapper=False)      await  send_message_to_socket(client_id=idt,what="sample data created...")            corr = correlation_matrix(idt,mapper=False)      await  send_message_to_socket(client_id=idt,what="correlation created...")            mds3 = accomplish_mds(idt,mapper=False)      await  send_message_to_socket(client_id=idt,what="main_data_structure 3 created...")  

How can I update a csv file through a code which constitutes of creating a folder holding the respective csv file without facing FileExistsError?

Posted: 03 Jul 2022 07:48 PM PDT

I have made a code of creating a folder that shall contain the output of the same code in a csv file. But when i am wish to make amendments to the code so as to modify the output obtained in the csv file, I do not wish to run into FileExistsError. Is there any way I can do that? Sorry if the query is a foolish one, as I am just beginning to learn Python. Here's my code:

path = Path('file\location\DummyFolder')  path.mkdir(parents=True)  fpath = (path / 'example').with_suffix('.csv')  colours = ['red','blue', 'green', 'yellow']  colour_count = 0    with fpath.open(mode='w', newline='') as csvfile:      fieldnames = ['number', 'colour']      thewriter = csv.DictWriter(csvfile, fieldnames=fieldnames)      thewriter.writeheader()      for colour in colours:          colour_count+=1          thewriter.writerow({'number':colour_count, 'colour':colour})    

Why $push query keeps throwing as undefined?

Posted: 03 Jul 2022 07:48 PM PDT

I have a command that when a user used an item called marriage ring it should be removed in the data array, but it always returning as undefined. Is there something I missed? Here's my current code:

economy.findOne({    memberID: i.author.id  }, {    $pull: {      inventory: {Name: "marriage ring"}    }  }, async(err, data) => {    if (data) {      data.spouseStatus = true      data.spouse = s.author.username      data.save();    } else {      await message.channel.send("Something went wrong.")    }  })  

And these is the array im having on my data

inventory: {   0: {    Name: "apple",    Value: "5"   },   1: {    Name: "marriage ring",    Value: "1"   }  }  

Even I do

{$pull: {inventory: [{Name: "marriage ring"}] } }  

still returning as undefined

GA4 tracks that the value of purchase revenue is less than the event value

Posted: 03 Jul 2022 07:48 PM PDT

GA4 tracks that the value of the purchase revenue is less than the event value

Some orders tracked on GA4 have a purchase revenue value less than the event value I re-ordered these faulty orders the other day and it didn't go wrong I can't find the reason

enter image description here

How to include this kind of html reference tag for intraweb 15 [delphi 11]

Posted: 03 Jul 2022 07:47 PM PDT

I am using a sidebar using HTMLTemplateProcessor

    <nav id="sidebar">        <h1><a href="index.html" class="logo">Side</a></h1>        <ul class="list-unstyled components mb-5">          <li class="active">            <a href="#"><span class="fa fa-home"></span> Home</a>          </li>          <li>            <span class="fa fa-user"></span>            {%IWFrameRegion_FRAME_Menu.lnkBF_FRAME_Menu%}          </li>          <li>            <a href="#"><span class="fa fa-sticky-note"></span> Reports</a>          </li>          <li>            <a href="#"><span class="fa fa-cogs"></span> Tools</a>          </li>          <li>            <a href="#"><span class="fa fa-paper-plane"></span> Contacts</a>          </li>        </ul>      </nav>  

The {%IWFrameRegion_FRAME_Menu.lnkBF_FRAME_Menu%} is the TIWLink reference part, but how do I put the span class (for the logo of link) correctly like the sidebar template.

Now it look something like this because can't put the span class into the rendered <a> tag for {%IWFrameRegion_FRAME_Menu.lnkBF_FRAME_Menu%}.

enter image description here

Error Deploying Django App on Elastic Beanstalk

Posted: 03 Jul 2022 07:50 PM PDT

I'm trying to deploy my Django app on elastic beanstalk. It is saying that it is deployed, but the health immediately turns red and I see "502 Bad Gateway / Nginx" when I try to go to the site. I know there are other answers to this question on stack overflow, but I am still stuck.

In my logs I see web: ModuleNotFoundError: No module named 'mysite.wsgi'.

In my file repos/mydjangoproject/mysite/.ebextensions/django.config I have

  aws:elasticbeanstalk:application:environment:      DJANGO_SETTINGS_MODULE: "core.settings"      PYTHONPATH: "/var/app/current:$PYTHONPATH"    aws:elasticbeanstalk:container:python:      WSGIPath: mysite.wsgi:application  

And I have a file: repos/mydjangoproject/mysite/mysite/wsgi.py Which contains

import os  from django.core.wsgi import get_wsgi_application  os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')  application = get_wsgi_application()  

I also am seeing these errors

2022/07/04 01:57:50 [error] 3507#3507: *536 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.22.27, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "44.241.154.93"  2022/07/04 01:57:50 [error] 3507#3507: *536 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.22.27, server: , request: "GET /blog/wp-includes/wlwmanifest.xml HTTP/1.1", upstream: "http://127.0.0.1:8000/blog/wp-includes/wlwmanifest.xml", host: "44.241.154.93"  

I have gunicorn installed and in my requirements.txt.

I am using Amazon Linux 2.

Any thoughts on what I might be doing wrong would be appreciated!

Error in startup application when using @ServiceActivator in Spring cloud Stream

Posted: 03 Jul 2022 07:47 PM PDT

I put @ServiceActivator to log all messages that gave error to kafka:

@ServiceActivator(inputChannel = "errorChannel")  public void handleErrors(final ErrorMessage in) {      log.error("encountered exception" + em.toString());  }  

and I'm also setting the errorChannelEnabled flag to true:

  cloud:      stream:        function:          definition: consumeProfile        bindings:          #kafka producer          produceProfile-out-0:            binder: kafka            destination: profile            producer:              use-native-encoding: true              error-channel-enabled: true  

the problem is when I'm uploading the application I'm getting this error log:

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'profileListener.handleErrors.serviceActivator': Requested bean is currently in creation: Is there an unresolvable circular reference?      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:355) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:227) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1160) ~[spring-context-5.3.21.jar:5.3.21]      at org.springframework.integration.monitor.IntegrationMBeanExporter.enhanceHandlerMonitor(IntegrationMBeanExporter.java:865) ~[spring-integration-jmx-5.5.13.jar:5.5.13]      at org.springframework.integration.monitor.IntegrationMBeanExporter.registerHandler(IntegrationMBeanExporter.java:695) ~[spring-integration-jmx-5.5.13.jar:5.5.13]      at org.springframework.integration.monitor.IntegrationMBeanExporter.postProcessAbstractEndpoint(IntegrationMBeanExporter.java:340) ~[spring-integration-jmx-5.5.13.jar:5.5.13]      at org.springframework.integration.monitor.IntegrationMBeanExporter.postProcessAfterInitialization(IntegrationMBeanExporter.java:324) ~[spring-integration-jmx-5.5.13.jar:5.5.13]      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:455) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1808) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.postProcessMethodAndRegisterEndpointIfAny(MessagingAnnotationPostProcessor.java:257) ~[spring-integration-core-5.5.13.jar:5.5.13]      at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.lambda$processAnnotationTypeOnMethod$1(MessagingAnnotationPostProcessor.java:215) ~[spring-integration-core-5.5.13.jar:5.5.13]      at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) ~[na:na]      at org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.afterSingletonsInstantiated(MessagingAnnotationPostProcessor.java:136) ~[spring-integration-core-5.5.13.jar:5.5.13]      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:974) ~[spring-beans-5.3.21.jar:5.3.21]      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.21.jar:5.3.21]      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.21.jar:5.3.21]      at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.1.jar:2.7.1]      at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.1.jar:2.7.1]      at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.1.jar:2.7.1]      at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.1.jar:2.7.1]      at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.1.jar:2.7.1]      at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.1.jar:2.7.1]      at com.github.victorsilva95.pocspringcloudstreamkafka.PocSpringCloudStreamKafkaApplication.main(PocSpringCloudStreamKafkaApplication.java:14) ~[main/:na]  

my application does not crash because of this exception, but I wanted your help to understand the reason, thank you

Soring data ascending

Posted: 03 Jul 2022 07:50 PM PDT

morning everyone,

I want to sort data from 3 tables but based on the total value that has been calculated automatically. this is my code

 $query = mysqli_query($konek,"select * from klasifikasi join siswa on siswa.id_siswa=klasifikasi.id_siswa join prodi on prodi.id_prodi=siswa.id_prodi where klasifikasi.id_klasifikasi ORDER BY klasifikasi.raport_mtk DESC, klasifikasi.raport_bindo DESC");  while ($dataku = mysqli_fetch_array($query)) {  $total = ((($dataku['raport_mtk'])/7) +  (($dataku['raport_bindo'])/7)+  (($dataku['raport_bing'])/7)+  (($dataku['raport_ipa'])/7)+  (($dataku['un_mtk'])/7)+  (($dataku['un_ipa'])/7)+  (($dataku['psikotest'])/7)*0.75)-  ((($dataku['raport_ips'])/4)+  (($dataku['un_bindo'])/4)+  (($dataku['un_bing'])/4)+  (($dataku['npa'])/4)*0.25);  

Later I want to sort the value from the largest based on the $total. I've tried but it doesn't work. please help bro

How to write this code in ViewModel and bind with XAML design page. Xamarin C#

Posted: 03 Jul 2022 07:49 PM PDT

I'm trying to implement this code in ViewModel, and Design part in the XAML page.

Below you can find my code. Now it's working in Code behind C# page. But i'm trying to move this code in ViewModel page and bind with XAML design page. But I don't know how I can do this. Can you help me to do this?

    public partial class CouponPage : ContentPage      {          private CouponViewModel _Model;            public static Frame[] CouponFrame = new Frame[1];          public static string[] CouponName = new string[1];          public static string[] CouponLimit = new string[1];          public static string[] CouponBarcode = new string[1];          public static bool[] CouponFreeUse = new bool[1];          public static string[] CouponNote = new string[1];          public static string[] CouponImageAddress = new string[1];            public static ImageSource[] CouponImageSource;            protected IMemberService CouponService => DependencyService.Get<IMemberService>();                    public CouponPage()          {              InitializeComponent();                _Model = new CouponViewModel(Navigation);              BindingContext = _Model;                           GetCoupon();          }            private async void GetCoupon()          {              // Retrieve the coupon from the app              _Model.IsProcessing = true;              var coupon = await CouponService.GetMemberCoupon(GlobalVar.MemberCode);              _Model.IsProcessing = false;                           if (coupon != null)              {                  StackLayout CouponStackLayout;                  Label CouponNameLabel;                  BoxView Line;                  Image CouponImage;                  Label CouponLimitLabel;                    if (coupon.Length >= 1 )                  {                      for (int i = 0; i < coupon.Length; i++)                      {                          // Increase array                          if (i != 0)                          {                              Array.Resize(ref CouponFrame, CouponFrame.Length + 1);                              Array.Resize(ref CouponName, CouponName.Length + 1);                              Array.Resize(ref CouponLimit, CouponLimit.Length + 1);                              Array.Resize(ref CouponBarcode, CouponBarcode.Length + 1);                              Array.Resize(ref CouponFreeUse, CouponFreeUse.Length + 1);                              Array.Resize(ref CouponNote, CouponNote.Length + 1);                              Array.Resize(ref CouponImageAddress, CouponImageAddress.Length + 1);                          }                                                        if (coupon[i].ExpirationDate != DateTime.MaxValue)                          {                                                                                    CouponLimit[i] = AppResources.DueDate + ":" + coupon[i].ExpirationDate.ToString("yyyy/MM/dd") + AppResources.By;                          }                          else                          {                              CouponLimit[i] = " ";                          }                          CouponName[i] = coupon[i].CouponName;                          CouponBarcode[i] = coupon[i].Barcode;                                                CouponFreeUse[i] = coupon[i].FreeUse;                          CouponNote[i] = coupon[i].Note;                            // Screen Display Creation                          CouponStackLayout = new StackLayout                          {                              HorizontalOptions = LayoutOptions.FillAndExpand,                              Margin = new Thickness(5, 5, 5, 0)                          };                          CouponFrame[i] = new Frame                          {                              Content = CouponStackLayout,                              HorizontalOptions = LayoutOptions.FillAndExpand,                              Margin = new Thickness(20, 10),                              Padding = new Thickness(20, 10),                              BorderColor = _Model.MainColor,                              BackgroundColor = Color.White,                              CornerRadius = 10,                              HaZZhadow = true                          };                          detail.Children.Add(CouponFrame[i]);                            CouponNameLabel = new Label                          {                              Text = CouponName[i],                              TextColor = _Model.MainColor,                              FontSize = _Model.FontSizeX3Large,                              FontAttributes = FontAttributes.Bold,                              HorizontalOptions = LayoutOptions.Center                          };                          CouponStackLayout.Children.Add(CouponNameLabel);                            Line = new BoxView                          {                              Color = _Model.MainColor,                              HeightRequest = 1,                              HorizontalOptions = LayoutOptions.FillAndExpand                          };                          CouponStackLayout.Children.Add(Line);                            CouponImageAddress[i] = coupon[i].ImageUrl ?? "";                          if (coupon[i].ImageUrl != "")                          {                              CouponImageAddress[i] = GlobalVar.WebServerShortAddress + CouponImageAddress[i];                              CouponImage = new Image                              {                                  Source = ImageSource.FromUri(new Uri(CouponImageAddress[i])),                                  HorizontalOptions = LayoutOptions.FillAndExpand,                                  VerticalOptions = LayoutOptions.StartAndExpand                              };                              CouponStackLayout.Children.Add(CouponImage);                          }                            CouponLimitLabel = new Label                          {                              Text = CouponLimit[i],                              TextColor = Color.Black,                              Margin = new ThickneZZ(0, 10, 0, 0),                              FontSize = _Model.FontSizeXLarge,                              HorizontalOptions = LayoutOptions.Center                          };                          CouponStackLayout.Children.Add(CouponLimitLabel);                            // Operation when pressed                          var tgr = new TapGestureRecognizer();                          tgr.Tapped += (sender, e) => Handle_OnClickedCoupon(sender, e);                          CouponFrame[i].GestureRecognizers.Add(tgr);                      }                  }                  else                  {                      // No coupon                      CouponNameLabel = new Label                      {                          Text = AppResources.CouponNotExists,                          TextColor = Color.Black,                          FontSize = _Model.FontSizeXLarge,                          Margin = new ThickneZZ(20, 5, 20, 0)                                             };                      detail.Children.Add(CouponNameLabel);                                                        }              }              else              {                     // communication error                     Label ErrorLabel = new Label                     {                         Text = "Unable to retrieve coupon",                         FontSize = _Model.FontSizeXLarge,                         TextColor = Color.Red,                         HorizontalOptions = LayoutOptions.CenterAndExpand,                         Margin = new ThickneZZ(0, 5, 0, 0)                     };                      detail.Children.Add(ErrorLabel);                      _Model.CurrentPage = BaseViewModel.PAGE_NONE;                      await DisplayAlert(AppResources.HttpErrorAlertTitle, AppResources.HttpErrorAlertText, AppResources.OK);                                    }                       }                }  }    

Here I'm trying to bind XAML page.

<StackLayout  BindableLayout.ItemsSource="{Binding Coupons}" Spacing="0" HorizontalOptions="FillAndExpand" Margin="5,5,5,0">                                  <Frame HorizontalOptions="FillAndExpand" Margin="20,10" Padding="20,10" BorderColor="Maroon" BackgroundColor="White" CornerRadius="10" HasShadow="True">                                      <StackLayout Orientation="Horizontal">                                          <StackLayout>                                              <Label Text="{Binding CouponName}" FontSize="Large" HorizontalOptions="Center" FontAttributes="Bold"/>                                              <BoxView HeightRequest="1" HorizontalOptions="FillAndExpand"/>                                              <Image Source="{Binding ImageUrl}" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand"></Image>                                              <Label Text="{Binding CouponLimit}" Margin="0,10,0,0" FontSize="Large" HorizontalOptions="Center" />                                          </StackLayout>                                      </StackLayout>                                      <Frame.GestureRecognizers>                                          <TapGestureRecognizer NumberOfTapsRequired="1" Command="{Binding tgr}" />                                      </Frame.GestureRecognizers>                                  </Frame>                              </StackLayout>    

Any help is appreciated. Thanks!

Autocomplete of input field with a lot of data

Posted: 03 Jul 2022 07:49 PM PDT

I am trying to create a search field, searching for cities in Denmark. I have an API with JSON to get all the cities, but there is a lot of data and therefore it takes time to load the page.

Is there any way that I can load data from this API after the user has typed in the field?

Here is a snippet of the Javascript/PHP I am using to get the data. Here you can see the link of all the cities too.

var cities = [];    <?    $citiesData = file_get_contents('https://api.dataforsyningen.dk/steder?hovedtype=Bebyggelse&undertype=by');    $cityJson = json_decode($citiesData, true);      for ($x = 0; $x <= count($cityJson) - 1; $x++) {  ?>      cities.push("<? echo $cityJson[$x]["primærtnavn"]; ?>");  <?    }  ?>  

After this I am using the autocomplete Javascript function from W3Schools, which can be found here: https://www.w3schools.com/howto/howto_js_autocomplete.asp

How can I make this so it does not take long for the page to load?

Login Page with ASP.NET Core (MVC)

Posted: 03 Jul 2022 07:47 PM PDT

I am trying to learn asp.net core (MVC) , and I am posting this question after trying to implement everything that I could understand from Google.

I want to create a simple login Page. I have earlier worked on asp.net framework with ado.net and webforms using edmx, but I learned that edmx and webforms are now outdated. So, I wanted to learn the new method.

These are the tables and stored procedure I created

create table users(userId int identity(1,1) primary key, username varchar(20), password varchar(20))    create proc login(  @username varchar(20),  @password varchar(20)  )  as  begin  if exists(select * from users where username = @username and password=@password)  select 'Success' as UserExists  else  select 'Failed' as UserExists  end    

Then I created the Model Class -

 public class Login      {             [Key]          public int userId { get; set; }            [Required(ErrorMessage = "Username is requried!")]          public string username { get; set; }            [Required(ErrorMessage = "Password is requried!")]          public string password { get; set; }      }  

Then I added model in my project. I referred this link

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-6.0&tabs=visual-studio

Then referencing the following link, I added my connection string details in appstring.json file -

link https://www.c-sharpcorner.com/article/crud-operations-in-asp-net-core-mvc-net-5-0/

 "WebsiteContext": "Server=DELL\\SQLEXPRESS01;Database=website;Trusted_Connection=True;MultipleActiveResultSets=true"  

This is startup.cs

   public void ConfigureServices(IServiceCollection services)          {              services.AddControllersWithViews();                services.AddDbContext<WebsiteContext>(options =>                      options.UseSqlServer(Configuration.GetConnectionString("WebsiteContext")));                          }  

I created the login.cshtml with basic asp.net.

  @{      ViewData["Title"] = "Login";  }    <h1>Login</h1>  <div>      <table>          <tr>              <td>                  <asp:TextBox ID="username"></asp:TextBox>              </td>              <td>                  <asp:TextBox ID="password"></asp:TextBox>              </td>          </tr>          <tr>              <td>                  <asp:Button ID="submit"></asp:Button>              </td>          </tr>      </table>  </div>    

Now, I am confused as how should I proceed next. Here is my LoginController class. This was generated automatically after scaffolding.

 public class LoginController : Controller      {          private readonly WebsiteContext _context;            public LoginController(WebsiteContext context)          {              _context = context;          }            // GET: Login          public async Task<IActionResult> Index()          {              return View(await _context.Login.ToListAsync());          }            // GET: Login/Details/5          public async Task<IActionResult> Details(int? id)          {              if (id == null)              {                  return NotFound();              }                var login = await _context.Login                  .FirstOrDefaultAsync(m => m.userId == id);              if (login == null)              {                  return NotFound();              }                return View(login);          }            // GET: Login/Create          public IActionResult Create()          {              return View();          }            // POST: Login/Create          // To protect from overposting attacks, enable the specific properties you want to bind to, for           // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.          [HttpPost]          [ValidateAntiForgeryToken]          public async Task<IActionResult> Create([Bind("userId,username,password")] Login login)          {              if (ModelState.IsValid)              {                  _context.Add(login);                  await _context.SaveChangesAsync();                  return RedirectToAction(nameof(Index));              }              return View(login);          }      }  

I know the process of ado.net but now I am confused how should I proceed with mvc.

Please guide me. Thank you!

ActiveMQ Artemis Shared Storage slave fail to start if master is not started

Posted: 03 Jul 2022 07:49 PM PDT

We have a master/slave setup with the shared storage strategy. We observed that if we start the slave when the master is down, we have the following message:

AMQ221032: Waiting to become backup node  

And the server does not become live.

So it means that the slave requires the master to be up at a given time to become operational. Is this the expected behavior? Is there a way to let the slave become live at startup if the master is down?

How to pass the dataprocs metastore (dpms) in DataprocClusterCreateOperator

Posted: 03 Jul 2022 07:46 PM PDT

I am trying to pass the DPMS config to DataprocClusterCreateOperator but not able to find the proper way to pass this configuration. Can anyone help me how to pass the dpms config in DataprocClusterCreateOperator?

Trying to insert sass stylesheets inside Shadow Root with LitElement

Posted: 03 Jul 2022 07:48 PM PDT

developers:

This is my first question after so many years as a simple viewer in Stackoverflow.

My trouble is: I'm trying to use scss stylesheets with LitElement components, encapsulated into a React project. The webpack config of my repository injects stylesheets in the header of the page (and it's something I can't change due to other projects in my repository), but I find that my ShadowRoot doesn't get the styles from the header (I tried to acceed to :host, :root, shadowroot... from the .scss file, but it never worked), and I realized that, initially, I can select the target I want to append to my stylesheet configuring the style-loader module in my webpack config and sending the target I want to include the stylesheet in with the .use() function, but I guess it only works with HTMLElement component, not with mine witch extends from LitElement.

This is my config of module.exports in webpack.config.js:

            rules: [                  {                      test: /\.css|\.s(c|a)ss$/,                      include: [                          path.resolve(__dirname, 'src/componentsLit/'),                          path.resolve(__dirname, 'src/pagesLit/'),                          path.resolve(__dirname, 'src/widgetsLit/'),                      ],                      use: [                          'lit-scss-loader',                          'extract-loader',                          {                              loader: 'style-loader',                              options: {                                  //injectType: 'lazyStyleTag',                                  insert: function insertIntoTarget(element, options) {                                      var parent = options.target || document.head;                                      parent.appendChild(element);                                  },                              },                          },                          'css-loader',                          'sass-loader',                      ],                  },              ],          },  

This is what I'm trying to render in my component:

import { html, css, LitElement } from 'lit-element';  import { nothing } from 'lit-html';  import myStyles from './myStyles.scss';    export class myCustomElement extends LitElement {      static get is() {          return 'my-customelement';      }        static get properties() {          return {              [...]          };      }        static get styles() {          /*var style = css([require('./myStyles.scss')]);          return [style];*/      }        constructor() {          super();            [...]      }        firstUpdated() {          myStyles.use({ target: this.shadowRoot });      }        [...]    }  customElements.define(myCustomElement.is, myCustomElement);    

I get that the function use() is not avaliable for LitElement, and as I see in the style-loader doc, is the way to select where I want to place the <style></style> markdown.

Any alternative to insert stylesheets from scss with this configuration? Thanks.

VLAN Priority, DEI and ID are missing in UDP Package

Posted: 03 Jul 2022 07:47 PM PDT

I am building an ethernet simulation project to send and receive UDP packages to an external device (let's call it A).

I am supposed to simulate multiple devices, some of them send UDP packages (let's call them B) and some receive UDP packages (let's call them C), B and C are on two different VLANs with two different IDs.

I used an external ETH/Adapter for B and C, which both are connected to a switch alongside the main device A (which can see both the VLANs). then I configured the two eth/adp on windows by setting the "VLAN and Priority" to Enabled and Set VLAN ID with the correct ID for each B and C, finally, I set static IPs for each one of them.

I then used QT to create the simulation project, The Receiving parts are perfect Device A is transmitting UDP packages to Multicast and I join with VLAN C on the Multicast and start reading these frames.

The problem is with sending, I am able to send the frames correctly however the 4 bytes that define the Priority, DEI, and ID are missing (which means device A is not receiving and dumping these frames)

You can see in the below screenshot, on the right the healthy packages that are accepted by device A and on the left the simulated frames that are not accepted

Comaprison between accepted and unaccepted packages

Here is the Code I use to bind and Join Multicast

    socket_1 = new QUdpSocket(this);      qDebug() << "Binding UDP Socket ..." ;        bool bind_res = socket_1->bind(QHostAddress("192.168.11.4"), 51011 , QUdpSocket::ShareAddress);      if(!bind_res)      {          qDebug() << "Faild to bind with Error: " +socket_1->errorString() ;          QApplication::quit();      }        bool join_res = socket_1->joinMulticastGroup(interface->GRP_IP,interface->Qinterface);      if(!join_res)      {          qDebug() << "Failed to join with error: "+ socket_1->errorString() ;          QApplication::quit();      }      connect(socket_1, SIGNAL(readyRead()), this, SLOT(handleReadyRead()));      qDebug() << "UDP Socket initialized successfully ..." ;  

and here is the function to send (interface->GRP_IP is the Multicast IP)

void UDPSocket_VLAN11::sendUDP_1(QByteArray data)  {      qint64 res =  socket_1->writeDatagram(data, interface->GRP_IP, 50011);      qDebug() << " --- Sending UDP Packet ---";      qDebug() << "Sending to: " << interface->GRP_IP;      qDebug() << "Sending port: " << port;      qDebug() << "Sending Size: " << data.size();      qDebug() << "Sending: " << data.toHex().toLower();      qDebug() << "Sending Result: " << res;  }  

Can someone please point how to set these values weather it's in the configuration of the VLAN or the socket in QT ?

CircleCI message "error: exec plugin: invalid apiVersion "client.authentication.k8s.io/v1alpha1"

Posted: 03 Jul 2022 07:48 PM PDT

I am facing an error while deploying deployment in CircleCI. Please find the configuration file below.

When running the kubectl CLI, we got an error between kubectl and the EKS tool of the aws-cli.

version: 2.1  orbs:    aws-ecr: circleci/aws-ecr@6.3.0    docker: circleci/docker@0.5.18    rollbar: rollbar/deploy@1.0.1    kubernetes: circleci/kubernetes@1.3.0    deploy:      version: 2.1      orbs:        aws-eks: circleci/aws-eks@1.0.0        kubernetes: circleci/kubernetes@1.3.0      executors:        default:          description: |            The version of the circleci/buildpack-deps Docker container to use            when running commands.          parameters:            buildpack-tag:              type: string              default: buster          docker:            - image: circleci/buildpack-deps:<<parameters.buildpack-tag>>      description: |        A collection of tools to deploy changes to AWS EKS in a declarative        manner where all changes to templates are checked into version control        before applying them to an EKS cluster.      commands:        setup:          description: |            Install the gettext-base package into the executor to be able to run            envsubst for replacing values in template files.            This command is a prerequisite for all other commands and should not            have to be run manually.          parameters:            cluster-name:              default: ''              description: Name of the EKS Cluster.              type: string            aws-region:              default: 'eu-central-1'              description: Region where the EKS Cluster is located.              type: string            git-user-email:              default: "deploy@mail.com"              description: Email of the git user to use for making commits              type: string            git-user-name:              default: "CircleCI Deploy Orb"              description:  Name of the git user to use for making commits              type: string          steps:            - run:                name: install gettext-base                command: |                  if which envsubst > /dev/null; then                    echo "envsubst is already installed"                    exit 0                  fi                  sudo apt-get update                  sudo apt-get install -y gettext-base            - run:                name: Setup GitHub access                command: |                  mkdir -p ~/.ssh                  echo 'github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==' >> ~/.ssh/known_hosts                  git config --global user.email "<< parameters.git-user-email >>"                  git config --global user.name "<< parameters.git-user-name >>"            - aws-eks/update-kubeconfig-with-authenticator:                aws-region: << parameters.aws-region >>                cluster-name: << parameters.cluster-name >>                install-kubectl: true                authenticator-release-tag: v0.5.1        update-image:          description: |            Generates template files with the specified version tag for the image            to be updated and subsequently applies that template after checking it            back into version control.          parameters:            cluster-name:              default: ''              description: Name of the EKS Cluster.              type: string            aws-region:              default: 'eu-central-1'              description: Region where the EKS Cluster is located.              type: string            image-tag:              default: ''              description: |                The tag of the image, defaults to the  value of `CIRCLE_SHA1`                if not provided.              type: string            replicas:              default: 3              description: |                The replica count for the deployment.              type: integer            environment:              default: 'production'              description: |                The environment/stage where the template will be applied. Defaults                to `production`.              type: string            template-file-path:              default: ''              description: |                The path to the source template which contains the placeholders                for the image-tag.              type: string            resource-name:              default: ''              description: |                Resource name in the format TYPE/NAME e.g. deployment/nginx.              type: string            template-repository:              default: ''              description: |                The fullpath to the repository where templates reside. Write                access is required to commit generated templates.              type: string            template-folder:              default: 'templates'              description: |                The name of the folder where the template-repository is cloned to.              type: string            placeholder-name:              default: IMAGE_TAG              description: |                The name of the placeholder environment variable that is to be                substituted with the image-tag parameter.              type: string            cluster-namespace:              default: sayway              description: |                Namespace within the EKS Cluster.              type: string          steps:            - setup:                aws-region: << parameters.aws-region >>                cluster-name: << parameters.cluster-name >>                git-user-email: dev@sayway.com                git-user-name: deploy            - run:                name: pull template repository                command: |                  [ "$(ls -A << parameters.template-folder >>)" ] && \                    cd << parameters.template-folder >> && git pull --force && cd ..                  [ "$(ls -A << parameters.template-folder >>)" ] || \                    git clone << parameters.template-repository >> << parameters.template-folder >>            - run:                name: generate and commit template files                command: |                  cd << parameters.template-folder >>                  IMAGE_TAG="<< parameters.image-tag >>"                  ./bin/generate.sh --file << parameters.template-file-path >> \                    --stage << parameters.environment >> \                    --commit-message "Update << parameters.template-file-path >> for << parameters.environment >> with tag ${IMAGE_TAG:-$CIRCLE_SHA1}" \                    << parameters.placeholder-name >>="${IMAGE_TAG:-$CIRCLE_SHA1}" \                    REPLICAS=<< parameters.replicas >>            - kubernetes/create-or-update-resource:                get-rollout-status: true                namespace: << parameters.cluster-namespace >>                resource-file-path: << parameters.template-folder >>/<< parameters.environment >>/<< parameters.template-file-path >>                resource-name: << parameters.resource-name >>  jobs:    test:      working_directory: ~/say-way/core      parallelism: 1      shell: /bin/bash --login      environment:        CIRCLE_ARTIFACTS: /tmp/circleci-artifacts        CIRCLE_TEST_REPORTS: /tmp/circleci-test-results        KONFIG_CITUS__HOST: localhost        KONFIG_CITUS__USER: postgres        KONFIG_CITUS__DATABASE: sayway_test        KONFIG_CITUS__PASSWORD: ""        KONFIG_SPEC_REPORTER: true      docker:      - image: 567567013174.dkr.ecr.eu-central-1.amazonaws.com/core-ci:test-latest        aws_auth:          aws_access_key_id: $AWS_ACCESS_KEY_ID_STAGING          aws_secret_access_key: $AWS_SECRET_ACCESS_KEY_STAGING      - image: circleci/redis      - image: rabbitmq:3.7.7      - image: circleci/mongo:4.2      - image: circleci/postgres:10.5-alpine      steps:      - checkout      - run: mkdir -p $CIRCLE_ARTIFACTS $CIRCLE_TEST_REPORTS      # This is based on your 1.0 configuration file or project settings      - restore_cache:          keys:          - v1-dep-{{ checksum "Gemfile.lock" }}-          # any recent Gemfile.lock          - v1-dep-      - run:          name: install correct bundler version          command: |            export BUNDLER_VERSION="$(grep -A1 'BUNDLED WITH' Gemfile.lock | tail -n1 | tr -d ' ')"            echo "export BUNDLER_VERSION=$BUNDLER_VERSION" >> $BASH_ENV            gem install bundler --version $BUNDLER_VERSION      - run: 'bundle check --path=vendor/bundle || bundle install --path=vendor/bundle --jobs=4 --retry=3'      - run:          name: copy test.yml.sample to test.yml          command: cp config/test.yml.sample config/test.yml      - run:          name: Precompile and clean assets          command: bundle exec rake assets:precompile assets:clean      # Save dependency cache      - save_cache:          key: v1-dep-{{ checksum "Gemfile.lock" }}-{{ epoch }}          paths:          - vendor/bundle          - public/assets      - run:          name: Audit bundle for known security vulnerabilities          command: bundle exec bundle-audit check --update      - run:          name: Setup Database          command: bundle exec ruby ~/sayway/setup_test_db.rb      - run:          name: Migrate Database          command: bundle exec rake db:citus:migrate      - run:          name: Run tests          command: bundle exec rails test -f      # By default, running "rails test" won't run system tests.      - run:          name: Run system tests          command: bundle exec rails test:system      # Save test results      - store_test_results:          path: /tmp/circleci-test-results      # Save artifacts      - store_artifacts:          path: /tmp/circleci-artifacts      - store_artifacts:          path: /tmp/circleci-test-results    build-and-push-image:      working_directory: ~/say-way/      parallelism: 1      shell: /bin/bash --login      executor: aws-ecr/default      steps:        - checkout        - run:            name: Pull latest core images for cache            command: |              $(aws ecr get-login --no-include-email --region $AWS_REGION)              docker pull "${AWS_ECR_ACCOUNT_URL}/core:latest"        - docker/build:            image: core            registry: "${AWS_ECR_ACCOUNT_URL}"            tag: "latest,${CIRCLE_SHA1}"            cache_from: "${AWS_ECR_ACCOUNT_URL}/core:latest"        - aws-ecr/push-image:            repo: core            tag: "latest,${CIRCLE_SHA1}"    deploy-production:      working_directory: ~/say-way/      parallelism: 1      shell: /bin/bash --login      executor: deploy/default      steps:        - kubernetes/install-kubectl:            kubectl-version: v1.22.0        - rollbar/notify_deploy_started:            environment: report        - deploy/update-image:            resource-name: deployment/core-web            template-file-path: core-web-pod.yml            cluster-name: report            environment: report            template-repository: git@github.com:say-way/sw-k8s.git            replicas: 3        - deploy/update-image:            resource-name: deployment/core-worker            template-file-path: core-worker-pod.yml            cluster-name: report            environment: report            template-repository: git@github.com:say-way/sw-k8s.git            replicas: 4        - deploy/update-image:            resource-name: deployment/core-worker-batch            template-file-path: core-worker-batch-pod.yml            cluster-name: report            environment: report            template-repository: git@github.com:say-way/sw-k8s.git            replicas: 1        - rollbar/notify_deploy_finished:            deploy_id: "${ROLLBAR_DEPLOY_ID}"            status: succeeded    deploy-demo:      working_directory: ~/say-way/      parallelism: 1      shell: /bin/bash --login      executor: deploy/default      steps:        - kubernetes/install-kubectl:            kubectl-version: v1.22.0        - rollbar/notify_deploy_started:            environment: demo        - deploy/update-image:            resource-name: deployment/core-web            template-file-path: core-web-pod.yml            cluster-name: demo            environment: demo            template-repository: git@github.com:say-way/sw-k8s.git            replicas: 2        - deploy/update-image:            resource-name: deployment/core-worker            template-file-path: core-worker-pod.yml            cluster-name: demo            environment: demo            template-repository: git@github.com:say-way/sw-k8s.git            replicas: 1        - deploy/update-image:            resource-name: deployment/core-worker-batch            template-file-path: core-worker-batch-pod.yml            cluster-name: demo            environment: demo            template-repository: git@github.com:say-way/sw-k8s.git            replicas: 1        - rollbar/notify_deploy_finished:            deploy_id: "${ROLLBAR_DEPLOY_ID}"            status: succeeded  workflows:    version: 2.1    build-n-test:      jobs:        - test:            filters:              branches:                ignore: master    build-approve-deploy:      jobs:        - build-and-push-image:            context: Core            filters:              branches:                only: master        - approve-report-deploy:            type: approval            requires:              - build-and-push-image        - approve-demo-deploy:            type: approval            requires:              - build-and-push-image        - deploy-production:            context: Core            requires:              - approve-report-deploy        - deploy-demo:            context: Core            requires:              - approve-demo-deploy  

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

Posted: 03 Jul 2022 07:47 PM PDT

Since a few days I got an issue with Mac OS High Sierra 10.13.3 : When I run a git clone like git clone github.com/xxx.git failed it print:

LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

Same issue with npm i command Even when I try to install brew like so:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"  

I also tried the alternative setup: same.

NodeJS concatenate all files in a directory

Posted: 03 Jul 2022 07:47 PM PDT

Is there a faster or more succinct way to concatenate all of the files located in a directory using NodeJS?

In bash I could do something like this:

for file in $1  do    cat "$file"    echo  done > $2;  

Here is what I'm doing now:

var fs = require('fs');  var Promise = require('bluebird');    module.exports = function(directory, destination) {      return new Promise((resolve, reject) => {          fs.readdir(directory, (err, files) => {              if (err) {                  return reject(err);              }                (function next() {                  var file = files.shift();                  if (!file) {                      return resolve();                  }                    fs.readFile(directory + '/' + file, (err, content) => {                      if (err) {                          return reject(err);                      }                        fs.appendFile(destination, '\n' + content, (err) => {                          if (err) {                              return reject(err);                          }                            return next();                      });                  });              })();          });      });  };  

Node JS req.body undefined

Posted: 03 Jul 2022 07:49 PM PDT

I've looked through quite a bit of other posts and I'm very lost with this.

I can run a console.log(req) and get the following output

ServerResponse {    ...    req:      IncomingMessage {      ...       url: '/my-endpoint',       method: 'POST',       statusCode: null,       statusMessage: null,       ...       body: { foo: 'bar' },       _body: true,       ...       route: Route { path: '/my-endpoint', stack: [Object], methods: [Object] } },    ...  

Looks solid, so I would expect to do console.log(req.body) and get { foo: 'bar' } back in the console...but nope, getting undefined

After research, I found that it may be something with my app.js file and specifically with a body-parser, however, I have all of that already

var express = require('express');  var path = require('path');  var favicon = require('serve-favicon');  var logger = require('morgan');  var cookieParser = require('cookie-parser');  var bodyParser = require('body-parser');  var http = require('http');    var app = express();    // view engine setup  app.set('views', path.join(__dirname, 'views'));  app.set('view engine', 'pug');    app.use(logger('dev'));  app.use(bodyParser.json());  app.use(bodyParser.urlencoded({ extended: false }));  app.use(cookieParser());  app.use(express.static(path.join(__dirname, 'public')));    //Home Page Rendering  var index = require('./routes/index');  app.use('/', index);    // All other routes are kept in the `routes` module  require('./routes')(app);    module.exports = app;  

routes.js

module.exports = function routing(app) {    var apiClient = require('./services/apiClient');      app.post('/get-device-info', function(err, req, res){      console.log("/get-device-info routes");      apiClient(req, res);    });  };  

apiClient.js

module.exports = function callApi(req, res){    console.log(req);    console.log(req.body)  };  

index.js

var express = require('express');  var router = express.Router();    /* GET home page. */  router.get('/', function(req, res, next) {    res.render('index', { title: 'Express' });  });    module.exports = router;  

Here's what I've tried

app.use(express.bodyParser());

Ensuring that the incoming request is explicitly declaring application/json

Declaring body parser.json in other ways

Adding a config function

how to write array obj into file with nodejs

Posted: 03 Jul 2022 07:50 PM PDT

I'm trying with this code below, I can write file on server and the file has content but, when I download the file, it's blank.

var file = fs.createWriteStream('./tmp/text.txt');    file.on('error', function(err) { console.log(err) });    rows.forEach(function(v) {    file.write(v + "\r\n");      productExport.DeleteProduct(v.ProductId, function(err){      if(err) throw err;    });  });    file.end();    var file = "./tmp/text.txt";  res.download(file); // Set disposition and send it.  

How can I download the file with all the content?

How can I add a custom value to my Node.js HTTP request for Express to consume

Posted: 03 Jul 2022 07:49 PM PDT

I have an Express server listening on a Unix Domain Socket. I'm making an http request like so:

const requestOptions = {socketPath, method, path, headers, _custom: {foo: () => 'bar'}}  http.request(requestOptions, responseCb)  

And want to use _custom in my Express route handlers

app.get('/', (req, res) => {      console.log(req._custom)  })  

Is this possible?

EDIT: _custom is an object with functions.

EDIT: The answer I marked as correct is the best solution I could find, however it does not allow sending of objects (which is what I really want).

node.js fs.writeFileSync() How to set encoding to big5?

Posted: 03 Jul 2022 07:50 PM PDT

the fs.writeFileSync encode default is UTF 8 I can't set the encode to big5. The documentation does not mention those encoding support. If this function does not support BIG5, what can I do?

var fs = require('fs');  var FilePath='./text.txt';  var Str='this is a test!';  var encode='utf8';  fs.writeFileSync(FilePath, Str, encode);  

When I set encoding(var encode='big5';) BIG5, the server generates an error.

What's the difference between async.waterfall and child_process.execSync?

Posted: 03 Jul 2022 07:48 PM PDT

say if this is linux shell, what i want to do is:

copy file1 tmp  rename tmp file2  

i can do waterfall

function copyFile(cb) {      child_process.exec('cp file1 tmp', function (error, stdout, stderr) {          ......      });  }  async.waterfall([      copyFile,      renameFile  ], function (error) {      if (error) {          //handle readFile error or processFile error here      }  });  

or guess i can do

child_process.execSync('cp file1 tmp");  child_process.execSync('rename tmp file2');  

What's the difference please ? e.g performance ? blocking ? Thanks very much !

S3 Iterate through Bucket/Folders/Files

Posted: 03 Jul 2022 07:48 PM PDT

I am iterating through S3 bucket using s3.listObjects but I am getting this error: { [UnexpectedParameter: Unexpected key 'Key' found in params] Below is the code I am using: exports.handler = function(event, context) {

var bucket = event.Records[0].s3.bucket.name;  var key = event.Records[0].s3.object.key;  var params = {      Bucket: bucket,      Key: key  };    console.log('bucket name ', bucket);  s3.getObject(params, function(err, data) {      if (err) {          console.log(err);        } else {          context.succeed(data.ContentType);      }  });    s3.listObjects(params, function(err, data) {      if (err) return console.log(err);        params = {Bucket: 'bucketName'};    });  };  

Can anyone please suggest what am I doing wrong here? Thanks

Escaping double-quote in `delims` option of `for /F`

Posted: 03 Jul 2022 07:48 PM PDT

I'm having a bit of trouble with a batch script which needs to parse a value out of an config file into a variable.

Suitably anonymised, the relevant line of the file looks like

<?define ProductShortName="Foo" ?>  

I want to set a variable to Foo. The string ProductShortName is unique enough to get the line with findstr, but then I have to extract the value. The correct approach seems to be for /F, but all of the following give errors:

for /F "delims=^" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)  for /F "delims="" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)  for /F "delims=\" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)  for /F 'delims=^" usebackq' %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)  for /F 'delims=" usebackq' %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)  for /F "delims=" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)  

mostly along the lines of

usebackq" %G in (`findstr /L "ProductShortName" "C:\foo\bar\Installer\Branding.wxi"`) was unexpected at this time.  

What's the correct way of escaping it to split the string on "?

Recommended way to embed PDF in HTML?

Posted: 03 Jul 2022 07:49 PM PDT

What is the recommended way to embed PDF in HTML?

  • iFrame?
  • Object?
  • Embed?

What does Adobe say itself about it?

In my case, the PDF is generated on the fly, so it can't be uploaded to a third-party solution prior to flushing it.

No comments:

Post a Comment