Saturday, 30 November 2019

Multivariate time series forecasting with 3 months dataset

I have 3 months of data (each row corresponding to each day) generated and I want to perform a multivariate time series analysis for the same :

the columns that are available are -

Date    Capacity_booked Total_Bookings  Total_Searches  %Variation

Each Date has 1 entry in the dataset and has 3 months of data and I want to fit a multivariate time series model to forecast other variables as well.

So far, this was my attempt and I tried to achieve the same by reading articles.

I did the same -

df['Date'] = pd.to_datetime(Date , format = '%d/%m/%Y')

data = df.drop(['Date'], axis=1)

data.index = df.Date

from statsmodels.tsa.vector_ar.vecm import coint_johansen
johan_test_temp = data
coint_johansen(johan_test_temp,-1,1).eig



#creating the train and validation set
train = data[:int(0.8*(len(data)))]
valid = data[int(0.8*(len(data))):]

freq=train.index.inferred_freq

from statsmodels.tsa.vector_ar.var_model import VAR

model = VAR(endog=train,freq=train.index.inferred_freq)
model_fit = model.fit()


# make prediction on validation
prediction = model_fit.forecast(model_fit.data, steps=len(valid))

cols = data.columns

pred = pd.DataFrame(index=range(0,len(prediction)),columns=[cols])
    for j in range(0,4):
        for i in range(0, len(prediction)):
           pred.iloc[i][j] = prediction[i][j]

I have a validation set and prediction set. However the predictions are way worse than expected.

The plots of the dataset are - 1. % Variation enter image description here

  1. Capacity_Booked enter image description here

  2. Total bookings and searches enter image description here

The output that I am receiving are -

Prediction dataframe -

enter image description here

Validation Dataframe -

enter image description here

As you can see that predictions are way off what is expected. Can anyone advise a way to improve the accuracy. Also, if I fit the model on whole data and then print the forecasts, it doesn't take into account that new month has started and hence to predict as such. How can that be incorporated in here. any help is appreciated.

EDIT

Link to the dataset - Dataset

Thanks



from Multivariate time series forecasting with 3 months dataset

Intercepting any request - javascript

I have a web page say - sample-page.html with 2 links in it -

sample-page.html
- link1 (GET, ajax)
- link 2 (GET, new page)

When I click link1 an ajax GET request is executed and it still stays at the sample-page.html.When I click link2 another get request is executed and a new page sample-page2 will appear.

To intercept both requests I've written a javascript code like this -

    //attempt-1 : javascript
    (function (send) {

        XMLHttpRequest.prototype.send = function () {
            this.setRequestHeader('some-header-param', 'some-value');
            send.apply(this, arguments);
        };

    })(XMLHttpRequest.prototype.send);

    //attempt-2: jquery 
    /*$.ajaxSetup({
        beforeSend: function (xhr,settings) {
           xhr.setRequestHeader('some-header', 'some-header-value');
       }
      }); */

The above, both attempts successfully able to intercept the ajax GET request from link1. But neither of the above code snippets can't able to intercept the request from link2. Can anyone help how to intercept both requests?

Thanks in advance.



from Intercepting any request - javascript

Script dont fuction properly

I have an script that reads the file and compares the string by a pattern, if it returns false it will delete the line on the .txt file.

This is my code

const readline = require('readline');
const lineReplace = require('line-replace')
const fs = require('fs');
const inputFileName = './outputfinal.txt';

const readInterface = readline.createInterface({
    input: fs.createReadStream(inputFileName),
});

let testResults = [];
readInterface.on('line', line => {
    testResult = test(line);
    console.log(`Test result (line #${testResults.length+1}): `, testResult);
    testResults.push({ input: line, testResult } );
    if (testResult == false){
        console.log(`Line #${testResults.length} will get deleted from this list`);
        lineReplace({
          file: './outputfinal.txt',
          line: testResults.length,
          text: '',
          addNewLine: false,
          callback: onReplace   
        });

        function onReplace({file, line, text, replacedText}) {

        };
    };
});

// You can do whatever with the test results here.
//readInterface.on('close', () => {
//    console.log("Test results:", testResults);
//});

function test(str){

    let regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; // email regex

    str = str.split(","); 

    // string should be of length 3 with str[1] number of length 7
    if(str && str.length === 3 && Number(str[1]) && str[1] ) {

        let temp = str[0].split("-");

        // check for 85aecb80-ac00-40e3-813c-5ad62ee93f42 separately.
        if(temp && temp.length === 5 &&  /[a-zA-Z\d]{8}/.test(temp[0]) &&  /[a-zA-Z\d]{4}/.test(temp[1]) &&  /[a-zA-Z\d]{4}/.test(temp[2]) &&  /[a-zA-Z\d]{4}/.test(temp[3]) &&  /[a-zA-Z\d]{12}/.test(temp[4])){

            // email regex
            if(regex.test(str[2])) {
                return true;
            } else {
                return false;
            }
        } else { 
            return false
        }
    } else {
        return false;
    }
}

But isn't working, returns error no such file or directory, I dont think that is the correct way to do a line remover script



from Script dont fuction properly

How to hid ngx-simple-modal by clicking outside of modal component in angular7?

I am using ngx-simple-modal plugin in angular7 app and i want to close modal when user click outside of modal component? I tried this

this.SimpleModalService.addModal(LinkPopupComponent, {title: 'Alert title!', message: 'Alert message!!!'},{ closeOnClickOutside: true });

i used this { closeOnClickOutside: true } option to close modal when user will outside of modal component as described in documentation. But still modal is not closing after clicking outside of it. How can i do that?



from How to hid ngx-simple-modal by clicking outside of modal component in angular7?

Adding App Events in iOS app produces undeclared identifier 'AppEvent'

I am trying to add facebook app events, and I installed FacebookSDK. Then I have next code:

import FacebookCore

static func logViewContentEvent(contentType : String, contentData : String, contentId : String, currency : String, price : Double) {
        let params : AppEvent.ParametersDictionary = [
            .contentType : contentType,
            .content : contentData,
            .contentId : contentId,
            .currency : currency
        ]
        let event = AppEvent(name: .viewedContent, parameters: params, valueToSum: price)
        AppEventsLogger.log(event)
    }

But I get error from the title. What I am doing wrong, and why this type is missing?



from Adding App Events in iOS app produces undeclared identifier 'AppEvent'

reading in a file from ubuntu on local machine?

I have a python script which I'm running on AWS (EC2 instance with Ubuntu). This python script outputs a JSON file daily, to a directory in /home/ubuntu:

with open("/home/ubuntu/bandsintown/sf_events.json", "w") as writeJSON:
file_str = json.dumps(allEvents, sort_keys=True)
file_str = "var sf_events = " + file_str

All works as expected here. My issue is that I'm unsure of how to read this JSON (existing on ubuntu) into a javascript file that I'm running on my local machine.

Javascript can't find the file if I call the file from ubuntu:

<script src="/home/ubuntu/bandsintown/sf_events.json"></script>

In other words, I'd like to read in the JSON that I've created in the cloud, to a file that exists on my local machine. Should I output the JSON somewhere other than home/ubuntu? Or, can my local file somehow recognize /home/ubuntu as a file location?

Thanks in advance.



from reading in a file from ubuntu on local machine?

slow down spoken audio (not from mp3/wav) using python

I need to slow down short bursts of spoken audio, captured over a mic and then play it out in realtime in a python script. I can capture and playback audio fine without changing the speed using an input and an output stream using PyAudio but I can't work out how to slow it down.

I've seen this post which uses pydub does something similar for audio from a file but can't work out how to modify it for my purposes.

Just to stress the key point from the question title, "(not from mp3/wav or any other file type)" as I want to do this in realtime with short bursts, idealy ~0.1s so just want to work with data read in from a PyAudio stream.

Does anyone who has experience with pydub know if it might do what I need?

NB I realise that the output would lag further and further behind and that there might be buffering issues however I'm just doing this for short bursts of upto 30 seconds and only want to slow the speech down by ~10%.



from slow down spoken audio (not from mp3/wav) using python

stripe: Create a 30-day trial subscription charge on a saved card but allow user to upgrade and start charging immediately?

So before a user can create an account I want to save their credit card to charge a subscription with 30 day trial AND the ability to immediately charge the card for a subscription if the user demands it.

so my logic is to

1) create a customer

2) add payment details for customer

3) create subscription with 30 day trial

4) activate subscription upon user upgrade action

I'm not clear on how 4) is possible. I get that on 3), after 30 days, they are on a subscription. but what if the customer wants to start using the full version immediately before the trial is over, how would I create a charge for the subscription?

const stripe = require('stripe')('sk_test_asdfasdf');
(async () => {
  // Create a Customer:
stripe.customers.create({
  email: 'jenny.rosen@example.com',
  payment_method: 'pm_1FWS6ZClCIKljWvsVCvkdyWg',
  invoice_settings: {
    default_payment_method: 'pm_1FWS6ZClCIKljWvsVCvkdyWg',
  },
}, function(err, customer) {
  // asynchronously called
});

//create subscription
stripe.subscriptions.create({
  customer: 'cus_4fdAW5ftNQow1a',
  items: [
    {
      plan: 'plan_CBXbz9i7AIOTzr',
    },
  ],
  expand: ['latest_invoice.payment_intent'],
}, function(err, subscription) {
    // asynchronously called
  }
);

})();


from stripe: Create a 30-day trial subscription charge on a saved card but allow user to upgrade and start charging immediately?

How to implement parallel, delayed in such a way that the parallelized for loop stops when output goes below a threshold?

Suppose I have the following code:

from scipy import *
import multiprocessing as mp
num_cores = mp.cpu_count()
from joblib import Parallel, delayed
import matplotlib.pyplot as plt

def func(x,y):
    return y/x
def main(y, xmin,xmax, dx):
    x = arange(xmin,xmax,dx)
    output = Parallel(n_jobs=num_cores)(delayed(func)(i, y) for i in x)
    return x, asarray(output)
def demo():
    x,z = main(2.,1.,30.,.1)
    plt.plot(x,z, label='All values')
    plt.plot(x[z>.1],z[z>.1], label='desired range') ## This is better to do in main()
    plt.show()

demo()

I want to calculate output only until output > a given number (it can be assumed that elements of output decreases monotonically with increase of x) and then stop (NOT calculating for all values of x and then sorting, that's inefficient for my purpose). Is there any way to do that using Parallel, delayed or any other multiprocessing?



from How to implement parallel, delayed in such a way that the parallelized for loop stops when output goes below a threshold?

Find Notch Cutout Type on Android

How can I get the notch cutout type of a device ?

You can get the safe edge insets for all the sides to make sure that the notch (if there) is not covering any parts of the UI. (This is only important if you enable the app to also fill the given space to the left and right of the notch by e.g. setting the window flag LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES.)

In the android developer options you can simulate a display-cutout by choosing between:

  • (None)
  • Corner display cutout
  • (Double display cutout)
  • Tall display cutout

These options are just to simulate but they also provide the same information as if the device really had the chosen cutout as far as I can tell, so there should also be a way to find the set type.

Most of the UI in my case (but also in general in many cases) is centered horizontally without really touching the corners of the screen.

I would like to differentiate between the "corner"- and the "tall"-cutout as the corner is not really occupying important parts of the screen in my case. -> If the screen is a corner-cutout, I can neglect the safe edge insets.

As a visual example: The upper screen is from the Samsung Galaxy S10 with a corner cutout, the lower one is the Google Pixel 3 with a tall-cutout:

Cutout types visually.

The "-Example-" is fitting on the corner-cutout screen, while it is covered by the tall cutout.

Thanks!



from Find Notch Cutout Type on Android

Node.js - JWT, Passport.js, API, Authentication: How To Implement Multiple Passport.js Middleware?

So I am trying to build two JWT authentication systems for one app. One for the users and one for businesses. The authentication uses passport (local and JWT). I started working on the user aspect of the authentication and I was able to make it work as I wanted. I thought it would be the same for business. All I did was simply copy paste and change few variable. Normally the business endpoints should work but it does not. So I tried to debug what was going on and I am still trying to figure out what it is. My guess is that when I load the strategies in my app.js, only the passport strategies for users get called. If I permute positions between passport and business-passport, everything breaks.

Here is my code.

Passport Middleware For User passport.js

const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const {ExtractJwt} = require('passport-jwt');
const LocalStrategy = require('passport-local').Strategy;
const { JWT_SECRET } = require('./config');
const User = require('./models/user');
// const Business = require('./models/business');

passport.use(new JwtStrategy({
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: JWT_SECRET,
    passReqToCallback: true
}, async (req, payload, done) => {
    console.log('payload', payload)

    try {
        // Find the user specified in token
        const user = await User.findById(payload.sub);

        // Handle if User dont exist
        if (!user) {
            return done(null, false);
        }

        // Otherwise, return the user
        req.user = user;
        done(null, user);
    } catch (error) {
        done(error, false);
    }

}));
// Local Strategy
passport.use(new LocalStrategy({
    usernameField: 'email'
}, async (email, password, done) => {

    try {
        // Find the user given the email
        const user = await User.findOne({email});

        // If not, handle it
        if (!user) {
            return done(null, false);
        }

        // check if password is correct

        const isMatch = await user.isValidPassword(password);

        // if not, handle it
        if (!isMatch) {
            return done(null, false);
        }

        // Otherwise, return the user
        done(null, user);

    } catch (error) {
        done(error, false);
    }

}));

Passport Middleware For Business passport-business.js

Just change User for Business

Controllers for Users controllers/user.js

const fs = require('fs');
const mongoose = require('mongoose');
const JWT = require('jsonwebtoken');
const { JWT_SECRET } = require('../config');

const User = require('../models/user');

signToken = user => {
    // Respond with token
    return JWT.sign({
        iss: 'My Business, Inc.',
        userType: 'users',
        sub: user._id, /* You can also use newUser.id */
        iat: new Date().getTime(), /* Current Time */
        exp: new Date().setDate(new Date().getDate() + 1), /* Current Time + 1 day ahead */
    }, JWT_SECRET);
};

module.exports = {

    signup: async (req, res, next) => {
        console.log('req.value.body', req.value.body);

        const {email, password} = req.value.body;

        // Check if User already exist by email address
        const foundUser = await User.findOne({email});
        if(foundUser) {
            return res.status(403).json({error: 'Email is already in use'});
        }

        // Create a new User
        const newUser = new User({email, password});
        await newUser.save();

        // Generate the token
        const token = signToken(newUser);

        // Respond with token
        res.status(200).json({token});
    },
    signin: async (req, res, next) => {
        // Generate token
        const token = signToken(req.user);
        res.status(200).json({token});
        // console.log('signin');
    },
};

The reason why I have req.value... is because of a middleware that I used to validate my body and url params.

Controllers for Business controllers/business.js . Everything is the same, just change User with Business.

I should also point out that whenever I use jwt.io to see if my token signature is valid, it always says invalid signature, but everything works on my application as expected. Wondering why it is saying invalid signature.

Routes for Users routes/user.js . Please remember that it is the same for Business.

const express = require('express');

// this router deals better with "try{} catch{}" situations"
const router = require('express-promise-router')();

const passport = require('passport');

const UserController = require('../controllers/user');

require('../passport');

const { validateBody, schemas, validateParam } = require('../helpers/route-helpers');

const StrategyLocal = passport.authenticate('local', {session: false});
const StrategyJWT = passport.authenticate('jwt', {session: false});

router.get('/', (req, res) => {

    res.json({message: "Welcome to our User's API Endpoint!"});
});

router.route('/signup')
    // .get(UserController.index)
    .post([validateBody(schemas.authSchema)], UserController.signup);
router.route('/signin')
    // Makes sense to implement localstrat here because jWt will always work because the user was issued a token at signup
    // So both solutions will work here as a strategy
    .post(validateBody(schemas.authSchema), StrategyLocal, UserController.signin);

module.exports = router;   

And finally, the file that I think is causing the problem... Introducing...
app.js

const express = require('express');
const logger = require('morgan');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const path = require('path');
const cors = require('cors');

const { dbName } = require('./config');

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/' + dbName, {
    useNewUrlParser:true,
    useUnifiedTopology:true,
    useCreateIndex: true,
    useFindAndModify: false
});

const app = express();

// 👇👇👇👇 This is where the problem is happening in my opinion
require('./passport-business')
require('./passport')


const user = require('./routes/user');
const business = require('./routes/business');

// Middlewares
// set the static files location /public/img will be /img for users
app.use(logger('dev'));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(bodyParser.json());

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, noauth");
    if (req.method === 'OPTIONS'){
        res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, OPTIONS");
        res.setHeader('Access-Control-Allow-Credentials', false);
        return res.status(200).json({});
    }
    next();
});

app.use('/api/users', user);
app.use('/api/businesses', business);


// Start the server

const port =  app.get('port') || 2019;
app.listen(port, () => console.log(`Server is listening on port ${port}`));

If I keep everything as is, all User endpoints work, signup works for Business, but I get 401 when I try to signin (Business). But if I do this...

require('./passport')
require('./passport-business')    

I get 401 when I try to signin (User) and I get 500 when I try to signin (Business).
Can someone tell me what I am doing wrong here? Maybe it is the order in which I load these files in app.js. Maybe it is the fact that I am creating two separate passport files for User and Business. I would love to know how to combine those two into one. .



from Node.js - JWT, Passport.js, API, Authentication: How To Implement Multiple Passport.js Middleware?

All elements children as select options

fiddle: https://jsfiddle.net/7qr0pLxj/

How can I show all of an element's children as select options? (select options goal is to select a single object but also an array without any duplicates)

Here's an example, the list should show something like this.....

svg > defs
svg > g
svg > g > rect
svg > g > g
svg > g > g:nth-child(0)
svg > g > g:nth-child(1)
svg > g > g:nth-child(2)
svg > g > g:nth-child(0) > ellipse
svg > g > g > g
svg > g > g > g:nth-child(2)
svg > g > g:nth-child(0) > g
svg > g > g:nth-child(0) > g > circle
svg > g > g:nth-child(0) > g > circle > path:nth-child(0)
svg > g > g:nth-child(0) > path

$(".vector svg").each(function() {
  $.each(this.children, function(i) {
    $("#getItems").append("<option>svg > "+ this.tagName +"</option>");
    $("#getItems").append("<option>svg > "+ this.tagName + ":nth-child("+ i +")" +"</option>");
    var str = this.tagName;
    $("#getItems").append("<option>svg > "+ str +" > "+ this.tagName +"</option>");

    // has children
    if (this.children) {
      $.each(this.children, function(i) {
        $("#getItems").append("<option>svg > "+ str +" > "+ this.tagName + ":nth-child("+ i +")" +"</option>");
      });
      var str = this.tagName;
      $("#getItems").append("<option>svg > "+ str +" > "+ this.tagName +"</option>");
      
      // are there more children?
      if (this.children) {
        $.each(this.children, function(i) {
          $("#getItems").append("<option>svg > "+ str +" > "+ this.tagName + ":nth-child("+ i +")" +"</option>");
        });
      }
    }
  });
});
<select id="getItems"></select>

<div class="vector">
  <!--?xml version="1.0" encoding="UTF-8" standalone="no"?-->
  <!-- Generator: Gravit.io -->
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="0 0 1080 1080">
    <defs>
      <clipPath id="_clipPath_MxF8Dkiwk1DE61ESpuAKmuW45DuiKU6M">
        <rect width="1080" height="1080"></rect>
      </clipPath>
    </defs>
    <g clip-path="url(#_clipPath_MxF8Dkiwk1DE61ESpuAKmuW45DuiKU6M)">
      <rect x="0" y="0" width="1080" height="1080" transform="matrix(1,0,0,1,0,0)" fill="rgb(255,233,75)"></rect>
      <g>
        <ellipse cx="-230.50000000000034" cy="759.5" rx="340.49999999999966" ry="79.50000000000011" fill="rgb(251,201,57)"></ellipse>
        <g>
          <circle cx="-230.5000000000004" cy="772.0000000000001" r="257.99999999999994" fill="rgb(51,48,94)"></circle>
          <path d="M -361.2 470.15 L -101.8 470.15 C -91.424 470.15 -83 478.574 -83 488.95 L -83 488.95 C -83 499.326 -91.424 507.75 -101.8 507.75 L -361.2 507.75 C -371.576 507.75 -380 499.326 -380 488.95 L -380 488.95 C -380 478.574 -371.576 470.15 -361.2 470.15 Z" style="stroke:none;fill:#F38D63;stroke-miterlimit:10;"></path>
          <path d="M -231.5 312 L -231.5 312 C -162.787 312 -107 367.787 -107 436.5 L -107 570.5 C -107 639.213 -162.787 695 -231.5 695 L -231.5 695 C -300.213 695 -356 639.213 -356 570.5 L -356 436.5 C -356 367.787 -300.213 312 -231.5 312 Z" style="stroke:none;fill:#5E433C;stroke-miterlimit:10;"></path>
          <path d=" M -233.068 335 L -229.932 335 C -170.049 335 -121.432 383.617 -121.432 443.5 L -121.432 522 C -192.811 575.333 -266.179 575.343 -341.568 522 L -341.568 443.5 C -341.568 383.617 -292.951 335 -233.068 335 Z " fill="rgb(246,168,117)"></path>
          <ellipse cx="-229.49999999999994" cy="556.9999999999999" rx="55.50000000000006" ry="33" fill="rgb(94,67,60)"></ellipse>
          <circle cx="-270" cy="494.00000000000006" r="15" fill="rgb(47,52,59)"></circle>
          <circle cx="-189" cy="494.00000000000006" r="15" fill="rgb(47,52,59)"></circle>
          <path d="M -229 475 L -229 475 C -218.514 475 -210 483.514 -210 494 L -210 521.5 C -210 531.986 -218.514 540.5 -229 540.5 L -229 540.5 C -239.486 540.5 -248 531.986 -248 521.5 L -248 494 C -248 483.514 -239.486 475 -229 475 Z" style="stroke:none;fill:#F38E65;stroke-miterlimit:10;"></path>
          <path d=" M -108.403 417.94 C -117.354 358.012 -169.096 312 -231.5 312 L -231.5 312 C -293.904 312 -345.646 358.012 -354.597 417.94 C -318.826 429.713 -276.644 436.5 -231.5 436.5 C -186.356 436.5 -144.174 429.713 -108.403 417.94 Z " fill="rgb(94,67,60)"></path>
          <path d=" M -258 557 L -201 557 L -201 568.5 C -201 580.366 -210.634 590 -222.5 590 L -236.5 590 C -248.366 590 -258 580.366 -258 568.5 L -258 557 Z " fill="rgb(255,254,255)"></path>
        </g>
        <path d=" M -571 759.5 L -571 1080 L 110 1080 L 110 759.5 L 110 759.5 C 110 803.377 -42.573 839 -230.5 839 C -418.427 839 -571 803.377 -571 759.5 L -571 759.5 Z " fill="rgb(255,233,75)"></path>
      </g>
      <g>
        <ellipse cx="539.9999999999998" cy="759.5" rx="340.4999999999998" ry="79.50000000000011" fill="rgb(251,201,57)"></ellipse>
        <g>
          <circle cx="539.9999999999998" cy="772" r="258" fill="rgb(51,48,94)"></circle>
          <path d="M 409.3 470.15 L 668.7 470.15 C 679.076 470.15 687.5 478.574 687.5 488.95 L 687.5 488.95 C 687.5 499.326 679.076 507.75 668.7 507.75 L 409.3 507.75 C 398.924 507.75 390.5 499.326 390.5 488.95 L 390.5 488.95 C 390.5 478.574 398.924 470.15 409.3 470.15 Z" style="stroke:none;fill:#F38D63;stroke-miterlimit:10;"></path>
          <path d="M 539 312 L 539 312 C 607.713 312 663.5 367.787 663.5 436.5 L 663.5 570.5 C 663.5 639.213 607.713 695 539 695 L 539 695 C 470.287 695 414.5 639.213 414.5 570.5 L 414.5 436.5 C 414.5 367.787 470.287 312 539 312 Z" style="stroke:none;fill:#5E433C;stroke-miterlimit:10;"></path>
          <path d=" M 537.432 335 L 540.568 335 C 600.451 335 649.068 383.617 649.068 443.5 L 649.068 522 C 577.689 575.333 504.321 575.343 428.932 522 L 428.932 443.5 C 428.932 383.617 477.549 335 537.432 335 Z " fill="rgb(246,168,117)"></path>
          <ellipse cx="541.0000000000002" cy="557" rx="55.50000000000003" ry="33" fill="rgb(94,67,60)"></ellipse>
          <circle cx="500.5" cy="494.00000000000006" r="15" fill="rgb(47,52,59)"></circle>
          <circle cx="581.5" cy="494.00000000000006" r="15" fill="rgb(47,52,59)"></circle>
          <path d="M 541.5 475 L 541.5 475 C 551.986 475 560.5 483.514 560.5 494 L 560.5 521.5 C 560.5 531.986 551.986 540.5 541.5 540.5 L 541.5 540.5 C 531.014 540.5 522.5 531.986 522.5 521.5 L 522.5 494 C 522.5 483.514 531.014 475 541.5 475 Z" style="stroke:none;fill:#F38E65;stroke-miterlimit:10;"></path>
          <path d=" M 662.097 417.94 C 653.146 358.012 601.404 312 539 312 L 539 312 C 476.596 312 424.854 358.012 415.903 417.94 C 451.674 429.713 493.856 436.5 539 436.5 C 584.144 436.5 626.326 429.713 662.097 417.94 Z " fill="rgb(94,67,60)"></path>
          <path d=" M 512.5 557 L 569.5 557 L 569.5 568.5 C 569.5 580.366 559.866 590 548 590 L 534 590 C 522.134 590 512.5 580.366 512.5 568.5 L 512.5 557 Z " fill="rgb(255,254,255)"></path>
        </g>
        <path d=" M 199.5 759.5 L 199.5 1080 L 880.5 1080 L 880.5 759.5 L 880.5 759.5 C 880.5 803.377 727.927 839 540 839 C 352.073 839 199.5 803.377 199.5 759.5 L 199.5 759.5 Z " fill="rgb(255,233,75)"></path>
      </g>
      <g>
        <ellipse cx="1310.4999999999993" cy="759.5" rx="340.4999999999998" ry="79.50000000000011" fill="rgb(251,201,57)"></ellipse>
        <g>
          <circle cx="1310.4999999999995" cy="1299" r="258" fill="rgb(51,48,94)"></circle>
          <path d="M 1179.8 997.15 L 1439.2 997.15 C 1449.576 997.15 1458 1005.574 1458 1015.95 L 1458 1015.95 C 1458 1026.326 1449.576 1034.75 1439.2 1034.75 L 1179.8 1034.75 C 1169.424 1034.75 1161 1026.326 1161 1015.95 L 1161 1015.95 C 1161 1005.574 1169.424 997.15 1179.8 997.15 Z" style="stroke:none;fill:#F38D63;stroke-miterlimit:10;"></path>
          <path d="M 1309.5 839 L 1309.5 839 C 1378.213 839 1434 894.787 1434 963.5 L 1434 1097.5 C 1434 1166.213 1378.213 1222 1309.5 1222 L 1309.5 1222 C 1240.787 1222 1185 1166.213 1185 1097.5 L 1185 963.5 C 1185 894.787 1240.787 839 1309.5 839 Z" style="stroke:none;fill:#5E433C;stroke-miterlimit:10;"></path>
          <path d=" M 1307.932 862 L 1311.068 862 C 1370.951 862 1419.568 910.617 1419.568 970.5 L 1419.568 1049 C 1348.189 1102.333 1274.821 1102.343 1199.432 1049 L 1199.432 970.5 C 1199.432 910.617 1248.049 862 1307.932 862 Z " fill="rgb(246,168,117)"></path>
          <ellipse cx="1311.5" cy="1084" rx="55.5" ry="33" fill="rgb(94,67,60)"></ellipse>
          <circle cx="1271" cy="1021" r="15" fill="rgb(47,52,59)"></circle>
          <circle cx="1352.0000000000005" cy="1021" r="15" fill="rgb(47,52,59)"></circle>
          <path d="M 1312 1002 L 1312 1002 C 1322.486 1002 1331 1010.514 1331 1021 L 1331 1048.5 C 1331 1058.986 1322.486 1067.5 1312 1067.5 L 1312 1067.5 C 1301.514 1067.5 1293 1058.986 1293 1048.5 L 1293 1021 C 1293 1010.514 1301.514 1002 1312 1002 Z" style="stroke:none;fill:#F38E65;stroke-miterlimit:10;"></path>
          <path d=" M 1432.597 944.94 C 1423.646 885.012 1371.904 839 1309.5 839 L 1309.5 839 C 1247.096 839 1195.354 885.012 1186.403 944.94 C 1222.174 956.713 1264.356 963.5 1309.5 963.5 C 1354.644 963.5 1396.826 956.713 1432.597 944.94 Z " fill="rgb(94,67,60)"></path>
          <path d=" M 1283 1084 L 1340 1084 L 1340 1095.5 C 1340 1107.366 1330.366 1117 1318.5 1117 L 1304.5 1117 C 1292.634 1117 1283 1107.366 1283 1095.5 L 1283 1084 Z " fill="rgb(255,254,255)"></path>
        </g>
        <path d=" M 970 759.5 L 970 1080 L 1651 1080 L 1651 759.5 L 1651 759.5 C 1651 803.377 1498.427 839 1310.5 839 C 1122.573 839 970 803.377 970 759.5 L 970 759.5 Z " fill="rgb(255,233,75)"></path>
      </g>
      <g>
        <ellipse cx="2080.999999999999" cy="759.5" rx="340.49999999999966" ry="79.50000000000011" fill="rgb(251,201,57)"></ellipse>
        <g>
          <circle cx="2080.999999999999" cy="1299" r="258" fill="rgb(51,48,94)"></circle>
          <path d="M 1950.3 997.15 L 2209.7 997.15 C 2220.076 997.15 2228.5 1005.574 2228.5 1015.95 L 2228.5 1015.95 C 2228.5 1026.326 2220.076 1034.75 2209.7 1034.75 L 1950.3 1034.75 C 1939.924 1034.75 1931.5 1026.326 1931.5 1015.95 L 1931.5 1015.95 C 1931.5 1005.574 1939.924 997.15 1950.3 997.15 Z" style="stroke:none;fill:#F38D63;stroke-miterlimit:10;"></path>
          <path d="M 2080 839 L 2080 839 C 2148.713 839 2204.5 894.787 2204.5 963.5 L 2204.5 1097.5 C 2204.5 1166.213 2148.713 1222 2080 1222 L 2080 1222 C 2011.287 1222 1955.5 1166.213 1955.5 1097.5 L 1955.5 963.5 C 1955.5 894.787 2011.287 839 2080 839 Z" style="stroke:none;fill:#5E433C;stroke-miterlimit:10;"></path>
          <path d=" M 2078.432 862 L 2081.568 862 C 2141.451 862 2190.068 910.617 2190.068 970.5 L 2190.068 1049 C 2118.689 1102.333 2045.321 1102.343 1969.932 1049 L 1969.932 970.5 C 1969.932 910.617 2018.549 862 2078.432 862 Z " fill="rgb(246,168,117)"></path>
          <ellipse cx="2082" cy="1084" rx="55.5" ry="33" fill="rgb(94,67,60)"></ellipse>
          <circle cx="2041.5" cy="1021" r="15.000000000000114" fill="rgb(47,52,59)"></circle>
          <circle cx="2122.5" cy="1021" r="15" fill="rgb(47,52,59)"></circle>
          <path d="M 2082.5 1002 L 2082.5 1002 C 2092.986 1002 2101.5 1010.514 2101.5 1021 L 2101.5 1048.5 C 2101.5 1058.986 2092.986 1067.5 2082.5 1067.5 L 2082.5 1067.5 C 2072.014 1067.5 2063.5 1058.986 2063.5 1048.5 L 2063.5 1021 C 2063.5 1010.514 2072.014 1002 2082.5 1002 Z" style="stroke:none;fill:#F38E65;stroke-miterlimit:10;"></path>
          <path d=" M 2203.097 944.94 C 2194.146 885.012 2142.404 839 2080 839 L 2080 839 C 2017.596 839 1965.854 885.012 1956.903 944.94 C 1992.674 956.713 2034.856 963.5 2080 963.5 C 2125.144 963.5 2167.326 956.713 2203.097 944.94 Z " fill="rgb(94,67,60)"></path>
          <path d=" M 2053.5 1084 L 2110.5 1084 L 2110.5 1095.5 C 2110.5 1107.366 2100.866 1117 2089 1117 L 2075 1117 C 2063.134 1117 2053.5 1107.366 2053.5 1095.5 L 2053.5 1084 Z " fill="rgb(255,254,255)"></path>
        </g>
        <path d=" M 1740.5 759.5 L 1740.5 1080 L 2421.5 1080 L 2421.5 759.5 L 2421.5 759.5 C 2421.5 803.377 2268.927 839 2081 839 C 1893.073 839 1740.5 803.377 1740.5 759.5 L 1740.5 759.5 Z " fill="rgb(255,233,75)"></path>
      </g>
    </g>
  </svg>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


from All elements children as select options

Simple router with url parameter variables

I'm trying to make a simple router with url parameters for id's. eg localhost/profile/123 This works fine but if I remove preventDefault so that the links works as normal, or refresh the browser, or go directly to that same url, it does not work and the browser looks for the javascript file main.js in localhost/profile instead of the origin localhost. Routes without parameters works fine. What is happening here?

const router = async path => {

  if(!path) path = location.pathname

  const segment = route.split('/')

  path =  '/' + segment[1]
  const parameter = segment[2]

  const routes = {
    '/' : { handler: home },
    '/about' : { handler: about },
    '/profile' : { handler: profile },
  }

  render(html`
    <main>${await routes[path].handler(parameter ? parameter : '')}</main>
  `, document.body)
}



const main = async () => {

    await router()

    document.body.addEventListener('click', e => {

      e.preventDefault()

      if(e.target && e.target.nodeName == "A") {
        let path = e.target.pathname

        history.pushState({urlPath: path}, '', location.origin + path)
        onpopstate = () => router()

        router(path)
      }

    })
}

main()


from Simple router with url parameter variables

JQuery UI Datepicker - MaxDate exclude disabled days

I am trying to exclude disabled dates when counting MaxDate. I tried many ways but still doesn't work. Any suggestion?

02-12-2019 and Sundays has been disabled but the Maxdate include the disabled date. Maxdate should be 3 days which excludes disabled days and Maxdays starts by today. My goal is to add days if the days between today until max days has disabled. Add 1 day per disabled day

Update

Now i am able to Exclude sunday when counting maxdate but i still can't exclude the array date where it should add one more day after 02-12-2019.

Updated Code :(

<script>
var array = ["02-12-2019"]

//new

function includeDate(date) {

    return date.getDay() !== 7 && date.getDay() !== 0;
}

function getTomorrow(date) {
    return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
}

//prev

    $('input').datepicker(
        {
      defaultDate: "+1d",
      inline: true,
      showOtherMonths: true,
      changeMonth: true,
      selectOtherMonths: true,
      required: true,
      showOn: "focus",
      numberOfMonths: 1,
      minDate: 1,
    beforeShowDay: function(date) {
        var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
         var isDisabled = ($.inArray(string, array) != -1);
        return [includeDate(date)  && !isDisabled];
    },

    maxDate: (function(max) {
        var today = new Date();
        var nextAvailable = getTomorrow(today);
        var count = 0;
        var countz = 1;
        var newMax = 0;
        while(count < max) {
            if (includeDate(nextAvailable) ) {
                count++;
            }
            if (includeDate(nextAvailable) ) {
                countz++;
            }
            newMax++;
            nextAvailable = getTomorrow(nextAvailable);            
        }
        return newMax;
    })
    (3)
    });

http://jsfiddle.net/3o1dmvw5/96/



from JQuery UI Datepicker - MaxDate exclude disabled days

Different ways to optimize with GPU PyOpenCL a python code : extern function inside kernel GPU/PyOpenCL

I have used the following command to profile my Python code :

python2.7 -m cProfile -o X2_non_flat_multiprocessing_dummy.prof X2_non_flat.py

Then, I can visualize globally the repartition of different greedy functions :

enter image description here

As you can see, a lot of time is spent into Pobs_C and interpolate routine which corresponds to the following code snippet :

def Pobs_C(z, zi, zj, h_p, wm_p, wDE_p, w0_p, wa_p, C_IAp, A_IAp, n_IAp, B_IAp, E_T, R_T, DG_T_fid, DG_T, WGT_T, WT_T, WIAT_T, cl, P_dd_spec, RT500):
    cc = 0
    P_dd_ok = np.zeros(len(z_pk))
    while cc < len(z_pk):
        if ((cl+0.5)/RT500[cc] < 35 and (cl+0.5)/RT500[cc] > 0.0005):
            P_dd_ok[cc] = P_dd_spec[cc]((cl+0.5)/RT500[cc])
        cc=cc+1

    P_dd_ok = CubicSpline(z_pk, P_dd_ok)
    if paramo == 8:
        P_dd_ok = P_dd_ok(z)*(DG_T(z)/DG_T_fid(z))**2
    else:
        P_dd_ok = P_dd_ok(z)

    if paramo != 9 or paramo != 10 or paramo != 11:
        C_gg = c/(100.*h_p)*0.5*delta_zpm*np.sum((F_dd_GG(z[1:], zi, zj, h_p, wm_p, wDE_p, w0_p, wa_p, E_T(z[1:]), R_T(z[1:]), WGT_T[aa][1:], WGT_T[bb][1:], DG_T(z[1:]), P_dd_ok[1:]) + F_dd_GG(z[:-1], zi, zj, h_p, wm_p, wDE_p, w0_p, wa_p, E_T(z[:-1]), R_T(z[:-1]), WGT_T[aa][:-1], WGT_T[bb][:-1], DG_T(z[:-1]), P_dd_ok[:-1]))) + P_shot_GC(zi, zj)
    else:
        C_gg = 0.
    if paramo < 12:
        C_ee = c/(100.*h_p)*0.5*delta_zpm*(np.sum(F_dd_LL(z[1:], zi, zj, h_p, wm_p, wDE_p, w0_p, wa_p, E_T(z[1:]), R_T(z[1:]), WT_T[aa][1:], WT_T[bb][1:], DG_T(z[1:]), P_dd_ok[1:]) + F_dd_LL(z[:-1], zi, zj, h_p, wm_p, wDE_p, w0_p, wa_p, E_T(z[:-1]), R_T(z[:-1]), WT_T[aa][:-1], WT_T[bb][:-1], DG_T(z[:-1]), P_dd_ok[:-1])) + np.sum(F_IA_d(z[1:], zi, zj, h_p, wm_p, wDE_p, w0_p, wa_p, C_IAp, A_IAp, n_IAp, B_IAp, E_T(z[1:]), R_T(z[1:]), DG_T(z[1:]), WT_T[aa][1:], WT_T[bb][1:], WIAT_T[aa][1:], WIAT_T[bb][1:], P_dd_ok[1:]) + F_IA_d(z[:-1], zi, zj, h_p, wm_p, wDE_p, w0_p, wa_p, C_IAp, A_IAp, n_IAp, B_IAp, E_T(z[:-1]), R_T(z[:-1]), DG_T(z[:-1]), WT_T[aa][:-1], WT_T[bb][:-1], WIAT_T[aa][:-1], WIAT_T[bb][:-1], P_dd_ok[:-1])) + np.sum(F_IAIA(z[1:], zi, zj, h_p, wm_p, wDE_p, w0_p, wa_p, C_IAp, A_IAp, n_IAp, B_IAp, E_T(z[1:]), R_T(z[1:]), DG_T(z[1:]), WIAT_T[aa][1:], WIAT_T[bb][1:], P_dd_ok[1:]) + F_IAIA(z[:-1], zi, zj, h_p, wm_p, wDE_p, w0_p, wa_p, C_IAp, A_IAp, n_IAp, B_IAp, E_T(z[:-1]), R_T(z[:-1]), DG_T(z[:-1]), WIAT_T[aa][:-1], WIAT_T[bb][:-1], P_dd_ok[:-1]))) + P_shot_WL(zi, zj)
    else:
        C_ee = 0.
    C_gl = c/(100.*h_p)*0.5*delta_zpm*np.sum((F_dd_GL(z[1:], zi, zj, h_p, wm_p, wDE_p, w0_p, wa_p, C_IAp, A_IAp, n_IAp, B_IAp, E_T(z[1:]), R_T(z[1:]), DG_T(z[1:]), WGT_T[aa][1:], WT_T[bb][1:], WIAT_T[bb][1:], P_dd_ok[1:]) + F_dd_GL(z[:-1], zi, zj, h_p, wm_p, wDE_p, w0_p, wa_p, C_IAp, A_IAp, n_IAp, B_IAp, E_T(z[:-1]), R_T(z[:-1]), DG_T(z[:-1]), WGT_T[aa][:-1], WT_T[bb][:-1], WIAT_T[bb][:-1], P_dd_ok[:-1])))
    return C_gg, C_ee, C_gl

1) MAIN QUESTION : Is there a way to implement a GPU/OpenCL layer in this routine, especially for CubicSpline or the whole Pobs_C function. What are the alternatives that would allow me to reduce the time passed into Pobs_C and its inner function CubicSpline ?

I have few notions with OpenCL (not PyOpenCL) like for example the map-reduce method or solving Heat 2D equation with classical kernel.

2) PREVIOUS FEEDBACK :

I know that we can't have optimization by thinking naively that calling an extern function inside a kernel brings a higher speedup since GPU can achieve a lot of calls. Instead, I should rather put all the content of the different functions allow to get optimization : Do you agree with that and confirm it ? So, can I declare inside the kernel code a call to an extern function (I mean a function not inside kernel, i.e the classical part code (called Host code ?) ?

3) OPTIONAL QUESTION : Maybe can I declare this extern function inside the kernel : is it possible by doing explicitely this declaration inside ? Indeed, that could avoid to copy all the content of all functions potentially GPU-parallilzed.

Any idea/remark/advice would be great, Regards.

PS: Sorry if this is a general topic but it will allow me to see clearer about the available ways to include GPU/OpenCL in my code above and then optimize it.



from Different ways to optimize with GPU PyOpenCL a python code : extern function inside kernel GPU/PyOpenCL

Distinguish between lightning connector and 3.5mm headphone jack on iOS

I am doing some precise measurement of audio signals on iOS using the earphones.

The audio signals vary quite significantly depending on whether the earphones are plugged into the device's 3.5mm headphone-jack or the lightning connector (the lightning includes its own ADC/DAC unit I believe).

I am therefore looking for a way to determine which port the headphones are plugged in to – lightning or headphone-jack.

When inspecting the types of the current route's output port for both connections, they both return AVAudioSessionPortHeadphones, which doesn't quite give me the granularity I need.

for (AVAudioSessionPortDescription *outputPort in [currentRoute outputs])
{
    if ([[outputPort portType] isEqualToString:AVAudioSessionPortHeadphones])
    {
        ...
    }
}

Does anyone know of a way to determine which port the AVAudioSessionPortHeadphones are connected to?

Thanks, Andy.



from Distinguish between lightning connector and 3.5mm headphone jack on iOS

Friday, 29 November 2019

What css alternative can I use to the non-supported margin-top:auto using mpdf to emulate footer on a4 pages?

I am trying to generate 1:1 a4 pages from my primitive wyswyg to pdf using mpdf. So using this css:

#editor {
  background-color: gray;
  border: 1px black;
  padding: 1em 2em;
}

.page {
  background-color: white;
  border-style: solid;
  border-color: black;
  border-width: 1px;
  /*padding: 10em 2em;*/
  width: 595px;
  height: 841px;
  display: flex;
  flex-direction: column;
}

.content {
  word-wrap: break-word;
  overflow-wrap: break-word;
  white-space: normal;
  padding-left: 2cm;
  padding-bottom: 2cm;
  padding-top: 2cm;
  outline-color: white;
}

.header {
  background-color: red;
  text-align: center;
}

.footer {
  background-color: darkgray;
  margin-top: auto;
  height: 100px;
  page-break-after:right;
}

.brasao {
  height: 60px;
  width: 60px;
}

#template {
  display: none;
}

Applied on this HTML + JS: https://jsitor.com/FWvNJa7XN As you can see, using margin-top:auto on div footer, at least on web browsers, I was able to stick the footers on the bottom of each page.

But when I've tried to write using mpdf :

<?php

use Mpdf\Mpdf;
use Mpdf\Output\Destination;

include 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';

$mpdf = new Mpdf();

 //via JS as I able to send each page outerHTML separated on hidden values
$pages = $_REQUEST['pages'];

$mpdf = new \Mpdf\Mpdf([
    'mode' => 'utf-8',
    'format' => 'A4',
    'margin_left' => 0,
    'margin_right' => 0,
    'margin_top' => 0,
    'margin_bottom' => 0,
    'margin_header' => 0,
    'margin_footer' => 0,
    'dpi' => 72
]);

$stylesheet = file_get_contents('redator.css');
$mpdf->WriteHTML($stylesheet, \Mpdf\HTMLParserMode::HEADER_CSS);
foreach ($pages as $page) {
    $mpdf->WriteHTML($page);
}
$mpdf->Output();

On firefox the rendered was this (including the editor div): https://i.imgur.com/UJldBr9.png

But, using mpdf, the result was not the expected: https://www.docdroid.net/vP4QALq/mpdf.pdf

So, How can try to render 1:1 on mpdf?



from What css alternative can I use to the non-supported margin-top:auto using mpdf to emulate footer on a4 pages?

how to put button on top of android.support.design.widget.AppBarLayout?

I'm having a button that is on top of android.support.design.widget.AppBarLayout but the button stays behind it in the layout display and on the device how do i put the button in front of it ?

or in a different question how do i add a button next to the on screen options menu on the upper right side ?

here is my Layout XML >

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="apps.radwin.wintouch.activities.alignmentActivities.WorkordersSelectionActivity"
    tools:showIn="@layout/app_bar_workorders_selection">

    <Button
        android:id="@+id/filterButtonMainWorkorderSelection"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="50dp"

        android:layout_marginTop="20dp"
        android:background="@drawable/ic_filter_list_black_24dp"
        android:text=""
        android:textSize="30dp" />



    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="8dp"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay">

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabsLayoutWorkorderSelection"
            android:layout_width="match_parent"
            style="@style/TabLayoutStyle"
            android:layout_height="wrap_content"
            />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/workorderSelectionMainViewPagerContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:src="@drawable/add_workorders_plus"
        android:layout_marginLeft="@dimen/fab_margin"
        android:layout_marginRight="@dimen/fab_margin"
        android:layout_marginBottom="@dimen/fab_margin"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true" />



    <android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <android.support.v4.widget.NestedScrollView
            android:id="@+id/bottom_sheet"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clipToPadding="true"
            android:background="#293339"
            app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
            >

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toStartOf="@+id/fab">


                <TextView
                    android:id="@+id/workorderFilterPopup_showAllText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentTop="true"
                    android:layout_marginLeft="10dp"
                    android:gravity="center"
                    android:paddingTop="5dp"
                    android:text="SHOW ALL"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textColor="@color/white"
                    android:textSize="20dp" />

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="30dp"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentTop="true"
                    android:id="@+id/filter_menu_workorders_show_all"
                    android:background="@color/transparent"
                    android:layout_marginLeft="10dp"
                    android:paddingTop="5dp"
                    />

                <ImageView
                    android:id="@+id/workorderFilterPopup_showAllCheckMark"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_alignParentTop="true"
                    android:layout_marginRight="20dp"
                    android:layout_alignParentEnd="true"
                    android:src="@drawable/ic_done_black_24dp" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="2dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginLeft="10dp"
                    android:id="@+id/workorderFilterPopup_showAllTextLine"
                    android:background="@color/white"
                    android:layout_below="@+id/workorderFilterPopup_showAllText"
                    ></View>

                <ImageView
                    android:layout_width="35dp"
                    android:layout_height="35dp"
                    android:src="@drawable/ic_alarm_black_24dp"
                    android:id="@+id/workorderFilterPopup_plannedImage"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="20dp"
                    android:layout_below="@+id/workorderFilterPopup_showAllTextLine"
                    android:layout_alignParentStart="true" />

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="35dp"
                    android:id="@+id/filter_menu_workorders_planned"
                    android:background="@color/transparent"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="20dp"
                    android:layout_below="@+id/workorderFilterPopup_showAllTextLine"
                    android:layout_alignParentStart="true"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:text="Planned"
                    android:textColor="@color/white"
                    android:layout_marginLeft="20dp"
                    android:id="@+id/workorderFilterPopup_plannedText"
                    android:layout_alignBottom="@+id/workorderFilterPopup_plannedImage"
                    android:layout_toEndOf="@+id/workorderFilterPopup_plannedImage" />

                <ImageView
                    android:id="@+id/workorderFilterPopup_PlannedCheckMark"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_marginRight="20dp"
                    android:layout_alignParentEnd="true"
                    android:layout_alignBottom="@+id/workorderFilterPopup_plannedText"
                    android:src="@drawable/ic_done_black_24dp" />

                <ImageView
                    android:layout_width="35dp"
                    android:layout_height="35dp"
                    android:src="@drawable/ic_cloud_off_black_24dp"
                    android:id="@+id/workorderFilterPopup_incompleteImage"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="20dp"
                    android:layout_below="@+id/workorderFilterPopup_plannedImage"
                    android:layout_alignParentStart="true" />

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="35dp"
                    android:id="@+id/filter_menu_workorders_incomplete"
                    android:background="@color/transparent"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="20dp"
                    android:layout_below="@+id/workorderFilterPopup_plannedImage"
                    android:layout_alignParentStart="true"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:text="Uncompleted"
                    android:textColor="@color/white"
                    android:layout_marginLeft="20dp"
                    android:id="@+id/workorderFilterPopup_intompleteText"
                    android:layout_alignBottom="@+id/workorderFilterPopup_incompleteImage"
                    android:layout_toEndOf="@+id/workorderFilterPopup_incompleteImage" />

                <ImageView
                    android:id="@+id/workorderFilterPopup_IncompleteCheckMark"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_marginRight="20dp"
                    android:layout_alignParentEnd="true"
                    android:layout_alignBottom="@+id/workorderFilterPopup_intompleteText"
                    android:src="@drawable/ic_done_black_24dp" />

                <ImageView
                    android:layout_width="35dp"
                    android:layout_height="35dp"
                    android:src="@drawable/ic_cloud_queue_black_24dp"
                    android:id="@+id/workorderFilterPopup_CompleteImage"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="20dp"
                    android:layout_below="@+id/workorderFilterPopup_incompleteImage"
                    android:layout_alignParentStart="true" />

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="35dp"
                    android:id="@+id/filter_menu_workorders_complete"
                    android:background="@color/transparent"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="20dp"
                    android:layout_below="@+id/workorderFilterPopup_incompleteImage"
                    android:layout_alignParentStart="true"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:text="complete 5"
                    android:textColor="@color/white"
                    android:layout_marginLeft="20dp"
                    android:id="@+id/workorderFilterPopup_completeText"
                    android:layout_alignBottom="@+id/workorderFilterPopup_CompleteImage"
                    android:layout_toEndOf="@+id/workorderFilterPopup_CompleteImage" />

                <ImageView
                    android:id="@+id/workorderFilterPopup_completeCheckMark"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_marginRight="20dp"
                    android:layout_alignParentEnd="true"
                    android:layout_alignBottom="@+id/workorderFilterPopup_completeText"
                    android:src="@drawable/ic_done_black_24dp" />



                <View
                    android:layout_width="match_parent"
                    android:layout_height="20dp"
                    android:layout_below="@+id/workorderFilterPopup_CompleteImage"
                    ></View>


            </RelativeLayout>



        </android.support.v4.widget.NestedScrollView>

    </android.support.design.widget.CoordinatorLayout>




</RelativeLayout>


from how to put button on top of android.support.design.widget.AppBarLayout?

Access Teams session and other information in external tab url application

I would like to create a Teams tab for a clientside rendered application. I know that I can generate a basic app using a generator

https://github.com/OfficeDev/generator-teams

This generator will create a React app and I have to deal with many deployment stuff. I would like to create a Vue app and add it as an external application via URL. The problem is that this generated React app ships with many Teams related packages to provide a nice Teams integration

https://github.com/OfficeDev/msteams-ui-components/tree/master/msteams-ui-components-react

e.g. fetching the current Teams session etc. I also know that Microsoft provides an API to fetch Office related data (Users, Groups, ...)

https://developer.microsoft.com/en-us/graph

So when I create a basic Vue app (or any other client side app) are there any packages I can use to integrate with Teams while having an external tabs app and no native Teams tab application?

I don't want to use the native Teams styles so it seems the only advantage in using native tab applications would be fetching the current Teams session. But I am not sure, this is totally new to me. So I'm hoping the generated React Teams app ships with some packages I can use in my Vue app too and add it via external URL to teams.. ?



from Access Teams session and other information in external tab url application

Rendering SurfaceTexture to Unity Texture2D

I came up with simillar questions earlier, but they weren't good clarified and right now I would like to take an advice what's wrong I'm doing in my code.

So what I'm trying to do is rendering SurfaceTexture from Android plugin to Unity Texture2D.

Unity code:

public class AndroidHandler : MonoBehaviour {

    [SerializeField]
    private RawImage _rawImage;

    private Texture2D _inputTexture;
    private AndroidJavaObject androidStreamerObj;
    private System.IntPtr _nativePtr;

    void Start () {

        _rawImage.material.SetTextureScale("_MainTex", new Vector2(-1, -1));
        InitAndroidStreamerObject();
    }

    private void InitAndroidStreamerObject()
    {
        androidStreamerObj = new AndroidJavaObject("makeitbetter.figazzz.com.vitamiousing7.AndroidStreamer");

        Int32 texPtr = androidStreamerObj.Call <Int32> ("GetTexturePtr");
        Debug.Log("texture pointer? " + texPtr);
        Texture2D nativeTexture = Texture2D.CreateExternalTexture (128, 128, TextureFormat.RGBA32 , false, false, new System.IntPtr(texPtr));

        _rawImage.texture = nativeTexture;
    }

    public void StartStream()
    {
        string streamLink = "rtmp://live.hkstv.hk.lxdns.com/live/hks"; //"rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"; //"rtmp://live.hkstv.hk.lxdns.com/live/hks";
        androidStreamerObj.Call("LaunchStream", streamLink);
    }

    void Update()
    {
        androidStreamerObj.Call("DrawFrame");
    }
}

I'm asking my Android plugin to create openGLTexture and I'm using the pointer of the brand-new texture to allocate Texture2D in Unity.

Android plugin code:

public class AndroidStreamer {

    private final int FLOAT_SIZE_BYTES = 4;
    private final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
    private final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
    private final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;

    private Activity _currActivity;
    private VideoView _streamConnection;

    private Surface _cachedSurface;
    private SurfaceTexture _cachedSurfaceTexture;

    private Boolean isNewFrame = false;

    //open gl
    private int texWidth = 128;
    private int texHeight = 128;
    private float[] mMVPMatrix = new float[16];
    private float[] mSTMatrix = new float[16];

    private int glProgram;
    private int muMVPMatrixHandle;
    private int muSTMatrixHandle;
    private int maPositionHandle;
    private int maTextureHandle;
    private int unityTextureID = -1;
    private int mTextureId = -1;   //surface texture id
    private int idFBO = -1;
    private int idRBO = -1;

    private final float[] mTriangleVerticesData = {
            // X, Y, Z, U, V
            -1.0f, -1.0f, 0, 0.f, 0.f,
            1.0f, -1.0f, 0, 1.f, 0.f,
            -1.0f,  1.0f, 0, 0.f, 1.f,
            1.0f,  1.0f, 0, 1.f, 1.f,
    };

    private FloatBuffer mTriangleVertices;

    private final String vertexShaderCode =
            "uniform mat4 uMVPMatrix;\n" +
                    "uniform mat4 uSTMatrix;\n" +
                    "attribute vec4 aPosition;\n" +
                    "attribute vec4 aTextureCoord;\n" +
                    "varying vec2 vTextureCoord;\n" +
                    "void main() {\n" +
                    "    gl_Position = uMVPMatrix * aPosition;\n" +
                    "    vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
                    "}\n";

    private final String fragmentShaderCode =
            "#extension GL_OES_EGL_image_external : require\n" +
                    "precision mediump float;\n" +      // highp here doesn't seem to matter
                    "varying vec2 vTextureCoord;\n" +
                    "uniform samplerExternalOES sTexture;\n" +
                    "void main() {\n" +
                    "    gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
                    "}\n";

    public AndroidStreamer() {
        Log.d("Unity", "AndroidStreamer was initialized");

        _currActivity = UnityPlayer.currentActivity;
        Vitamio.isInitialized(_currActivity);

        _currActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                _streamConnection = new VideoView(_currActivity);
                _currActivity.addContentView(_streamConnection, new FrameLayout.LayoutParams(100, 100));
            }
        });

        mTriangleVertices = ByteBuffer.allocateDirect(
                mTriangleVerticesData.length * FLOAT_SIZE_BYTES)
                .order(ByteOrder.nativeOrder()).asFloatBuffer();
        mTriangleVertices.put(mTriangleVerticesData).position(0);
        Matrix.setIdentityM(mSTMatrix, 0);

        initShaderProgram();
    }

    private void initShaderProgram()
    {
        Log.d("Unity", "initShaderProgram");
        int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
        int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);

        glProgram = GLES20.glCreateProgram();
        GLES20.glAttachShader(glProgram, vertexShader);
        checkGlError("glAttachVertexShader");
        GLES20.glAttachShader(glProgram, fragmentShader);
        checkGlError("glAttachFragmentShader");
        GLES20.glLinkProgram(glProgram);
        checkGlError("glLinkProgram");

        maPositionHandle = GLES20.glGetAttribLocation(glProgram, "aPosition");
        checkLocation(maPositionHandle, "aPosition");
        maTextureHandle = GLES20.glGetAttribLocation(glProgram, "aTextureCoord");
        checkLocation(maTextureHandle, "aTextureCoord");

        muMVPMatrixHandle = GLES20.glGetUniformLocation(glProgram, "uMVPMatrix");
        checkLocation(muMVPMatrixHandle, "uVMPMatrix");
        muSTMatrixHandle = GLES20.glGetUniformLocation(glProgram, "uSTMatrix");
        checkLocation(muSTMatrixHandle, "uSTMatrix");
    }

    private int loadShader(int shaderType, String source) {
        int shader = GLES20.glCreateShader(shaderType);
        if (shader != 0) {
            GLES20.glShaderSource(shader, source);
            GLES20.glCompileShader(shader);
            int[] compiled = new int[1];
            GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
            if (compiled[0] == 0) {
                Log.e("Unity", "Could not compile shader " + shaderType + ":");
                Log.e("Unity", GLES20.glGetShaderInfoLog(shader));
                GLES20.glDeleteShader(shader);
                shader = 0;
            }
        }
        return shader;
    }

    private void checkLocation(int location, String label) {
        if (location < 0) {
            throw new RuntimeException("Unable to locate '" + label + "' in program");
        }
    }

    private void checkGlError(String op) {
        int error;
        while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
            Log.e("Unity", op + ": glError " + error);
            throw new RuntimeException(op + ": glError " + error);
        }
    }

    private void checkFrameBufferStatus()
    {
        int status = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER);
        checkGlError("glCheckFramebufferStatus");
        switch (status)
        {
            case GLES20.GL_FRAMEBUFFER_COMPLETE:
                Log.d("Unity", "complete");
                break;
            case GLES20.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
                Log.e("Unity", "incomplete attachment");
                break;
            case GLES20.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
                Log.e("Unity", "incomplete missing attachment");
                break;
            case GLES20.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
                Log.e("Unity", "incomplete dimensions");
                break;
            case GLES20.GL_FRAMEBUFFER_UNSUPPORTED:
                Log.e("Unity", "framebuffer unsupported");
                break;

            default : Log.d("Unity", "default");
        }
    }

    private void initGLTexture()
    {
        Log.d("Unity", "initGLTexture");
        int textures[] = new int[1];
        GLES20.glGenTextures(1, textures, 0);
        checkGlError("glGenTextures initGLTexture");
        mTextureId = textures[0];

        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        checkGlError("glActiveTexture initGLTexture");
        GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId);
        checkGlError("glBindTexture initGLTexture");

        GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
        checkGlError("glTexParameterf initGLTexture");
        GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
        checkGlError("glTexParameterf initGLTexture");
    }

    public int GetTexturePtr()
    {
        Bitmap bitmap = Bitmap.createBitmap(texWidth, texHeight, Bitmap.Config.ARGB_8888);
        for(int x = 0; x < texWidth; x++)
        {
            for (int y = 0; y < texHeight; y++)
            {
                bitmap.setPixel(x, y, Color.argb(155, 255, 50, 255));
            }
        }
        Log.d("Unity", "Bitmap is: " + bitmap);

        ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount());
        bitmap.copyPixelsToBuffer(buffer);

        //GLES20.glEnable(GLES11Ext.GL_TEXTURE_EXTERNAL_OES);
        //checkGlError("glEnable GetTexturePtr");

        int textures[] = new int[1];
        GLES20.glGenTextures(1, textures, 0);
        checkGlError("0");
        unityTextureID = textures[0];

        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        checkGlError("1");
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, unityTextureID);
        checkGlError("2");

        GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, texWidth, texHeight, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
        checkGlError("12");
        //GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
        //checkGlError("3");
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
        checkGlError("4");
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
        checkGlError("5");
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
        checkGlError("6");
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
        checkGlError("7");
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
        checkGlError("8");

        setupBuffers();
        Log.d("Unity", "texture id returned: " + unityTextureID);

        return unityTextureID;
    }

    private void setupBuffers()
    {
        Log.d("Unity", "setupBuffers");

        //framebuffer
        int buffers[] = new int[1];
        GLES20.glGenFramebuffers(1, buffers, 0);
        checkGlError("9");
        idFBO = buffers[0];
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, idFBO);
        checkGlError("10");

        //render buffer
        int rbuffers[] = new int[1];
        GLES20.glGenRenderbuffers(1, rbuffers, 0);
        checkGlError("glGenRenderBuffers setupBuffers");
        idRBO = rbuffers[0];
        GLES20.glBindRenderbuffer(GLES20.GL_RENDERBUFFER, idRBO);
        checkGlError("glBindRenderBuffer setupBuffers");
        GLES20.glRenderbufferStorage(GLES20.GL_RENDERBUFFER, GLES20.GL_RGBA4, texWidth, texHeight);
        checkGlError("glRenderBufferStorage setupBuffers");

        GLES20.glFramebufferRenderbuffer(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_RENDERBUFFER, idRBO);
        checkGlError("glFramebufferRenderbuffer setupBuffers");

        GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, unityTextureID, 0);
        checkGlError("glFrameBufferTexture2D");

        checkFrameBufferStatus();

        GLES20.glClearColor(1.0f, 0.5f, 0.0f, 1.0f);
        checkGlError("glClearColor setupBuffers");
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        checkGlError("glClear setupBuffers");
    }

    public void DrawFrame()
    {
        if(isNewFrame && mSTMatrix != null) {

            int[] testBuffer = new int[1];
            GLES20.glGetIntegerv(GLES20.GL_FRAMEBUFFER_BINDING, testBuffer, 0);

            Log.d("Unity", "DrawFrame binded = " + testBuffer[0] + " idFBO = " + idFBO);

            GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, idFBO);
            checkGlError("glBindFrameBuffer DrawFrame");

            GLES20.glClearColor(0.0f, 1.0f, 0.2f, 1.0f);
            checkGlError("glClearColor DrawFrame");
            GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
            checkGlError("glClear DrawFrame");

            GLES20.glUseProgram(glProgram);
            checkGlError("glUseProgram DrawFrame");

            GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
            checkGlError("glActiveTexture DrawFrame");
            GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId);
            checkGlError("glBindTexture DrawFrame");

            mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
            GLES20.glVertexAttribPointer(maTextureHandle, 2, GLES20.GL_FLOAT, false, TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
            checkGlError("glVertexAttribPointer DrawFrame");
            GLES20.glEnableVertexAttribArray(maTextureHandle);
            checkGlError("glEnableVertexAttribArray DrawFrame");

            Matrix.setIdentityM(mMVPMatrix, 0);
            GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
            checkGlError("glUniformMatrix4fv MVP onFrameAvailable");
            GLES20.glUniformMatrix4fv(muSTMatrixHandle, 1, false, mSTMatrix, 0);
            checkGlError("glUniformMatrix4fv ST onFrameAvailable");

            GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
            checkGlError("glDrawArrays onFrameAvailable");

            GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
            checkGlError("glBindFrameBuffer 0 onFrameAvailable");
            GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
            checkGlError("glBindTexture onFrameAvailable");

            isNewFrame = false;
        }
    }

    public void LaunchStream(String streamLink) {

        final String path = streamLink; //"http://dlqncdn.miaopai.com/stream/MVaux41A4lkuWloBbGUGaQ__.mp4"; //"rtmp://live.hkstv.hk.lxdns.com/live/hks";
        Log.i("Unity", "hop hop1 = " + path);

        _currActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                _streamConnection.setVideoPath(path);
                _streamConnection.setMediaController(new MediaController(_currActivity));
                _streamConnection.requestFocus();

                _streamConnection.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        Log.i("Unity", "some error, I don't know. what = " + what + " extra = " + extra);
                        return false;
                    }
                });

                _streamConnection.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        // optional need Vitamio 4.0
                        Log.i("Unity", "hop hop5");
                        mediaPlayer.setPlaybackSpeed(1.0f);

                    }
                });

                initGLTexture();

                _cachedSurfaceTexture = new SurfaceTexture(mTextureId);
                _cachedSurfaceTexture.setDefaultBufferSize(texWidth, texHeight);

                _cachedSurfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {
                    @Override
                    public void onFrameAvailable(SurfaceTexture surfaceTexture) {
                        synchronized (this) {
                            surfaceTexture.updateTexImage();

                            mSTMatrix = new float[16];
                            surfaceTexture.getTransformMatrix(mSTMatrix);
                            isNewFrame = true;
                        }
                    }
                });

                _cachedSurface = new Surface(_cachedSurfaceTexture);
                _streamConnection.setSurfaceToPlayer(_cachedSurface);

                Log.i("Unity", "You're the best around!");
            }
        });
    }
}

I decided to provide the all code of my Android plugin in order to give the most clear understanding of situation I'm having. Basically, what I'm trying to do:

  1. I call method "GetTexturePtr" from Unity side, it creates GL_TEXTURE_2D texture which I apply to Unity Texture2D. Also in the Android side I setup frame and render buffers for changing color of this texture. It works fine because it fills with color just perfectly.
  2. Then I call method "LaunchStream", where creates GL_TEXTURE_EXTERNAL_OES texture (in "initGLTexture()" method) and this texture applies to SurfaceTexture.
  3. Also in the Unity Update() method I call android method "DrawFrame()" which should update my Unity texture according to SurfaceTexture changes.

Right now I'm having the glError 1282 on GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId); and of course texture just fills with green color here

GLES20.glClearColor(0.0f, 1.0f, 0.2f, 1.0f);
            checkGlError("glClearColor DrawFrame");

What I'm doing wrong?



from Rendering SurfaceTexture to Unity Texture2D

ReactDOM not rendering anything from separate js file

I used "npx create-react-app testreact" to create the react project. When testing from browser on my PC, the server returns a blank page, other than the expected words —— "Learn React".

What's happening here? how to fix this?

env info
nodejs: v13.2.0
npm: 6.13.1
system: 18.04.1-Ubuntu
reverse proxy server: nginx

code Info
index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: 
serviceWorker.unregister();

App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;


from ReactDOM not rendering anything from separate js file

Swift - Cut hole in shadow layer

I want to "cut a hole" in the shadow layer of a UIView an Swift3, iOS

I have a container (UIView), that has 2 children:

  • one UIImageView
  • one UIView on top of that image ("overlay")

I want to give the overlay a shadow and cut out an inner rect of that shadow, to create a glow-like effect at the edges of the ImageView
It is crucial that the glow is inset, since the image is taking the screen width
My code so far:

let glowView = UIView(frame: CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight))
glowView.layer.shadowPath = UIBezierPath(roundedRect: container.bounds, cornerRadius: 4.0).cgPath
glowView.layer.shouldRasterize = true
glowView.layer.rasterizationScale = UIScreen.main.scale
glowView.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
glowView.layer.shadowOpacity = 0.4

container.addSubview(imageView)
container.addSubview(glowView)

The result looks like the following right now:

image

Now I would like to cut out the darker inner part, so that just the shadow at the edges remains
Any idea how to achieve this?



from Swift - Cut hole in shadow layer

Image onLoad event is not triggered using Chrome on iOS

I am using Scala.js and d3.js (scala-js-d3) to draw an SVG in a web application. The problem I have is that for my background image the load event is not triggered when using Chrome on iOS (iPhone). It does trigger when using Chrome on Windows. The image itself is visible on all platforms.

Here is how I add the image:

d3.select("#backgroundImg")
  .append("image")
  .attr("id", "graphBackgroundImage")
  .attr("width", "1954px")
  .attr("height", "1532px")
  .attr("xlink:href", "img/maps/map.png")
  // TODO this load event does not trigger on iOS!
  .on("load", (_: EventTarget) => { println("image loaded") } : Unit)
  .on("error", (_: EventTarget) => { prinltn("an error has occured") } : Unit)

On Windows this creates the following svg dom element (and everything works as expected):

<g id="backgroundImg">
  <image id="graphBackgroundImage" width="1954px" height="1532px" xlink:href="img/maps/map.png"></image>
</g>

It is a bit hard to debug on the iPhone I have, so this is all I found out so far. I just know that image loaded is not logged when using Chrome on iOS (there is also no an error has occured log).



from Image onLoad event is not triggered using Chrome on iOS

How can I display a negative mode preview with CameraX in Android?

I'm learning CameraX API, and CameraXBasic is a office sample code.

CameraFragment.kt in CameraXBasic project displays a real camera preview.

Now I hope to display a negative mode preview. How can I do with CameraX API? Is there a sample code?

CameraFragment.kt

private lateinit var viewFinder: TextureView

private fun bindCameraUseCases() {
    // Get screen metrics used to setup camera for full screen resolution
    val metrics = DisplayMetrics().also { viewFinder.display.getRealMetrics(it) }
    val screenAspectRatio = Rational(metrics.widthPixels, metrics.heightPixels)
    Log.d(TAG, "Screen metrics: ${metrics.widthPixels} x ${metrics.heightPixels}")

    // Set up the view finder use case to display camera preview
    val viewFinderConfig = PreviewConfig.Builder().apply {
        setLensFacing(lensFacing)
        // We request aspect ratio but no resolution to let CameraX optimize our use cases
        setTargetAspectRatio(screenAspectRatio)
        // Set initial target rotation, we will have to call this again if rotation changes
        // during the lifecycle of this use case
        setTargetRotation(viewFinder.display.rotation)
    }.build()

    // Use the auto-fit preview builder to automatically handle size and orientation changes
    preview = AutoFitPreviewBuilder.build(viewFinderConfig, viewFinder)

 ....

 CameraX.bindToLifecycle(
            viewLifecycleOwner, preview, imageCapture, imageAnalyzer)
}


from How can I display a negative mode preview with CameraX in Android?

Cordova Android Will Not Display StatusBar

I have an issue I have been trying to solve, none of the solutions online I have seen have helped either.

Very simple, so you think the solution would be as well. On the Android platform for Cordova build I am using the StatusBar plugin which is set in the config.xml to preference and DISPLAY it...Yes, I am trying to get it to display in the app and not hide. It seems to be hidden every time the app runs.

In my InAppBrowser option string, I also set fullscreen=no so that that won't affect it either.

Running the app in the simulator and on-device both hide it still. Would someone possibly know a solution to FORCE the status bar to show and if not, what are the causes of this?

onDeviceReady: function() {
StatusBar.overlaysWebView(true);
    //InAppBrowser Init
    var options = "location=no,fullscreen=no,zoom=no"
    Browser = cordova.InAppBrowser.open('http://www.app.example', '_self', options);

The StatusBar plugin is also being imported correctly and can be seen here, this was done via plugman:

enter image description here

Here is my Config.xml file for better supporting information:

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.pulse_co" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<feature name="Notification">
    <param name="android-package" value="org.apache.cordova.dialogs.Notification" />
</feature>
<feature name="InAppBrowser">
    <param name="android-package" value="org.apache.cordova.inappbrowser.InAppBrowser" />
</feature>
<feature name="NetworkStatus">
    <param name="android-package" value="org.apache.cordova.networkinformation.NetworkManager" />
</feature>
<feature name="Whitelist">
    <param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" />
    <param name="onload" value="true" />
</feature>
<feature name="OneSignalPush">
    <param name="android-package" value="com.plugin.gcm.OneSignalPush" />
</feature>

<name>Pulse</name>
<description>
    Add Pulse App Description Here
</description>
<author email="email@test.com" href="https://support.example.com">
    Team
</author>
<content src="index.html" />
<access origin="https://root.domain.co*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<allow-intent href="market:*" />
<preference name="loglevel" value="DEBUG" />
<preference name="StatusBarOverlaysWebView" value="true" />
<feature name="StatusBar">
    <param name="android-package" value="org.apache.cordova.statusbar.StatusBar" />
    <param name="onload" value="true" />
</feature>


from Cordova Android Will Not Display StatusBar

Set a path to options/tooltips/callbacks/afterTitle and pass parameter to Array

I'm working on a chart, I'm live updating the Chart every 5 seconds that the data comes in. I could manage to get the info from the database and update it really easy, but I just came across a problem with involves setting a path to a part of the chart, in the case: options->tootltips->callbacks->afterTitle and inside of it create an array and pass the array from the JSON to an array inside the callback.

Inside this patch, I made an example that didn't work, with is the //:

$.getJSON('loadchart.php', function(response) {
          myLineChart.data.datasets[0].data = response[0];
          myLineChart.data.datasets[1].data = response[1];
          myLineChart.data.datasets[2].data = response[2];
          myLineChart.data.datasets[3].data = response[3];
          myLineChart.data.labels = response[4];

          //The response array that I need is response[5];
          //myLineChart.options.tooltips.callbacks[1] = return response[tooltipItem[0]['index']]; 
          myLineChart.update();
        });

All my Chart so you can see the path:

var myLineChart = new Chart(ctx1, {
        type: 'line', 
        data: {
          labels: lbl,
          datasets: [
            {
              label: "Corrente 1",
              data: [],
              borderWidht: 6,
              borderColor: 'red',
              backgroundColor: 'transparent'
            },
            {
              label: "Corrente 2",
              data: [],
              borderWidht: 6,
              borderColor: 'blue',
              backgroundColor: 'transparent'
            },
            {
              label: "Corrente 3",
              data: [],
              borderWidht: 6,
              borderColor: 'green',
              backgroundColor: 'transparent'
            },
            {
              label: "Corrente Total",
              data: [],
              borderWidht: 6,
              borderColor: 'black',
              backgroundColor: 'transparent'
            },
          ]            
        },
        options: {
          animation:{
            update: 0
          },
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }],
            xAxes: [{
              gridLines: {
                display: false
              }
            }]
          },

          title: {
            display: true,
            fontSize: 20,
            text: "Gráfico das Correntes"
          },

          labels: {
            fontStyle: "bold",
          },

          layout: {
            padding: {
              left: 0,
              right: 0,
              top: 0,
              bottom: 0
            }
          },
          tooltips: {
            enabled: true,
            mode: 'single',
            responsive: true,
            backgroundColor: 'black',
            titleFontFamily: "'Arial'",
            titleFontSize: 14,
            titleFontStyle: 'bold',
            titleAlign: 'center',
            titleSpacing: 4,
            titleMarginBottom: 10,
            bodyFontFamily: "'Mukta'",
            bodyFontSize: 14,
            borderWidth: 2,
            borderColor: 'grey',
            callbacks:{
              title: function(tooltipItem, data) {
                  return data.labels[tooltipItem[0].index];
              },
              afterTitle: function(tooltipItem, data) {
                var tempo = [];
                return tempo[tooltipItem[0]['index']]; 
              },
              label: function(tooltipItem, data) {
                    var label = data.datasets[tooltipItem.datasetIndex].label || '';                  
                    if (label) {
                        label += ': ';
                    }
                    label += (tooltipItem.yLabel)+"A";                  
                    return label;
              }
            }
          },

The part I need is this one:

afterTitle: function(tooltipItem, data) {
                var tempo = [];
                return tempo[tooltipItem[0]['index']]; 


from Set a path to options/tooltips/callbacks/afterTitle and pass parameter to Array