2023-08-31

Mockito InjectMocks not working but constructor call does

I'm using Kotlin with Mockito. Given these dependencies:

    @Mock
    private lateinit var tokenService: TokenService

    @Mock
    private lateinit var jwtDecoder: JwtDecoder

    @Mock
    private lateinit var passwordEncoder: PasswordEncoder

    @Mock
    private lateinit var authManager: AuthenticationManager

    @Mock
    private lateinit var mailLoginUserService: MailLoginUserService

    @Mock
    private lateinit var simpleMailService: SimpleMailService

I though the following codes should be equivalent.

First Variant:

@InjectMocks
private lateinit var underTest: MailLoginService

Second Variant:

private lateinit var underTest: MailLoginService

    @BeforeEach
    fun setup() {
    underTest = MailLoginService(
            tokenService,
            jwtDecoder,
            passwordEncoder,
            authManager,
            mailLoginUserService,
            simpleMailService
        )
    }

I know that BeforeEach is called before every test giving a knew instance of the MailLoginService but I'm only running one test.

In the test I specified

given(passwordEncoder.encode(anyString()))
            .willReturn("EncodedPassword")

Inside the tested method of MailLoginService the method passwordEncoder.encode is called. With the second variant (the manual constructor call) everything works fine. But with the first variant (InjectMocks) I get the following error:

java.lang.NullPointerException: encode(...) must not be null

I'd like to use InjectMocks as it reduces Code. Does anybody know why this problem occurs and how to fix it?



2023-08-30

Increase width of box for data frame printing quarto revealjs

The data frame is not being printed over the width of the (assumed) box, but the last column is being cut and printed below. This happens with (see example picture) or without {.smaller} class.

How can I change the width of the box that is used for data frame printing? Ideally a dynamic width that adjusts to the width of the window, but I'd be happy with fixed widths too.

---
title: "Untitled"
format: revealjs
editor: visual
---

## "amd" data set from R package eyedata {.smaller}

```{r}
head(eyedata::amd, 15, row)
```

Example figure

enter image description here



2023-08-29

Spring security 6.0 - oauth2Login with MS Azure and CSRF token - how to login there in Postman?

I'm beginner in Spring Security configuration and my purpose is set 2 things:

  1. CSRF token
  2. Authorization by Microsoft Azure

Firstly I've added oauth client in properties:

spring.security.oauth2.client.provider.azure.issuer-uri=https://login.microsoftonline.com/${id}/v2.0
spring.security.oauth2.client.registration.azure-dev.provider=azure
spring.security.oauth2.client.registration.azure-dev.client-id=${clientId}
spring.security.oauth2.client.registration.azure-dev.client-secret=${secret}
spring.security.oauth2.client.registration.azure-dev.scope=openid,email,profile

And all my GET endpoints started proxy my requests to Microsoft Login page -> after login all GET endpoints are available.

So I created security config:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authz -> authz
                        .requestMatchers("/").permitAll()
                        .requestMatchers("/oauth2/authorization/azure-dev").permitAll()
                        .requestMatchers("/login").permitAll()
                        .requestMatchers(HttpMethod.POST, "/logout").permitAll()
                        .requestMatchers( "/api/v1/**").authenticated()
                        .requestMatchers(HttpMethod.POST, "/api/v1/**").authenticated()
                        .requestMatchers(HttpMethod.PUT, "/api/v1/**").authenticated()
                )
                .csrf(httpSecurityCsrfConfigurer -> httpSecurityCsrfConfigurer
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
                .logout(l -> l
                        .logoutSuccessUrl("/")
                        .logoutRequestMatcher(new AntPathRequestMatcher("/logout")))
                .oauth2Login(Customizer.withDefaults());

        return http.build();
    }
}

Option withHttpOnlyFalse should add CSRF token to headers automatically, but I couldn't find it in GET requests, but it probably will be add only to POST/PUT/DELETE requests. Then I tried to send some requests from Postman, but it's secured under Microsoft Azure login, and response is always:

<html dir="ltr" class="" lang="en">
<head>
    <title>Sign in to your account</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=yes">
    <meta http-equiv="Pragma" content="no-cache">
    (...)

So it's HTML to login page, but I can't open it, or handle (in browser after log in one time - I have access all the time to all requests). Again, I can't find any header/cookie which auth me in browser (to paste it in postman).

  1. Where is this oAuth2 key, after login to Microsoft in Browser? I want to copy it to postman (I even tried to get it from OAuth2AuthorizedClient authorizedClient with authorizedClient.getAccessToken().getTokenValue(), and there was value, but this token doesn't work in postman -> it still returns microsoft HTML page).
  2. Is spring security configured correctly in your opinion?
  3. I'm wondering how to auth with this login page and csrf tokens from frontend, if I can't find any tokens in browser? Should I create some special endpoint (in Spring app)?


How to animate the selection in LazyGrid with Android Compose

I am doing the UI effect like this with Android Compose. enter image description here

I implemented with below code. But it's not a good way and it causes bug when drag the Grid. Please give me some suggestions to implement it with diffrent ways.

fun GridView2() {
    var selectedIndex by remember { mutableStateOf(0) }
    var offsetX by remember {
        mutableStateOf((selectedIndex % 4) * 207f)
    }
    var offsetY by remember {
        mutableStateOf((selectedIndex / 4) * 150f)
    }

    val animatedOffset by animateOffsetAsState(
        targetValue = Offset(offsetX, offsetY), label = "",
    )

    Box(modifier = Modifier.fillMaxSize()) {
        LazyVerticalGrid(
            modifier = Modifier
                .fillMaxSize(),
            columns = GridCells.Adaptive(200.dp),
            contentPadding = PaddingValues(0.dp)
        ) {
            items(count = 20) { index ->
                Box(
                    modifier = Modifier
                        .width(200.dp)
                        .height(150.dp)
                        .clickable {
                            selectedIndex = index
                            offsetX = (selectedIndex % 4) * 207f
                            offsetY = (selectedIndex / 4) * 150f
                        },
                    contentAlignment = Alignment.Center
                ) {
                    Box(
                        modifier = Modifier
                            .width(190.dp)
                            .height(140.dp)
                            .background(Color.Gray)
                    )
                }
            }
        }
        Box(
            modifier = Modifier
                .width(207.dp)
                .height(150.dp)
                .offset(
                    x = Dp(animatedOffset.x),
                    y = Dp(animatedOffset.y)
                ),
            contentAlignment = Alignment.Center
        ) {
            Box(
                modifier = Modifier
                    .width(190.dp)
                    .height(140.dp)
                    .border(2.dp, Color.Green)
            )
        }
    }
}


2023-08-28

Jasper Reports Groups and Calculating Percentages of each group of the total

I have a data series like the following

Year Month Item SaleCount
2020 Jan Apple 2
2020 Jan Banana 3
2020 Feb Apple 1
2020 Feb Banana 3
2020 March Apple 5
2020 March Banana 0
2021 Jan Apple 5
2021 Jan Banana 3
2021 Feb Apple 2
2021 Feb Banana 7
2021 March Apple 5
2021 March Banana 2

I am grouping data By Year then By Month then By Item Type

I would like to to show the percentage sales of each item as a function of the monthly total. However this is problematic given I use a variable reset on the Month Grouping to count total sales for that month. Then I tried to use F{SalesCount}/v{Total_Monthly_Sales}/100

as the v{Percent_of_Total} But as that variable is still being calculated dynamicaly during the internal Item lines basically for the first item its 100 and then each subsequent item is a percentage of the incrementing count..and not valid. The Total Sales are really on valid when the monthly group has finished being generated. The only solution I can see is use a sql calculation to produce a monthly total field and use this in my percentage variable.



2023-08-27

i cound not find the solution of inline style condition

Please help me, I could not find the solution of inline style and if this is not possible then tell me the alternative to render dynamic property change in style. The snippet is find from below like, and you can see what is error: error location

I tried lots but could not fix it.

This is my code:

<div 
  class="template"
  style="border-color: <%= details && details.brandAndLogoData && details.brandAndLogoData.brand_color ? details.brandAndLogoData.brand_color : '#000000' %>"
>
  <% if (details.brandAndLogoData && details.brandAndLogoData.brand_logo &&
  details.brandAndLogoData.brand_logo.url) { %>
  <table border="0" cellpadding="0" cellspacing="0" width="100%">
    <tr>
      <td align="center" valign="top" style="padding-bottom: 20px">
        <table border="0" cellpadding="0" cellspacing="0" width="100%">
          <tr>
            <td
              align="<%= details.brandAndLogoData.logo_alignment %>"
              valign="top"
              style="background-color: #ffffff"
            >
              <img
                src="<%= details.brandAndLogoData.brand_logo.url %>"
                alt="brandLogoBtn"
                style="max-width: 100%; max-height: 100%"
              />
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>

  <% } %>
  <div style="padding: 0 20px">
    <p><%= details.text %></p>
  </div>
</div>


2023-08-26

GqlGen incorrectly generates directives that have colon character in value field

I use https://github.com/99designs/gqlgen for generating golang code from graphql schema. I need to be able to add gorm tags to the resulting golang types. For that, I declare a directive for custom go tags (in schema.directives.gql):

directive @goTag(
    key: String!
    value: String
) on INPUT_FIELD_DEFINITION | FIELD_DEFINITION

Then I use it the following way in a graphql schema file:

type Value {
  value: Float!
  unit: String!
}

type Order {
    name: String! @goTag(key: "gorm", value: "primaryKey")
    amount: Value! @goTag(key: "gorm", value: "embedded;embeddedPrefix:dissolutionAmount_") 
    submitterRef String!
    submitter: Person! @goTag(key: "gorm", value: "foreignKey: SubmitterRef")  
}

Then I run code generation: go run github.com/99designs/gqlgen generate and the resulting code contains gorm tags that cut out text after ":" character:

type Order struct {
    Name              string    `json:"name" gorm:"primaryKey"` // <--- this is correct
    Amount          Value     `json:"amount" gorm:"embedded;embeddedPrefix` // INCORRECT - everything after "embeddedPrefix" is truncated: ":dissolutionAmount_" is missing, including trailing double quote
    SubmitterRef string. `json:"submitterRef"`
    Submitter       Person    `json:"submitter" gorm:"foreignKey` // INCORRECT - value in gorm tag is truncated, ": SubmitterRef" is missing
}


Get all augments id and name from League of legends API

Whats the endpoint for latest game Arena

"PlayerAugment1": 71, "PlayerAugment2": 46, "PlayerAugment3": 0, "PlayerAugment4": 0, "PlayerSubteamId": 1,

Want endpoint like https://ddragon.leagueoflegends.com/cdn/13.16.1/data/en_US/champion.json i've tried https://ddragon.leagueoflegends.com/cdn/13.16.1/data/en_US/arenaAugments.json



2023-08-25

Updated pdf fields don't show up when page is written - French CERFA document

I try again publishing this:

here the function supposed to resolve the writting in the pdf file:

def set_need_appearances_writer(writer):
    # See 12.7.2 and 7.7.2 for more information: http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
    try:
        catalog = writer._root_object
        # get the AcroForm tree
        if "/AcroForm" not in catalog:
            writer._root_object.update({
                NameObject("/AcroForm"): IndirectObject(len(writer._objects), 0, writer)
            })

        need_appearances = NameObject("/NeedAppearances")
        writer._root_object["/AcroForm"][need_appearances] = BooleanObject(True)
        # del writer._root_object["/AcroForm"]['NeedAppearances']
        return writer

    except Exception as e:
        print('set_need_appearances_writer() catch : ', repr(e))
        return writer


Why am I getting a MDXSCRIPT Model Error - DATEADD PowerBI when I am using my Calendar Table?

I am currently working on building a model representing YOY and MOM for Net Revenue. Everything works for YOY - MOM I am having issues.

My MOM works fine; however, the table is showing days and I just want to see Months, not every day in the month.

1

I do have a Calendar Table:

2

My Dax is referencing the Calendar Table. When I change my MOM to reflect Months instead of day, I get this error:

3

I am not sure what is happening?

I have tried leverage both Date and Month and seems to work in the model, but i don't want 'Date' in the model because it brings in all the days.

4



2023-08-24

GET http://localhost:8080/socket.io/?EIO=4&transport=polling&t=Oe3Y5xL 404 (Not Found) [closed]

I am facing this issue:

GET http://localhost:8080/socket.io/?EIO=4&transport=polling&t=Oe3Y5xL 404 (Not Found)

What to do to solve this issue? I am stuck at this problem.

backend code at server.js 
const express = require('express');
const app = express();
app.use(express.json());
require('dotenv').config();
const cors = require('cors');
app.use(cors());

const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);

const dbConfig = require('./config/dbConfig');


io.on('connection', (socket) => {
   console.log('user connected successfully');
   socket.on('disconnect', () => {
      console.log('user dis connected disconnected');
   })
})

const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`server has been started on ${port}`));

This is the frontend code for calling the backend socket

import io from 'socket.io-client';

const socket = io.connect('http://localhost:8080');


socket.on('connect', () => {
     console.log('user connected ');
})
socket.on('disconnect', () => {
     console.log('user disconnected');
 })

export default socket;



2023-08-23

Add preload attribute in wp_enqueue_script

I am trying to add attributes in :

<script src='http://localhost/projects/eviden/wp-content/themes/evidian/assets/build/fonts/Montserrat-VariableFont_wght.ttf' id='preload-custom-font-js'></script>

but it's not getting added, not sure what went wrong:

function my_style_loader_tag_filter($html, $handle)
    {
        if ($handle === 'preload-custom-font') {
            return str_replace(
                "id='preload-custom-font-js'",
                "rel='preload' as='font' type='font/ttf' id='preload-custom-font-js'",
                $html
            );
        }
        return $html;
    }
add_filter('style_loader_tag', array($this, 'my_style_loader_tag_filter'), 10, 2);

I want to add rel='preload' as='font' type='font/ttf' in the script tag getting rendered.



2023-08-22

Python Multiprocessing Pool Download Errors

Im using python multiproccing pool to download thousands of images and process these with python PIL

All works as should except when a image downloads and is corrupt, then PIL throws an error

Im looking for advice on how to re loop the pool, maybe just re downloading the image or the whole pool, the total data per pool is around 15Mb

I check the returned pool data array is the expected length but then the next step throws the error because the image is corrupt.

Pool code


    pool = multiprocessing.Pool(multiprocessing.cpu_count())
    func = partial(url_downloader, map_id)
    data = pool.map(func, url_list)
    pool.close()
    pool.join()

    if len(data) == len(url_list):
        for d in data:
            image = Image.open(BytesIO(d[0]))
            dst.paste(image, (d[1], d[2]))
    else:
        helpers.write_log(os.getcwd(), '{} : {}'.format(map_id, 'data size mismatch, skipping'))
        return

    exif_data = dst.getexif()
    # https://www.awaresystems.be/imaging/tiff/tifftags/extension.html
    # 0x270 ImageDescription - A string that describes the subject of the image
    # 0x269 DocumentName - The name of the document from which this image was scanned.
    # 0x285 PageName - The name of the page from which this image was scanned.
    exif_data[0x269] = str(helpers.normalizefilename(page_meta[0]))

    dst.save(os.path.join(image_folder, master_image_name), exif=exif_data)
    helpers.write_to_file(os.path.join(os.getcwd(), 'index.txt'), 'a+', index_text)

Download function

def url_downloader(map_id, url):

    header = {"User-Agent": "Mozilla/5.0 (X11; CrOS "
                            "x86_64 12871.102.0) "
                            "AppleWebKit/537.36 (KHTML, "
                            "like Gecko) "
                            "Chrome/81.0.4044.141 "
                            "Safari/537.36"}

    try:
        response = requests.get(url[0], headers=header)
        if response.status_code == 200:
            image_data = response.content
            return [image_data, url[1], url[2]]
    except requests.exceptions.RequestException as e:
        helpers.write_log(os.getcwd(), '{} : {}'.format(map_id, e))
        return

Error as requested

Traceback (most recent call last):
  File "/home/james/mapgrabber/./map-grabber.py", line 291, in <module>
    main()
  File "/home/james/mapgrabber/./map-grabber.py", line 69, in main
    auto_map_grabber(save_path, conn)
  File "/home/james/mapgrabber/./map-grabber.py", line 166, in auto_map_grabber
    map_builder(m[1], save_path, conn)
  File "/home/james/mapgrabber/./map-grabber.py", line 247, in map_builder
    image = Image.open(BytesIO(d[0]))
TypeError: 'NoneType' object is not subscriptable

Edit:

For now I have added a simple try, except function, maybe a limit on the retries? I'm guessing usually its just a single bad download so this should suffice

Edit 2:

I have tested this further by saving the tiles into a directory for trouble shooting, i did go down the route of checking the tile size's as i thought it was failed download's but upon checking the directory of tile's I can see all the images download correctly but sometimes they fail to be pasted correctly onto the larger image, its about 1 in 20 or so, i wonder if I'm causing some memory issues and causing a glitch somewhere. Checking the image size or validity cant help as there seems to be no issues there and if there is i catch it with my requests response.

current code

 pool = multiprocessing.Pool(multiprocessing.cpu_count())
    func = partial(url_downloader, map_id)
    data = pool.map(func, url_list)
    pool.close()
    pool.join()

    for d in data:
        try:
            image = Image.open(BytesIO(d[0]))
            dst.paste(image, (d[1], d[2]))
            image.close()
        except Exception as e:
            helpers.write_log(os.getcwd(), '{} : {}'.format(map_id, e))
            map_builder(map_id, save_path, conn)

dst is the main image created earlier in the script using the total dimensions of the image, then each piece is pasted in based on its coords.

working perfectly most of the time. i just cant seem to find the reason for the missing tiles.



2023-08-21

Show me in PHP, if new AD Password is required

I create a web interface with information about the AD users.

Now I want the information, if the user must set a new password or not. I want this information also if the account was new created and is locked.

I use the following code-snipped, but allways get the value "NULL" for $userEntry['pwdLastSet'].

$passwordChangeRequired = isset($userEntry['pwdLastSet']) && $userEntry['pwdLastSet'][0] == 0 ? "Yes" : "No";

For your information. I get other values, for example the if the user is locked or last logon.

I also tested the following code-snippet:

$userAccountControl = $userEntry['pwdlastset'][0];
$passwordChangeRequired = ($userAccountControl & 0x800000) ? "Yes" : "No";

but it also didn't work as expected.

Could anyone help me please, to get the information, if the checkbox is set or not, without checking the consideration if the account is locked and without checking the consideration if the user has logged in at least one time.

Edit: Here is a var_dump;

array(2) { ["count"]=> int(1) [0]=> array(64) { ["objectclass"]=> array(5) { ["count"]=> int(4) [0]=> string(3) "top" [1]=> string(6) "person" [2]=> string(20) "organizationalPerson" [3]=> string(4) "user" } [0]=> string(11) "objectclass" ["cn"]=> array(2) { ["count"]=> int(1) [0]=> string(14) "max.mustermann" } [1]=> string(2) "cn" ["sn"]=> array(2) { ["count"]=> int(1) [0]=> string(10) "Mustermann" } [2]=> string(2) "sn" ["givenname"]=> array(2) { ["count"]=> int(1) [0]=> string(3) "Max" } [3]=> string(9) "givenname" ["distinguishedname"]=> array(2) { ["count"]=> int(1) [0]=> string(69) "CN=max.mustermann,OU=Verwaltung,OU=UserDirectory,DC=example,DC=local" } [4]=> string(17) "distinguishedname" ["instancetype"]=> array(2) { ["count"]=> int(1) [0]=> string(1) "4" } [5]=> string(12) "instancetype" ["whencreated"]=> array(2) { ["count"]=> int(1) [0]=> string(17) "20230819234419.0Z" } [6]=> string(11) "whencreated" ["whenchanged"]=> array(2) { ["count"]=> int(1) [0]=> string(17) "20230819234419.0Z" } [7]=> string(11) "whenchanged" ["displayname"]=> array(2) { ["count"]=> int(1) [0]=> string(14) "Max Mustermann" } [8]=> string(11) "displayname" ["usncreated"]=> array(2) { ["count"]=> int(1) [0]=> string(5) "25065" } [9]=> string(10) "usncreated" ["usnchanged"]=> array(2) { ["count"]=> int(1) [0]=> string(5) "25067" } [10]=> string(10) "usnchanged" ["name"]=> array(2) { ["count"]=> int(1) [0]=> string(14) "max.mustermann" } [11]=> string(4) "name" ["objectguid"]=> array(2) { ["count"]=> int(1) [0]=> string(16) "�x�C�X�C�d�mwc�" } [12]=> string(10) "objectguid" ["useraccountcontrol"]=> array(2) { ["count"]=> int(1) [0]=> string(3) "546" } [13]=> string(18) "useraccountcontrol" ["badpwdcount"]=> array(2) { ["count"]=> int(1) [0]=> string(1) "0" } [14]=> string(11) "badpwdcount" ["codepage"]=> array(2) { ["count"]=> int(1) [0]=> string(1) "0" } [15]=> string(8) "codepage" ["countrycode"]=> array(2) { ["count"]=> int(1) [0]=> string(1) "0" } [16]=> string(11) "countrycode" ["badpasswordtime"]=> array(2) { ["count"]=> int(1) [0]=> string(1) "0" } [17]=> string(15) "badpasswordtime" ["lastlogoff"]=> array(2) { ["count"]=> int(1) [0]=> string(1) "0" } [18]=> string(10) "lastlogoff" ["lastlogon"]=> array(2) { ["count"]=> int(1) [0]=> string(1) "0" } [19]=> string(9) "lastlogon" ["pwdlastset"]=> array(2) { ["count"]=> int(1) [0]=> string(1) "0" } [20]=> string(10) "pwdlastset" ["primarygroupid"]=> array(2) { ["count"]=> int(1) [0]=> string(3) "513" } [21]=> string(14) "primarygroupid" ["objectsid"]=> array(2) { ["count"]=> int(1) [0]=> string(28) "��$!��٥w�`" } [22]=> string(9) "objectsid" ["accountexpires"]=> array(2) { ["count"]=> int(1) [0]=> string(19) "9223372036854775807" } [23]=> string(14) "accountexpires" ["logoncount"]=> array(2) { ["count"]=> int(1) [0]=> string(1) "0" } [24]=> string(10) "logoncount" ["samaccountname"]=> array(2) { ["count"]=> int(1) [0]=> string(14) "max.mustermann" } [25]=> string(14) "samaccountname" ["samaccounttype"]=> array(2) { ["count"]=> int(1) [0]=> string(9) "805306368" } [26]=> string(14) "samaccounttype" ["userprincipalname"]=> array(2) { ["count"]=> int(1) [0]=> string(29) "max.mustermann@example.local" } [27]=> string(17) "userprincipalname" ["objectcategory"]=> array(2) { ["count"]=> int(1) [0]=> string(57) "CN=Person,CN=Schema,CN=Configuration,DC=example,DC=local" } [28]=> string(14) "objectcategory" ["dscorepropagationdata"]=> array(2) { ["count"]=> int(1) [0]=> string(17) "16010101000000.0Z" } [29]=> string(21) "dscorepropagationdata" ["mail"]=> array(2) { ["count"]=> int(1) [0]=> string(21) "max.mustermann@example.de" } [30]=> string(4) "mail" ["count"]=> int(31) ["dn"]=> string(69) "CN=max.mustermann,OU=Verwaltung,OU=UserDirectory,DC=example,DC=local" } }



2023-08-20

Karate :Instead of sleep function in karate is there any wait conditions in karate?

In selenium we have explicit wait conditions and in karate is there any feature similar to explicit?

Currently i am using

def sleep = function(millis){}


2023-08-19

Need Help For This Error AttributeError: 'res.users' object has no attribute 'chatter_position' [closed]

I got this error message: AttributeError:'res.users' object has no attribute 'chatter position' Template: web.webclient_bootstrap Path: /t/t/t[5] Node: <t t-set="body_classname" t-value="'o_web_client' + ' o_chatter_position_' + (request.env.user.chatter_position or 'normal')"/> when i try to install theme for odoo14, but the instalation process is not 100% complete, becauses i waiting to long, i decide to refresh the browser page and try to access the localhost : 8069 again, but it give me the Internal Server Error. so i check the log file and then i see that error message.

I already tried to uninstall the module from the database and then restart the server but I'm still seeing the same error message.

Any solutions for my problem?



2023-08-18

Create a python dictionary from a .csv file

I have a comma separated file listing the fifty states followed by cities in that state. The structure of the file is as follows:

Alabama, Alexander City, Decatur, Florence, Gadsden, Greenville, Guntersville, Huntsville,...
Arizona, Ajo, Avondale, Bisbee, Casa Grande, Chandler, Clifton,...
Arkansas, Arkadelphia, Arkansas, West Memphis,...
California, Alameda, Alhambra, Anaheim, Yorba Linda, Yuba City,...
...

The first item of each row is the state followed by the list of cities. The number of cities varies from state to state. I want to create a dictionary such that the state is the key who's value is the list of cities.

Here is my code:

import csv

# initialize an empty dictionary, and an empty list
my_dict = dict()
cities = list()

# read the csv file
with open('cities.csv', 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    # process each row
    for row in csvreader:
        cities = row
        # pop the first item (state) off the list
        new_key = cities.pop(0)
        # store the key:value entry into the dictionary
        my_dict[new_key] = cities

# Print the results
print(my_dict)

I expected this: Results similar to a hash table.

{'Alabama' : ['Alexander City', 'Decatur', 'Florence', 'Gadsden', 'Greenville', 'Guntersville', 'Huntsville',]}
{'Arizona' : ['Ajo', 'Avondale', 'Bisbee', 'Casa Grande', 'Chandler', 'Clifton',]}
{'Arkansas' : ['Arkadelphia', 'Arkansas', 'West Memphis',]}
{'California' : ['Alameda', 'Alhambra', 'Anaheim', 'Yorba Linda', 'Yuba City',]}

but got this:

{'Alabama': [' Alexander City', ' Decatur', ' Florence', ' Gadsden', ' Greenville', ' Guntersville', ' Huntsville', ''], 'Arizona': [' Ajo', ' Avondale', ' Bisbee', ' Casa Grande', ' Chandler', ' Clifton', ''], 'Arkansas': [' Arkadelphia', ' Arkansas', ' West Memphis', ''], 'California': [' Alameda:', ' Alhambra', ' Anaheim', ' Yorba Linda', ' Yuba City', '']}

As you can see, I got one long row with the row having all the states and their associated cities. Maybe it is just the way I am printing it? Considering the actual csv file has up to 20 or more cities, some with 40 or more, for each state - the output is ridiculously long.



How to force all the traffic to http (no ssl) on vue3 project

i have problem with sending requests to https backend. currently i'm using laravel 10 as backend and vue 3 on front.

the problem is when i deploy (production version of laravel and built of vue) on a hosting service (you can visit on eros.pacode.ir), all requests when project (front) is loading on https and if i change base url to https and visit https version (preventing mix-content) all requests status in network devtool will be (failed) with "net::ERR_CERT_COMMON_NAME_INVALID" error.

  • and if you could please give a htaccess code to redirect all traffic to http

I lunched a demo at http://eros.pacode.ir User:admin Pass:password

Feel free to investigate...

front htaccess

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

back htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_URI} !/public
    RewriteRule ^(.*)$ public/ [L]
</IfModule>

and APP_URL in laravel .env is: http://localhost if any piece of code you need from any file (give me a small description), just add a comment.

thanks in advance :)



2023-08-17

Code is printing only the first index item in the list but not the rest

I have this web application that will allow a user to enter a Input id to get information for. For example:

Input: x632 

Output would be like:

Comp Unique ID: x123 Label of Page: Apple Name of Comp: Fruit

Comp Unique ID: x456 Label of Page: Water Name of Comp: Environment

Comp Unique ID: x789 Label of Page: Shirt Name of Comp: Clothing

HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" placeholder="name">
        <button type="submit">Submit</button>
    </form>
    <ol>
        
    </ol>
</body>
</html>

Python Code:

from flask import Flask, request, render_template
import xml.etree.ElementTree as ET
import datetime
import os
import csv
import re
import glob

app = Flask(__name__)

temp_storage = {}
    def myFunction(COMP, source="."):
        list_output = []
        for pathway in glob.glob(os.pathway.join(source,"x*.xml")):
            document = temp_storage.setdefault(pathway, ET.parse(pathway).getroot())
            theLocationPoint = document.findall('.//*[@Comp="' + COMP + '"]')
            if theLocationPoint:
                comp_unique_id = document.get("ID")
                comp_label = document.tag
                comp_name = document.get("Name")
                myFunction(comp_unique_id, source=source) 
                list_output.append("Comp Unique ID: " + comp_unique_id + " " + "Label of Page: " + comp_label + " " + "Name of Comp: " + comp_name)
                myFunction(comp_unique_id, source=source)
        return list_output
            

# Creating a route that has both GET and POST request methods
@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        name = request.form.get('name')
        #calling myFunction
        return_string = myFunction(name, source=r"C:/Sam/XMLContentFiles/")
        return render_template('my-form.html', result=return_string)
    return render_template('my-form.html', result='')

if __name__ == '__main__':
    app.run()

Question: The problem I am running into with this code is that this code prints only the first index of the list_output to the web page.

For example if I input

input: x632

The Output is:

Comp Unique ID: x123 Label of Page: Apple Name of Comp: Fruit

But the output should actually be:

Comp Unique ID: x123 Label of Page: Apple Name of Comp: Fruit

Comp Unique ID: x456 Label of Page: Water Name of Comp: Environment

Comp Unique ID: x789 Label of Page: Shirt Name of Comp: Clothing

Why is the code printing only the first index in the list? Is it not being appended properly? Is it ignoring the myFunction() recursive call? I am thinking there is something wrong with these lines of code but I am exactly sure why:

list_output.append("Comp Unique ID: " + comp_unique_id + " " + "Label of Page: " + comp_label + " " + "Name of Comp: " + comp_name)
myFunction(comp_unique_id, source=source)



2023-08-16

My sed command won't execute a rename of fastq.gz files using a .txt file as a reference, but will show me a desirable output

I am looking to write some code using dummy samples that will look at a confusing fastq.gz filename and rename it based on it's corresponding simple sample ID from a .txt file that contains both. I will eventually do this in one pass for hundreds of files so I want to dial it in on something small and lowrisk. I have written some empty txt files to pose as my fastq.gz filenames. The reference .txt file contains both sequence and sample IDs. I want to read the sequence ID's find a match and edit the file name in my dummy file to match the corresponding Sample ID

An example of a line from my .txt file:

52704.3.422276.TTGCGAAG-TTGCGAAG.fastq.gz S19_BESC 156_B1_d1

I have written code that shows a rename, but when I add the 'e' flag to it, it does nothing or it tells me sed: -e expression #1, char 1: unknown command:m'`

I have written: sed 's/\(\w+\.fastq\.gz\)/${SeqID%.fastq.gz} ${SampleID}/' BESC-156_Swaps.txt

To give me a desirable output of:

52704.3.422276.TTGCGAAG-TTGCGAAG.fastq.gz       S19_BESC 156_B1_d1
52704.3.422276.ACATAGGC-ACATAGGC.fastq.gz       S19_BESC 156_B1_d3
52704.3.422276.GTTGTAGC-GTTGTAGC.fastq.gz       S19_BESC 156_B1_d6
52704.3.422276.ACCACGAT-ACCACGAT.fastq.gz       S19_BESC 156_B1_d9
52704.3.422276.CTGAAGCT-CTGAAGCT.fastq.gz       S19_BESC 156_B1_d12
52704.3.422276.TCCTTAGC-TCCTTAGC.fastq.gz       S19_BESC 156_B1_d15
52704.3.422276.ACGACTTG-ACGACTTG.fastq.gz       S19_BESC 156_B2_d1
52704.3.422276.TGCTTCCA-TGCTTCCA.fastq.gz       S19_BESC 156_B2_d3
52704.3.422276.GCATACAG-GCATACAG.fastq.gz       S19_BESC 156_B2_d6
52704.3.422276.CTTCGTTC-CTTCGTTC.fastq.gz       S19_BESC 156_B2_d9
52704.3.422276.TGCGAACT-TGCGAACT.fastq.gz       S19_BESC 156_B2_d12
52704.3.422276.CATCGTGA-CATCGTGA.fastq.gz       S19_BESC 156_B2_d15
52704.3.422276.TCTCCGAT-TCTCCGAT.fastq.gz       S19_BESC 156_B3_d1
52704.3.422276.AGAGTAGC-AGAGTAGC.fastq.gz       S19_BESC 156_B3_d3
52704.3.422276.CAACACCT-CAACACCT.fastq.gz       S19_BESC 156_B3_d6
52704.3.422276.TTGTGTGC-TTGTGTGC.fastq.gz       S19_BESC 156_B3_d9
52709.1.423639.ACTGCTAG-ACTGCTAG.fastq.gz       S19_BESC 156_B3_d12
52709.1.423639.GTCATCGA-GTCATCGA.fastq.gz       S19_BESC 156_B3_d15

But when I add the 'e' flag:

sed -e 's/\(\w+\.fastq\.gz\)/${SeqID%.fastq.gz} ${SampleID}/' BESC-156_Swaps.txt

I get nothing. Or if I do this:

sed 's/\(\w+\.fastq\.gz\)/${SeqID%.fastq.gz} ${SampleID}/' -e 'mv $1 $2' BESC-156_Swaps.txt

I get:

sed: -e expression #1, char 1: unknown command: m'`

Thank you in advance this type of code really gets me hung up.



2023-08-15

Failed to connect to localhost/127.0.0.1:44393

In my code, the 'error message' part keeps returning as the response, and the try-catch section is not functioning.

TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState){ `This function is working`
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button b = (Button) findViewById(R.id.btn1);
    tv1 = (TextView) findViewById(R.id.txtview2);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tv1.setText("sunucu cevabı");
            new arkaPlan().execute("https://localhost:44393/api/Arac");
        }

    });
}
//

package com.ilkdeneme.aracyakittakibi;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.net.NetPermission;
import java.security.Permission;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {

    TextView tv1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b = (Button) findViewById(R.id.btn1);
        tv1 = (TextView) findViewById(R.id.txtview2);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv1.setText("sunucu cevabı");
                new arkaPlan().execute("https://localhost:44393/api/Arac");
            }

        });
    }
    //

    class arkaPlan extends AsyncTask<String,String,String> {
        @Override
        protected String doInBackground(String ... params) {

            HttpURLConnection connection = null;
            BufferedReader br = null;
            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
                InputStream is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is));
                String satir= "";
                String dosya = "";
                while ((satir = br.readLine()) != null) {
                    Log.d("satir:", satir);
                    dosya += satir;
                }
                Log.d("dosya:", dosya);
                return dosya;

            } catch (Exception e) {
              e.printStackTrace();

            }
            return "hata mesajı";

        }
        protected void onPostExecute(String s){
            Log.d("postExecutetangelen", s);
            tv1.setText(s.toString());
        }
    }

}

The error I got.

I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
W/System.err: java.net.ConnectException: Failed to connect to localhost/127.0.0.1:44393
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:1417)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:1367)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:219)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:142)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:104)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:392)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:325)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:489)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(Unknown Source:0)
W/System.err:     at com.ilkdeneme.aracyakittakibi.MainActivity$arkaPlan.doInBackground(MainActivity.java:51)
W/System.err:     at com.ilkdeneme.aracyakittakibi.MainActivity$arkaPlan.doInBackground(MainActivity.java:41)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
W/System.err:     at java.lang.Thread.run(Thread.java:764)


Permissions Denied with Firebase Messaging for notifications

I've checked my service permissions and theye are fine, the users have read/write permissions for EventCards so long as they are in the userID field. I've enabled the cloud messaging API.

Here is the error:

W/Firestore( 7028): (24.7.0) [Firestore]: Listen for Query(target=Query(Users/6jmDcBDb0aNy5XJ9gVwu9tFbyhm2 order by __name__);limitType=LIMIT_TO_FIRST) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}
E/flutter ( 7028): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation.
E/flutter ( 7028): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:652:7)
E/flutter ( 7028): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:310:18)
E/flutter ( 7028): <asynchronous suspension>
E/flutter ( 7028): #2      MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:510:43)
E/flutter ( 7028): <asynchronous suspension>
E/flutter ( 7028): #3      MethodChannelDocumentReference.get (package:cloud_firestore_platform_interface/src/method_channel/method_channel_document_reference.dart:69:42)
E/flutter ( 7028): <asynchronous suspension>
E/flutter ( 7028): #4      _JsonDocumentReference.get (package:cloud_firestore/src/document_reference.dart:148:7)
E/flutter ( 7028): <asynchronous suspension>
E/flutter ( 7028): 

Here is the code that actions it:

class _EventCardState extends State<EventCard> {
  bool _isCancelled = false;

  Future<void> _cancelEvent(BuildContext context) async {
    final currentUserUid = FirebaseAuth.instance.currentUser!.uid;
    final eventRef = FirebaseFirestore.instance.collection('Events').doc(widget.documentId);
    final eventSnapshot = await eventRef.get();
    final userIds = List<String>.from(eventSnapshot.data()?['userID'] ?? []);
    final cancelledUserIds = List<String>.from(eventSnapshot.data()?['cancelledUserIDs'] ?? []);
    final userIDs = List<String>.from(eventSnapshot.data()?['userID'] ?? []);
// Create a notification payload
    final notificationPayload = {
      'title': 'Event Cancelled',
      'body': 'The event "${widget.titleEvent}" has been cancelled.',
    };

    if (userIds.contains(currentUserUid)) {
      setState(() {
        _isCancelled = !_isCancelled;
      });

      if (_isCancelled) {
        cancelledUserIds.add(currentUserUid);
      } else {
        cancelledUserIds.remove(currentUserUid);
      }

      await eventRef.update({'cancelledUserIDs': cancelledUserIds});

      if (cancelledUserIds.length == userIds.length &&
          cancelledUserIds.toSet().containsAll(userIds.toSet())) {
        await showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('${widget.titleEvent} has been cancelled'),
          ),
        );

        for (String userID in userIDs) {
          FirebaseFirestore.instance
              .collection('Users')
              .doc(userID)
              .get()
              .then((userDocument) {
            if (userDocument.exists) {
              final fcmToken = userDocument.data()!['fcmToken'];
              FirebaseMessaging.instance.sendMessage(to: fcmToken, data: notificationPayload);
            }
          });
        }

        await eventRef.delete();
      } else {
        await showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text(
                'You have voted to ${_isCancelled ? 'cancel ' : 'uncancel '}${widget.titleEvent}'),
          ),
        );

        await eventRef.update({'cancelledUserIDs': cancelledUserIds});
      }
    }
  }

I've stopped and re-run the app, updated the dependencies, and checked permissions. The only thing I'm not sure of is my fcmToken handling.

EDIT:

See rules below

rules_version = '2'; ​ service cloud.firestore {   match /databases/{database}/documents {

match /Events/{docId} { 
  allow read, write: if request.auth != null;
}   } }


2023-08-14

Astro server endpoints with nodejs adapter has empty header

I am following this tutorial: [Astro with Firebase][1]https://ift.tt/nDzfRLM and everything works as expected after I run npm run dev. However when I run npm run build and start the server with node ./dist/server/entry.mjs I am not able to access headers from the request sent to server. Here is the server endpoint code:


export const get: APIRoute = async ({ request, cookies, redirect }) => {
  /* Get token from header*/
  const idToken = request.headers.get("Authorization")?.split("Bearer ")[1];
  if (!idToken) //idToken null
{
    return new Response(
      "No token found",
      { status: 401 }
    );
  }
 ...
  return redirect("/dashboard");
};

I am running newest version of Astro with SSR nodejs (hybrid rendering.

So far I tried:

  1. Use axios instead of request for HTTP get request
  2. Different version of node (18 /20)
  3. Add token as a param after my base url (localhost:3000/api/auth?token) - it seems that only plain URL is available on the server side.

Thanks for any ideas.



2023-08-13

How can I set the "lifecycle" option for my project?

I am currently in the process of learning Swift as a beginner and I am using Xcode 14.2 for my learning journey.

In the tutorial book I am following, it mentions the ability to configure the "lifecycle" within UIKit App Delegate.

However, I have encountered a challenge in locating this particular option when I attempt to initiate a new project.

I would greatly appreciate it if someone could kindly guide me on how to properly set up the "lifecycle" for a project within the context of my current Xcode version.

Alternatively, I wonder if it is unnecessary to perform this step anymore due to the advancements in Xcode versions 12 and above.

Thank you ever so much for your time and assistance.

Create project - step 1 Create project - step 2

Tried: Try to find "lifecycle" option in "General" tab of project. enter image description here

Expecting: Understand how to set "lifecycle" within UIKit App Delegate



2023-08-12

ClassNotFoundException com.twilio.voice.CallInvite when reading ConnectionService Bundle extras in onCreateIncomingConnection

I'm upgrading a Flutter library to use a Twilio Voice integrated with a ConnectionService for native call management. To accomplish this, one has to extend a ConnectionService (inherits from a Service with associated communication methods, i.e. Intents)


Background & Context

To receive incoming call (via a notification manager like FCM), one needs to notify the ConnectionService of an incoming call using

override fun onCreateIncomingConnection(connectionManagerPhoneAccount: PhoneAccountHandle?, request: ConnectionRequest?): Connection {
    super.onCreateIncomingConnection(connectionManagerPhoneAccount, request)
    Log.d(TAG, "onCreateIncomingConnection")'
    // ... code goes here
    // return new Connection(...)
}

With this onCreateIncomingConnection, it will ask the native 'Phone Call' app to show an incoming call with parameters you provide, e.g. showing the incoming caller number with Connection.setAddress

This additional information can be passed into the ConnectionService by adding them to an extras Bundle with the Key TelecomManager.EXTRA_INCOMING_CALL_EXTRAS (for incoming calls) which is then added to a new Bundle e.g.

Source

private fun handleFCMCallInvite(callInvite: CallInvite, notificationId: Int) {
    // Get telecom manager
    val telecomManager = getSystemService(TELECOM_SERVICE) as TelecomManager

    // Get PhoneAccountHandle
    val caller = callInvite.from!!.toString()
    val componentName = ComponentName(applicationContext.packageName, TwilioVoiceConnectionService::class.java.name)
    val phoneAccountHandle = PhoneAccountHandle(componentName, caller)

    // Create my Bundle containing information e.g. notificationId and callInvite
    val myBundle = Bundle()
    myBundle.putInt(Constants.INCOMING_CALL_NOTIFICATION_ID, notificationId)
    myBundle.putParcelable(Constants.INCOMING_CALL_INVITE, callInvite)

    // Add new incoming call to the telecom manager
    telecomManager.addNewIncomingCall(phoneAccountHandle, Bundle().apply {
        putBundle(EXTRA_INCOMING_CALL_EXTRAS, myBundle)
        putParcelable(EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle)
    })
}

Problem

The issue comes in when trying to unparcel() the CallInvite from Bundled extras in the ConnectionService's onCreateIncomingConnection implementation, see as follows:

override fun onCreateIncomingConnection(connectionManagerPhoneAccount: PhoneAccountHandle?, request: ConnectionRequest?): Connection {
    super.onCreateIncomingConnection(connectionManagerPhoneAccount, request)
    Log.d(TAG, "onCreateIncomingConnection")
    val connection: Connection = VoipConnection(applicationContext)
    connection.extras = request?.extras

    var ci: CallInvite? = null
    val myBundle: Bundle? = connection.extras.getBundle(TelecomManager.EXTRA_INCOMING_CALL_EXTRAS);
    if(myBundle != null) {
        Log.d(TAG, "onCreateIncomingConnection: myBundle is not null")

        /// --------------------------------------------------------
        /// This next line throws the ClassNotFoundException occurs
        /// --------------------------------------------------------
        if (myBundle.containsKey(Constants.INCOMING_CALL_INVITE) ) { 
            Log.d(TAG, "onCreateIncomingConnection: myBundle contains INCOMING_CALL_INVITE")
            ci = myBundle.getParcelable(Constants.INCOMING_CALL_INVITE)
        } else {
            Log.d(TAG, "onCreateIncomingConnection: myBundle does not contain INCOMING_CALL_INVITE")
        }
    } else {
        Log.d(TAG, "onCreateIncomingConnection: myBundle is null")
    }

    ...
}

As shown in the snippet above, when calling myBundle.containsKey() with a valid key any time I have a CallInvite object bundled in. If I only pass in e.g. notificationId, contains and accessors work as intended.

When including the CallInvite in the bundle, I get the following exception:

*Note: CallInvite implements Parcelable

Class not found when unmarshalling: com.twilio.voice.CallInvite
java.lang.ClassNotFoundException: com.twilio.voice.CallInvite
    at java.lang.Class.classForName(Native Method)
    at java.lang.Class.forName(Class.java:454)
    at android.os.Parcel.readParcelableCreator(Parcel.java:3403)
    at android.os.Parcel.readParcelable(Parcel.java:3337)
    at android.os.Parcel.readValue(Parcel.java:3239)
    at android.os.Parcel.readArrayMapInternal(Parcel.java:3636)
    at android.os.BaseBundle.initializeFromParcelLocked(BaseBundle.java:292)
    at android.os.BaseBundle.unparcel(BaseBundle.java:236)
    at android.os.BaseBundle.containsKey(BaseBundle.java:516)
    at com.twilio.twilio_voice.connectionservice.TwilioVoiceConnectionService.onCreateIncomingConnection(TwilioVoiceConnectionService.kt:43)
    at android.telecom.ConnectionService.createConnection(ConnectionService.java:2061)
    at android.telecom.ConnectionService.access$400(ConnectionService.java:96)
    at android.telecom.ConnectionService$2$1.loggedRun(ConnectionService.java:914)
    at android.telecom.Logging.Runnable$1.run(Runnable.java:37)
    at android.telecom.ConnectionService.onAccountsInitialized(ConnectionService.java:3272)
    at android.telecom.ConnectionService.access$5000(ConnectionService.java:96)
    at android.telecom.ConnectionService$5$1.loggedRun(ConnectionService.java:2577)
    at android.telecom.Logging.Runnable$1.run(Runnable.java:37)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:226)
    at android.os.Looper.loop(Looper.java:313)
    at android.app.ActivityThread.main(ActivityThread.java:8663)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
Caused by: java.lang.ClassNotFoundException: com.twilio.voice.CallInvite
    at java.lang.Class.classForName(Native Method)
    at java.lang.BootClassLoader.findClass(ClassLoader.java:1358)
    at java.lang.BootClassLoader.loadClass(ClassLoader.java:1418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at java.lang.Class.classForName(Native Method) 
    at java.lang.Class.forName(Class.java:454) 
    at android.os.Parcel.readParcelableCreator(Parcel.java:3403) 
    at android.os.Parcel.readParcelable(Parcel.java:3337) 
    at android.os.Parcel.readValue(Parcel.java:3239) 
    at android.os.Parcel.readArrayMapInternal(Parcel.java:3636) 
    at android.os.BaseBundle.initializeFromParcelLocked(BaseBundle.java:292) 
    at android.os.BaseBundle.unparcel(BaseBundle.java:236) 
    at android.os.BaseBundle.containsKey(BaseBundle.java:516) 
    at com.twilio.twilio_voice.connectionservice.TwilioVoiceConnectionService.onCreateIncomingConnection(TwilioVoiceConnectionService.kt:43) 
    at android.telecom.ConnectionService.createConnection(ConnectionService.java:2061) 
    at android.telecom.ConnectionService.access$400(ConnectionService.java:96) 
    at android.telecom.ConnectionService$2$1.loggedRun(ConnectionService.java:914) 
    at android.telecom.Logging.Runnable$1.run(Runnable.java:37) 
    at android.telecom.ConnectionService.onAccountsInitialized(ConnectionService.java:3272) 
    at android.telecom.ConnectionService.access$5000(ConnectionService.java:96) 
    at android.telecom.ConnectionService$5$1.loggedRun(ConnectionService.java:2577) 
    at android.telecom.Logging.Runnable$1.run(Runnable.java:37) 
    at android.os.Handler.handleCallback(Handler.java:938) 
    at android.os.Handler.dispatchMessage(Handler.java:99) 
    at android.os.Looper.loopOnce(Looper.java:226) 
    at android.os.Looper.loop(Looper.java:313) 
    at android.app.ActivityThread.main(ActivityThread.java:8663) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) 
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

Libraries, etc

build.gradle (module)

buildscript {
    ext.kotlin_version = '1.8.0'

    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.4.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
...
android {
    compileSdk 33
    ...
}
...
dependencies {
    ...
    implementation("com.twilio:voice-android:6.2.1")
    implementation("com.google.firebase:firebase-messaging-ktx:23.2.1")
    ...
}

UPDATE 1

Using the last working solution (Java), I resolved to parcelling and unparcelling immediately to emulate what's happening in the background, seems there might be a problem here.

public class VoiceFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(final RemoteMessage remoteMessage) {
        // ... valid message
        handleInvite(callInvite, notificationId);
        //...
    }

    private void handleInvite(CallInvite callInvite, int notificationId) {
        Parcel p = Parcel.obtain();
        p.writeParcelable(callInvite, 0);
        ClassLoader classLoader = getApplicationContext().getClassLoader();
        CallInvite ci = p.readParcelable(classLoader); // <----------------- ci is always null
        if(ci != null){
            Log.d(TAG, "handleInvite: " + ci.getCallSid());
        } else {
            Log.d(TAG, "handleInvite: null");
        }
    }

}

The same occurs on with Kotlin, though I get a ClassNotFoundException for CallInvite.

So far, I've traced the issue to Parcel.readParcelableCreator(@Nullable ClassLoader) (for Android 11, API 30)

public final Parcelable.Creator<?> readParcelableCreator(@Nullable ClassLoader loader) {
        String name = readString();
        if (name == null) {
            return null;
        }
        Parcelable.Creator<?> creator;

name is always null, thus returns null when calling Parcel.readParcelable.

This occurs on both Android 11 & 12 (API 30, 31)



2023-08-11

Pass Ethernet Interface Alias as value to create a secondary IP on that Interface

I have a couple of VM's in Azure that I need to temporary add secondary IP in the Windows Server (guest os). I don't know the Interface Aliases of NIC's present in that systems (systems will be newly generated by ASR), I know the primary IP's assigned.

I need to add secondary IP to only one existing NIC in the OS, I plan to use command: New-NetIPAddress -IPAddress xxx.xxx.xxx.xxx -InterfaceAlias "NAME" -SkipAsSource $true

How can I grab name of Interface Alias from this NIC and put on command above, or maybe there is some other solution to do that?

Thanks from advance for every help.

Current code:

$PrimaryIP = "10.20.30.5"
$NetworkInterface = Get-NetIPConfiguration | Where-Object { $_.IPv4Address.IPAddress -eq $PrimaryIP }

$InterfaceAlias = $NetworkInterface.InterfaceAlias

$SecondaryIP = "10.20.30.6"  
New-NetIPAddress -IPAddress $SecondaryIP -InterfaceAlias $InterfaceAlias -PrefixLength 24 -SkipAsSource $false

Start-Sleep -Seconds 60

New-NetRoute -DestinationPrefix 0.0.0.0/0 -InterfaceAlias $InterfaceAlias -NextHop 10.20.30.1


2023-08-10

Decoding G711 encoded rtp payloads and generating an audio file [closed]

I've wrote a code in python to capture network traffic, identify when a voip call starts based on an implemented logic for the softphone im using, then extract the rtp payload of each rtp packet, decode it, save it in a data list, then it gets passed to a function to generate an audio file of the audio captured from the rtp packets.

now the code works but the audio is not perfect..

now my question is, where is the issue exactly ? is it in the decoding part ? or the way im handling the packets ? I can't pinpoint the issue and would appreciate any help you can give.

Kindly check this video https://streamable.com/s8c0t9 to help understand the issue more. the generated audio is played in second 15 which shows that the audio is not as it should be.

Ideally the generated audio file should contain the voip call audio exactlyt as it is.

Current code can be found here : https://github.com/OsaidAlHasan/Osaid-Al-Hasan/blob/master/G711%20Code



2023-08-09

Is there a way to documentally confirm that the whole C++ standard or g++ compiler with hardware satisfy exactly IEEE 754 2008?

Is there some one place in C++ standard or g++ where it is declerated that the compiler or standard satisfies IEEE-754 2008

I notice some references to IEEE-754 2008 standard in C++17 standard and a lot of them in C++20 standard. But does it mean that C++ standards satisfy IEEE-754 2008 only in some specific considerations declared in C++ standard(one or another).

Or maybe there is some way to confirm that the whole standard satisfy IEEE-754 2008

How can I confirm documentally, that the program I wrote will work with fp-numbers in the way IEEE-754 2008 states? And can I do so?



2023-08-08

OSINT instagram tool - Terra - Usage

I properly installed the tool as shown in Github: xadhrit/terra

When I run the program:

python3 terra.py username

It shows enter image description here

I have modified the insta.yml file as my own Instagram account: enter image description here

But I always get the above result.... Could someone help to find out?

Thank you



2023-08-07

How to convert Figma design to HTML5/CSS?

I am making an app using Django and Python and I want to integrate some Figma designs with my web application. Does anyone know how to do this?



2023-08-06

Animate a Reanimated Animated.View from zero width to flex fill smoothly

I have a react-native-reanimated View that is zero width when flex: 0 and fills available width when flex: 1.

I want to animate the transition smoothly, making the view animate from 0 width to fill availabla width dynamically, while also animating any elements as it grows:

[#1 first elem] -- [#2 elem i want to grow] -- [#3 elem that should be pushed animated because #2 grows animated]

In my initial view, as #2 has zero width, it looks like [#1] -- [#3]. I want to animate flex of #2 from 0 to 1, but it animates immediately to full width instead of smoothly animating. I can imagine why this happens (as flex is relative, there is no difference between non-zero values as long as it's the only flex-filling element) but don't know how to solve it.

Given that:

  • The full width of my animating element is dynamic
  • The elements after the animating element also need to be pushed animated in the layout

How can I animate a Reanimated View to grow in size and animatedly push any elements after it in the layout?

I'm using Reanimated 3.4.1.



2023-08-05

Grouping values inside of a dict of Dataframes

Scenario: I have one dict of Dataframes. Each of those Dataframes contains the data for one year (2017 to 2022). They have each two columns, the Code and the Value (where the value column name is simply the year of that given Dataframe).

Input Data Sample:

Code    2017
33200   6957
33200   151906
33200   142025
33200   729494
33200   68842
32420   153499
32320   1756310
32320   33949
32310   81860
32310   56127
32200   165520

Each of the Dataframes has the same list of codes, only difference is the year.

Expected output:

Code    2017
33200   1099224
32420   153499
32320   1790259
32310   137987
32200   165520

Objective: I am trying to do a groupby code to sum each value for that given code (similar to an SUMIF).

Issue: When I run the code below, the output dictionary is exactly the same as the input.

Code:

year_list_1 = [2017,2018,2019,2020,2021,2022]
sales_dict_2={}
for year_var in year_list_1:
    sales_dict_2[year_var] = sales_dict[year_var].groupby('Code',as_index=False)[[year_var]].sum() # where sales_dict is the dictionary mentioned above
    

Question: Why is this code outputting the same DF as the input DF?



Recreating shape using CSS

I'm trying to recreate the shape from the image below with CSS only.

image

This is what I've tried:

<svg width="450" height="50">
      <defs>
        <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" style="stop-color:#555;stop-opacity:1" />
          <stop offset="100%" style="stop-color:#333;stop-opacity:1" />
        </linearGradient>
        <filter id="f1" x="0" y="0">
          <feDropShadow dx="0" dy="4" stdDeviation="3"/>
        </filter>
      </defs>
      <path d="M0,0 L450,0 L450,20 L300,20 C270,20 250,50 230,50 L0,50 Z" fill="url(#grad1)" />
      <path d="M0,0 L450,0 L450,20 L300,20 C270,20 250,50 230,50 L0,50 Z" fill="transparent" filter="url(#f1)" />
  </svg>

It is very similar but it is not the same curve I want to achieve and I've used SVG. How to do it with CSS and how to make exactly the same curve?

Here is where I' am stuck with css (I've marked the place for the curve with red color):

<!DOCTYPE html>
<html>
<head>
<style>

#top-rectangle {
    height: 50px;
    width: 250px;
    background-color: #555;
}

#bottom-rectangle {
    height: 20px;
    width: 250px;
    background-color: #555;
    margin-left: 250px;
    margin-top: -50px;
}

#curve {
    height: 30px;
    width: 2px; 
    background-color: red;
    margin-left: 250px;
}

#curve2 {
    height: 2px;
    width: 30px; 
    background-color: red;
    margin-left: 250px;
    margin-top: -30px;
}

</style>
</head>
<body>
<div id="top-rectangle"></div>
<div id="bottom-rectangle"></div>
<div id="curve"></div>
<div id="curve2"></div>
</body>
</html>


Spring boot application reads messages from kafka after deleting them

I have spring boot application which reads messages from Kafka and I can't understand one behavior. I have set kafka properties regarding max poll size to:

spring:
  kafka:
    consumer:
      max-poll-records: 5
    listener:
      ack-mode: record
      concurrency: 1
logging:
  level:
    org.springframework.kafka.listener.KafkaMessageListenerContainer: DEBUG

And I can see that messages are read in packages by 5 in each:

2023-08-04T13:21:25.053+02:00 DEBUG [,] 12001 --- [ntainer#0-0-C-1] o.s.k.l.KafkaMessageListenerContainer    : Received: 5 records
//Handling first 4 messages
2023-08-04T13:21:57.114+02:00  INFO [,] 12001 --- [ntainer#0-0-C-1] SomeListener: Handling command message

2023-08-04T13:22:05.134+02:00 DEBUG [,] 12001 --- [ntainer#0-0-C-1] o.s.k.l.KafkaMessageListenerContainer    : Received: 5 records
2023-08-04T13:22:05.135+02:00  INFO [,] 12001 --- [ntainer#0-0-C-1] SomeListener: Handling command message
//Handling next 4 messages

I sent 200 messages to topic and deleted them (with kafka-ui and also by setting retention.ms) after processing started to check if application really fetch 5 messages in poll. But even if messages are not in the topic application still is able to read all messages which are sent. I can't understand why. Is it a normal behaviour that kafka allows consumer which already started to read all messages, even these deleted?



Why Pending Developer Release taking a long time?

My app was approved by the app review. But Pending Developer Release. How much time take for this?



mmenu Wrapping All Body Elements Instead of Page Selector

I've got mmenu up and running and doing everything I need it to do, except that it's breaking my sticky footer because it is automatically wrapping all code inside <body>.

My script has

page: { selector: "#page" }

and I have the content I want to be wrapped inside <div id="page"></div> and yet it still wraps around everything.

I am using the latest version from mmenujs.com.

Here's an example layout of what I've got:

<html>
<head>
    <link href="mmenu/mmenu.css" rel="stylesheet" />
</head>
<body style="min-height: 100vh; display: flex; flex-direction: column;">
    <div id="page">All the page content</div>
    <div id="footer" style="padding-top: 30px; padding-bottom: 20px; margin-top: auto;">My sticky footer</div>
    <nav id="navmenu">
        <ul>
            <li><span>HOME</span></li>
            <li><span>Example</span>
            <ul>
                <li><span>Test</span></li>
            </ul>
            </li>
        </ul>
    </nav>
    <script src="mmenu/mmenu.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            function mediaqueryresponse(mql) {
                var mmenuOptions = {
                    navbar: {
                        title: "My Menu"
                    },
                    offCanvas: {
                        page: {
                            selector: "#page"
                         },
                        position: "left-front"
                    },
                    pageScroll: {
                        scroll: true,
                        update: true
                    },
                    setSelected: {
                        current: "detect",
                        hover: true
                    },
                    sidebar: {
                        collapsed: {
                            use: "(min-width: 50px)"
                        },
                        expanded: {
                            use: "(min-width: 1024px)"
                        }
                    },
                    theme: "dark-contrast"
                };

                if (mql.matches) {
                    mmenuOptions.navbars = [
                        {
                            position: "top",
                            content: [
                                "prev",
                                "title",
                                "close"
                            ]
                        }
                    ];
                } else {
                    mmenuOptions.navbars = [
                        {
                            position: "top",
                            content: [
                                "prev",
                                "title"
                            ]
                        }
                    ];
                }

                new Mmenu("#navmenu", mmenuOptions);
            }

            const mql = window.matchMedia("screen and (max-width: 900px)");
            mediaqueryresponse(mql);
            mql.addListener(mediaqueryresponse);
        });
    </script>
</body>
</html>

What happens is this:

<div id="mm-4" class="mm-page mm-slideout">
<div id="page"></div>
<div id="footer"></div>
</div>

which breaks my sticky footer.

I need it to be:

<div id="mm-4" class="mm-page mm-slideout">
<div id="page"></div>
</div>
<div id="footer"></div>

I know offCanvas is working because I can change position to be "right-front" and the menu appears on the right. I also have confirmed that #page is in the DOM before the function runs.

Of course without mmenu, my sticky footer works perfectly.

Not sure what I'm doing wrong, but appreciate any help. Thanks!



2023-08-04

How to automate aws sagemaker studio notebook

I am quite new to AWS and trying to run AWS Sagemaker Studio Notebook when file is uploaded to S3.

I came to know that there is a difference between AWS Sagemaker Notebook Instance and AWS Sagemaker Studio Notebook. Got approaches to run AWS Sagemaker Notebook Instance but not getting anything related to AWS Sagemaker Studio Notebook.



2023-08-03

Regex Split Match AND Group [duplicate]

I've a little regex (\d\.){2,} to split Chapters of a Book. The Chapters are recognized as a single digit followed by a dot and this combination occures at least twice. It should just split Chapters no single listings. Here's an example:

3.2.4.2. porta pellentesque   
139. Nunc maximus maximus aliquet? 
 a) dignissim 
 b) volutpat  
 c) ullamcorper  

3.2.4.3. ligula at condimentum fringilla  
152. Sed dapibus nulla mi, id lobortis ligula bibendum vehicula?  
 a) vestibulum   
 b) pellentesque   
 c) tempus   
 d) rutrum   
 
153. Lorem ipsum dolor sit amet. Sed iaculis lacus pellentesque, non auctor eros lobortis?  
 a) suscipit   
 b) vulputate   
 c) vestibulum   
 d) congue   
 
3.2.5. elementum quis  

It should be split at 3.2.4.2., 3.2.4.3. and 3.2.5. The regex Builder recognize the correct match but it always add an unwanted group match at the end and i don't get rid of that. The result looks like (one Bullet is one split):

  • 3.2.4.
  • 2.
  • ...

  • 3.2.4.
  • 3.
  • ...

  • 3.2.
  • 5.
  • ...

I want it to be three splits not nine. I tried it with greedy/lazy quantifiers, various encapsulations but unfortunately I didn't get it right. What may be worth mentioning is that the whole thing should run in a python project. For a better understanding here is the link to the regexbuilder I used.



2023-08-02

Sed-Script to comment out lines between two multiline markers A\nB and U\nV

I have the file "test" with the content in (1). I want a sed script, that edits "test" so that i have the output in (2).

I cannot not simply do this:

cat test | sed -E '1,/B/!{/U/,$!s/.+/# &/}'

...because it would start commenting out beginning from first 'B' and not from 'A\nB'.

(1)

X
X

B

A
B

X
X
X

U

U
V

X
X

(2)

X
X

B

A
B

# X
# X
# X

# U

U
V

X
X


2023-08-01

Owasp Zap and GitHub Action

We have integrated OWASP ZAP in GitHub Action CI/CD. After scanning a web application, we then relayed the issues to the developers. After the developers have assessed the issues, they found out that some of the issues found are false positives. So the problem is, how do we configure ZAP to mark those issues as False Positives on the next run in the pipeline? We are using the stable version of OWASP ZAP Docker image. All of your inputs are much welcome, thank you!

I tried integrating a Jason rule file but GitHub ignore to take that into consideration



Flutter: use SVG as a Button and change color onPressed state

I want to create an icon button from an SVG. The icon, i.e. the SVG hast to change its color, when the button is in pressed state.

What I have is this:

TextButton(
   style: (disabled) ? iconButtonStyleDisabled : iconButtonStyle,
   onPressed: (!disabled) ? _onPressed : null,
   child: SvgPicture.asset(iconPath, ...));

Unfortunately SvgPicture doesn't care about the TextButtons state, so it won't change it's color. Nevertheless, it works like a charm with an Icon() as a child so my styles are working as intended.

I tried FlutterIcon.com, but when uploading my SVGs they get scrapped, so this won't work either. Maybe I can switch the whole SVG-child of the TextButton depending on it's state?

Any ideas?

Here's my iconButtonStyle which works fine with simple TextButtons and Icon as a child:

ButtonStyle get iconButtonStyle => ButtonStyle(
  shape: MaterialStateProperty.all<BeveledRectangleBorder>(const BeveledRectangleBorder()),
  foregroundColor: getColor(defaultColor: green_medium, pressedColor: context.theme.contentPrimary!), // TextColor
  iconColor: getColor(defaultColor: green_medium, pressedColor: context.theme.contentPrimary!), // TextColor
  backgroundColor: MaterialStateProperty.all(Colors.transparent),
  surfaceTintColor: getColor(defaultColor: green_medium, pressedColor: context.theme.contentPrimary!), // TextColor
  overlayColor: MaterialStateProperty.all(Colors.transparent));

MaterialStateProperty<Color> getColor({required Color defaultColor, required Color pressedColor}) {
getColor(Set<MaterialState> states) {
  if (states.contains(MaterialState.pressed)) {
    return pressedColor;
  }
  return defaultColor;
}

return MaterialStateProperty.resolveWith(getColor);
}