Wednesday, May 25, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


python flask socketio not working - import failiture

Posted: 25 May 2022 12:33 PM PDT

I'm trying to use socketio inside my flaks app, but for some reason, it is not working. When I try to run my app with this module, I get the following error:

ModuleNotFoundError: No module named 'socketio.exceptions'

I tried to pip install flask and flask-socketio both from existing and new virtual environments, but it does not work...

Any ideas what is wrong? Python version 3.7

My code is following:

from flask import Flask, render_template  from flask_socketio import SocketIO, emit    app = Flask(__name__)  app.config['SECRET_KEY'] = 'secret!'  socketio = SocketIO(app)    @app.route('/')  def index():      return render_template('index.html')    @socketio.event  def my_event(message):      emit('my response', {'data': 'got it!'})    if __name__ == '__main__':      socketio.run(app)  

Update databricks job status through API

Posted: 25 May 2022 12:32 PM PDT

We need to execute a long running exe and thinking of ways to integrate with the Databricks. The plan is to integrate the exe as part of a task in the Databricks workflow.

We have come up with couple of approaches

  1. Create a DB table and enter a record when this particular task gets started in the workflow and run the batch file when a new record is inserted in that table. The batch file will ping the DB table every one minute. After it is completed, update the record and databricks will read the status from the table.

  2. Using databricks API, check whether the task has started execution in the console application and once console application is completed, update the task status to completion until then the job will run like while (true). But the current API doesn't support updating the task execution status (To Complete) (not 100% sure).

Please share thoughts OR alternate solutions.

Trying to Drop values by column (I convert these values to nan but could be anything) not working

Posted: 25 May 2022 12:32 PM PDT

Trying to drop NAs by column, given a certain threshold and I receive the error below.

I'm receiving the following error, but this should be working. Please advise.

enter image description here

reproducible example.

import pandas as pd  import dask    data = [['tom', 10], ['nick', 15], ['juli', 5]]      # Create the pandas DataFrame  df = pd.DataFrame(data, columns = ['Name', 'Age'])    import numpy as np  df = df.replace(5, np.nan)    ddf = dd.from_pandas(df, npartitions = 2)    ddf.dropna(axis='columns')     

Cannot RDP to SAGE 100 from International Location

Posted: 25 May 2022 12:32 PM PDT

We are developing a website that will use data from SAGE 100. In the U.S. I can RDP to the SAGE 100 server but if our offshore developers in India try they cannot. We've unblocked IP address etc. but they still can't access. The developers are building a website so need this access to test functionality. Is there a way to RDP in or is there another preferred method? We are using Magento Community CMS.

PS. I'm the project manager so do not have super technical knowledge so please explain in easy terms.

Thanks

What is the best way to add multiple React SPA's to a .NET 6.0 MVC web application/project

Posted: 25 May 2022 12:32 PM PDT

Trying to find the best modern solution to for our .NET 6.0 project. It needs to be able to handle multiple React SPA's and make use of the views / razer templates. Some of the solutions I have looked into had some manual steps I wasn't a fan of.

Fill value of a numeric with the entry of another row based on name

Posted: 25 May 2022 12:32 PM PDT

Good day, I have a dataframe that looks like this;

  Community Value   Num    <chr>     <dbl> <dbl>  1 A          3.54     3  2 A          4.56     3  3 A          2.22     3  4 B          0       NA  5 B          0.76    NA  6 C          1.2      5  

I am hoping to fill the Num observation of Community B with the Num observation of Community A while keeping the names as is.

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object referenc

Posted: 25 May 2022 12:33 PM PDT

When I want to chat with any user in my application, I get this error, what do you think is the reason?

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference          at com.hiddy.katana.user.ChatActivity$11.onDataChange(ChatActivity.java:441)  

My code

if (Objects.requireNonNull(modelChat).getReceiver().equals(myId) && modelChat.getSender().equals(hisUid)) {                          HashMap<String, Object> hashMap = new HashMap<>();                          hashMap.put("isSeen", true);                          snapshot.getRef().updateChildren(hashMap);  

Is it possible to create an protobuf object with type function in Python? If so how?

Posted: 25 May 2022 12:32 PM PDT

We have a db table where we keep payload and type of the messages that sent to pubsub for retry purposes. The problem I am having is, I don't have the reference of the object but I have the type of it as a string.

I am wondering if it is possible to use that type string to initialise that object and update its attributes depending what I have in the payload.

Our objects are generated protobufs coming from proto files.

What I want to do is something like this but I couldn't find a way to do it.

msg_type = "<class 'example.protobuf.pubsub.example.example_pb2.ExampleMessage'>"  payload = {"key": "value", "key2": "value"}    example_message = create_protobuf_object(msg_type)    # then update its values with payload (Which I can figure out by myself).    

How do get start_of_week(Monday) from dates in other column in dataframe

Posted: 25 May 2022 12:32 PM PDT

I need to get for each value, beginning of week (Monday). Here is dataframe that I haveenter image description here

And I want to get beginning of week purchase_date_x column to create new column with new column

I am not able to launch npx create react app. What do i do?

Posted: 25 May 2022 12:31 PM PDT

Your environment has been set up for using Node.js 18.2.0 (x64) and npm.

C:\Users\aanan>npx create-react-app my-app

Creating a new React app in C:\Users\aanan\my-app.

Installing packages. This might take a couple of minutes. Installing react, react-dom, and react-scripts with cra-template...

Aborting installation. Unexpected error. Please report it as a bug: Error: spawn UNKNOWN at ChildProcess.spawn (node:internal/child_process:413:11) at Object.spawn (node:child_process:689:9) at spawn (C:\Users\aanan\AppData\Local\npm-cache_npx\c67e74de0542c87c\node_modules\cross-spawn\index.js:12:24) at C:\Users\aanan\AppData\Local\npm-cache_npx\c67e74de0542c87c\node_modules\create-react-app\createReactApp.js:383:19 at new Promise () at install (C:\Users\aanan\AppData\Local\npm-cache_npx\c67e74de0542c87c\node_modules\create-react-app\createReactApp.js:334:10) at C:\Users\aanan\AppData\Local\npm-cache_npx\c67e74de0542c87c\node_modules\create-react-app\createReactApp.js:461:16 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { errno: -4094, code: 'UNKNOWN', syscall: 'spawn' }

Deleting generated file... package.json Deleting my-app/ from C:\Users\aanan Done.

C:\Users\aanan>

Why when i want to install npm this error apears?

Posted: 25 May 2022 12:32 PM PDT

Hi when i want to install the npm with 'npm install' i get this error below

npm ERR! code 1  npm ERR! path C:\Users\doran\Desktop\Petropolis-FE-develop1\node_modules\node-sass  npm ERR! command failed  npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node-gyp rebuild  npm ERR! gyp info it worked if it ends with ok  npm ERR! gyp info using node-gyp@3.8.0  npm ERR! gyp info using node@16.15.0 | win32 | x64  npm ERR! gyp ERR! configure error   npm ERR! gyp ERR! stack Error: Command failed: C:\Users\doran\AppData\Local\Programs\Python\Python310\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];  npm ERR! gyp ERR! stack   File "<string>", line 1  npm ERR! gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];  npm ERR! gyp ERR! stack                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  npm ERR! gyp ERR! stack SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?  npm ERR! gyp ERR! stack  npm ERR! gyp ERR! stack     at ChildProcess.exithandler (node:child_process:398:12)  npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:527:28)  npm ERR! gyp ERR! stack     at maybeClose (node:internal/child_process:1092:16)  npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:302:5)  npm ERR! gyp ERR! System Windows_NT 10.0.19043  npm ERR! gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\doran\\Desktop\\Petropolis-FE-develop1\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"  npm ERR! gyp ERR! cwd C:\Users\doran\Desktop\Petropolis-FE-develop1\node_modules\node-sass  npm ERR! gyp ERR! node -v v16.15.0  npm ERR! gyp ERR! node-gyp -v v3.8.0  npm ERR! gyp ERR! not ok    npm ERR! A complete log of this run can be found in:  npm ERR!     C:\Users\doran\AppData\Local\npm-cache\_logs\2022-05-25T18_50_11_980Z-debug-0.log  

I took the code project from a client and in my machine this error is displayed. I cant run the 'ng serve' it need the npm install.

But when i run npm install this error comes, where is the problem ?

How do I change the save location of an altered PDF using PyPDF2

Posted: 25 May 2022 12:32 PM PDT

I need to change the location that the output file is saved. Currently the save location is wherever the application is located. I would like to change it to the user's desktop.

Any help would be appreciated.

filename = askopenfilename()   packet.seek(0)  new_pdf = PdfFileReader(packet)  existing_pdf = PdfFileReader(open(filename, "rb"))  output = PdfFileWriter()  page = existing_pdf.getPage(0)  page.mergePage(new_pdf.getPage(0))  output.addPage(page)  name = (os.path.basename(filename))  name = name[:-4]  outputStream = open(name + "-CARB.pdf", "wb")  output.write(outputStream)  outputStream.close()  

Converting InputStream to JsonElement to fix ParserException [duplicate]

Posted: 25 May 2022 12:32 PM PDT

I am converting InputStream to JSonElement using following code. My question is, is there any simple way to convert InputStream to JSonElement. Without doing InputStream -> BufferedReader -> JsonParser -> parser.parser(bufferedReader).

  public jsonElement parsejsonContentFromStream (Inputstream in){      BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (in));      JsonParser parser = new JsonParser();      return parser.parse(bufferedReader);  }  

Swipe down update from Firebase in RecylerViewer

Posted: 25 May 2022 12:32 PM PDT

I am trying to make update of my RecyclerViewer with data from Storage for profile picture and Firestore for other data. But I tried many methods and I don't know how to make this. The goal is to make a RecyclerViewer update each time user goes to fragment and also be able to swipe to refresh the list. Also the layout gets inflated after second 'visit' on the Fragment, the first time it does not get inflated. Is this a problem with a Glide? And the cache keeps the data in RecyclerViewer even when new user is logged in with completely different data in Firebase.

fragment_item_list.xml

<?xml version="1.0" encoding="utf-8"?>  <androidx.swiperefreshlayout.widget.SwipeRefreshLayout      xmlns:android="http://schemas.android.com/apk/res/android"      android:id="@+id/swiperefresh"      android:layout_width="match_parent"      android:layout_height="match_parent">  <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      xmlns:tools="http://schemas.android.com/tools"      android:id="@+id/itemContainer"      android:layout_width="match_parent"      android:layout_height="match_parent"      tools:context=".FriendFragment">        <androidx.recyclerview.widget.RecyclerView          android:id="@+id/list"          android:name="com.msmmhm.hauimetyourmother.FriendFragment"          android:layout_width="match_parent"          android:layout_height="match_parent"          android:layout_marginLeft="16dp"          android:layout_marginRight="16dp"          app:layoutManager="LinearLayoutManager"          tools:context=".FriendFragment"          tools:listitem="@layout/fragment_item" />    </androidx.constraintlayout.widget.ConstraintLayout>    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>  

FriendFragment.kt

imports ...    class FriendFragment : Fragment() {        private lateinit var binding: FragmentItemListBinding      private lateinit var  mSwipeRefreshLayout: SwipeRefreshLayout        override fun onCreateView(          inflater: LayoutInflater, container: ViewGroup?,          savedInstanceState: Bundle?      ): View? {            binding = FragmentItemListBinding.inflate(inflater, container, false)            with(binding.list) {              layoutManager = LinearLayoutManager(context)              adapter = MyFriendRecyclerViewAdapter(Friend.ITEMS,container!!.context)                return binding.root            }        }    }  

MyFriendRecyclerViewAdapter.kt

imports ...    class MyFriendRecyclerViewAdapter(      private val values: List<FriendItem>,      val context: Context  ) : RecyclerView.Adapter<MyFriendRecyclerViewAdapter.ViewHolder>() {        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {            return ViewHolder(              FragmentItemBinding.inflate(                  LayoutInflater.from(parent.context),                  parent,                  false              )          )        }        override fun onBindViewHolder(holder: ViewHolder, position: Int) {          val item = values[position]          var events: CollectionReference = FirebaseFirestore.getInstance().collection("events")          val docRef = events.document(item.id)          Log.i(ContentValues.TAG,"EVENTS ITEM ID: "+item.id)          docRef.get()              .addOnSuccessListener { document ->                  if (document.exists())                  {                      Log.i(ContentValues.TAG,"DOCUMENT EXISTS")                      val map = document.data                      if (map!!.size != 0)                      {                          holder.activeIcon.setColorFilter(R.drawable.presence_online)                      }                      else                      {                          holder.activeIcon.setImageResource(R.drawable.presence_invisible)                      }                    }                  else                  {                      holder.activeIcon.setImageResource(R.drawable.presence_invisible)                  }              }          holder.friendNickname.text = item.friendName            loadWithGlide2(item.id,holder)        }          fun loadWithGlide2(id: String, holder: ViewHolder) {          val storageReference = Firebase.storage.reference.child("ProfilePictures/${id}.jpg")          Log.d(ContentValues.TAG, "NAME IS: ${storageReference.name}")            Glide.with(context)              .load(storageReference)              .error(R.drawable.defaultprofilepicture)              .into(holder.friendImg)      }          override fun getItemCount(): Int = values.size        inner class ViewHolder(binding: FragmentItemBinding) : RecyclerView.ViewHolder(binding.root) {          val friendImg: ImageView = binding.friendPicture          var friendNickname: TextView = binding.friendNickname          var activeIcon: ImageView = binding.activeIcon          val itemContainer: View = binding.root            override fun toString(): String {              return super.toString() + " '" + friendNickname.text + "'"          }      }    }  

How to select a parent element in tree and not lose child's 'selected' styles

Posted: 25 May 2022 12:32 PM PDT

I have a MUI TreeView component with a nested mapping of Categories (parent) and Articles (Child). When I select a child, that child has styles applied to it based on "selected". When I click a parent, the previous child loses its "selected" styles.

How can I make a differentiation between "child selected" and "parent clicked(selected)".

I would prefer to do this all in CSS if possible. This is a Next.js app.

My CategoryItem CSS:

const StyledCategoryItemRoot = styled(TreeItem)(({ theme }) => ({    [`& .${treeItemClasses.content}`]: {      fontWeight: theme.typography.fontWeightBold,      marginBottom: 5,      paddingLeft: 0,      borderRadius: theme.shape.borderRadius,      '&.Mui-selected.Mui-focused, &:hover, &.Mui-selected:hover': {        backgroundColor:          theme.palette.mode === 'light'            ? alpha('#ff9aff', 0.16)            : alpha('#2f506f', 0.24),      },      '&.Mui-selected, &.Mui-focused': {        backgroundColor: 'transparent',      },    },  }));  

My ArticleItem CSS:

const StyledArticleItemRoot = styled(TreeItem)(({ theme, router, post }) => ({    color:      theme.palette.mode === 'light'        ? theme.palette.grey[900]        : theme.palette.grey[500],    [`& .${treeItemClasses.content}`]: {      fontWeight: theme.typography.fontWeightBold,      paddingLeft: 0,      borderRadius: theme.shape.borderRadius,      transition: '.2s',      '&.Mui-selected:hover, &.Mui-selected.Mui-focused:hover, &:hover': {        color: theme.palette.mode === 'light' ? theme.palette.grey[800] : 'white',      },      '&.Mui-focused, &.Mui-selected, &.Mui-selected.Mui-focused': {        backgroundColor:          theme.palette.mode === 'light'            ? alpha('#ff9aff', 0.16)            : alpha('#2f506f', 0.16),        color:          post.attributes.slug !== router.query.slug            ? theme.palette.grey[500]            : theme.palette.mode === 'light'            ? theme.palette.primary.main            : theme.palette.secondary.main,      },    },  }));  

AWS - Dynamo Query Partition key List

Posted: 25 May 2022 12:31 PM PDT

I'm new to AWS. Can I query the dynamo data on the same table where the Partition key(docType) equals to AA or BB or CC etc? I don't see "OR" or "IN" clauses in keyConditionExpression. Is there any way to achieve this? I'm using node.js Thanks.

Filter a list based on values compared against a string

Posted: 25 May 2022 12:32 PM PDT

First off, this is my first question on here so if I do something wrong please let me know.

Ok, now to the problem. I am trying to search a list of words and remove any word that doesn't contain a set letter or letters in no particular order. I have tried using the in function as shown below. The list_to_clean shown here is the first few words of the list as an example, the list is really 15,000 values long.

list_to_clean = ['aalii', 'aargh', 'aaron', 'abaci', 'abada', 'abaft', 'abama', 'aband', 'abash', 'abate', 'abave', 'abbas', 'abbes', 'abbot', 'abdat', 'abeam', 'abear', 'abele', 'aberr', 'abhor', 'abidi', 'abyes', 'abime', 'abyss', 'abkar', 'abler', 'ablet', 'abm', 'aboma', 'abord', 'abort', 'about', 'abray', 'abram', 'abret', 'abrim']  cleanby = "ar"    def list_cleaner(cleanby:str, list_to_clean:list):  dict = list_to_clean  for letter in cleanby:      for word in dict:          if letter in word:              nothing = 1          else:              dict.remove(word)  return(dict)  

I have also tried using re.

def list_cleaner(cleanby:str, list_to_clean:list):  dict = list_to_clean  for letter in cleanby:      for word in dict:          if search(letter, word):              nothing = 1          else:              dict.remove(word)  return(dict)  

I don't know what the problem is but it works great for about the first 1000 or so words. Then, after a little while, it stops working and lets words thought that don't contain my "key" letters. I am sure there is a really simple reason for this but I am new to python and programming so really basic things stump me.

Thanks in advance for all of yalls help.

Firebase Emulator fails at startup Cannot find module --dns-result-order=ipv4first

Posted: 25 May 2022 12:32 PM PDT

Pulling my hair out here, bought a new mac m1 pro but can't get firebase working locally.

firebase emulators:start is failing when it gets to Emulator UI...

enter image description here

The stack trace from firebase-debug.log shows...

enter image description here

Looks like the error has something to do with line 84...

Starting Emulator UI with command {"binary":"node","args":["--dns-result-order=ipv4first"  

Which then throw an error in node as its unable to find a module called --dns-result-order=ipv4first

Any ideas?

Running Node 16 and Firebase 11.0.0

Prevent null values to being written in SQLite with PDO Php in Online Counter

Posted: 25 May 2022 12:32 PM PDT

I have a php script that counts how many users are online at any given time using php, sqlite and PDO. I using apache 2.4.53 and php 8.0.19 both at 64bit. The problem is that null values ​​are often written inside the database which cause the counter to increment unnecessarily and which are not canceled in any way, I have tried everything to eliminate the null values ​​that are written but I have not succeeded:

  $deleteNull = $db->prepare('DELETE FROM online WHERE last_activity IS NULL AND id IS NULL');    $deleteNull->execute();  

But is not working, I only found a trick that only counts the values ​​that are not null but obviously it is a hack because in the database these null values ​​are there and they remain there without being able to delete them:

$count = $db->query('SELECT COUNT() AS visitors FROM online WHERE last_activity IS NOT NULL AND id IS NOT NULL')->fetch(PDO::FETCH_ASSOC);  

In the screenshot you can see 2 columns and 3 rows, 2 rows are legit, the 3rd is fake since is null. The result is that counter counts 3 visitors instead of 2. This happens on Linux machines (CentOS).

Is there any way to modify the script to prevent these null values ​​from being written in database?

<?php    if (session_status() == PHP_SESSION_NONE) {      session_start();    }    $_SESSION['id'] = (isset($_SESSION['id'])) ? $_SESSION['id'] : uniqid();    $secondsToConsiderOffline = 60;    $hitonlinedb = "online.sqlite";    try {      if (!file_exists($hitonlinedb)) {        $db = new PDO("sqlite:" . $hitonlinedb);        $db->exec('CREATE TABLE online(id TEXT PRIMARY KEY NOT NULL, last_activity INTEGER)');      } else {        $db = new PDO("sqlite:" . $hitonlinedb);      }    }    catch (PDOException $e) {      die($e->getMessage());    }    $currentTime = time();    $gracePeriod = $currentTime - $secondsToConsiderOffline;    $id = $_SESSION['id'];    $delete = $db->prepare('DELETE FROM online WHERE last_activity < :gracePeriod OR id = :id');    $delete->bindValue(':gracePeriod', $gracePeriod, PDO::PARAM_INT);    $delete->bindValue(':id', $id, PDO::PARAM_STR);    $delete->execute();    $insert = $db->prepare('INSERT INTO online(id, last_activity) VALUES (:id, :currentTime)');    $insert->bindValue(':id', $id, PDO::PARAM_STR);    $insert->bindValue(':currentTime', $currentTime, PDO::PARAM_INT);    $insert->execute();    $count = $db->query('SELECT COUNT() AS visitors FROM online')->fetch(PDO::FETCH_ASSOC);    if ($count['visitors'] <= 1) {      $visitors = 1;    } else {      $visitors = $count['visitors'];    }    echo $visitors;    $db = null;  ?>  

download the database to see the bug: online.sqlite

SQlite where you can see null values inside table 1

SQlite where you can see null values inside table 2

I edited the script like below, is there a good chance the following version will work fine?

<?php    if (session_status() == PHP_SESSION_NONE) {      session_start();    }    $_SESSION['id'] = (isset($_SESSION['id'])) ? $_SESSION['id'] : uniqid();    $secondsToConsiderOffline = 60;    $hitonlinedb = "online.sqlite";    try {      if (!file_exists($hitonlinedb)) {        $db = new PDO("sqlite:" . $hitonlinedb);        $db->exec('CREATE TABLE online(id TEXT PRIMARY KEY NOT NULL, last_activity INTEGER NOT NULL)');      } else {        $db = new PDO("sqlite:" . $hitonlinedb);      }    }    catch (PDOException $e) {      die($e->getMessage());    }    $currentTime = time();    $gracePeriod = $currentTime - $secondsToConsiderOffline;    $id = $_SESSION['id'];    $delete = $db->prepare('DELETE FROM online WHERE (last_activity < :gracePeriod OR last_activity IS NULL) OR (id = :id OR id IS NULL)');    $delete->bindValue(':gracePeriod', ((is_null($gracePeriod) || empty($gracePeriod)) ? time() - 60 : $gracePeriod), PDO::PARAM_INT);    $delete->bindValue(':id', ((is_null($id) || empty($id)) ? uniqid() : $id), PDO::PARAM_STR);    $delete->execute();    $insert = $db->prepare('INSERT INTO online(id, last_activity) VALUES (:id, :currentTime)');    $insert->bindValue(':id', ((is_null($id) || empty($id)) ? uniqid() : $id), PDO::PARAM_STR);    $insert->bindValue(':currentTime', ((is_null($currentTime) || empty($currentTime)) ? time() : $currentTime), PDO::PARAM_INT);    $insert->execute();    $count = $db->query('SELECT COUNT() AS visitors FROM online')->fetch(PDO::FETCH_ASSOC);    if ($count['visitors'] <= 1) {      $visitors = 1;    } else {      $visitors = $count['visitors'];    }    echo $visitors;    $db = null;  ?>  

"pyautogui" doesn't respond

Posted: 25 May 2022 12:32 PM PDT

I wrote a small code with python. But this part of the code doesn't work when game focused on and it doesnt respond back.

pyautogui.moveRel(-2, 4)

Also this part works when my cursor appear in menu or etc. too. But when i switched into game (when my cursor disappear and crosshair appeared) it doesn't work (doesn't matter fullscreen or else). These type of keyboard commands are in my code also but they works fine.

keyboard.is_pressed('Alt')

It's about mouse or pyautogui ?.. How can i make mouse moves correct ?

browseVignettes not returning anything for ggplot2 package in R - No error message

Posted: 25 May 2022 12:32 PM PDT

I'm very new to R and recently installed R-studio. I'm trying to familiarize myself with packages by using browseVignettes() but it isn't returning anything for the package ggplot2, which I know contains vignettes from a tutorial video.

When I try using browseVignettes with certain packages in the system library, I receive an error message, e.g.:

> browseVignettes("stats")  No vignettes found by browseVignettes("stats")  

By contrast, I receive no error message when attempting to access the vignettes of ggplot2.

My theory is that I installed the package incorrectly. When I went through the installation, I received the below message.

> install.packages("ggplot2")  Installing package into 'C:/Users/micha/Documents/R/win-library/4.0'  (as 'lib' is unspecified)  trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/ggplot2_3.3.0.zip'  Content type 'application/zip' length 4015425 bytes (3.8 MB)  downloaded 3.8 MB    package 'ggplot2' successfully unpacked and MD5 sums checked    The downloaded binary packages are in      C:\Users\micha\AppData\Local\Temp\RtmpyYnCz3\downloaded_packages  

Any assistance would be much appreciated, as I am hoping to be able to review these vignettes and avoid this error repeating itself next time I install a package from CRAN.

Expo Google-Sign-In DEVELOPER_ERROR

Posted: 25 May 2022 12:31 PM PDT

I developed a React Native app, and I am using Expo Google-Sign-In for my Firebase authentication. I receive the error "DEVELOPER_ERROR" when I attempt authentication on my standalone APK on Android.

Initially, I was using "Expo Google", however that is now deprecated and my sign-in button did not do anything on my standalone APK. With Expo Google method, I found that I had to set the androidStandaloneAppClientId. Even after that, the sign-in got stuck at the Google homepage after authentication. I tried the solution of using a custom redirect URI, as in

redirectUrl: ${AppAuth.OAuthRedirect}:/oauth2redirect/google

but that resulted in another error: redirect_uri mismatch.

I switched to the Expo Google-Sign-In library instead, and that is giving me a DEVELOPER_ERROR every time I try to authenticate.

After that, I have tried:

  • downloading the google-services.json and using it in my app
  • setting the SHA1 fingerprint in google-services.json and in Firebase
  • setting the certificateHash inside android.configuration.certificate hash inside my app.json to my SHA1 fingerprint.
  • checking and making sure package names are set properly

I tried anything else I may have failed to mention from the existing threads involving DEVELOPER_ERROR in Expo Google-Sign-In.

The variables I mention in my code below are from the following:

SHA1 was generated and used to create my credential, and is the fingerprint used in my OAuth Android Client ID.

The client ID I reference throughout my files is the ID of my OAuth Web client ID. However, I also tried using the Android one and that did not change anything.

"CurrentKey" in api_key is the API key from my Firebase project.

This is a link to my Google Credentials page.

https://imgur.com/a/u8cPxQl

/* My app.json: */

{    "expo": {      "name": "AssistiveNote",      "privacy": "public",      "description": "A note app for people who have trouble reading text.",      "slug": "assistivenote",        "sdkVersion": "33.0.0",      "version": "2.0.0",      "orientation": "portrait",      "icon": "./screens/images/icon.png",          "ios": {        "bundleIdentifier": "com.danyalbabar.assistivenote"      },        "android": {        "versionCode": 2,        "package": "com.danyalbabar.assistivenote",        "googleServicesFile": "./google-services.json",        "permissions": [ " " ],        "config": {          "googleSignIn": {              "certificateHash": "XXXX"          }        }      }      }  }  

My google-services.json:

  {    "project_info": {      "project_number": "XXXX",      "firebase_url": "https://era-gvision.firebaseio.com",      "project_id": "era-gvision",      "storage_bucket": "era-gvision.appspot.com"    },    "client": [      {        "client_info": {          "mobilesdk_app_id": "XXXX",          "android_client_info": {            "package_name": "com.danyalbabar.assistivenote"          }        },        "oauth_client": [          {            "client_id": "XXXX",            "client_type": 3          }        ],        "api_key": [          {            "current_key": "XXXX"          }        ],        "services": {          "appinvite_service": {            "other_platform_oauth_client": [              {                "client_id": "XXXX",                "client_type": 3              }            ]          }        }      }    ],    "configuration_version": "1"  }  

How do I create an SSH key in Terraform?

Posted: 25 May 2022 12:31 PM PDT

I need to spin up a bunch of EC2 boxes for different users. Each user should be sandboxed from all the others, so each EC2 box needs its own SSH key.

What's the best way to accomplish this in Terraform?

Almost all of the instructions I've found want me to manually create an SSH key and paste it into a terraform script.

(Bad) Examples:

Since I need to programmatically generate unique keys for many users, this is impractical.

This doesn't seem like a difficult use case, but I can't find docs on it anywhere.

At a pinch, I could generate Terraform scripts and inject SSH keys on the fly using Bash. But that seems like exactly the kind of thing that Terraform is supposed to do in the first place.

Mongodb order & fetch records by the array of ids specified

Posted: 25 May 2022 12:32 PM PDT

Hi I am looking for solution. I am not sure if this question is already here in stackoverflow. I was trying to find its solution on google but couldn't find any solution. I need to fetch records from mongo database such that it should be ordered by the array of ids I specify only. For example following is the set of data from the required table.

{ "_id" : NumberLong("5832686213760"), "created_by" : "3694181860160", "title" : "adsf", "date" : "2015-10-12 21:57:27", "cat" : "251", "description" : "dsafadsf", "members" : [ "3694181860160" ], "battles" : [ ], "is_deleted" : NumberLong(0) }    { "_id" : NumberLong("5836854817600"), "created_by" : "3692778550272", "title" : "dd", "date" : "2015-10-13 02:13:32", "cat" : "939", "description" : "dddd", "members" : [ "3692778550272", "3690476217152" ], "battles" : [ "1475499726016" ], "is_deleted" : NumberLong(0) }    { "_id" : NumberLong("5830033945536"), "created_by" : "3692705624256", "title" : "My own group", "date" : "2015-10-11 11:50:27", "cat" : "731", "description" : "yes this is my own group. hahahhahah", "members" : [ "3692705624256" ], "battles" : [ "1478264481792", "1472313521152", "1478428020992" ], "is_deleted" : NumberLong(0) }  

If I need to fetch the above data in the order as following array specify.

array("5830033945536","5832686213760", "5836854817600")  

Please note that this is only a part of data and ids, the real query will be dynamic. I am working in Yii 1.x. So I need the solution in json as well as in php.

How to run multiple jobs in one Sparkcontext from separate threads in PySpark?

Posted: 25 May 2022 12:32 PM PDT

It is understood from Spark documentation about Scheduling Within an Application:

Inside a given Spark application (SparkContext instance), multiple parallel jobs can run simultaneously if they were submitted from separate threads. By "job", in this section, we mean a Spark action (e.g. save, collect) and any tasks that need to run to evaluate that action. Spark's scheduler is fully thread-safe and supports this use case to enable applications that serve multiple requests (e.g. queries for multiple users)."

I could found few example code of the same in Scala and Java. Can somebody give an example of how this can be implemented using PySpark?

Highmaps tooltips in drilldowned map of Slovakia

Posted: 25 May 2022 12:31 PM PDT

I would like implemented names of town (Trencin, Nemsova, Ilava... ) and their tooltips together. Click on green TN block in map and check it.

I try some solutions, but:

  1. tooltip overllaps names of towns:

     useHTML: true,      

http://jsfiddle.net/jezrael/grzwuL9g/5/ (line 47)

  1. three names of towns are missing:

     useHTML: false //(default),  

http://jsfiddle.net/jezrael/grzwuL9g/4/ (line 47)

  1. give tooltip out of map, but impossible:

     positioner: function () {       return { x: 0, y: 250 };   },  

http://jsfiddle.net/LyUxF/
http://jsfiddle.net/j92p2/ in chart
http://jsfiddle.net/jezrael/grzwuL9g/5/ (line 55)

  1. giving name of town with connectors out of map:
    http://www.highcharts.com/maps/demo/us-data-labels
    http://jsfiddle.net/highcharts/9Fk3a/5/
    I cant do it.

Ruby on Rails inflections not working with underscore character "_"

Posted: 25 May 2022 12:32 PM PDT

I'm developing an application in Portuguese, and I have the class ContaPagar (which translates to Accounts Payable in English), which generates the conta_pagar relation by default.

I want to create a plural for that, so that I can use it on a has_many relationship. The plural should be on the word "Conta" (Account), so it should be contas_pagar, however I tried that and it didn't work:

inflections.rb      inflect.irregular 'conta_pagar', 'contas_pagar'    class FaturaPagar < ActiveRecord::Base        ...      has_many :contas_pagar  end  

.

NoMethodError: undefined method 'contas_pagar' for #< FaturaPagar:0x007f39604ddf50>  

It only works when I declare it on singular:

class FaturaPagar < ActiveRecord::Base        ...      has_many :conta_pagar  end  

However I know the inflection is working when I try it on the console:

irb(main):018:0> "conta_pagar".pluralize  => "contas_pagar"  irb(main):019:0> "contas_pagar".singularize  => "conta_pagar"  

Am I doing something wrong or is this a limitation?

Undefined local variable or method new_ composed spanish model name in rails

Posted: 25 May 2022 12:32 PM PDT

I'm working with RoR with a legacy database in spanish language. I have the table and registropersona and model RegistroPersona and RegistrosPersonasController.

When RegistrosPersonasController/index is rendered I get the error

undefined local variable or method new_registro_persona_path for #<#Class:0xb5d2296c>:0xa5f82a0>

Here is my code:

registro_persona.rb

class RegistroPersona < ActiveRecord::Base    self.table_name = "registrospersonas"  end  

registros_personas_controller.rb

class RegistrosPersonasController < ApplicationController    before_action :set_registro_persona, only: [:show, :edit, :update, :destroy]    def index      @registros_personas = RegistroPersona.all    end  end  

inflections.rb

ActiveSupport::Inflector.inflections do |inflect|    inflect.irregular 'registro_persona', 'registros_personas'  end  

This is the output from command rake routes | grep registro_persona

 new_registro_persona GET    /registros_personas/new(.:format)      registros_personas#new  edit_registro_persona GET    /registros_personas/:id/edit(.:format) registros_personas#edit       registro_persona GET    /registros_personas/:id(.:format)      registros_personas#show  

What I'm doing wrong?

Unbinding events on scrollout - recommended?

Posted: 25 May 2022 12:32 PM PDT

My site is built on Backbone. It has a feed based UI, which means there are often a large amount of content displayed in a feed. Roughly, about 30 events bind to each item.

It gets sluggish after scrolling down a couple of pages.

Does it make sense to unbind the items that has been scrolled out, and bind again when they are scrolled in?

What might be causing the slowness?

Symmetric matrices in numpy?

Posted: 25 May 2022 12:32 PM PDT

I wish to initiate a symmetric matrix in python and populate it with zeros.

At the moment, I have initiated an array of known dimensions but this is unsuitable for subsequent input into R as a distance matrix.

Are there any 'simple' methods in numpy to create a symmetric matrix?

Edit

I should clarify - creating the 'symmetric' matrix is fine. However I am interested in only generating the lower triangular form, ie.,

ar = numpy.zeros((3, 3))    array([[ 0.,  0.,  0.],         [ 0.,  0.,  0.],         [ 0.,  0.,  0.]])  

I want:

array([[ 0],         [ 0, 0 ],         [ 0.,  0.,  0.]])  

Is this possible?

No comments:

Post a Comment