Saturday, 31 October 2020

FCM notification "click_action" not working

I'm using a Cloud Function and sending push notifications with it. Sending notification works as expected but click_action attribute not working. When I click the notification nothing happens. Here is my code:

My notification payload:

const payload = {
  notification: {
      title: 'Soru Çözüm',
      body: 'Attığınz soruya bir yorum geldi: ' + data.content,
      icon: 'ic_stat_logo',
      click_action: '.activities.SoruDetayActivity'
  },
  data: {
      title: 'Soru Çözüm',
      content: 'Sorunuz çözüldü.',
      post: data.parent
  }
};

Intent Filter:

<activity
    android:name=".activities.SoruDetayActivity"
    android:label="Soru"
    android:windowSoftInputMode="adjustResize">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <action android:name=".activities.SoruDetayActivity"/>

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data
            android:host="www.website.com"
            android:scheme="https" />
    </intent-filter>
</activity>


from FCM notification "click_action" not working

Is there a way to get data from sensors from command line?

In Android, I know it's possible to use Runtime.getRuntime().exec(...) to execute native command line on android system like echo or ls. I wonder if is there is any way to get data from any sensor module (like photo or gps) not from Android API (through Java or Kotlin), but by executing a command line with Runtime.getRuntime().exec(...). Is there a way to do it?



from Is there a way to get data from sensors from command line?

Postman not reaching AWS EKS API endpoint

I'm trying to figure out how to get postman to work with EKS. I have a simple nodejs app

const express = require('express');
const app = express();


app.get('/', (req, res) => res.send('hello world'));

app.listen(3000, () => {
    console.log('My REST API running on port 3000!');
});

I created a docker container and successfully pushed it to ECR. Also I tested docker by running it locally and I was able to reach it and get hello world response so the docker container seems fine.

I created an EKS cluster with the docker container and have the api server endpoint

enter image description here

but when I try and make a call with postman, I get

enter image description here

I even tried adding access key and secret from IAM user that has access to EKS, but I get same error.

When I configured the cluster, I set it to public so I don't understand why Postman can't reach the API endpoint. enter image description here

Also I added the following permissions to the IAM user I'm using in postman. I wasn't sure which one was correct so I added all of them. I also put the security credentials for that IAM user in postman.

enter image description here

What am I missing? I appreciate the help!



from Postman not reaching AWS EKS API endpoint

Group values if a date condition is respected in pandas

I have this pandas dataframe

import pandas as pd    
d1 = pd.DataFrame({
    'date' : ['2020-08-01', '2020-08-03', '2020-08-07', 
              '2020-08-02', '2020-08-04', '2020-08-10'],
    'user_id' : ['u123', 'u123', 'u123', 
                 'u321', 'u321', 'u321'],
    'item_id' : ['i1', 'i2', 'i3',
                 'i3', 'i1', 'i2' ],
    'like' : [1, 1, 0, 
             0, 1, 0]
})

Original_df

My goal is to get to a dataframe like this

Desired_df

For each row, I want 3 new columns:

  1. List of all previously liked items (like == 1 and date of previously liked items for that user < current date of the row)
  2. List of all previously disliked items (like == 0 and date of previously disliked items for that user < current date of the row)
  3. Mean of the column 'like' for all previous interactions (date of previous interactions < current date of the row)

More infos :

  • My complete dataframe is very big so I'm looking for an efficient way to do this in term of memory and computational costs
  • The data is already ordered by date and by user_id
  • I have no problem using other librairies than pandas
  • I have access to a multithreaded cpu and to a GPU

Here's a non-efficient code to achieve what I'm trying to do. Do you have suggestions on how I can improve this ?

import pandas as pd
d1 = pd.DataFrame({
    'date' : ['2020-08-01', '2020-08-03', '2020-08-07', 
              '2020-08-02', '2020-08-04', '2020-08-10'],
    'user_id' : ['u123', 'u123', 'u123', 
                 'u321', 'u321', 'u321'],
    'item_id' : ['i1', 'i2', 'i3',
                 'i3', 'i1', 'i2' ],
    'like' : [1, 1, 0, 
             0, 1, 0]
})

d1['previously_liked_item_ids'] = ""
d1['previously_disliked_item_ids'] = ""
d1['previous_like_avg'] = ""

for index, row in d1.iterrows():
    d1_u = d1[(d1.user_id == row['user_id']) & (d1.date < row['date'])]
    d1.at[index, 'previously_liked_item_ids'] = d1_u[d1_u.like == 1].item_id,
    d1.at[index, 'previously_disliked_item_ids'] = d1_u[d1_u.like == 0].item_id,
    d1.at[index, 'previous_like_avg'] = d1_u.like.mean()
print(d1)


from Group values if a date condition is respected in pandas

Django & Geopy : calcul distance btwn fixed position (post) and moving position (user.userprofile) position

I am looking for how to define a distance between two points. The first one is related to the post itself and does not change. It indicates the position of the post. The second would be linked to the user's position.

The problem is that nothing is displayed. Do you have an idea?

Thanks a lot for your help,


FIRST TRY :

user/models.py

    class UserProfile(models.Model):
        ...
        latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0')
        longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0')
post/models.py

class Cuisine(models.Model):
     ...
     latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0')
     longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0')

     def distance_post(self, request):
        post_situation = (self.longitude, self.latitude)
        user_situation = (self.request.user.userprofile.longitude, self.request.user.userprofile.latitude)
        
        return geodesic(post_situation, user_situation).km

SECOND TRY:

@register.inclusion_tag('index.html')
def distance_post(request):
    post_situation = (request.GET['longitude'], request.GET['latitude'])
    user_situation = (self.request.user.userprofile.longitude, self.request.user.userprofile.latitude)
    distance = geodesic(post_situation, user_situation).km
    
    return {'distance': distance}  

But nothing works, do you have any idea?

Here is where I'd like to to use distance

post/views.py :

def Homemainpage(request):
    post = Cuisine.objects.filter(status=0).order_by('-publishing_date').all()
    
    paginator = Paginator(post, 3)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    listaliments = ListAliments.objects.filter(status=1).all()
    typerepas = Typerepas.objects.filter(status=1).all()
    sperepas = Sperepas.objects.filter(status=1).all()
    
    return render(request, 'index.html', {
        'post': post,
        'listaliments': listaliments,
        'typerepas': typerepas,
        'sperepas': sperepas,
        'page_obj': page_obj,
    })

Another idea will be to create something like a pattern to use in a template:

And to load directly the longitude and latitude into template for calculation. Does anyone has an idea about that?



from Django & Geopy : calcul distance btwn fixed position (post) and moving position (user.userprofile) position

Infrared not returning 1 as correct value

I am trying to create a glove that when you turn your wrist down it sends 1 as an IR signal and if you turn your wrist up it returns a 0 for the glove I used javascript:

input.onGesture(Gesture.TiltDown, function () {
music.playMelody("E B C5 A B G A F ", 262)
network.infraredSendNumber(1)
light.showRing(
    `blue red blue red blue blue red blue red blue`)
})
input.onGesture(Gesture.TiltUp, function () {
    music.wawawawaa.play()
    network.infraredSendNumber(0)
    light.showAnimation(light.cometAnimation, 500)
})

I don't believe there is a problem there but when I go to my arduino to pick up the IR signal and print the value in the Serial it prints as 4E5CE275On even though I told the Serial to print in Hex form so it should be 0x1. I thought maybe I just don't understand how that works so I tried sending 0 and I got the same result. I do not know what is going wrong. here is my code:

#include <FastLED.h>
#include <IRremote.h> 

#define NUM_LEDS 150

#define DATA_PIN 5
#define CLOCK_PIN 13
int IRpin = 7;
IRrecv irrecv(IRpin);
decode_results results;

CRGB leds[NUM_LEDS];
boolean LEDon = false;

void setup() { 
  Serial.begin(9600);
  irrecv.enableIRIn();
  irrecv.blink13(true);
  Serial.println("resetting");
  LEDS.addLeds<WS2812,DATA_PIN,RGB>(leds,NUM_LEDS);
  LEDS.setBrightness(84);
}

void fadeall() { for(int i = 0; i < NUM_LEDS; i++) { leds[i].nscale8(250); } }

void loop() { 
    if (irrecv.decode(&results))
    {
  
      while((LEDon) == false)  
      {
          Serial.print(results.value, HEX);   
          Serial.print("On");
          static uint8_t hue = 0;
          Serial.print("x");
          // First slide the led in one direction
          for(int i = 0; i < NUM_LEDS; i++) {
            // Set the i'th led to red 
            leds[i] = CHSV(hue++, 255, 255);
            // Show the leds
            FastLED.show(); 
            // now that we've shown the leds, reset the i'th led to black
            // leds[i] = CRGB::Black;
            fadeall();
            // Wait a little bit before we loop around and do it again
            delay(10);
          }
          Serial.print("x");
        
          // Now go in the other direction.  
          for(int i = (NUM_LEDS)-1; i >= 0; i--) {
            // Set the i'th led to red 
            leds[i] = CHSV(hue++, 255, 255);
            // Show the leds
            FastLED.show();
            // now that we've shown the leds, reset the i'th led to black
            // leds[i] = CRGB::Black;
            fadeall();
            // Wait a little bit before we loop around and do it again
            delay(10);
          }
         
  }
    }
}

The code is reading for a signal and if signal is present the leds start running but later on I want to use while(results.value) == 0) the LEDS run.



from Infrared not returning 1 as correct value

Flask wtforms ValidationError not displayed to user

I'm using flask wtforms with input validation. Everything's working fine, except with validation failure my ValidationError message is not getting displayed to the user...

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField, ValidationError # URLField, EmailField
from wtforms.validators import DataRequired, Email, EqualTo

class SignupForm(FlaskForm):
    name = StringField("Name:", validators=[DataRequired()])
    email = StringField("Email:", validators=[DataRequired(), Email()])
    password = PasswordField("Password:", validators=[DataRequired(), EqualTo('pass_confirm', message='Passwords must match')])
    pass_confirm = PasswordField("Confirm:", validators=[DataRequired()])
    submit = SubmitField("Create Account")

    def validate_email(self, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError('Your email has already been registered.')

    def validate_name(self, field):
        if User.query.filter_by(name=field.data).first():
            raise ValidationError('This username is taken.')

and in my view:

@users.route('/signup', methods=['GET','POST'])
def signup():
    form = SignupForm()

    if form.validate_on_submit():
        url = form.name.data # todo: generate unique url
        user = User(name=form.name.data,
                    url=url,
                    email = form.email.data,
                    password = form.password.data)
        db.session.add(user)
        db.session.commit()

        return redirect(url_for('users.login'))

    return render_template('signup.html', form=form)

and this is the template:

<div class="jumbotron">
  <h1>Sign up Page</h1>
  <p>Please fill out the form</p>
  <form method="POST">
    
    <div class="form-group">
      
      
    </div>

    <div class="form-group">
      
      
    </div>

    <div class="form-group">
      
      
    </div>

    <div class="form-group">
      
      
    </div>

      
  </form>

</div>

Upon submitting an invalid form (either invalid email or name) the form simply returns blank, without indicating what the user did wrong. How can I display those validationerrors to the user? Much appreciated!



from Flask wtforms ValidationError not displayed to user

No exact matches in call to intializer

I have recently shifted to Xcode 12 and start getting error which is not there in the Xcode 11. The Error is related to an Extension which says No exact matches in call to intializer Below is the code -

public typealias UpdateBlock<T> = (_ object: T?) -> Void

protocol ModelMappeable {
    func map(_ values: JSON, realm: Realm?)
}

extension ModelMappeable where Self: BaseModel {
    
    static func getOrCreate(realm: Realm, values: JSON?, updates: UpdateBlock<Self>?) -> Self {
        var object: Self!
        
        if let primaryKey = values?["_id"].string {
            if let newObject = realm.object(ofType: Self.self, forPrimaryKey: primaryKey as AnyObject) {
                object = newObject
            }
        }

        if object == nil {
            object = self()
        }

        if let values = values {
            object.map(values, realm: realm)
        }

        updates?(object)
        return object
    }

}

enter image description here

enter image description here



from No exact matches in call to intializer

How to configure AWS CDK Account and Region to look up a VPC

I am learning the AWS CDK, and this is a problem I can't seem to figure out. JS/Node are not languages I use often, so if there is some obvious native thing that I am missing, please don't be too harsh. I'm trying to deploy a container to an existing VPC / new ECS Cluster. The following code isn't my whole script but is an important part. Hopefully, it gives the idea of what I'm trying to do.

//import everything first

stack_name = "frontend";

class Frontend extends core.Stack {
constructor(scope, id, props = {}) {
    super(scope, id);

    console.log("env variable " + JSON.stringify(props));
    
    const base_platform = new BasePlatform(this, id, props);

    //this bit doesn't matter, I'm just showing the functions I'm calling to set everything up

    const fargate_load_balanced_service = ecs_patterns.ApplicationLoadBalancedFargateService();
    this.fargate_load_balanced_service.taskDefinition.addToTaskRolePolicy();
    this.fargate_load_balanced_service.service.connections.allowTo();
    const autoscale = this.fargate_load_balanced_service.service.autoScaleTaskCount({});
    this.autoscale.scale_on_cpu_utilization();
    }
}

class BasePlatform extends core.Construct {
constructor(scope, id, props = {}) {
    super(scope, id);
    this.environment_name="frontend";
    
    console.log("environment variables " + JSON.stringify(process.env));

    //This bit is my problem child

    const vpc = ec2.Vpc.fromLookup(
        this, "VPC",{
        vpcId: 'vpc-##########'
    });

    //this bit doesn't matter, I'm just showing the functions I'm calling to set everything up

    const sd_namespace = service_discovery.PrivateDnsNamespace.from_private_dns_namespace_attributes();
    const ecs_cluster = ecs.Cluster.from_cluster_attributes();
    const services_sec_grp = ec2.SecurityGroup.from_security_group_id();
    }
}

const app = new core.App();

_env = {account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION };

new Frontend(app, stack_name, {env: _env});

app.synth();

When I run CDK synth, it spits out:

Error: Cannot retrieve the value from context provider vpc-provider since the account/region is not specified at the stack level. Either configure "env" with explicit account and region when you define your stack or use the environment variables "CDK_DEFAULT_ACCOUNT" and "CDK_DEFAULT_REGION" to inherit environment information from the CLI (not recommended for production stacks)

But I don't know why. My usage here fits several other Stackoverflow answers to similar questions, it loos like the examples in the AWS docs, and when I console.log(process.env), it spits out the correct/expected values of CDK_DEFAULT_REGION and CDK_DEFAULT_ACCOUNT. When I log "env" it spits out the expected values as well.

So my question is, how do I configure my environment so ec2.Vpc.fromLookup knows my account info, or how do I pass the values properly to "env"?



from How to configure AWS CDK Account and Region to look up a VPC

Elastich search - ICU Collation Keyword Field - Norwegian language - aa elastich search consider as å when sorting

I am using elastic search elasticsearch:6.8.4 on fos in Symfony 4.4 by friendsofsymfony/elastica-bundle": "^5.0"

I am facing an issue with sort field with config in fos_elastica.yaml. My config like:

 user_first_name_sort: {type: icu_collation_keyword, language: nb, index: true}

This work fine for Norwegian language as expected. But, word aa elastich search consider as å when sorting. Example: enter image description here

How can i ignore implictly transfer?



from Elastich search - ICU Collation Keyword Field - Norwegian language - aa elastich search consider as å when sorting

CRITICAL WORKER TIMEOUT on gunicorn when deployed to AWS

I have a flask web-app that uses a gunicorn server and I have used the gevent worker class as that previously helped me not get [CRITICAL] WORKER TIMEOUT issues before but since I have deployed it on to AWS behind an ELB, I seem to be getting this issue again.

I have tried eventlet worker class before and that didn't work but gevent did locally

This is the shell script that I have used as an entrypoint for my Dockerfile:

gunicorn -b 0.0.0.0:5000 --worker-class=gevent --worker-connections 1000 --timeout 60 --keep-alive 20 dataclone_controller:app

When i check the logs on the pods, this is the only information that gets printed out:

[2019-09-04 11:36:12 +0000] [8] [INFO] Starting gunicorn 19.9.0
   [2019-09-04 11:36:12 +0000] [8] [INFO] Listening at: 
   http://0.0.0.0:5000 (8)
   [2019-09-04 11:36:12 +0000] [8] [INFO] Using worker: gevent
   [2019-09-04 11:36:12 +0000] [11] [INFO] Booting worker with pid: 11
   [2019-09-04 11:38:15 +0000] [8] [CRITICAL] WORKER TIMEOUT (pid:11)


from CRITICAL WORKER TIMEOUT on gunicorn when deployed to AWS

Error while using VueI18n plugin in vue - Cannot set property '_vm' of undefined

I've just started working with Vue.js and learning it through some online code snippet and tutorials. I'm trying to implement internationalization support for my vue project, but I'm getting error in web-console.

Here are my code snippets

main.js

import { createApp } from 'vue';
import App from './App.vue';
import VueI18n from 'vue-i18n'
import router from './router/index'

function loadLocaleMessages () {
    const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
    const messages = {}
    locales.keys().forEach(key => {
        const matched = key.match(/([A-Za-z0-9-_]+)\./i)
        if (matched && matched.length > 1) {
            const locale = matched[1]
            messages[locale] = locales(key)
        }
    })
   return messages
}

const i18n = VueI18n({
    locale: process.env.VUE_APP_I18N_LOCALE || 'en',
    fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
    messages: loadLocaleMessages()
})


const app = createApp(App);
app.use(router);
app.use(i18n);
app.mount('#app');

Here is my HelliI18n.vue file where I want to use translation

<template>
    hello
    <p></p>
</template>

<script>
    export default {
        name: 'HelloI18n'
    }
</script>

Following code is from my package.json file (for versions)

"dependencies": {
    "core-js": "^3.6.5",
    "vue": "^3.0.0",
    "vue-i18n": "^8.22.1",
    "vue-router": "^4.0.0-0"
},
"devDependencies": {
    "@intlify/vue-i18n-loader": "^1.0.0",
    "@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.7.2",
    "eslint-plugin-vue": "^7.0.0-0",
    "vue-cli-plugin-i18n": "~1.0.1"
},

When I run my project, I see following error on web console

Uncaught TypeError: Cannot set property '_vm' of undefined
at VueI18n (vue-i18n.esm.js?a925:1173)
at eval (main.js?56d7:19)
at Module../src/main.js (app.js:1167)
at __webpack_require__ (app.js:854)
at fn (app.js:151)
at Object.1 (app.js:1228)
at __webpack_require__ (app.js:854)
at checkDeferredModules (app.js:46)
at app.js:994
at app.js:997

Anything I'm doing wrong here ? any dependency I'm missing ? Any help would be really appreciated.



from Error while using VueI18n plugin in vue - Cannot set property '_vm' of undefined

How to make Android's ViewPager look like iOS 13 UISegmentedControl

I am using ViewPager in Android and would like to style it to look like the iOS 13 segmented control. I'm not too sure where to get started doing that. Can anyone point me to how I can get started?

The iOS segmented control has these boxes that slide between.

Here are some screenshots:

Android currently looks like this:

enter image description here

I would like for it to look like this:

enter image description here



from How to make Android's ViewPager look like iOS 13 UISegmentedControl

How to make Android's ViewPager look like iOS 13 UISegmentedControl

I am using ViewPager in Android and would like to style it to look like the iOS 13 segmented control. I'm not too sure where to get started doing that. Can anyone point me to how I can get started?

The iOS segmented control has these boxes that slide between.

Here are some screenshots:

Android currently looks like this:

enter image description here

I would like for it to look like this:

enter image description here



from How to make Android's ViewPager look like iOS 13 UISegmentedControl

Django renders an "in exception" page instead of a page that can help debugging

Django was working normally, suddenly I wasn't able to get any debugging messages. I have been commenting out my code to see which part is causing that and it turned out to be my last_visit middleware which gets when was the last time user visited the app. But why? what is wrong with it?!

last_visit.py (The middleware I made)

from django.http import HttpResponse
from django.utils.timezone import now
from django.contrib.auth import get_user_model
User = get_user_model()


class SetLastVisitMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated:
            User.objects.filter(id=request.user.id).update(last_visit=now())
        return self.get_response(request)

    def process_exception(self, request, exception):
        return HttpResponse("in exception")

settings.py:

MIDDLEWARE = [
    ...
    'users.get_request.RequestMiddleware',
    'users.last_visit.SetLastVisitMiddleware'
]


from Django renders an "in exception" page instead of a page that can help debugging

Getting error "You have exceeded the maximum transaction amount set by your bank" when calling Google Pay intent from my android app

I am facing this weird problem with my Google pay integration in android app. When I am sending an amount more than 2000(INR) I am getting the error "You have exceeded the maximum transaction amount set by your bank" even though I have not transacted any amount. And when I try to send amount directly from Google pay it works. It is also working for the amounts below 2000(INR) but not for more than that.

Here is code

  val uri: Uri = Uri.Builder()
        .scheme("upi")
        .authority("pay")
        .appendQueryParameter("pa", MY_UPI_ID)
        .appendQueryParameter("pn", MY_USER_NAME)
        //.appendQueryParameter("mc", "1234")
        //.appendQueryParameter("tr", "123456789")
        .appendQueryParameter("tn", "test transaction note")
        .appendQueryParameter("am", "2500.00")
        .appendQueryParameter("cu", "INR")
        //.appendQueryParameter("url", "https://test.merchant.website")
        .build()
    
    
    val intent = Intent(Intent.ACTION_VIEW)
    intent.data = uri
    intent.setPackage(GOOGLE_PAY_PACKAGE_NAME)
    startActivityForResult(intent, PAY_REQUEST_CODE)

I have read a lot of blogs, docs but didn't found any solution. Any help or suggestions?



from Getting error "You have exceeded the maximum transaction amount set by your bank" when calling Google Pay intent from my android app

@Google-cloud/storage suddenly throwing weird exception after working for a long time

Context:

I have an API endpoint which serves .stl files stored in a public Google Cloud Storage bucket. Until sometime this week, it was working fine. I can step all the way through my code with the debugger. The NPM module in question is not even referenced in my project. I've tried using the exact code on Googles documentation for download and get the same exception: https://github.com/googleapis/nodejs-storage/blob/master/samples/downloadFile.js

What I've tried

npm rebuild @google-cloud/storage and different ways of using the same Google npm package.

Questions:

1.) Shouldn't the catch, catch the exception to prevent the crash?

2.) Anyone have any ideas on a workaround?

File: https://storage.cloud.google.com/fancy_induction_ui/1inX1in.stl

Code:

  getFile: async (req, res) => {
    try {
      const fileName = req.param('file');
      res.setHeader('Content-Type', 'application/octet-stream');
      res.setHeader('Content-Disposition', 'attachment; filename=' + fileName + '');
      const storage = new Storage();
      let file = await storage.bucket('fancy_induction_ui').file(fileName).createReadStream();
      file.pipe(res);
    } catch (e) {
      res.status(500).json({message: 'Something is wrong!', err: e.message});
    }
  }

Stacktrace:

path/to/code/node_modules/readable-stream/lib/_stream_writable.js:317
  var isBuf = !state.objectMode && _isUint8Array(chunk);
                     ^

TypeError: Cannot read property 'objectMode' of undefined
    at DestroyableTransform.Writable.write (path/to/code/node_modules/readable-stream/lib/_stream_writable.js:317:22)
    at PassThrough.ondata (_stream_readable.js:714:22)
    at PassThrough.emit (events.js:321:20)
    at PassThrough.EventEmitter.emit (domain.js:482:12)
    at PassThrough.Readable.read (_stream_readable.js:512:10)
    at flow (_stream_readable.js:989:34)
    at resume_ (_stream_readable.js:970:3)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)


from @Google-cloud/storage suddenly throwing weird exception after working for a long time

(Node.js child process) Spawning explorer, with /select option, does not work with spaces in path

I'm writing a Node script that performs a "Reveal file in explorer" function. My code boils down to this:

const {spawn} = require('child_process');

// This works (it opens C:/path/to/file and highlights the file named "WithoutSpaces"
spawn('explorer', ["C:\\path\\to\\file\\WithoutSpaces,", "/select"]);

// However, this does not work. It defaults to opening a file explorer window with my Documents folder.
spawn('explorer', ["C:\\this path\\has spaces,", "/select"]
spawn('explorer', ["C:\\this path\\has spaces\\file.txt,", "/select"]

// Strangely, spaces DO work if I'm not doing the /select option:
spawn('explorer', ["C:\\this path\\has spaces,", "/select"]

Strangely, when I use the /select argument to select a file, it only works when the path does not include any spaces. If the path does have spaces, then it defaults to the Documents folder.

Is there any way around this? Perhaps a way to encode a space with a backslash? Or maybe some other special arguments to the explorer command?



from (Node.js child process) Spawning explorer, with /select option, does not work with spaces in path

Friday, 30 October 2020

Tool tip in html

I have a div that needs to be identified using a line and box(which will contain a message) like in the below mockup image.2 and 3(Line and a rectangular box) are fixed to each other and draggable and 1(Line) can be stretched to any direction. I have created the box but I am not able to figure out how can I attach a line to it. Here is what I have tried.

JSFIDDLE

js

const $b1 = $("#box1");
const $b2 = $("#box2");
const $line = $("#line");

const coordinates = function() {
debugger;
  const x1 = $b1.offset().left;
  const y1 = $b1.offset().top + $b1.height()/2;
  const x2 = $b2.offset().left + $b1.width()/2;
  const y2 = $b2.offset().top + $b1.height()/2;

  moveLine(x1, y1, x2, y2);  
}

coordinates();

function moveLine(x1, y1, x2, y2) {
    var length = Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)));
    var angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
    var transform = 'rotate(' + angle + 'deg)';

    offsetX = (x1 > x2) ? x2 : x1;
    offsetY = (y1 > y2) ? y2 : y1;
    
    $line.css({
        'position': 'absolute',
        '-webkit-transform': transform,
        '-moz-transform': transform,
        'transform': transform
      })
      .width(length)
      .offset({
        left: offsetX,
        top: offsetY
      });
}

$('#box1').draggable({
  drag: coordinates
});

Html

<div class="box" id="box1">10%</div>
<p id="box2">www.google.com</p>

<div class="line" id="line"></div>

css

.box {
  border: 1px solid black;
  background-color: #ffffff;
  width: 100px;
  height: 40px;
  position: absolute;
}

#line1 {
  top: 100px;
  left: 50px;
  /*transform: rotate(222deg);
    -webkit-transform: rotate(222deg);
    -ms-transform: rotate(222deg);*/
}

.line {
  width: 1px;
  height: 1px;
  background-color: black;
  position: absolute;
  z-index: -1; /* put line behind the boxes */
}


#box1 {
  top: 150px;
  left: 150px;
}

#box2 {
  top: 200px;
  left: 200px;
  position:relative;
}

enter image description here



from Tool tip in html

Android 4.4 Locked Task Mode

I'm creating a flutter app that will be installed on a Samsung Galaxy 7-inch Tablet with Android KitKat (v4.4). It will be the only app on the tablet, and will be implemented such that it loads when the device is powered up, and the user will be unable to exit the application.

I've found this on the Android Developer docs, but it only applies for versions 5.0 and over. https://developer.android.com/work/dpc/dedicated-devices/lock-task-mode#java

I have not been able to find any documentation/tutorials that could possibly assist with this, without using a 3rd party application such as Surelock and Kioware.

Is there a way to implement the above for older Android version (in my case for version 4.4)? Thank you.



from Android 4.4 Locked Task Mode

Restangular PUT without an identifier

I've been using Restangular for a long time now, but for one problem I could never find a clean solution.

Let's say I have a rest endpoint like this:

/rest/team/123 -> gives me the Team.
/rest/team/123/season/7 -> gives me the season-specific data for team 123 in Season 7

the seasonTeam looks like this:

{
  coachId: 15,
  imageURL: '',
}

my code looks something like this:

var resource = team.resource.one('season', seasonId);
resource.get().then(function(to) {
    $scope.seasonTeam = to;
});

and at a later point:

$scope.seasonTeam.coachId = ... ;
$scope.seasonTeam.put();

I purposely didn't include an id in my object model. Now when I run this, I get an error because Restangular is trying to put it to /rest/team/123/season instead of /rest/team/123/season/7

I hoped that Restangular would use the same URL from the get() function to use in the put().

So I added an id:

{
  id: 7,
  coachId: 15,
  imageURL: '',
}

and now it works nicely. But it bugs me that the id in the object is not really the object's id, but the season.id . The server source code just got incredibly ugly.

I could live with:

{
  seasonId: 7,
  coachId: 15,
  imageURL: '',
}

but the put() doesn't know that it should use the seasonId for the resource path.

I'm looking for a clean solution fo this, maybe something like:

var resource = team.resource.one('season', seasonId);
resource.get().then(function(to) {
    to.tellRestangularToUseThisAsIdForPath('seasonId');
    $scope.seasonTeam = to;
});

any good suggestions? and I'd also love to understand why RestAngular doesn't use the same URL for get() and put()



from Restangular PUT without an identifier

reactjs - redux form and material ui framework — autocomplete field

I am building a nested form framework that uses the redux form and material ui framework -- I've built the components here to date - https://codesandbox.io/s/bold-sunset-uc4t5

what I would like to do - is add an autocomplete field -- that only shows the possible results after 3 chars have been typed.

https://material-ui.com/components/autocomplete/

I want it to have similar properties/styles to the text field and select box



from reactjs - redux form and material ui framework — autocomplete field

Unable to resolve dependency tree error when installing npm packages

When trying to install the npm packages using npm i command I am getting the following exception:

enter image description here

I have tried reinstalling the node js package and setting proxy to off using:

set HTTP_PROXY=
set HTTPS_PROXY=

The issue is still there. What I am doing wrong?



from Unable to resolve dependency tree error when installing npm packages

Swift: Share Auth state between apps

Inside my app the user can sign in with Apple, Google, Facebook and Email using Firebase. I also have a Share Extension and I would like to share the auth-state from the Main-App so I can also call Auth.auth.currentUser inside my ShareExtension so the user can access Cloud-Firestore.

Now I know there is this documentation provided by Firebase. However I am not sure about Step 2:

do {
   try Auth.auth().useUserAccessGroup("TEAMID.com.example.group1")
} catch let error as NSError {
   print("Error changing user access group: %@", error)
}

Where exactly do I have to call this?



from Swift: Share Auth state between apps

Piping requests using gaxios (or axios)

At present I'm performing the trick of piping a request req to a destination url, and piping the response back to res, like so:

const request = require('request');

const url = 'http://some.url.com' + req.originalUrl;
const destination = request(url);

// pipe req to destination...
const readableA = req.pipe(destination);
readableA.on('end', function () {
    // do optional stuff on end
});

// pipe response to res...
const readableB = readableA.pipe(res);
readableB.on('end', function () {
    // do optional stuff on end
});

Since request is now officially deprecated (boo hoo), is this trick at all possible using the gaxios library? I thought that setting responseType: 'stream' on the request would do something similar as above, but it doesn't seem to work.

SImilarly, can gaxios be used in the following context:

request
.get('https://some.data.com')
.on('error', function(err) {
    console.log(err);
})
.pipe(unzipper.Parse())
.on('entry', myEntryHandlerFunction);


from Piping requests using gaxios (or axios)

Handling a SOAP request in NodeJS with PHP documentation

I'm struggling to convert a PHP code handling a SOAP request into NodeJS. I tried a lot of things, including npm:

I really don't understand how to fit the lines I have in PHP into a NodeJS code. Here it is:

$stream_context = stream_context_create([
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ],
     'http' => [
         'header' => 'MailToken: ' . $token
     ]
]);

$client = new SoapClient(null, [
    'stream_context' => $stream_context,
    'location' => self::MAIL_URL,
    'uri' => 'SOAPService/Mail'
]);

return $client->__soapCall('send', [
    'subject' => $subject,
    'body' => $body,
    'recipients' => $recipients
], null);

Could anybody give me a piece of advice? Thanks a lot.



from Handling a SOAP request in NodeJS with PHP documentation

Handling a SOAP request in NodeJS with PHP documentation

I'm struggling to convert a PHP code handling a SOAP request into NodeJS. I tried a lot of things, including npm:

I really don't understand how to fit the lines I have in PHP into a NodeJS code. Here it is:

$stream_context = stream_context_create([
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ],
     'http' => [
         'header' => 'MailToken: ' . $token
     ]
]);

$client = new SoapClient(null, [
    'stream_context' => $stream_context,
    'location' => self::MAIL_URL,
    'uri' => 'SOAPService/Mail'
]);

return $client->__soapCall('send', [
    'subject' => $subject,
    'body' => $body,
    'recipients' => $recipients
], null);

Could anybody give me a piece of advice? Thanks a lot.



from Handling a SOAP request in NodeJS with PHP documentation

How to get dashed line svg animation on accordingly scroll?

enter image description here

Whenever i apply on scroll animation on dashed line svg than it converted into a simple line without dashed.

I want same animation which is currently working but line would be dashed-line as shown as Svg Before animation in below example.

// Get the id of the <path> element and the length of <path>
var triangle = document.getElementById("dashed-path");
var length = triangle.getTotalLength();

// The start position of the drawing
triangle.style.strokeDasharray = length;

// Hide the triangle by offsetting dash. Remove this line to show the triangle before scroll draw
triangle.style.strokeDashoffset = length;

// Find scroll percentage on scroll (using cross-browser properties), and offset dash same amount as percentage scrolled
window.addEventListener("scroll", myFunction);

function myFunction() {
var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);

  var draw = length * scrollpercent;
  
  // Reverse the drawing (when scrolling upwards)
  triangle.style.strokeDashoffset = length - draw;
}
.height-div{
        height: 500px; width: 100%; background:#eeeeee; 
    }
    .desktop-pattern-wrap{display: inline-block;vertical-align: top;width: 100%;}
    .desktop-pattern-wrap > div{float: left;width: 50%;}
<div class="desktop-pattern-wrap">
        <div class="desktop-pattern">
            <h2>Svg after animation</h2>
            <svg width="198px" height="1458px" viewBox="0 0 198 1458" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                <defs>
                    <linearGradient x1="50%" y1="7.06935325%" x2="50%" y2="100%" id="linearGradient-1">
                        <stop stop-color="#DE1652" offset="0%"></stop>
                        <stop stop-color="#F37121" offset="50.2239948%"></stop>
                        <stop stop-color="#FBAB26" offset="100%"></stop>
                    </linearGradient>
                </defs>
                <g id="Homepage" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" stroke-dasharray="12,16" stroke-linejoin="round">
                    <g id="Desktop-Homepage-1" transform="translate(-646.000000, -825.000000)" stroke="url(#linearGradient-1)" stroke-width="4">
                        <g id="content" transform="translate(0.000000, 560.000000)">
                            <path d="M702,266 C682,424 795.064639,474.307498 716,600 C599,786 769,821 688,988 C548.560405,1275.48657 822.815807,1223 840.843207,1373 C858.870608,1523 605.485477,1528 687.610302,1728" id="dashed-path"></path>
                        </g>
                    </g>
                </g>
            </svg>
        </div>
        <div class="desktop-pattern-right">
            <h2>Svg Before animation</h2>
            <svg width="198px" height="1458px" viewBox="0 0 198 1458" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                <defs>
                    <linearGradient x1="50%" y1="7.06935325%" x2="50%" y2="100%" id="linearGradient-1">
                        <stop stop-color="#DE1652" offset="0%"></stop>
                        <stop stop-color="#F37121" offset="50.2239948%"></stop>
                        <stop stop-color="#FBAB26" offset="100%"></stop>
                    </linearGradient>
                </defs>
                <g id="Homepage" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" stroke-dasharray="12,16" stroke-linejoin="round">
                    <g id="Desktop-Homepage-1" transform="translate(-646.000000, -825.000000)" stroke="url(#linearGradient-1)" stroke-width="4">
                        <g id="content" transform="translate(0.000000, 560.000000)">
                            <path d="M702,266 C682,424 795.064639,474.307498 716,600 C599,786 769,821 688,988 C548.560405,1275.48657 822.815807,1223 840.843207,1373 C858.870608,1523 605.485477,1528 687.610302,1728" id="dashed-path"></path>
                        </g>
                    </g>
                </g>
            </svg>
        </div>
    </div>
    <div class="height-div">
        
    </div>


from How to get dashed line svg animation on accordingly scroll?

Fragment and viewLifecycleOwner deviation

I'm collecting a flow on the viewLifecycleOwner. It flows on Dispatchers.Default, but the collection itself takes place on Dispatchers.Main.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    viewLifecycleOwner.lifecycleScope.launch {
        flow.flowOn(Default).collect {
            requireContext()
        }
    }
}

In one occation I found the IllegalStateException stating, that the fragment is not attached.

IllegalStateException: Fragment Test not attached to a context.

I assumed that the collection of the flow would be canceled before the fragment is detached.

How is it possible for the coroutine to resume on a detached fragment?



from Fragment and viewLifecycleOwner deviation

Creating overlapping boarder colours with xlsxwriter and pandas

Given the following data:

import pandas as pd
import numpy as np
# sample data
np.random.seed(1)
np.random.seed(1)
df = pd.DataFrame(
    np.random.randint(low=0, high=1000, size=(6, 5)),
    columns=["X", "a", "b", "c", "d"],
    index=["a", "b", "X", "d", "e", "X"],
)

I can create a xlsx file with formatted boarders using the following:

with pd.ExcelWriter("testing.xlsx") as writer:
    #  need to create xlsx output for this example
    sheet_name = "Sheet1"
    df.to_excel(writer, sheet_name=sheet_name)
    workbook = writer.book
    worksheet = writer.sheets[sheet_name]

    # create horizontal line
    row_range = (3, 3)
    col_range = (1, 8)
    worksheet.conditional_format(
        row_range[0],
        col_range[0],
        row_range[1],
        col_range[1],
        {
            "type": "no_errors",
            "format": workbook.add_format(
                {
                    "top": 2,
                    "border_color": "red",
                }
            ),
        },
    )
    # create vertical line
    row_range = (1, 9)
    col_range = (4, 4)
    worksheet.conditional_format(
        row_range[0],
        col_range[0],
        row_range[1],
        col_range[1],
        {
            "type": "no_errors",
            "format": workbook.add_format(
                {
                    "left": 2,
                    "border_color": "red",
                }
            ),
        },
    )

However the formatting is incorrect (or, not as desired), and looks as:

enter image description here

The part which is incorrect is:

enter image description here

It seems that I am unable to format a cell twice? Which is an issue here.

This question might generalise from creating an overlapping boarder to creating overlapping conditional formatting, I'm not familiar enough with xlsxwriter to say.



from Creating overlapping boarder colours with xlsxwriter and pandas

Load html text in WKWebView

I use this code to load my html file with text in WKWebView:

do {
   guard let filePath = Bundle.main.path(forResource: "\(readBookNumber)", ofType: "html")
       else { 
           print ("File reading error")
           return
       }
   var content =  try String(contentsOfFile: filePath, encoding: .utf8)
   let baseUrl = URL(fileURLWithPath: filePath)
            
   content.changeHtmlStyle(font: "Iowan-Old-Style", fontSize:  UserDefaults.standard.integer(forKey: "textSize"), fontColor: textColor)
   webView.loadHTMLString(headerString+content, baseURL: baseUrl)
}
catch {
    print ("File HTML error")
}

and this code to load the page where the user stopped reading last time:

self.webView.scrollView.contentOffset.x = CGFloat(UserDefaults.standard.integer(forKey: "pageToLoad"))

I use code for loading last page in this method:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
         self.webView.scrollView.contentOffset.x = CGFloat(UserDefaults.standard.integer(forKey: "pageToLoad"))
    }
}

At first I used deadline: .now() + 0.1, but that didn't work. Because the last read page was loaded initially, and after a few seconds I see my text on the first page. I change it to deadline: .now() + 0.5 and the text loads fine from the last page read. Its was 700 pages. But now I want to load another text with 1700 pages. And I have same problem like first time. I can change deadline: .now() + 1.0 and my text will load fine. But I think this is not the best solution. I run it on my iPhone X. But maybe if I run it on iPad mini 2 I should change deadline: .now() + 10.0 because iPad mini 2 not very powerful. How to solve the problem?

Update based on @DPrice code:

If I use this code:

override func viewDidLoad() {
    super.viewDidLoad()
    webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)

....
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if (keyPath == "estimatedProgress") {
        if webView.estimatedProgress == 1.0 {
            self.webView.scrollView.contentOffset.x = CGFloat(UserDefaults.standard.integer(forKey: "pageToLoad\(self.readBookNumber)"))
        }
    }
}

I have same bad result like in my code.

But if I use this code:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if (keyPath == "estimatedProgress") {
        if webView.estimatedProgress == 1.0 {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.webView.scrollView.contentOffset.x = CGFloat(UserDefaults.standard.integer(forKey: "pageToLoad\(self.readBookNumber)"))
            }
        }
    }
}

Everything works fine. And my last page loading fine. But it does not solve the problem in my question.



from Load html text in WKWebView

python asyncio aiohttp timeout

Word of notice: This is my first approach with asyncio, so I might have done something really stupid.

Scenario is as follows:

I need to "http-ping" a humongous list of urls to check if they respond 200 or any other value. I get timeouts for each and every request, though tools like gobuster report 200,403, etc.

My code is sth similar to this:

import asyncio,aiohttp
import datetime 
#-------------------------------------------------------------------------------------
async def get_data_coroutine(session,url,follow_redirects,timeout_seconds,retries):
    #print('#DEBUG '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' '+url)
    try:
        async with session.get(url,allow_redirects=False,timeout=timeout_seconds) as response:
            status  =   response.status
            #res     =   await response.text()
            if(  status==404):
                pass
            elif(300<=status and status<400):
                location = str(response).split("Location': \'")[1].split("\'")[0]
                print('#HIT   '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' '+str(status)+' '+url+' ---> '+location)
                if(follow_redirects==True):
                    return await get_data_coroutine(session,location,follow_redirects,timeout_seconds,retries)
            else:
                print('#HIT   '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' '+str(status)+' '+url)
            return None
    except asyncio.exceptions.TimeoutError as e:
        print('#ERROR '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' '+'   '+' '+url+' TIMEOUT '+str(e))
        return None
#---------------------------------------------------------------------------    
async def main(loop):
        base_url                =   'http://192.168.59.37'
        extensions              =   ['','.html','php']
        fd                      =   open('/usr/share/wordlists/dirb/common.txt','r')
        words_without_suffix    =   [x.strip() for x in fd.readlines()]#[-5:] #DEBUG!
        words_with_suffix       =   [base_url+'/'+x+y for x in words_without_suffix for y in extensions]
        follow                  =   True
        total_timeout           =   aiohttp.ClientTimeout(total=60*60*24)
        timeout_seconds         =   10
        retries                 =   1
        async with aiohttp.ClientSession(loop=loop,timeout=total_timeout) as session:
            tasks = [get_data_coroutine(session,url,follow,timeout_seconds,retries) for url in words_with_suffix]
            await asyncio.gather(*tasks)
        print('DONE')
#---------------------------------------------------------------------------    
if(__name__=='__main__'):
    loop    =   asyncio.get_event_loop()
    result  =   loop.run_until_complete(main(loop))
   

Did I do something really wrong?

Any word of advice?

Thank you SO much!



from python asyncio aiohttp timeout

Enemy not staying at original spot

So I been trying make my enemy move at the same spot while my player moves the camera but it's not working, when the screen moves my enemy will slowly move from its original spot but once its out of its original spot it will start glitching. Also when my player collides with a side of a platform my enemy will move the same way as my player but faster e.g.: https://gyazo.com/926207e82cd9849266decd68c08ea84d

A part of my camera movement(Not working)

if keys[pygame.K_d]:
        for Platform in platforms:
            Platform.x -= playerman.speed
        for Snake in snakes:
            Snake.scroll(-playerman.speed,0)
        for Rule in rules:
            Rule.x -= playerman.speed
        if not playerman.isJump:
            playerman.direction = "right"

My full code

import pygame
pygame.init()

window = pygame.display.set_mode((700,500))
pygame.display.set_caption("Noobs First Game")


move = pygame.image.load("WASD.png")


# Playerman
class Player:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.speed = 5
        self.isJump = False
        self.JumpCount = 10
        self.idle =[pygame.image.load("player_idel_1.png"),
                            pygame.image.load("player_idel_2.png"),
                            pygame.image.load("player_idel_3.png"),
                            pygame.image.load("player_idel_4.png"),
                            pygame.image.load("player_idel_5.png"),
                            pygame.image.load("player_idel_6.png"),
                            pygame.image.load("player_idel_7.png"),
                            pygame.image.load("player_idel_8.png")
                            ]

        self.idlel = [pygame.image.load("Player_idel_left1.png"),
                         pygame.image.load("Player_idel_left2.png"),
                         pygame.image.load("Player_idel_left3.png"),
                         pygame.image.load("Player_idel_left4.png"),
                         pygame.image.load("Player_idel_left5.png"),
                         pygame.image.load("Player_idel_left6.png"),
                         pygame.image.load("Player_idel_left7.png"),
                         pygame.image.load("Player_idel_left8.png")
                         ]
        self.right = [pygame.image.load("Player_walk_right1.png"),
                      pygame.image.load("Player_walk_right2.png"),
                      pygame.image.load("Player_walk_right3.png")]
        
        self.left = [pygame.image.load("Player_walk_left1.png"),
                     pygame.image.load("Player_walk_left2.png"),
                     pygame.image.load("Player_walk_left3.png")]

        self.jump1 = [pygame.image.load("Player_jump5.png")]

        
        self.jump2 = [
                     pygame.image.load("Player_rjump1.png")]
        

        self.fall = 0
        self.rect = pygame.Rect(x,y,height,width)
        self.idle = [pygame.transform.scale(image,(image.get_width()*2,image.get_height()*2)) for image in self.idle]
        self.idlel = [pygame.transform.scale(image,(image.get_width()*2,image.get_height()*2)) for image in self.idlel]
        self.right = [pygame.transform.scale(image,(image.get_width()*2,image.get_height()*2)) for image in self.right]
        self.left = [pygame.transform.scale(image,(image.get_width()*2, image.get_height()*2)) for image in self.left]
        self.jump1 = [pygame.transform.scale(image,(image.get_width()*2,image.get_height()*2)) for image in self.jump1]
        self.jump2 = [pygame.transform.scale(image,(image.get_width()*2,image.get_height()*2)) for image in self.jump2]
        self.fps = 10
        self.clock = pygame.time.Clock()
        self.anim_index = 0
        self.direction = "idle"
        self.direction = "right"
        self.direction = "left"
        self.dierection = "idleleft"
        self.dierection = "jump1"
        self.dierection = "jump2"
        self.next_frame_time = 0
    def get_rect(self):
        self.rect.topleft = (self.x,self.y)
        return self.rect
        pygame.draw.rect(self.color,self.rect)
    
    def draw(self):
        if self.direction == "idle":
            image_list = self.idle
        if self.direction == "right":
            image_list = self.right
        if self.direction == "left":
            image_list = self.left
        if self.direction == "idlel":
            image_list = self.idlel
        if self.direction == "jump1":
            image_list = self.jump1
        if self.direction == "jump2":
            image_list = self.jump2
    

         

        # Is it time to show the next animation frame?
        time_now = pygame.time.get_ticks()
        if ( time_now > self.next_frame_time ):
            # set the time for the next animation-frame
            inter_frame_delay = 1000 // self.fps   
            self.next_frame_time = time_now + inter_frame_delay  # in the future
            # move the current image to the next (with wrap-around)
            self.anim_index += 1
            if self.anim_index >= len( image_list ):
                self.anim_index = 0
                    
        if self.anim_index >= len(image_list):
            self.anim_index = 0
        player_image = image_list[self.anim_index]

        pygame.draw.rect( window, self.color, self.get_rect(), 2 )
        player_image = image_list[self.anim_index]

        player_rect = player_image.get_rect(center = self.get_rect().center)
        player_rect.centerx += 3
        player_rect.centery -= 13
        window.blit(player_image, player_rect)

class Snake:
    def __init__(self, x, y, width, height, end):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.path = [x, end]
        self.walkCount = 0
        self.vel = 3
        self.visible = True
        self.no = pygame.image.load("Player_jump5.png")
        self.rect = pygame.Rect(x,y,width,height)
    def draw(self):
        self.move()
        self.rect.topleft = (self.x,self.y)
        window.blit(self.no,self.rect)

    def move(self):
        if self.visible:
            # turn around if the move would go out-of-bounds
            proposed_move = self.x + self.vel
            if ( proposed_move < self.path[0] or proposed_move > self.path[1] ):
                # Move hits a boundary, so we need to turn around
                self.vel = -self.vel
                self.Walking_index = 0
            # now make the correct move
            self.x += self.vel   # add +/- velocity
    def scroll(self,sx,sy):
        self.x += sx
        self.y += sy
        self.path[0] += sx
        self.path[1] += sx


class Platform:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y =y
        self. width = width
        self.color = color
        self.height = height
        self.color = color
        self.speed = 4
        self.rect = pygame.Rect(x,y,width,height)
    def get_rect(self):
        self.rect.topleft = (self.x,self.y)
        return self.rect
    def draw(self):
        pygame.draw.rect(window,self.color,self.get_rect())


class Rule:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y =y
        self. width = width
        self.color = color
        self.height = height
        self.color = color
        self.speed = 4
        self.rect = pygame.Rect(x,y,width,height)
    def draw(self):
        self.rect.topleft = (self.x,self.y)


# Colors for hitbox
white = (255,255,255)
green = (0,255,0)

# Drawing Player
playerman = Player(350,445,40,40,white)

#Drawing Platforms
platform1 = Platform(300,-9.1,40,500,green)
platform2 = Platform(330,451,2000,40,green)
platform3 = Platform(2300,-9.1,40,500,green)

# Drawing Rule
rule1 = Rule(340,-9.1,220,500,green)
rule2 = Rule(20000,-9,1,5,green)

snake1 = Snake(100, 110, 64, 64, 300)

# List
platforms = [platform1,platform2,platform3]

rules = [rule1,rule2]

snakes = [snake1]


# draws map
platformGroup = pygame.sprite.Group
Level = [
"                                         1   1",
"                                         1    ",
"                         1  1        111 1    ",
"                         1  1         1  1    ",
"                         11 1      1  1 11    ",
"                         1  1         1  1    ",
"                         1  1    1    11 1    ",
"           1   1   111   1 11         1  1    ",
"           1   1  11111        1      1          ",]

for iy,row in enumerate(Level):
    for ix, col in enumerate(row):
        if col == "1":
            new_platforms = Platform(ix*50,iy*50.2,50,50,(255,255,255))
            platforms.append(new_platforms)
    
            

# Windows color
def redrawwindow():
    window.fill((0,0,0))

    # Drawing the player and other stuff to the screen
    playerman.draw()

    for Platform in platforms:
        Platform.draw()
    for Rule in rules:
        Rule.draw()
    for Snake in snakes:
        Snake.draw()

x = 10
y = 10
x_change = 0
y_change = 0
old_x = x
old_y = y
fps = (30)
clock = pygame.time.Clock()

run = True
while run:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    
            

        


 # part of player screen movment
    if playerman.y < 250:
        playerman.y += 1
        for Platform in platforms:
            Platform.y += playerman.speed

        for Snake in snakes:
            Snake.scroll(0, +playerman.speed)

    if playerman.y > 410:
        playerman.y -= playerman.fall
        for Platform in platforms:
            Platform.y -= playerman.fall
        for Snake in snakes:
            Snake.scroll(0, -playerman.fall)

    # part of side colliding    
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_d:
            x_change = -7
            for Snake in snakes:
                Snake.scroll(playerman.speed,0)
            
        if event.key == pygame.K_a:
            x_change = 7
            for Snake in snakes:
                Snake.scroll(-playerman.speed,0)

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_d or event.key == pygame.K_a:
            x_change = 0

        x += x_change
        if x > 500 - playerman.width or x < 0:
            x = old_x
           
        # lets player move
    keys = pygame.key.get_pressed()
    px, py = playerman.x, playerman.y

    for Platform in platforms:    
        if playerman.fall > 0 and keys[pygame.K_SPACE]:
            if keys[pygame.K_d]:
                playerman.direction = "jump1"
        else:
            if playerman.direction == "left":
                if keys[pygame.K_SPACE]:
                    playerman.direction = "jump2"

               

 # direction for player animation and screen movment
    if keys[pygame.K_d]:
        for Platform in platforms:
            Platform.x -= playerman.speed
        for Snake in snakes:
            Snake.scroll(-playerman.speed,0)
        for Rule in rules:
            Rule.x -= playerman.speed
        if not playerman.isJump:
            playerman.direction = "right"

        
    elif keys[pygame.K_a]:
        for Platform in platforms:
            Platform.x += playerman.speed
        for Rule in rules:
            Rule.x += playerman.speed
        if not playerman.isJump:
            playerman.direction = "left"
        for Snake in snakes:
            Snake.scroll(playerman.speed,0)






            
    else:
        if playerman.direction == "left" and playerman.direction == "idlel":
         
            playerman.direction = "idlel"
        else:
            if playerman.direction == "right" and playerman.direction == "idle":
                
                playerman.direction = "idle"


    if playerman.direction == "right" and keys[pygame.K_SPACE]:
        playerman.direction = "jump1"
            
    if playerman.direction == "left":
        if keys[pygame.K_SPACE]:
            playerman.direction = "jump2"

    
    # sides for player and player screen movment
    platform_rect_list = [p.rect for p in platforms]
    player_rect = playerman.get_rect()
    player_rect.topleft = (px, py)

    playerman.y = py
    if player_rect.collidelist(platform_rect_list) < 0:
        playerman.x = px

    move_right = keys[pygame.K_d]
    move_left = keys[pygame.K_a]
    if move_right: 
        for Platform in platforms:
            Platform.x -= playerman.speed
        for Rule in rules:
            Rule.x -= playerman.speed     # <---
        for Snake in snakes:
            Snake.scroll(-playerman.speed,0)

    if move_left:
        for Platform in platforms:
            Platform.x += playerman.speed
        for Rule in rules:
            Rule.x += playerman.speed     # <---
        for Snake in snakes:
            Snake.scroll(playerman.speed,0)

    platform_rect_list = [p.get_rect() for p in platforms] # get_rect()
    player_rect = playerman.get_rect()
    player_rect.topleft = (px, py)

    playerman.y = py
    cI = player_rect.collidelist(platform_rect_list)
    if cI >= 0:
        # undo movement of platforms dependent on the direction and intersection distance
        dx = 0
        if move_right: 
            dx = platform_rect_list[cI].left - player_rect.right
        if move_left:
            dx = platform_rect_list[cI].right - player_rect.left
        for Platform in platforms:
            Platform.x -= dx
            Platform.get_rect() # update rectangle
        for Rule in rules:
            Rule.x -= dx             # <---
        for Snake in snakes:
            Snake.x -= dx


##############                
  
    # About isJump
    if not playerman.isJump:
        playerman.y += playerman.fall
        playerman.fall += 1
        playerman.isJump = False

        # this part lets you jump on platform only the top 
        collide = False
        for Platform in platforms:
            if playerman.get_rect().colliderect(Platform.rect):
                collide = True
                playerman.isJump = False
                playerman.y = Platform.rect.top - playerman.height
                if playerman.rect.right > Platform.rect.left and playerman.rect.left < Platform.rect.left - playerman.width:
                    playerman.x = Platform.rect.left - playerman.width
                if playerman.rect.left < Platform.rect.right and playerman.rect.right > Platform.rect.right + playerman.width:
                    playerman.x = Platform.rect.right
                       
            # colliding with floor      
            if playerman.rect.bottom >= 500:
                collide = True
                playerman.isJump = False
                playerman.Jumpcount = 10
                playerman.y = 500 - playerman.height

        # Jumping
        if collide:
            if keys[pygame.K_SPACE]:
                playerman.isJump = True
                py -= playerman.speed
            playerman.fall = 0
            

    # Jump Count

    else:
        if playerman.JumpCount >= 0:
            playerman.y -= (playerman.JumpCount*abs(playerman.JumpCount))*0.3
            playerman.JumpCount -= 1
        else:
            playerman.isJump = False
            playerman.JumpCount = 10

    redrawwindow()
    if playerman.rect.colliderect(rule1.rect):
        window.blit(move,(-40,-100))
    
    pygame.display.update()
pygame.quit()



from Enemy not staying at original spot

How can i fill color between 4 lines in canvas?

I am trying to fill color between lines in ionic. I want fill color between line when four line touch each other. For that i created a canvas demo with touch event.

html file:

 <canvas #canvasDraw width="300" height="300" (touchstart)="handleTouchStart($event)"
        (touchmove)="handleTouchmove($event)" 
        (touchend)="handleTouchEnd($event)">
        You need a browser that supports HTML5!
 </canvas>

ts file:

import { Component, ElementRef, ViewChild } from '@angular/core';

@Component({
    selector: 'app-home',
    templateUrl: 'home.page.html',
    styleUrls: ['home.page.scss'],
})
export class HomePage {
    @ViewChild('canvasDraw', { static: false }) canvas: ElementRef;

    canvasElement: any;
    lines: any[];
    isDown: boolean = false;
    startX: number;
    startY: number;
    nearest: any;
    offsetX: any;
    offsetY: any;

    constructor() {
    }

    ngAfterViewInit() {
        this.canvasElement = this.canvas.nativeElement;
        this.lines = [];
        this.lines.push({ x0: 75, y0: 25, x1: 125, y1: 25 });
        this.lines.push({ x0: 75, y0: 100, x1: 125, y1: 100 });
        this.lines.push({ x0: 50, y0: 35, x1: 50, y1: 85 });
        this.lines.push({ x0: 150, y0: 35, x1: 150, y1: 85 });
        this.draw();
        //this.reOffset();
        requestAnimationFrame(() => {
            this.reOffset()
        })
    }

    reOffset() {
        let BB = this.canvasElement.getBoundingClientRect();
        this.offsetX = BB.left;
        this.offsetY = BB.top;
    }

    // select the this.nearest line to the mouse
    closestLine(mx, my) {
        let dist = 100000000;
        let index, pt;
        for (let i = 0; i < this.lines.length; i++) {
            //
            let xy = this.closestXY(this.lines[i], mx, my);
            //
            let dx = mx - xy.x;
            let dy = my - xy.y;
            let thisDist = dx * dx + dy * dy;
            if (thisDist < dist) {
                dist = thisDist;
                pt = xy;
                index = i;
            }
        }
        let line = this.lines[index];
        return ({ pt: pt, line: line, originalLine: { x0: line.x0, y0: line.y0, x1: line.x1, y1: line.y1 } });
    }

    // linear interpolation -- needed in setClosestLine()
    lerp(a, b, x) {
        return (a + x * (b - a));
    }

    // find closest XY on line to mouse XY
    closestXY(line, mx, my) {
        let x0 = line.x0;
        let y0 = line.y0;
        let x1 = line.x1;
        let y1 = line.y1;
        let dx = x1 - x0;
        let dy = y1 - y0;
        let t = ((mx - x0) * dx + (my - y0) * dy) / (dx * dx + dy * dy);
        t = Math.max(0, Math.min(1, t));
        let x = this.lerp(x0, x1, t);
        let y = this.lerp(y0, y1, t);
        return ({ x: x, y: y });
    }

    // draw the scene
    draw() {
        let ctx = this.canvasElement.getContext('2d');
        let cw = this.canvasElement.width;
        let ch = this.canvasElement.height;
        ctx.clearRect(0, 0, cw, ch);
        // draw all lines at their current positions
        for (let i = 0; i < this.lines.length; i++) {
            this.drawLine(this.lines[i], 'black');
        }
        // draw markers if a line is being dragged
        if (this.nearest) {
            // point on line this.nearest to mouse
            ctx.beginPath();
            ctx.arc(this.nearest.pt.x, this.nearest.pt.y, 5, 0, Math.PI * 2);
            ctx.strokeStyle = 'red';
            ctx.stroke();
            // marker for original line before dragging
            this.drawLine(this.nearest.originalLine, 'red');
            // hightlight the line as its dragged
            this.drawLine(this.nearest.line, 'red');
        }        
    }

    drawLine(line, color) {
        let ctx = this.canvasElement.getContext('2d');
        ctx.beginPath();
        ctx.moveTo(line.x0, line.y0);
        ctx.lineTo(line.x1, line.y1);
        ctx.strokeStyle = color;
        ctx.stroke();
    }

    handleTouchStart(e) {
        // tell the browser we're handling this event
        let tch = e.touches[0];
        // tch.preventDefault();
        // tch.stopPropagation();
        // mouse position
        this.startX = tch.clientX - this.offsetX;
        this.startY = tch.clientY - this.offsetY;
        // find this.nearest line to mouse
        this.nearest = this.closestLine(this.startX, this.startY);
        this.draw();
        // set dragging flag
        this.isDown = true;
    }

    handleTouchEnd(e) {
        // tell the browser we're handling this event
        let tch = e.touches[0];
        // tch.preventDefault();
        // tch.stopPropagation();
        // clear dragging flag
        this.isDown = false;
        this.nearest = null;
        this.draw();
    }

    handleTouchmove(e) {
        if (!this.isDown) { return; }
        // tell the browser we're handling this event
        let tch = e.touches[0];
        // tch.preventDefault();
        // tch.stopPropagation();
        // mouse position
        const mouseX = tch.clientX - this.offsetX;
        const mouseY = tch.clientY - this.offsetY;
        // calc how far mouse has moved since last mousemove event
        let dx = mouseX - this.startX;
        let dy = mouseY - this.startY;
        this.startX = mouseX;
        this.startY = mouseY;
        // change this.nearest line vertices by distance moved
        let line = this.nearest.line;
        line.x0 += dx;
        line.y0 += dy;
        line.x1 += dx;
        line.y1 += dy;
        // redraw
        this.draw();

        let ctx = this.canvasElement.getContext('2d');
        ctx.beginPath();
        ctx.rect(line.x0, line.y0, line.x1, line.y1);
        ctx.fillStyle = "red";
        ctx.fill();
    }

}

enter image description here

How to fill color when four line touch or connect?



from How can i fill color between 4 lines in canvas?

Connect and Print in th esc/pos mobile printerusing ionic

I am thinking to develop a Android application related to connect a Bluetooth POS printer and print the same in printer ...once connected device in local starage and transaction details are stored in local db and sync to server on daily basis .. I I have limited experience in dotnet as well as angular. Is xamarin or ionic is best suited for my requirement please suggest

EDIT: i need sample solution ionic latest version application which print in the esc/pos thermal printer take the printer from Paired devices (Printer is able to auto connect to mobile)

Please any experienced in suggest me a print the simple text in pos portable printer ( For ex: https://www.tvs-e.in/mp-280-lite/)



from Connect and Print in th esc/pos mobile printerusing ionic

Connect and Print in th esc/pos mobile printerusing ionic

I am thinking to develop a Android application related to connect a Bluetooth POS printer and print the same in printer ...once connected device in local starage and transaction details are stored in local db and sync to server on daily basis .. I I have limited experience in dotnet as well as angular. Is xamarin or ionic is best suited for my requirement please suggest

EDIT: i need sample solution ionic latest version application which print in the esc/pos thermal printer take the printer from Paired devices (Printer is able to auto connect to mobile)

Please any experienced in suggest me a print the simple text in pos portable printer ( For ex: https://www.tvs-e.in/mp-280-lite/)



from Connect and Print in th esc/pos mobile printerusing ionic

How to end Google Speech-to-Text streamingRecognize gracefully and get back the pending text results?

I'd like to be able to end a Google speech-to-text stream (created with streamingRecognize), and get back the pending SR (speech recognition) results.

In a nutshell, the relevant Node.js code:

// create SR stream
const stream = speechClient.streamingRecognize(request);

// observe data event
const dataPromise = new Promise(resolve => stream.on('data', resolve));

// observe error event
const errorPromise = new Promise((resolve, reject) => stream.on('error', reject));

// observe finish event
const finishPromise = new Promise(resolve => stream.on('finish', resolve));

// a 5 seconds test timeout
const timeoutPromise = new Promise(resolve => setTimeout(resolve, 5000)); 

// send the audio
stream.write(audioChunk);

// for testing purposes only, give the SR stream 2 seconds to absorb the audio
await new Promise(resolve => setTimeout(resolve, 2000));

// end the SR stream gracefully, by observing the completion callback
const endPromise = util.promisify(callback => stream.end(callback))();

// finishPromise wins the race here
await Promise.race([
  dataPromise, errorPromise, finishPromise, endPromise, timeoutPromise]);

// endPromise wins the race here
await Promise.race([
  dataPromise, errorPromise, endPromise, timeoutPromise]);

// timeoutPromise wins the race here
await Promise.race([dataPromise, errorPromise, timeoutPromise]);

// I don't see any data or error events, dataPromise and errorPromise don't get settled

What I experience is that the SR stream ends successfully, but I don't get any data events or error events. Neither dataPromise nor errorPromise gets resolved or rejected.

How can I signal the end of my audio, close the SR stream and still get the pending SR results?

I need to stick with streamingRecognize API because the audio I'm streaming is real-time, even though it may stop suddenly.

To clarify, it works as long as I keep streaming the audio, I do receive the real-time SR results. However, when I send the final audio chunk and end the stream like above, I don't get the final results as I'd otherwise expect.

To get the final results, I actually have to keep streaming silence for several more seconds. I feel like there must be a better way to get them.


Updated: so it appears, the only proper time to end a streamingRecognize stream is upon data event where StreamingRecognitionResult.is_final is true. As well, it appears we're expected to keep streaming audio until data event is fired, to get any result at all, final or interim.

This looks like a bug to me, filing an issue.


Updated:, it now seems to have been confirmed as a bug. Until it's fixed, I'm looking for a potential workaround.



from How to end Google Speech-to-Text streamingRecognize gracefully and get back the pending text results?

Convert and export EPS file from an SVG

I want to export a .EPS file from a .SVG in a NodeJS application. I have found multiple converting APIs but I need to create it internally. are there any packages that help me achieve that?

Notice: I have already used GraphicsMagick but I did not find anything to export .EPS

Edit: I found a way using python and svglib to convert SVG to pdf then using pdf2ps to extract a .EPS file. Unfortunately, the final .eps file was corrupted or with poor quality



from Convert and export EPS file from an SVG

How do I change the background of a button when clicked?

Okay, okay. I know many people have asked this question on Stack Overflow, but the solutions don't work for me. So my problem is simple: how do I make the female-av-button and male-av-button have a background URL of female-avatar & male-avatar respectively? Here's my code:

body{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    background-color: black;
}

.avatars{
    justify-content: center;
    margin-left: 15%;
    display: flex;
}

.choose-a-user-text{
    font-family: 'Luckiest Guy';
    font-size: 400%;
    justify-content: center;
}

.choose-a-username{
    margin-left: 25%;
}

.user-input{
    margin-left: 29%;
}

.user-input:focus{
    outline: none;
}

.female-av-button{
    background: none;
    border: none;
    padding: 1px;
}

.female-av-button:focus{

}

.male-av-button{
    background: none;
    border: none;
    padding: 1px;
}

.female-av{
    background: url('../img/female-avatar-silhouette.png') no-repeat;
    width: 500px;
    height: 700px;
}

.female-av:hover{
    background: url('../img/female-avatar.png') no-repeat;
    width: 500px;
    height: 700px;
}

.male-av{
    background: url("../img/male-avatar-silhouette.png") no-repeat;
    width: 500px;
    height: 700px;
}

.male-av:hover{
    background: url("../img/male-avatar.png") no-repeat;
    width: 500px;
    height: 700px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Choose Your Character</title>
        <link rel="stylesheet" href="css/avatar-page.css">
        <link href="https://fonts.googleapis.com/css2?family=Luckiest+Guy&display=swap" rel="stylesheet">
    </head>
    <body>
        <div class="choose-a-username">
            <h2 class="choose-a-user-text" style="color: #018D94;">CHOOSE A USERNAME</h2>
            <input class="user-input" type="text" name="" value="" placeholder="username">
        </div>
        <div class="avatars">
            <button type="button" onclick="chooseanav()" class="female-av-button" name="button"><div class="female-av"></div></button>
            <button type="button" class="male-av-button" name="button"><div class="male-av"></div></button>
        </div>


        <!-- <div class="avatars">
            <div class="silhos">
                <img src="img/male-avatar-silhouette.png" class="avatar-silho" alt="male avatar silho">
                <img src="img/female-avatar-silhouette.png" class="avatar-silho" alt="female avatar silho">
            </div>
            <div class="avas">
                <img src="img/male-avatar.png" class="avatar" alt="male avatar">
                <img src="img/female-avatar.png" class="avatar" alt="female avatar">
            </div>
        </div> -->
        <script type="text/javascript">
            // document.getElementsByClassName("user-input").style.height="500px";

            function chooseanav() {
                document.getElementsByClassName('female-av').style.background = "url('../img/female-avatar.png') no-repeat";
            }

        </script>
    </body>
</html>

Any help is greatly appreciated. Thanks!



from How do I change the background of a button when clicked?

Python numpy groupby multiple columns

Is there a way to make a group by aggregation by multiple columns in numpy? Im trying to do it with this module: https://github.com/ml31415/numpy-groupies Goal is to get a faster groupby than pandas. for example:

group_idx = np.array([
np.array([4, 3, 3, 4, 4, 1, 1, 1, 7, 8, 7, 4, 3, 3, 1, 1]),
np.array([4, 3, 2, 4, 7, 1, 4, 1, 7, 8, 7, 2, 3, 1, 14 1]),
np.array([1, 2, 3, 4, 5, 1, 1, 2, 3, 4, 5, 4, 2, 3, 1, 1])
]
a = np.array([1, 2, 1, 2, 1, 2, 1, 2, 3, 4, 5, 4, 2, 3, 1, 1])

result = aggregate(group_idx, a, func='sum')

It should be like pandas df.groupby(['column1','column2','column3']).sum().reset_index()



from Python numpy groupby multiple columns

Passing require('chromedriver).path directly to selenium-webdriver

tl;dr: Does anyone know how to pass the path of chromedriver to selenium-webdriver in code without setting the PATH environment variable?

I'm attempting to use selenium-webdriver with chrome, but would prefer to not physically install chromedriver and manipulate the path. I have the following code:

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
    withCapabilities(webdriver.Capabilities.chrome()).
    build();

Without chromedriver set in the path, this throws the error:

Error: The ChromeDriver could not be found on the current PATH. Please download the latest 
version of the ChromeDriver from http://chromedriver.storage.googleapis.com/index.html and 
ensure it can be found on your PATH.

I'd prefer not have to setup my path, so I've installed chromedriver from npm and added to my package.json:

"scripts": {
    "preinstall-chromedriver": "npm install",
    "install-chromedriver": "node node_modules/chromedriver/install.js",
    "pretest_e2e": "npm run install-chromedriver",
    "test_e2e": "node release/test/rune2e.js"
},

Now I have chromedriver installed and can get the path with require('chromedriver').path, but I have no way of passing this to the selenium-webdriver. Anyone know?



from Passing require('chromedriver).path directly to selenium-webdriver

Thursday, 29 October 2020

Apollo GraphQL Server - Access query params from cache plugin

I have an Apollo GraphQL server using the apollo-server-plugin-response-cache plugin and I need to determine whether or not I'm going to write to the cache based on incoming parameters. I have the plugin set up and I'm using the shouldWriteToCache hook. I can print out the GraphQLRequestContext object that gets passed into the hook, and I can see the full request source, but request.variables is empty. Other than parsing the query itself, how can I access the actual params for the resolver in this hook? (In the example below, I need the value of param2.)

Apollo Server:

new ApolloServer({
    introspection: true,
    playground: true,
    subscriptions: false,
    typeDefs,
    resolvers,
    cacheControl: {
        defaultMaxAge: 60
    },
    plugins: [
        apolloServerPluginResponseCache({
            cache,  // This is a "apollo-server-cache-redis" instance
            shouldWriteToCache: (requestContext) => {
                
                // I get a lot of info here, including the source query, but not the 
                // parsed out query variables
                console.log(requestContext.request);
                
                // What I want to do here is:
                return !context.request.variables.param2
                // but `variables` is empty, and I can't see that value parsed anywhere else
            }
        })
    ]
})

Here is what I get logged out from the code above:

{
  query: '{\n' +
    '  exapi(param1: "value1", param2: true) {\n' +
    '    records\n' +
    '  }\n' +
    '}\n',
  operationName: null,
  variables: {},            // <-- this is empty?! How can I get param2's value??
  extensions: undefined,
  http: Request {
    size: 0,
    timeout: 0,
    follow: 20,
    compress: true,
    counter: 0,
    agent: undefined,
    [Symbol(Body internals)]: { body: null, disturbed: false, error: null },
    [Symbol(Request internals)]: {
      method: 'POST',
      redirect: 'follow',
      headers: [Headers],
      parsedURL: [Url],
      signal: null
    }
  }
}


from Apollo GraphQL Server - Access query params from cache plugin

Session cookie set `SameSite=None; Secure;` does not work

I added SameSite=None; Secure; to set-cookie. but the cookie was not set and I can’t log in to my site.

response.writeHead(200, {
  'Content-Type': 'application/json',
  'Set-Cookie': 'token=' + token + '; SameSite=None; Secure; Expires=' + time.toUTCString() + '; Path=/' + '; Domain=' + hostname,
  'csrf-token': csrfToken
});

I reviewed the cookie in developer tools under Application>Storage>Cookies and see more details. it showed a warning message:

this set-cookie was blocked because it was not sent over a secure connection

chrome blockes cookies, Because I work on the development environment and i send http request. But this test on Firefox browser logs in correctly.
I put the word secure inside the cookie and it worked properly, but because the word secure must be used next to samesite = none for cross-origin, otherwise the cookie will be blocked.
My question is why when I use secure, only the Chrome browser blocks the cookie, but it is true in other browsers. And that if I do not use secure I can not test the payment gateway because it blocks Chrome cross-orign if I do not use secure...



from Session cookie set `SameSite=None; Secure;` does not work