Friday, July 23, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to interoperate StackExchange.Redis with Microsoft.Extensions.Caching.StackExchangeRedis

Posted: 23 Jul 2021 08:20 AM PDT

I have a web application with radis cache implementation with Microsoft.Extensions.Caching.StackExchangeRedis. Now I am trying to create a console app to use redis cache but the API is different. Is there any way to acheive it as StackExchange.Redis do not have InstanceName API which i think is creating lot of issue.

Thanks

concatenate two different color spaces as input image for image.summary tensorflow

Posted: 23 Jul 2021 08:20 AM PDT

I'm using tensorflow v1 and have a code which runs perfectly for one color space only (such as RGB or HSV)

    Class Database_loader:                #Defines a loading scheme for database                    def __init__(self, directory, size, proportion = 1.0, seed=42) :              # data init              self.dir = directory          # directory with the train / test / validation               self.size = size              # size of the sub image that should be croped              self.nb_channels = 3          # return only the green channel of the images              self.file_train = []          # list of the train images : tuple (image name / class)              self.file_test = []           # list of the test images : tuple (image name / class)              self.file_validation = []     # list of the validation images : tuple (image name / class)              self.image_class = ['Real', 'CGG']         # list of the class (label) used in the process              self.nb_class = 0              self.train_iterator = 0       # iterator over the train images              self.test_iterator = 0        # iterator over the test images              self.validation_iterator = 0  # iterator over the validation images              self.load_images(seed)        # load the data base            def get_next_train(self) :                 # load next image (size should be big enough)              image = []              while True:                            # pop file name and class                  data = self.file_train[self.train_iterator]                  self.train_iterator += 1                  if self.train_iterator >= len(self.file_train) :                      self.train_iterator = 0                    # load image                  file_name = self.dir + '/train/' + data[1] + '/' + data[0]                  image = Image.open(file_name)                                               # convert to float image              image = image.astype(np.float32) / 255.                    #image = image.reshape(1, self.size, self.size, 3)                        if self.size == None:                   image = image.reshape(image.shape[0], image.shape[1], self.nb_channels)              else:                   image = image.reshape(self.size, self.size, self.nb_channels)  

and the code for model:

    def image_summaries(var, name):          tf.summary.image(name + '_1', var[:,:,:,0:1], max_outputs = 1)          tf.summary.image(name + '_2', var[:,:,:,1:2], max_outputs = 1)          tf.summary.image(name + '_3', var[:,:,:,2:3], max_outputs = 1)        database_path = 'I:/users/Database/test/'          # to change to the format of your image      image_size = 100        # define a single-image classifier      clf = Model(database_path, image_size, config = 'Personal', filters = [32,32,64],                  batch_size = 50, feature_extractor = 'Stats',                   remove_filter_size = 5, using_GPU = True)        # trains the classifier and test it on the testing set      clf.train(nb_train_batch = 800,                nb_test_batch = 80,                 nb_validation_batch = 40,                validation_frequency = 20,                show_filters = False)  

but i want to concatenate rgb images and hsv images in channel dimension and have 6 number of channels instead of 3 channels so i made these changes:

        self.nb_channels = 6  
            image1 = image.convert("HSV")              t1 = np.asarray(image1)              t2 = np.asarray(image)               t3 = np.concatenate((t1, t2))              image2 = Image.fromarray(t3)              image = np.asarray(image2)                # convert to float image              image = image.astype(np.float32) / 255.  
   def image_summaries(var, name):        tf.summary.image(name + '_1', var[:,:,:,0:1], max_outputs = 1)        tf.summary.image(name + '_2', var[:,:,:,1:2], max_outputs = 1)        tf.summary.image(name + '_3', var[:,:,:,2:3], max_outputs = 1)        tf.summary.image(name + '_4', var[:,:,:,3:4], max_outputs = 1)        tf.summary.image(name + '_5', var[:,:,:,4:5], max_outputs = 1)        tf.summary.image(name + '_6', var[:,:,:,5:6], max_outputs = 1)   

and got this error:

InvalidArgumentError: Tensor must be 4-D with last dim 1, 3, or 4, not [50,100,100,6] [[Node: Input_Data/Image_Visualization/Input_Data = ImageSummary[T=DT_FLOAT, bad_color=Tensor<type: uint8 shape: [4] values: 255 0 0...>, max_images=3, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Input_Data/Image_Visualization/Input_Data/tag, Input_Data/Reshape/_91)]]

any idea about what i should do?

What's the most safe way to copy from one string to another in C?

Posted: 23 Jul 2021 08:20 AM PDT

strcpy_s, strncpy_s, memcpy_s maybe another function?

What you prefer and why? In which case you use one or another?

Secondary DB got Crash Unexpectedly

Posted: 23 Jul 2021 08:20 AM PDT

Primary and Secondary are running on Windows server 2012 R2 Standard. and Today Primary Machine got down. and after that Secondary Mongo instance goes down due to below error of Got signal: 22 (SIGABRT). and then Primary goes into Recovering Mode. Primary Server don't print any clear logs.

Primary Server Log:

2021-07-23T19:13:53.237+0530 I REPL     [replexec-23] Member SecondaryHost:27017 is now in state RS_DOWN 2021-07-23T19:13:53.237+0530 I REPL     [replexec-23] can't see a majority of the set, relinquishing primary 2021-07-23T19:13:53.237+0530 I REPL     [replexec-23] Stepping down from primary in response to heartbeat 2021-07-23T19:13:53.237+0530 I REPL     [replexec-23] transition to RECOVERING from PRIMARY 2021-07-23T19:13:53.238+0530 I NETWORK  [replexec-23] Skip closing connection for connection # 11139  

Today our UAT Primary goes into Recovering Mode suddenly and Secondary Server was not getting up. From logs I have got below Errors from Secondary Server. Just want to know why this happened.

Secondary Server Logs:

2021-07-23T19:05:26.900+0530 E STORAGE [WTCheckpointThread] WiredTiger error (13) [1627047326:876858][1540:140704437702784], file:ReconDB_UAT/collection/26--5782211086932514962.wt, WT_SESSION.checkpoint: __win_open_file, 543: D:\MongoData\Data\ReconDB_UAT/collection/26--5782211086932514962.wt: handle-open: CreateFileW: Access is denied.       : Permission denied Raw: [1627047326:876858][1540:140704437702784], file:ReconDB_UAT/collection/26--5782211086932514962.wt, WT_SESSION.checkpoint: __win_open_file, 543: D:\MongoData\Data\ReconDB_UAT/collection/26--5782211086932514962.wt: handle-open: CreateFileW: Access is denied.       : Permission denied      2021-07-23T19:05:26.900+0530 F - [WTCheckpointThread] Invariant failure: s->checkpoint(s, "use_timestamp=true") resulted in status UnknownError: 13: Permission denied at src\mongo\db\storage\wiredtiger\wiredtiger_kv_engine.cpp 352      2021-07-23T19:05:26.900+0530 F - [WTCheckpointThread]            ***aborting after invariant() failure                  2021-07-23T19:05:28.595+0530 I ASIO [Replication] Connecting to ArbHost:27017      2021-07-23T19:05:28.642+0530 I ASIO [Replication] Failed to connect to ArbHost:27017 - AuthenticationFailed: Authentication failed.      2021-07-23T19:05:28.642+0530 I CONNPOOL [Replication] Dropping all pooled connections to ArbHost:27017 due to AuthenticationFailed: Authentication failed.      2021-07-23T19:05:28.642+0530 I REPL_HB [replexec-99] Error in heartbeat (requestId: 1211726) to ArbHost:27017, response status: AuthenticationFailed: Authentication failed.      2021-07-23T19:05:30.643+0530 I ASIO [Replication] Connecting to ArbHost:27017      2021-07-23T19:05:30.689+0530 I ASIO [Replication] Failed to connect to ArbHost:27017 - AuthenticationFailed: Authentication failed.      2021-07-23T19:05:30.689+0530 I CONNPOOL [Replication] Dropping all pooled connections to ArbHost:27017 due to AuthenticationFailed: Authentication failed.      2021-07-23T19:05:30.690+0530 I REPL_HB [replexec-99] Error in heartbeat (requestId: 1211729) to ArbHost:27017, response status: AuthenticationFailed: Authentication failed.      2021-07-23T19:05:32.691+0530 I ASIO [Replication] Connecting to ArbHost:27017      2021-07-23T19:05:32.736+0530 I ASIO [Replication] Failed to connect to ArbHost:27017 - AuthenticationFailed: Authentication failed.      2021-07-23T19:05:32.736+0530 I CONNPOOL [Replication] Dropping all pooled connections to ArbHost:27017 due to AuthenticationFailed: Authentication failed.      2021-07-23T19:05:32.736+0530 I REPL_HB [replexec-99] Error in heartbeat (requestId: 1211732) to ArbHost:27017, response status: AuthenticationFailed: Authentication failed.      2021-07-23T19:05:32.952+0530 F - [WTCheckpointThread] Got signal: 22 (SIGABRT).      mongod.exe ...\src\mongo\util\stacktrace_windows.cpp(247) mongo::printStackTrace+0x43      mongod.exe ...\src\mongo\util\signal_handlers_synchronous.cpp(184) mongo::`anonymous namespace'::printSignalAndBacktrace+0x74      mongod.exe ...\src\mongo\util\signal_handlers_synchronous.cpp(240) mongo::`anonymous namespace'::abruptQuit+0x85      ucrtbase.DLL raise+0x1e7      ucrtbase.DLL abort+0x31      mongod.exe ...\src\mongo\util\assert_util.cpp(129) mongo::invariantOKFailed+0x228      mongod.exe ...\src\mongo\db\storage\wiredtiger\wiredtiger_kv_engine.cpp(352) mongo::WiredTigerKVEngine::WiredTigerCheckpointThread::run+0x661      mongod.exe ...\src\mongo\util\background.cpp(153) mongo::BackgroundJob::jobBody+0x131      mongod.exe c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(247) std::_LaunchPad<std::unique_ptr<std::tuple<<lambda_8929d5e2502e4de5883694c1a7a329eb> >,std::default_delete<std::tuple<<lambda_8929d5e2502e4de5883694c1a7a329eb> > > > >::_Run+0x77      mongod.exe c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(210) std::_Pad::_Call_func+0x9      ucrtbase.DLL o__realloc_base+0x60      KERNEL32.DLL BaseThreadInitThunk+0x22      2021-07-23T19:05:33.006+0530 F CONTROL [WTCheckpointThread] *** unhandled exception 0x0000000E at 0x00007FF84DC27AFC, terminating      2021-07-23T19:05:33.006+0530 F CONTROL [WTCheckpointThread] *** stack trace for unhandled exception:      2021-07-23T19:05:33.021+0530 I - [WTCheckpointThread] KERNELBASE.dll RaiseException+0x6c      mongod.exe ...\src\mongo\util\signal_handlers_synchronous.cpp(241) mongo::`anonymous namespace'::abruptQuit+0x9d      ucrtbase.DLL raise+0x1e7      ucrtbase.DLL abort+0x31      mongod.exe ...\src\mongo\util\assert_util.cpp(129) mongo::invariantOKFailed+0x228      mongod.exe ...\src\mongo\db\storage\wiredtiger\wiredtiger_kv_engine.cpp(352) mongo::WiredTigerKVEngine::WiredTigerCheckpointThread::run+0x661      mongod.exe ...\src\mongo\util\background.cpp(153) mongo::BackgroundJob::jobBody+0x131      mongod.exe c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(247) std::_LaunchPad<std::unique_ptr<std::tuple<<lambda_8929d5e2502e4de5883694c1a7a329eb> >,std::default_delete<std::tuple<<lambda_8929d5e2502e4de5883694c1a7a329eb> > > > >::_Run+0x77      mongod.exe c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(210) std::_Pad::_Call_func+0x9      ucrtbase.DLL o__realloc_base+0x60      KERNEL32.DLL BaseThreadInitThunk+0x22      2021-07-23T19:05:33.022+0530 I CONTROL [WTCheckpointThread] writing minidump diagnostic file C:\Program Files\MongoDB\Server\4.2021-07-23T13-35-33.mdmp      2021-07-23T19:13:01.047+0530 I NETWORK [listener] connection accepted from PrimaryHost:51006 #182621 (15 connections now open)  

Cannot read property 'map' of undefined on useEffect hook

Posted: 23 Jul 2021 08:20 AM PDT

I recently started learning react and I got stuck in the above-mentioned error. I know there are plenty of answers to this error. yes, I have seen those solutions but I am not able to map those solutions to my problems. I am pasting my code below please tell me what is wrong with the below code. any help is very much appreciated. thank you.

const orders = () => {        const [stateValue, setState] = useState({          orders: [],          loading: true      });        // getting the orders      useEffect(() => {          axiosInstance.get('/orders.json').then(res => {              transformData(res);              setState({loading: false});          }).catch(err => {              console.log(err)              setState({loading: false});          })      }, []);        // transforming firebase response(objects of objects) into array of objects      const transformData = (response) => {            const ordersData = [];          if(response.data) {              for (let key in response.data) {                  ordersData.push({                      ...response.data[key],                      id: key                  })              }          }            setState({orders: ordersData});      }            let orders;      orders = stateValue.orders.map((order) => <Order //error line                  key={order.id}                  ingredients={order.ingredients}                   email={order.email}                  price={order.price}                  />);                 if(stateValue.loading) {          orders = <Loading />      }        return(          <div>               {orders}          </div>               )  }

RealTime-Chart Angular Laravel

Posted: 23 Jul 2021 08:19 AM PDT

I want to know How can I make a real time chart with angular anda laravel, the backend and the channels are working and I'm receiving the data at the front but when I need to re-render or change the value of the variable the chart this doesnt work.

At the BackEnd I'm using pusher and laravel-websockets And in the front I'm using pusher and Laravel Echo

I have a barchart and I'm making a filter of all what the back send me to separate it. in my try i've this

this.echo.private('channel-count')          .listen('CountEvent', (resp: any) => {            this.piezasContadasUno.push(resp.count);            this.piezasContadasUnoLenght = this.piezasContadasUno.length;            var listFilter = ['Juno A'];            var JunoACounted = this.piezasContadasUno.filter(function(itm){            return listFilter.indexOf(itm.linea) > -1          })            this.JUNOACounted = JunoACounted.length            this.barChartData = [                              { data: [this.JUNOACounted, this.JUNOBCounted, this.JUNOCCounted, this.ZEUZBCounted, this.SECounted, this.ICEMAKERCounted, this.PRCounted], label: 'Conteo', stack: 'a' },            { data: [this.JUNOATotal, this.JUNOBTotal, this.JUNOCTotal, this.ZEUZBTotal, this.SETotal, this.ICEMAKERTotal, this.PRTotal], label: 'Piezas', stack: 'a' }                ]          })  

I have the same in the onInit to charge the data untill the start of the component but when I add something and the channel return it and make the push to add to the array and the assing the new length to the variable this doesn't work, stay at the same value when start the component

Why jdk works well but get mvn compile error

Posted: 23 Jul 2021 08:19 AM PDT

My jdk works well, but I get the error when running mvn compile

PS H:\Learning\Maven> java -version  java version "1.8.0_281"  Java(TM) SE Runtime Environment (build 1.8.0_281-b09)  Java HotSpot(TM) 64-Bit Server VM (build 25.281-b09, mixed mode)  
PS H:\Learning\Maven> mvn compile  [INFO] Scanning for projects...  [INFO]  [INFO] --------------------------< com.xxx:maven01 >---------------------------  [INFO] Building maven01 0.0.1-SNAPSHOT  [INFO] --------------------------------[ jar ]---------------------------------  [INFO]  [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ maven01 ---  [INFO] Using 'UTF-8' encoding to copy filtered resources.  [INFO] Copying 0 resource  [INFO]  [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ maven01 ---  [INFO] Changes detected - recompiling the module!  [INFO] Compiling 1 source file to H:\Learning\Maven\target\classes  [INFO] -------------------------------------------------------------  [ERROR] COMPILATION ERROR :  [INFO] -------------------------------------------------------------  [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?  [INFO] 1 error  [INFO] -------------------------------------------------------------  [INFO] ------------------------------------------------------------------------  [INFO] BUILD FAILURE  [INFO] ------------------------------------------------------------------------  [INFO] Total time:  0.566 s  [INFO] Finished at: 2021-07-23T23:18:05+08:00  [INFO] ------------------------------------------------------------------------  [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project maven01: Compilation failure  [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?  [ERROR]  [ERROR] -> [Help 1]  [ERROR]  [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.  [ERROR] Re-run Maven using the -X switch to enable full debug logging.  [ERROR]  [ERROR] For more information about the errors and possible solutions, please read the following articles:  [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException  

Angular material datepicker error after opening the calendar

Posted: 23 Jul 2021 08:19 AM PDT

I freshly created a new project with angular 12 (also 11) and when I try to add the datepicker described in the documentation: https://material.angular.io/components/datepicker/overview I get the following error as soon as I click on the button to show the calendar

core.js:6479 ERROR Error: Invalid date "1" for month with index "6".      at NativeDateAdapter.createDate (core.js:641)      at MatMonthView._init (datepicker.js:978)      at SafeSubscriber._next (datepicker.js:871)      at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)      at SafeSubscriber.next (Subscriber.js:122)      at Subscriber._next (Subscriber.js:72)      at Subscriber.next (Subscriber.js:49)      at MergeMapSubscriber.notifyNext (mergeMap.js:70)      at SimpleInnerSubscriber._next (innerSubscribe.js:10)      at SimpleInnerSubscriber.next (Subscriber.js:49)  

Decompose time series in Python with statsmodels

Posted: 23 Jul 2021 08:19 AM PDT

I am trying to decompose a time series. The database is a 2x8638 matrix. Follow the code.

import numpy as np  import pandas as pd  import matplotlib.pylab as plt  %matplotlib inline  from matplotlib.pylab import rcParams  rcParams['figure.figsize'] = 15, 6  from pandas.plotting import register_matplotlib_converters  register_matplotlib_converters()    df1 = pd.read_csv("u_x_ts.csv").set_index("0")  df1.head()  

enter image description here

from statsmodels.tsa.seasonal import seasonal_decompose  result = seasonal_decompose(df1, model='multiplicative')  result.plot()  plt.show()  

then python returns the error message:

ValueError: Multiplicative seasonality is not appropriate for zero and negative values

I think statsmodels doesn't support such small values, because at the beginning of the series the values ​​are too small. But if anyone knows a way out of this problem I appreciate it.

Values outside of the while statement condition are being returned, how can I fix this?

Posted: 23 Jul 2021 08:20 AM PDT

I have written two functions. They are each reading from the same file. The user will input two time points, time_stamp1 and time_stamp2. Within the file there are corresponding beam values. I am trying to print the beam values that are within the time range.

When I implement the code, every beam value is returned, not just the values within the time range. How can I fix this?

Here are the definitions:

boop = 0  def time_stamp():      for elem in ds.iterall():          if elem.tag==[0x3008,0x0025]:               if elem.value >= time_stamp1 and elem.value <= time_stamp2:                  print(elem)                   global boop                      boop = 1                      def get_beam():             for elem in ds.iterall():          if elem.tag == [0x300a,0x0114]:              print(elem)           time_stamp()  if boop == 1:       get_beam()  

How can I create a multi-value Dictionary

Posted: 23 Jul 2021 08:20 AM PDT

So I have user info from an SQL server a username and password and now i want to create a dictionary

{ID : password}  

but if I have more then one it just saves the last one I put in

for i in (cursor.execute('select * from Person')):      idNameDict = {i[0]:i[3]}  

I want to do it this way so it would be easier for me to do check if the based on the ID that the password input would be correct because right now and it seems to long

def logIn(userName,userPassword):      userID=[]      global p      lbl = Label(root)      lbl.grid(row=5,column=1)      for user in (cursor.execute('select * from Person')):          p = Person(user[0],user[1],user[2],user[3])          userID.append(p)      for id in userID:          if userName == id.ID:              if userPassword == id.password:                  userPage(root,userName)              else:                  lbl.config(text= "Invalid Password")          else:              lbl.config(text= "Invalid User Name")  

Why are my Pandas dataframe columns are being displayed on top of one another instead of horizontally?

Posted: 23 Jul 2021 08:20 AM PDT

I am working with 99 different columns and want to group related topics together for future analysis. However, when I print my new group the columns are not displayed on the same level. They will be stacked on top of one another. It doesn't happen with all columns though. I have tried %pprint but that didn't do anything.

The image below shows the columns I want to call, the other 2 columns are below the first 2 columns. Both have their column name followed by a \ and with the next column displayed at the bottom of the previous column.

enter image description here

Passing props from child function to parent function with React Native

Posted: 23 Jul 2021 08:21 AM PDT

Within Session() I want to access stateABC, which is in Item5().

The setup of my code looks like this:

Session.js:

function Session() {        return (          <View>              {handleRender(item)}              <Text>{handleRender(item).props.stateABC}</Text>          </View>      );  }  

handleRender.js:

export function handleRender(item) {        if(item == "Item05"){          return (                  {Item5()}              );      }  }  

Item5.js:

 export function Item5() {                const [stateABC, setStateABC] = useState("123");                 return (                      ....                  );      }  

I tried to get the value in Session() by using handleRender(item).props.stateABC, but all I get is an empty value.

Is it possible to receive properties from a function like that or are props only accessible in class components?

Any help is appreciated.

Thanks

Program crashes when String used by StringSink goes out of scope

Posted: 23 Jul 2021 08:19 AM PDT

Today I started trying out the Cryptopp library. I took an example from the documentation here.

The program crashes and I cannot seem to figure out why.

My code:

#include <cryptopp/dll.h>  #include <cryptopp/hex.h>  #include <string>    int main(int argc, const char* argv[]) {        std::cout << "START OF PROGRAM" << std::endl;        {          std::string encoded;          CryptoPP::byte decoded[] = { 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00 };            //Method 1          CryptoPP::HexEncoder encoder2;          encoder2.Attach(new CryptoPP::StringSink(encoded));          encoder2.Put(decoded, sizeof(decoded));          encoder2.MessageEnd();            //Method 2          //CryptoPP::StringSource ss(decoded, sizeof(decoded), true, new CryptoPP::HexEncoder(new CryptoPP::StringSink(encoded)));            std::cout << "Encoded: ";          std::cout << encoded;          std::cout << std::endl;      }        std::cout << "END OF PROGRAM" << std::endl;  }  

The output is:

START OF PROGRAM  Encoded: FFEEDDCCBBAA99887766554433221100  

Which means that END OF PROGRAMis not reached, but the HexEncoder did its job as expected. As soon as my std::string encoded; goes out of scope the program crashes. If I move std::string encoded; to the outer scope (the scope of int main(...)) then END OF PROGRAM is printed and the program crashes at the end of main.

Also, if I don't call encoder2.Put(...) the program does not crash, but obviously the HexEncoder also does nothing. Using Method 2 instead of Method 1 results in the same error.

The error I get is:

HEAP[app.exe]: Invalid address specified to RtlValidateHeap( 000001CE84480000, 000001CE84761390 )  

About my environment:

I use Microsoft Visual Studio 2019. I used the solution of cryptopp to build the library using the DLL-Import Debug config. I only had to change the Runtime Library setting from /MTd to /MDd (since the larger program I'm working on and want to use cryptopp in is using /MDd). I also removed the CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2=1 preprocessor-definition since it caused issues (I think because of running my program in the Visual Studio debugger).

Other details

Another example which involved HexEncoder using a FileSink which takes a stringstream did work:

std::stringstream encoded;  CryptoPP::HexEncoder encoder2(new CryptoPP::FileSink(encoded));  encoder2.Put(decoded, sizeof(decoded));  encoder2.MessageEnd();  std::cout << encoded.str();  

And stuff involving symmetric Salsa20 encryption and decryption (example from here) did also work.

Question

Can somebody explain what goes wrong, how I can fix it or if it is a bug in the library or my building process?

get the boundaries of a plot and plot the boundaries over the same plot

Posted: 23 Jul 2021 08:19 AM PDT

I am new to Python and I have a question of how to get the boundaries of a figure that plotted by matplotlib imshow. For example, the following figure is the one that plotted by imshow and I want to get the coordinate of the boundaries and plot the boundaries over the same image. I hope you can help me.

image

Here is the code that I wrote for the first two lines.

df = pd.read_csv('data.txt', sep='\t')  plt.imshow(df,origin='lower')  

How to close an html website using javascript?

Posted: 23 Jul 2021 08:20 AM PDT

So basically, I'm trying to create a system that closing the website when you get the password wrong. but I started to learn js just a couple of days ago and I don't know much of it yet.

here is the code:

<!DOCTYPE html>  <html id="web" lang="en">    <head>      <meta charset="UTF-8">      <meta http-equiv="X-UA-Compatible" content="IE=edge">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>MySite</title>      <script>          var web = document.getElementById("web");          var password = "BigDips12";          alert("Hey, For security messures and to make sure you are truly not a robot ...");          var security = prompt("Please enter the password here:");          if (security === password) {              alert('Welcome!')          } else {              alert('Password is wrong! The program will close itself now..')                function closeWin() {                  web.close();              }          }      </script>  </head>    <body>      <h1>Hello World!</h1>  </body>    </html>

I really need help pls

How do I edit a key in python dictionary that is variable

Posted: 23 Jul 2021 08:20 AM PDT

I am working on a code in python and relatively new at python so excuse me if the title of this post is unclear, am currently unable to figure out how to solve this issue where I have a blank dictionary

Cart={}  

And I have a few lines of code that adds an variable to it if selected

if x==1:     Cart['Milk']=[qnty],[total],[gst],[offer]  if x==2:     Cart['Butter']=[qnty],[total],[gst],[offer]  if x==3:     Cart['Cookies']=[qnty],[total],[gst],[offer]  

Here's the part where I am unable to figure out, I would like to now edit the qnty part of the variable but as there is no 'fix' key in the dictionary i am unsure how to do it, I tried doing it the way below but will only give me the name and qnty and removes the other key.

if y == 2:     print(Cart)     item=str(input('key in an item to edit: '))     for item in Cart:           qnty=int(input('Key in the quantity of %s you want: '%item))           Cart=[item],[qnty]     print(shopping_basket)  

Is there a way to edit the Qnty of the item only? I have also tried using list or assigning fixed key to the blank dictionary but just can't seem to work.

Thank you in advance feel free to ask me more if clarifications is needed.

Is there a way to use (if number in range) whilst using .apply in python?

Posted: 23 Jul 2021 08:19 AM PDT

I have a dataframe that looks something like this

Difference Min Max
2.5 -5 5
7.3 -3 3
0.1 -0.1 0.1

The numbers in the "Min" and "Max" column are different from row to row, but always take the value Min = -Max. What I am wanting to create is a final column that tells me if the value in the "Difference" column falls between the values in the "Min" and "Max" column. Something like this:

Difference Min Max Signal
2.5 -5 5 Signal
7.3 -3 3 No Signal
0.1 -0.1 0.1 Signal

"Signal and "No Signal" could also be replaced with True or False if there was a way to use boolean operators.

The code that I am currently using is as follows.

df['Signal'] = df['Difference'].apply(lambda x: 'Signal' if x in range((df['Min']), (df['Max'])) else 'No Signal')  

This gives me the error code

  File "<ipython-input-52-13b6ff6e946a>", line 5  df['Signal'] = df['Difference'].apply(lambda x: 'Signal' if x in range((df['Min']), (df['Max'])) else 'No Signal')   ^  SyntaxError: invalid syntax  

I also tried a different approach with the following code

df['Signal'] = df['Difference'].apply(lambda x: 'Signal' if df['Min'] <= x <= df['Max'] else 'No Signal')  

This then gave me the error message

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().  

The issue here is that I don't fully understand the error message and therefore don't know how to go about fixing it.

Any help greatly appreciated.

How can I take characters of a string with the data type of uint8_t Variable and use them as hexadecimal variables?

Posted: 23 Jul 2021 08:21 AM PDT

i have an uint8_t Variable which contains a substring of 4 hexadecimal variables. Example:

uint8_t String[10] = "00AABBCC";  

I would like to take these 4 hex Variables into different hex values:

uint8_t Data_Byte[4];  Data_Byte[0]=0x00;  Data_Byte[1]=0xAA;  Data_Byte[2]=0xBB;  Data_Byte[3]=0xCC;  

How can I take these 4 substrings into 4 different uint8_t Variables?

put grid in pageview flutter

Posted: 23 Jul 2021 08:20 AM PDT

I have an apps sheet that I have installed on my phone. for this i use device_apps: ^ 2.1.1. I also use drag_and_drop_gridview: ^ 1.0.8 to make a free drag-and-drop grid out of the application sheet. I managed to put it all in a PageView. But every PageView of My Apps is repeated. How can I split the list of applications into parts and put them in a PageView? My phone has 175 applications and only 18 fits on the screen, so I have made static data for now

import 'dart:developer';    import 'package:device_apps/device_apps.dart';  import 'package:flutter/material.dart';  import 'package:launcher_ios_iphone_pro/widget/devdrag.dart';  import 'package:quiver/iterables.dart';    class HomePage extends StatefulWidget {    HomePage({Key? key}) : super(key: key);      @override    _HomePageState createState() => _HomePageState();  }    class _HomePageState extends State<HomePage> {    int variableSet = 0;    ScrollController? _scrollController;    double? width;    double? height;    int? intAppsPage; //18    var pairs;    void calcApps() async {      List<Application> apps = await DeviceApps.getInstalledApplications();      intAppsPage = apps.length;      intAppsPage = (intAppsPage! / 18).ceil();      pairs = partition(apps, 10);    }      @override    void initState() {      super.initState();      calcApps();    }      @override    Widget build(BuildContext context) {      log('intAppsPage: $intAppsPage');      return Scaffold(        body: Container(          color: Colors.black,          child: intAppsPage == null              ? Center(                  child: CircularProgressIndicator(),                )              : PageView.builder(                  itemCount: intAppsPage,                  itemBuilder: (BuildContext context, int index) {                    return FutureBuilder(                      future: DeviceApps.getInstalledApplications(                        includeSystemApps: true,                        onlyAppsWithLaunchIntent: true,                        includeAppIcons: true,                      ),                      builder: (BuildContext context,                          AsyncSnapshot<List<Application>> data) {                        if (data.data == null) {                          return Center(child: CircularProgressIndicator());                        } else {                          List<Application> allApps = data.data!;                          return DragAndDropGridView(                            controller: _scrollController,                            gridDelegate:                                SliverGridDelegateWithFixedCrossAxisCount(                              crossAxisCount: 3,                              childAspectRatio: 5 / 5,                            ),                            padding: EdgeInsets.all(20),                            itemBuilder: (context, index) => Card(                              elevation: 2,                              color: Color(0x00FFFFFF),                              child: LayoutBuilder(builder: (context, costrains) {                                if (variableSet == 0) {                                  height = costrains.maxHeight;                                  width = costrains.maxWidth;                                  variableSet++;                                }                                return Padding(                                  padding: const EdgeInsets.all(12.0),                                  child: Column(                                    children: [                                      ClipRRect(                                        borderRadius: BorderRadius.circular(15.0),                                        child: Image.memory(                                            (allApps[index]                                                    as ApplicationWithIcon)                                                .icon,                                            width: 64),                                      ),                                      Text(                                        '${allApps[index].appName}',                                        style: TextStyle(color: Colors.white),                                        textAlign: TextAlign.center,                                        overflow: TextOverflow.ellipsis,                                        maxLines: 1,                                      ),                                    ],                                  ),                                );                              }),                            ),                            itemCount: allApps.length,                            onWillAccept: (oldIndex, newIndex) => true,                            onReorder: (oldIndex, newIndex) {                              int indexOfFirstItem =                                  allApps.indexOf(allApps[oldIndex]);                              int indexOfSecondItem =                                  allApps.indexOf(allApps[newIndex]);                                if (indexOfFirstItem > indexOfSecondItem) {                                for (int i = allApps.indexOf(allApps[oldIndex]);                                    i > allApps.indexOf(allApps[newIndex]);                                    i--) {                                  var tmp = allApps[i - 1];                                  allApps[i - 1] = allApps[i];                                  allApps[i] = tmp;                                }                              } else {                                for (int i = allApps.indexOf(allApps[oldIndex]);                                    i < allApps.indexOf(allApps[newIndex]);                                    i++) {                                  var tmp = allApps[i + 1];                                  allApps[i + 1] = allApps[i];                                  allApps[i] = tmp;                                }                              }                            },                          );                        }                      },                    );                  },                ),        ),      );    }  }  

UPDATE:

I found a way, but now I have an error in the console:

RangeError (index): Invalid value: Not in inclusive range 0..1: 2  The relevant error-causing widget was  LayoutBuilder  lib\pages\HomePage.dart:83  

The error indicates this piece of code:

LayoutBuilder(builder: (context, costrains) {      if (variableSet == 0) {         height = costrains.maxHeight;         width = costrains.maxWidth;         variableSet++;         }  

My code now looks like this:

import 'dart:developer';    import 'package:device_apps/device_apps.dart';  import 'package:flutter/material.dart';  import 'package:launcher_ios_iphone_pro/widget/devdrag.dart';  import 'package:quiver/iterables.dart';    class HomePage extends StatefulWidget {    HomePage({Key? key}) : super(key: key);      @override    _HomePageState createState() => _HomePageState();  }    class _HomePageState extends State<HomePage> {    int variableSet = 0;    ScrollController? _scrollController;    double? width;    double? height;    late int intAppsPage; //18    // var pairs;        void calcApps() async {      List<Application> apps = await DeviceApps.getInstalledApplications(        includeSystemApps: true,        onlyAppsWithLaunchIntent: true,        includeAppIcons: true,      );            intAppsPage = apps.length;      log('intAppsPage: $intAppsPage');      intAppsPage = (intAppsPage / 18).ceil();      // pairs = List.generate(apps.length~/18, (i) => [apps[18 * i], apps[18 * i + 1]]);      log('intAppsPage2: $intAppsPage');      // log('pairs: $pairs');    }      @override    void initState() {      super.initState();      calcApps();    }      @override    Widget build(BuildContext context) {      // calcApps();            log('intAppsPage: $intAppsPage');      return Scaffold(        body: Container(          color: Colors.black,          child: intAppsPage == null              ? Center(                  child: CircularProgressIndicator(),                )              : PageView.builder(                  itemCount: intAppsPage,                  itemBuilder: (BuildContext context, int indexx) {                    return FutureBuilder(                      future: DeviceApps.getInstalledApplications(                        includeSystemApps: true,                        onlyAppsWithLaunchIntent: true,                        includeAppIcons: true,                      ),                      builder: (BuildContext context,                          AsyncSnapshot<List<Application>> data) {                        if (data.data == null) {                          return Center(child: CircularProgressIndicator());                        } else {                          var allApps = List.generate(data.data!.length~/18, (i) => [data.data![18 * i], data.data![18 * i + 1]]);                          log('allApps: $allApps');                          return DragAndDropGridView(                            controller: _scrollController,                            gridDelegate:                                SliverGridDelegateWithFixedCrossAxisCount(                              crossAxisCount: 3,                              // childAspectRatio: 5 / 5,                            ),                            padding: EdgeInsets.all(20),                            itemBuilder: (context, index) => Card(                              elevation: 3,                              color: Color(0x00FFFFFF),                              child: LayoutBuilder(builder: (context, costrains) {                                if (variableSet == 0) {                                  height = costrains.maxHeight;                                  width = costrains.maxWidth;                                  variableSet++;                                }                                return Padding(                                  padding: const EdgeInsets.all(12.0),                                  child: Column(                                    children: [                                      ClipRRect(                                        borderRadius: BorderRadius.circular(15.0),                                        child: Image.memory(                                            (allApps[0][index]                                                    as ApplicationWithIcon)                                                .icon,                                            width: 64),                                      ),                                      // Text(                                      //   '${allApps[index].appName}',                                      //   style: TextStyle(color: Colors.white),                                      //   textAlign: TextAlign.center,                                      //   overflow: TextOverflow.ellipsis,                                      //   maxLines: 1,                                      // ),                                    ],                                  ),                                );                              }),                            ),                            itemCount: 18,                            onWillAccept: (oldIndex, newIndex) => true,                            onReorder: (oldIndex, newIndex) {                              int indexOfFirstItem =                                  allApps.indexOf(allApps[oldIndex]);                              int indexOfSecondItem =                                  allApps.indexOf(allApps[newIndex]);                              if (indexOfFirstItem > indexOfSecondItem) {                                for (int i = allApps.indexOf(allApps[oldIndex]);                                    i > allApps.indexOf(allApps[newIndex]);                                    i--) {                                  var tmp = allApps[i - 1];                                  allApps[i - 1] = allApps[i];                                  allApps[i] = tmp;                                }                              } else {                                for (int i = allApps.indexOf(allApps[oldIndex]);                                    i < allApps.indexOf(allApps[newIndex]);                                    i++) {                                  var tmp = allApps[i + 1];                                  allApps[i + 1] = allApps[i];                                  allApps[i] = tmp;                                }                              }                            },                          );                        }                      },                    );                  },                ),        ),      );    }  }  

Screenshot:

screen

How to prevent Cargo.lock from updating itself automatically?

Posted: 23 Jul 2021 08:19 AM PDT

I was following the tutorial https://project-serum.github.io/anchor/tutorials/tutorial-0.html#defining-a-program with its repo https://github.com/project-serum/anchor

After running anchor build, I noticed a few files have been added/updated so I could not pull the repo anymore... so I tried to revert any changes by deleting the target folder and removed the package.json, yarn.lock, and node_modules.

Then I found whenever I undo changes in Cargo.lock (the one at the repo root), it would add the changes back by itself as if it refuses to revert to the repo's commit version!

WHY? How can I do this? Please help... thank you!

Angular primeng how to move the component style with host to generic style

Posted: 23 Jul 2021 08:21 AM PDT

I have following code. the demo component is using the numberinput component. I want to move the style from numberinput component to styles.scss where the same is going to be used for other components.

democomponent.html

  <app-number-input-simple class="form-control" name="numberSimpleDecimal" [placeholderText]="'Enter a number...'"      [readonly]="model.readonlyState" [disabled]="model.disabledState"      [config]="{ integer:false}" [(ngModel)]="model.ng_numberInput"></app-number-input-simple>  

number-input-simple.component.html

<p-inputNumber         [showButtons]="readonly ? false : true"      [placeholder]="placeholderText"      incrementButtonIcon="fal fa-plus"      decrementButtonIcon="fal fa-minus"      [minFractionDigits]="_config?.integer ? 0 : 1"         [min]="_config?.minValue"      [max]="_config?.maxValue"      [(ngModel)]="value"      (onBlur)="onBlur()"      [disabled]="disabled"  >   </p-inputNumber>  

number-input-simple.component.scss

@mixin no-pointer {      cursor: default;      pointer-events: none;        }    :host[ng-reflect-readonly='true'] ::ng-deep .p-inputnumber-input {      background-color: $light;      @include no-pointer;  }  

Create key array from duplicate value in Typescript

Posted: 23 Jul 2021 08:20 AM PDT

I have an array in the form:

  {      itemTitle: 'value example',      itemType: 'value example',      itemDescription: 'value example',      itemFamily: 'Asset',    },    {      itemTitle: 'value example',      itemType: 'value example',      itemDescription: 'value example',      itemFamily: 'Asset',    },    {      itemTitle: 'value example',      itemType: 'value example',      itemDescription: 'value example',      itemFamily: 'Periodic',    },    {      itemTitle: 'value example',      itemType: 'value example',      itemDescription: 'value example',      itemFamily: 'Periodic',    },  

and I would like to transform it into map (key, value) with as key the value is itemFamily so that it looks like this:

{ Asset:       [ { itemTitle: 'value example',          itemType: 'value example',          itemDescription: 'value example',          itemFamily: 'Asset' },        { itemTitle: 'value example',          itemType: 'value example',          itemDescription: 'value example',          itemFamily: 'Asset' } ],     Periodic:       [ { itemTitle: 'value example',          itemType: 'value example',          itemDescription: 'value example',          itemFamily: 'Periodic' },        { itemTitle: 'value example',          itemType: 'value example',          itemDescription: 'value example',          itemFamily: 'Periodic' } ]   }  

do you have any idea how to do it?

Plotting Algebraic Curves in Julia

Posted: 23 Jul 2021 08:20 AM PDT

I'm looking to visualize some algebraic curves in Julia

I have the polynomials:

f1=(x^4+y^4-1)(x^2+y^2-2)+x^5y

f2 = x^2+2xy^2-2y^2-1/2

and I would like to plot V(f1) and V(f2) so I can see their common intersections. I have tried using contour plot in Gadfly.jl but it seems to only allow me to plot one curve at a time. Is there a way to plot both curves in Gadfly.jl or doing it in another Julia package?

Here is what I have so far. enter image description here

Media queries max-width value doesn't load at the asked screensize

Posted: 23 Jul 2021 08:20 AM PDT

I'm having multiple projects now who's media queries are acting weird. For example:

@media only screen and (max-width: 891px) {    .lang-selector{      top: -150px;    }  }  

This only loads starting from 801px and less, although I do not have this media query set in my scss (it should be starting from 891px): console output

I'm working on Windows 10 and I get the same result in Firefox, Chrome, Edge...

I'm breaking my head on this simple thing. Hope I am clear enough.

Thanks for helping

I don't know how to make a random number of 0,1,2 appear as rock, paper, and sissors when printing the result sentence

Posted: 23 Jul 2021 08:20 AM PDT

I just started learning programming, so I'm not good enough. I'd appreciate it if someone could help me:)

Question : Two random values should be made to play a total 10 times of rock-scissors-paper games and produce the following results.

Here is example result.

The 1 th game was won by the computer (computer = sissors, player = paper)

The 2 th game was won by the player (computer = paper, player = sissors)

The 3 th game was a draw (computer = sissors, player = sissors)

......

The 10 th game ~

This is the code I write

#include <stdio.h>  #include <stdlib.h>  #include <time.h>    int main(void)   {   // 0=rock, 1=paper, 2=sissors   // c = computer , p = player      srand(time(NULL));   for(int i=0; i<10; i++)   {   int c;    int p;     c = rand() % 3;   p = rand() % 3;      sprintf (rock, "%d", 0);   sprintf (paper, "%d", 1);   sprintf (sissors, "%d", 2);       if (c == p)   {       printf("The %d th game was a draw \n", i+1);       printf("      (computer = %s, player = %s)",c,p);   }      else if ((c == 0 && p == 2) || (c == 1 && p == 0) || (c == 2) && (p == 1));       {           printf("The %d th game was won by the computer. \n", i+1);           printf("      (computer = %s, player = %s\n)",c,p);       }         else      {       printf("The %d th game was won by the player \n", i+1);       printf("      (computer = %s, player = %s\n)",c,p);      }   }   return 0;  }  

Amazon MWAA Airflow - Tasks container shut down / stop / killed without logs

Posted: 23 Jul 2021 08:19 AM PDT

We use Amazon MWAA Airflow, rarely some task as marked as "FAILED" but there is no logs at all. As if the container had been shut down without noticing us.

I have found this link: https://cloud.google.com/composer/docs/how-to/using/troubleshooting-dags#task_fails_without_emitting_logs Which explain this by OOM on the machine. But our tasks are doing almost nothing with CPU and RAM. They only do 1 HTTP call to AWS API. So very light.

On Cloudwatch, I can see that no others tasks are launched on the same container (the DAG run start by printing the container IP, so I can search this IP on all tasks).

If someone has an idea, would be great, thanks !

Entry name 'META-INF/MANIFEST.MF' collided when building for API 21 emulator, AS 4.0.1

Posted: 23 Jul 2021 08:19 AM PDT

When building for API 21 emulator in Android Studio 4.0.1 I get the error: "Entry name 'META-INF/MANIFEST.MF' collided". Building for other platform versions, emulator or device does work. Any ideas what might be wrong? My guess is there is a collision related to backward compatibility dependencies that Android build process injects for API 21, the error message does not help to isolate the problem. Running the build task itself t get more log output yields no problems ("Task execution finished 'build'.")

Lombok/Jackson - POJO for a json array

Posted: 23 Jul 2021 08:19 AM PDT

I have a json array that I need to receive(de-serialize) from a server and send (serialize) to another server:

Example:

[    {      "car-name": "string",      "parts": [        "engine",        "wheels"      ]    }  ]  

I started with writing the following POJO to represent this Json array:

import lombok.Builder;  import lombok.Singular;  import lombok.Value;      @Builder  @Value  public class Car {        private String carName;      @Singular("part")      private List<String> parts;  }  

With this:

  1. I am able to build the object using Lombok as:

Car myCar = Car.builder().carName("Tesla").part("engine").part("wheels").build();

  1. Unmarshal using something like unmarshal().json(Jackson, Car.class).

While 1) and 2) work, they do NOT give me objects that actually represent the json example above.

They instead give this:

  {      "car-name": "string",      "parts": [        "engine",        "wheels"      ]    }  

I tried using a parent class as below:

import lombok.Builder;  import lombok.Singular;  import lombok.Value;    @Builder  @Value  public class Vehicle {        private List<Car> vehicles;  }  

But this also gives me a wrong object (notice the "vehicles" key Vs what I have in my above Example):

  {      "vehicles": {          "car-name": "string",          "parts": [               "engine",               "wheels"               ]          }  }  

How can I write a POJO that represents this JSON array, preferably using Lombok? Or Jackson?

Connect to Kafka running in Docker

Posted: 23 Jul 2021 08:20 AM PDT

I setup a single node Kafka Docker container on my local machine like it is described in the Confluent documentation (steps 2-3).

In addition, I also exposed Zookeeper's port 2181 and Kafka's port 9092 so that I'll be able to connect to them from a client running on local machine:

$ docker run -d \      -p 2181:2181 \      --net=confluent \      --name=zookeeper \      -e ZOOKEEPER_CLIENT_PORT=2181 \      confluentinc/cp-zookeeper:4.1.0    $ docker run -d \      --net=confluent \      --name=kafka \      -p 9092:9092 \      -e KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181 \      -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092 \      -e KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 \      confluentinc/cp-kafka:4.1.0  

Problem: When I try to connect to Kafka from the host machine, the connection fails because it can't resolve address: kafka:9092.

Here is my Java code:

Properties props = new Properties();  props.put("bootstrap.servers", "localhost:9092");  props.put("client.id", "KafkaExampleProducer");  props.put("key.serializer", LongSerializer.class.getName());  props.put("value.serializer", StringSerializer.class.getName());  KafkaProducer<Long, String> producer = new KafkaProducer<>(props);  ProducerRecord<Long, String> record = new ProducerRecord<>("foo", 1L, "Test 1");  producer.send(record).get();  producer.flush();  

The exception:

java.io.IOException: Can't resolve address: kafka:9092      at org.apache.kafka.common.network.Selector.doConnect(Selector.java:235) ~[kafka-clients-2.0.0.jar:na]      at org.apache.kafka.common.network.Selector.connect(Selector.java:214) ~[kafka-clients-2.0.0.jar:na]      at org.apache.kafka.clients.NetworkClient.initiateConnect(NetworkClient.java:864) [kafka-clients-2.0.0.jar:na]      at org.apache.kafka.clients.NetworkClient.ready(NetworkClient.java:265) [kafka-clients-2.0.0.jar:na]      at org.apache.kafka.clients.producer.internals.Sender.sendProducerData(Sender.java:266) [kafka-clients-2.0.0.jar:na]      at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:238) [kafka-clients-2.0.0.jar:na]      at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:176) [kafka-clients-2.0.0.jar:na]      at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]  Caused by: java.nio.channels.UnresolvedAddressException: null      at sun.nio.ch.Net.checkAddress(Net.java:101) ~[na:1.8.0_144]      at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:622) ~[na:1.8.0_144]      at org.apache.kafka.common.network.Selector.doConnect(Selector.java:233) ~[kafka-clients-2.0.0.jar:na]      ... 7 common frames omitted  

Question: How to connect to Kafka running in Docker? My code is running from host machine, not Docker.

Note: I know that I could theoretically play around with DNS setup and /etc/hosts but it is a workaround - it shouldn't be like that.

There is also similar question here, however it is based on ches/kafka image. I use confluentinc based image which is not the same.

No comments:

Post a Comment