Monday, October 25, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Get result Cannot GET / from Webpack

Posted: 25 Oct 2021 11:14 AM PDT

I'm trying to run webpack with my React Project, but I when I run my project with the commend webpack-dev-serve I get the error:

Cannot GET /  

I try looking into the http://localhost:8080/webpack-dev-serve to look if the routing to the build is incorrect but I don't see a problem? Can someone help me with this problem I am looking around for hours now

webpack.config.js

{    "name": "react-shopping-bag",    "version": "1.0.0",    "description": "",    "main": "index.js",    "scripts": {      "serve": "webpack-dev-server",      "build": "webpack",      "test": "echo \"Error: no test specified\" && exit 1"    },    "keywords": [],    "author": "",    "license": "ISC",    "devDependencies": {      "@babel/core": "^7.15.8",      "@babel/plugin-transform-runtime": "^7.15.8",      "@babel/preset-env": "^7.15.8",      "@babel/preset-react": "^7.14.5",      "@babel/preset-typescript": "^7.15.0",      "@types/react": "^17.0.32",      "@types/react-dom": "^17.0.10",      "babel-loader": "^8.2.3",      "css-loader": "^6.4.0",      "html-webpack-plugin": "^5.4.0",      "react": "^17.0.2",      "react-dom": "^17.0.2",      "style-loader": "^3.3.1",      "typescript": "^4.4.4",      "webpack": "^5.59.1",      "webpack-cli": "^4.9.1",      "webpack-dev-server": "^4.3.1"    }  }  

package.json

{    "name": "react-shopping-bag",    "version": "1.0.0",    "description": "",    "main": "index.js",    "scripts": {      "serve": "webpack-dev-server",      "build": "webpack",      "test": "echo \"Error: no test specified\" && exit 1"    },    "keywords": [],    "author": "",    "license": "ISC",    "devDependencies": {      "@babel/core": "^7.15.8",      "@babel/plugin-transform-runtime": "^7.15.8",      "@babel/preset-env": "^7.15.8",      "@babel/preset-react": "^7.14.5",      "@babel/preset-typescript": "^7.15.0",      "@types/react": "^17.0.32",      "@types/react-dom": "^17.0.10",      "babel-loader": "^8.2.3",      "css-loader": "^6.4.0",      "html-webpack-plugin": "^5.4.0",      "react": "^17.0.2",      "react-dom": "^17.0.2",      "style-loader": "^3.3.1",      "typescript": "^4.4.4",      "webpack": "^5.59.1",      "webpack-cli": "^4.9.1",      "webpack-dev-server": "^4.3.1"    }  }  

http://localhost:8080/webpack-dev-server

http://localhost:8080/build/bundle.js

Why does selenium not memorize my autorization in my Chrome Options?

Posted: 25 Oct 2021 11:14 AM PDT

guys, I have a deal with selenium and just now i faced with a problem:

In my project i have a file where i set all the necessary settings for parser correct working. This file I use everywhere in my program.

In that file is only one class. It named ParsingSettings. And below is my problem fucntion that doesn't save authorization. This function returns a finished webdriver copy:

@staticmethod  def driver_and_driver_settings():        with open('ChromeDriver-and-Options/paths.json', 'r', encoding='utf-8-sig') as file:          paths = json.load(file)        chromedriver_path = paths["Path to chromedriver.exe"]      chromeoptions_path = paths["Path to chromeoptions"]        options = webdriver.ChromeOptions()        options.add_argument(fr"--user-data-dir={chromeoptions_path}")      options.add_argument('--ignore-certificate-errors')      options.add_argument('--ignore-ssl-errors')        return webdriver.Chrome(chromedriver_path, options=options)  

And this is paths.json file which i open in code above:

{      "Path to chromedriver.exe": "C:\\Users\\Nazar\\Downloads\\chromedriver.exe",      "Path to chromeoptions": "C:\\Users\\Nazar\\AppData\\Local\\Google\\Chrome\\User Data\\Default"  }  

Else in my projejct catalog i do have else 3 .py files where in each of them i get webdriver copy by the next method: driver = ParsingSettings.driver_and_driver_settings()

Well, when i do authorization, i see how it finishes always correct, i am about that selenium always pass the login correct. Then webdriver is closing and i start doing the operations in site that require to be logined. And, ofc, when i get some site page it asks me to login. Help me please, this is really important !

Error while starting Kafka on Windows 10 using kafka-server-start.bat on windows. Giving AccessDenied excpetion

Posted: 25 Oct 2021 11:14 AM PDT

Earlier, i tried running kafka 2.13-3.0.0 on windows 10 with Java 8. After making changes to the config\zookeeper.properties and zonfig\server.properties file, adding a path in logs.dir variable, my zookeeper start running, but i am unable to get the kafka serve up, it is always giving the issue mentioned below:

ERROR Error while writing to checkpoint file D:\kafka_2.13-3.0.0\data\kafka\recovery-point-offset-checkpoint (kafka.server.LogDirFailureChannel) java.nio.file.AccessDeniedException: D:\kafka_2.13-3.0.0\data\kafka at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:89) at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103) at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108) at java.base/sun.nio.fs.WindowsFileSystemProvider.newFileChannel(WindowsFileSystemProvider.java:120) at java.base/java.nio.channels.FileChannel.open(FileChannel.java:292) at java.base/java.nio.channels.FileChannel.open(FileChannel.java:345) at org.apache.kafka.common.utils.Utils.flushDir(Utils.java:953) at org.apache.kafka.common.utils.Utils.atomicMoveWithFallback(Utils.java:941) at kafka.server.checkpoints.CheckpointFile.liftedTree1$1(CheckpointFile.scala:114) at kafka.server.checkpoints.CheckpointFile.write(CheckpointFile.scala:92) at kafka.server.checkpoints.OffsetCheckpointFile.write(OffsetCheckpointFile.scala:67) at kafka.log.LogManager.$anonfun$checkpointRecoveryOffsetsInDir$1(LogManager.scala:675) at kafka.log.LogManager.$anonfun$checkpointRecoveryOffsetsInDir$1$adapted(LogManager.scala:671) at scala.Option.foreach(Option.scala:437) at kafka.log.LogManager.checkpointRecoveryOffsetsInDir(LogManager.scala:671) at kafka.log.LogManager.$anonfun$shutdown$9(LogManager.scala:542) at kafka.log.LogManager.$anonfun$shutdown$9$adapted(LogManager.scala:535) at kafka.utils.Implicits$MapExtensionMethods$.$anonfun$forKeyValue$1(Implicits.scala:62) at scala.collection.mutable.HashMap$Node.foreachEntry(HashMap.scala:633) at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:499) at kafka.log.LogManager.shutdown(LogManager.scala:535) at kafka.server.KafkaServer.$anonfun$shutdown$18(KafkaServer.scala:701) at kafka.utils.CoreUtils$.swallow(CoreUtils.scala:68) at kafka.server.KafkaServer.shutdown(KafkaServer.scala:701) at kafka.server.KafkaServer.startup(KafkaServer.scala:435) at kafka.Kafka$.main(Kafka.scala:109) at kafka.Kafka.main(Kafka.scala) [2021-10-25 23:37:06,621] ERROR Disk error while writing recovery offsets checkpoint in directory D:\kafka_2.13-3.0.0\data\kafka: Error while writing to checkpoint file D:\kafka_2.13-3.0.0\data\kafka\recovery-point-offset-checkpoint (kafka.log.LogManager) [2021-10-25 23:37:06,626] ERROR Error while writing to checkpoint file D:\kafka_2.13-3.0.0\data\kafka\log-start-offset-checkpoint (kafka.server.LogDirFailureChannel) java.nio.file.AccessDeniedException: D:\kafka_2.13-3.0.0\data\kafka at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:89) at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103) at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108) at java.base/sun.nio.fs.WindowsFileSystemProvider.newFileChannel(WindowsFileSystemProvider.java:120) at java.base/java.nio.channels.FileChannel.open(FileChannel.java:292) at java.base/java.nio.channels.FileChannel.open(FileChannel.java:345) at org.apache.kafka.common.utils.Utils.flushDir(Utils.java:953) at org.apache.kafka.common.utils.Utils.atomicMoveWithFallback(Utils.java:941) at kafka.server.checkpoints.CheckpointFile.liftedTree1$1(CheckpointFile.scala:114) at kafka.server.checkpoints.CheckpointFile.write(CheckpointFile.scala:92) at kafka.server.checkpoints.OffsetCheckpointFile.write(OffsetCheckpointFile.scala:67) at kafka.log.LogManager.$anonfun$checkpointLogStartOffsetsInDir$1(LogManager.scala:698) at kafka.log.LogManager.$anonfun$checkpointLogStartOffsetsInDir$1$adapted(LogManager.scala:694) at scala.Option.foreach(Option.scala:437) at kafka.log.LogManager.checkpointLogStartOffsetsInDir(LogManager.scala:694) at kafka.log.LogManager.$anonfun$shutdown$9(LogManager.scala:545) at kafka.log.LogManager.$anonfun$shutdown$9$adapted(LogManager.scala:535) at kafka.utils.Implicits$MapExtensionMethods$.$anonfun$forKeyValue$1(Implicits.scala:62) at scala.collection.mutable.HashMap$Node.foreachEntry(HashMap.scala:633) at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:499) at kafka.log.LogManager.shutdown(LogManager.scala:535) at kafka.server.KafkaServer.$anonfun$shutdown$18(KafkaServer.scala:701) at kafka.utils.CoreUtils$.swallow(CoreUtils.scala:68) at kafka.server.KafkaServer.shutdown(KafkaServer.scala:701) at kafka.server.KafkaServer.startup(KafkaServer.scala:435) at kafka.Kafka$.main(Kafka.scala:109) at kafka.Kafka.main(Kafka.scala)

After looking at solutions on net, i found this issue is majorly visible in latest kafka versions, so i installed 2.12-2.0.0 as well (the version which the guy in the tutorial from where i was learning from, used) and tried the same thing again, it is again giving the same error mentioned above. Is it impossible to run kafka on windows 10? Is yes, then what are the alternatives? Any help will be appreciated.

html bootsrap карточки

Posted: 25 Oct 2021 11:14 AM PDT

Парни, помогите пж, я новичок в html) Нужно нормально расположить карточки (по 3 в ряд), но у меня вот так получается. Видимо, проблема у меня в том, что блоки неправильно вложены, но не знаю...Всё перепробовал, идей никаких( Очень нужно)) Скрин: enter image description here

CSS:

body {  background-color: #D1D1D1;  }    div.content {  width:450px;  }  div#sidebar {  float:left;  }  div.content {  float:right;  }    .column {    display: flex;    justify-content: space-between;    float: left;    width: 25%;    padding: 0 10px;  }    .row {    display: flex;    justify-content: space-between;    margin-left: 200px;    padding: 1px 16px;    height: 1000px;  }    #sidebar {    position: left;    margin: 0;    margin-top: 10px;    margin-left: 10px;    padding: 0;    width: 200px;    background-color: #f1f1f1;    height: 100%;    overflow: auto;  }    #sidebar a.active {    background-color: #4CAF50;    color: white;  }    /* Ссылки при наведении мыши */  #sidebar a:hover:not(.active) {    background-color: #555;    color: white;  }    .nav-link {  color: white !important;  font-size: 20px;  font-family: 'Days', sans-serif;  }    .logo {  width: 70%;  margin-left: 20px;  }    #dropdownMenuLink {  font-size: 20px;  margin-top: 18px;  }    .product-grid{      font-family: 'Poppins', sans-serif;      text-align: center;  }  .product-grid .product-image{      overflow: hidden;      position: relative;      z-index: 1;  }  .product-grid .product-image a.image{display: block; }  .product-grid .product-image img{      width: 100%;      height: auto;  }  .product-grid .product-discount-label{      color: #fff;      background: #A5BA8D;      font-size: 13px;      font-weight: 600;      line-height: 25px;      padding: 0 20px;      position: absolute;      top: 10px;      left: 0;  }  .product-grid .product-links{      padding: 0;      margin: 0;      list-style: none;      position: absolute;      top: 10px;      right: -50px;      transition: all .5s ease 0s;  }    .product-grid:hover .product-links{ right: 10px; }  .product-grid .product-links li a{      color: #333;      background: transparent;      font-size: 17px;      line-height: 38px;      width: 38px;      height: 38px;      border: 1px solid #333;      border-bottom: none;      display: block;      transition: all 0.3s;  }  .product-grid .product-links li:last-child a{ border-bottom: 1px solid #333; }  .product-grid .product-links li a:hover{      color: #fff;      background: #333;  }  .product-grid .add-to-cart{      background: #A5BA8D;      color: #fff;      font-size: 16px;      text-transform: uppercase;      letter-spacing: 2px;      width: 100%;      padding: 10px 26px;      position: absolute;      left: 0;      bottom: -60px;      transition: all 0.3s ease 0s;  }  .product-grid:hover .add-to-cart{ bottom: 0; }  .product-grid .add-to-cart:hover{ text-shadow: 4px 4px rgba(0,0,0,0.2); }  .product-grid .product-content{      background: #fff;      padding: 15px;      box-shadow: 0 0 0 5px rgba(0,0,0,0.1) inset;  }  .product-grid .title{      font-size: 16px;      font-weight: 600;      text-transform: capitalize;      margin: 0 0 7px;  }  .product-grid .title a{      color: #777;      transition: all 0.3s ease 0s;  }  .product-grid .title a:hover{ color: #a5ba8d; }  .product-grid .price{      color: #0d0d0d;      font-size: 14px;      font-weight: 600;  }  .product-grid .price span{      color: #888;      font-size: 13px;      font-weight: 400;      text-decoration: line-through;  }  @media screen and (max-width: 990px){      .product-grid{ margin-bottom: 30px; }  }
{% extends "shop/base.html" %}  {% load static %}  {% block title %}      {% if category %}{{ category.name }}{% else %}Products{% endif %}  {% endblock %}  {% block content %}      <div id="main" class="product-list">          <h1>{% if category %}{{ category.name }}{% else %}Products{% endif %}</h1>          <div class="row">              {% for product in products %}                  <div class="col-md-4 col-sm-6">                      <div class="product-grid">                          <div class="product-image">                              <a href="{{ product.get_absolute_url }}" class="image">                                  <img class="card-img-top" src="{% if product.image %}{{ product.image.url }}{% else %}{% static "img/no_image.png" %}{% endif %}">                              </a>                              <a href="" class="add-to-cart">Добавить в корзину</a>                          </div>                              <div class="product-content">                                  <h3 class="title">                                      <a href="{{ product.get_absolute_url }}">                                          {{ product.name }}                                      </a>                                  </h3>                              <div class="price">{{ product.price }}₴</div>                          </div>                      </div>              </div>          </div>      </div>  {% endfor %}  </div>  {% endblock %}

Они расположены в разных блоках..

Regarding how to render openlayers on offscreencanvas

Posted: 25 Oct 2021 11:13 AM PDT

Recently I came across a post that talks about rendering openlayer layers on the offscreencanvas in a web worker (https://openlayers.org/en/latest/examples/offscreen-canvas.html). I would like to adopt this into my project. My plan is first to figure out how the offscreencanvas rendering works and then add the web worker. Right now I am stuck at the first step (rendering layers on offscreencanvas). I tried to follow the pattern in the post but I could not get the layers rendered on the offscreencanvas.

Here's my understanding of the approach used in the post:

  1. In the main thread, create a "dummy" layer and add it to the openlayer map. The "render" hook on the "dummy" layer will be executed. It then passes the framestate to the web worker.
  2. After receiving the framestate, web worker creates the real layers and renders layers on the offscreencanvas defined in the web worker. Then what is rendered on the offscreencanvas is transferred to a bitmap image. This bitmap image is passed back to the main thread.
  3. After receiving the bitmap image, main thread attaches it to the canvas.

I am playing around the offscreencanvas approach on a codesandbox sample.

Here's the codesandbox that contains the correct shapes rendered on canvas: https://codesandbox.io/s/confident-elion-6qzj9?file=/src/index.js

Here's the codesandbox that contains the offscreencanvas approach but the layers are not rendered: https://codesandbox.io/s/mystifying-glitter-4nqn7?file=/src/index.js

I wonder if anyone has experience rendering openlayer layers on offscreencanvas? Any help is greatly appreciated!

What's the cleanest way to turn an object into a list without using a double for loop?

Posted: 25 Oct 2021 11:13 AM PDT

I have an object called 'times', that holds another object called'20102', that holds a list of 3 objects. It looks like this:

times: {  20102: [  obj1:{'key':value},  obj2:{'key':value},  obj3:{'key':value},  ]  }  

However, what I want it to look like is this:

times:[  obj1:{'key':value},  obj2:{'key':value},  obj3:{'key':value},  ]  

I was thinking of doing a double for loop but that's not efficient. What's a better way?

SQL Conditional WHERE clause from a Function

Posted: 25 Oct 2021 11:13 AM PDT

say i have the following function:

function xx_func   return varchar2  is        l_value varchar2(1);    begin        select  'Y'      into    l_value      from    func_table      where   lookup = 'hello';            RETURN l_value;        EXCEPTION      WHEN NO_DATA_FOUND THEN          l_value := 'N';          RETURN l_value;  end xx_func;  

Now, in the current PL/SQL code, we have this:

DECLARE        l_optin varchar2(100);      t_col1  varchar2(100);    BEGIN        l_optin := xx_func;            if l_optin = 'Y' then                select  col1          into    t_col1          from    xx_table_1 xx1              ,   xx_table_2 xx2          where   1=1          and     xx1.t_col2 = xx2.t_col2;                else            select  col1          into    t_col1          from    xx_table_1 xx1              ,   xx_table_2 xx2          where   1=1          and     xx1.t_col2 = xx2.t_col2          and     xx1.t_col3 = xx2.t_col3;                end if;        END;  

I wanted to code it like this to make it shorter:

DECLARE        l_optin varchar2(100);      t_col1  varchar2(100);    BEGIN        l_optin := xx_func;            select  col1      into    t_col1      from    xx_table_1 xx1          ,   xx_table_2 xx2      where   1=1      and     xx1.t_col2 = xx2.t_col2       and     ((xx1.t_col3 = xx2.t_col3 and l_optin = 'N')      OR       (l_optin = 'Y'));                END;      

The code above tells me If l_optin is 'N' then evaluate xx1.t_col3 = xx2.t_col3. if l_optin = 'Y', then don't evaluate xx1.t_col3 = xx2.t_col3. I tried testing it locally and it works but my co-worker says it won't work on all scenarios. The columns are not nullable.

Are there any possible scenarios that this wouldn't handle?

LinkContainer dosn't open new page at the top

Posted: 25 Oct 2021 11:13 AM PDT

Why doens't LinkContainer from react-router-bootstrap open the new page at the top? I have a LinkContainer at the bottom of my page and after clicking it, it redirects me to the bottom of the new page and not to the top, effectively keeping the scrollbar postion on the new page.

I can't find anything about that issue.

How to run and stop an application at certain time on Heroku?

Posted: 25 Oct 2021 11:12 AM PDT

I have an application on Heroku and it is written in python. But, I heard that the free version of Heroku only give us 550 hours so I want to save a little of it.

Is there any way to stop an application at a certain time and rerun it at a certain time on Heroku?

Simplifying if statements for project

Posted: 25 Oct 2021 11:12 AM PDT

I'm new to python and I need some help on this part of my project. How can I simplify this?

 if x == 'C':      if y == 1:          z = 1      if y == 2:          z = 2      if y == 3:          z = 3      if y == 4:          z = 1      if y == 5:          z = 2  

How do you access resources like .json files in a Typescript Nest.js project?

Posted: 25 Oct 2021 11:15 AM PDT

Using this resource https://docs.nestjs.com/cli/monorepo#assets , I'm having a hard time understanding how I'm to access the files from the dist folder.

in the nest-cli.json file:

{     "collection": "@nestjs/schematics",     "sourceRoot": "src",     "compilerOptions": {        "assets": [{"include": "**/*.json", "outDir": "./dist/src"}]     }  }  

I'm then just calling the directory with some code like this

readFileSync(`./dist/src/jsonFiles/${fileName}`  

I'm more used to the Java Maven world where there was a resources folder, and a formal way of accessing files from the resources folder. My concern is that though my current implementation works when I'm running it locally, the files won't be accessible in the production environment because of how the build/deployment process works there.

Is there a proper nest.js way of storing non-TypeScript files like .json files, and how is that way supposed to be done in order to avoid production environment issues?

From a parent folder, how do I get git to go to specific folders that all have the same suffix using a loop?

Posted: 25 Oct 2021 11:14 AM PDT

I have a parent folder named 'gitt' Inside this, I have four subfolders 'gitt1' 'gitt2' 'gitt3' 'gitt4'

Each of these four subfolders have a few folders, including a git repository folder which has the same name as the subfolder +1.0

E.g gitt1 has few folders, including its' repository : gitt11.0

gitt2 has few folders, including its' repository : gitt21.0 etc

From the parent folder gitt, I want a loop command that goes to each of the subfolders, finds the folder with the same name as the subfolder but ending in '1.0' then navigates into it, checks its' git status and goes back two levels up.

I have found this for /f "tokens=*" %a in ('dir /ad /b') do cd %a & git status & cd but it only does git status on the subfolders and does not go into the folders ending with 1.0

I do not want to make the parent folder(gitt) a repository.

How can I get the CustomerID field programmatically?

Posted: 25 Oct 2021 11:12 AM PDT

(Bing Ads API) In order to perform operations such as GetKeywordsByAdGroupId I have to set the CustomerId field in the request header.

This can be found in the UI but we manage several customers and need to get this CustomerID programmatically, to then use it in other requests.

I tried the GetCustomersInfo Service Operation, but the returned ID is not the CustomerID. It's some other system ID (3 digits in this test case).

How can I find the CustomerID field programmatically? I think this is also called the Manager account number.

Post async method invalidate session using Spring Security

Posted: 25 Oct 2021 11:12 AM PDT

I am trying to execute a @async method in a Spring Aplication. The controller even doesn't reach to execute and session is invalidated (I supuse the problem is in chain filtering) and the application is redirected to de login page (result URL: http://localhost:8080/auth/login?logout=true)

I've intented many options but I haven't found someone that works.

Thanks.

CODE: The following code works when the login do de post on my custom Authentication Provider (/auth/dopost) but not /visor/publishenv who executes a async method.

Controller:

@Controller  @RequestMapping("/visor")  public class PublishController  {        @Autowired      private AmbienteClient ambienteClient;        @Autowired      private PublishAsyncService publishService;        @PostMapping("/publishenv")      public String publish(PublishData sala, Model model, RedirectAttributes redirectAttributes)      {          Ambiente ambiente = ambienteClient.getAmbbienteById(sala.getAmbienteid()).getBody();          if (ambiente != null)          {              try              {                  publishService.runTransmitStream(ambiente, sala.getPin());                  redirectAttributes.addFlashAttribute("test2", "Publicando " + ambiente.getNombre());              }              catch (InterruptedException ex)              {                  redirectAttributes.addFlashAttribute("test2", "Ha ocurrido un error interno.");              }          }          else          {              redirectAttributes.addFlashAttribute("test2", "Error al recuperar el ambiente.");          }          return "redirect:/visor/publicar";      }  }  

Service

@Service  public class PublishAsyncService  {        @Autowired      private SalasRepository salasRepo;        @Autowired      private VisorParams vParams;        @Async      public void runTransmitStream(Ambiente ambiente, int pin) throws InterruptedException      {          try          {              DBSalas dbsala = null;              Set<Integer> inUsePorts = new TreeSet<>();              List<DBSalas> salasActivas = salasRepo.findByEstado(1);              for (DBSalas dbs : salasActivas)              {                  if (Objects.equals(dbs.getAmbienteid(), ambiente.getId()))                  {                      dbsala = dbs;                  }                  inUsePorts.add(dbs.getPuerto());              }                if (dbsala == null)              {                  dbsala = DBSalas.builder()                          .ambienteid(ambiente.getId())                          .ambiente(ambiente)                          .usuarioid("test")                          .fec_hora_inicio(new Date())                          .estado(1)                          .pin(pin)                          .puerto(Ports.getAvailablePort(inUsePorts))                          .build();                  dbsala = salasRepo.save(dbsala);                  List<String> lst = new LinkedList<>();                  lst.add(vParams.getCommand());                  lst.add(ambiente.getCamara().getStreamUri(vParams.getInputprotocol()));                  lst.add(":sout=#transcode{vcodec=theo,vb=800,acodec=vorb,ab=128,channels=2,samplerate=44100,scodec=none}:http{mux=ogg,dst=:" + dbsala.getPuerto() + "/" + dbsala.getPin() + "}");                  lst.add(":sout-all");                  lst.add(":sout-keep");                       ProcessBuilder pb = new ProcessBuilder();                  pb.command(lst);                  Process p = pb.start();                  Thread.sleep(3000);                  long pid = p.pid();                  dbsala.setPid(pid);                  dbsala = salasRepo.save(dbsala);                  salasRepo.flush();                  p.waitFor();              }          }          catch (IOException ex)          {              ex.printStackTrace();          }      }  }  

Async config

@Configuration  @EnableAsync  public class PublishAsyncConfig implements AsyncConfigurer  {        @Override      public Executor getAsyncExecutor()      {          ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();          executor.setCorePoolSize(5);          executor.setMaxPoolSize(5);          executor.setThreadNamePrefix("visor-");          executor.setWaitForTasksToCompleteOnShutdown(true);          executor.initialize();          return new DelegatingSecurityContextAsyncTaskExecutor(executor);      }        @Override      public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler()      {          return new AsyncUncaughtExceptionHandler()          {                @Override              public void handleUncaughtException(Throwable ex,                      Method method, Object... params)              {                  System.out.println("Exception: " + ex.getMessage());                  System.out.println("Method Name: " + method.getName());                  ex.printStackTrace();              }          };      }  }  

Auth config

@Configuration  @EnableWebSecurity  public class AuthenticateConfig extends WebSecurityConfigurerAdapter  {        @Autowired      private PortalAuthProvider authProvider;        @Override      protected void configure(AuthenticationManagerBuilder auth) throws Exception      {          auth.authenticationProvider(authProvider);      }        @Override      protected void configure(HttpSecurity http) throws Exception      {          String[] publicUriAcces =          {              "/", "/auth/**", "/css/**", "/js/**", "/img/**"          };            String[] postAcces =          {              "/visor/publishenv", "/auth/dologin"          };            http.authorizeRequests()                  .antMatchers(publicUriAcces).permitAll()                  .antMatchers(HttpMethod.POST, "/visor/publishenv").hasAnyRole("ADMIN", "USER")                  .anyRequest().authenticated()                  .and()                  .formLogin()                  .loginPage("/auth/login")                  .defaultSuccessUrl("/visor/index", true)                  .failureUrl("/auth/login?error=true")                  .loginProcessingUrl("/auth/dologin")                  .permitAll()                  .usernameParameter("Usuario")                  .passwordParameter("SessionId")                  .and()                  .logout()                  .logoutUrl("/logout")                  .logoutSuccessUrl("/auth/login?logout=true")                  .and()                  .csrf().disable()                  ;      }  }  

pairwise comparison with all vectors of a list

Posted: 25 Oct 2021 11:13 AM PDT

I have, for example, a list of 5 vectors and would like to compare each one of them. Example

L = list(c(1:5), c(-1:-5), c(3:7), c(-4:-8), c(5:9))  [[1]]  [1] 1 2 3 4 5    [[2]]  [1] -1 -2 -3 -4 -5    [[3]]  [1] 3 4 5 6 7    [[4]]  [1] -4 -5 -6 -7 -8    [[5]]  [1] 5 6 7 8 9  

I have also a function to make pairwise comparisons between the 5 elements of the list:

foo = function(x, y) t(x) %*% abs(y)  

I would like to apply foo to make pairwise comparisons of my list. For example: Pairwise comparisons (the 'x' and 'y' of foo):

[[1]]and [[2]]  [[1]]and [[3]]  [[1]]and [[4]]  [[1]]and [[5]]   [[2]]and [[3]]  [[2]]and [[4]]  [[2]]and [[5]]  [[3]]and [[4]]  [[3]]and [[5]]  [[4]]and [[5]]  ...  My original file has 1000 elements  

I tried using: lapply(L, foo) but I have the following message error: ```argument "y" is missing, with no default````

How can I apply foo to my list?

Make the Checkout Billing address read only in WooCommerce

Posted: 25 Oct 2021 11:13 AM PDT

We have a website for orders that are then delivered. Now the thing is we want to utilise the details from the My Account Address Billing as the address to ship to , on checkout we want this populated from what's there but not allow the user to make any changes on that check out page Billing form.

This code:

add_action('woocommerce_checkout_fields','customization_readonly_billing_fields',10,1);  function customization_readonly_billing_fields($checkout_fields){      $current_user = wp_get_current_user();;      $user_id = $current_user->ID;      foreach ( $checkout_fields['billing'] as $key => $field ){          if($key == 'billing_address_1' || $key == 'billing_address_2'){              $key_value = get_user_meta($user_id, $key, true);              if( strlen($key_value)>0){                  $checkout_fields['billing'][$key]['custom_attributes'] = array('readonly'=>'readonly');              }          }      }      return $checkout_fields;  }  

Only makes the Address part to not be changed however everything else from first name,last name, cellphone etc is able to be modified.

We need all those fields to be locked just as that code as locked the Address field to read only.

I can't get all metadata tags in Python with Pillow

Posted: 25 Oct 2021 11:12 AM PDT

I'm trying to get all metadata tags from an image using the Pillow library but I get only 5 tags here :

ExifOffset          :140  Make                :HUAWEI  Model               :VOG-L29  Software            :Adobe Lightroom 5.0 (Android)  DateTime            :2019:12:10 11:40:30  

This is my code :

from PIL import Image  from PIL.ExifTags import TAGS      file = 'IMG_20191210_114027.jpg'  img = Image.open(file)    img_exif = img.getexif()    for tag_id in img_exif:      tag=TAGS.get(tag_id,tag_id)      data=img_exif.get(tag_id)      if isinstance(data,bytes):          data=data.decode()      print(f"{tag:20}:{data}")  

and this is the pic I was using IMAGE

If we check this WEBSITE we get more tags like:

Make                    HUAWEI  Model                   VOG-L29  Software                Adobe Lightroom 5.0 (Android)  ModifyDate              2019:12:10 11:40:30  ExposureTime            1/6900  FNumber                 1.6  ExposureProgram         Program AE  DateTimeOriginal        2019:12:10 11:40:30  ShutterSpeedValue       1/6900  ApertureValue           1.6  BrightnessValue         0  ExposureCompensation    0  MaxApertureValue        1.6  MeteringMode            Multi-segment  LightSource             Daylight  Flash                   No Flash  FocalLength             5.6 mm  SubSecTime              758  SubSecTimeOriginal      758  FocalLengthIn35mmFormat 55 mm  LensModel               HUAWEI P30 Pro Rear Main Camera  

How can I get all tags like on metapicz website? And how can I store each tag in different variable?

Injecting Spring managed prototype bean into non-spring managed classes

Posted: 25 Oct 2021 11:13 AM PDT

I've my Logger bean configured as below, for some specific requirements I need to access the Logger into some of the classes that are not managed by Spring. I've done the following steps to do so.

@bean  @scope("prototype")  Logger logger(InjectionPoint injectionPoint){      return LoggerFactory.getLogger(injectionPoint.getMethodParameter().getContainingClass());  }  

I'm trying to inject the logger bean into a non-spring class using the below line.

LOGGER = SpringApplicationContext.getBean(Logger.class);

And my SpringApplicationContext class is below

@component  public class SpringApplicationContext implements ApplicationContextAware {        private static ApplicationContext context;        public static <T extends Object> T getBean(Class<T> beanClass) {          return context.getBean(beanClass);      }         @Override      public void setApplicationContext(ApplicationContext context) throws BeansException {          // store ApplicationContext reference to access required beans later on          SpringApplicationContext.context = context;      }  }  

Since the Logger is a prototype with InjectionPoint argument, I'm getting this error No current InjectionPoint available for method 'logger' parameter 0.

Can someone help to fix this or is there a better way to inject prototype beans with InjectionPoint argument into non-spring classes??

Using predict() method after the training process is completed in TensorFlow

Posted: 25 Oct 2021 11:14 AM PDT

I use a callback to stop the training after my loss goes below a certain value. Once the training is over, I call the predict() method on the training input, however, when I calculate the loss function manually, I get a quiet bad result. Is using predict() wrong? or am I doing something else wrong?

import numpy as np  import random  import tensorflow as tf  from sklearn.metrics import mean_squared_error as my_mse    class stopAtLossValue(tf.keras.callbacks.Callback):          def on_epoch_end(self, batch, logs={}):              eps = 0.00001               if logs.get('loss') <= eps:                   self.model.stop_training = True    model = tf.keras.Sequential([        tf.keras.layers.Flatten(input_shape=(x.shape[1],)),      tf.keras.layers.Dense(8, activation='relu'),      tf.keras.layers.Dense(8, activation='relu'),      tf.keras.layers.Dense(8, activation='relu'),      tf.keras.layers.Dense(16, activation='relu'),      tf.keras.layers.Dense(1)   ])  model.compile(loss='mse',optimizer = tf.keras.optimizers.Adam(learning_rate=0.001))     model.fit(x,  y, epochs=1000, batch_size=1, verbose=1, callbacks=[stopAtLossValue()])  

For example, when I run the code snippet, I reach the loss value desired after 112 epochs.

Epoch 111/1000  20/20 [==============================] - 0s 2ms/step - loss: 0.0294  Epoch 112/1000  20/20 [==============================] - 0s 315us/step - loss: 1.0666e-06  <keras.callbacks.History at 0x153a7b70d30>  

Then, I call the predict() method and compute the loss myself. By the way, my loss function is just a vanilla minimum squared error (MSE). The value that I get is quite high. In fact, if I print the predictions, they seem to be pretty bad even though tf stopped the training due to having a low MSE.

my_mse(y,model.predict(x))  0.027716089  

How to clone a document in MongoDB using python

Posted: 25 Oct 2021 11:13 AM PDT

I am using MongoDB and am trying to clone a document and cannot for the life of me figure this out - what's frustrating me is that I know this is probably very simple indeed but it seems my brain has blocked, so here it is:

I am trying to automate a process which involves cloning a document in the users collection of my Mongo database. The process goes like this:

  1. Clone user with email testing@company.com
  2. Modify some attributes (email, name, etc.) and save the new document

Basically, I am just trying to do what the "clone document" button does in MongoDB Compass but can't figure it out.

My problem is that when I try to do this in python my testing_user keeps being overwritten when I call await db().save(user). I thought about creating a blank new user and adding the attributes manually but I'm sure there must be a better way to do this. All of my google searches have returned hits about cloning entire databases or collections, does someone know of a better way to do this?


Relevant lines from my (not functioning) script:

testing_user = await db().find_one(User, User.email == "testing@company.com")  new_user = testing_user  new_user.attr1 = "foo"  new_user.attr2 = "bar"  await db().save(new_user)  

Can I post a same document to 2 different collections in Firebase?

Posted: 25 Oct 2021 11:14 AM PDT

I am trying to post the same document with same ID's to 2 different collections I tried this:

 db.collection("users").add({      name: "userName",      lastName: "userLastName"  })  .then(userDocRef => {      userDocRef.collection("favFood").add({          favDrink: "userDrink",          favDessert: "userDesert",   })     // then post the same information to different collection   .then(userDocRef => {      db.collection("users__2").add({          name: "userName",          lastName: "userLastName"      }).then(userDocRef => {          userDocRef.collection("favFood").add({              favDrink: "userDrink",              favDessert: "userDesert",      })   })    });     

and It worked Everything was the same But the ID was different is Possible to Have the same ID's?

VBA - Range(Selection, Selection.End(xlUp)).Select is changing the active cell

Posted: 25 Oct 2021 11:12 AM PDT

I'm attempting to select all cells from the current active cell up to the last non-blank cell. I'm doing this with the macro recorder right now because I don't know how to write the code yet. What it's recording when I do Ctrl+Shift+Up is

Range(Selection, Selection.End(xlUp)).Select

This is fine, except it's changing the active cell to the top cell instead of the bottom cell. I've tried going from top to bottom, from left to right, and right to left. Down to up and right to left are the only ones where the active cell changes when I run the code. I have a feeling this is because Excel selects ranges in the positive direction by default, but I don't know how to fix the issue.

cv2 rename ä ö ü to ae oe ue

Posted: 25 Oct 2021 11:13 AM PDT

in the code i'm converting multiple 1-page PDFs into PNG Format. The converting itself works out well with cv2 but sadly many documents (PDFs) names contain german umlauts (ä,ö,ü) and the PNGs end up having special characters.

Example: After converting the PDF (lösung_122.png) to PNG, it looks like this "lösung_122.png". It should be loesung_122.png.

I would like to replace all these characters (ä,ö,ü) in the document titles with ae, oe, ue.

How can i adjust my code to archieve this? What options do i have? Maybe theres a way to rename the documents (PDFs) before converting them?

from pdf2image import convert_from_path  import os  import cv2      if __name__ == '__main__':        # Init      dir_name = os.getcwd()      path_pdf = dir_name + '/data/doc/October' #Folder containing all documents (PDF)      save_path = dir_name + '/data/blanko/' #Folder with all converted doc (PNG)        # Loop sub Folders:      files = os.listdir(path_pdf)      for pdf_file in files:            # Check if PDF file          if pdf_file[-3:] == 'pdf':              images = convert_from_path(path_pdf + '/' + pdf_file, dpi=300, poppler_path='C:/Develop/poppler-0.68.0_x86/poppler-0.68.0/bin')                # Save Images              images[0].save(save_path + 'tmp.png', 'PNG')              img = cv2.imread(save_path + 'tmp.png')              cv2.imwrite(save_path + pdf_file[:-4] + '.png', img)  

Any help appreciated

Regards

I have three tables with schema as t1[uid,name],t2[user,event],t3[eid,organizer]

Posted: 25 Oct 2021 11:13 AM PDT

UID,user,organizer is same data.

Now I want to retrieve data from t1 in such a way that t1.uid=t2.user but t2.user!=t3.organizer. So we can say Extract data from t1 if it is present in t2 but if data in t2 is in t3 then we have to skip.

I have worked with few queries not getting the correct answer.

select distinct uid, name   from user,review   where (user.uid=review.user) join event   on review.user<>event.organizer;    select distinct uid,name   from user,review,event   where user.uid<>event.organizer and user.uid=review.user;  

What is digest in the Superset API?

Posted: 25 Oct 2021 11:13 AM PDT

I want to programmatically generate an image of superset dashboard. I have found one endpoint, but not sure what is the digest in this endpoint. I don't see how to get this digest parameter using any API.

/dashboard/{pk}/thumbnail/{digest}/  

This is the API endpoint to

Compute async or get already computed dashboard thumbnail from cache

But I could not understand what should I put in place of digest parameter here.

Adding a column in AWS glue dynamic dataframe

Posted: 25 Oct 2021 11:13 AM PDT

I am very new to AWS Glue. I am working on a small project and the ask is to read a file from S3 bucket, transpose it and load it in a mysql table. The source data in S3 bucket looks as below

    +----+----+-------+-----+---+--+--------+      |cost|data|minutes|name |sms|id|category|      +----+----+-------+-----+---+--+--------+      |  5 |1000|  200  |prod1|500|p1|service |      +----+----+-------+-----+---+--+--------+  

The target table structure is Product_id, Parameter, value

I am expecting target table to have following values

p1, cost, 5

P1, data, 1000

I am able to load the target table with ID and Value. But I am not able to populate the parameter column. This column is not present in the input data and I want to populate a string depending on which column value I am populating.

Here is the code I used for cost.

import sys  from awsglue.transforms import *  from awsglue.utils import getResolvedOptions  from pyspark.context import SparkContext  from awsglue.context import GlueContext  from awsglue.job import Job    ## @params: [JOB_NAME]  args = getResolvedOptions(sys.argv, ['JOB_NAME'])    sc = SparkContext()  glueContext = GlueContext(sc)  spark = glueContext.spark_session  job = Job(glueContext)  job.init(args['JOB_NAME'], args)    ## @type: DataSource  ## @args: [database = "mainclouddb", table_name = "s3product", transformation_ctx = "datasource0"]  ## @return: datasource0  ## @inputs: []  datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "mainclouddb", table_name = "s3product", transformation_ctx = "datasource0")    ## @type: ApplyMapping  ## @args: [mapping = [("cost", "long", "value", "int"), ("id", "string", "product_id", "string")], transformation_ctx = "applymapping1"]  ## @return: applymapping1  ## @inputs: [frame = datasource0]  applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [("cost", "long", "value", "int"), ("id", "string", "product_id", "string")], transformation_ctx = "applymapping1")    ## @type: SelectFields  ## @args: [paths = ["product_id", "parameter", "value"], transformation_ctx = "selectfields2"]  ## @return: selectfields2  ## @inputs: [frame = applymapping1]  selectfields2 = SelectFields.apply(frame = applymapping1, paths = ["product_id", "parameter", "value"], transformation_ctx = "selectfields2")    ## @type: ResolveChoice  ## @args: [choice = "MATCH_CATALOG", database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "resolvechoice3"]  ## @return: resolvechoice3  ## @inputs: [frame = selectfields2]  resolvechoice3 = ResolveChoice.apply(frame = selectfields2, choice = "MATCH_CATALOG", database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "resolvechoice3")    ## @type: ResolveChoice  ## @args: [choice = "make_cols", transformation_ctx = "resolvechoice4"]  ## @return: resolvechoice4  ## @inputs: [frame = resolvechoice3]  resolvechoice4 = ResolveChoice.apply(frame = resolvechoice3, choice = "make_cols", transformation_ctx = "resolvechoice4")    ## @type: DataSink  ## @args: [database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "datasink5"]  ## @return: datasink5  ## @inputs: [frame = resolvechoice4]  datasink5 = glueContext.write_dynamic_frame.from_catalog(frame = resolvechoice4, database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "datasink5")    job.commit()  

Can somebody help me to add this new column to my data frame so that it can be made available in the table?

Thanks

What are _mm_prefetch() locality hints?

Posted: 25 Oct 2021 11:13 AM PDT

The intrinsics guide says only this much about void _mm_prefetch (char const* p, int i) :

Fetch the line of data from memory that contains address p to a location in the cache heirarchy specified by the locality hint i.

Could you list the possible values for int i parameter and explain their meanings?

I've found _MM_HINT_T0, _MM_HINT_T1, _MM_HINT_T2, _MM_HINT_NTA and _MM_HINT_ENTA, but I don't know whether this is an exhaustive list and what they mean.

If processor-specific, I would like to know what they do on Ryzen and latest Intel Core processors.

Can I use a CSS preprocessor with Polymer?

Posted: 25 Oct 2021 11:13 AM PDT

With Polymer I can include my CSS styles in the element definition simply by adding a <style> tag. What I would like to do though is to add a preprocessor to those styles. Something like https://autoprefixer.github.io/ would be great.

Is there a way to do so without an external CSS file?

How to delete only the content of file in python

Posted: 25 Oct 2021 11:13 AM PDT

I have a temporary file with some content and a python script generating some output to this file. I want this to repeat N times, so I need to reuse that file (actually array of files). I'm deleting the whole content, so the temp file will be empty in the next cycle. For deleting content I use this code:

def deleteContent(pfile):        pfile.seek(0)      pfile.truncate()      pfile.seek(0) # I believe this seek is redundant        return pfile    tempFile=deleteContent(tempFile)  

My question is: Is there any other (better, shorter or safer) way to delete the whole content without actually deleting the temp file from disk?

Something like tempFile.truncateAll()?

Moving average or running mean

Posted: 25 Oct 2021 11:14 AM PDT

Is there a SciPy function or NumPy function or module for Python that calculates the running mean of a 1D array given a specific window?

No comments:

Post a Comment