Saturday, August 14, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Connect to 000webhost files when the file or folder is password protect with csharp

Posted: 14 Aug 2021 08:02 AM PDT

So I have a file in https://files.000webhost.com/ that is a protected folder or file. and I want to connect to it and get the string in the file.

But it's is password protected. how do I connect to the file when there's password protection to it?

Python Edgar asks for useragent

Posted: 14 Aug 2021 08:01 AM PDT

I ran the following command:

import edgar import pandas as pd edgar.download_index('/Users/myusername/Desktop/Desktop', 2010,skip_all_present_except_last=False)

It's throwing the following error asking for user_agent. Please clarify where can I get that useragent and guide if I am getting wrong on anything else? The error message is:

TypeError Traceback (most recent call last) in 1 import edgar 2 import pandas as pd ----> 3 edgar.download_index('/Users/myusername/Desktop/Desktop', 2010,skip_all_present_except_last=False)

TypeError: download_index() missing 1 required positional argument: 'user_agent'

Thanks for your help Thayyib

Why WhenAll working in C# desktop application and not working in Windows services

Posted: 14 Aug 2021 08:01 AM PDT

I want create windows service which execute list of services. For example, I have 3 vawe of services. In each wave I have few services. I want execute wave1 - wave2- wave3 serial and service under waves in paralel. Wave 2 starts when Wave1 finished etc... Code below working in C# desktop windows application but not working as windows service. Any idea what is problem?

Task<IEnumerable<string>> result = start_ps_scheduler(for_running_paralel);  await result;    private async Task<IEnumerable<string>>start_ps_scheduler(IOrderedEnumerable<TreeNode>fl)  {              List<Task<string>> listOfTasks = new List<Task<string>>();              foreach (var thing in for_running_local)              {                  listOfTasks.Add(execute_service_task((Sofi_Tree.SofiNode)thing.Tag));              }              return await Task.WhenAll(listOfTasks);  }    private Task<string> execute_service_task(Sofi_Tree.SofiNode current_Sofi_node)  {  return...  }    

On the codechef aug long challenge, AUG21C >CHFINVNT, this is the code i wrote, but the submit dosent work. Its showing RE(NZEC) error

Posted: 14 Aug 2021 08:01 AM PDT

On the codechef aug long challenge, AUG21C >CHFINVNT, this is the code i wrote, but the submit dosent work. Its showing RE(NZEC) error. The out put still works.... but it wont submit. Please Help. .....................................................................................................................................................................................................

/* package codechef; // don't place package name! */    import java.util.*;  import java.lang.*;  import java.io.*;    /* Name of the class has to be "Main" only if the class is public. */  class Codechef  {      public static void main (String[] args) throws java.lang.Exception      {          // your code goes here          Scanner scr = new Scanner(System.in);                    try {          int T = scr.nextInt();                                    while(T-- > 0)          {              int N = scr.nextInt();              int p = scr.nextInt();              int K = scr.nextInt();                                          int[] A = new int[N];                            for(int i=0; i<N; i++)              {                  A[i%K]++;              }                            int sum=0;                            for(int i=0; i<p%K; i++)              {                  sum+=A[i];              }                            int add = (p - (p%K)) / K;              add++;                            sum = sum + add;                            System.out.println(sum);                                                                  }          }catch(Exception e){}      }  }  

how to get information about which user is logged in drupal portal

Posted: 14 Aug 2021 08:00 AM PDT

I have Drupal installed and dedicated non-Drupal website, where I want to check if the user is logged in Drupal website, tells which user is it and I use that information on the non-Drupal website to authenticate user, I read all about JSON: API web services at Drupalize, but I have no idea how exactly use it in my project, or do I even need that. would be grateful for any advice.

Run Mediapipe pose tracker on Colab as a continuous video stream

Posted: 14 Aug 2021 08:00 AM PDT

I am running a pose tracking application on Colab (with mediapipe). It does not show a continuous video, instead it runs my video frame by frame, showing them in succession in the output section below my block of code. So it becomes very slow at processing a single video and I have the output section full of frames, so I have to scroll a lot of stuff to check the top or the bottom of the output section. The goal is to have a video stream like a normal linux application on my PC. This is the main() file of my application

cap = cv2.VideoCapture('1500_doha.mp4')  pTime = 0  detector = poseDetector()  while cap.isOpened():        success, img = cap.read()      width,height, c=img.shape      img = detector.findPose(img)      lmList = detector.findPosition(img, draw=False)      angle=detector.findAngle(img, 11, 13, 15) #attenzione, cambia braccio ogni tanto!!      cTime = time.time()      fps = 1 / (cTime - pTime)      pTime = cTime      text=cv2.putText(img, str(int(fps)), (70, 50), cv2.FONT_HERSHEY_PLAIN, 3,                  (255, 0, 0), 3)      cv2_imshow(img)      cv2.waitKey(10)  

The problem is clearly in cv2_imshow(), because if I run a YOLO-V4 box detector I don't need this command and I obtain a continuous stream. Have you any suggestions? Is there already a solution online? I did not find it! Colab is amazing because of cloud computing, but it has this little, hidden problems. If you need more info, let me know! Here you find part of the output box of my google colab.

Here you find the complete file https://colab.research.google.com/drive/1uEWiCGh8XY5DwalAzIe0PpzYkvDNtXID#scrollTo=HPF2oi7ydpdV

Thank you for your help!

locating and emailing data from a database

Posted: 14 Aug 2021 08:02 AM PDT

I have a site where users clock in and out for work.

I save theres times under the following headings

ID (Key) | Date | Day | userid | Start-time | End-time | total

my issue is every two weeks i need the site to email me all of my employees start and end times for the past two weeks.


after connecting to the database i have tried this:

    if ($result->num_rows > 0 ){       //period = start of pay period      $period = strtotime($row['period']);       //start = 14 days previous to current period start     $start = $period - 1209500;           while ($start < $period){             $sql = "SELECT * FROM `clocks` WHERE ``date` = '".gmdate("d.m.Y", $start)."'";           $res = $conn->query($sql);             if ($res->num_rows > 0){             while($row = $res->fetch_assoc()) {              $line = "{$row['userid']} {$row['date']} {$row['start']} {$row['finish']} {$row['breakstart']}";              echo $line;              }                         } else {             }        $start = $start + 86400;         }  

there are results in my db that should have echo'd as seen before but im not having anything showing. there is also no error log.

thank you for your help

How can I configure my connector to run in specific worker group in multicluster connect environment in distributed kafka connect?

Posted: 14 Aug 2021 08:00 AM PDT

As per the documentation, worker service is set to run before adding connectors. Suppose I am running worker-a with group.id "cluster-a" and worker-b with group.id "cluster-b" on three distributed VM's. What is the configuration that makes connectors to choose their worker group.

Suppose I need to configure debezium mysql connector's tasks to run on cluster-a and jdbc connector's all tasks on cluster-b. How should I do it?

Thanks in advance.

Can't type in react input field

Posted: 14 Aug 2021 08:01 AM PDT

I have a simple form with an input field that I can't type on. I first thought the problem was with the onChange or the value props that were setting the input to readonly, but the fact is that I cant type with the browser suggestions and the state updates perfectly (See gif here) it's just that I won't let me type with the keyboard, even after reloading the page.

I also have a Login page that works perfectly except when I log out and redirect back to that page, it won't work until I reload the page, now it will work.

<input  value={name}  onChange={handleChange}  name="name"  />  
const [name, setName] = useState("");    const handleChange = (e:any) => {      setName(e.target.value);  }  

Weird thing is that it's in like a readonly state but when I use browser suggestions it works and updates the state.

t.test outputs in the `table` package in R

Posted: 14 Aug 2021 08:02 AM PDT

So here's a sample of the data I am working with:

> dput(sample_data)  structure(list(youngTreatment = structure(c(NA, 1, 0, 1, 0, 1,   0, 1, 1, 0, 1, 1, 0, 0, NA, NA, NA, NA, 1, 1), format.stata = "%10.0g"),       candTrustworthy = structure(c(0, 0, 0, 0, 0, 0, 0, 1, 0,       1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), format.stata = "%10.0g"),       candKnowledgeable = structure(c(1, 0, 0, 0, 1, 0, 0, 0, 0,       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1), format.stata = "%10.0g"),       candQualified = structure(c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0,       0, 0, 0, 0, 0, 0, 0, 0, 0, 1), format.stata = "%10.0g"),       candConservative = structure(c(0, 0, 0, 0, 1, 0, 0, 0, 0,       0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0), format.stata = "%10.0g"),       candLiberal = structure(c(0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,       0, 0, 0, 0, 0, 0, 0, 0, 0), format.stata = "%10.0g"), candInexperienced = structure(c(0,       1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0), format.stata = "%10.0g"),       candPrincipled = structure(c(1, 1, 0, 0, 0, 0, 1, 0, 0, 0,       0, 0, 0, 1, 1, 1, 0, 0, 0, 0), format.stata = "%10.0g"),       candDistance = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0,       0, 0, 0, 0, 0, 0, 1, 0, 0, 0), format.stata = "%10.0g"),       candEfficacy = structure(c(1, 0, 0, 0, 1, 0, 0, 0, 0, 0,       0, 0, 0, 0, 1, 0, 0, 1, 0, 0), format.stata = "%10.0g")), row.names = c(NA,   -20L), class = c("tbl_df", "tbl", "data.frame"))  

What I am trying to do is generate a table using the tables package with results from a t.test. The trouble I am having is I've taken this dataset and have used lapply to calculate my t.tests on each of the variables with youngTreatment as my 'y' variable:

      candidateEvokesDiffYoung = lapply(candidateEvokeDFYoung[-1], function(x) t.test(x ~ candidateEvokeDFYoung$youngTreatment))    

This gives me a list of lists. I have no clue how to use tables::tabular to access

      list[['statistics']]    

and

      list[['p.value]]    

I could definitely just manually pull all of these out myself and put it in a dataframe for stargazer or something, but I was wondering if there was someone who knew how I could do this more efficiently and with the tables package.

How to rename multiple files in powershell from parent folder?

Posted: 14 Aug 2021 08:00 AM PDT

Hello I would like to know is there a way to replace multiple filenames from parent folder?

I was able to rename multiple files using command below, but I have to access each folder first to rename multiple files.

dir .\* -include ('*.mp4','*.srt') | Rename-Item -NewName { $_.Name -replace '\[','' -replace '\]','' }   

I was trying to replace dir .\* to dir .\**\* to select from parent folder but didn't work.

What am I missing?

How can I make drawString faster in Windows 10?

Posted: 14 Aug 2021 08:00 AM PDT

My ancient application leans heavily on drawString. It's at least 20 times slower in Windows 10. Are there ways to speed up drawing text in Windows? The following code illustrates the difference.

import javax.swing.*;  import java.awt.*;    public class hello{    // hello takes roughly 1 second in Ubuntu 20.04 SDK 11.  // hello takes roughly 2 seconds in Windows 7 Java SDK 1.7.  // hello takes roughly 40 seconds in Windows 10 Java SDK 16.     public static void main(String[] args) {          JPanel panel= new JPanel();          JFrame frame = new JFrame();          frame.add(panel);          frame.pack();          frame.setSize(100,100);          frame.setVisible(true);          Graphics g=panel.getGraphics();          g.setFont(new Font("Arial", Font.PLAIN,12));            long start_time=System.currentTimeMillis();          for (int times=0;times<150000;times++)              g.drawString("hello",50,50);           System.out.println("total drawString time was "+(System.currentTimeMillis()-start_time));         System.exit(0);      }  }  

What are the managed stack and the managed heap?

Posted: 14 Aug 2021 08:01 AM PDT

MSDN's C# docs uses the terms stack and heap (eg. when talking about variable allocation).

It is stated that these terms means different memory spaces with well defined purposes (eg. local variables are always allocated in the stack whereas member variables of reference types are always allocated in the heap).

I understand what those terms mean in terms of certain CPU architecture and certain operating systems. Let's assume the x86-64 architecture, where the stack will be a per-thread contiguous memory block used to store call frames (local variables, return address, etc), and the heap being a one-per-process memory block for general purpose use.

What I do not understand yet is how those high-level and low-level definitions relate together.

I couldn't find an objective definition for the terms stack and heap in the MSDN docs, but I assume they mean something very similar to what those terms means in the x86-64 architecture.

For the purpose of this question, let's assume we are working on a custom device which the CPU and OS don't implement the concept of a separate stack and heap, they both (CPU/OS) deal directly with virtual memory. Will the stack and the heap (as cited in the MSDN docs) even exists in an .net application running on this particular device? If so, are they enforced by the CLR? Are they created on top of what the OS returns as allocated memory?

Why this code show this "control reaches end of non-void function [-Werror=return-type] " ERROR?

Posted: 14 Aug 2021 08:01 AM PDT

I tried to program to add the previous three numbers of an nth number recursively until attaining the nth value

for example ;

func(n) = {return a if n = 1 ; return b if n= 2 ;return c if n = 3 ;return func(n - 1) + func( n - 2) + func( n - 3) if n > 3} }

int find_nth_term(int n , int a ,int b,int c)  {   if (n == 2)   {    return b;       }   else if (n == 1)   {    return a;   }   else if (n == 3)   {     return c;   }   else if (n > 3)   {     int temp = a + b +c;     a= b;     b = c;     c = temp;     return find_nth_term(n-1, a ,b,c);   }  }       int main() {      int n, a, b, c;          scanf("%d %d %d %d", &n, &a, &b, &c);      int ans = find_nth_term(n, a, b, c);         printf("%d", ans);       return 0;  

Convert df value of specific columns to string if the digits of the df value in those columns is greater than or equal to 12

Posted: 14 Aug 2021 08:00 AM PDT

Im trying to convert those values in a few columns to string if the number of digits of those numbers are greater than to equal to 12.

I am doing this so as to avoid scientific notation display when I write to excel of these numbers.

Code I tried :-

def count_digits(string):   if string is None:      return 0   string=str(string)   return sum(item.isdigit() for item in string)    if df['col1'].apply(count_digits) or df['col2'].apply(count_digits) or df['col3'].apply(count_digits) >= 12:    df.values=str(df.values())  

Sample df :-

col1      col2        col3  56465780 56.678       None  19937000 430624000    26847651.79  4457000  999999999999 None  256000   344578000    None  225000   35           None  219000   None         None  

Put two queries into one query - Query - SQL - SAP B1

Posted: 14 Aug 2021 08:01 AM PDT

I have a very simple Inventory in Warehouse query, and now I need to do a sum in the IsCommitted column with another query that I have called "Set Demand".

Like this = Sum( [IsCommited] + "Set Demand Query qty")

Warehouse query

SELECT T0.[ItemCode] AS 'Item No.',  T0.[WhsCode] AS 'Warehouse Code',  T0.[OnHand] AS 'In Stock',  T0.[IsCommited] AS 'Committed',  T0.[MinStock] AS 'Minimum Inventory',  T0.[MaxStock] AS 'Maximum Inventory',  T1.[ItmsGrpCod] AS 'Itemcode',  T2.Price AS 'StandardCost'  FROM [OITW] T0 INNER JOIN [OITM] T1 ON T0.ItemCode = T1.ItemCode LEFT JOIN [ITM1] T2 ON T1.ItemCode = T2.ItemCode and T2.PriceList = 26  WHERE (T0.[WhsCode] = (N'9500' )) AND (T1.[ItmsGrpCod] = (N'100' )) AND T0.[OnHand] > 0  

Set Demand query.

SELECT T3.[ItemCode] ,  (-T3.[OnHand] + T1.[Quantity]) as 'Set Demand'  FROM [OITT] T0 WITH (NOLOCK) INNER JOIN [ITT1] T1 WITH (NOLOCK) ON T0.[Code] = T1.[Father], [OSRI] T2 WITH (NOLOCK), [OITW] T3 WITH (NOLOCK) INNER JOIN [OITM] T4 WITH (NOLOCK) ON T3.[ITEMCode] = T4.[ItemCode]  WHERE T0.[Code] = T2.[ItemCode] AND T1.[Code] = T3.[ItemCode] AND T2.[IntrSerial] = T3.[WhsCode] AND T2.[Status] <> 1 and T2.[U_IsCon] <> 'YES' and T3.[OnHand] - T1.[Quantity] < 0 and substring (T2.[WhsCode],8,1)<>'C' AND T2.[WhsCode] = '9000' AND t4.[ItmsGrpCod] = 100  

What Im trying to do = ( [IsCommited] + "Set Demand Query qty")

SELECT T0.[ItemCode] AS 'Item No.',  T0.[WhsCode] AS 'Warehouse Code',  T0.[OnHand] AS 'In Stock',    (T0.[IsCommited] + (SELECT (-T3.[OnHand] + T1.[Quantity])    FROM [OITT] T0 WITH (NOLOCK) INNER JOIN [ITT1] T1 WITH (NOLOCK) ON T0.[Code] = T1.[Father], [OSRI] T2 WITH (NOLOCK), [OITW] T3 WITH (NOLOCK) INNER JOIN [OITM] T4 WITH (NOLOCK) ON T3.[ITEMCode] = T4.[ItemCode]  WHERE T0.[Code] = T2.[ItemCode] AND T1.[Code] = T3.[ItemCode] AND T2.[IntrSerial] = T3.[WhsCode] AND T2.[Status] <> 1 and T2.[U_IsCon] <> 'YES' and T3.[OnHand] - T1.[Quantity] < 0 and substring (T2.[WhsCode],8,1)<>'C' AND T2.[WhsCode] = '9000' AND t4.[ItmsGrpCod] = 100) as '**Commited&SetDemand**',    T0.[MinStock] AS 'Minimum Inventory',  T0.[MaxStock] AS 'Maximum Inventory',  T1.[ItmsGrpCod] AS 'Itemcode',  T2.Price AS 'StandardCost'  FROM [OITW] T0 INNER JOIN [OITM] T1 ON T0.ItemCode = T1.ItemCode LEFT JOIN [ITM1] T2 ON T1.ItemCode = T2.ItemCode and T2.PriceList = 26  WHERE (T0.[WhsCode] = (N'9500' )) AND (T1.[ItmsGrpCod] = (N'100' )) AND T0.[OnHand] > 0  

Your help will be greatly appreciated. Thank you very much!!!!! :)

Having issues on assigning a word to length

Posted: 14 Aug 2021 08:01 AM PDT

I'm trying to write a program that does the following:

Enter a word: supercalifragilisticoespialidoso    The word's length is: 32.    Enter a smaller number than the length: 23    The word cut on letter 23 is: supercalifragilisticoes.  

For that I'm doing:

#include <stdio.h>    #include<string.h>    #define DIM 99    int main() {        char name[DIM], name2[DIM];      int length, length2;        printf("Enter a word: ");      scanf("%s", name);      length = strlen(name);      printf("The word's length is: %d\n", length);      printf("Enter a smaller number than the length: ");      scanf("%d", &length2);      name2 = name[length2];      printf("The word cut on the letter %d is: %c", length2, name2);                  return 0;  }  

But I get

main.c:16:11: error: assignment to expression with array type  

The problem is in the line name2 = name[length2], that's the way I found to create the new smaller word, but it's not right.

Could someone please help?

How to create a CMakeLists.txt for a gtkmm application?

Posted: 14 Aug 2021 08:00 AM PDT

My Application tree is as follows:

├── build  ├── CMakeLists.txt  ├── example  │   ├── applicationwindow.cpp  │   ├── applicationwindow.h  │   └── Application.glade  └── main.cpp    2 directories, 5 files  

And the CMakeLists.txt file I created is as follows:

cmake_minimum_required(VERSION 3.1.0)  project(Example_App)  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")    find_package(PkgConfig)  pkg_check_modules(GTKMM gtkmm-3.0)    include_directories(${GTKMM_INCLUDE_DIRS})  link_directories(${GTKMM_LIBRARY_DIRS})    set(SOURCE_FILES main.cpp)  add_executable(${CMAKE_PROJECT_NAME} ${SOURCE_FILES} example/applicationwindow.cpp)  target_link_libraries(${CMAKE_PROJECT_NAME} ${GTKMM_LIBRARIES})  

After a successful cmake .. and make when I execute the application I get the following error:

terminate called after throwing an instance of 'Glib::FileError'  Aborted (core dumped)  

I have tried building this with a Makefile but that doesn't seem to give any issues. I have also tried to look into Glib::FileError however, I am unable to extract the exact cause of the problem. On trying the similar CMakeLists on a simpler instance like this example as denoted here: Gtkmm Example of a Application Window

It however seems to work. What might be the exact problem here?

Is there a way to access Environment.DIRECTORY_DOWNLOADS?

Posted: 14 Aug 2021 08:01 AM PDT

I'm working on backup and restore SQLite Database to cloud server. I've completed the backup code and it works. However, I have a problem when I'm trying to restore it. The problem is, on Android 11, the Environment.DIRECTORY_DOWNLOADS is in Android/data/package/files/Download, but somehow I cannot access or write to Environment.DIRECTORY_DOWNLOADS, and I don't know why. Here's my code (the download from cloud method, it succeeds).

DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);  Uri uri = Uri.parse(response.body().getPath());  DownloadManager.Request request = new DownloadManager.Request(uri);  request.setDestinationInExternalFilesDir(getApplicationContext(), Environment.DIRECTORY_DOWNLOADS, sharedPreference.getUser().getEmail() + ".db");  request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);  request.setTitle(sharedPreference.getUser().getEmail() + ".db");  request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);  Long downloadReference = manager.enqueue(request);  

When I'm trying to access them, I cannot access the Environment.DIRECTORY_DOWNLOADS. Here is the code

File internal = new File(Environment.DIRECTORY_DOWNLOADS);    if (internal.canRead()) {      File currentDB = new File("/data/data/" + getPackageName() + "/databases/", DBHelper.DATABASE_NAME);      File backupDB = new File(internal, sharedPreference.getUser().getEmail() + ".db");      Toast.makeText(getApplicationContext(),backupDB.toString(),Toast.LENGTH_SHORT).show();        if (backupDB.exists()) {          FileChannel src = new FileInputStream(backupDB).getChannel();          FileChannel dst = new FileOutputStream(currentDB).getChannel();          dst.transferFrom(src, 0, src.size());          src.close();          dst.close();          progressDialog.dismiss();          Toast.makeText(getApplicationContext(), backupDB.toString(), Toast.LENGTH_SHORT).show();      } else {          progressDialog.dismiss();          Toast.makeText(getApplicationContext(), "Error, file not exist!", Toast.LENGTH_SHORT).show();      }    } else {      progressDialog.dismiss();      Toast.makeText(getApplicationContext(), "Error, cannot read the directory!", Toast.LENGTH_SHORT).show();  }  

How to determine how much "slack" in postgres database?

Posted: 14 Aug 2021 08:01 AM PDT

I've got a postgres database which I recently vacuumed. I understand that process marks space as available for future use, but for the most part does not return it to the OS.

I need to track how close I am to using up that available "slack space" so I can ensure the entire database does not start to grow again.

Is there a way to see how much empty space the database has inside it?

I'd prefer to just do a VACUUM FULL and monitor disk consumption, but I can't lock the table for a prolonged period, nor do I have the disk space.

Running version 13 on headless Ubuntu if that's important.

Merging 2 Projects into 1 [School Project] with Pygame [duplicate]

Posted: 14 Aug 2021 08:01 AM PDT

I am doing a math program for my school project, and I have already prepared the menu for the game and the process of the game, that basically consists in doing endless loop of sums till you fail, giving you 5 points for every correct answer (in the future I have planned to connect it to a SQLite base, because it asks you a name and your age). Anyway, here are the code of the sums and the menu:

https://www.sololearn.com/Discuss/2848691/help-me-to-turn-this-into-a-function-and-make-this-infinite-school-project https://www.sololearn.com/Discuss/2856421/making-the-school-project-menu-with-pygame-menu-school-project

[Updated] The problem consists in when I try to make the code of the sums to appear in the window that the menu produces after pressing 'Comencem', the sums appear in the Python Console, but not in the window. I would like it to appear in the window, but I don't know how to do it. Any help please?

import pygame  import pygame_menu  from pygame import mixer  import random  pygame.init()  #Mida i nom de la finestra  surface = pygame.display.set_mode((600, 400))  pygame.display.set_caption("Projecte MatZanfe")  #Logotip de la finestra  logotip = pygame.image.load("calculator.png")  pygame.display.set_icon(logotip)    font = pygame_menu.font.FONT_8BIT  font1 = pygame_menu.font.FONT_NEVIS    def start_the_game():      # Variables      puntuacio = 0      usuari = str(input("Com et dius? "))      edat = str(input("Quina edat tens? "))      while True:          for event in pygame.event.get():              if event.type == pygame.QUIT:                  exit()          surface.fill((0, 0, 0))          text = font.render(str(puntuacio), True, (255, 255, 255))          surface.blit(text, (0, 0))          pygame.display.update()          x = random.randint(0, 10)          y = random.randint(0, 10)          z = x + y          print(str(x) + "+" + str(y))          resultat = int(input())          if resultat == z:              print("Correcte")              puntuacio = puntuacio + 5              print("Tens aquests punts:", puntuacio)          else:              if resultat != z:                  print("Malament!")                  parar = input("Vols parar? ")                  if parar == ("si"):                      print(usuari + ", has aconseguit " + str(puntuacio) + " punts")                      break                  else:                      continue    menu = pygame_menu.Menu('Projecte MatZanfe', 600, 400,                         theme=pygame_menu.themes.THEME_SOLARIZED)    menu.add.text_input('Usuari: ', font_name = font1, font_color = 'blue')  menu.add.text_input('Edat: ', font_name = font1, font_color = 'purple')  mixer.music.load('MusicaMenu.wav')  mixer.music.play(-1)  menu.add.button('Comencem', start_the_game,font_name = font, font_color = 'green')  menu.add.button('Sortir', pygame_menu.events.EXIT, font_name = font,font_color = 'red')    menu.mainloop(surface)  

(Some words are in catalan but I think you can understand them. I will change it if you can't).

Playing a wav file with TarsosDSP on Android

Posted: 14 Aug 2021 08:00 AM PDT

Problem: Wav file loads and is processed by AudioDispatcher, but no sound plays.

First, the permissions:

public void checkPermissions() {      if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this.requireContext(), Manifest.permission.RECORD_AUDIO)) {          //When permission is not granted by user, show them message why this permission is needed.          if (ActivityCompat.shouldShowRequestPermissionRationale(this.requireActivity(), Manifest.permission.RECORD_AUDIO)) {              Toast.makeText(this.getContext(), "Please grant permissions to record audio", Toast.LENGTH_LONG).show();              //Give user option to still opt-in the permissions          }            ActivityCompat.requestPermissions(this.requireActivity(), new String[]{Manifest.permission.RECORD_AUDIO}, MY_PERMISSIONS_RECORD_AUDIO);          launchProfile();      }      //If permission is granted, then proceed      else if (ContextCompat.checkSelfPermission(this.requireContext(), Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {          launchProfile();      }  }  

Then the launchProfile() function:

public void launchProfile() {          AudioMethods.test(getActivity().getApplicationContext());          //Other fragments load after this that actually do things with the audio file, but           //I want to get this working before anything else runs.  }  

Then the AudioMethods.test function:

public static void test(Context context){      String fileName = "audio-samples/samplefile.wav";      try{          releaseStaticDispatcher(dispatcher);            TarsosDSPAudioFormat tarsosDSPAudioFormat = new TarsosDSPAudioFormat(TarsosDSPAudioFormat.Encoding.PCM_SIGNED,                  22050,                  16, //based on the screenshot from Audacity, should this be 32?                  1,                  2,                  22050,                  ByteOrder.BIG_ENDIAN.equals(ByteOrder.nativeOrder()));            AssetManager assetManager = context.getAssets();          AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);            InputStream stream = fileDescriptor.createInputStream();          dispatcher = new AudioDispatcher(new UniversalAudioInputStream(stream, tarsosDSPAudioFormat),1024,512);                    //Not playing sound for some reason...          final AudioProcessor playerProcessor = new AndroidAudioPlayer(tarsosDSPAudioFormat, 22050, AudioManager.STREAM_MUSIC);          dispatcher.addAudioProcessor(playerProcessor);              dispatcher.run();            Thread audioThread = new Thread(dispatcher, "Test Audio Thread");          audioThread.start();        } catch (Exception e) {          e.printStackTrace();      }  }  

Console output. No errors, just the warning:

W/AudioTrack: Use of stream types is deprecated for operations other than volume control  See the documentation of AudioTrack() for what to use instead with android.media.AudioAttributes to qualify your playback use case  D/AudioTrack: stop(38): called with 12288 frames delivered  

Because the AudioTrack is delivering frames, and there aren't any runtime errors, I'm assuming I'm just missing something dumb by either not having sufficient permissions or I've missed something in setting up my AndroidAudioPlayer. I got the 22050 number by opening the file in Audacity and looking at the stats there:

enter image description here

Any help is appreciated! Thanks :)

how to convert javax.xml.transform.dom.DOMSource object to javax.xml.transform.Source

Posted: 14 Aug 2021 08:00 AM PDT

I have java code written in JDK 11 that uses transform. But I need to compile it in JDK 8.

    TransformerFactory transformerFactory = TransformerFactory.newInstance();      Transformer transformer = null;        transformer = transformerFactory.newTransformer();      DOMSource source = new DOMSource(irisdoc);      File file = new File(fileName);      //file.getParentFile().mkdirs();      file.createNewFile();      StreamResult result = new StreamResult(file);      transformer.setOutputProperty(OutputKeys.INDENT, "yes");      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");      transformer.transform(source, result);  

I need to change source variable above into javax.xml.transform.Source datatype to make it work in Java 8.

VsCode, how to change Javascript Object key colours

Posted: 14 Aug 2021 08:01 AM PDT

I am currently struggling a little to change the colour of keys inside javascript objects in my vscode theme. Hoping someone could help me out.

Vscode theme demonstration

As you can see, the keys end up being the same colour as strings, which is a little annoying to me. Looking to change it to something else. Anyone know what to do? I probably need to change some css settings but can't find the right one.

Thanks for your time :)

Java OpenAL - Source gain of zero after passing the max distance

Posted: 14 Aug 2021 08:00 AM PDT

(Sorry for my bad english)

Hi, I'm learning LWJGL 3 OpenAL library.

Playing around with the 3D audio attenuation, I noticed that you can't get a gain of zero for a source using a good realistic distance model like AL_INVERSE_DISTANCE_CLAMPED: 3

I can archieve this using the AL_LINEAR_DISTANCE_CLAMPED because after the AL_MAX_DISTANCE the source gain is zero: 4 But this is a very bad and unrealistic model....

So, is there a way to have a AL_INVERSE_DISTANCE_CLAMPED model but with a gain of zero after passing the AL_MAX_DISTANCE? Something like this: 5

Here's a very simplified example of my current code:

import java.io.BufferedInputStream;  import java.nio.ByteBuffer;    import javax.sound.sampled.AudioFormat;  import javax.sound.sampled.AudioInputStream;  import javax.sound.sampled.AudioSystem;    import org.lwjgl.BufferUtils;    import static org.lwjgl.openal.AL.*;  import static org.lwjgl.openal.AL10.*;  import static org.lwjgl.openal.ALC11.*;  import static org.lwjgl.openal.ALC.*;    public class Main {            public static void main(String[] args) throws Exception {                    // some init stuff from the docs          long device;          long context;                    String deviceName = alcGetString(0, ALC_DEFAULT_DEVICE_SPECIFIER);                    device = alcOpenDevice(deviceName);          context = alcCreateContext(device, new int[]{0});                    alcMakeContextCurrent(context);          createCapabilities(createCapabilities(device));                              alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);   // using inverse distance clamped model                    int source = alGenSources();    // create a source          alSource3f(source, AL_POSITION, 0, 0, 0);   // set the source position to 0                    // source values to work with the distance model          alSourcef(source, AL_ROLLOFF_FACTOR, 1f);   // the rolloff factor makes some changes to the gain curve: the higher the rolloff, the steeper the curve will be          alSourcef(source, AL_REFERENCE_DISTANCE, 5f);   // the reference distance determines the distance between source and listener where the gain is exactly 1          //alSourcef(source, AL_MAX_DISTANCE, 15f);      // after this distance between source and listener, the sound won't be attenuated anymore in the clamped models                                                          // I leave this value commented because it would be exactly what I don't want                    alSourcef(source, AL_GAIN, 1f);     // set the gain of the sound to 1          alSourcei(source, AL_LOOPING, AL_TRUE); // loop the sound                              // now let's load the audio file          int audioBuffer = alGenBuffers();   // we'll store the buffer id of the sound in this variable          // load the audio file to an AudioInputStream          AudioInputStream stream = AudioSystem.getAudioInputStream(new BufferedInputStream(Main.class.getResourceAsStream("/sound.wav")));                    AudioFormat audioFormat = stream.getFormat();          int format, sampleRate, bytesPerFrame, totalBytes;          // OpenAL needs a ByteBuffer to fill its buffer with readable data, so now we need to convert the AudioInputStream to a ByteBuffer and some audio infos          ByteBuffer data;                    format = AL_FORMAT_MONO16;  // for simplicity, I set the format to mono16 but there are some other ways to get the right format          sampleRate = (int)audioFormat.getSampleRate();          bytesPerFrame = audioFormat.getFrameSize();          totalBytes = (int)stream.getFrameLength() * bytesPerFrame;                    data = BufferUtils.createByteBuffer(totalBytes);                    // read the stream and put the data in the ByteBuffer          byte[] temp = new byte[totalBytes];          int read = stream.read(temp, 0, totalBytes);          data.clear();          data.put(temp, 0, read);          data.flip();    // flip the buffer, otherwise OpenAL won't be able to read it                    stream.close(); // close the stream, we don't need it anymore                    alBufferData(audioBuffer, format, data, sampleRate);    // now we can finally send the audio data to OpenAL                              alSourcei(source, AL_BUFFER, audioBuffer);  // tell the source to play this sound                              float listenerX = -20f;          alListener3f(AL_POSITION, listenerX, 0, 2); // set the initial listener position to -20 on the x and 2 on the z to have a nice 3D audio transition between the channels                    alSourcePlay(source);   // play the sound                    while(listenerX < 50) {              listenerX += .05f;  // move the listener on the X axis              alListener3f(AL_POSITION, listenerX, 0, 2);              Thread.sleep(10);          }      }    }  

If you run this code, you'll notice that even when the listener is 50 units far away from the source the sound still clearly audible! I'd like to have a maximum distance from the source where the listener won't be able anymore to hear the sound but without suddently setting the gain to 0.

Is there any way to do it?

snail in the well javascript challenge

Posted: 14 Aug 2021 08:01 AM PDT

This is my first question on stack overflow although this question had been answered before I didn't get enough details to understand why the code was written that way and I didn't just want to copy and paste the solution without understanding it.

The snail climbs 7 feet each day and slips back 2 feet each night, How many days will it take the snail to get out of a well with the given depth? Sample Input 31 Sample Output 6 this is was what i wrote but it didn't work

function main() {  var depth = parseInt(readLine(), 10);  //your code goes here  let climb = 0, days = 0;     for(climb + 7; climb < depth; days++){         climb += 2;         console.log(days);           

JAVA mockito unit test for resttemplate and retryTemplate

Posted: 14 Aug 2021 08:00 AM PDT

I am currently writing unit test for below method

@Autowired  private RequestConfig requestConfig;    @Autowired  private RetryTemplate retryTemplate;    public ResponseEntity<String> makeGetServiceCall(String serviceUrl) throws Exception {      try {          return retryTemplate.execute(retryContext -> {                RestTemplate restTemplate = new RestTemplate();              HttpHeaders headers = requestConfig.createHttpHeaders();              HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);              ResponseEntity<String> response = restTemplate.exchange(serviceUrl, HttpMethod.GET, entity, String.class);              return response;            });      } catch (Exception e) {          throw new Exception("Generic exception while makeGetServiceCall due to" + e + serviceUrl);      }  }  

UPDATED METHOD:

@Autowired  private RequestConfig requestConfig;    @Autowired  private RetryTemplate retryTemplate;    @Autowired  private RestTemplate restTemplate;    public ResponseEntity<String> makeGetServiceCall(String serviceUrl) throws Exception {      try {          return retryTemplate.execute(retryContext -> {                HttpHeaders headers = requestConfig.createHttpHeaders();              HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);              ResponseEntity<String> response = restTemplate.exchange(serviceUrl, HttpMethod.GET, entity, String.class);              return response;            });      } catch (Exception e) {          throw new Exception("Generic exception while makeGetServiceCall due to" + e + serviceUrl);      }  }  

I tried all possibilities but I am unable to get it right. Here is my below test.

@Mock  private RestTemplate restTemplate;    @Mock  public RequestConfig requestConfig;    @InjectMocks  private RetryTemplate retryTemplate;    ServiceRequest serviceRequest;      @Test  public void makeGetServiceCall() throws Exception {      String url = "http://localhost:8080";      RetryTemplate mockRetryTemplate = Mockito.mock(RetryTemplate.class);      RestTemplate mockRestTemplate = Mockito.mock(RestTemplate.class);      ResponseEntity<String> myEntity = new ResponseEntity<>(HttpStatus.ACCEPTED);      Mockito.when(mockRetryTemplate.execute(ArgumentMatchers.any(RetryCallback.class), ArgumentMatchers.any(RecoveryCallback.class), ArgumentMatchers.any(RetryState.class))).thenReturn(myEntity);        Mockito.when(mockRestTemplate.exchange(              ArgumentMatchers.eq(url),              ArgumentMatchers.eq(HttpMethod.GET),              ArgumentMatchers.<HttpEntity<String>>any(),              ArgumentMatchers.<Class<String>>any())      ).thenReturn(myEntity);        ResponseEntity<String> response = serviceRequest.makeGetServiceCall(url);      Assert.assertEquals(myEntity, response);  }  

UPDATED TEST CASE:

 @Mock  public RequestConfig requestConfig;    @Mock  private RestTemplate restTemplate;    @Mock  private RetryTemplate retryTemplate;    @InjectMocks  ServiceRequest serviceRequest;    @Test  public void makeGetServiceCall() throws Exception {      //given:      String url = "http://localhost:8080";        when(requestConfig.createHttpHeaders()).thenReturn(null);      ResponseEntity<String> myEntity = new ResponseEntity<>( HttpStatus.ACCEPTED);      when(retryTemplate.execute(any(RetryCallback.class), any(RecoveryCallback.class), any(RetryState.class))).thenAnswer(invocation -> {          RetryCallback retry = invocation.getArgument(0);          return retry.doWithRetry(/*here goes RetryContext but it's ignored in ServiceRequest*/null);      });      when(restTemplate.exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class), eq(String.class)))              .thenReturn(myEntity);        //when:      ResponseEntity<String> response = serviceRequest.makeGetServiceCall(url);        //then:      assertEquals(myEntity, response);  }  

The response object which I get from my method call makeGetServiceCall always return null. When I debug the code I see exception org.mockito.exceptions.misusing.WrongTypeOfReturnValue: ResponseEntity cannot be returned by toString() toString() should return String error on the resttemplate mocking where I return myEntity

I am not sure what am I missing.

Laravel Scout: only search in specific fields

Posted: 14 Aug 2021 08:00 AM PDT

Laravel Scout: Is there a way that I search in only a specific field?

At the moment this line is working fine:

    $es = Element::search($q)->get();  

But it searches title, shortdescription and description fields. I need it to only search in title field.

Differentiating in SymPy

Posted: 14 Aug 2021 08:01 AM PDT

I'm trying to use SymPy to differentiate the following equation:

log(n)**k

import math, sympy  from sympy.abc import x, y, n, k  print(sympy.diff(math.pow(math.log(n, 2), k), n))  

But I'm getting the can't convert expression to float error from SymPy. What am I doing wrong?

runfile('C:/Users/towis/.spyder-py3/temp.py', wdir='C:/Users/towis/.spyder-py3')  Traceback (most recent call last):      File "<ipython-input-19-3728a7ec31a4>", line 1, in <module>      runfile('C:/Users/towis/.spyder-py3/temp.py', wdir='C:/Users/towis/.spyder-py3')      File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile      execfile(filename, namespace)      File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile      exec(compile(f.read(), filename, 'exec'), namespace)      File "C:/Users/towis/.spyder-py3/temp.py", line 6, in <module>      print(sympy.diff(math.pow(math.log(n,2), k), n))      File "C:\ProgramData\Anaconda3\lib\site-packages\sympy\core\expr.py", line 226, in __float__      raise TypeError("can't convert expression to float")    TypeError: can't convert expression to float  

How to terminate the script in JavaScript?

Posted: 14 Aug 2021 08:01 AM PDT

How can I exit the JavaScript script much like PHP's exit or die? I know it's not the best programming practice but I need to.

No comments:

Post a Comment