Monday 31 January 2022

JQuery - Mouseenter / hover event on top level menu ONLY, not the submenu ( list items NOT nested list items)

I have a navigation menu with 2 levels built using nested lists. I need an event to only trigger on the mouseenter of the top level of the menu, not the submenu. From what I have read this should work as it should only target direct children:

$('.#primary-menu > li').mouseenter(function() {
    console.log('please work');
}); 

However, it does not work as it triggers when the submenu items are hovered as well.

I have also seen some examples where the NOT selector is used but I cant get this working either.

$('#primary-menu:not(:has(ul.subnav))').mouseenter(function() {
    console.log('please work');
});

Can anyone one help?

I have done a very simplistic example here:

https://codepen.io/lol4000/pen/VwMLOMO

//*UPDATE//

I tried the code suggestions by @CertainPerformance but this does not work for my code as I am using wordpress so I cannot add classes to the links. I tried using the .menu-item-has-children class instead but this does not work.

$('.menu-item-has-children').on('mouseenter', () => {
  console.log('top-level item entered');
});

Neither does this

$('#primary-menu > li').on('mouseenter', (e) => {
  console.log('top-level item entered:' + e.currentTarget.children[0].textContent);
});

Actual HTML code below:

<ul id="primary-menu" class="menu nav-menu"><li id="menu-item-4793" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-4793"><a href="#" class="menu-image-title-after menu-image-not-hovered"><img width="1" height="1" src="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2021/12/Plan-de-travail-1-copie.svg" class="menu-image menu-image-title-after" alt="" loading="lazy"><span class="menu-image-title-after menu-image-title">Faculté</span></a>
<ul class="sub-menu">
    <li id="menu-item-4908" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4908"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/la-faculte-2/origine-vocation-internationale/">Présentation</a></li>
    <li id="menu-item-4893" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4893"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/la-faculte-2/origine-vocation-internationale/">Nos atouts</a></li>
    <li id="menu-item-4892" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4892"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/la-faculte-2/">Devenir des diplômés</a></li>
</ul>
</li>


 <li id="menu-item-4794" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current-menu-ancestor current-menu-parent menu-item-has-children menu-item-4794"><a href="/formations/" aria-current="page" class="menu-image-title-after menu-image-not-hovered"><img width="1" height="1" src="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2021/12/Plan-de-travail-1.svg" class="menu-image menu-image-title-after" alt="" loading="lazy"><span class="menu-image-title-after menu-image-title">Formations</span></a>
<ul class="sub-menu" style="display: none;">
    <li id="menu-item-5049" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item menu-item-5049"><a href="/formations/" aria-current="page">Formations</a></li>
</ul>
</li>
<li id="menu-item-4795" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-4795"><a href="#" class="menu-image-title-after menu-image-not-hovered"><img width="1" height="1" src="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2021/12/DEPARTEMENTS1.svg" class="menu-image menu-image-title-after" alt="" loading="lazy"><span class="menu-image-title-after menu-image-title">Départements</span></a>
<ul class="sub-menu">
    <li id="menu-item-4883" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4883"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/formations/aes-economie-gestion/">AES – Economie-Gestion</a></li>
    <li id="menu-item-4884" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4884"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/formations/anglais/">Anglais</a></li>
    <li id="menu-item-4895" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4895"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/formations/droit/">Droit</a></li>
    <li id="menu-item-4886" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4886"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/formations/pole-international-management/">Pôle International de Management</a></li>
    <li id="menu-item-4887" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4887"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/formations/langues-orientales/">ILCO</a></li>
    <li id="menu-item-4888" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4888"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/formations/langues-romanes-germaniques/">LRG</a></li>
</ul>
</li>
<li id="menu-item-4796" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-4796"><a href="#" class="menu-image-title-after menu-image-not-hovered"><img width="1" height="1" src="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2021/12/Plan-de-travail-1-copie-2.svg" class="menu-image menu-image-title-after" alt="" loading="lazy"><span class="menu-image-title-after menu-image-title">Vie étudiante</span></a>
<ul class="sub-menu">
    <li id="menu-item-4833" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4833"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/le-campus/">Le Campus</a></li>
    <li id="menu-item-4834" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4834"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/la-faculte-2/vie-associative/">Les associations</a></li>
    <li id="menu-item-4897" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4897"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/le-cadre-de-vos-etudes/">Vivre au Havre</a></li>
</ul>
</li>
<li id="menu-item-4797" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-4797"><a href="#" class="menu-image-title-after menu-image-not-hovered"><img width="1" height="1" src="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2021/12/Plan-de-travail-1-copie-4.svg" class="menu-image menu-image-title-after" alt="" loading="lazy"><span class="menu-image-title-after menu-image-title">Entreprises</span></a>
<ul class="sub-menu">
    <li id="menu-item-4858" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4858"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/alternance/">Alternance</a></li>
    <li id="menu-item-4896" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4896"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/entreprises/stages-et-offres-demploi/">Stages</a></li>
    <li id="menu-item-4898" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4898"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/reprise-detudes/">Formations tout au long de la vie</a></li>
    <li id="menu-item-4857" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4857"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/taxe-dapprentissage/">Taxe d’apprentissage</a></li>
</ul>
</li>
<li id="menu-item-4798" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-4798"><a href="#" class="menu-image-title-after menu-image-not-hovered"><img width="1" height="1" src="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2021/12/Plan-de-travail-1-copie-6.svg" class="menu-image menu-image-title-after" alt="" loading="lazy"><span class="menu-image-title-after menu-image-title">Recherche</span></a>
<ul class="sub-menu">
    <li id="menu-item-4859" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4859"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/laboratoires/">Laboratoires</a></li>
    <li id="menu-item-4905" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4905"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/formations/formations-par-niveaux/doctorat/">Ecoles Doctorales</a></li>
</ul>
</li>
<li id="menu-item-4799" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-4799"><a href="#" class="menu-image-title-after menu-image-not-hovered"><img width="1" height="1" src="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2021/12/Plan-de-travail-1-copie-5.svg" class="menu-image menu-image-title-after" alt="" loading="lazy"><span class="menu-image-title-after menu-image-title">International</span></a>
<ul class="sub-menu">
    <li id="menu-item-4861" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4861"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/la-faculte-2/venir-etudier-au-havre/">Venir étudier au Havre</a></li>
    <li id="menu-item-4862" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4862"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/partir-a-letranger/">Partir à l’étranger</a></li>
    <li id="menu-item-4866" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4866"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/international-students/">International Students</a></li>
    <li id="menu-item-4907" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4907"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/international/">Partenaires Internationaux</a></li>
</ul>
</li>
<li id="menu-item-4800" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-4800"><a href="#" class="menu-image-title-after menu-image-not-hovered"><img width="1" height="1" src="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2021/12/Plan-de-travail-1-copie-3.svg" class="menu-image menu-image-title-after" alt="" loading="lazy"><span class="menu-image-title-after menu-image-title">Infos pratiques</span></a>
<ul class="sub-menu">
    <li id="menu-item-4808" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4808"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/venir-sur-le-campus/">Venir sur le campus</a></li>
    <li id="menu-item-4903" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4903"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/procedure-dadmission/">Candidater à nos formations</a></li>
    <li id="menu-item-4870" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4870"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/la-vie-etudiante/services-numeriques/">Outils numériques / Services en ligne</a></li>
    <li id="menu-item-4871" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4871"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/ma-rentree/">[Ma rentrée]</a></li>
    <li id="menu-item-4872" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4872"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/quiz-pour-les-indecis/">FAQ</a></li>
</ul>
</li>
</ul>


from JQuery - Mouseenter / hover event on top level menu ONLY, not the submenu ( list items NOT nested list items)

Dynamically load data into rmarkdown html output

Is there a way to have the data associated with and html output file generated via Rmarkdown be loaded dynamically (e.g., via javascript or ajax) when opening the html output?

For instance, I have this simple Rmarkdown file which produces a plot (in svg) and a table:

---
title: "test"
output: 
    html_document:
        self_contained: false
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = "svglite", fig.ext = ".svg")
library(svglite)
library(DT)
```

```{r, echo=FALSE}
DATA <- data.frame(a = 1:5, b = 6:10)
plot(DATA)
datatable(DATA)
```

Is there a way to feed the data to the html file so that when the data changes and I open it again the plot and table are updated automatically without having to render the Rmarkdown script?



from Dynamically load data into rmarkdown html output

Your app contains an Implicit Internal Intent vulnerability

Google rejecting my app and i'm having trouble with this security error that appear when i submit app as production release:

Implicit Internal Intent

Your app contains an Implicit Internal Intent vulnerability. Please see this Google Help Center article for details.

com.mypackage.name.sync.SyncService.onHandleIntent

I applied all recommendations listed here: Remediation for Implicit PendingIntent Vulnerability

But the error still persists.

My service:

public class SyncService extends IntentService {
    protected void onHandleIntent(Intent intent) {
... 
 Intent i = new Intent("com.mypackage.name.REFRESH");
 app.sendBroadcast(i);
...
   }
 }

Manifest:

<service
    android:name=".sync.SyncService"
    android:exported="false" >
</service>

The service started in many places in 3 methods like this: (As recommended by google i did add PendingIntent.FLAG_IMMUTABLE)

Method 1:

Intent intent = new Intent(this, SyncService.class);
PendingIntent pIntent = PendingIntent.getService(this, 0, intent,
            PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis,
        SYNC_FREQUENCY, pIntent);

Method 2:

Intent intent = new Intent("com.mypackage.name.REFRESH");
intent = new Intent(getApplicationContext(), SyncService.class);
intent.putExtra("notification_unassigned_sync", true);
startService(intent);

Method 3:

Intent intent = new Intent(getApplicationContext(), SyncService.class);
startService(intent);

Is there anything wrong in my code ? Any recommendations ?



from Your app contains an Implicit Internal Intent vulnerability

Can I preserve the order of a javascript object's entries, when some entry keys are integers?

I am working with an object where I need to preserve the order of the entries, even though some keys are alphanumeric and others are integers. (Yes, I know.)

The object I'm starting with looks like this:

{
  a: 'the',
  quick: 'quick',
  b: 'brown',
  fox: 'fox'
}

After manipulation, the object should look like this:

{
  a: 'the',
  0: 'quick',
  b: 'brown',
  1: 'fox'
}

But. Because iteration order in javascript objects differs from insertion order (integers are iterated first), if I go about this straightforwardly, I won't get the correctly ordered result:

let myReindexedObject = {};

myReindexedObject['a'] = 'the';
myReindexedObject['0'] = 'quick';
myReindexedObject['b'] = 'brown';
myReindexedObject['1'] = 'fox';

console.log(myReindexedObject);

I've tried to solve this issue by building a Map (which, unlike an object, preserves entry order) which I can then convert into an object.

Source: (I adapted this gist by Luke Horvat: Convert ES6 Map to Object Literal .)

Can you guess what happens?

let myMap = new Map();

myMap.set('a', 'the');
myMap.set('0', 'quick');
myMap.set('b', 'brown');
myMap.set('1', 'fox');

let myArray = Array.from(myMap);

let myReindexedObject = myArray.reduce((myReindexingObject, [key, value]) => {
  return Object.assign(myReindexingObject, { [key]: value })
}, {});

console.log(myReindexedObject);

Is there any way I can use integer-based keys like 0 and 1 and still preserve the object entries in a custom order?

Or do I need to consider other approaches?



from Can I preserve the order of a javascript object's entries, when some entry keys are integers?

response is undefined despite sendResponse from bg script

I just don't understand why it isn't working!I have a background.js script that creates a tab (history.html). This html page contains a content script (history.js) that sends a message to the background script to get some history data (historyItems) and waits for a response from the background script containing that data.

The manifest file includes the following:

"web_accessible_resources": [
        "/history.html",
        "/script/history.js",
        "/images/*.png"
],
"content_security_policy": "script-src 'self'; object-src 'self'; img-src *; ",
"background": {
    "scripts": [
        "/scripts/background.js"
    ]
},
"permissions": [
    "<all_urls>",
    "contextMenus",
    "storage",
    "tabs",
    "search",
    "webRequest",
    "webRequestBlocking"
],
"optional_permissions": [
    "notifications",
    "downloads",
    "bookmarks",
    "history"
],
"content_scripts": [
    {
        "matches": [
            "<all_urls>"
        ],
        "js": [
            "/scripts/history.js",
            "/scripts/selection.js",
            "/scripts/exif.js",
            "/scripts/color-thief.min.js",
            "/scripts/Sortable.min.js",
            "/scripts/RGraph.svg.common.core.js",
            "/scripts/RGraph.svg.line.js",
            "/scripts/exif_tags.js"
        ]
    }
]

I'm not sure whether history.js should be defined as a content script or if extension scripts can message to/from background scripts.

history.js contains the following code:

document.addEventListener('DOMContentLoaded', getHistoryItems);

function getHistoryItems() {
    // Send message to background script and get response
    browser.runtime.sendMessage({ action: 'getHistoryItems' })
        .then(handleResponse)
        .catch((err) => {
            console.error(err);
            console.log('Failed to get history items.');
        });
}

function handleResponse(response) {
    const historyItems = response.historyItems;
    const ol = document.getElementById('historyItems');
    for (let item of historyItems) {
        let li = document.createElement('li');
        li.style.listStyleType = 'none';
        li.style.margin = '0px';
        li.style.padding = '0px';
        let title = document.createElement('h3');
        title.textContent = item.title;
        let url = document.createElement('p');
        url.textContent = item.url;
        let lastVisitTime = document.createElement('p');
        lastVisitTime.textContent = item.lastVisitTime;
        li.appendChild(title);
        li.appendChild(url);
        li.appendChild(lastVisitTime);
        ol.appendChild(li);
    }
}

and background.js contains the following code:

let historyItems;

/// Handle Incoming Messages
// Listen for messages from the content or options script
browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
    switch (message.action) {
...
        case 'getHistoryItems':
            if (logToConsole) console.log(historyItems);
            sendResponse({ historyItems: historyItems });
            return true;
        default:
            break;
    }
});
...
            switch (keyword) {
...
                case ('!h' || 'history'):
                    historyItems = await browser.history.search({ text: searchTerms });
                    await browser.tabs.create({
                        active: contextsearch_makeNewTabOrWindowActive,
                        index: tabPosition,
                        url: '/history.html'
                    })
                    break;
...

Finally, history.html just contains the history.js script:

<!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>History Search</title>
    </head>
    <body>
        <h2>History Search Results</h2>
        <ol id="historyItems"></ol>
        <script src="/scripts/history.js"></script>
    </body>
</html>


from response is undefined despite sendResponse from bg script

Looking for GPU support on Markov-chain Monte-Carlo (MCMC) for Python codes in general and for a specific code

I am looking for MCMC codes with a GPU suport (like NVIDIA or OpenCL libraries) to make faster run chains in Python but I would like also to find a C++ library that allows to perform this.

I know there is a plenty of codes that does MCMC but which ones could allow to exploit GPU power with MCMC ?

In particular, it seems it is possible with the Gibbs sampler but I would like to know more in practice, i.e how to implement it ?

Finally, the code on which I work currently is this Python code : emcee code and I would like to introduce or add a GPU extra functionality in this code to benefit fully from the parallel computing of Markov chain : I don't know if this is possible.

Any help is welcome.



from Looking for GPU support on Markov-chain Monte-Carlo (MCMC) for Python codes in general and for a specific code

React production build not showing page after logging in

React returns an Uncaught SyntaxError: Unexpected token '<' error and I was able to figure out that it's because the script tag returns HTML instead of Javascript bundle. This only happens when trying to navigate programmatically, say after logging in. Other pages show fine but.

How do I make the script tag return Javascript instead of HTML? Also, why does the script tag return HTML instead of JavaScript when the program navigates programmatically.

I'm using the React-router package to route the pages and I'm suspecting it has something to do with it. If so, any way around it?

App.js

import { Routes, Route } from "react-router-dom";
import { ChakraProvider } from "@chakra-ui/react";

import LandingPage from "./LandingPage";

import Login from "./authentication/Login";
import RequireAuth from "./authentication/RequireAuth";
import Register from "./authentication/Register";

import ClientDashboard from "./dashboard/client/ClientDashboard";
import LoanRequest from "./dashboard/client/LoanRequest";
import Offers from "./dashboard/client/Offers";

import ShowOffer from "./dashboard/client/ShowOffer";
import EditOffer from "./dashboard/client/EditOffer";
import PublishOffer from "./dashboard/client/PublishOffer";

import InvestorDashboard from "./dashboard/investor/InvestorDashboard";
import InvestorDashboard2 from "./dashboard/investor/InvestorDashboard2";
import InvestorOffers from "./dashboard/investor/InvestorOffers";
import InvestorBids from "./dashboard/investor/InvestorBids";
import InvestorDeclinedBids from "./dashboard/investor/InvestorDeclinedBids";

import Profile from "./dashboard/client/ProfileSettings";

import BrokerDashboard from "./dashboard/broker/Dashboard";
import NewClient from "./dashboard/broker/NewClient";
import AllClients from "./dashboard/broker/AllClients";
import NewOffer from "./dashboard/broker/NewOffer";
import NewOfferTranche from "./dashboard/broker/NewOfferTranche";
import NewOfferTiming from "./dashboard/broker/NewOfferTiming";

function App() {
  return (
    <ChakraProvider>
      <Routes>
        <Route path="/" element={<LandingPage />} />
        <Route path="/login" element={<Login />} />
        <Route path="/register" element={<Register />} />
        <Route path="/profile" element={<Profile />} />

        {/*Client dashboard*/}
        <Route
          path="/client/dashboard"
          element={
            <RequireAuth>
              <ClientDashboard />
            </RequireAuth>
          }
        />
        <Route
          path="/client/new-loan"
          element={
            <RequireAuth>
              <LoanRequest />
            </RequireAuth>
          }
        />
        <Route
          path="/client/offers"
          element={
            <RequireAuth>
              <Offers />
            </RequireAuth>
          }
        />
        <Route
          path="/client/offers/offer"
          element={
            <RequireAuth>
              <ShowOffer />
            </RequireAuth>
          }
        />
        <Route
          path="/client/offers/offer/edit"
          element={
            <RequireAuth>
              <EditOffer />
            </RequireAuth>
          }
        />
        <Route
          path="/client/offers/offer/publish"
          element={
            <RequireAuth>
              <PublishOffer />
            </RequireAuth>
          }
        />

        {/*Investor Dashboard*/}
        <Route
          path="/investor/dashboard"
          element={
            <RequireAuth>
              <InvestorDashboard />
            </RequireAuth>
          }
        />
        <Route
          path="/investor/offers"
          element={
            <RequireAuth>
              <InvestorDashboard2 />
            </RequireAuth>
          }
        />
        <Route
          path="/investor/offers/offer"
          element={
            <RequireAuth>
              <InvestorOffers />
            </RequireAuth>
          }
        />
        <Route
          path="/investor/bids"
          element={
            <RequireAuth>
              <InvestorBids />
            </RequireAuth>
          }
        />
        <Route
          path="/investor/bids/declined"
          element={
            <RequireAuth>
              <InvestorDeclinedBids />
            </RequireAuth>
          }
        />
    </ChakraProvider>
  );
}

export default App;

Login.js

import React, { useState } from "react";
import { Link, useNavigate, useLocation, Navigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";

import { signInAsync } from "../../redux/authSlice";

import DocumentHead from "../DocumentHead";
import Button from "../Button";

import setBgImage from "../../utils/setBgImage";
import phoneLady from "../../assets/images/phoneLady.jpg";

export default function Login() {
    const pageName = "Login";
    const navigate = useNavigate();
    const { state } = useLocation();

    const [form, setForm] = useState({
        emailAddress: "",
        password: "",
        isChecked: false,
        isLoading: false,
    });


    const [formErrors, setFormErrors] = useState({
        emailAddress: "",
        password: "",
        emptyFields: "",
    });

    const { isLoggedIn } = useSelector((state) => state.auth);

    const { message } = useSelector((state) => state.message.server);

    // Dipstach Redux actions
    const dispatch = useDispatch();

    const handleChange = (e) => {
        const target = e.target;
        const name = target.name;
        const value =
            target.type === "checkbox" ? target.checked : target.value;

        setForm((state) => {
            return {
                ...state,
                [name]: value,
            };
        });
    };

    // Input from form state
    const { emailAddress, password } = form;

    const handleSubmit = (e) => {
        e.preventDefault();

        setForm((state) => {
            return {
                ...state,
                isLoading: true,
            };
        });

        const data = { email: emailAddress, password };

        for (let props in data) {
            if (data[props] === "" || data[props] === null) {
                setForm((state) => ({...state, isLoading: false}));
                setFormErrors((state) => ({...state, emptyFields: "Please fill in the fields"}));
                return
            } 
        }

        // Redux hook dispatches sign-in action (Login requst)
        dispatch(signInAsync(data)).then((response) => {
            console.log(response);

            if ("user" in response) {

                const userType = response.user.groups[0];

                if (userType.name === "Client") {
                    navigate(state?.path || "/client/dashboard"); // <----- Error upon navigation

                    // Reload to update Redux state
                    window.location.reload()
                }

                if (userType.name === "Broker") {
                    navigate(state?.path || "/broker/dashboard"); // <----- Error upon navigation

                    // Reload to update Redux state
                    window.location.reload()
                }

                if (userType.name === "Investor") {
                    navigate(state?.path || "/investor/dashboard"); // <--- Error upon navigation

                    // Reload to update Redux state
                    window.location.reload()
                }

                return
            }
        });
    };

    if (isLoggedIn) return (<Navigate to="/" replace />);

    return (
        <>
            <DocumentHead title={pageName} />
            <section id="orderbook-login" className="orderbook-authentication">
                <div className="grid grid-cols-1 md:grid-cols-2 h-full">
                    <div
                        id="intro-background"
                        className="hidden md:block"
                        style={setBgImage && setBgImage(phoneLady)}
                    >
                        <div
                            id="login-intro"
                            className="flex flex-col items-center auth-intro"
                        >
                            <div
                                id="login-title"
                                className="bg-white px-6 mb-3 self-start flex items-center justify-center shadow-md orderbook-icon"
                            >
                                Orderbook
                            </div>
                            <h1 className="shadow-sm">
                                Welcome to your go to financial platform
                            </h1>
                            <p>
                                Lorem ipsum dolor sit amet, consectetur
                                adipiscing elit, sed do eiusmod tempor
                                incididunt ut labore et dolore magna aliqua. Ut
                                enim ad minim veniam, quis nostrud exercitation.
                            </p>
                        </div>
                        <div id="overlay"></div>
                    </div>

                    <div id="orderbook-form">
                        <form
                            className="h-full"
                            onSubmit={(e) => handleSubmit(e)}
                        >
                            <div className="pt-20 pb-10 px-12">
                                <h1
                                    id="orderbook-home"
                                    className="text-center mb-10 leading-6 md:hidden"
                                >
                                    <Link to="/" className="text-gray-400">
                                        Orderbook Online
                                    </Link>
                                </h1>
                                <div className="px-4 sm:px-0 mb-3">
                                    <h2 className="text-lg font-medium leading-6 pb-3 sm:pb-2">
                                        Welcome back
                                    </h2>
                                    <p className="mt-1 text-sm text-gray-600">
                                        Log into your account
                                    </p>
                                </div>
                                <div className="grid grid-cols-2 gap-5">
                                    <div className="col-span-6 sm:col-span-4">
                                        <input
                                            type="text"
                                            name="emailAddress"
                                            id="email-address"
                                            autoComplete="email"
                                            placeholder="Email"
                                            className="mt-1 focus:ring-white block w-full sm:text-sm bg-gray-300 form-field"
                                            required
                                            onChange={(e) => handleChange(e)}
                                        />
                                    </div>

                                    <div className="col-span-6 sm:col-span-4">
                                        <input
                                            type="password"
                                            name="password"
                                            id="password"
                                            autoComplete="password"
                                            placeholder="Password"
                                            className="mt-1 focus:ring-white block w-full sm:text-sm bg-gray-300 form-field"
                                            required
                                            onChange={(e) => handleChange(e)}
                                        />
                                    </div>

                                    <div className="col-span-6 sm:col-span-4">
                                        <div className="flex items-start">
                                            <div className="flex items-center h-5">
                                                <input
                                                    type="checkbox"
                                                    name="isChecked"
                                                    id="persist-login"
                                                    className="focus:ring-white h-4 w-4 text-indigo-600 border-black rounded"
                                                    onChange={(e) =>
                                                        handleChange(e)
                                                    }
                                                />
                                            </div>
                                            <div className="ml-3 text-sm">
                                                <label
                                                    htmlFor="persist-login"
                                                    className="font-medium text-black"
                                                >
                                                    Keep me logged in
                                                </label>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="col-span-6 sm:col-span-4 mt-1 flex items-end">
                                        <Link
                                            to="#"
                                            id="forgot-password"
                                            className="w-full"
                                        >
                                            Forgot password?
                                        </Link>
                                    </div>

                                    <div className="col-span-6 sm:col-span-4 mt-1">
                                        <Button
                                            type="submit"
                                            buttonClass="login-button auth-button"
                                        >
                                            Login{" "}
                                            {form.isLoading ? (
                                                <i className="fa fa-spinner fa-pulse fa-3x fa-fw" style=></i>
                                            ) : null}
                                        </Button>
                                    </div>

                                    <div
                                        id="dont-have-account"
                                        className="col-span-6 sm:col-span-4 mt-1 text-center account-signal"
                                    >
                                        <span>Don't have an account yet?</span>{" "}
                                        <Link to="/register">Sign up</Link>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </section>
        </>
    );
}


from React production build not showing page after logging in

AWS API aut from oauth

Firstly working with AWS api, so sorry for newbee question.

I need to access this endpoint

https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/declarations

to post declarations on this web

postingdeclaration.eu

I found config file on site

{
    "aws": {
        "enabled": true,
        "config": {
            "Auth": {
                "region": "eu-west-1",
                "mandatorySignIn": true,
                "clearStorageOnInit": false,
                "identityPoolId": "eu-west-1:adb74568-cac1-89b3-75e8-db123d6rtee9",
                "userPoolId": "eu-west-1_U8iuLTd6R",
                "userPoolWebClientId": "12db2t9v156qgdpsrlujjlc6kl",
                "oauth": {
                    "domain": "auth.postingdeclaration.eu",
                    "scope": [
                        "user",
                        "email",
                        "domain",
                        "firstName",
                        "lastName"
                    ],
                    "redirectSignIn": "https://www.postingdeclaration.eu/home",
                    "redirectSignOut": "https://ecas.ec.europa.eu/cas/logout",
                    "responseType": "code",
                    "identityProvider": "euLogin"
                }
            },
            "API": {
                "endpoints": [
                    {
                        "name": "Users",
                        "region": "eu-west-1",
                        "endpoint": "https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/users"
                    },
                    {
                        "name": "Invitations",
                        "region": "eu-west-1",
                        "endpoint": "https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/invitations"
                    },
                    {
                        "name": "Accounts",
                        "region": "eu-west-1",
                        "endpoint": "https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/accounts"
                    },
                    {
                        "name": "Declarations",
                        "region": "eu-west-1",
                        "endpoint": "https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/declarations"
                    },
                    {
                        "name": "RoadsideCheck",
                        "region": "eu-west-1",
                        "endpoint": "https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/bo/declarations"
                    },
                    {
                        "name": "Drivers",
                        "region": "eu-west-1",
                        "endpoint": "https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/drivers"
                    },
                    {
                        "name": "Operators",
                        "region": "eu-west-1",
                        "endpoint": "https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/operators"
                    },
                    {
                        "name": "Requests",
                        "region": "eu-west-1",
                        "endpoint": "https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/requests"
                    },
                    {
                        "name": "Documents",
                        "region": "eu-west-1",
                        "endpoint": "https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/documents"
                    },
                    {
                        "name": "Messages",
                        "region": "eu-west-1",
                        "endpoint": "https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/messages"
                    },
                    {
                        "name": "HistoryLog",
                        "region": "eu-west-1",
                        "endpoint": "https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/history-logs"
                    }
                ]
            }
        }
    }
}

I have only that config, endpoints, username and passwords from this website postingdeclaration.eu

I tryed use this script, but suck, my username and passwords is not equal to AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY

import requests
from requests_aws4auth import AWS4Auth

session = requests.Session()
session.auth = AWS4Auth(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, 'eu-west-1', 'execute-api')

response = requests.get('https://b7dyyr5r1s.execute-api.eu-west-1.amazonaws.com/prod/declarations', auth=auth)

website geting aws keys from response

headers = {
    'authority': 'cognito-identity.eu-west-1.amazonaws.com',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
    'content-type': 'application/x-amz-json-1.1',
    'x-amz-content-sha256': 'Hash',
    'x-amz-target': 'AWSCognitoIdentityService.GetCredentialsForIdentity',
    'x-amz-user-agent': 'aws-amplify/2.3.0 js aws-amplify/2.3.0 js callback',
    'sec-ch-ua-platform': '"Windows"',
    'accept': '*/*',
    'origin': 'https://www.postingdeclaration.eu',
    'sec-fetch-site': 'cross-site',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.postingdeclaration.eu/',
    'accept-language': 'en-US,en;q=0.9',
}

data = '{"Logins":{"cognito-idp.eu-west-1.amazonaws.com/eu-west-1_M5iuBYd1C":"Hash"},"IdentityId":"eu-west-1:ID"}'

But how website generate hashes?

So how to write right syntax to use that type of config of AWS API?



from AWS API aut from oauth

Sunday 30 January 2022

Apollo onError Observable fowarding not working

it seems as if the request is not being retried.

  • The refreshToken mutation successfully provides a new token
  • This new token is then being successfully passed to the operation via the operation.setContext() function
  • The then() function is being successfully called (catch does not activate)
  • The request does not get retried and is being fullfilled with the same error "Signature has expired"

The idea is from How to execute an async fetch request and then retry last failed request? and is the accepted answer.

const errorLink = onError(
  ({ graphQLErrors, networkError, operation, forward }) => {
    if (graphQLErrors) {
      for (let err of graphQLErrors) {
        switch (err.message) {
          case "Signature has expired":
            return new Observable((observer) => {
              getNewToken()
                .then((token) => {
                  operation.setContext(({ headers = {} }) => {
                    return {
                      headers: {
                        ...headers,
                        authorization: `JWT ${token}`,
                      },
                    };
                  });
                })
                .then(() => {
                  const subscriber = {
                    next: observer.next.bind(observer),
                    error: observer.error.bind(observer),
                    complete: observer.complete.bind(observer),
                  };

                  forward(operation).subscribe(subscriber);
                })
                .catch((error) => {
                  // No refresh or client token available, we force user to login
                  observer.error(error);
                });
            });
        }
      }
    }
  }
);


from Apollo onError Observable fowarding not working

App crash on firestick 2nd gen when getting presigned URL

Gradle

implementation platform('software.amazon.awssdk:bom:2.17.119')
implementation 'software.amazon.awssdk:s3'

Code Used To get Presigned Url

public static URL getPresignedUrl(String bucketName, String keyName ) {
    PresignedGetObjectRequest presignedGetObjectRequest = null;
    try {
        AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create
                (AwsBasicCredentials.create(Access Key, Secret Key));


        S3Presigner preSigner = S3Presigner.builder()
                .credentialsProvider(credentialsProvider)
                .region(Region.US_WEST_2).build();
        GetObjectRequest getObjectRequest =
                GetObjectRequest.builder()
                        .bucket(bucketName)
                        .key(keyName)
                        .build();

        GetObjectPresignRequest getObjectPresignRequest = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            getObjectPresignRequest = GetObjectPresignRequest.builder()
                    .signatureDuration(Duration.ofDays(1))
                    .getObjectRequest(getObjectRequest)
                    .build();
        }

        // Generate the presigned request
         presignedGetObjectRequest =
                 preSigner.presignGetObject(getObjectPresignRequest);
    } catch (Exception e) {
        e.getStackTrace();
    }
    return  presignedGetObjectRequest.url();
}

App working fine if the fire OS version is greater than or equal 7.x.x Crashes on fire OS version 5.x.x

Crashing on the line S3Presigner preSigner = S3Presigner.builder()

Crash Log

Need help



from App crash on firestick 2nd gen when getting presigned URL

Running "python -m unittest" failing with maven exec-maven-plugin

I'm trying to set up my maven build so that mvn test runs my python tests in addition to my Java tests. I'm trying to use the exec-maven-plugin to do this.

My pom.xml has:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>3.0.0</version>
  <executions>
    <execution>
      <configuration>
        <executable>python3</executable>
        <workingDirectory>${project.basedir}/src/main/resources/scripts/</workingDirectory>
        <arguments>
          <argument>-m</argument>
          <argument>unittest</argument>
          <argument>discover</argument>
          <argument>-p</argument>
          <argument>'*_test.py'</argument>
        </arguments>
      </configuration>
      <id>python-test</id>
      <phase>test</phase>
      <goals>
        <goal>exec</goal>
      </goals>
    </execution>
  </executions>
</plugin>

My project structure is like:

.
├── pom.xml
├── src
│   ├── main
│   │   └── resources
│   │       ├── scripts
│   │       │   ├── __init__.py
│   │       │   ├── foo.py
│   │       │   ├── foo_test.py

When I try to run it from the project root:

mvn exec:exec@python-test

I get 0 tests ran:

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

But, if I do this manually, it works fine:

cd src/main/resources/scripts 
python3 -m unittest discover -p '*_test.py' 
...
----------------------------------------------------------------------
Ran 3 tests in 0.010s

What am I doing wrong here?

Thanks in advance!



from Running "python -m unittest" failing with maven exec-maven-plugin

How to write clean tests on model with database access

I'm using SQLAlchemy + Ormar and I want to write clean tests as it possible to write with pytest-django:

import pytest
@pytest.mark.django_db
def test_user_count():
    assert User.objects.count() == 0

I'm using FastAPI and not using Django at all so decorator as above isn't possible to use.

How to write clean tests on model with Database access as above but not with Django. It would be great to have that infrastructure for SQLAlchemy + Ormar but changing ORM is an option too.

Example of model to test:

class User(ormar.Model):
    class Meta:
        metadata = metadata
        database = database

    id: int = ormar.BigInteger(primary_key=True)
    phone: str = ormar.String(max_length=100)
    account: str = ormar.String(max_length=100)


from How to write clean tests on model with database access

Saturday 29 January 2022

Vue JS 3 Application to run in older Firefox/Chrome

I'm developing an app in VueJS 3 and it seems that's working on my local computer. But I have to make it runs also on older browsers like Firefox 38 Chrome 49.

My app uses some "fetch" functions to load content from api, to authenticate, to send commands, etc. After reading the following 2 links I believe I have some issues with it (despite it should works on CH 42). https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API and Babel not Polyfilling Fetch when using babel-preset-env . What it is your opinion?

I have babel and in package.json the following settings:

"browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead",
    "Chrome > 48",
 ]

But the errors received in Firefox and Chrome are very cryptic and I don't know what how should I transpile that function. I would focus on Chrome 49 and I'll add some context

Indeed the async function is available after Chrome 55. But I don't know how to convert it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

For example in Chrome 49 I have the following console error on the following page: webpack:///./node_modules/@vue/devtools-api/esm/proxy.js

Uncaught SyntaxError: Unexpected identifier proxy.js:94

The content of that file is:

import { HOOK_PLUGIN_SETTINGS_SET } from './const';
export class ApiProxy {
constructor(plugin, hook) {
    this.target = null;
    this.targetQueue = [];
    this.onQueue = [];
    this.plugin = plugin;
    this.hook = hook;
    const defaultSettings = {};
    if (plugin.settings) {
        for (const id in plugin.settings) {
            const item = plugin.settings[id];
            defaultSettings[id] = item.defaultValue;
        }
    }
    const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
    let currentSettings = Object.assign({}, defaultSettings);
    try {
        const raw = localStorage.getItem(localSettingsSaveId);
        const data = JSON.parse(raw);
        Object.assign(currentSettings, data);
    }
    catch (e) {
        // noop
    }
    this.fallbacks = {
        getSettings() {
            return currentSettings;
        },
        setSettings(value) {
            try {
                localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
            }
            catch (e) {
                // noop
            }
            currentSettings = value;
        },
    };
    if (hook) {
        hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
            if (pluginId === this.plugin.id) {
                this.fallbacks.setSettings(value);
            }
        });
    }
    this.proxiedOn = new Proxy({}, {
        get: (_target, prop) => {
            if (this.target) {
                return this.target.on[prop];
            }
            else {
                return (...args) => {
                    this.onQueue.push({
                        method: prop,
                        args,
                    });
                };
            }
        },
    });
    this.proxiedTarget = new Proxy({}, {
        get: (_target, prop) => {
            if (this.target) {
                return this.target[prop];
            }
            else if (prop === 'on') {
                return this.proxiedOn;
            }
            else if (Object.keys(this.fallbacks).includes(prop)) {
                return (...args) => {
                    this.targetQueue.push({
                        method: prop,
                        args,
                        resolve: () => { },
                    });
                    return this.fallbacks[prop](...args);
                };
            }
            else {
                return (...args) => {
                    return new Promise(resolve => {
                        this.targetQueue.push({
                            method: prop,
                            args,
                            resolve,
                        });
                    });
                };
            }
        },
    });
}
async setRealTarget(target) {
    this.target = target;
    for (const item of this.onQueue) {
        this.target.on[item.method](...item.args);
    }
    for (const item of this.targetQueue) {
        item.resolve(await this.target[item.method](...item.args));
    }
}
}

I tried to change anything I found:

vue.config.js

    transpileDependencies: [
    "config",
    "vue",
    "vue-router",
    "vuex",
    "xml2js"
],

package.json

"dependencies": {
"@babel/polyfill": "^7.12.1",
"babel-polyfill": "^6.26.0",
"config": "^3.3.7",
"core-js": "^3.6.5",
"regenerator-runtime": "^0.13.9",
"vue": "^3.2.26",
"vue-router": "^4.0.12",
"vuex": "^4.0.2",
"xml2js": "^0.4.23"
  },
  "devDependencies": {
"@babel/cli": "^7.16.8",
"@babel/core": "^7.16.12",
"@babel/preset-env": "^7.16.11",
"@vue/babel-preset-app": "^4.5.15",
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-plugin-router": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"@vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.8.0",
"eslint-plugin-vue": "^7.0.0"
  },
  "browserslist": [
"defaults",
"> 1%",
"last 2 versions",
"not dead",
"Chrome > 48"
  ]

babel.config.js

module.exports = {
presets: [
  [
      '@vue/cli-plugin-babel/preset',
      {
          useBuiltIns: "usage",
          forceAllTransforms: true,
          targets: {
              "chrome": "49"
          },
          }
  ]
  ]
};

main.js

import "@babel/polyfill";
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './_store'
createApp(App).use(router).use(store).mount('#app');


from Vue JS 3 Application to run in older Firefox/Chrome

RxJava Single - Getting a memory leak, how to correctly unsubscribe?

I'm using RxJava's Single.fromCallable() to wrap around a third party library that makes an API call. I was testing different states on the call, success, failed, low network, no network.

But on the no network test I ran into a memory leak for the first time ever using RxJava. I spent the last hour combing through the code and trying to narrow down the leak with the LeakCanary library.

I figured out it was coming from subscribing to the Single.fromCallable().

Single.fromCallable(() -> {
       return remoteRepository.makeTransaction(signedTransaction).execute();
})
       .subscribeOn(Schedulers.newThread())
       .observeOn(AndroidSchedulers.mainThread())
       .subscribe(txHash -> {
              Log.d(TAG, "makeTransaction: " + txHash);
                    
                   
       }, err -> {
             Log.e(TAG, "makeTransaction: ", err);
                    
       });

Once I remove the

.subscribe(txHash -> { ... });

It no longer leaks.

I've tried googling stackoverflow with RxJava Single unsubscribe and I'm getting answers saying that you don't need to unsubscribe from Single

https://stackoverflow.com/a/43332198/11110509.

But if I don't I'll be getting memory leaks.

I've tried to unsubscribe by making the Single call an instance variable in my ViewModel:

Disposable mDisposable;

mDisposable = Single.fromCallable(() -> {...}).subscribe(txHash -> {..});

and unsubscribing it in the Fragment's onDestroy() method so it will unsubscribe if the user exits the screen before the call is finished.

@Override
    public void onDestroy() {
        super.onDestroy();
        mViewModel.getDisposable().dispose();
    }

But it's still leaking. I'm not sure if this is the correct way to unsubscribe or maybe I'm doing something else incorrectly.

How can I correctly unsubscribe from the Single Callable?



from RxJava Single - Getting a memory leak, how to correctly unsubscribe?

Python 3 app running in docker-compose will not print using print('text', end='\r')

Would appreciate a suggestion for a workaround or fix:

Python 3.9 running in docker-compose 3.8 and using CMD [ "python3", "-u", "app.py" ]

print('text', end='\r', flush=True) will not print to terminal - want this printed.

print('text', flush=True) will print to terminal.

Yes, using both "python3", "-u" and flush=True is an overkill. 🤷‍♂️



from Python 3 app running in docker-compose will not print using print('text', end='\r')

How can i solve "RunUAT ERROR: AutomationTool was unable to run successfully." error

I'm fairly new to Unreal Engine. And I'm using mac computer. I get such an error when I want to start the project on the android device in Unreal Engine. I keep getting the error even though I set the SDK, NDK and JDK paths. The version of Unreal Enigne I'm using is 4.27.2. I am sharing the error logs with you, thank you

enter image description here enter image description here



from How can i solve "RunUAT ERROR: AutomationTool was unable to run successfully." error

How to use the Form File Input widget of Bootstrap-Vue in RTL application?

I'm using the Form File Input of Bootstrap-Vue. Since my application in RTL, I want to reverse it. The current code:

<b-form-file
class="modal-input"
v-model="fileLocation"
:state="stateFileLocation"
browse-text="בחר"
placeholder="בדיקה בדיקה בדיקה" />

What I get:

enter image description here

How can I move the button to the other side?

EDIT: I tired using this suggestion, but without any success:

.custom-file-label::after {
    left: 0;
    right: auto;
    border-left-width: 0;
    border-right: inherit;
}

EDIT: The postcss-rtl is EOL, so I tried rtlcss by having the postcss.config.js file:

module.exports = {
  plugins: {
    'rtlcss':{
      autoRename: true
    }
  }
}

Also I had to install rtlcss@2.6.2 since it depends on postcss 8 which does not work with Vue 2. The result is that it flips everything the other way around, even the text:

enter image description here



from How to use the Form File Input widget of Bootstrap-Vue in RTL application?

Prevent y-axis labels from being cut off

My chart y labels are cut off and by trying different solution found on stackoverflow like adding spaces in labels or setting layout padding did not solved the problem.

The code

const optionsTotali = {
  maintainAspectRatio: false,
  responsive: true,
  plugins: {
    legend: {
      display: false
    },
    tooltip: {
      displayColors: false,
      mode: "index",
      intersect: 0,
      callbacks: {
        label: function(context) {
          return "€" + context.parsed.y.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(/[,.]/g, m => (m === ',' ? '.' : ','));
        }
      }
    },
  },
  scales: {
    y: {
      grid: {
        display: false
      },
      ticks: {
        min: 0,
        beginAtZero: true,
        sampleSize: 1,
        callback: function(value, index, values) {
          return "€" + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        }
      }
    }
  }
};

const ctx = document.getElementById("chartTotali").getContext('2d');
const chartTotali = new Chart(ctx, {
  type: 'line',
  data: {
    labels: [
      "08:00",
      "09:00",
      "10:00",
      "11:00",
      "12:00",
      "13:00",
      "14:00",
      "15:00",
      "16:00",
      "17:00",
      "18:00",
      "19:00",
      "20:00"
    ],
    datasets: [{
      label: "Totale €",
      fill: true,
      backgroundColor: '#0084ff',
      borderColor: '#0084ff',
      borderWidth: 2,
      pointBackgroundColor: '#0084ff',
      data: [
        "17089.36",
        "394279.52",
        "514863.02",
        "540198.74",
        "379222.06",
        "8793.42",
        "79.58",
        "116379.41",
        "444580.43",
        "506663.36",
        "457947.28",
        "138158.94",
        "398.46"
      ],
    }]
  },
  options: optionsTotali
});
.card-chart {
  overflow: hidden;
}

.card {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border: 0.0625rem solid rgba(34, 42, 66, .05);
  border-radius: 0.2857rem;
}

.card {
  background: #27293d;
  border: 0;
  position: relative;
  width: 100%;
  margin-bottom: 30px;
  box-shadow: 0 1px 20px 0 rgb(0 0 0 / 10%);
}

.card .card-body {
  padding: 15px 15px 15px 15px;
}

.card-body {
  flex: 1 1 auto;
  padding: 1.5rem;
}

.card-chart .chart-area {
  height: 220px;
  width: calc(100% + 30px);
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js"></script>
<div class="card card-chart">
  <div class="card-header">
    <div class="row">
      <div class="col-sm-6 text-left">
        <h5 class="card-category">Totale vendite</h5>
        <h2 class="card-title">Totali</h2>
      </div>
    </div>
  </div>
  <div class="card-body">
    <div class="chart-area">
      <canvas id="chartTotali" width="1563" height="220" style="display: block; box-sizing: border-box; height: 220px; width: 1563px;"></canvas>
    </div>
  </div>
</div>


from Prevent y-axis labels from being cut off

Friday 28 January 2022

Image picked from gallery on Android device throws "no such file or directory" when saving to online storage

In my React Native 0.66 app, there is a function saving images to online storage service OSS. Here is the code for saving to OSS:

import AliyunOSS from 'aliyun-oss-react-native';
AliyunOSS.initWithSecurityToken(STSConfig.SecurityToken,STSConfig.AccessKeyId,STSConfig.SecretKeyId,endPoint,configuration); 

const saveOSS = async (bucket_name, objkey, filePath) => {
        return (new Promise((resolve) => {
            AliyunOSS.asyncUpload(bucket_name, objkey, filePath).then( async (res) => {
                resolve(true);
            }).catch(async (error)=>{
                //==<< no such file/directory was thrown. see error image
                setTimeout(()=> {
                    AliyunOSS.asyncUpload(bucket_name, objkey, filePath).then( async (res) => {
                        //console.log("Success : ", res);
                        resolve(true);
                    }).catch(async (error)=>{
                        resolve(false);
                    })
                }, 20);
            })
        }));
    };
...
//<<== filePath returned below is from response out of [image crop picker][1]. 
//It is a cache path. see image below for detail
res = await saveOSS(bucket_name, objkey, filePath);  //<<==

enter image description here

After image was picked (displayed on device), saving it to online OSS throws error in saveOSS on device. Except the image name, the path in error is not exactly the same as the path passed in:

enter image description here

The code above works in dev but not on real android device. How to fix this error of image file not found?

UPDATE: tried to install and use another image picker (react-native-image-picker) and the error is the same on real device. I guess the issue may not be image picker related.



from Image picked from gallery on Android device throws "no such file or directory" when saving to online storage

FCM Notification On Android Not Opening Chrome When Tapped

So I am developing a website for a company. I need to send a notification from server to all supervisors account (whether on browser or mobile). So I implement the FCM for sending the notification.

In the client web page I have these code to make the client subscribe to FCM:

var firebaseConfig = {
    messagingSenderId: "xxxx",
    apiKey: "xxxx",
    projectId: "xxxx",
    appId: "xxxxx"
};
firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();
messaging
    .requestPermission()
    .then(function () {
        console.log('Notification permission granted.');

        // get the token in the form of promise
        return messaging.getToken();
    })
    .then(async function (token) {
        console.log('Token: ' + token);
        await fetch("/api/Supervisor/SubscribeToAllTopic?token=" + token);
    })
    .catch(function (err) {
        console.log('Unable to get permission to notify.', err);
    });

let enableForegroundNotification = true;
messaging.onMessage(function (payload) {
    console.log('Message received. ', payload);

    if (enableForegroundNotification) {
        let notification = payload.notification;

        const notificationOptions = {
            body: notification.body,
            data: payload.data
        };

        navigator.serviceWorker
            .getRegistrations()
            .then((registration) => {
                //registration[0].showNotification(notification.title);
                registration[0].showNotification(notification.title, notificationOptions);
            });
    }
});

Then there is service worker firebase-messaging-sw.js to handle the background activities:

importScripts("https://www.gstatic.com/firebasejs/7.16.1/firebase-app.js");
importScripts(
    "https://www.gstatic.com/firebasejs/7.16.1/firebase-messaging.js",
);
// For an optimal experience using Cloud Messaging, also add the Firebase SDK for Analytics.
importScripts(
    "https://www.gstatic.com/firebasejs/7.16.1/firebase-analytics.js",
);

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
    messagingSenderId: "xxxx",
    apiKey: "xxxx",
    projectId: "xxxx",
    appId: "xxxx"
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function (payload) {
    console.log(
        "[firebase-messaging-sw.js] Received background message ",
        payload,
    );
    // Customize notification here
    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
        data: payload.data
    };

    return self.registration.showNotification(
        notificationTitle,
        notificationOptions,
    );
});

self.addEventListener('notificationclick', function (event) {
    console.log(event);
    event.notification.close();
    //var urlToRedirect = event.notification.data.action;
    //event.waitUntil(self.clients.openWindow(urlToRedirect));

    let url = event.notification.data.action;
    event.notification.close(); // Android needs explicit close.
    event.waitUntil(
        clients.matchAll({ type: 'window' }).then(windowClients => {
            // Check if there is already a window/tab open with the target URL
            for (var i = 0; i < windowClients.length; i++) {
                var client = windowClients[i];
                // If so, just focus it.
                if (client.url === url && 'focus' in client) {
                    return client.focus();
                }
            }
            // If not, then open the target URL in a new window/tab.
            if (clients.openWindow) {
                return clients.openWindow(url);
            }
        })
    );


});

The notifications are successfully sent to web browsers or mobile phones. The problem is when I tapped the notification, it supposed to open chrome and redirect me to the action url. This only works if only there is an open web browser with the same host url.

For example if my website is https://mywebsite.com, if the mobile phone is now browsing at that url, it will open a new window and redirect to the action url (it works fine). If I do not have the host url opened, then tapping the notification will do nothing, also if the mobile phone does not have a chrome instance running, tapping the notification will do nothing.

How can I always instruct the client to open chrome and redirect them to the action url?



from FCM Notification On Android Not Opening Chrome When Tapped

discord.py ffmpeg song plays too quickly at the beginning

I build a discord bot using discord.py and ffmpeg, it works but the song in the first 0-5 seconds plays too fast, I think it's buffering so I tried to use asyncio.sleep but didn't work, suggestions to solve the problem?

play func:

with youtube_dl.YoutubeDL(self.opts) as ydl:
    await asyncio.sleep(0.1)
    ydl.cache.remove()
    await asyncio.sleep(0.1)
    info = ydl.extract_info(url, download=False)
    raw_url_song = info['formats'][0]['url']
    await self.real_play(ctx, raw_url_song)

real_play func:

source = await discord.FFmpegOpusAudio.from_probe(processed_url_song, **self.FFMPEG_OPTIONS)
await asyncio.sleep(0.5)
self.vc.play(source, after=lambda e: asyncio.run_coroutine_threadsafe(self.real_play(ctx, processed_url_song), self.client.loop))

these are the options:

self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
self.OPTIONS = {'format': 'bestaudio'}
self.opts = {'extract_flat': True, 'skip_download': True}

the functions are separate because I do something else (such as playlists), I have reported only the essential code to understand the problem, and the cache remove is essential to reduce the occurence of HTTP 404 forbidden error, btw also without cache remove the problem persists



from discord.py ffmpeg song plays too quickly at the beginning

Is there a way for Logic Pro X scripts to communicate with each other?

Say I have a script attached to a midi Piano and a script attached to a midi Bass. Is there any way those scripts can message each other? It seems as if each script is running in its own VM.



from Is there a way for Logic Pro X scripts to communicate with each other?

Can Logic Pro X scripts access the file system or load scripts from outside of Logic?

Is there any way to load an external script from within a Logic Pro X script?



from Can Logic Pro X scripts access the file system or load scripts from outside of Logic?

React Native Issue Highlighting Hashtags/Mentions in TextInput as User Types

I'm attempting to create a TextInput that detects and highlights #hashtags or @mentions as the user types. I'm using the code from this gist as a starting point which, from the GIFs on the gist, appears to do exactly what I want. However, I'm seeing some unexpected lag when I implement this solution.

I have "mention" color set to red, and all other text set to green. You'll notice in the GIF that after I move the cursor back to the highlighted portion of the code, then press space and start typing again, each letter from then on is very briefly colored red then flips to green. It's very subtle, and only appears to happen if I move the cursor back to a highlighted word and start typing from there.

I observed the same behavior on iOS simulator (14.5 and 15.2), a physical device (15.2) running Expo Go, and when running the app from Xcode directly on my physical device (outside of Expo Go).

How can I avoid the delay in formatting?

This is a fresh react native project created via expo init. The entirety of the project is pasted below:

package.json

{
  "name": "reactnativeplayground",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "expo start --dev-client",
    "android": "expo run:android",
    "ios": "expo run:ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "expo": "~44.0.2",
    "expo-splash-screen": "~0.14.1",
    "expo-status-bar": "~1.2.0",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-native": "0.64.3",
    "react-native-web": "0.17.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true
}

App.js

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, TextInput } from 'react-native';

export default function App() {
  const [testFormattedContent, setTestFormattedContent] = React.useState('');

  const handleChangeText = (inputText) => {
    const retLines = inputText.split("\n");
    const formattedText = [];
    retLines.forEach((retLine) => {
      const words = retLine.split(" ");
      const contentLength = words.length;
      var format = /[ !#@$%^&*()_+\-=\[\]{};':"\\|,.<>\/?\n]/;
      words.forEach((word,index) => {
        if (
          (word.startsWith("@") && !format.test(word.substr(1))) ||
          (word.startsWith("#") && !format.test(word.substr(1)))
        ) {
          const mention = (
            <Text key={index} style=>
              {word}
            </Text>
          );
          if (index !== contentLength - 1) formattedText.push(mention, " ");
          else formattedText.push(mention);
        } else {
          if (index !== contentLength - 1) return formattedText.push(word, " ");
          else return formattedText.push(word);
        }
      });
    });

    setTestFormattedContent(formattedText);
  };

  return (
    <View style={styles.container}>
      <TextInput
        style=
        onChangeText={handleChangeText}
      >
        <Text>{testFormattedContent}</Text>
      </TextInput>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    // alignItems: 'center',
    // justifyContent: 'center',
  },
});




from React Native Issue Highlighting Hashtags/Mentions in TextInput as User Types

React open collapse when the selected student is greater than 0

What I want is when the studentCount is greater than zero then the collapse automatic open and the Typography(viewStudentList) will 'Close', and when the studentCount is equal to zero then the collapse are close and the text on Typography(viewStudentList) 'View',

const onHandleSetViewStudentList = () => {
    if (!viewStudentList) {
      mapDiv.current.popup.close();
    }

    if (viewStudentList) {
      onHandleSetActiveStudent('');
    }

    setViewStudentList(!viewStudentList);
  };

<StudentWidget
   setViewStudendList={onHandleSetViewStudentList}
   viewStudentList={studentList.length > 0 ? true : false}
   countStudent={studentList.length}
/>

///

const propTypes = {
  countStudent: PropTypes.func,
  viewStudentList: PropTypes.bool,
};

const defaultProps = {
  countStudent:''
  viewStudentList: false,
};
const StudentWidget = ({
  countStudent,
  viewStudentList,
}) => {
   ....
   <Typography sx=>
       {viewStudentList ? 'Close' : 'View'}
   </Typography>
   <Collapse in={viewStudentList} sx=>
      .....
   </Collapse>
}

in this update i can show the studentlists if the studentCount is greater than zero but the only problem is the button doesnt work. the button function is it will close the collapse and view collapse



from React open collapse when the selected student is greater than 0

Thursday 27 January 2022

Connect android mobile bluetooth with desktop for mouse and keyboard access

How to connect a bluetooth with desktop and android phone. i able to parring and connect bluetooth but unable to connected with Mouse, keyboard & pen device type.

Below given are both mobile device. but A50 device connect using other app and i want to connect M30s as mouse, keyboard.

enter image description here

private  class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            BluetoothSocket tmp = null;
            mmDevice = device;
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
             
            } catch (IOException e) {
                e.printStackTrace();
            }
            mmSocket = tmp;
        }

        public void run() {
            btAdapter.cancelDiscovery();
            try {
                mmSocket.connect();
            } catch (IOException connectException) {
                try {
                    mmSocket.close();
                } catch (IOException closeException) { }
                return;
            }

            mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
        }


        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
}


from Connect android mobile bluetooth with desktop for mouse and keyboard access

mypy - erroring when there are no Python files

Is there a way to stop mypy erroring when it doesn't find any .py files? In essence, this isn't an error. What Im looking to do is hide or silence this one error.

$ poetry run mypy .
There are no .py[i] files in directory '.'
Error: Process completed with exit code 2.

Thanks,



from mypy - erroring when there are no Python files

HoneyBee Hive View For android

Hello all can any one help me to create this view i am able to create this view static but i want this dynamic view , According to the data.Thanks

I have Try this but its seem not working like i want BeeHive View

Honey Bee Hive View



from HoneyBee Hive View For android

Filter data from zipped databases in python

I have a following problem. I have two large databases. The first database is called an_visit_ab. It is large and zipped as an_visit_ab.sql.bz2. The second database is large too, but I am able to store it on my computer as an_visit.db.

Structure of databases:

an_visit_ab is ordered by visit_id in ascending order:

visit_id    ab_test_id  variant
594817698   1   0
594817704   1   1
594817705   1   1
594817706   1   0
594817709   1   0

an_visit is ordered by visit_id in ascending order, too:

visit_id    datetime_add    is_bot
1   2017-06-21 18:10:38 0
3   2017-06-21 18:10:39 1

I need to filter out from an_visit_ab all visit_id where is_bot is 1 in an_visit. Normally, I would to a simple JOIN in SQL. But because I am not able to even unzip an_visit_ab.sql.bz2 I need a different strategy.

What I came with until now:

  1. I need to read an_visit_ab.sql.bz2 line by line. Because both databases are ordered by visit_id, I can look to the an_visit to a corresponding visit_id and check if is_bot is 1.
  2. I do it in python. I have a following code that reads an_visit_ab.sql.bz2 line by line:
from bz2 import BZ2File as bzopen

AN_VISIT_AB = "an_visit_ab.sql.bz2"

with bzopen(AN_VISIT_AB, "r") as bzfile:
    for i, line in enumerate(bzfile):
        print(line)

The output looks like this:

b'-- MySQL dump 10.13  Distrib 5.7.33, for Linux (x86_64)\n'
b'--\n'
b'-- Host: localhost    Database: XXX\n'
b'-- ------------------------------------------------------\n'
b'-- Server version\t5.7.33-0ubuntu0.16.04.1\n'
b'\n'
b'/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n'
b'/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n'
b'/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n'
b'/*!40101 SET NAMES utf8 */;\n'
b'/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;\n'
b"/*!40103 SET TIME_ZONE='+00:00' */;\n"
b'/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n'
b'/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n'
b"/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n"
b'/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;\n'
b'\n'
b'--\n'
b'-- Table structure for table `an_visit_ab`\n'
b'--\n'
b'\n'
b'DROP TABLE IF EXISTS `an_visit_ab`;\n'
b'/*!40101 SET @saved_cs_client     = @@character_set_client */;\n'
b'/*!40101 SET character_set_client = utf8 */;\n'
b'CREATE TABLE `an_visit_ab` (\n'
b'  `visit_id` int(11) unsigned NOT NULL,\n'
b'  `ab_test_id` int(10) unsigned NOT NULL,\n'
b'  `variant` tinyint(4) NOT NULL,\n'
b'  PRIMARY KEY (`visit_id`,`ab_test_id`,`variant`),\n'
b'  UNIQUE KEY `visit_id_ab_test_id` (`visit_id`,`ab_test_id`),\n'
b'  KEY `ab_test_id_ab_test_variant` (`ab_test_id`,`variant`),\n'
b'  KEY `ab_test_id` (`ab_test_id`),\n'
b'  CONSTRAINT `an_visit_ab_ibfk_1` FOREIGN KEY (`visit_id`) REFERENCES `an_visit` (`visit_id`),\n'
b'  CONSTRAINT `an_visit_ab_ibfk_4` FOREIGN KEY (`ab_test_id`, `variant`) REFERENCES `an_new_ab_test_variant` (`ab_test_id`, `variant`)\n'
b') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n'
b'/*!40101 SET character_set_client = @saved_cs_client */;\n'
b'\n'
b'--\n'
b'-- Dumping data for table `an_visit_ab`\n'
b'--\n'
b'\n'
b'LOCK TABLES `an_visit_ab` WRITE;\n'
b'/*!40000 ALTER TABLE `an_visit_ab` DISABLE KEYS */;\n'

(594878944,1,1),(594878945,1,0),(594878946,1,0),(594878947,1,1),(594878948,1,0),(594878949,1,1),(594878950,1,0),(594878951,1,0),(594878952,1,1),(594878953,1,1),(594878954,1,1),(594878955,1,1),(594878956,1,0),(594878957,1,1),(594878958,1,1),(594878959,1,1),(594878960,1,0),(594878961,1,0),(594878962,1,0),(594878963,1,1),(594878964,1,1),(594878965,1,0),(594878966,1,1),(594878967,1,0),(594878968,1,1),(594878969,1,1),(594878970,1,1),(594878971,1,0),(594878972,1,1),(594878973,1,0),(594878974,1,0),(594878975,1,1),(594878976,1,1),(594878977,1,0),(594878978,1,1),(594878979,1,1),(594878980,1,0),(594878981,1,1),(594878982,1,1),(594878983,1,0),(594878984,1,1),(594878985,1,1),(594878986,1,0),(594878987,1,1),(594878988,1,1),(594878989,1,0),(594878990,1,1),(594878991,1,0),(594878992,1,0),(594878993,1,1),(594878994,1,0),(594878995,1,1),(594878996,1,1),(594878997,1,1),(594878998,1,1),(594878999,1,0),(594879000,1,0),(594879001,1,0),(594879002,1,0),(594879003,1,0),(594879004,1,1),(594879005,1,1),(594879006,1,0),(594879007,1,1),(594879008,1,1),(594879009,1,1),(594879010,1,0),(594879011,1,1),(594879012,1,1),(594879013,1,0),(594879014,1,0),(594879015,1,0),(594879016,1,1),(594879017,1,0),(594879018,1,0),(594879019,1,1),(594879020,1,1),(594879021,1,1),(594879022,1,1),(594879023,1,0),(594879024,1,1),(594879025,1,0),(594879026,1,0),(594879027,1,1),(594879028,1,0),(594879029,1,1),(594879030,1,0),(594879031,1,1),(594879032,1,0),(594879033,1,1),(594879034,1,1),(594879035,1,0),(594879036,1,1),(594879037,1,1),(594879038,1,0),(594879039,1,1),(594879040,1,1),(594879041,1,1),(594879042,1,1),(594879043,1,0),(594879044,1,0),(594879045,1,0),(594879046,1,0),(594879047,1,1),(594879048,1,0),(594879049,1,1),(594879050,1,0),(594879051,1,1),(594879052,1,1),(594879053,1,1),(594879054,1,0),(594879055,1,1),(594879056,1,0),(594879057,1,0),(594879058,1,0),(594879059,1,0),(594879060,1,1),(594879061,1,1),(594879062,1,0),(594879063,1,0),(594879064,1,0),(594879065,1,1),(594879066,1,1),(594879067,1,0),(594879068,1,1),(594879069,1,0),(594879070,1,0),(594879071,1,0),(594879072,1,0),(594879073,1,0),(594879074,1,0),(594879075,1,0),(594879076,1,0),(594879077,1,0),(594879078,1,1),(594879079,1,1),(594879080,1,1),(594879081,1,1),(594879082,1,1),(594879083,1,0),(594879084,1,0),(594879085,1,0),(594879086,1,0),(594879087,1,1),(594879088,1,1),(594879089,1,0),(594879090,1,1),(594879091,1,0),(594879092,1,1),(594879093,1,0),(594879094,1,0),(594879095,1,0),(594879096,1,1),(594879097,1,1),(594879098,1,0),(594879099,1,1),(594879100,1,0),(594879101,1,1),(594879102,1,1),(594879103,1,0),(594879104,1,0),(594879105,1,1),(594879106,1,1),(594879107,1,0),(594879108,1,1),(594879109,1,1),(594879110,1,0),(594879111,1,1),(594879112,1,1),(594879113,1,0),(594879114,1,0),(594879115,1,1),(594879116,1,1),(594879117,1,1),(594879118,1,1),(594879119,1,0),(594879120,1,1),(594879121,1,1),(594879122,1,0),(594879123,1,1),(594879124,1,1),(594879125,1,0),(594879126,1,1),(594879127,1,1),(594879128,1,1),(594879129,1,1),(594879130,1,0),(594879131,1,1),(594879132,1,0),(594879133,1,0),(594879134,1,0),(594879135,1,1),(594879136,1,0),(594879137,1,0),(594879138,1,0),(594879139,1,1),(594879140,1,1),(594879141,1,0),(594879142,1,0),(594879143,1,1),(594879144,1,0),(594879145,1,0),(594879146,1,1),(594879147,1,0),(594879148,1,0),(594879149,1,1),(594879150,1,0),(594879151,1,0),(594879152,1,0),(594879153,1,1),(594879154,1,1),(594879155,1,1),(594879156,1,1),(594879157,1,1),(594879158,1,1),(594879159,1,1),(594879160,1,1),(594879161,1,0),(594879162,1,1),(594879163,1,1),(594879164,1,0),(594879165,1,0),(594879166,1,0),(594879167,1,1),(594879168,1,1),(594879169,1,1),(594879170,1,0),(594879171,1,0),(594879172,1,1),(594879173,1,0),(594879174,1,1),(594879175,1,1),(594879176,1,1),(594879177,1,0),(594879178,1,1),(594879179,1,1),(594879180,1,0),(594879181,1,1),(594879182,1,0),(594879183,1,1),(594879184,1,0),(594879185,1,0),(594879186,1,0),(594879187,1,1),(594879188,1,0),(594879189,1,0),(594879190,1,1),(594879191,1,0),(594879192,1,0),(594879193,1,1),(594879194,1,1),(594879195,1,1),(594879196,1,1),(594879197,1,1),(594879198,1,0),(594879199,1,1),(594879200,1,1),(594879201,1,0),(594879202,1,0),(594879203,1,0),(594879204,1,1),(594879205,1,1),(594879206,1,1),(594879207,1,0),(594879208,1,1),(594879209,1,1),(594879210,1,1),(594879211,1,0),(594879212,1,0),(594879213,1,0),(594879214,1,0),(594879215,1,0),(594879216,1,1),(594879217,1,1),(594879218,1,0),(594879219,1,1),(594879220,1,0),(594879221,1,1),(594879222,1,0),(594879223,1,0),(594879224,1,1),(594879225,1,1),(594879226,1,0),(594879227,1,0),(594879228,1,0),(594879229,1,1),(594879230,1,1),(594879231,1,1),(594879232,1,1),(594879233,1,1),(594879234,1,0),(594879235,1,0),(594879236,1,0),(594879237,1,1),(594879238,1,0),(594879239,1,0),(594879240,1,0),(594879241,1,1),(594879242,1,0),(594879243,1,0),(594879244,1,1),(594879245,1,0),(594879246,1,1),(594879247,1,0),(594879248,1,1),(594879249,1,1),(594879250,1,0),(594879251,1,0),(594879252,1,1),(594879253,1,0),(594879254,1,1),(594879255,1,0),(594879256,1,0),(594879257,1,1),(594879258,1,1),(594879259,1,1),(594879260,1,0),(594879261,1,1),(594879262,1,0),(594879263,1,0),(594879264,1,0);\n'

But I got stuck here and I don`t know how to continue. I would like to ask you:

  1. Is my strategy good? Or is there something better than reading it line by line?
  2. Can you show me, how can I filter is_bot from an_visit_ab.sql.bz2 as I have tried above?

Please, if there is something unclear in my question, do not downgrade immediately and give my chance to explain it more preciously :-). Thanks



from Filter data from zipped databases in python

Set Latex greek letter in plotting script using matplotlib

I have a plotting script where I load subtitles (variable subplot_titles) from a JSON file :

example of JSON file :

"subplot_titles" : {

    "0" : "Model: $~w_{0},~w_{a}~$ - flat - optimistic - No $\\gamma$",
    "1" : "Model: $~w_{0},~w_{a}~$ - flat - optimistic - With $\\gamma$",
    "2" : "Model: $~w_{0},~w_{a}~$ - flat - semi-pessimistic - No $\\gamma$",
    "3" : "Model: $~w_{0},~w_{a}~$ - flat - semi-pessimistic - With $\\gamma$"
},

In my script, I load this file like this :

 for i, ax in enumerate(np.ravel(axes)):

    config = load_config('./config.json')

    df = parse_input(config['subplot_files'][i])
    df = format_dataframe(df, config)
    title = config['subplot_titles'][i]
    lgd = plot_barchart(df, ax, title)
    bbea.append(lgd)

But once the figure is generated, I have an uggly symbol "gamma", like this :

bad gamma

I would like to display a Latex gamma symbol.

I tried to add r' in the plotting script to get Latex support :

title = config[r'subplot_titles'][i]

But I get an error.

Could anyone see what can I do to ge this gamma greek symbol under Latex displaying ?

UPDATE:

The solutions given works but I want to keep the matplotlib font for legend which appears under the form in jSON file :

"bars" : {

"0" : "$GC_{s}$",
"1" : "$GC_{ph} + WL$",
"2" : "$GC_{s} + GC_{ph} + WL$",
"3" : "$GC_{ph} + WL + XC$",
"4" : "$GC_{s} + (GC_{ph} + WL + XC)$",
"5" : "($GC_{s} + GC_{ph} + WL) + XC2$",
"6" : "$GC_{s} + (GC_{ph} + WL + XC) + XC2$"

},

that produces a nice legend :

wanted result

For the subplot_titles, I have just to replace a greek symbol by the Latex equivalent but caution, with the real Latex symbol \gamma, not the one which makes part of Latex of matplotlib like the uggly "\gamma" symbol I have shown above, and keep all the rest as it is currently.

I tried to make this subsitution :

title = title.replace("\\gamma", "+r\"\\mathit{\\gamma}")

but without success...

How to perform this rendering ?



from Set Latex greek letter in plotting script using matplotlib