Monday, October 4, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Number comparison throws 'Text to date conversion' error in redshift

Posted: 04 Oct 2021 08:54 AM PDT

I am running a query in redshift that compares a column with a value and filters the data. But, when i change the number from 1 to 0, redshift throws 'Text to Date Conversion Error'

Any idea on how to resolve this

Vue.Js: Alias configurations

Posted: 04 Oct 2021 08:54 AM PDT

I am trying to make aliases for the components and sub-directories using jsconfig.json in my Vue.js project. But I am getting this error:

jsconfig.json

{      "compilerOptions": {          "baseUrl": ".",          "paths": {              "@components/*": [                  "./src/components/*"              ],          }      },      "exclude": [          "node_modules"      ]  }  

SomeFile.vue

import GuestLayout from '@components/Layouts/GuestLayout';  

Error:

ERROR  Failed to compile with 1 error    ...    To install it, you can run: npm install --save @components/Layouts/GuestLayout  

What am I doing wrong here..?

When to use $ for a variable in bash inside double parenthesis

Posted: 04 Oct 2021 08:54 AM PDT

Why do we need to express a without $ but for RANDOM we do need it?

$((a + 200))  $(($RANDOM%200))  

Block access for traffic to fake PDF pages

Posted: 04 Oct 2021 08:54 AM PDT

I have a lot of 404 hits to my site to PDF pages that have never existed on the site. These are all spammy-subject.pdf URLs. I get tens of these per day, which is much higher than genuine site traffic.

I'm currently adding 410 rewrites for each.

Can I use htaccess rule to totally block this traffic from reaching this site? Before it becomes a 404?

Upgrading react 15 to 17 and it's dependencies

Posted: 04 Oct 2021 08:54 AM PDT

In our existing project we are using react 15, but want to upgrade to new version(react@17 or react@16.8) and it's dependencies, we can't change whole code. kindly suggest ways whether we can upgrade it, if yes then how we can do it with minimal changes.

Copy file from network directory with python

Posted: 04 Oct 2021 08:53 AM PDT

i have this python's program that search (by input) files in specific directory and copy it in destination folder. I dont't know why its dont work with network directory, the program just dont found nothing, how can i use it for copy from big network directory? In my local pc that work fine.

import shutil  import os  from os import path    searchDirs = ["InputDirectory1", "InputDirectory2"]  outputDir = "OutputDirectory"    phrase = input("Enter phrase to search in filenames: ")    if not path.exists(outputDir):  # If output directory doesn't exist, then create one  os.mkdir(outputDir)    for dir in searchDirs:  if path.exists(dir):  # If input directory found then search      elements = os.listdir(dir)      for element in elements:          if os.path.isfile(dir + "/" + element) and phrase in element:              shutil.copy2(dir + "/" + element, outputDir)  else:      print(dir, "not found")  

ng-click for an entire DIV in AngularJS

Posted: 04 Oct 2021 08:53 AM PDT

Whenever any element inside my DIV is clicked I want to execute a function in Angular controller.

How to do this?

Basically I am looking to place a ng-click on DIV element and expect the ng-click event be called when any/all elements nested inside the div are clicked.

How to achieve this requirement?

Laravel middleware doesn't give the access even to the admins

Posted: 04 Oct 2021 08:53 AM PDT

I have dashboard project and I made Admin model and configured it in the auth.php so any of the Auth::functions will execute on it, and now I created middleware IsLogin to redirect the user to the login page if he is not Admin and put all the routes into it and let the login route outside the middleware, but when I login it returns me to login page again and the credentials is right and exists in the database

here is the code

the login route

Route::post('/handle-login', 'App\Http\Controllers\AuthController@handleLogin')->name('auth.handle-login');  

the handleLogin function

public function handleLogin(Request $request) {      $request->validate(['username' => 'required|string|max:100', 'password' => 'required|min:8|max:100']);        $username = $request->username;      $password = $request->password;        $is_login = Auth::attempt(['username' => $username, 'password' => $password]);        if (!$is_login) {          return redirect(route('auth.login'));      }        return redirect(route('users.all'));  }  

middleware code

public function handle(Request $request, Closure $next)  {      if (Auth::check()) {          return $next($request);      }            return redirect(route('users.index'));  }  

How do I prevent webpack from building if there is an error in watch mode?

Posted: 04 Oct 2021 08:53 AM PDT

I want to use webpack to do the following:

If the resulting javascript is valid, then build it. If not, then don't build it.

I was surprised to see that if I have invalid javascript, webpack will still compile the code and build invalid javascript.

I came across the bail config option, but this will prevent me from being able to use watch mode.

I want to watch, and only create the new file if the javascript ends up being valid.

Is there any way of accomplishing this?

Is there a way to create a JSON record to store in elasticsearch that only has the tip UUID?

Posted: 04 Oct 2021 08:53 AM PDT

I'm somewhat familiar to JSON and ElasticSearch through Java but I was requested to make an implementation that helps store elasticsearch data while minding the fact that there will be an expansion of the number of mapped values.

Can anyone give me cookie crumb trail on how to start this and where I should go from there?

How to produce a feature importance plot for numeric predictions in XGBoost?

Posted: 04 Oct 2021 08:54 AM PDT

I am trying to figure out how to retrieve the feature importance plot for a regression-based numeric prediction in XGBoost using R. On the last line of code there is no 'importance' heading and I just wanted to plot a conventional importance plot but I am struggling to see where I am going wrong.

#Train and prediction   train_XG = AE_1[1:52, ]  pred_XG = AE_1[53:56, ]    #Transform into matrices   x_train = xgb.DMatrix(as.matrix(train_XG))  x_pred = xgb.DMatrix(as.matrix(pred_XG))   y_train = train_XG$`Number of A&E attendances Type 1`    #Train model   xgb_trcontrol <- caret::trainControl(    method = "cv",     number = 5,    allowParallel = TRUE,     verboseIter = FALSE,     returnData = FALSE)    #Grid  xgb_grid <- base::expand.grid(    list(      nrounds = c(100, 200),      max_depth = c(10, 15, 20),       colsample_bytree = seq(0.5),       eta = 0.1,      gamma = 0,       min_child_weight = 1,        subsample = 1     ))    #XGB model  xgb_model <- caret::train(    x_train, y_train,    trControl = xgb_trcontrol,    tuneGrid = xgb_grid,    method = "xgbTree",    nthread = 1  )    #Feature importance   xgb_imp = xgb.importance(feature_names = colnames(x_train),                            model = xgb_model$finalModel)    xgb_imp$  

Creating a Computed Int Column in SQL from a Text Column

Posted: 04 Oct 2021 08:55 AM PDT

I want to create a new column in an existing SQL table that utilizes state abbreviations (an existing column) to recode the states into a number (1-50) for statistical analysis that will be performed after exporting the output. Assuming that Alabama is AL = 1 and Wyoming is WY = 50, how would I go about doing this for every state?

Rotate Left k cells where k is greater than the length of the array

Posted: 04 Oct 2021 08:54 AM PDT

If the length of the given array is 6 and the value of k is 7 then the resultant array should be like this [20, 30, 40, 50, 60, 10]. My work.

source = [10, 20, 30, 40, 50, 60]  def rotateLeft(array, k):      tempArray = [0] * len(array)      flag = k      j = len(array)      temp = k - len(array) - 1      temp2 = len(array) - 1      for i in range(j):          tempArray[i] = source[i]          if i + k < j:              source[i] = source[i + k]              source[flag] = tempArray[i]              flag += 1          //Before this everything is alright.          elif k > len(array):              while temp2 >= temp:                  source[temp2] = source[temp2 - temp]                  temp2 -= 1      print(source)      rotateLeft(source, 7)  

Output is [10, 20, 30, 40, 50, 60]. Expected [20, 30, 40, 50, 60, 10]. Can anyone help!!Thank you.

Running Simple Java Programs In Command Line

Posted: 04 Oct 2021 08:53 AM PDT

I'm learning Java and wanted to run this simple program via the command line, and got this error. I have tried putting all my classes within another package but that does not seem to work. It works fine when I run it the typical way in IntelliJ (using f+10). How can I get it to run via the command line? I have tried Java Main.java, Javac Main.java and then java -cp . Main after it has compiled.

PS C:\Users\Cullen\Documents\careerdevs\programs\EncryptionDecryption\src\com\csmithswim> Java Main.class  Error: Could not find or load main class Main.class  Caused by: java.lang.ClassNotFoundException: Main.class  PS C:\Users\Cullen\Documents\careerdevs\programs\EncryptionDecryption\src\com\csmithswim> Javac Main.java  Main.java:9: error: cannot find symbol      Program program = new Program();      ^    symbol:   class Program    location: class Main  Main.java:9: error: cannot find symbol      Program program = new Program();                            ^    symbol:   class Program    location: class Main  2 errors  

error

Sed - find and replace text in html code (from one language to another)

Posted: 04 Oct 2021 08:54 AM PDT

I have html file index.html with english version. I want to create one more language version. I think the best way to do this is use sed. So I want to automatically change language version to another and save it in new file using sed.

For example my index:

    <section class="p-b-10">      <div class="container">      <div class="row">      <div class="col-lg-6">      <div class="heading-text heading-section">      <h2>THE COMPANY</h2>      <span class="lead">The most happiest eu, sodales vel dolor. </span>      </div>      </div>      <div class="col-lg-6 m-t-60">      <div class="p-progress-bar-container title-up small color">      <div class="p-progress-bar" data-percent="100" data-delay="100" data-type="%">      <div class="progress-title">One    </div>      </div>      </div>      <div class="p-progress-bar-container title-up small color">      <div class="p-progress-bar" data-percent="94" data-delay="200" data-type="%">      <div class="progress-title">Two    </div>      </div>      </div>      <div class="p-progress-bar-container title-up small color">      <div class="p-progress-bar" data-percent="78" data-delay="300" data-type="%">      <div class="progress-title">JQUERY    </div>      </div>      </div>      <div class="p-progress-bar-container title-up small color">      <div class="p-progress-bar" data-percent="65" data-delay="400" data-type="%">      <div class="progress-title">Three    </div>      </div>      </div>      <div class="p-progress-bar-container title-up small color">      <div class="p-progress-bar" data-percent="65" data-delay="400" data-type="%">      <div class="progress-title">Three    </div>      </div>      </div>      </div>      </div>      </div>      </section>  

Sed shoud find and replace all given english words to spanish inside my whole code.

The Company (replace to) Empresa One (replace to) Uno Two (replace to) Dos Three (replace to) Tres

Please help! Thank You

mongod command not working after installing on macOS Big Sur, showing this error below ����. Tried everything nothing worked

Posted: 04 Oct 2021 08:53 AM PDT

WITHOUT SUDO {"t":{"$date":"2021-10-04T20:40:10.650+05:30"},"s":"I", "c":"NETWORK", "id":4915701, "ctx":"-","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0,"maxWireVersion":13},"isInternalClient":true}}} {"t":{"$date":"2021-10-04T20:40:10.651+05:30"},"s":"I", "c":"CONTROL", "id":23285, "ctx":"-","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"} {"t":{"$date":"2021-10-04T20:40:10.651+05:30"},"s":"W", "c":"ASIO", "id":22601, "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"} {"t":{"$date":"2021-10-04T20:40:10.651+05:30"},"s":"I", "c":"NETWORK", "id":4648602, "ctx":"main","msg":"Implicit TCP FastOpen in use."} {"t":{"$date":"2021-10-04T20:40:10.653+05:30"},"s":"W", "c":"ASIO", "id":22601, "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"} {"t":{"$date":"2021-10-04T20:40:10.653+05:30"},"s":"I", "c":"REPL", "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","ns":"config.tenantMigrationDonors"}} {"t":{"$date":"2021-10-04T20:40:10.653+05:30"},"s":"I", "c":"REPL", "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","ns":"config.tenantMigrationRecipients"}} {"t":{"$date":"2021-10-04T20:40:10.654+05:30"},"s":"I", "c":"CONTROL", "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":4418,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"leonofjudah-MBP.local"}} {"t":{"$date":"2021-10-04T20:40:10.654+05:30"},"s":"I", "c":"CONTROL", "id":23403, "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"5.0.3","gitVersion":"657fea5a61a74d7a79df7aff8e4bcf0bc742b748","modules":[],"allocator":"system","environment":{"distarch":"x86_64","target_arch":"x86_64"}}}} {"t":{"$date":"2021-10-04T20:40:10.654+05:30"},"s":"I", "c":"CONTROL", "id":51765, "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Mac OS X","version":"20.6.0"}}} {"t":{"$date":"2021-10-04T20:40:10.654+05:30"},"s":"I", "c":"CONTROL", "id":21951, "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{}}} {"t":{"$date":"2021-10-04T20:40:10.655+05:30"},"s":"E", "c":"NETWORK", "id":23024, "ctx":"initandlisten","msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Permission denied"}} {"t":{"$date":"2021-10-04T20:40:10.655+05:30"},"s":"F", "c":"-", "id":23091, "ctx":"initandlisten","msg":"Fatal assertion","attr":{"msgid":40486,"file":"src/mongo/transport/transport_layer_asio.cpp","line":960}} {"t":{"$date":"2021-10-04T20:40:10.655+05:30"},"s":"F", "c":"-", "id":23092, "ctx":"initandlisten","msg":"\n\n***aborting after fassert() failure\n\n"}

WITH SUDO {"t":{"$date":"2021-10-04T20:44:59.700+05:30"},"s":"I", "c":"CONTROL", "id":23285, "ctx":"-","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"} {"t":{"$date":"2021-10-04T20:44:59.702+05:30"},"s":"I", "c":"NETWORK", "id":4915701, "ctx":"main","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0,"maxWireVersion":13},"isInternalClient":true}}} {"t":{"$date":"2021-10-04T20:44:59.706+05:30"},"s":"W", "c":"ASIO", "id":22601, "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"} {"t":{"$date":"2021-10-04T20:44:59.706+05:30"},"s":"I", "c":"NETWORK", "id":4648602, "ctx":"main","msg":"Implicit TCP FastOpen in use."} {"t":{"$date":"2021-10-04T20:44:59.708+05:30"},"s":"W", "c":"ASIO", "id":22601, "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"} {"t":{"$date":"2021-10-04T20:44:59.708+05:30"},"s":"I", "c":"REPL", "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","ns":"config.tenantMigrationDonors"}} {"t":{"$date":"2021-10-04T20:44:59.708+05:30"},"s":"I", "c":"REPL", "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","ns":"config.tenantMigrationRecipients"}} {"t":{"$date":"2021-10-04T20:44:59.708+05:30"},"s":"I", "c":"CONTROL", "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":4430,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"leonofjudah-MBP.local"}} {"t":{"$date":"2021-10-04T20:44:59.709+05:30"},"s":"I", "c":"CONTROL", "id":23403, "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"5.0.3","gitVersion":"657fea5a61a74d7a79df7aff8e4bcf0bc742b748","modules":[],"allocator":"system","environment":{"distarch":"x86_64","target_arch":"x86_64"}}}} {"t":{"$date":"2021-10-04T20:44:59.709+05:30"},"s":"I", "c":"CONTROL", "id":51765, "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Mac OS X","version":"20.6.0"}}} {"t":{"$date":"2021-10-04T20:44:59.709+05:30"},"s":"I", "c":"CONTROL", "id":21951, "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{}}} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"E", "c":"CONTROL", "id":20557, "ctx":"initandlisten","msg":"DBException in initAndListen, terminating","attr":{"error":"NonExistentPath: Data directory /data/db not found. Create the missing directory or specify another path using (1) the --dbpath command line option, or (2) by adding the 'storage.dbPath' option in the configuration file."}} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"REPL", "id":4784900, "ctx":"initandlisten","msg":"Stepping down the ReplicationCoordinator for shutdown","attr":{"waitTimeMillis":15000}} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"COMMAND", "id":4784901, "ctx":"initandlisten","msg":"Shutting down the MirrorMaestro"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"SHARDING", "id":4784902, "ctx":"initandlisten","msg":"Shutting down the WaitForMajorityService"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"NETWORK", "id":20562, "ctx":"initandlisten","msg":"Shutdown: going to close listening sockets"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"NETWORK", "id":4784905, "ctx":"initandlisten","msg":"Shutting down the global connection pool"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"CONTROL", "id":4784906, "ctx":"initandlisten","msg":"Shutting down the FlowControlTicketholder"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"-", "id":20520, "ctx":"initandlisten","msg":"Stopping further Flow Control ticket acquisitions."} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"NETWORK", "id":4784918, "ctx":"initandlisten","msg":"Shutting down the ReplicaSetMonitor"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"SHARDING", "id":4784921, "ctx":"initandlisten","msg":"Shutting down the MigrationUtilExecutor"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"ASIO", "id":22582, "ctx":"MigrationUtil-TaskExecutor","msg":"Killing all outstanding egress activity."} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"COMMAND", "id":4784923, "ctx":"initandlisten","msg":"Shutting down the ServiceEntryPoint"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"CONTROL", "id":4784925, "ctx":"initandlisten","msg":"Shutting down free monitoring"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"CONTROL", "id":4784927, "ctx":"initandlisten","msg":"Shutting down the HealthLog"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"CONTROL", "id":4784928, "ctx":"initandlisten","msg":"Shutting down the TTL monitor"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"CONTROL", "id":4784929, "ctx":"initandlisten","msg":"Acquiring the global lock for shutdown"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"-", "id":4784931, "ctx":"initandlisten","msg":"Dropping the scope cache for shutdown"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"FTDC", "id":4784926, "ctx":"initandlisten","msg":"Shutting down full-time data capture"} {"t":{"$date":"2021-10-04T20:44:59.711+05:30"},"s":"I", "c":"CONTROL", "id":20565, "ctx":"initandlisten","msg":"Now exiting"} {"t":{"$date":"2021-10-04T20:44:59.712+05:30"},"s":"I", "c":"CONTROL", "id":23138, "ctx":"initandlisten","msg":"Shutting down","attr":{"exitCode":100}}

Apache rewrite with and without Parameters

Posted: 04 Oct 2021 08:54 AM PDT

I need to rewrite URL's with and without parameters in the URL, I configured a RewriteMap via dbm

kronen-und-gehaeusetuben/wasserdicht-typ-pbbz.html => Produkte/Werke-Uhrenersatzteile/Schraubkronen-PBBZ-wasserdicht/  kronen-und-gehaeusetuben/wasserdicht-typ-pbbz.html?___store=default => Produkte/Werke-Uhrenersatzteile/Schraubkronen-PBBZ-wasserdicht/  kronen-und-gehaeusetuben/wasserdicht-typ-pbbz.html?___store=en => en/Products/Watch-replacement-parts/Watch-crowns/Screw-on-crowns/Screw-on-crowns-PBBZ-waterproof/  kronen-und-gehaeusetuben/wasserdicht-typ-pbbz.html?___store=fr => fr/Produits/Couronnes/Couronnes-vissees/Couronnes-vissees-PBBZ-etanches/  kronen-und-gehaeusetuben/wasserdicht-typ-pbbz.html?___store=es => es/Productos/Movimientos-Piezas/Piezas-de-repuesto-para-relojes/Coronas/Coronas-a-rosca/Coronas-a-rosca-PBBZ-hermeticas/  
<VirtualHost *:80>      DocumentRoot "/var/www/html"      #ServerName www.example.com      RewriteMap rewrite_DB "dbm:conf/rewrite.dbm"      <Directory "/var/www/html">          Options FollowSymLinks Includes ExecCGI          AllowOverride All          DirectoryIndex index.html          RewriteEngine On          LogLevel alert rewrite:trace4          RewriteBase /          RewriteRule "^(.*html)" "${rewrite_DB:$1|/}" [L,NC,R=301]      </Directory>  </VirtualHost>  

It works but how should I handle the parameters like ?___store=default? All HTML files without parameters work but not those with ?___store=default or similar.

How to implement .includes in JavaScript

Posted: 04 Oct 2021 08:54 AM PDT

I'm developing a very simple chatbot using JS and HTML, and I have the following code which outputs an "answer" as a reply to what the user has asked. This works fine but when I try to implement .includes to check if a certain phrase has been asked it no longer outputs anything. For example, if the user asks "can you help" it should output the same answer as "help" since it contains the "help" keyword. Without .includes the code works fine.

function talk() {      var know = {      "Hey": "Hello!",      "Help": `You can find help by clicking <a href='https://addressname.com'target="_blank">here</a>`    };      var user = document.getElementById('userBox').value;        document.getElementById('chatLog').innerHTML = user + "<br>";        if (user in know) {      document.getElementById.includes('chatLog').innerHTML = know[user] + "<br>";    } else {      document.getElementById('chatLog').innerHTML = "I do not understand.";    }    }  

Is there a way for a consumer to stop listening to a topic by just using config/properties file?

Posted: 04 Oct 2021 08:54 AM PDT

Is there a way we can put in the properties/config file to stop a consumer from listening to a topic? I just want to know whether I can have an option that I can just simply like "Turn on/off" Kafka without having to build and deploy my project.

Sending dates into postgresql

Posted: 04 Oct 2021 08:53 AM PDT

I have some doubts about this one, I already saw the others topics but I still can't make my code work properly.

I want to send dates into my DB using JDBC, I'm using a jTextField (or a JformattedField, trying both ways) and all I get is an error by the database, Because I'm sending text instead date, so, how can I send dates ?

EDIT1: I'm trying to send date of birth.

Already made some tries, that's why I have: SimpleDateFormat formatter = new SimpleDateFormat ("dd/MM/yyyy"); java.sql.Date data = new java.sql.Date(formatter.parse().getTime());

try {             conecta.conn.setAutoCommit(false);          PreparedStatement pst = conecta.conn.prepareStatement("INSERT INTO cad_pessoa(cad_cpf,cad_nome, cad_idade, cad_apelido, cad_data) values (?,?,?,?,?)");                      pst.setString(1, jFormattedTextFieldCPF.getText()); //pega o texto insirido e armazena no banco de dados          pst.setString(2, jTextFieldNOME.getText()); //pega o texto insirido e armazena no banco de dados          pst.setString(3, jTextFieldIDADE.getText()); //pega o texto insirido e armazena no banco de dados          pst.setString(4, jTextFieldApelido.getText());//pega o texto insirido e armazena no banco de dados          SimpleDateFormat formatter  = new SimpleDateFormat ("dd/MM/yyyy");          java.sql.Date data = new java.sql.Date(formatter.parse().getTime());          pst.setDate(5, formatter.parse(jFormattedTextFieldDATA.getText())); //pega o texto insirido e armazena no banco de dados          pst.executeUpdate(); //executa o SQL                              conecta.conn.commit();                              jFormattedTextFieldCPF.setText(""); //deixa o campo vazio          jTextFieldNOME.setText(""); //deixa o campo vazio          jTextFieldIDADE.setText(""); //deixa o campo vazio          jFormattedTextFieldDATA.setText("");          jTextFieldApelido.setText(""); //deixa o campo vazio                    jFormattedTextFieldCPF.setEnabled(false);          jTextFieldNOME.setEnabled(false);          jTextFieldIDADE.setEnabled(false);          jFormattedTextFieldDATA.setEnabled(false);          jTextFieldApelido.setEnabled(false);          JOptionPane.showMessageDialog(null, "Salvo!");                                                                                          } catch (SQLException ex) {          JOptionPane.showMessageDialog(rootPane, "Erro!\n" +ex);        }  

asp.NET 4.8 WebRequest errors with "The underlying connection was closed: An unexpected error occurred on a send."

Posted: 04 Oct 2021 08:53 AM PDT

On one particular website on my web server WebRequests have started throwing the following error: "The underlying connection was closed: An unexpected error occurred on a send."

  • My asp.NET website is running framework version 4.8.
  • I am requesting a page on the same website that is doing the request.
  • This code has been in place for years and has suddenly stopped working on this website
  • This same code works fine on a different website running on the same webserver

Request code:

Dim myReq As System.Net.WebRequest = System.Net.WebRequest.Create("https://example.com")  myReq.Method = "GET"    myReq.ContentType = "text/html; encoding='utf-32'"      Dim wr As System.Net.WebResponse = myReq.GetResponse()  Dim receiveStream As System.IO.Stream = wr.GetResponseStream()  Dim reader As System.IO.StreamReader = New System.IO.StreamReader(receiveStream, Encoding.UTF8)  Dim content As String = reader.ReadToEnd()  

I have tried adding the following to the page doing the request, and the global.asax, but it did not work. It should not be required, though, because I am using .net 4.8:

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12  

How to use first and last option to create new variable in Power Bi?

Posted: 04 Oct 2021 08:54 AM PDT

I want to create a new variable based on the first and last records of each ID variable. A sample reference table is given below that will make it easier to understand the problem.

Table: -

enter image description here

    pkBookingItemID StartTime   EndTime BusinessStartTime   BusinessEndTime      3417              13:45       14:00        09:00           17:00      3417              13:45       14:00        09:00           17:00      3417              13:45       14:00        09:00           17:00      3417              13:45       14:00        09:00           17:00      3418              10:00       15:00        09:00           16:00      3418              10:00       15:00        09:00           16:00      3418              10:00       15:00        09:00           16:00  

I want to create variables New_BusinessStartTime and New_BusinessEndTime based on pkBookingItemID occurance.

Desired output table:-

enter image description here

pkBookingItemID StartTime   EndTime BusinessStartTime   BusinessEndTime New_BusinessStartTime   New_BusinessEndTime  3417               13:45      14:00           09:00              17:00           13:45              17:00  3417               13:45      14:00           09:00              17:00           09:00              17:00  3417               13:45      14:00           09:00              17:00           09:00              17:00  3417               13:45      14:00           09:00              17:00           09:00              14:00  3418               10:00      15:00           09:00              16:00           10:00              16:00  3418               10:00      15:00           09:00              16:00           09:00              16:00  3418               10:00      15:00           09:00              16:00           09:00              15:00  

I have to achieve this by M query in Power BI. I tried so far to get the desired table but could not get any success.

New_BusinessStartTime  =      if [pkBookingItemID] = [pkBookingItemID.First]      then [StartTime] else [BusinessStartTime]        New_BusinessEndTime =      if [pkBookingItemID] = [pkBookingItemID.Last]      then [EndTime] else [BusinessEndTime]  

.First and .Last parts are not giving results as I thought initially. Can anyone help out with the problem or offer a suggestion to solve this problem?

Is there a way to acknowledge specific message in Pulsar?

Posted: 04 Oct 2021 08:53 AM PDT

Is there a way to acknowledge a particular message in a topic on behalf of a specific subscriber?

I couldn't find anything related to this in the api, both the admin and client api.

Index.html not loading when npx serve is run (caddy, nodejs)

Posted: 04 Oct 2021 08:54 AM PDT

I'm running fastify on node.js and using Caddy server for reverse proxying localhost to a domain (authsvc.dev) that serves up an index.html file in this UI project.

All was running fine until a couple days ago. Now, when I run npm run ui I get the following error messages in the console. The index.html file is not being served up. The src/public/index.html file exists and was working a couple days ago, but maybe some issue with npx serve {{path-to-file}}? Please help!

I do have Caddy running with a reverse proxy set up.

{    local_certs  }    authsvc.dev {    reverse_proxy 127.0.0.1:5000  }    api.authsvc.dev {    reverse_proxy 127.0.0.1:4000  }  
ERROR: Not able to read /{{path-to-proj}}/ui/src/public/index.html/serve.json: ENOTDIR: not a directory, open '/{{path-to-proj}}/ui/src/public/index.html/serve.json'  npx serve src/public/index.html exited with code 1  

Not sure where or why index.html/serve.json is trying to be read and how to go about fixing it.

I'm running macOs Big Sur v11.6

Some things I've tried.

  1. Deleting node_modules and npm install
  2. Deleting package-lock.json and npm install
  3. updating to latest npm
  4. Changing to different version of node (now on v14.15.1)
  5. Clearing npm cache rm -rf ~/.npm npm clear cache
  6. npx serve src/public/ -- allows me to see when I'm at localhost:5000, but not authsvc.dev

package.json scripts

  "scripts": {      "all": "concurrently \"npm run server\" \"cd ../ui\" \"npm run ui\"",      "server": "cd ../api && npm run start",      "ui": "concurrently \"nodemon src/index.js\" \"npx serve src/public/index.html\"",      "ui1": "nodemon src/index.js",      "ui2": "npx serve src/public/",      "caddy": "caddy run",      "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watchAll"    },    "dependencies": {      "colors": "^1.4.0",      "concurrently": "^6.2.2",      "cross-fetch": "^3.1.4",      "dotenv": "^10.0.0",      "fastify": "^3.22.0",      "fastify-static": "^4.2.3"    }  

results of npm run all

Invoking Django-river manually for workflow management

Posted: 04 Oct 2021 08:54 AM PDT

Our application uses Django_river for workflow management. And currently, the river is being invoked based on the post save signal created by Django. But for performance-related issues, we had to use the bulk option for inserting data that does not support signals by default. We have generated signals manually, but this is slowing down our system.

Is there a way to manually invoke the river from our code based on the business conditions? The river documentation is minimalistic, hence.

Manual Post Save Signal creation makes the application slow, Django

Posted: 04 Oct 2021 08:53 AM PDT

We have a Django application that uses Django-river for workflow management. For performance improvement, we had to use bulk_create. We need to insert data into a couple of tables and several rows in each. Initially, we were using the normal .save() method and the workflow was working as expected (as the post save() signals were creating properly). But once we moved to the bulk_create, the performance was improved from minutes to seconds. But the Django_river stopped working and there was no default post save signals. We had to implement the signals based on the documentation available.

class CustomManager(models.Manager):      def bulk_create(items,....):           super().bulk_create(...)           for i in items:                [......] # code to send signal  

And

class Task(models.Model):      objects = CustomManager()      ....  

This got the workflow working again, but the generation of signals is taking time and this destroys all the performance improvement gained with bulk_create. So is there a way to improve the signal creation?

More details

def post_save_fn(obj):      post_save.send(obj.__class__, instance=obj, created=True)     class CustomManager(models.Manager):      def bulk_create(self, objs, **kwargs):          #Your code here          data_obj = super(CustomManager, self).bulk_create(objs,**kwargs)          for i in data_obj:              # t1 = threading.Thread(target=post_save_fn, args=(i,))              # t1.start()              post_save.send(i.__class__, instance=i, created=True)           return data_obj                      class Test(Base):       test_name = models.CharField(max_length=100)      test_code = models.CharField(max_length=50)      objects = CustomManager()      class Meta:          db_table = "test_db"  

Biomod2 formatting error: incorrect number of layer names

Posted: 04 Oct 2021 08:53 AM PDT

I keep running into an error while trying to run the BIOMOD_FormatingData() function.

I have checked through all arguments and removed any NA values, the explanatory variables are the same for both the testing and training datasets (independent datasets), and I've generated pseudo-absence data for the evaluation dataset (included in eval.resp.var). Has anyone run into this error before? and if so, what was the issue related to? This is my first time using Biomod2 for ensemble modeling and I've run out of ideas as to what could be causing this error!

Here is my script and the subsequent error:

geranium_data <-   +   BIOMOD_FormatingData(  +     resp.var = SG.occ.train['Geranium.lucidum'],  +     resp.xy = SG.occ.train[, c('Longitude', 'Latitude')],  +     expl.var = SG.variables,   +     resp.name = "geranium_data",  +     eval.resp.var = SG.test.data['Geranium.lucidum'],   +     eval.expl.var = SG.variables,   +     eval.resp.xy = SG.test.data[, c('Longitude', 'Latitude')],   +     PA.nb.rep = 10,   +     PA.nb.absences = 4650,   +     PA.strategy = 'random',  +     na.rm = TRUE  +   )    -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= geranium_data Data Formating -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=  Response variable name was converted into geranium.data     > Pseudo Absences Selection checkings...     > random pseudo absences selection     > Pseudo absences are selected in explanatory variablesError in `names<-`(`*tmp*`, value = c("calibration", "validation")) : incorrect number of layer names  

how can I create response curves using biomod2?

Posted: 04 Oct 2021 08:53 AM PDT

I am using R version 3.6.0. I have made some biomod models. There is one factor among my environmental variables. When I am trying to create response plots this error comes up:

Error in subinfo == "MinMax" :     comparison (1) is possible only for atomic and list types  

The code I use is:

SumGBMs <- BIOMOD_LoadModels(WgBiomodModelOut, models='GBM')  SumGBM_repcurves <- response.plot2(model= SumGBMs ,                                    Data = WgBiomodModelOut,                                    show.variables= get_formal_data(WgBiomodModelOut, dem),                                    fixed.var.metric = 'median',                                    col = c("blue", "red"),                                    legend = TRUE,                                    plot=T)  

although I don't think that's the problem, but I have tried to use github biomod2:

devtools::install_github("biomodhub/biomod2", dependencies = TRUE)  

but it did not work and the following erro0r showed up:

Error: Failed to install 'biomod2' from GitHub:    (converted from warning) installation of package 'C:/Users/NP/AppData/Local/Temp/RtmpAtIiba/file70c6f00293b/biomod2_3.4-03.tar.gz' had non-zero exit status  

Can you tell me what goes wrong?

Thanks

How to return unauthorized using Laravel API Authentication

Posted: 04 Oct 2021 08:54 AM PDT

I am using Laravel API authentication with a token. (as explained here: https://laravel.com/docs/5.8/api-authentication#protecting-routes)

I am running some tests with Postman and it works fine. When I try to access the route without a valid token, I see that the response is the (html of the) login page of my app. How can I return a Unauthorized message instead of the complete login page? Do I have to create a custom middleware?

Controller

class ExampleController extends Controller  {      public function __construct()      {          $this->middleware('auth:api');      }        public function show(Request $request) {          return response()->json($request->user()->name);      }   }  

Moodle Baracuda check bypass or highest antelope version

Posted: 04 Oct 2021 08:54 AM PDT

On our server, we cannot change any database settings and newer versions of Moodle require the barracuda file format as opposed to antelope.

We are running 3.4.1. 3.5+ requires innoDB. I thought a point upgrade to 3.4.4 would be ok, but that also has the same problems.

What is the highest version I could use? Or is it possible to bypass these checks and continue using current database?

Your database uses Antelope as the file format. Full UTF-8 support in MySQL and MariaDB requires the Barracuda file format. Please switch to the Barracuda file format. See the documentation MySQL full unicode support for details.    Check  mysql_full_unicode_support#Large_prefix   this test must pass  For full support of UTF-8 both MySQL and MariaDB require you to change your MySQL setting 'innodb_large_prefix' to 'ON'. See the documentation for further details.  

No comments:

Post a Comment