Sunday, August 22, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Match Wildcard Pattern and Character String in R

Posted: 22 Aug 2021 08:37 AM PDT

I am trying to count how many times a keyword appears in a string. In the following variable text, I would like to count how many times keyword appears in text. The result should display 3 because AWAY appears twice and WIN appears once in the string.

text<- "AWAYTEAM IS XXX. I THINK THEAWAYTEAM WILL WIN"  keyword<- c("AWAY","WIN")  

Any ideas?

plugins not working after jquery ajax call,

Posted: 22 Aug 2021 08:37 AM PDT

I am using a scrollbar plugin, but the plugin is not working after the success ajx call.

I am using this plugin

https://github.com/gromo/jquery.scrollbar/

now what happens, this is ajax success call

    success: function(data) {                  $("#searchResultsNoShow").hide();                  $("#searchResults").show();                  $('.scrollbar-rail').scrollbar();  }  

the .scrollbar-rails is applied to the element inside the #searchResults > div and that div has other class along with scrollbar-rails but the scrollbar is not applied, it is even happening for the tooltips plugin which is tooltipster

How can I get the data inside a beast::flat_buffer?

Posted: 22 Aug 2021 08:36 AM PDT

I'm connecting to a websocket using the boost/beast libraries and writing the data into a beast::flat_buffer. My issue is that I'm having trouble getting the data from buffer. I have a thread-safe channel object that I can to write to, but I'm not sure how to pull the most recently received message from the buffer.

beast::flat_buffer buffer;  // send through socket  send_socket(     ws, get_subscribe_string(trade_tickers, bar_tickers, quote_tickers));  // read into buffer  while (channel.running) {     ws.read(buffer); // need to write the most recently received message into the channel  }  

I can write to the channel with channel.write(std::string arg). Any ideas on how to pull from the buffer?

Flutter SfCartesianChart Not Showing X . Y Axis

Posted: 22 Aug 2021 08:36 AM PDT

I am trying to show price and date in SfCartesianChart . It shows me blank chart

here is my code ,

enter image description here

enter image description here

Using py2app to create standalone application

Posted: 22 Aug 2021 08:36 AM PDT

I'm trying to create a standalone app to facilitate editing of photos out of this project which provides a GUI as well.

I'm following all the steps described in the project's README.md and I can successfully launch the GUI and edit my photos. After that, when I follow the steps from py2app to create the application, setting the gui.py as main, the application crashes.

Any help would be highly appreciated. I have worked with py2app in the past but not with such complex projects.

How can i make a iOS Phone Recorder app using xcode and swift

Posted: 22 Aug 2021 08:35 AM PDT

I wanna make an app to record phone call's but I'm still junior so any one can help me with article or code to make it .

How do I take input in a 2D char array using C

Posted: 22 Aug 2021 08:35 AM PDT

enter image description here

It doesn't take input properly

enter image description here

How do I make a role in Discord.JS that is a bit higher than other roles on the Role Hierarchy?

Posted: 22 Aug 2021 08:35 AM PDT

Sort of a follow up to my other question but, I am making a slash command that'd make a role with customisable permissions, customisable colours, and a customisable place up in the Role Hierarchy.

I've seen that it isn't possible to make a role that is higher up on the Role Hierarchy if the bot is lower than the role you want to put it above, unless done by a member with MANAGE_ROLES and a high role but, is it actually possible to make the bot do this or not?

Any ideas?

P.S: I have seen bots that, upon invited, request that you put their role at the top of the list. I might make something like that for my bot.

How to use arabert-v2 completely offline?

Posted: 22 Aug 2021 08:36 AM PDT

I want to use the arabert-v2 preprocess offline. but it seems saving model is not enough for arabert preprocess function. What else should I download? any ideas?

The git repository: https://github.com/aub-mind/arabert

Checking if User is Logged in via Express.js and Firestore

Posted: 22 Aug 2021 08:35 AM PDT

I am trying to determine if a user is logged in via Express.js and Firestore. The idea is to have the login/create user form displayed on the url path, '/'. However, if the user is logged in, then the app will redirect the user to the user's dashboard page. This would happen when the user logs in or creates an account.

When I run my code I get the error

TypeError: admin.auth(...).onAuthStateChanged is not a function  

I've realized that the admin package doesn't have onAuthStateChanged as that is something that only exists for the client-side. However, I was wondering how I would implement loading a different view depending on if the user is logged in or not from the server side? Is it even good for me to do this via the server-side or is there a better way for me to approach this?

const admin = require('firebase-admin')  ...    app.get('/', (req, res) => {      admin.auth().onAuthStateChanged(function(user) {            // render user dashboard if user is logged in           if (user) {              getRestaurant('KOBmyfQEu4urNGgBTuiJ').then(data => {                  let ambassadorPromise = getAmbassadorInfo('KOBmyfQEu4urNGgBTuiJ')                  let activityPromise = getActivityFeed('KOBmyfQEu4urNGgBTuiJ')                            var restaurantName = data['name']                  var totalScans = data['total_scans']                            Promise.all([ambassadorPromise, activityPromise]).then(values => {                      ...                                res.render('dashboard', {restaurantName, totalScans, ambassadorList, activityList})                  })              })          }             // render account creation/login page is user is not logged in          else {              res.render('auth')          }        });    })  

How can I change the position of an <hr> element?

Posted: 22 Aug 2021 08:37 AM PDT

I just started in web dev and my first project is a resume website. I am trying to separate the education and experience sections with an hr element. It was working, then I used the float property in CSS to align education descriptions to the left and corresponding dates to the right. Now, the line that came after the education section is in the wrong area. Here is some code:

    <section>          <h2>EDUCATION</h2>          <p id='e1'><strong>M.A. in Teaching</strong>, University of North Carolina</p>          <p id='e2'><strong>June 2021 - May 2022</strong></p>          <p id='e1'><strong>B.A., Human Development & Family Studies major & Education minor</strong>, University of North Carolina</p>      </section>      <hr>      <section>          <h2>EXPERIENCE</h2>  

The id e1 just floats left, and the id e2 floats right. How can I get the hr element to actually appear between the two sections, instead of in the middle of the education section?

NullReferenceException when raycasting in unity

Posted: 22 Aug 2021 08:35 AM PDT

I am trying to use a raycast that writes the name of the object that hits and the position and when shooting the ray it gives a null reference exception. It happens at this line Ray ray = cam.ScreenPointToRay(Input.mousePosition); Here is the code.

using System.Collections;  using System.Collections.Generic;  using UnityEngine;    public class PlayerController : MonoBehaviour  {    Camera cam;    // Start is called before the first frame update  void Start()  {      cam = Camera.current;  }    // Update is called once per frame  void Update()  {      if (Input.GetMouseButtonDown(0))      {          //a ray is created          Ray ray = cam.ScreenPointToRay(Input.mousePosition);          RaycastHit hit;            //it is then casted          if (Physics.Raycast(ray, out hit))          {              Debug.Log("We have hit " + hit.collider.name + " " + hit.point);                        }      }  }  }  

Random sample of points on a region of the surface of a unit sphere

Posted: 22 Aug 2021 08:37 AM PDT

I need to generate a random sample of points distributed on a region of the surface of a sphere. This answer gives an elegant recipe to sample the entire surface of the sphere:

def sample_spherical(npoints, ndim=3):      vec = np.random.randn(ndim, npoints)      vec /= np.linalg.norm(vec, axis=0)      return vec  

(vec returns the (x, y, z) coordinates) which results in:

enter image description here

I need to restrict the sampling to a rectangular region. This region is defined by center values and lengths, for example:

  • center coordinates, eg: (ra_0, dec_0) = (34, 67)
  • side lengths, eg: (ra_l, dec_l) = (2, 1)

where (ra_0, dec_0) are coordinates in the equatorial system, and the lengths are in degrees.

I could use the above function in the following way: call it using a large npoints, transform the returned (x, y, z) values into the equatorial system, reject those outside the defined region, and repeat until the desired number of samples is reached. I feel that there must be a more elegant way of achieving this though.

Private string becomes null when called from another method

Posted: 22 Aug 2021 08:36 AM PDT

I am making a 'Who Wants To Be A Millionaire' game. I am at the later stages, and I am trying to store the user names and scores, but when I call getUser() from another method it comes up as null, I printed the value of getUser() out to make sure it actually storing the values. Here is my code

/*   * To change this license header, choose License Headers in Project Properties.   * To change this template file, choose Tools | Templates   * and open the template in the editor.   */  package assignment1;    import java.util.HashMap;    /**   *   * @author ac918   */  public class User {           // Earnings earning;      String namee;      private String user;      private Integer scores;      boolean repeat = true;      GameMethods getGameMethods = new GameMethods();      HashMap <String, Integer> storeDetails = new HashMap<>();                  public String storeUser()      {          System.out.println("Before we begin what is your name?");          setUser(getGameMethods.getUserInput());          //user = this.getUser();          namee = this.getUser();          System.out.println("This is getUser in storeUser method" + namee);                    if (this.getUser().matches(".*[a-zA-Z]+.*"))          {              System.out.println("Goodluck to you " + this.getUser() + " on your quest to win a million dollars");            }          else           {              while(repeat)              {                  System.out.println("Invalid Input!");                  System.out.println("Name must be letters");                  System.out.println("Please input name to begin");                  setUser(getGameMethods.getUserInput());                                    if (this.getUser().matches(".*[a-zA-Z]+.*"))                  {                      System.out.println("Goodluck to you " + this.getUser() + " on your quest to win a million dollars");                        repeat = false;                  }              }          }                    return this.getUser();      }        /**       * @return the user       */      public String getUser() {          return user;      }        /**       * @param user the user to set       */      public void setUser(String user) {          this.user = user;      }        /**       * @return the score       */      public Integer getScore() {          return scores;      }            public int setUserEarnings (int count)      {          setScore(count);                    switch (count) {              case 0:                  System.out.println("Unfortunately, you have won nothing !!!");                  break;              case 1:                  System.out.println("Congratulations!!! you have won " + Earnings.ONEHUNDRED.getValue());                  break;              case 2:                  System.out.println("Congratulations!!! you have won " + Earnings.TWOHUNDRED.getValue());                  break;              case 3:                  System.out.println("Congratulations!!! you have won " + Earnings.THREEHUNDRED.getValue());                  break;              case 4:                  System.out.println("Congratulations!!! you have won " + Earnings.FIVEHUNDRED.getValue());                  break;              case 5:                  System.out.println("Congratulations!!! you have won " + Earnings.ONETHOUSAND.getValue());                  break;              case 6:                  System.out.println("Congratulations!!! you have won " + Earnings.TWOTHOUSAND.getValue());                  break;              case 7:                  System.out.println("Congratulations!!! you have won " + Earnings.FOURTHOUSAND.getValue());                  break;              case 8:                  System.out.println("Congratulations!!! you have won " + Earnings.EIGHTTHOUSAND.getValue());                  break;              case 9:                  System.out.println("Congratulations!!! you have won " + Earnings.SIXTEENTHOUSAND.getValue());                  break;              case 10:                  System.out.println("Congratulations!!! you have won " + Earnings.THIRTYTWOTHOUSAND.getValue());                  break;              case 11:                  System.out.println("Congratulations!!! you have won " + Earnings.SIXTYFOURTHOUSAND.getValue());                  break;              case 12:                  System.out.println("Congratulations!!! you have won " + Earnings.ONETWENTYFIVETHOUSAND.getValue());                  break;              case 13:                  System.out.println("Congratulations!!! you have won " + Earnings.TWOFIFTYTHOUSAND.getValue());                  break;              case 14:                  System.out.println("Congratulations!!! you have won " + Earnings.FIVEHUNDREDTHOUSAND.getValue());                  break;              case 15:                  System.out.println("Congratulations!!! you have won " + Earnings.ONEMILLION.getValue());                  break;              default:                  System.out.println("Unfortunately, you have won nothing !!!");                  break;          }                      return this.getScore();      }            public void storeUserHighscore(String name, int score)      {          System.out.println("This is getUser in storeUserHighscore method" + namee);          name = this.getUser();          score = this.getScore();                    storeDetails.put(name, score);          System.out.println(storeDetails);      }        /**       * @param score the score to set       */      public void setScore(Integer score) {          this.scores = score;      }  }  

Here is the output

Before we begin what is your name?  John  This is getUser in storeUser method John  Goodluck to you John on your quest to win a million dollars  What does 'NFL' stand for  a) National Food League  b) National Federation League  c) National Football League  d) National Fighting League  a  Unfortunately this answer is wrong  Unfortunately, you have won nothing !!!  Thank you for playing  This is getUser in storeUserHighscore method null  {null=-5}  

Prevent foreach loop from repeating -laravel

Posted: 22 Aug 2021 08:37 AM PDT

I fetch services from our database through code

'services' =>  Service::with('seller.user', 'seller.level', 'subcategory')              ->whereHas('seller', function ($query) {                  return   $query->where('status', 'active');              })              ->Where('tags', 'like', '%' . $this->tag . '%')              ->withAvg('review', 'rating')              ->withCount('review')              ->paginate(20)  

How to ignore duplicate subcategories in the loop

 @foreach ($services as $service)          $$service->subcategory->name          @endforeach  

I get a lot of duplicate subcategories

I need the details of the subcategory not just the name

relations

class Service extends Model  {      public function subcategory()      {          return $this->belongsTo(Subcategory::class);      }  }    class Subcategory extends Model  {      public function service()      {          return $this->hasMany(Service::class);      }  }  

table services

Schema::create('services', function (Blueprint $table) {          $table->id();          $table->foreignId('seller_id')->constrained()->onDelete('cascade')->onUpdate('cascade');          $table->foreignId('subcategory_id')->constrained()->onDelete('cascade')->onUpdate('cascade');          $table->string('title')->nullable();          $table->string('slug')->nullable();          $table->float('price')->nullable();          $table->json('tags')->nullable();      }  

table subcategory

  Schema::create('subcategories', function (Blueprint $table) {          $table->id();          $table->foreignId('category_id')->constrained()->onDelete('cascade')->onUpdate('cascade');          $table->string('name');      }  

Why is my app crashing while emulating on Android Studio (Kotlin Multiplatform) due to Null ImageView?

Posted: 22 Aug 2021 08:35 AM PDT

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

The line this points to is

sleepButton.setOnClickListener() {makeCurrentFragmentS(sleepFragment)}  

where sleepButton is a button within a fragment that someone presses, to open another fragment within a frame layout.

The app has a notification bar which cycles through 3 fragments: home, flight and settings. sleepButton's xml information is on the settings page, while the activity starts on home and this code is contained within MainActivity.kt

Settings (Including sleepButton)

<?xml version="1.0" encoding="utf-8"?>  <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      tools:context=".fragments.SettingsFragment">        <RelativeLayout          android:layout_width="match_parent"          android:layout_height="match_parent">            <ImageButton              android:id="@+id/SleepButton"              android:layout_width="100dp"              android:layout_height="100dp"              android:backgroundTint="#FBFBFB"              android:src="@drawable/ic_sleep"              tools:ignore="SpeakableTextPresentCheck" />       </RelativeLayout>    </FrameLayout>    

In MainActivity, references to sleepButton are as follows:

val sleepButton = findViewById<ImageButton>(R.id.SleepButton)   sleepButton.setOnClickListener{makeCurrentFragmentS(sleepFragment)}  

and the method makeCurrentFragmentS is

 private fun makeCurrentFragmentS(fragment: Fragment) =          supportFragmentManager.beginTransaction().apply {              replace(R.id.SettingsSwapFLFragment, fragment)              commit()          }  

vuepress2: how to get Vue instance so I can use third part vue plugin?

Posted: 22 Aug 2021 08:37 AM PDT

I am trying to use v-wave in VuePress 2 (the VuePress powered by Vue 3)

I followed the docs, try to use the v-wave as a local plugin of the VuePress 2

.vuepress/config.js

const vwave = require('path/to/v-wave.js');    module.exports = {      plugins: [          (options, app) => {              app.use(vwave); // the `app` is a instance of VuePress not Vue              return {name: 'v-wave'};          }      ]  };  

But it didn't work, because the app isn't the Vue instance but the VuePress.

How can I install v-wave to make it work in VuePress 2?

Thanks a lot!

creating objects and naming them at runtime in C++

Posted: 22 Aug 2021 08:35 AM PDT

Actually I'm making a budget calculating app, where there is a class for the items I buy.

class Item  {      string name;      string date;      int amount;      float singlePrice;      float totalPrice;      // constructor      Public Item(string name, int amount, float price)      {                }  };  

But I don't want to hard code every Item, I want to add items in the app and save it to file and calculate how much money I have left.

How to pass multiple id's/values in the gremlin query?

Posted: 22 Aug 2021 08:37 AM PDT

How to pass multiple id's/values in the gremlin query?

g.V().hasNot(T.id, [need_to_pass_multiple_id's]).....  

How to read configuration value in minimal api in ASP.NET .NET 7

Posted: 22 Aug 2021 08:35 AM PDT

I have existing code which i am upgrading from .NET5 to .NET 6

currently I have it like

ApplicationInsightsServiceOptions aiOptions = new ApplicationInsightsServiceOptions();  aiOptions.EnableAdaptiveSampling = false;  aiOptions.InstrumentationKey = Configuration["ApplicationInsights:InstrumentationKey"];  aiOptions.EnableQuickPulseMetricStream = true;  builder.Services.AddApplicationInsightsTelemetry();  

How do I inject the Configuration dependency to be used in minimal ?

  aiOptions.InstrumentationKey = Configuration["ApplicationInsights:InstrumentationKey"];  

Python multiprocessing pyaudio error (Ran out of input)

Posted: 22 Aug 2021 08:36 AM PDT

Code:

  from multiprocessing import Process, Queue, Pipe, freeze_support  from PyQt5.QtCore import pyqtSignal, QThread  import pyaudio  from time import sleep    class Papinhio_Player_Child_Proc(Process):            def __init__(self,to_emitter,process_input_queue):          super().__init__()            self.to_emitter = to_emitter          self.process_input_queue = process_input_queue          #QoS settings          bit_rate = 128*1024 #128 kb/sec          packet_time = 744          packet_size = 4104          new_sample_rate = 44100            format = pyaudio.paInt16          channels = 2            p = pyaudio.PyAudio()            #self.stream = p.open(format=pyaudio.paInt16,channels=channels,output=True,input=True,rate=new_sample_rate,frames_per_buffer=packet_size)          #self.stream.start_stream()                  def run(self):          pass          '''          while(True):              microphone_data = self.stream.read(8*int(4104))#744msec              microphone_slice = AudioSegment(microphone_data, sample_width=2, frame_rate=44100, channels=1)              microphone_slice = AudioSegment.from_mono_audiosegments(microphone_slice, microphone_slice)              self.stream.write(microphone_slice.raw_data)              self.to_emitter.send("Read microphone packet, and write to output.")          '''                class Papinhio_Player_Emitter(QThread):      a_signal = pyqtSignal(str)        def __init__(self, from_process: Pipe):          super().__init__()          self.data_from_process = from_process        def run(self):          while True:              try:                  data = self.data_from_process.recv()                  self.a_signal.emit(data)              except EOFError as e:                  print(e)                    def a_signal_handler(self,string_data):      print(string_data)    if __name__ == '__main__':      freeze_support()      #papinhio_player_child_process = Papinhio_Player_Child_Proc()      #papinhio_player_child_process.start()      papinhio_player_mother_pipe, papinhio_player_child_pipe = Pipe()      papinhio_player_queue = Queue()      papinhio_player_emitter = Papinhio_Player_Emitter(papinhio_player_mother_pipe)      papinhio_player_emitter.start()      papinhio_player_emitter.a_signal.connect(a_signal_handler)                    #papinhio_player_queue.put(stream)      papinhio_player_child_process = Papinhio_Player_Child_Proc(papinhio_player_child_pipe, papinhio_player_queue)      papinhio_player_child_process.start()      while(True):          sleep(1)    

Problem with the up code: None

When the problem is occured? If you uncomment this two lines:

          #self.stream = p.open(format=pyaudio.paInt16,channels=channels,output=True,input=True,rate=new_sample_rate,frames_per_buffer=packet_size)          #self.stream.start_stream()  

What problem happens?

  Traceback (most recent call last):    File "pyaudio_2.py", line 71, in       papinhio_player_child_process.start()    File "C:/msys64/mingw64/lib/python3.8/multiprocessing/process.py", line 121, i  n start      self._popen = self._Popen(self)    File "C:/msys64/mingw64/lib/python3.8/multiprocessing/context.py", line 224, i  n _Popen      return _default_context.get_context().Process._Popen(process_obj)    File "C:/msys64/mingw64/lib/python3.8/multiprocessing/context.py", line 327, i  n _Popen      return Popen(process_obj)    File "C:/msys64/mingw64/lib/python3.8/multiprocessing/popen_spawn_win32.py", l  ine 93, in __init__      reduction.dump(process_obj, to_child)    File "C:/msys64/mingw64/lib/python3.8/multiprocessing/reduction.py", line 60,  in dump      ForkingPickler(file, protocol).dump(obj)  TypeError: cannot pickle '_portaudio.Stream' object  Traceback (most recent call last):    File "", line 1, in     File "C:/msys64/mingw64/lib/python3.8/multiprocessing/spawn.py", line 116, in  spawn_main      exitcode = _main(fd, parent_sentinel)    File "C:/msys64/mingw64/lib/python3.8/multiprocessing/spawn.py", line 126, in  _main      self = reduction.pickle.load(from_parent)  EOFError: Ran out of input    

Question: How can i use a pyaudio stream inside a Process?

Thanks in advance, Chris Pappas

Is there a way to change someDataGridViewCell.Style.BackColor (&etc) at any time?

Posted: 22 Aug 2021 08:35 AM PDT

Documentation says it must be done inside someDataGridView.CellFormatting event, but how can you pass the needed color information into it and force CellFormatting to be triggered when needed ?

someDataGridViewCell.Value is working fine for changing cell text from a System.Windows.Forms.Timer Tick event, but I can't seem to change the coloring at the same time. In my case, all the columns are built and changed dynamically from user menus, and there can be dozens of them.

This is VS2015.

Update: My issue was I used Color.FromName() which returns Empty (transparent) for misspelled names -- very very bad for grid background colors. (I required coloring in data streams I was using so name seemed handy.)

CellFormatting event used in most examples assumes you can derive the color information from the visible cell contents which is too limiting.

Python Tornado WebSocket: not working on second network interface

Posted: 22 Aug 2021 08:35 AM PDT

I have WebSocket server and client app running on the same physical server. The server has two network interfaces and two IP addresses. When I run WebSocket server/client on first IP it works perfect. Bit it dosn't work on second.

Server:

port = 8080  ip1 = '192.168.100.11'  ip2 = '10.110.50.11'  http_server = tornado.httpserver.HTTPServer(app)  http_server.listen(port, ip1)  

With second IP I got the following errors on client:

ERROR:tornado.application:Exception in callback <bound method WebSocketClient.keep_alive of <__main__.WebSocketClient instance at 0x7efc93d912d8>>  Traceback (most recent call last):    File "/opt/python/lib/python2.7/site-packages/tornado/ioloop.py", line 1229, in _run      return self.callback()    File "./client_rt_websocket.py", line 70, in keep_alive      self.ws.write_message("sendHeartbeat 1")    File "/opt/python/lib/python2.7/site-packages/tornado/websocket.py", line 1214, in write_message      return self.protocol.write_message(message, binary=binary)    File "/opt/python/lib/python2.7/site-packages/tornado/websocket.py", line 870, in write_message      raise WebSocketClosedError()  

It seems like socket is closed and client cannot write message.

Unable to find bundled Java version. MacBook Air M1

Posted: 22 Aug 2021 08:37 AM PDT

I was using flutter on MacBook Pro with intel. It was working fine. Now I switch to MacBook Air with M1 chip. I get error Unable to find bundled Java version. How can I fix it pleas? flutter doctor -v
[✓] Flutter (Channel stable, 2.2.3, on macOS 11.2 20D64 darwin-arm, locale en-KW) • Flutter version 2.2.3 at /Users/mac/FlutterDev/flutter • Framework revision f4abaa0735 (5 weeks ago), 2021-07-01 12:46:11 -0700 • Engine revision 241c87ad80 • Dart version 2.13.4

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0) • Android SDK at /Users/mac/Library/Android/sdk • Platform android-31, build-tools 31.0.0 • Java binary at: /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java • Java version Java(TM) SE Runtime Environment (build 1.8.0_301-b09) • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS • Xcode at /Applications/Xcode.app/Contents/Developer • Xcode 12.5.1, Build version 12E507 • CocoaPods version 1.10.2

[✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[!] Android Studio (version 2020.3) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/6351-dart ✗ Unable to find bundled Java version. • Try updating or re-installing Android Studio.

[✓] Connected device (2 available) • macOS (desktop) • macos • darwin-arm64 • macOS 11.2 20D64 darwin-arm • Chrome (web) • chrome • web-javascript • Google Chrome 92.0.4515.131

! Doctor found issues in 1 category.

Powershell number format

Posted: 22 Aug 2021 08:35 AM PDT

I am creating a script converting a csv file in an another format. To do so, i need my numbers to have a fixed format to respect column size : 00000000000000000,00 (20 characters, 2 digits after comma)

I have tried to format the number with -f and the method $value.toString("#################.##") without success

Here is an example Input :

4000000  45817,43  400000  570425,02  15864155,69  1068635,69  128586256,9  8901900,04  29393,88  126858346,88  1190011,46  2358411,95  139594,82  13929,74  11516,85  55742,78  96722,57  21408,86  717,01  54930,49  391,13  2118,64  

Any hints are welcome :)

Thank you !

Use existing session cookie in gin router

Posted: 22 Aug 2021 08:35 AM PDT

I'm building a simple webserver in Go / Gin and I want to use cookies to create a persistent session that keeps a user logged in if they navigate away or navigate across several pages.

Ideally, this is the flow:

  • initialize router
  • check for an existing cookie
    • if a cookie exists, take the cookie token value
    • if a cookie does not exist, create a new random token value
  • initiate session with token value
  • use session with router

Code later on will verify if the cookie token value is expired and/or corresponds to an active user in the database.

The most recent iteration I've tried is:

router := gin.Default();    token_value := func(c *gin.Context) string {        var value string        if cookie, err := c.Request.Cookie("session"); err == nil {        value = cookie.Value      } else {        value = RandToken(64)      }      return value    }      cookie_store := cookie.NewStore([]byte(token_value))    router.Use(sessions.Sessions("session",cookie_store))  

But this fails because token_value is type func(c *gin.Context) string, and not string.

I know there's something I'm missing here, and I'd love some guidance in how to resolve this issue.

Thanks!

dial tcp lookup: no such host issue on docker windows desktop

Posted: 22 Aug 2021 08:35 AM PDT

I've installed docker on my office windows 10 Pro machine. I'm facing dial tcp lookup issue while trying to pull from the registry.

Error response from daemon: Get https://registry-1.docker.io/v2/: dial tcp: lookup registry-1.docker.io on 192.168.65.1:53: no such host

I've tried many possible solutions from online. But I couldn't figure out the issue. Can someone please help me regarding this issue.

Thanks.

How to convert datetime in jmeter using beanshell sampler

Posted: 22 Aug 2021 08:35 AM PDT

I have timestamp for one of my http sampler in following format

Tue Nov 07 10:28:10 PST 2017  

and i need to convert it to in following format

11/07/2017 10:28:10  

i tried different approaches but don't know what am i doing wrong.Can anyone help me on that.Thanks.

Convert a JavaScript string in dot notation into an object reference

Posted: 22 Aug 2021 08:37 AM PDT

Given a JavaScript object,

var obj = { a: { b: '1', c: '2' } }  

and a string

"a.b"  

how can I convert the string to dot notation so I can go

var val = obj.a.b  

If the string was just 'a', I could use obj[a]. But this is more complex. I imagine there is some straightforward method, but it escapes me at present.

Finding the index of an item in a list

Posted: 22 Aug 2021 08:35 AM PDT

Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index (1) in Python?

No comments:

Post a Comment