Saturday 31 December 2022

React native app crashing android 13 production but fine on android 11

I made a react app and it was working fine using the expo app to test it. I built in for production and on my phone i found it would open once and crash everyother time if it would open after building. (I am using andriod 13) i sent it to a friend using andriod 11 and it works perfectly. I belive the problem is wiht one of the packages i am using.

So I have changed and some of the packages and added information in the app.json file as i have seen on other stackoverflow posts but have not had any luck.

this is my app.json

{
  "expo": {
    "name": "Finder",
    "slug": "finder",
    "version": "2.3.1",
    "orientation": "portrait",
    "icon": "./assets/icon.png",
    "userInterfaceStyle": "light",
    "splash": {
      "image": "./assets/splash.png",
      "resizeMode": "contain",
      "backgroundColor": "#ffffff"
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ],
    "ios": {
      "supportsTablet": true,
      "bundleIdentifier": "apple.spoonfinder.ml"
    },
    "android": {
      "adaptiveIcon": {
        "foregroundImage": "./assets/adaptive-icon.png",
        "backgroundColor": "#FFFFFF"
      },
      "package": "com.im_the_tea_drinker.spoon_finder"
    },
    "web": {
      "favicon": "./assets/icon.png"
    },
    "extra": {
      "eas": {
        "projectId": "2f14cfae-f990-4aab-9d8e-ca06ea8bec1d"
      }
    }
  }
}

and theses are the packages i am using



{
  "name": "finder",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "expo": "~47.0.8",
    "expo-cli": "^6.0.8",
    "expo-location": "~15.0.1",
    "expo-permissions": "~14.0.0",
    "expo-sensors": "~12.0.1",
    "expo-status-bar": "~1.4.2",
    "geolib": "^3.3.3",
    "react": "18.1.0",
    "react-dom": "18.1.0",
    "react-native": "0.70.5"
  },
  "devDependencies": {
    "@babel/core": "^7.19.3"
  },
  "private": true
}

Does any one know what could be coursing this and how i can fix it?



from React native app crashing android 13 production but fine on android 11

React Query optimistic update with React Spring animation

I'm using react query mutation to create an object and update UI optimistically

const queryClient = useQueryClient()

useMutation({
    mutationFn: updateTodo,
    onMutate: async newTodo => {
        await queryClient.cancelQueries({ queryKey: ['todos'] })
        const previousTodos = queryClient.getQueryData(['todos'])

        // Optimistically update to the new value
        queryClient.setQueryData(['todos'], old => [...old, newTodo])

        return { previousTodos }
    },
    onError: (err, newTodo, context) => {
        queryClient.setQueryData(['todos'], context.previousTodos)
    },
    onSettled: () => {
        queryClient.invalidateQueries({ queryKey: ['todos'] })
    },
})

New in-memory todo item have some random ID and displayed in UI with React Spring animation. Then i get response from server with success confirmation and real todo item ID. My application replaces and reanimates UI element and this is the problem. Optimistic update is must-have feature, but i don't know how to stop this behaviour. Need help



from React Query optimistic update with React Spring animation

Hilt - Question on making a Dao object in a module a Singleton

I'm following the tutorial on dependency injection with Hilt using the Google Sunflower app repo:

@InstallIn(SingletonComponent::class)
@Module
class DatabaseModule {

    @Singleton
    @Provides
    fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase {
        return AppDatabase.getInstance(context)
    }

    @Provides
    fun providePlantDao(appDatabase: AppDatabase): PlantDao {
        return appDatabase.plantDao()
    }

    @Provides
    fun provideGardenPlantingDao(appDatabase: AppDatabase): GardenPlantingDao {
        return appDatabase.gardenPlantingDao()
    }
}

https://github.com/android/sunflower/blob/main/app/src/main/java/com/google/samples/apps/sunflower/di/DatabaseModule.kt

I noticed they did not use the Singleton annotation for the two functions below provideAppDatabase().

Does this mean that by using the Singleton annotation on provideAppDatabase, automatically make the two functions providePlantDao() and provideGardenPlantingDao() Singletons?


Other tutorials I've checked, annotate the Dao provide functions with @Singleton.

@Module
@InstallIn(SingletonComponent::class)
object DbModule {
    @Provides
    @Singleton
    fun provide(@ApplicationContext context: Context) = Room.databaseBuilder(
        context, NoteDatabase::class.java, NOTE_DATABASE)
        .allowMainThreadQueries()
        .fallbackToDestructiveMigration()
        .build()

    @Provides
    @Singleton
    fun provideDao(db: NoteDatabase) = db.noteDoa()
  
}

https://androidgeek.co/how-to-use-hilt-with-room-database-complete-guide-part-2-2c2bbf52f610

So I'm confused on to annotate or not to.



from Hilt - Question on making a Dao object in a module a Singleton

Friday 30 December 2022

Any way to detect that app have been force stop

Is there any way to detect that past launch have finished with force stop (terminate)? Not in the moment, just in next launch. Maybe resets someone temporary flag, state or other that can be checked. For example, I tried to check WorkInfo from WorkManager. But his requests survive after force stop.



from Any way to detect that app have been force stop

How to add dynamic json in a build in react.js?

I have a react app that loads data from a local json file using

import data from './data.json'

it is all working fine without any issues and I'm able to open my index.html in 3000 and also open it as simple HTML page in browser.

Now I run npm run build which creates the build directory. However, my json values become kind of stagnant as it is hardcoded in the javascript in the build. So the question is how can my code in build directory reads json files from a specific location dynamically.



from How to add dynamic json in a build in react.js?

Is it possible for dramatiq worker to auto shutdown if no messages are present in the queue?

I am running some dramatiq as kubernetes jobs. The usecase require the pods to shutdown if no messages are in the queue. So what I need is that the dramatiq worker process shutsdown if not messages are in the queue.

Is it possible to do that in dramatiq ?



from Is it possible for dramatiq worker to auto shutdown if no messages are present in the queue?

delete an entry from the database on click of a button from the webpage in javascript/php

I have a html/php/javascript code as shown below which outputs the following 3 elements on the webpage (shown below the code):

index.php:

<html>
<head> ABCDE </head>
<body>
<dl id="dl_<?php echo $row['attribute']; ?>"><a href="abcde.php?<?php echo 'id='.rawurlencode($row['attribute'])
        .'&action='.rawurlencode($row['action'])
        .'&name='.rawurlencode($row['map_value_name']); ?>">
        <?php echo $row['attribute']; ?></a> (
    <?php echo $row['owner']; ?>)
    <button type="button" class="btn btn-danger"
        onclick="deleteAttribute('<?php echo $row['attribute']; ?>')">Delete</button>  <!-- Delete button -->
    <dd><?php echo $row['description']; ?></dd>
</dl>

<!-- script -->

<script>
    function deleteAttribute(attribute) {
        console.log(attribute);
        console.log('I am in attribute');
        jQuery.ajax({
            url: 'delete.php',
            type: 'post',
            data: 'attribute='+attribute,
            success: function(result) {
                jQuery('#dl_'+attribute).hide(500);
            }
        });
    }
</script>
</body>
</html>

It prints:

Good Morning
Hello World

Good Evening
World

Good Afternoon
Hello

I am using the following file to delete an entry from the database on click of a delete button from the webpage.

delete.php file

<?php
require 'connect.php';

$attribute = $_POST['attribute'];
$sql = "Delete from attributes where attribute='".$attribute."'";
$stmt = $con->prepare($sql);
$stmt->execute();

?>

Problem Statement:

On click of a delete button from the index.php file above, I don't see any entry getting deleted both from the webpage and the database.

I am wondering what changes I need to make in the delete.php and index.php files above so that on click of a Delete button, entry both from the webpage and the database gets deleted.



from delete an entry from the database on click of a button from the webpage in javascript/php

insert items in table and Sub table using Jquery

I am trying to write a single-page app with the below details, but unable to complete all. (shared the code below)

  • Header input fields.
  • Items input(can be using modal) and View(as table)
  • Sub-items input(using modal) and view(as table) , each items can or cannot have sub-items.
  • Create/Submit button will send all data to an end-point using Ajax.

sub table data will be added by input form through a bootstrap modal.

enter image description here

 <!DOCTYPE html>  
<html>  
<head>  
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>  
</head>  
<body>  
  
<div class="container">  
  
  <form>  
   
<table class="table">
<tbody>
  <tr>
<td><input type="text" class="form-control"  id='txtCustomerNumb' placeholder="Customer Number" /></td>
<td><input type="text" class="form-control" id='txtCustomerName' placeholder="Customer Name" /></td>
<td><input type="text" class="form-control" id='txtDeliverTo' placeholder="Deliver To" /></td>
<td></td>
  </tr>
  <tr>
<td><input type="text" class="form-control" id='txtDriverName' placeholder="Driver Name" /></td>
<td><input type="text" class="form-control" id='txtDriverContact' placeholder="Driver Contact" /></td>
<td><input type="text" class="form-control" id='txtVehNumber' placeholder="Vehicle No." /></td>
<td></td>
  </tr>
  <tr>
<td>
  <select class="form-control" id="txtDeliverTo" placeholder="Exit Point">
    <option value="">Select Exit Point</option>
    <option value="Exit_Point_1">Exit Point 1</option>
    <option value="Exit_Point_2">Exit Point 2</option>
    <option value="Exit_Point_3">Exit Point 3</option> 
  </select>
            
</td>
<td><input type="text" class="form-control" id='txtDeliverTo' placeholder="Deliver To" /></td>
<td><input type="text" class="form-control" id='txtExitType' placeholder="Type Of Exit" /></td>
<td></td>
  </tr>
</tbody>
</table>   
<div class="form-row">
<div class="form-group col-md-4">  
  <label>Name:</label>  
  <input type="text" name="name" class="form-control" value="Smith" required="">  
</div>  
  
<div class="form-group col-md-6">  
  <label>Email:</label>  
  <input type="text" name="email" class="form-control" value="smith@abc.com" required="">  
 
 </div>  
 <div class="form-group col-md-2" style="padding-top: 23px;">
 <button type="submit" class="btn btn-success save-btn">Add</button> 
 </div>
  </div>
  </form>  
  <br/>  
  <table class="table table-bordered data-table">  
<thead>  
  <th>Name</th>  
  <th>Email</th>  
  <th width="200px">Action</th>  
</thead>  
<tbody>  
  
</tbody>  
  </table>  
 
</div>  
 
<script type="text/javascript">  
 
$("form").submit(function(e){  
    e.preventDefault();  
    var name = $("input[name='name']").val();  
    var email = $("input[name='email']").val();  
   
    $(".data-table tbody").append("<tr data-name='"+name+"' data-email='"+email+"'><td>"+name+"</td><td>"+email+"</td><td><button class='btn btn-info btn-xs btn-edit'>Edit</button><button class='btn btn-danger btn-xs btn-delete'>Delete</button></td></tr>");  
  
    $("input[name='name']").val('');  
    $("input[name='email']").val('');  
});  
 
$("body").on("click", ".btn-delete", function(){  
    $(this).parents("tr").remove();  
});  
  
$("body").on("click", ".btn-edit", function(){  
    var name = $(this).parents("tr").attr('data-name');  
    var email = $(this).parents("tr").attr('data-email');  
  
    $(this).parents("tr").find("td:eq(0)").html('<input name="edit_name" value="'+name+'">');  
    $(this).parents("tr").find("td:eq(1)").html('<input name="edit_email" value="'+email+'">');  
  
    $(this).parents("tr").find("td:eq(2)").prepend("<button class='btn btn-info btn-xs btn-update'>Update</button><button class='btn btn-warning btn-xs btn-cancel'>Cancel</button>")  
    $(this).hide();  
});  
 
$("body").on("click", ".btn-cancel", function(){  
    var name = $(this).parents("tr").attr('data-name');  
    var email = $(this).parents("tr").attr('data-email');  
  
    $(this).parents("tr").find("td:eq(0)").text(name);  
    $(this).parents("tr").find("td:eq(1)").text(email);  
 
    $(this).parents("tr").find(".btn-edit").show();  
    $(this).parents("tr").find(".btn-update").remove();  
    $(this).parents("tr").find(".btn-cancel").remove();  
});  
 
$("body").on("click", ".btn-update", function(){  
    var name = $(this).parents("tr").find("input[name='edit_name']").val();  
    var email = $(this).parents("tr").find("input[name='edit_email']").val();  
  
    $(this).parents("tr").find("td:eq(0)").text(name);  
    $(this).parents("tr").find("td:eq(1)").text(email);  
   
    $(this).parents("tr").attr('data-name', name);  
    $(this).parents("tr").attr('data-email', email);  
  
    $(this).parents("tr").find(".btn-edit").show();  
    $(this).parents("tr").find(".btn-cancel").remove();  
    $(this).parents("tr").find(".btn-update").remove();  
});  
  
</script>  
   
</body>  
</html>


from insert items in table and Sub table using Jquery

Converting or printing all sections of rendered quarto document into html in one go

I want to convert Shiny for Python document into pdf. Jumping to each section and then printing into pdf is possible. However, wondering if there is a more compact way to print all sections in a one go.



from Converting or printing all sections of rendered quarto document into html in one go

Thursday 29 December 2022

Webpack code splitting - Automatically load all chunks by requesting a single chunk?

I'm using Webpack 4.x and have the following in my config:

splitChunks: {
    chunks: 'all',
},
runtimeChunk: true

This results in three chunks in my project:

  • app.prod.js
  • 1.app.prod.js
  • 2.app.prod.js

I'd like to load all three scripts using just one initial request. The reason for this is that I'd like to use the "preload" feature in Electron for security reasons, which accepts a single script.

Is there a way to have the initial app.prod.js require/import the additional chunks automatically?



from Webpack code splitting - Automatically load all chunks by requesting a single chunk?

Pentaho Data Integration: extract language distribution code

I'm using PDI API to get the language distribution for code in my projects.

Using a request like

var url = "http://<my_sonar_instance>/api/measures/component?additionalFields=metrics&component=<sonar_key>&metricKeys=duplicated_lines_density%2Cblocker_violations%2Ccomment_lines_density%2Ccritical_violations%2Cnew_maintainability_rating%2Cnew_duplicated_lines_density%2Cnew_reliability_rating%2Cnew_security_rating%2Cncloc%2Cncloc_language_distribution";

and parsing the JSON result by

$.component.measures[?(@.metric=="ncloc_language_distribution")].value

to assign the value at a variable named

sonar_ncloc_language_distribution

I obtain for example

java=10514;js=237;jsp=3995;web=5;xml=42

Now I'd like to assign those values at some variables in a PDI transformation using a Modified JavaScript value using this Javascript code

var map = new Map();
sonar_ncloc_language_distribution.split(";").forEach(x => map[x.split("=")[0]] = x.split("=")[1]);

var sonar_ncloc_java = map.java;
var sonar_ncloc_js = map.js;
var sonar_ncloc_jsp = map.jsp;
var sonar_ncloc_web = map.web;
var sonar_ncloc_xml = map.xml;

but it doesn't work and the error is

Unable compile javascript: 
syntax error (script#2)

(NOTE: if I try to execute the javascript code "alone" in a HTML file all works fine ...)

<!DOCTYPE html>
<html>
<body>

<script>
var sonar_ncloc_language_distribution = "java=10514;js=237;jsp=3995;web=5;xml=42";

var map = new Map();

sonar_ncloc_language_distribution.split(";").forEach(x => map[x.split("=")[0]] = x.split("=")[1]);
console.log(map);

var sonar_ncloc_java = map.java;
var sonar_ncloc_js = map.js;
var sonar_ncloc_jsp = map.jsp;
var sonar_ncloc_web = map.web;
var sonar_ncloc_xml = map.xml;

console.log(map.java);
console.log(map.js);
console.log(map.jsp);
console.log(map.web);
console.log(map.xml);

</script>

</body>
</html> 

Any suggestion will be appreciated and thank you in advance



from Pentaho Data Integration: extract language distribution code

binding the movement/rotation of two kivy scatter widgets

Below I have a code that displays 2 scatter widgets in a kivy screen. If one widget is dragged, the other also drags and vice versa.

What I want is in addition to movement, if one is rotated, the other rotates in the same way. In other words, they are exactly mimicking each other with both rotation and position.

The problem I am facing is that kivy's default position is the bottom left of the widget. So, if the user rotates one widget from some random axis point, the other widget rotates at the bottom left. When introducing rotation while the positions are locked, it becomes all messed up, and I cannot find a way to overcome this bug in order to match both rotation and movement.

Here is code with positions locked.

from kivy.uix.scatter import Scatter
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder

class ScatterWidget(Scatter):
    pass

class SquareWidget(Widget):
    pass

class WindowManager(ScreenManager):
    pass

class GeneralWindow(Screen,RelativeLayout):

    start_position_1=(200,200)
    start_position_2=(300,400)
    def on_touch_move(self, touch):
        app=self.manager.get_screen('General')
        pos1=app.ids['widget10'].parent.to_parent(*self.pos)
        pos2=app.ids['widget20'].parent.to_parent(*self.pos)
        mov1=(pos1[0]-self.start_position_1[0],pos1[1]-self.start_position_1[1])
        mov2=(pos2[0]-self.start_position_2[0],pos2[1]-self.start_position_2[1])

        if self.ids.one.collide_point(*touch.pos):
            app.ids['two'].pos=(mov1[0]+self.start_position_2[0],mov1[1]+self.start_position_2[1])
        if self.ids.two.collide_point(*touch.pos):
            app.ids['one'].pos =(mov2[0]+self.start_position_1[0],mov2[1]+self.start_position_1[1])

KV = Builder.load_string("""

WindowManager:
    GeneralWindow:

<GeneralWindow>:
    name: 'General'
    RelativeLayout:
        canvas: 
            Color: 
                rgba: 0,0,0,0.3
            Rectangle: 
                size: self.size
                pos: self.pos
        
        ScatterWidget:
            do_scale: False
            id: one
            size_hint: None,None
            size: widget10.size
            rotation: 0
            pos: root.start_position_1

            SquareWidget:
                id: widget10
                size: (200,20)
                canvas: 
                    Color:
                        rgba: 1,1,0,0.7
                    Rectangle:
                        size: self.size
                        pos:  self.pos  

        ScatterWidget:
            do_scale: False
            id: two
            size_hint: None,None
            size: widget20.size
            rotation: 0
            pos: root.start_position_2

            SquareWidget:
                id: widget20
                size: (200,20)
                canvas: 
                    Color:
                        rgba: 0,1,0,0.7
                    Rectangle:
                        size: self.size
                        pos:  self.pos 

""")

class TApp(App):

    def build(self):
        return KV

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


from binding the movement/rotation of two kivy scatter widgets

Android deep linking not loading from browser, even from simple tutorial

I'm having trouble getting deep linking to work in my android application, so I found the most bare-bones tutorial I could and it's still just opening the browser when I click on the link. All of this is pasted from my code not the tutorial, in case I pasted something wrong. Even with this

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools">
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.DeepLinkTest">
    <activity android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <!-- as we want to open main activity from our link so we are specifying
            only in main activity or we can specify that in different activity as well -->
        <!-- on below line we are adding intent filter to our MainActivity -->
        <intent-filter>
            <!-- below line is to set the action to our intent to view -->
            <action android:name="android.intent.action.VIEW" />

            <!-- on below line we are adding a default category to our intent -->
            <category android:name="android.intent.category.DEFAULT" />

            <!-- on below line we are adding a category to make our app browsable -->
            <category android:name="android.intent.category.BROWSABLE" />

            <!-- on below line we are specifying the host name and
                the scheme type from which we will be calling our app -->
            <data
                android:host="www.chaitanyamunje.com"
                android:scheme="https" />
        </intent-filter>

        <!-- below is the same filter as above just the scheme is changed to http -->
        <!-- so we can open our app with the url starting with https and http as well -->
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data
                android:host="www.chaitanyamunje.com"
                android:scheme="http" />
        </intent-filter>
    </activity>
</application>

MainActivity.kt

package me.paxana.deeplinktest

import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class MainActivity : AppCompatActivity() {

  // creating a variable for our text view
  private lateinit var messageTV: TextView
  private var uri: Uri? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // initializing our variable
    messageTV = findViewById(R.id.idTVMessage)
    // getting the data from our intent in our uri.
    uri = intent.data

    // checking if the uri is null or not.
    if (uri != null) {
      // if the uri is not null then we are getting
      // the path segments and storing it in list.
      val parameters = uri!!.pathSegments

      // after that we are extracting string
      // from that parameters.
      val param = parameters[parameters.size - 1]

      // on below line we are setting that
      // string to our text view which
      // we got as params.
      messageTV.text = param
    }
  }
}

The result of using the App Link Testing feature of android studio to load https://www.chaitanyamunje.com/hello/GeeksForGeeks

Browser showing "This site can't be reached. Check if there is a typo in chaitanyamunje.com. DNS_PROBE_FINISHED_NXDOMAIN."



from Android deep linking not loading from browser, even from simple tutorial

AAPT2 warning about "Unknown chunk type"

I'm building an Android app targeting Android API 33 (Android 13). When I build the app on the command line using gradlew, I see the following warning:

aapt2 W 09-02 02:57:09  6715  6715 LoadedArsc.cpp:682] Unknown chunk type '200'.

What on earth does this mean, and should I expect side effects?



from AAPT2 warning about "Unknown chunk type"

Android Slow Bluetooth RFCOMM Transfer Rate with RN4678

We are experimenting with a bunch of new tablets, and every one we tried is having issues with slow transfer rates with the RN4678 board. We currently use the Lenovo M10 FHD Plus. We tried a few such as the Teclast M40S, Nokia T20, and Samsung Galaxy Tab A8. The first two had horrible transfer rates, while the latter was okay but not ideal. We cannot use the Lenovo M10 Plus 3rd Gen because the buttons are too close to the corner to use with our tablet holders.

Here is my code:

public void SendMessage(BluetoothSocket socket, String msg) {
    OutputStream outStream;
    try {
        outStream = BluetoothConnectionService.outputStream;
        outStream.write("S".getBytes());
        Thread.sleep(4000);
        processThread = true;
        mApp.running = true;
        BluetoothSocketListener bsl = new BluetoothSocketListener(socket,
                CollectingDetail.this);
        Thread messageListener = new Thread(bsl);

        messageListener.start();
        timer = new CounterClass(remaingTime, 1000);
        timer.start();
        bt_stop.setText("Stop");

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(bluetoothReceiver, filter);
        bluetoothReceiver.setRegistered(true);
    } catch (IOException | InterruptedException e) {
        Log.e("BLUETOOTH_COMMS", e.getMessage());

        connectSocket();
    } 
}

public static class BluetoothSocketListener implements Runnable {
    private final WeakReference<CollectingDetail> wrActivity;
    private BluetoothSocket socket;

    public BluetoothSocketListener(BluetoothSocket socket, CollectingDetail collectingDetail) {
        this.socket = socket;
        wrActivity = new WeakReference<CollectingDetail>(collectingDetail);
    }

    @Override
    public void run() {
        final CollectingDetail activity = wrActivity.get();
        if (activity != null) {
            activity.inStream = null;
            if (!Thread.currentThread().isInterrupted()) {
                int bufferSize = 512;
                byte[] buffer = new byte[bufferSize];
                Log.i("Bluetooth bytes", new String(buffer));
                activity.inStream = BluetoothConnectionService.inputStream;
                int availableBytes;
                int bytesRead = -1;
                String message = "";

                while (activity.processThread) {
                    message = "";
                    try {
                        availableBytes = activity.inStream.available();
                        if (availableBytes > 0) {
                            bytesRead = activity.inStream.read(buffer);
                            if (bytesRead != -1 && bytesRead < bufferSize) {
                                message = new String(buffer, 0, bytesRead);

                                if (activity.mainHandler != null) {
                                    activity.mainHandler.post(new MessagePoster(message, activity));

                                }


                            }
                        }
                    } catch (IOException e) {
                        Log.e("BLUETOOTH_COMMS", "Error reading bytes");
                        try {
                            socket.close();
                        } catch (IOException e1) {
                            Log.e("BLUETOOTH_COMMS", "Could not close socket");
                        }
                        activity.processThread = false;
                    }
                }
            }
        }
    }
}


public void seprateData(String message) {
    try {
        message = message.replaceAll("(\\r\\n|\\n|\\r)", ",");
        String[] a = message.split(",");
        boolean goodData = false;

        for (int i = 0; i < a.length; i++) {
            final String data = a[i];
            if (data.length() > 0 && !data.equals(" ")) {
                if (data.length() >= 10 && data.startsWith("5A")) {
                    al_sepratedMessageList.add(data);
                    goodData = true;

                }
            }
        }

        if (goodData) {
            calculation();
            if (ConnectThrough.equalsIgnoreCase("usb")) {
                UsbConnectionSerivce.sendMessage("K");
            } else {
                BluetoothConnectionService.sendMessage(socket, "K");
            }
        }

    } catch (Exception e) {
        Log.e("BiSym", "Error Parsing BiSym Data");
    }
}

Is there any way we can increase the transfer rate without changing the firmware? It appears others have faced similar problems, but none of the answers have a real solution. Could you please help me out. Thanks.



from Android Slow Bluetooth RFCOMM Transfer Rate with RN4678

Wednesday 28 December 2022

GMaps, OverlayView, GTiff - Image is shifted/squished the further N latitude you go

I have a 3857 GTiff (no difference if I use a 4326 version) that correctly produces tiles (we use TiTiler), but if I try cropping that image and serve a single image that I try overlaying with OverlayView (like the USGS example) it seems to shift North and/or "squishes" the image to fit within the div.

Here's a fiddle I made, https://jsfiddle.net/m6pvLe0d/1/, using the exact USGS source from the Google doc's and if you toggle the image, you can see where the Great Lakes should be, and where they are being put due to the shift/crop issue.

/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
// This example adds hide() and show() methods to a custom overlay's prototype.
// These methods toggle the visibility of the container <div>.
// overlay to or from the map.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 5,
    center: { lat: 41.3139, lng: -75.77767 },
    mapTypeId: "satellite",
  });
  const bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(25.76400806673997, -117.59163484375),
    new google.maps.LatLng(53.88085455391184, -33.96370515625001)
  );
  // The photograph is courtesy of the U.S. Geological Survey.
  let image = "https://i.imgur.com/la39KvI.png";
  /**
   * The custom USGSOverlay object contains the USGS image,
   * the bounds of the image, and a reference to the map.
   */
  class USGSOverlay extends google.maps.OverlayView {
    bounds;
    image;
    div;
    constructor(bounds, image) {
      super();
      this.bounds = bounds;
      this.image = image;
    }
    /**
     * onAdd is called when the map's panes are ready and the overlay has been
     * added to the map.
     */
    onAdd() {
      this.div = document.createElement("div");
      this.div.style.borderStyle = "none";
      this.div.style.borderWidth = "0px";
      this.div.style.position = "absolute";

      // Create the img element and attach it to the div.
      const img = document.createElement("img");

      img.src = this.image;
      img.style.width = "100%";
      img.style.height = "100%";
      img.style.position = "absolute";
      this.div.appendChild(img);

      // Add the element to the "overlayLayer" pane.
      const panes = this.getPanes();

      panes.overlayLayer.appendChild(this.div);
    }
    draw() {
      // We use the south-west and north-east
      // coordinates of the overlay to peg it to the correct position and size.
      // To do this, we need to retrieve the projection from the overlay.
      const overlayProjection = this.getProjection();
      // Retrieve the south-west and north-east coordinates of this overlay
      // in LatLngs and convert them to pixel coordinates.
      // We'll use these coordinates to resize the div.
      const sw = overlayProjection.fromLatLngToDivPixel(
        this.bounds.getSouthWest()
      );
      const ne = overlayProjection.fromLatLngToDivPixel(
        this.bounds.getNorthEast()
      );

      // Resize the image's div to fit the indicated dimensions.
      if (this.div) {
        this.div.style.left = sw.x + "px";
        this.div.style.top = ne.y + "px";
        this.div.style.width = ne.x - sw.x + "px";
        this.div.style.height = sw.y - ne.y + "px";
      }
    }
    /**
     * The onRemove() method will be called automatically from the API if
     * we ever set the overlay's map property to 'null'.
     */
    onRemove() {
      if (this.div) {
        this.div.parentNode.removeChild(this.div);
        delete this.div;
      }
    }
    /**
     *  Set the visibility to 'hidden' or 'visible'.
     */
    hide() {
      if (this.div) {
        this.div.style.visibility = "hidden";
      }
    }
    show() {
      if (this.div) {
        this.div.style.visibility = "visible";
      }
    }
    toggle() {
      if (this.div) {
        if (this.div.style.visibility === "hidden") {
          this.show();
        } else {
          this.hide();
        }
      }
    }
    toggleDOM(map) {
      if (this.getMap()) {
        this.setMap(null);
      } else {
        this.setMap(map);
      }
    }
  }

  const overlay = new USGSOverlay(bounds, image);

  overlay.setMap(map);

  const toggleButton = document.createElement("button");

  toggleButton.textContent = "Toggle";
  toggleButton.classList.add("custom-map-control-button");

  const toggleDOMButton = document.createElement("button");

  toggleDOMButton.textContent = "Toggle DOM Attachment";
  toggleDOMButton.classList.add("custom-map-control-button");
  toggleButton.addEventListener("click", () => {
    overlay.toggle();
  });
  toggleDOMButton.addEventListener("click", () => {
    overlay.toggleDOM(map);
  });
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleDOMButton);
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleButton);
}

window.initMap = initMap;

I'm really trying to understand "where" in the process this would be happening, as the same underlying GTiff that produced that large image correctly makes tiles. The cut-off on the Western side of the United States is expected as that was outside of the bounding box (lat/lon) I used to pass to TiTiler.

I know there's presumably "a lot" that can go into exactly where in the stack it's causing this to happen, but being very fresh with mapping, I don't even really know where to start looking and I guess the real head-scratcher for me is how it correctly produces tiles.



from GMaps, OverlayView, GTiff - Image is shifted/squished the further N latitude you go

GMaps, OverlayView, GTiff - Image is shifted/squished the further N latitude you go

I have a 3857 GTiff (no difference if I use a 4326 version) that correctly produces tiles (we use TiTiler), but if I try cropping that image and serve a single image that I try overlaying with OverlayView (like the USGS example) it seems to shift North and/or "squishes" the image to fit within the div.

Here's a fiddle I made, https://jsfiddle.net/m6pvLe0d/1/, using the exact USGS source from the Google doc's and if you toggle the image, you can see where the Great Lakes should be, and where they are being put due to the shift/crop issue.

/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
// This example adds hide() and show() methods to a custom overlay's prototype.
// These methods toggle the visibility of the container <div>.
// overlay to or from the map.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 5,
    center: { lat: 41.3139, lng: -75.77767 },
    mapTypeId: "satellite",
  });
  const bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(25.76400806673997, -117.59163484375),
    new google.maps.LatLng(53.88085455391184, -33.96370515625001)
  );
  // The photograph is courtesy of the U.S. Geological Survey.
  let image = "https://i.imgur.com/la39KvI.png";
  /**
   * The custom USGSOverlay object contains the USGS image,
   * the bounds of the image, and a reference to the map.
   */
  class USGSOverlay extends google.maps.OverlayView {
    bounds;
    image;
    div;
    constructor(bounds, image) {
      super();
      this.bounds = bounds;
      this.image = image;
    }
    /**
     * onAdd is called when the map's panes are ready and the overlay has been
     * added to the map.
     */
    onAdd() {
      this.div = document.createElement("div");
      this.div.style.borderStyle = "none";
      this.div.style.borderWidth = "0px";
      this.div.style.position = "absolute";

      // Create the img element and attach it to the div.
      const img = document.createElement("img");

      img.src = this.image;
      img.style.width = "100%";
      img.style.height = "100%";
      img.style.position = "absolute";
      this.div.appendChild(img);

      // Add the element to the "overlayLayer" pane.
      const panes = this.getPanes();

      panes.overlayLayer.appendChild(this.div);
    }
    draw() {
      // We use the south-west and north-east
      // coordinates of the overlay to peg it to the correct position and size.
      // To do this, we need to retrieve the projection from the overlay.
      const overlayProjection = this.getProjection();
      // Retrieve the south-west and north-east coordinates of this overlay
      // in LatLngs and convert them to pixel coordinates.
      // We'll use these coordinates to resize the div.
      const sw = overlayProjection.fromLatLngToDivPixel(
        this.bounds.getSouthWest()
      );
      const ne = overlayProjection.fromLatLngToDivPixel(
        this.bounds.getNorthEast()
      );

      // Resize the image's div to fit the indicated dimensions.
      if (this.div) {
        this.div.style.left = sw.x + "px";
        this.div.style.top = ne.y + "px";
        this.div.style.width = ne.x - sw.x + "px";
        this.div.style.height = sw.y - ne.y + "px";
      }
    }
    /**
     * The onRemove() method will be called automatically from the API if
     * we ever set the overlay's map property to 'null'.
     */
    onRemove() {
      if (this.div) {
        this.div.parentNode.removeChild(this.div);
        delete this.div;
      }
    }
    /**
     *  Set the visibility to 'hidden' or 'visible'.
     */
    hide() {
      if (this.div) {
        this.div.style.visibility = "hidden";
      }
    }
    show() {
      if (this.div) {
        this.div.style.visibility = "visible";
      }
    }
    toggle() {
      if (this.div) {
        if (this.div.style.visibility === "hidden") {
          this.show();
        } else {
          this.hide();
        }
      }
    }
    toggleDOM(map) {
      if (this.getMap()) {
        this.setMap(null);
      } else {
        this.setMap(map);
      }
    }
  }

  const overlay = new USGSOverlay(bounds, image);

  overlay.setMap(map);

  const toggleButton = document.createElement("button");

  toggleButton.textContent = "Toggle";
  toggleButton.classList.add("custom-map-control-button");

  const toggleDOMButton = document.createElement("button");

  toggleDOMButton.textContent = "Toggle DOM Attachment";
  toggleDOMButton.classList.add("custom-map-control-button");
  toggleButton.addEventListener("click", () => {
    overlay.toggle();
  });
  toggleDOMButton.addEventListener("click", () => {
    overlay.toggleDOM(map);
  });
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleDOMButton);
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleButton);
}

window.initMap = initMap;

I'm really trying to understand "where" in the process this would be happening, as the same underlying GTiff that produced that large image correctly makes tiles. The cut-off on the Western side of the United States is expected as that was outside of the bounding box (lat/lon) I used to pass to TiTiler.

I know there's presumably "a lot" that can go into exactly where in the stack it's causing this to happen, but being very fresh with mapping, I don't even really know where to start looking and I guess the real head-scratcher for me is how it correctly produces tiles.



from GMaps, OverlayView, GTiff - Image is shifted/squished the further N latitude you go

Python: how to speed up this function and make it more scalable?

I have the following function which accepts an indicator matrix of shape (20,000 x 20,000). And I have to run the function 20,000 x 20,000 = 400,000,000 times. Note that the indicator_Matrix has to be in the form of a pandas dataframe when passed as parameter into the function, as my actual problem's dataframe has timeIndex and integer columns but I have simplified this a bit for the sake of understanding the problem.

Pandas Implementation

indicator_Matrix = pd.DataFrame(np.random.randint(0,2,[20000,20000]))
def operations(indicator_Matrix):
   s = indicator_Matrix.sum(axis=1)
   d = indicator_Matrix.div(s,axis=0)
   res = d[d>0].mean(axis=0)
   return res.iloc[-1]

I tried to improve it by using numpy but it is still taking ages to run. I also tried concurrent.future.ThreadPoolExecutor but it still take a long time to run and not much improvement from list comprehension.

Numpy Implementation

indicator_Matrix = pd.DataFrame(np.random.randint(0,2,[20000,20000]))
def operations(indicator_Matrix):
   s = indicator_Matrix.to_numpy().sum(axis=1)
   d = (indicator_Matrix.to_numpy().T / s).T
   d = pd.DataFrame(d, index = indicator_Matrix.index, columns = indicator_Matrix.columns)
   res = d[d>0].mean(axis=0)
   return res.iloc[-1]

output = [operations(indicator_Matrix) for i in range(0,20000**2)]

Note that the reason I convert d to a dataframe again is because I need to obtain the column means and retain only the last column mean using .iloc[-1]. d[d>0].mean(axis=0) return column means, i.e.

2478    1.0
0       1.0

Update: I am still stuck in this problem. I wonder if using gpu packages like cudf and CuPy on my local desktop would make any difference.



from Python: how to speed up this function and make it more scalable?

Monaco Editor - node_modules package entry point resolution

I'm trying to load a very basic project using Monaco Editor but I'm having issues resolving node_modules. It seems that the entry point of the project defined in package.json is ignored.

In the example here axios works fine because it has an index.d.ts file at the root of the folder, but any project that doesn't have a .d.ts, or where the main entry point/typings of the file aren't inside the root, don't get resolved. One example of this is delayed-stream where the entry point is inside /lib/delayed_stream.js.

The project has a structure such as:

- <root>
  - src
    - index.ts
  - package.json
  - node_modules
    - axios
      - ...
    - delayed-stream
      - ...
// ./src/index.ts
import axios from 'axios'; // Resolves
import delayedStream from 'delayed-stream'; // Cannot find module 'delayed-stream' or its corresponding type declarations.(2307)

All .d.ts files are loaded with:

monaco.languages.typescript.typescriptDefaults.addExtraLib(data, file);
monaco.languages.typescript.javascriptDefaults.addExtraLib(data, file);
monaco.editor.createModel(data, 'typescript', monaco.Uri.parse(file));

And all .js, .ts and .json files are loaded with:

monaco.editor.createModel(data, language, monaco.Uri.parse(file));

I am creating an editor with the same settings as my tsconfig such as:

  monaco.languages.typescript.javascriptDefaults.setEagerModelSync(true);
  monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
    noSemanticValidation: false,
    noSyntaxValidation: false,
  });
  monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
    target: monaco.languages.typescript.ScriptTarget.ESNext,
    alwaysStrict: true,
    allowNonTsExtensions: true,
    moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
    module: monaco.languages.typescript.ModuleKind.CommonJS,
    noEmit: true,
    esModuleInterop: true,
    allowJs: true,
    skipLibCheck: true,
    allowSyntheticDefaultImports: true,
    baseUrl: './'
  });

I fear I'm missing something obvious here but I've been searching for days, help very much appreciated.



from Monaco Editor - node_modules package entry point resolution

Tuesday 27 December 2022

MongoExpiredSessionError: Cannot use a session that has ended

I am trying to create new documents from existing ones in one of my database's collections. I'm flattening one of the fields from the original document. The process worked perfectly when using mongosh, but now I have to run this script on a gcp function. So I need to have everything inside the script.

I managed to connect to the db, add the flattened document to the new collection, but when I go to close the connection it gives me the error:

MongoExpiredSessionError: Cannot use a session that has ended

And it never adds the document to the new collection.

I have figured out that when I remove the DB.close() from the code, it adds the documents but the program never finished/exits.

I have placed each await document where it interacts with the DB, but it has not been of much help. Here is my full code. The main function calls the connectMongo which connects to the mongo db and runs the execute function. This execute functions takes the documents from the original collection and passes them one by one to the flatten function. The flatten function does the flattening plus the adding of the new document to the new collection.

Here is the code: The print statements at all cases (w/ & w/out DB.close()) work and print out each one.

const {MongoClient} = require('mongodb');
const uri = "mongodb://<myURI>"


const DB = new MongoClient(uri);
var collections;

//---------------------------------------------------------------------------------------------
execute = async function(db){
    
    docs = await db.collection('observations6').find()
    
    await docs.forEach(flatten)
    
}
//---------------------------------------------------------------------------------------------

flatten = async function(myDoc){

    forms = myDoc.properties.forms
    for(var i = 0; i < forms.length; i++){

        FormObj = {
            parent_id : myDoc._id+'_form_'+i,
            eventId: myDoc.eventId,
            userId: myDoc.userId,
            deviceId: myDoc.deviceId,
            createdAt: myDoc.createdAt,
            lastModified : myDoc.lastModified,
            type: myDoc.type,
            geometry: myDoc.geometry,
            favoriteUserIds: myDoc.favoriteUserIds,
            states: myDoc.states,
            attachments: myDoc.attachments,
            formId: forms[i]['formId'],
        }
        console.log('Created form object')
        field_count = 0
        retry = 0

        while (retry <= 10){
            if (!forms[i].hasOwnProperty('field'+field_count)){
                field_count += 1
            }
            retry += 1
        }
        console.log(`Did ${field_count} retry(s)`)
        while(forms[i].hasOwnProperty('field'+field_count)){
            FormObj['field'+field_count] = forms[i]['field'+field_count]
            field_count+=1
        }
        console.log('Added field properties')
        
        parent_id = myDoc._id + '_form_' + i
        await collections.collection('observations6_flatten').updateOne({parent_id},{$set: {FormObj}}, {upsert:true})

        console.log('Added object to collection')
       
    }
    
}
//---------------------------------------------------------------------------------------------
async function connectMongo() {
     
    try {
        // Connect to the MongoDB cluster
        await DB.connect();
 
        // Make the appropriate DB calls
        collections = await DB.db('magedb')
        //console.log(collections)
        await execute(collections)
    
       
    } catch (e) {
        console.error(e);
    } 
    
}

//---------------------------------------------------------------------------------------------
//Main call
main = async function(){
    await connectMongo()
    .then(()=>{
        DB.close()
    })
}

main()

This is the error it returns

aortiz@WW-593 MINGW64 ~/Documents/GitHub/engineering_etl (main)
$ node flattening/flattening.js
Created form object
Did 11 retry(s)
Added field properties
Created form object
Did 0 retry(s)
Added field properties
Created form object
Did 1 retry(s)
Added field properties
Created form object
Did 0 retry(s)
Added field properties
Created form object
Did 0 retry(s)
Added field properties
Created form object
Did 0 retry(s)
Added field properties
Created form object
Did 0 retry(s)
Added field properties
C:\Users\aortiz\Documents\GitHub\engineering_etl\node_modules\mongodb\lib\sessions.js:655
        return new error_1.MongoExpiredSessionError();
               ^

MongoExpiredSessionError: Cannot use a session that has ended
    at applySession (C:\Users\aortiz\Documents\GitHub\engineering_etl\node_modules\mongodb\lib\sessions.js:655:16)        
    at Connection.command (C:\Users\aortiz\Documents\GitHub\engineering_etl\node_modules\mongodb\lib\cmap\connection.js:281:53)
    at C:\Users\aortiz\Documents\GitHub\engineering_etl\node_modules\mongodb\lib\sdam\server.js:210:18
    at Object.callback (C:\Users\aortiz\Documents\GitHub\engineering_etl\node_modules\mongodb\lib\cmap\connection_pool.js:327:13)
    at ConnectionPool.processWaitQueue (C:\Users\aortiz\Documents\GitHub\engineering_etl\node_modules\mongodb\lib\cmap\connection_pool.js:506:33)
    at C:\Users\aortiz\Documents\GitHub\engineering_etl\node_modules\mongodb\lib\cmap\connection_pool.js:183:37
    at processTicksAndRejections (node:internal/process/task_queues:78:11) {
  [Symbol(errorLabels)]: Set(0) {}
}

When I remove the DB.close() it returns

aortiz@WW-593 MINGW64 ~/Documents/GitHub/engineering_etl (main)
$ node flattening/flattening.js
Created form object
Did 11 retry(s)
Added field properties
Created form object
Did 0 retry(s)
Added field properties
Created form object
Did 1 retry(s)
Added field properties
Created form object
Did 0 retry(s)
Added field properties
Created form object
Did 0 retry(s)
Added field properties
Created form object
Did 0 retry(s)
Added field properties
Created form object
Did 0 retry(s)
Added field properties
Added object to collection
Added object to collection
Added object to collection
Added object to collection
Added object to collection
Added object to collection
Added object to collection


and never finished/exits the script

EDIT

Now that I am looking better at the output when I remove DB.close(), I see that the Added Object to collection print statement gets printer and when I have the DB.close() it stops just before then. So this must mean that the error is ocurring on the line:

await collections.collection('observations6_flatten').updateOne({parent_id},{$set: {FormObj}}, {upsert:true})

But what exactly is going on that the connection ends before this point?



from MongoExpiredSessionError: Cannot use a session that has ended

How can I efficiently plot a distance matrix using seaborn?

So I have a dataset of more ore less 11.000 records, with 4 features all them are discrete or continue. I perform clustering using K-means, then I add the column "cluster" to the dataframe using kmeans.labels_. Now I want to plot the distance matrix so I used pdist from scipy, but the matrix is not plotted.

Here is my code.

from scipy.spatial.distance import pdist
from scipy.spatial.distance import squareform
import gc

# distance matrix
def distance_matrix(df_labeled, metric="euclidean"):
    df_labeled.sort_values(by=['cluster'], inplace=True)
    dist = pdist(df_labeled, metric)
    dist = squareform(dist)    
    sns.heatmap(dist, cmap="mako")
    print(dist)
    del dist
    gc.collect()

distance_matrix(finalDf)

Output:

[[ 0.          2.71373462  3.84599479 ...  7.59910903  8.10265588
   8.27195104]
 [ 2.71373462  0.          2.94410672 ...  7.90444283  8.28225031
   8.48094661]
 [ 3.84599479  2.94410672  0.         ...  9.78706347 10.42014451
  10.61261498]
 ...
 [ 7.59910903  7.90444283  9.78706347 ...  0.          1.27795469
   1.44711258]
 [ 8.10265588  8.28225031 10.42014451 ...  1.27795469  0.
   0.52333107]
 [ 8.27195104  8.48094661 10.61261498 ...  1.44711258  0.52333107
   0.        ]]

I get the following graph:
enter image description here

As you can see, the plot is empty. Also I have to free up some RAM because google colab crashes.

How can I solve the problem?



from How can I efficiently plot a distance matrix using seaborn?

Android Background activity start

I'm aware of the Restrictions on starting activities from the background starting from Android API 29, but I'm challenged by some app which is able to present an Activity despite the restrictions. The app does not use the SYSTEM_ALERT_WINDOW permission to draw over other apps. It just presents an activity while having only foreground service running.

The app listens to package added (ACTION_PACKAGE_ADDED) and removed (ACTION_PACKAGE_REMOVED) broadcasts and starts an activity styled as a dialog.

Normally, when I register the receiver (either in manifest or runtime in foreground service) and want to start an activity I get the next log from ActivityTaskManager:

2022-12-25 11:29:57.188   511-855   ActivityTaskManager     pid-511                              I  START u0 {flg=0x10000000 cmp=com.jasperapps.testpackageremoveintent/.TargetActivity} from uid 10146
2022-12-25 11:29:57.190   511-855   ActivityTaskManager     pid-511                              W  Background activity start [callingPackage: com.jasperapps.testpackageremoveintent; callingUid: 10146; appSwitchAllowed: false; isCallingUidForeground: false; callingUidHasAnyVisibleWindow: false; callingUidProcState: FOREGROUND_SERVICE; isCallingUidPersistentSystemProcess: false; realCallingUid: 10146; isRealCallingUidForeground: false; realCallingUidHasAnyVisibleWindow: false; realCallingUidProcState: FOREGROUND_SERVICE; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: null; allowBackgroundActivityStart: false; intent: Intent { flg=0x10000000 cmp=com.jasperapps.testpackageremoveintent/.TargetActivity }; callerApp: ProcessRecord{5224fb8 12583:com.jasperapps.testpackageremoveintent:remote/u0a146}; inVisibleTask: false]
2022-12-25 11:29:57.191   511-855   ActivityTaskManager     pid-511                              E  Abort background activity starts from 10146

Where Abort background activity starts from 10146 means that I'm violating the background restrictions, which is expected.

Instead, when I examined the logcat for ActivityTaskManager for the app which workarounds this I found next:

2022-12-25 11:34:59.196   511-4063  ActivityTaskManager     pid-511                              I  START u0 {cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras)} from uid 10148
2022-12-25 11:34:59.198   511-4063  ActivityTaskManager     pid-511                              W  Background activity start [callingPackage: com.bingo.cleaner; callingUid: 10148; appSwitchAllowed: false; isCallingUidForeground: false; callingUidHasAnyVisibleWindow: false; callingUidProcState: FOREGROUND_SERVICE; isCallingUidPersistentSystemProcess: false; realCallingUid: 10148; isRealCallingUidForeground: false; realCallingUidHasAnyVisibleWindow: false; realCallingUidProcState: FOREGROUND_SERVICE; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: PendingIntentRecord{921ede4 com.bingo.cleaner startActivity}; allowBackgroundActivityStart: false; intent: Intent { cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }; callerApp: ProcessRecord{c06f774 13034:com.bingo.cleaner/u0a148}; inVisibleTask: false]
2022-12-25 11:34:59.199   511-4063  ActivityTaskManager     pid-511                              W  startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { flg=0x800000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }
2022-12-25 11:34:59.200   511-4063  ActivityTaskManager     pid-511                              E  Abort background activity starts from 10148

2022-12-25 11:34:59.209   511-857   ActivityTaskManager     pid-511                              I  START u0 {flg=0x10000000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras)} from uid 10148
2022-12-25 11:34:59.210   511-857   ActivityTaskManager     pid-511                              W  Background activity start [callingPackage: com.bingo.cleaner; callingUid: 10148; appSwitchAllowed: false; isCallingUidForeground: false; callingUidHasAnyVisibleWindow: false; callingUidProcState: FOREGROUND_SERVICE; isCallingUidPersistentSystemProcess: false; realCallingUid: 10148; isRealCallingUidForeground: false; realCallingUidHasAnyVisibleWindow: false; realCallingUidProcState: FOREGROUND_SERVICE; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: null; allowBackgroundActivityStart: false; intent: Intent { flg=0x10000000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }; callerApp: ProcessRecord{c06f774 13034:com.bingo.cleaner/u0a148}; inVisibleTask: false]
2022-12-25 11:34:59.210   511-857   ActivityTaskManager     pid-511                              E  Abort background activity starts from 10148

2022-12-25 11:34:59.285   511-857   ActivityTaskManager     pid-511                              I  START u0 {cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras)} from uid 10148
2022-12-25 11:34:59.287   511-857   ActivityTaskManager     pid-511                              W  Background activity start [callingPackage: com.bingo.cleaner; callingUid: 10148; appSwitchAllowed: false; isCallingUidForeground: false; callingUidHasAnyVisibleWindow: false; callingUidProcState: FOREGROUND_SERVICE; isCallingUidPersistentSystemProcess: false; realCallingUid: 10148; isRealCallingUidForeground: false; realCallingUidHasAnyVisibleWindow: false; realCallingUidProcState: FOREGROUND_SERVICE; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: PendingIntentRecord{921ede4 com.bingo.cleaner startActivity (allowlist: d43f3f6:+30s0ms/0/NOTIFICATION_SERVICE/NotificationManagerService)}; allowBackgroundActivityStart: false; intent: Intent { cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }; callerApp: ProcessRecord{c06f774 13034:com.bingo.cleaner/u0a148}; inVisibleTask: false]
2022-12-25 11:34:59.287   511-857   ActivityTaskManager     pid-511                              W  startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { flg=0x800000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }
2022-12-25 11:34:59.288   511-857   ActivityTaskManager     pid-511                              E  Abort background activity starts from 10148

2022-12-25 11:34:59.288   511-857   ActivityTaskManager     pid-511                              I  START u0 {flg=0x10000000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras)} from uid 10148
2022-12-25 11:34:59.288   511-857   ActivityTaskManager     pid-511                              W  Background activity start [callingPackage: com.bingo.cleaner; callingUid: 10148; appSwitchAllowed: false; isCallingUidForeground: false; callingUidHasAnyVisibleWindow: false; callingUidProcState: FOREGROUND_SERVICE; isCallingUidPersistentSystemProcess: false; realCallingUid: 10148; isRealCallingUidForeground: false; realCallingUidHasAnyVisibleWindow: false; realCallingUidProcState: FOREGROUND_SERVICE; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: null; allowBackgroundActivityStart: false; intent: Intent { flg=0x10000000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }; callerApp: ProcessRecord{c06f774 13034:com.bingo.cleaner/u0a148}; inVisibleTask: false]
2022-12-25 11:34:59.289   511-857   ActivityTaskManager     pid-511                              E  Abort background activity starts from 10148

2022-12-25 11:34:59.522   511-543   ActivityTaskManager     pid-511                              I  START u0 {cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras)} from uid 10148
2022-12-25 11:34:59.522   511-543   ActivityTaskManager     pid-511                              W  startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { flg=0x800000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }
2022-12-25 11:34:59.527   511-543   ActivityTaskManager     pid-511                              W  Can't find TaskDisplayArea to determine support for multi window. Task id=27 attached=false
2022-12-25 11:34:59.606   511-852   ActivityTaskManager     pid-511                              W  Tried to set launchTime (0) < mLastActivityLaunchTime (556847)
2022-12-25 11:34:59.914   511-546   ActivityTaskManager     pid-511                              I  Displayed com.bingo.cleaner/.modules.scene.fork.ForkActivityC: +325ms

Note, I intentionally added blank lines to the logcat to make it clearer. So the app tries to launch an activity 3 times and gets rejected by the system. However on the 4th time it somehow succeeds!

Please take a look on the video of my screen recording: https://yura-misc.s3.eu-central-1.amazonaws.com/activity_from_bakcground.mov

P.S. What I have tried (from onReceive of the runtime-registered broadcast receiver):

  1. starting the activity in a loop up to 10 times (to replicate what the sample app is doing)
  2. showing a notification along with starting the activity (I thought the notification could increase priority of my app)
  3. starting another foreground service and launching the activity from it (I thought it could increase priority of my app too)
  4. sending a Pending Intent instead of regular intent to start the activity

I suppose this must be some kind of a hack, which is potentially android system vulnerability. Do you please have any ideas of what could it be or in what direction would I want to look?



from Android Background activity start

How can I hide a user from the Wikipedia "Recent changes" page?

I need to hide all the contributions of a particular user. (e.g. "‎Adumbrativus") from this page.

So this entry will be hidden.

25 December 2022
Javaris Crittenton‎ 10:34  −23‎  ‎Adumbrativus talk contribs‎ (Remove "convicted murderer"; the charge was dropped)

I am already using a similar script with Tampermonkey.

I am trying to find what changes needs to be done in this script so that it will hide the user on Wikipedia recent changes page.


Update:

I am using this script on a non-english wikipedia and I am able to hide the username. But I need to hide the entire line and not just username.

// ==UserScript==
// @name         Hide usernames from the "Recent changes" page
// @description  Hide usernames on non english wikis
// @version      0.1
// @author       double-beep
// @match        https://mr.wikipedia.org/wiki/%E0%A4%B5%E0%A4%BF%E0%A4%B6%E0%A5%87%E0%A4%B7:%E0%A4%85%E0%A4%B2%E0%A5%80%E0%A4%95%E0%A4%A1%E0%A5%80%E0%A4%B2_%E0%A4%AC%E0%A4%A6%E0%A4%B2*
// @require      https://gist.githubusercontent.com/BrockA/2625891/raw/waitForKeyElements.js
// @require      https://code.jquery.com/jquery-3.6.3.min.js
//
// @icon         https://www.google.com/s2/favicons?sz=64&domain=wikipedia.org
// @grant        none
// ==/UserScript==
/* globals waitForKeyElements */

(function() {
    const blacklisted = ['अभय नातू', 'InternetArchiveBot'];

    waitForKeyElements('.mw-changeslist-line-inner-userLink', ([element]) => {
        const userLink = element.querySelector('.mw-userlink');
        const username = userLink?.textContent.trim();

        if (!blacklisted.includes(username)) return; // not blacklisted

        element.style.display = 'none';
    }, false);
})();



from How can I hide a user from the Wikipedia "Recent changes" page?

check whether android device in maintenance window

I want to check whether device is in a maintenance window of doze mode.

so I used :

//on receive alarm broadcast
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean isDeviceIdleMode = pm.isDeviceIdleMode();
//do work

but realized that it returned false always.

After referring to documentation, I found that,

it will return false if the device is in a long-term idle mode but currently running a maintenance window where restrictions have been lifted.

Is there a method like isDeviceInMaintenanceWindow or how can I programmatically detect it?



from check whether android device in maintenance window

How can I replicate rows in Pandas?

My pandas dataframe looks like this:

   Person  ID   ZipCode   Gender
0  12345   882  38182     Female
1  32917   271  88172     Male
2  18273   552  90291     Female

I want to replicate every row 3 times like:

   Person  ID   ZipCode   Gender
0  12345   882  38182     Female
0  12345   882  38182     Female
0  12345   882  38182     Female
1  32917   271  88172     Male
1  32917   271  88172     Male
1  32917   271  88172     Male
2  18273   552  90291     Female
2  18273   552  90291     Female
2  18273   552  90291     Female

And of course, reset the index so it is:

0
1
2
...

I tried solutions such as:

pd.concat([df[:5]]*3, ignore_index=True)

And:

df.reindex(np.repeat(df.index.values, df['ID']), method='ffill')

But none of them worked.



from How can I replicate rows in Pandas?

How can I match a pattern, and then everything upto that pattern again? So, match all the words and acronyms in my below example

Context

I have the following paragraph:

text = """
בביהכנ"ס - בבית הכנסת דו"ח - דין וחשבון הת"ד -  התיקוני דיקנא
בגו"ר  - בגשמיות ורוחניות ה"א - ה' אלוקיכם התמי' - התמיהה
בהנ"ל - בהנזכר לעיל ה"א - ה' אלקיך ואח"כ - ואחר כך
בהשי״ת - בהשם יתברך ה"ה - הרי הוא / הוא הדין ואת"ה - ואיגוד תלמידי 
"""

this paragraph is combined with Hebrew words and their acronyms.

A word contains quotation marks (").

So for example, some words would be:

[
    'בביהכנ"ס',
     'דו"ח',
     'הת"ד'
 ]

Now, I'm able to match all the words with this regex:

(\b[\u05D0-\u05EA]*\"\b[\u05D0-\u05EA]*\b)

enter image description here

Question

But how can I also match all the corresponding acronyms as a separate group? (the acronyms are what's not matched, so not the green in the picture).

Example acronyms are:

[
    'בבית הכנסת',
    'דין וחשבון',
    'התיקוני דיקנא'
]

Expected output

The expected output should be a dictionary with the Words as keys and the Acronyms as values:

{
    'בביהכנס': 'בבית הכנסת',
    'דו"ח': 'דין וחשבון',
    'הת"ד': 'התיקוני דיקנא'
}

My attempt

What I tried was to match all the words (as above picture):

(\b[\u05D0-\u05EA]*\"\b[\u05D0-\u05EA]*\b)

and then match everything until the pattern appears again with .*\1, so the entire regex would be:

(\b[\u05D0-\u05EA]*\"\b[\u05D0-\u05EA]*\b).*\1

But as you can see, that doesn't work:

enter image description here

  • How can I match the words and acronyms to compose a dictionary with the words/acronyms?

Note

When you print the output, it might be printed in Left-to-right order. But it should really be from Right to left. So if you want to print from right to left, see this answer:

right-to-left languages in Python



from How can I match a pattern, and then everything upto that pattern again? So, match all the words and acronyms in my below example

Monday 26 December 2022

Android 13 - TileService for Quick Settings Panel is not collapsing onClick

Short Question: startActivityAndCollapse not working for Android 13

Long Question: I am creating a tile for the quick settings panel. I have tried to implement this demo. It's working fine for all other devices except Android 13

override fun onClick() {
    super.onClick()
    try {
        val newIntent =
            FlutterActivity.withNewEngine().dartEntrypointArgs(listOf("launchFromQuickTile"))
                .build(this)
        newIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivityAndCollapse(newIntent)
    } catch (e: Exception) {
        Log.d("debug", "Exception ${e.toString()}")
    }
}

The above code is working to open the application but it's not collapsing the quick settings panel.

Is there any solution, any help?

Edited:

I had taken a look more into this and found that It's working only If I pass the Android activity.

Example (Android):

val newIntent = Intent(this, MainActivity::class.java)
newIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivityAndCollapse(newIntent)

Example (Flutter):

val newIntent = FlutterActivity.withNewEngine().dartEntrypointArgs(listOf("launchFromQuickTile")).build(this)
newIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivityAndCollapse(newIntent)

Is there any other way to open Flutter App with Params?



from Android 13 - TileService for Quick Settings Panel is not collapsing onClick

Problem with solving exquations of TransposedConv2D for finding its parameters

Regarding the answer posted here, When I want to use the equations for obtaining the values of the parameters of the transposed convolution, I face some problems. For example, I have a tensor with the size of [16,256,16,160,160] and I want to upsample that to the size of [16,256,16,224,224]. Based on the equation of the transposed convolution, when, for solving the equations for the height, I select stride+2 and I want to find the k (kernel size), I have the following equation that the kernel size will have a large and also negative value.

224 = (160 - 2)x (2) + 1x(k - 1) + 1

What is wrong with my calculations and how I can find the parameters.



from Problem with solving exquations of TransposedConv2D for finding its parameters

Missing "nonce" claim with Quickbooks + Authlib

When I try to implement an OAuth flow into Quickbooks Online with the openid scope, I receive an error authlib.jose.errors.MissingClaimError: missing_claim: Missing "nonce" claim.

Here is the code:

from authlib.integrations.flask_client import OAuth

oauth = OAuth(app)
oauth.register(
    name="qbo",
    client_id='x',
    client_secret='x',
    server_metadata_url='https://developer.api.intuit.com/.well-known/openid_sandbox_configuration',
    client_kwargs={"scope": "openid email profile com.intuit.quickbooks.accounting"},
)


@app.route("/login")
def login():
    redirect_uri = url_for("callback", _external=True)
    client = getattr(oauth, 'qbo')
    return client.authorize_redirect(redirect_uri, state='hello')


@app.route("/callback")
def callback():
    client = getattr(oauth, 'qbo')
    token = client.authorize_access_token()
    return 'authorized'

The line client.authorize_access_token() is failing. This also fails when I pass a nonce param to the authorize_redirect() method.

When I remove the openid email profile scopes, then this works without an issue. I have similar code for openid and Google, and that works without any issues.

Any ideas on what is happening in this case?



from Missing "nonce" claim with Quickbooks + Authlib

Clean architecture principles in FastAPI + SQLModel development

When I develop with Flask and SQLAlchemy, I commonly use the following layers:

  • A repository layer, that deals with database connections and data persistence;
  • A use cases layers, a bunch of functions that use the repository and do exactly what the application is intented to do;
  • A rest layer where my REST endpoints where located.

I get this architectural pattern from the book "Clean Architectures in Python", by Leonardo Giordani. You can get the book here.

Recently I started to learn FastAPI and SQLModel ORM. The whole idea of using Pydantic in SQLModel and FastAPI create the possibility to do an endpoint like this:

@app.get("/songs", response_model=list[Song])
def get_songs(session: Session = Depends(get_session)):
    result = session.execute(select(Song))
    songs = result.scalars().all()
    return [Song(name=song.name, artist=song.artist, id=song.id) for song in songs]

In this endpoint the very database logic is dealt with, as the endpoint receives a session as a dependency and executes a query to get the results and, using Pydantic's magic, receives parsed and validated data and responds with a Pydantic model.

My question is: something like this is considered an clean architecture? Based on the principles I've learn, we have the web framework doing almost everything. And I think the very idea of using Pydantic both in SQLModel and FastAPI is to allow us to create endpoints like that.

But this is clean? When my app grows, couldn't I be limited by this kind of design?



from Clean architecture principles in FastAPI + SQLModel development

Securely pass current wordpress user to external flask app

I have a Wordpress site with users, and a separate Flask app with logic for responding to Get/Post requests from the WordPress site.

I am able to get the current user into a JavaScript variable on the WP site and send to the Flask app - however how do I ensure that someone cannot pretend to be a different current user, or make this secure to other potential vulnerabilities?

Is there some way of exposing a token or suchlike to JavaScript on the WP side, which then the Flask app can verify, say by using the WordPress API?



from Securely pass current wordpress user to external flask app

Fast way to calculate Hessian matrix of model parameters in PyTorch

I want to calculate the Hessian matrix of a loss w.r.t. model parameters in PyTorch, but using torch.autograd.functional.hessian is not an option for me since it recomputes the model output and loss which I already have from previous calls. My current implementation is as follows:

import torch
import time

# Create model
model = torch.nn.Sequential(torch.nn.Linear(1, 100), torch.nn.Tanh(), torch.nn.Linear(100, 1))
num_param = sum(p.numel() for p in model.parameters())

# Evaluate some loss on a random dataset
x = torch.rand((1000,1))
y = torch.rand((1000,1))
y_hat = model(x)
loss = ((y_hat - y)**2).mean()

''' Calculate Hessian '''
start = time.time()

# Allocate Hessian size
H = torch.zeros((num_param, num_param))

# Calculate Jacobian w.r.t. model parameters
J = torch.autograd.grad(loss, list(model.parameters()), create_graph=True)
J = torch.cat([e.flatten() for e in J]) # flatten

# Fill in Hessian
for i in range(num_param):
    result = torch.autograd.grad(J[i], list(model.parameters()), retain_graph=True)
    H[i] = torch.cat([r.flatten() for r in result]) # flatten

print(time.time() - start)

Is there any way to do this faster? Perhaps without using the for loop, since it is calling autograd.grad for every single model variable.



from Fast way to calculate Hessian matrix of model parameters in PyTorch

Sunday 25 December 2022

How to create pop up window in Android Native code?

I am not able to find a way to create a Pop up window in Android NDK. Can someone share some code reference or NDK API reference for creating a pop up window? I meant in C++ and not java code for pop up window.



from How to create pop up window in Android Native code?

Does MongoDB scale without it being asynchronous

Background: I'm working on a discord bot that uses MongoDB as a database. I'm not sure this will scale very well as MongoDB is not asynchronous. The function the MongoDB cluster edits are in is asynchronous. I don't want the discord bot to pause if someone else is using the same function.

I'm wondering if I need to use something like Motor (Mongodb's Async driver).



from Does MongoDB scale without it being asynchronous

pipenv is not able to pickup the python versions from pyenv(pyenv-win)?

I tried using pyenv(pyenv-win) with pipenv in python. i installed some of the versions of python using pyenv but when am trying to create a virtual environment using the one of the versions which i have installed through pyenv. pipenv is not able to pickup the python versions from pyenv.

pipenv --python 3.10.6
C:\Users\MUZUB\test1>pipenv --python 3.10.6
Warning: Python 3.10.6 was not found on your system...
Would you like us to install CPython 3.10.6 with Pyenv? [Y/n]: n

Installed Pyenv Python Versions :

C:\Users\MUZUB>pyenv versions
  3.10.6
  3.10.7
  3.11.0rc2
  3.6.0
  3.7.1
  3.7.2
  3.8.1
  3.9.2
  3.9.5
* 3.9.9 (set by C:\Users\MUZUB\.pyenv\pyenv-win\version)

My default python version is 3.11

C:\Users\MUZUB\test1>python
Python 3.11.1 (tags/v3.11.1:a7a450f, Dec  6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

when i don't specify a specific version of python .pipenv is using my default python installation to create a virtual environment.

C:\Users\MUZUB\test1>pipenv shell
Creating a virtualenv for this project...
Pipfile: C:\Users\MUZUB\test1\Pipfile
Using C:/Users/MUZUB/Desktop/python311/python.exe (3.11.1) to create virtualenv...
[    ] Creating virtual environment...created virtual environment CPython3.11.1.final.0-64 in 4715ms
  creator Venv(dest=C:\Users\MUZUB\.virtualenvs\test1-y9ytVeDV, clear=False, no_vcs_ignore=False, global=False, describe=CPython3Windows)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\MUZUB\AppData\Local\pypa\virtualenv)
    added seed packages: pip==22.3.1, setuptools==65.6.3, wheel==0.38.4
  activators BashActivator,BatchActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator

Successfully created virtual environment!
Virtualenv location: C:\Users\MUZUB\.virtualenvs\test1-y9ytVeDV
requirements.txt found in C:\Users\MUZUB instead of Pipfile! Converting...
Warning: Your Pipfile now contains pinned versions, if your requirements.txt did.
We recommend updating your Pipfile to specify the "*" version, instead.
Launching subshell in virtual environment...
Microsoft Windows [Version 10.0.22621.963]
(c) Microsoft Corporation. All rights reserved.

User Environment variables:

PYENV         C:\Users\MUZUB\.pyenv\pyenv-win\
PYENV_HOME    C:\Users\MUZUB\.pyenv\pyenv-win\
PYENV_ROOT    C:\Users\MUZUB\.pyenv\pyenv-win\versions

Path:

C:\Users\MUZUB\Desktop\python311
C:\Users\MUZUB\Desktop\python311\Scripts
C:\Users\MUZUB\.pyenv\pyenv-win\shims
C:\Users\MUZUB\.pyenv\pyenv-win\bin
C:\Users\MUZUB\.pyenv\pyenv-win\versions

I have tried changing priority in path.but it doesn't work.

iam expecting the python versions installed with pyenv be available to pipenv.



from pipenv is not able to pickup the python versions from pyenv(pyenv-win)?

Regex-rule for matching single word during input (TipTap InputRule)

I'm currently experimenting with TipTap, an editor framework. My goal is to build a Custom Node extension for TipTap that wraps a single word in <w>-Tags, whenever a user is typing text. In TipTap I can write an InputRule with Regex for this purpose

For example the rule /(?:^|\s)((?:~)((?:[^~]+))(?:~))$/ will match text between two tildes (~text~) and wrap it with <strike>-Tags.

Click here for my Codesandbox

I was trying for so long and can't figure it out. Here are the rules that I tried:

/**
 * Regex that matches a word node during input
 */

// Will match words between two tilde characters; I'm using this expression from the documentation as my starting point. 
//const inputRegex =  /(?:^|\s)((?:~)((?:[^~]+))(?:~))$/

// Will match a word but will append the following text to that word without the space inbetween
//const inputRegex =  /\b\w+\b\s$/

// Will match a word but will append the following text to previous word without the space inbetween; Will work with double spaces
//const inputRegex =  /(?:^|\s\b)(?:[^\s])(\w+\b)(?:\s)$/

// Will match a word but will swallow every second character
//const inputRegex =  /\b([^\s]+)\b$/g

// Will match every second word
//const inputRegex =  /\b([^\s]+)\b\s(?:\s)$/

// Will match every word but swallow spaces; Will work if I insert double spaces
const inputRegex =  /\b([^\s]+)(?:\b)\s$/


from Regex-rule for matching single word during input (TipTap InputRule)

Saturday 24 December 2022

Type hint that excludes a certain type

In Python, is it possible to declare a type hint that excludes certain types from matching? For example, is there a way to declare a type hint that is "typing.Iterable except not str" or the like?



from Type hint that excludes a certain type

Memory efficient dot product between a sparse matrix and a non-sparse numpy matrix

I have gone through similar questions that has been asked before (for example [1] [2]). However, none of them completely relevant for my problem.

I am trying to calculate a dot product between two large matrices and I have some memory constraint that I have to meet.

I have a numpy sparse matrix, which is a shape of (10000,600000). For example,

from scipy import sparse as sps
x = sps.random(m=10000, n=600000, density=0.1).toarray()

The second numpy matrix is of size (600000, 256), which consists of only (-1, 1).

import numpy as np
y = np.random.choice([-1,1], size=(600000, 256))

I need dot product of x and y at lowest possible memory required. Speed is not the primary concern.

Here is what I have tried so far:

Scipy Sparse Format:

Naturally, I converted the numpy sparse matrix to scipy csr_matrix. However, task is still getting killed due to memory issue. There is no error, I just get killed on the terminal.

from scipy import sparse as sps
sparse_x = sps.csr_matrix(x, copy=False)
z = sparse_x.dot(y)
# killed

Decreasing dtype precision + Scipy Sparse Format:

from scipy import sparse as sps

x = x.astype("float16", copy=False)
y = y.astype("int8", copy=False)

sparse_x = sps.csr_matrix(x, copy=False)
z = sparse_x.dot(y)
# Increases the memory requirement for some reason and dies 

np.einsum

Not sure if it helps/works with sparse matrix. Found something interesting in this answer. However, following doesn't help either:

z = np.einsum('ij,jk->ik', x, y)
# similar memory requirement as the scipy sparse dot

Suggestions?

If you have any suggestions to improve any of these. Please let me know. Further, I am thinking in the following directions:

  1. It would be great If I can get rid of dot product itself somehow. My second matrix (i.e. y is randomly generated and it just has [-1, 1]. I am hoping if there is way I could take advantage of its features.

  2. May be diving dot product into several small dot product and then, aggregate.



from Memory efficient dot product between a sparse matrix and a non-sparse numpy matrix

Pycharm doesn't recognize packages with remote interpreter

TL;DR - This is a PyCharm remote interpreter question.

Remote libraries are not properly synced, and PyCharm is unable to index properly when using remote interpreter. Everything runs fine.

Following is the entire (currently unsuccessful) debug process


I am using a virtual environment created with python -m venv venv, then pointing to it as I always have using ssh interpreter. The exact same happens with conda as well.

enter image description here

enter image description here

enter image description here

After configuring the interpreter, many of the installed packages are marked red by PyCharm, not giving auto complete, and not knowing these packages.

Here is pip freeze

absl-py==1.3.0
aggdraw==1.3.15
aiohttp==3.8.3
aiosignal==1.3.1
albumentations==1.3.0
algo-api==2.5.0
algo-flows==2.4.0
allegroai==3.6.1
altair==4.2.0
amqp==5.1.1
anomalib==0.3.2
antlr4-python3-runtime==4.9.3
anyio==3.6.2
astunparse==1.6.3
async-timeout==4.0.2
attrs==20.3.0
bcrypt==4.0.1
bleach==5.0.1
boto3==1.26.34
botocore==1.29.34
cachetools==5.2.0
certifi==2022.12.7
cffi==1.15.1
charset-normalizer==2.1.1
clearml==1.8.3
click==8.1.3
commonmark==0.9.1
contourpy==1.0.6
cpu-cores==0.1.3
cryptography==38.0.4
cycler==0.11.0
DateTime==4.7
decorator==5.1.1
deepmerge==1.1.0
dnspython==2.2.1
docker-pycreds==0.4.0
docopt==0.6.2
docutils==0.19
dotsi==0.0.3
efficientnet==1.0.0
einops==0.6.0
entrypoints==0.4
fastapi==0.88.0
ffmpy==0.3.0
fire==0.5.0
Flask==2.2.2
flatbuffers==1.12
focal-loss==0.0.7
fonttools==4.38.0
frozenlist==1.3.3
fsspec==2022.11.0
furl==2.1.3
future==0.18.2
gast==0.4.0
gitdb==4.0.10
GitPython==3.1.29
google-auth==2.15.0
google-auth-oauthlib==0.4.6
google-pasta==0.2.0
gradio==3.15.0
grpcio==1.51.1
gunicorn==20.1.0
h11==0.14.0
h5py==3.7.0
httpcore==0.16.3
httpx==0.23.1
humanfriendly==9.2
idna==3.4
image-classifiers==1.0.0
imageio==2.23.0
imagesize==1.4.1
imgaug==0.4.0
importlib-metadata==5.2.0
importlib-resources==5.10.1
imutils==0.5.4
inflection==0.5.1
iniconfig==1.1.1
itsdangerous==2.1.2
jaraco.classes==3.2.3
jeepney==0.8.0
Jinja2==3.1.2
jmespath==1.0.1
joblib==1.2.0
jsonschema==3.2.0
keras==2.9.0
Keras-Applications==1.0.8
Keras-Preprocessing==1.1.2
keyring==23.13.1
kiwisolver==1.4.4
kmeans1d==0.3.1
kornia==0.6.8
libclang==14.0.6
linkify-it-py==1.0.3
luqum==0.11.0
Markdown==3.4.1
markdown-it-py==2.1.0
MarkupSafe==2.1.1
maskrcnn-benchmark==1.1.2+cu113
matplotlib==3.6.2
mdit-py-plugins==0.3.3
mdurl==0.1.2
ml-distillery==1.0.1
more-itertools==9.0.0
multidict==6.0.3
networkx==2.8.8
numpy==1.23.1
oauthlib==3.2.2
omegaconf==2.3.0
opencv-python==4.6.0.66
opencv-python-headless==4.6.0.66
opt-einsum==3.3.0
orderedmultidict==1.0.1
orjson==3.8.3
overrides==6.1.0
packaging==22.0
pandas==1.5.2
paramiko==2.12.0
pathlib==1.0.1
pathlib2==2.3.7.post1
pathtools==0.1.2
pika==1.3.1
Pillow==9.3.0
pkginfo==1.9.2
pluggy==1.0.0
ply==3.11
promise==2.3
protobuf==3.19.6
psd-tools==1.9.23
psutil==5.9.4
py==1.11.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
pyclipper==1.3.0.post4
pycocotools==2.0.6
pycparser==2.21
pycpd==2.0.0
pycryptodome==3.16.0
pydantic==1.9.0
pyDeprecate==0.3.2
pydub==0.25.1
pygit2==1.11.1
Pygments==2.13.0
pyhumps==3.8.0
PyJWT==2.4.0
pymongo==4.1.1
PyNaCl==1.5.0
pyparsing==2.4.7
pyrsistent==0.19.2
pytest==7.1.2
python-dateutil==2.8.2
python-multipart==0.0.5
pytorch-lightning==1.6.4
pytz==2022.7
PyWavelets==1.4.1
PyYAML==6.0
qudida==0.0.4
readme-renderer==37.3
requests==2.28.1
requests-oauthlib==1.3.1
requests-toolbelt==0.10.1
rfc3986==1.5.0
rich==12.6.0
rsa==4.9
s3transfer==0.6.0
scikit-image==0.19.3
scikit-learn==1.1.3
scipy==1.9.3
SecretStorage==3.3.3
segmentation-models==1.0.1
sentry-sdk==1.12.1
setproctitle==1.3.2
shapely==2.0.0
shortuuid==1.0.11
six==1.16.0
sklearn==0.0.post1
smmap==5.0.0
sniffio==1.3.0
starlette==0.22.0
tensorboard==2.9.1
tensorboard-data-server==0.6.1
tensorboard-plugin-wit==1.8.1
tensorflow==2.9.1
tensorflow-estimator==2.9.0
tensorflow-io-gcs-filesystem==0.29.0
termcolor==2.1.1
threadpoolctl==3.1.0
tifffile==2022.10.10
timm==0.5.4
tinytree==0.2.1
tomli==2.0.1
toolz==0.12.0
torch==1.10.2+cu113
torchmetrics==0.9.0
torchtext==0.11.2
torchvision==0.11.3+cu113
tqdm==4.64.0
twine==4.0.2
typing-utils==0.1.0
typing_extensions==4.4.0
uc-micro-py==1.0.1
urllib3==1.26.13
uv-build-utils==1.4.0
uv-envyaml==2.0.1
uv-python-serving==2.0.1
uv-python-utils==1.12.0
uvicorn==0.20.0
uvrabbit==1.4.1
validators==0.20.0
vine==5.0.0
wandb==0.12.17
webencodings==0.5.1
websockets==10.4
Werkzeug==2.2.2
windshield-grid-localisation==1.0.0.dev5
wrapt==1.14.1
yacs==0.1.8
yarl==1.8.2
zipp==3.11.0
zope.interface==5.5.2

The following minimal test program

import pytest
import uv_python_utils
from importlib_metadata import version as version_query
from pkg_resources import parse_version
import requests


installed_pytest_version = parse_version(version_query('pytest'))
installed_uv_python_utils_version = parse_version(version_query('uv_python_utils'))
installed_importlib_metadata_version = parse_version(version_query('importlib_metadata'))
print(installed_pytest_version)
print(installed_uv_python_utils_version)
print(installed_importlib_metadata_version)

runs with output

7.1.2
1.12.0
5.2.0

but in the IDE, it looks like this:

enter image description here

Here is the support ticket for JetBrains (not sure if visible for everyone or not). They were not able to help yet.

They offered, and I have done all of the following which did not help:

  1. Delete ~/.pycharm_helpers on remote
  2. Go to Help | Find Action... and search for "Registry...". In the registry, search for python.use.targets.api and disable it. Reconfigure your project interpreter.

I also tried to purge everything from Pycharm from both local and remote, and reinstall, and this persists.

  1. Uninstall PyCharm, resinstall an older version that works for a colleague (works on the same remote in the same directory for the colleague, so the problem is local)
  2. Delete .idea
  3. Delete C:\Users\noam.s\AppData\Roaming\JetBrains
  4. Obviously I tried invalidate caches & restart.

The libraries just don't get downloaded to the External Libraries, as shown in the Project menu, which doesn't agree with pip freeze

In the venv case:

enter image description here

In the conda case, the downloaded remote libraries don't even agree with the Pycharm interpreter screen!

enter image description here

enter image description here

This really makes it hard for me to work and I am not able to find any workaround. Any ideas?


For the bounty, it is enough for me to know how to fix it, though it would be preferable to know:

  1. Why does this happen?
  2. How to fix it?
  3. How to avoid it?


from Pycharm doesn't recognize packages with remote interpreter