text:
Q: twilio gather significant delay in speech2text processing I'm using TwilioML  to collect user's input.
What I'm seeing is a significant delay 4-6 sec. from the time the user stop speaking to the time my service ( endpoint) is called. This happens even with very simple sentences (ex. my name is john).
Is this a known issue? From a user experience point of view it is not a great experience.
I tried to add a 'filler' via  but it does not have any effect because the earlier I can get it started is when the  endpoint is called.
Maybe there is a way to play a file in parallel while the the audio is converted to text.

A: From the documentation:

The 'timeout' attribute sets the limit in seconds that Twilio will
  wait for the caller to press another digit or say another word before
  moving on and making a request to the 'action' URL. For example, if
  'timeout' is '3', Twilio will wait three seconds for the caller to
  press another key or say another word before submitting the previously
  entered digits or speech to the 'action' URL. Twilio waits until
  completing the execution of all nested verbs before beginning the
  timeout period.

The fact you are seeing a delay of between 4 and 6 seconds is probably explained by the fact the default timeout setting is 5 seconds.
Have you tried using a partialResultCallback URL? If set Twilio will submit results of speech recognition in real time to this URL. It's also worth adding hints if you are expecting callers to say certain words as this can speed up the recognition.


text:
Q: Multidimensional array sort by another array value I'm trying to sort out the sequence of individual array. How to use my another array list?
There is a predefined array:
$sortOrder = array("Night","Breakfast","Lunch","Dinner","Lying");

And this is it my original array content:
Array
(
    [Normal] => Array
        (
        [Dinner] => Array
            (
                [avgtime] => 17,06
                [avg] => 5.24
            )

        [Breakfast] => Array
            (
                [avgtime] => 04,25
                [avg] => 4.96
            )

        [Lying] => Array
            (
                [avgtime] => 14,49
                [avg] => 4.7
            )

        [Lunch] => Array
            (
                [avgtime] => 09,53
                [avg] => 5.26
            )

        [Night] => Array
            (
                [avgtime] => 00,00
                [avg] => 4.4
            )

    )

[High] => Array
    (
        [Dinner] => Array
            (
                [avg] => 9
                [avgtime] => 17,35
            )

    )

[Low] => Array
    (
        [Night] => Array
            (
                [avg] => 3.5
                [avgtime] => 02,35
            )

        [Breakfast] => Array
            (
                [avg] => 3.8
                [avgtime] => 07,12
            )
    )
)

How can I order placed based on the list? Please help me, and thanks so much!

A: solution using uksort,
$temp = array ('Lunch'=>'3', 'Lying' => '5', 'Night' => '1', 'Dinner' => '4', 'Breakfast' => '2');

function cmp($a, $b) {
    $sortOrder = array("Night","Breakfast","Lunch","Dinner","Lying");
    $pos1 =  array_search($a, $sortOrder);
    $pos2 =  array_search($b, $sortOrder);
    if (pos1 == pos2) return 0;
    return ($pos1 > $pos2)? 1:-1;
}

uksort($temp, 'cmp');

// output: Array ( [Night] => 1 [Breakfast] => 2 [Lunch] => 3 [Dinner] => 4 [Lying] => 5 )

A: To achieve more efficient key searching let's use static arrays in the comparison function:
foreach ($arr as $key => $row) {
  uksort($arr[$key], function($a, $b) {
    static $sortOrder = ['Night', 'Breakfast', 'Lunch', 'Dinner', 'Lying'];

    static $order;
    if (!isset($order)) {
      $order = array_flip($sortOrder);
    }

    $value = 0;
    if (array_key_exists($a, $order) && array_key_exists($b, $order)) {
      $value = ($order[$a] > $order[$b] ? 1 : -1);
    }
    return $value;
  });
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to run an ASP.NET project and an ASP.NET MVC project side-by-site on the same website? I have an existing ASP.NET website with some custom routing, within a Solution that also contains Business Logic projects.
I want to create a new project within the Solution, which is an ASP.NET MVC website.
This website will also call the Business logic, and the ultimate aim is to port most of the code from ASP.NET to ASP.NET MVC.
But I want them to both work side-by-side for now, to ensure minimal down-time, as it's a high-traffic website.
Is it possible to accomplish this somehow using either ASP.NET routing or some kind of IIS setting?

A: Yep, you just need to add some routing to your current application.  Try http://www.packtpub.com/article/mixing-asp.net-webforms-and-asp.net-mvc

A: Please have a look at this post by Scott HanselMan.
It provides detailed discussion about this along with a nice walk through.

A: I just wrote a blog post on this. It is possible. You might find it easier to simply relocate your web forms from your existing web forms project to your new MVC project. You may not have to change any code.


text:
Q: Django app initialization process There is a set of functions that I need to carry out during the start of my server. Regardless of path whether that be "/", "/blog/, "/blog/post". For developments purposes I'd love for this script to run every time I run python manage.py runserver and for production purposes I would love this script to run during deployment. Anyone know how this can be done?
My script is scraping data off and making a call to Facebook's Graph API with python and some of its libraries.

A: Sounds like the quickest (if not most elegant) solution would be to call 'python manage.py runserver' at the end of your script.

A: I would suggest you to use custom management commands:

*

*Create command for initialization:
e.g. app/management/commands/initialize_some_stuff.py
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Description of your command.'

    def handle(self, *args, **options):
        # Add your initialization here.
        print 'What should I initialize?'

*Create command for running server during development:
e.g. app/management/commands/rundevserver.py
import os

from django.core.management import call_command
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Description of your command.'

    def handle(self, *args, **options):
        if not os.environ.get('RUN_MAIN'):
            call_command('initialize_some_stuff', *args, **options)
        call_command('runserver', *args, **options)

*Call ./manage.py rundevserver instead of ./manage.py runserver during development.

*Add ./manage.py initialize_some_stuff to your deployment script.
As an alternative to 3rd clause you can also override default runserver command and conditionally call ./manage.py initialize_some_stuff from it:

*

*Add additional imports:
import os

from django.conf import settings

*Override handle method:
def handle(self, *args, **options):
    if os.environ.get('RUN_MAIN') and settings.DEBUG:
        call_command('initialize_some_stuff', *args, **options)
    super(Command, self).handle(*args, **options)


text:
Q: Help with derivative of $y=x^2\sin^5x+x\cos^{-5}x$
Find $y^{\prime}$ of $y=x^2\sin^5x+x\cos^{-5}x$

My try:
$\dfrac{d}{dx}(x^2\sin^5x)=x^2(-5\sin^4x)+(2x\sin^5x)$
$\dfrac{d}{dx}(x\cos^{-5}x)=x(-5\cos^{-6}x)+1(\cos^{-5}x)$
This doesn't seem right. Can you please show how to do it correctly?
The answer is $y^{\prime}=x\sin^4(x) ( 2 \sin(x)+5x\cos(x)) +(5x\tan(x)+1)\sec^5x$

A:
$$y=x^2\sin^5x+x\cos^{-5}x$$

When taking the derivative of each summand of $y$, you left out a component of the chain rule for each of the trigonometric functions: $$[g(x)]^n = n[g(x)]^{n - 1} \cdot \color{blue}{g'(x)}$$ See the text highlighted in blue:
$$\dfrac{d}{dx}(x^2\sin^5x)=x^2(5\sin^4x){\bf\color{blue}{ \cos x}}+(2x\sin^5x)$$
$$\dfrac{d}{dx}(x\cos^{-5}x)=x(-5\cos^{-6}(x){\bf \color{blue}{(-\sin x)}})+1(\cos^{-5}x)$$
$$y' = 5x^2\sin^4x\cos x+ 2x\sin^5x +5x\cos^{-6}x\sin x + \cos^{-5}x$$

A: $\dfrac{d}{dx}(x^2\sin^5x)=x^25\sin^4x \cos x+(2x\sin^5x)$
$\dfrac{d}{dx}(x\cos^{-5}x)=5x\cos^{-6}x \sin {x}+1(\cos^{-5}x)$

A: Hint:
$$\frac{d\color{blue}{f^{\color{red}n}(x)}}{dx}=\color{red}n\color{blue}{f^{\color{red}{n-1}}(x)}\color{grey}{f'(x)}$$


text:
Q: Collecting tweets with geocode in R I am attempting to map tweets that have the hastag #trump or include trump in their language. I only want to collect tweets that have a geocode tied to them. I tried
library(tweetR)
tweets <- searchTwitter("#trump OR Trump or trump", n = 200, lang = "en", geocode = '33.7490, 84.3880, 1000mi')

but was not getting any results. How can I search for tweets that include trump and have a geocode?


text:
Q: tp link WA801ND wireless operation mode I have a TL TL-WA801ND from TP-Link. My goal is to improve Wifi signal on the ground floor in our house. The router from the ISP is located on the first floor.
I'm in doubt which mode I should use. The TP-link is connected to the wired network with an ethernet cable and should "convert" the wired ethernet to wifi (same network, same SSID, ...)

A: You need to set it up in Bridge Mode with AP:

*

*To do that login to your 801ND

*Click Network. Please make sure the access point's IP address is in
the same IP segment with the Root Router and avoid  the  IP
conflict. Click Save.

*Click Wireless ->Wireless Settings. Select Bridge with AP as the
Operation Mode and your Region.

*Click on Search button at the bottom, an AP list will be displayed.
Choose your root AP and locate the BSSID (MAC address) of root AP,
Click Connect, and then click on save button.

*Go to Wireless-Security Settings to secure the wireless as WEP. Type
in exactly the same password as your root router's  and click on
save button.   Note: It only supports WEP when TL-WA801ND V1 is
configured as bridge mode.

Go to System Tools-Reboot to reboot the device or the settings will not take effect.


text:
Q: Is there any difference between the result of these two format strings? I have inherited some code where prices are formatted like this:
(1.23d).ToString("£0.00");

I would normally format a currency like this:
(1.23d).ToString("C");

If the machine's locale is set to the UK (which it is) then is there any difference between these two approaches? Can I just do a big find and replace across the solution?

A: According to Standard Numeric Format Strings, behavior of the "C" format specifier is determined by settings in the current culture's NumberFormatInfo. You can check to make sure by examining the NumberFormatInfo:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
var nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
Console.WriteLine(nfi.CurrencyDecimalDigits);
Console.WriteLine(nfi.CurrencyDecimalSeparator);
Console.WriteLine(nfi.CurrencyNegativePattern);
Console.WriteLine(nfi.CurrencyPositivePattern);
Console.WriteLine(nfi.CurrencySymbol);

A: You can partially verify that by running this code on a machine with that locale (or by enforcing it first with Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");):
var nf = CultureInfo.CurrentCulture.NumberFormat;
Console.WriteLine("CurrencyPositivePattern: " + nf.CurrencyPositivePattern);
Console.WriteLine("CurrencyNegativePattern: " + nf.CurrencyNegativePattern);
Console.WriteLine("NegativeSign: " + nf.NegativeSign);
Console.WriteLine("CurrencySymbol: " + nf.CurrencySymbol);
Console.WriteLine("CurrencyDecimalDigits: " + nf.CurrencyDecimalDigits);
Console.WriteLine("CurrencyDecimalSeparator: " + nf.CurrencyDecimalSeparator);
Console.WriteLine("CurrencyGroupSeparator: " + nf.CurrencyGroupSeparator);
Console.WriteLine("CurrencyGroupSizes: " + string.Join(",", nf.CurrencyGroupSizes.Select(gs => gs.ToString())));

Note the group sizes property. On my machine this code:
Console.WriteLine((1232323d).ToString("C"));
Console.WriteLine((1232323d).ToString("£0.00"));

produces two different strings, because of the digit groups.
Also, as noted by others here, and as you may already know anyway - decimal should be used instead of double for currency.

A: It will be no difference. If in your Regional language settings desired currency is selected.
And yes, Always prefer decimal as data type for money.

A: (1.23d).ToString("£0.00"); might make it more explicit that the numbers always represent £ (business logic) and that this is not merely an arbitrary display thing.


text:
Q: python find string concatenations and replace them with actual strings Tried finding an answer for this but haven't been able to exactly find what I'm looking for. I'm trying to create a python script that will find strings concatenations in a text file, and transform them into a single string.
For example, the file would contain:
"h" + "e" + "l" + "l" + "o" + world;

An I'd like to have a script turn this into:
"hello" + world;

If something like this is feasible, could I get some pointers on how to write such script?

A: You could try to remove " + " when it is found.  Ostensibly, it should only be found between two strings that are being concatenated.  The regular expression below will drop the following sequence: a double quote, 0 or 1 whitespace characters, the plus sign, 0 or 1 whitespace characters, and an other double quote.
import re

with open('filename.txt', 'r') as fp:
    cleaned_text = [re.sub(r'"\W?\+\W?"', '',line) for line in fp]

# example
> re.sub(r'"\W?\+\W?"', '','"h" + "e" + "l" + "l" + "o" + world;')
# "hello" world;


text:
Q: Collision detection after rotation I rotated my squares on canvas and I want to detect collision between them, although the normal method obviously doesn't work. How should it be done?
As you may see if they collide one of the boxes turns red, but if only the tips collide nothing happens.

var canvas,ctx,box1,box2,mouseX,mouseY,intervalo;
function load(){
 canvas = document.getElementById('box');
 ctx = canvas.getContext('2d');

 function box(x,y,width,height,color,angle){
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
  this.color = color;
  this.angle = angle;
  this.rotateX = x;
  this.rotateY = y;

  this.drawn = function(){

   var rad = this.angle*(Math.PI/180);//Here you should turn degrees into radians by -> *(Math.PI/180);
   ctx.translate(this.x + (this.width / 2), this.y + (this.height / 2))//Change screen cordinates to center of object
   ctx.rotate(rad);//Rotate canvas
   //What you want to rotate:
   this.rotateX = (this.width / 2) * (-1);
   this.rotateY = (this.height / 2) * (-1);
   ctx.fillStyle = this.color;
   ctx.fillRect(this.rotateX,this.rotateY,this.width,this.height);
   //end
   ctx.rotate(rad * (-1));//Unrotate canvas
   ctx.translate((this.x + (this.width / 2)) * (-1), (this.y + (this.height / 2)) * (-1));//Change screen cordinates back to normal
  }
 }
 box1 = new box(500,250,50,50,"white",45);
 box2 = new box(250,250,50,50,"white",45);

 document.onmousemove = mouseMove;
 function mouseMove(event) {
  event = event || canvas.event
  mouseX = event.pageX;
  mouseY = event.pageY;
  mouseX = mouseX - 11;
  mouseY = mouseY - 13;
  box2.x = mouseX;
  box2.y = mouseY;
 }
 intervalo = setInterval(animation, 1000/60);
}
function animation(){
 ctx.fillStyle = "black";
 ctx.fillRect(0,0,canvas.width,canvas.height);
 for (var i = 0;i < 2; i++){
  //Colision detection that doesn't work:
  if (!(box1.x+box1.width < box2.x) &&
  !(box2.x+box2.width < box1.x) &&
  !(box1.y+box1.height < box2.y) &&
  !(box2.y+box2.height < box1.y)) {
   console.log("colision");
   box2.color = "red";
  } else {
   box2.color = "white";
  }

  box1.drawn();
  box2.drawn();
 }
}
#box {
 border: 1px solid black;
 border-color: white;

}
#button {
 border: none;
 background-color: gray;
 width: 70;
 height: 50;
}
canvas {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
html {
 background-color: black;
 color: white;
 font-family: courier new;
}
<html>
 <head>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="css/estilo.css">
  <script src="js/main.js"></script>
 </head>
 <body onload="load()">
  <canvas id="box" width="1330" height="500"></canvas>
  <button onclick="play()" id="button">Play</button>
 </body>
</html>


text:
Q: PHP call function in separate process sorry for long text.
I am looking for an idea to trigger execution of php function (in different directory, tested and in same directory) when specific act occurs.
System is Debian and php framework yii.
With API we receive new data from remote server and for specific value in data we receive I need to start function in separate process. No need to wait for its completion.
Because API response time I can't integrate this function into it and integration breaks down API rendering it unusable.
I have read dozens of answers on Stackoverflow and many other examples.
For test I just tried to create new folder at specific location and file wasn't created (permission problem I think but can't confirm since it makes it if done from main code - api).
It is supposed to do following:

*

*pass 2 arguments received from API to function

*create folder if it doesn't exist

*call internal class that uses fpdf to print pdf file.

*save document and mail it with PHPMailer.

Can't use pcntl_fork because it requires additional installation (which I am not allowed to do).
Covered topics:

*

*forking with pcntl_fork (execution stops on reaching it.)

*popen/pclose, exec, proc_open/proc_close (no reply and can't confirm it actually entered function).

Of course this situation excludes possibility of use of include and require.
Can't release api code but here is what I was asking it to do:
background.php
$docs_dir='test_folder';
if (!file_exists('/var/www/created_documents/'.$docs_dir))
{
    mkdir('/var/www/created_documents/'.$docs_dir, 0777, true);
    chmod('/var/www/created_documents/'.$docs_dir, 0777);
}

And it does nothing.
Few examples what I used in api code to jump to it (many others were deleted during work).
$proc = popen('php ' . __DIR__ . '/background.php &', 'r');
return $proc;
while (!feof($proc))
{
    $data = fgets($proc);
    var_dump($data);
}

exec("php background.php");

$cmd = "php background.php";
$timer = popen("start ". $cmd, "r");
pclose($timer);

exec($cmd . " > /dev/null &");
pclose(popen("php background.php &","r"));

A: You could make a separate internal http request using curl and its async funcionality.
Or you may use a queuing mechanism where one part is firing an event and the other part is consuming it. RabbitMQ or Gearman could do this for you.


text:
Q: 'undefined is not an object' in karma/jasmine unit test I have the following simple unit test:
describe('SyncController', function() {
  var controller,
      deferredRecount,
      pouchdbServiceMock;

  beforeEach(module('inspector'));

  beforeEach(inject(function($controller, $q, $scope) {
    deferredRecount = $q.defer();

    pouchdbServiceMock = {
      getRecordCounts: jasmine.createSpy('getRecordCounts spy').and.returnValue(deferredRecount.promise)
    };

    controller = $controller('SyncController', {
      '$scope': $scope,
      'pouchdbService': pouchdbServiceMock
    });
  }));

  beforeEach(inject(function(_$rootScope_) {
    $rootScope = _$rootScope_;
    controller.recount();
  }));

  describe('recount', function() {
    it('should call getRecordCounts on pouchdbService', function() {
      expect(pouchdbServiceMock.getRecordCounts).toHaveBeenCalled();
    });
  });
});

Calling pouchdbServiceMock.getRecordCounts in the last describe block generates an error:
TypeError: undefined is not an object (evaluating 'pouchdbServiceMock.getRecordCounts') in unit-tests/sync.controller.tests.js (line 29)

However pouchdbServiceMock is assigned in the second beforeEach block. What is wrong?

A: Your declaration of pouchdbServiceMock is a bit odd, at least from my experience doing tests in the last year.
pouchdbServiceMock = jasmine.createSpy('getRecordCounts', ['getRecordCounts']);
pouchdbServiceMock.getRecordCounts.and.returnValue(deferredRecount.promise);
$provide.value('pouchdbService', pouchdbServiceMock);

That's how I would structure it. Try it out, see if works.

A: The problem was, that the second beforeEach block had an error:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope

So it did not initialized the variable pouchdbServiceMock. I rewrote the block a little bit:
  beforeEach(inject(function($controller, $q, $rootScope) {
    deferredRecount = $q.defer();
    scope = $rootScope.$new();

    pouchdbServiceMock = {
      getRecordCounts: jasmine.createSpy('getRecordCounts spy').and.returnValue(deferredRecount.promise)
    };

    controller = $controller('inspector.SyncController', {
      '$scope': scope,
      'pouchdbService': pouchdbServiceMock
    });
  }));

This solved the problem.


text:
Q: Edit Configuration custom specific instrumentation runner missing property Android Studio 2.3 RC 1
Build #AI-162.3742087, built on February 16, 2017
JRE: 1.8.0_112-release-b06 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

I have created my own custom test runner that I want to use to run my instrumentation espresso tests.
I have entered this in the build.gradle file:
testInstrumentationRunner "me.androidbox.busbymovies.CustomTestRunner"

I have created my espresso tests, but under Edit Configuration there is no property to change from the default InstrumentationRunner to my custom one.

In earlier configuration there used to be a property called:
Specific Instrumentation Runner (Optional)

When I run my tests I get the error:
Cannot find any tests
Test running failed: Unable to find instrumentation info for: ComponentInfo{me.androidbox.busbymovies.debug.test/android.support.test.runner.AndroidJUnitRunner}

Before when I used to do this it was easy to switch to another instrumentation runner.
Many thanks for any suggestions on how to change your default test runner to your custom one,

A: I found the answer to my question.
My mistake was that I need to remove my Instrumented Test from the Edit Configuration and add a new one.
My build.gradle file was ok, and that is all you need to do to get this to work under the Android Studio 2.2.


text:
Q: Can I modify Devise params from within an app I have this homework from a security class where I need to make an app using some sort of authentification system. So I decided to use ruby on rails and I got it all working with devise at the moment.
But for this home work I need an admin to be able to go into an admin page within the app and be able to modify some security options like :

*

*Being able to lock people after too many login attempts

*Complexity of user password

I can't seem to find anything on the internet for this...
Is this possible ? Should I use another method ?
Thank you,
Guillaume


text:
Q: Grimmett and Stirzaker 1.5.5.b The question asks to show an example to show that conditional independence does not imply (nor is it implied by) independence.
In the solutions they include Example b:
Roll two dice; let A be the event that the smaller is 3, let B be the event that the larger
is 6, and let C be the event that the smaller score is no more than 3, and the larger is 4 or more. Then A and B are conditionally independent given C, but not independent.
1.) Why are A and B not independent? They correspond to different dice and the probabilities are P(A) = 1/3 and P(B) = 1/6. The probability of $P(A \cap B)$ is 2/36 which is 1/18 and therefore equal to P(A)p(B)?
2.) I'm also struggling to see how C would make the conditionally independent, but maybe that will be clearer when I have an answer to the first question.
Thanks


text:
Q: console.log(this) following by console.log(this.props) don't show same common values All is in the title.
I am using :"react": "16.8.6"
console.log(this) is showing good information
line following: console.log(this.props) is showing not expected data different from the one in console.log(this)
The plugin React dev tools gives me same good information as console.log(this)
Not the same "this" in both case? How is it possible?

A: Here is my code. You can point at console.log(this.props) in the getPost method!
import React from 'react'
import { Container, Row, Col, Alert } from 'reactstrap'

const Api = require('../lib/Api.js')

class PageComponent extends React.Component {

  constructor(props) {
    super(props)

    this.state = {
      page: {
        id: props.match.params.id,
        content: ''
      },
      loading: true,
      flashMessage: {
        message: undefined,
        style: 'success'
      }
    }

  }

  render() {
    if (this.state.loading) {
      return null
    }

    return (
      <Container>
        <Row>
          <Col xs="12" md="12">

            {this.state.flashMessage.message &&
              <Container>
                <Row>
                  <Col xs="12" md="12">
                    <Alert color={this.state.flashMessage.style}>
                      {this.state.flashMessage.message}
                    </Alert>
                  </Col>
                </Row>
              </Container>
            }

{this.state.page.content}

          </Col>
        </Row>
      </Container>
    )
  }

  componentDidMount() {
    this.getPage()
  }

  componentWillReceiveProps(nextProps) {

    let prevPageId = this.props.match.params.id
    let newPageId = nextProps.match.params.id

    // check if page component is being reloaded with new page props && reload page from Api
    if (prevPageId !== newPageId) {
      this.setState({
        page: {
          id: newPageId,
          content: ''
        }
      })
      this.getPage(newPageId)
    }
  }

  getPage(pageId = null) {
    pageId = pageId || this.state.page.id

    this.setState({
      loading: true,
      flashMessage: {
        message: undefined,
        style: 'success'
      }
    })
    console.log("from Page1")
    console.log(this)
    console.log(this.props)
    console.log(this.state)
    let jwt = this.props.appState.jwt
    console.log(jwt)

    Api.getPage(jwt, pageId).then(response => {
      if (response) {
        this.setState({
          page: response,
          loading: false
        })
      }
      else {
        this.setState({
          loading: false,
          flashMessage: {
            message: 'Access Denied.',
            style: 'danger'
          }
        })
      }
    })
  }

}

export default PageComponent

In console for console.log(this) I got:
PageComponent {props: {…}, context: {…}, refs: {…}, updater: {…}, state: {…}, …}
context: {}
props:
appState:
cookieName: "rails-react-token-auth-jwt"
email: "eric.london@example.com"
jwt:   "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NTkzODI3MTAsInN1YiI6MX0.hMSIIHK6jl3ftEkTCfbuVtgiUKjt-8dsfR2U-VAUjec"
pages: (4) [{…}, {…}, {…}, {…}]
user_id: 1
In console for console.log(this.props) I got:
appState:
cookieName: "rails-react-token-auth-jwt"
email: undefined
jwt: undefined
pages: []
user_id: undefined

A: OK...the former code is not mine and comes from:
https://github.com/EricLondon/Rails5-React-Token-Auth
I must say that code is working with old libraries
I did some refactoring because I don't trust "this" anymore from JS !!
Using Hooks and functions only code is much more readeable and 71 lines instead of 116 ! I am sold ....
New refactored code :
import React, { useState, useEffect } from 'react'
import { Container, Row, Col, Alert } from 'reactstrap'

const Api = require('../lib/Api.js')

export default function PageComponent(props)  {

  //states init n Hooks
  const [page, setPage] = useState({ id: props.match.params.id, content: ''})
  const [loading, setLoading] = useState(true)
  const [flashMessage, setFlashMessage] = useState({ message: undefined, style: 'success'})
  console.log(page.id)

  useEffect( () => {
    const pageId = props.match.params.id
    const getPage = () => {
      setLoading(true)
      setFlashMessage({
        message: undefined,
        style: 'success'
      })
      let jwt = props.appState.jwt
      console.log(jwt)

      Api.getPage(jwt, pageId).then(response => {
        if (response) {
          setPage(response)
          setLoading(false)
        }
        else {
          setPage({id:pageId, content: ''})
          setLoading(false)
          setFlashMessage({
            message: 'Access Denied.',
            style: 'danger'
          })
        }
      })
    }
    getPage()
  },[ props ])

  //rendering:

  if (loading) {
    return
Loading

  }
  else {
    return (
      <Container>
        <Row>
          <Col xs="12" md="12">

            {flashMessage.message &&
              <Container>
                <Row>
                  <Col xs="12" md="12">
                    <Alert color={flashMessage.style}>
                      {flashMessage.message}
                    </Alert>
                  </Col>
                </Row>
              </Container>
            }

{page.content}

          </Col>
        </Row>
      </Container>
    )}
}


text:
Q: Firebase REST API Authenticate With Phone Number I am using PAW to try and test different cloud functions deployed with Firebase. The app uses phone authentication, however currently there is little to no documentation on how to accomplish phone number authentication via REST API.
I have whitelisted a phone number for testing as per instructions here.
It appears that what I need to do is call on the verifyPhoneNumber method, which I have pieced together that the REST API endpoint I need is in the format:
https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPhoneNumber?key={WEB_API_KEY}

Now where I get stuck is in trying to pass the data that is expected. It looks like this endpoint expects a phoneNumber and an applicationVerifier object. I've pieced this together from the corresponding documentation here.
I try to make a request that looks like:
POST /identitytoolkit/v3/relyingparty/verifyPhoneNumber?key={WEB_API_KEY}
Content-Type: application/json; charset=utf-8
Host: www.googleapis.com
Connection: close
User-Agent: Paw/3.1.7 (Macintosh; OS X/10.13.6) GCDHTTPRequest
Content-Length: 73

{"phoneNumber":"+18035551111","applicationVerifier":{"type":"recaptcha"}}

The response I receive is:
HTTP/1.1 400 Bad Request
Vary: X-Origin
Vary: Referer
Content-Type: application/json; charset=UTF-8
Date: Thu, 13 Sep 2018 16:35:33 GMT
Server: ESF
Cache-Control: private
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Alt-Svc: quic=":443"; ma=2592000; v="44,43,39,35"
Accept-Ranges: none
Vary: Origin,Accept-Encoding
Connection: close

{
  "error": {
    "code": 400,
    "message": "MISSING_SESSION_INFO",
    "errors": [
      {
        "message": "MISSING_SESSION_INFO",
        "domain": "global",
        "reason": "invalid"
      }
    ]
  }
}

I'm not sure what I'm doing wrong at this point as I'm running out of documentation and sort of just blindly guessing parameters now. How can I authenticate via white-listed phone number via REST API for testing?

A: *

*Create you verification code request (the key is an environment variable)

*(but this is optional) make the session info a Body Response Dynamic Value

*Create your verify phone number request

*(again, optional) make the idToken also a Body Response Dynamic Value

*Use the idToken dynamic value in any other subsequent requests you perform to Firebase

The best part about adding the variables as Body Response Dynamic Values is you can chain them and call them in a sequence:

A: For the REST API POST, you have to pass the reCAPTCHA token instead of the captcha object you are passing. You can obtain the token in the callback function when you create RecaptchaVerifier
        window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('my_btn', {
            'size': 'invisible',
            'callback': function(response) {
                // reCAPTCHA solved, allow signInWithPhoneNumber.
                recaptchaToken = response;
                .....
            }
        });

This article helped me - https://medium.com/@shangyilim/verifying-phone-numbers-with-firebase-phone-authentication-on-your-backend-for-free-7a9bef326d02

A: After a lot of research (I'm struggling to create automated tests for my "login with phone" flow), I finally found a solution for this, based on @Danut Pralea's answer. Hopefully it will help people in future :)
Considering that your phone number is already whitelisted (as mentioned in the question), first step would be a call to firebase to send the verification code:
POST /v1/accounts:sendVerificationCode?key={WEB_API_KEY} HTTP/1.1
Host: identitytoolkit.googleapis.com:443
Content-Type: application/json
Content-Length: 39

{
    "phoneNumber": "{PHONE_NUMBER}"
}

The response will be the sessionInfo, like this:
{
    "sessionInfo": "ALiwoWJhYJgtFav1DKc0yBoTwcjjiyQNu240eDJ76GmlH-2i3RmHAYamaPkx3rjEmOBcgrua5QfLw8Nrn_QwjVPO6N09fYsiWQha0-5o2Jb5Hwqxkw7qwsl6YK0gotZ16HmiwqJkyd-stAXTVU1ZIBUwfrFqZmFY7g"
}

Then, the next step is to use login in firebase with the code (same used in the whitelisting) and the session info:
POST /v1/accounts:signInWithPhoneNumber?key={WEB_API_KEY} HTTP/1.1
Host: identitytoolkit.googleapis.com:443
Content-Type: application/json
Content-Length: 207

{
    "sessionInfo": "ALiwoWJhYJgtFav1DKc0yBoTwcjjiyQNu240eDJ76GmlH-2i3RmHAYamaPkx3rjEmOBcgrua5QfLw8Nrn_QwjVPO6N09fYsiWQha0-5o2Jb5Hwqxkw7qwsl6YK0gotZ16HmiwqJkyd-stAXTVU1ZIBUwfrFqZmFY7g",
    "code": 123456
}

And that's it! Response will be something like:
{
    "idToken": "idToken",
    "refreshToken": "refreshToken",
    "expiresIn": "3600",
    "localId": "localId",
    "isNewUser": false,
    "phoneNumber": "{PHONE_NUMBER}"
}

More info in the official documentation: https://cloud.google.com/identity-platform/docs/reference/rest/v1/accounts


text:
Q: Fitting a GAMM for non-gaussian response variable in R (package gamm4) I am trying to model two variables showing a non-linear relationship, as shown in the scatterplot below, with a Generalized Additive Mixed Model in R (package 'gamm4). The data represents roughly 15 years of data about wildlife monitoring, across more than 150 areas.

The response variable does not follow a Gaussian distribution (skewness=4.31, kurtosis=27.15, see histogram below) and I would like to know which distribution may be suitable to model the error term of a GAMM.

Unfortunately, I have seen that most of the 'family' options are available for GAM only, and cannot be used for mixed-effect models.
I have noticed that gamm4 allows for a Tweedie distribution of the error, which can be a suitable option for my data. Indeed, an automatic specification of the optimal parameter cannot be achieved for GAMM (e.g like in GAM: family=tw()) and I have do specify the shape parameters by myself.
I guess it will be a matter of trial and error. I would like to ask you two things:

*

*Do you think that the Tweedie distribution can be a valuable distribution for the error? What about other distributions?

*How can I decide the most suitable values (theta and power) for the Tweedie distribution?

*Is there any approach for unknown shape parameters, based performance iteration, for the package 'gamm4'?

I have mentioned the package 'gamm4', but even older packages (e.g 'gamm') are accepted.
Kind regards,
Jacopo


text:
Q: Change label on an mxgraph cell/vertex I've created an interface, including mxgraph (javascript), that allows a user to click on a cell and edit the cell's label in a regular form text input that's separate from the graph.  I'd like to change the cell's label after the user saves the form (ajax submit) without having to reload the graph.
I really don't need to do anything fancy with a cell/vertext label, but I do need to be able to change it's text.  I don't need HTML labels if that's avoidable.  And, I haven't found something like a "setLabel" method in the API.
Sounds like a simply thing.  What am I missing?
Thanks

A: Set the value on the cell via the model:
graph.model.setValue(cell, value);


text:
Q: I want to make this json in table form in dynamic way, how can i make it in android? String jsonData="{\"sem1\" :[{\"subname\":\"TOC\",\"subcode\":\"1009\",\"subcredit\":\"6\",\"subgrade\":\"AB\"},{\"subname\":\"DS\",\"subcode\":\"10090\",\"subcredit\":\"5\",\"subgrade\":\"BB\"},{\"subname\":\"TOC\",\"subcode\":\"1009\",\"subcredit\":\"6\",\"subgrade\":\"AB\"}],\"sem2\":[{\"subname\":\"AAS\",\"subcode\":\"111009\",\"subcredit\":\"6\",\"subgrade\":\"AB\"},{\"subname\":\"AE\",\"subcode\":\"103309\",\"subcredit\":\"6\",\"subgrade\":\"DD\"}]}";

Here is My Code :
 protected String doInBackground(String... params1) {

        try {
            jsonObject = new JSONObject(jsondata);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Iterator<String> iter = jsonObject.keys();
        while (iter.hasNext()) {
            String key = iter.next();

            try {
                JSONArray jsonArray = jsonObject.getJSONArray(key);
                int length = jsonArray.length();
                for (int i = 0; i < length; i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    subname = jsonObject1.getString("subname");
                    subcode = jsonObject1.getString("subcode");
                    subcredit = jsonObject1.getString("subcredit");
                    subgrade = jsonObject1.getString("subgrade");

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        return null;
    }

A: create a listview and add values to it.
 private List<YourListcontainer> listContainer = new ArrayList<YourListcontainer>();

Get your json values and add it in yourListContainer.
 MyListAdapter adapter = new MyListAdapter();
 Listview lv = (ListView) rootView.findViewById(R.id.lvid);
 lv.setAdapter(adapter);

 private class MyListAdapter extends ArrayAdapter<YourListcontainer> {

    public MyListAdapter() {
        // calls the base class constructor.
        super(context, R.layout.list_adapter, listContainer);

// context,resources,object
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View itemview = convertView;
        LayoutInflater listView = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (itemview == null) {
            itemview = listView.inflate(R.layout.list_adapter,
                    parent, false);
        }
        final YourListContainer item = listContainer.get(position);// returns the index of the cell
        TextView subject = (TextView) itemview
                .findViewById(R.id.txvsubject);
        subject.setText(item.getSubjectname());
        TextView code= (TextView) itemview
                .findViewById(R.id.txvcode);
        code.setText(item.getCode());
        TextView credit = (TextView) itemview
                .findViewById(R.id.txvcredit );
        credit .setText(item.getCredit ());
        TextView grade = (TextView) itemview
                .findViewById(R.id.txvgrade );
        grade .setText(item.getGrade ());

            subject.setBackgroundResource(R.drawable.borderstyle);
            code.setBackgroundResource(R.drawable.borderstyle);
            credit.setBackgroundResource(R.drawable.borderstyle);
            grade.setBackgroundResource(R.drawable.borderstyle);

        return itemview;
    }

}

Note: These border style is for draw your border.xml in table form like box type .


text:
Q: 33/31/32 frames skipped, although i'm using runOnUiThread My imageview animation skips frames although i am using runOnUiThread. Does anyone know what i'm doing wrong? Here's my java code:
import android.app.Activity;
import android.os.*;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;

public class MainActivity extends Activity {

ImageView a;
TranslateAnimation pengesat;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    a = (ImageView) findViewById(R.id.imageView3);
    pengesat = new TranslateAnimation( 0.0f,  300.0f,  0.0f,  0.0f );
    pengesat.setDuration(5000);
    pengesat.setRepeatCount(2);
    pengesat.setInterpolator(new LinearInterpolator());
    new Thread(new Runnable(){
        @Override
        public void run() {
              runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                      a.startAnimation(pengesat);
                  }
              });
        }
    }).start();
    }
   }

And here's my xml code. I am only using four imageViews, may the Images' sizes be too large? I have seen many tutorials and i think i am using threads right, but why does the frames skip, and why does it say that the main thread may be doing too much work??
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@string/layout"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ennio.lojaprove.MainActivity">

<ImageView
    android:id="@+id/img"
    android:src="@drawable/bg"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:src="@drawable/border"
    android:scaleType="centerCrop"
    android:layout_alignTop="@+id/img"
    android:layout_centerHorizontal="true" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView2"
    android:src="@drawable/border"
    android:scaleType="centerCrop"
    android:layout_alignBottom="@+id/img"
    android:layout_centerHorizontal="true" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView3"
    android:src="@drawable/pengesa"
    android:layout_above="@+id/imageView2"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

 </RelativeLayout>

A: If you're skipping frames it's likely because the main thread is doing too much work. The other possibility is that you're blocking the main thread in some way (waiting on async call, sleep, etc). In this case, however, from your code I would suspect it's because it's doing too much work.
A bigger problem I see, though, is that you shouldn't be spawning a thread here.
new Thread(new Runnable(){
    @Override
    public void run() {
          runOnUiThread(new Runnable() {
              @Override
              public void run() {
                  a.startAnimation(pengesat);
              }
          });
    }
}).start();

What this does is create a separate thread that lives very briefly. All it does in this short time is add a runnable to be executed on the main thread.
You should replace the above code with the following:
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        a.startAnimation(pengesat);
    }
});

In the case of seeing skipped frames on the android emulator, you probably don't have to worry unless the number is greater than 60 or so. The android emulator is extremely slow and I would not be surprised to see skipped frames on it especially when doing animations. You can safely ignore this message (in this case).

Supposedly, if you're still getting this message on a real device, this might be a potential solution:
a = (ImageView) findViewById(R.id.imageView3);
pengesat = new TranslateAnimation( 0.0f,  300.0f,  0.0f,  0.0f );
pengesat.setDuration(5000);
pengesat.setRepeatCount(2);
pengesat.setInterpolator(new LinearInterpolator());
a.setAnimation(pengesat); //<-- this line here is new

I've read somewhere that on android 4.2.2 you have to set the animation being used on the view before calling startAnimation. I have never tried this myself but might extend to 5.0+ android


text:
Q: Why don't we have timeout for review audit questions? Why don't we have timeout for review audits?
Consider the following scenario:

*

*User A access the review queue.

*He/she chooses one question, which happens to be a review audit.

*User A won't take any actions.

*User B access the review queue also.

*User B comments on the low quality posts.

*User A viewing the content can see the comment that user B made, and user A can simply bypass the review audits.


text:
Q: Printing NSView to PDF not working as expected I converted in PDF an NSView (PDFContentView:NSView) with the method NSPrintOperation. This NSView contains 2 subviews (Drawing:NSView). This subviews are drawn using the drawRect method.
The expected result is correct when I display my view in a NSWindow :

But in the PDF file, the second subview seem to be included in the first :

It seems to be a problem of layers, but when I change setWantsLayer: to NO, it's the same result.
Nota : I found answers that recommend to convert the subviews, which are drawn by drawRect method, into NSImage and then add it to the View. But This solution don't fit my problem, because I need to keep the possibility of zooming in the pdf without pixelising the subviews.
Thank you for your help.
Here is my code :
The method to convert my pdfContentView in PDF :
- (void)createPDFWithPages
{
    NSPrintInfo *printInfo;
    NSPrintInfo *sharedInfo;
    NSPrintOperation *printOp;
    NSMutableDictionary *printInfoDict;
    NSMutableDictionary *sharedDict;

    sharedInfo = [NSPrintInfo sharedPrintInfo];
    sharedDict = [sharedInfo dictionary];
    printInfoDict = [NSMutableDictionary dictionaryWithDictionary:sharedDict];

    [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *desktopURLArray = [fileManager URLsForDirectory:NSDesktopDirectory inDomains:NSUserDomainMask];
    NSURL *desktopURL = [desktopURLArray objectAtIndex:0];
    NSString *fileName = [NSString stringWithFormat:@"/%@", @"myPDF.pdf"];
    NSURL *fileURL = [NSURL fileURLWithPath:[[desktopURL path] stringByAppendingString:fileName]];

    [printInfoDict setObject:[fileURL path] forKey:NSPrintSavePath];

    printInfo = [[NSPrintInfo alloc] initWithDictionary: printInfoDict];
    [printInfo setTopMargin:30.0];
    [printInfo setBottomMargin:30.0];
    [printInfo setLeftMargin:30.0];
    [printInfo setRightMargin:30.0];
    [printInfo setHorizontalPagination: NSAutoPagination];
    [printInfo setVerticalPagination: NSAutoPagination];
    [printInfo setVerticallyCentered:NO];

    printOp = [NSPrintOperation printOperationWithView:pdfContentView printInfo:printInfo];

    [printOp setShowsPrintPanel:NO];
    [printOp runOperation];
}

PDFContentView.m :
#import "PDFContentView.h"
#import "Drawing.h"

@interface PDFContentView ()
{
    Drawing *drawing1;
    Drawing *drawing2;
}
@end

@implementation PDFContentView

- (id)init
{
    if(self = [super init])
    {
        self.frame = NSMakeRect(10, 10, 520, 780); //page size = (520, 780)
        [self setWantsLayer:YES];
        self.layer.backgroundColor = [NSColor whiteColor].CGColor;

        drawing1 = [[Drawing alloc] initWithFrame:NSMakeRect(0, 20, 50, 50)];
        [drawing1 setBackgroundColor:[NSColor greenColor]];
        [self addSubview:drawing1];

        drawing2 = [[Drawing alloc] initWithFrame:NSMakeRect(30, 0, 50, 50)];
        [drawing2 setBackgroundColor:[NSColor yellowColor]];
        [self addSubview:drawing2];
    }

    return self;
}

- (BOOL)isFlipped
{
    return YES;
}

@end

Drawing.m :
#import "Drawing.h"

@interface Drawing ()
{
    NSColor *backgrounColor;
}
@end

@implementation Drawing

- (id)initWithFrame:(NSRect)contentRect
{
    if(self = [super initWithFrame:(NSRect)contentRect])
    {
        self.frame = contentRect;
        [self setWantsLayer:YES];

        backgrounColor = [[NSColor alloc] init];
        backgrounColor = [NSColor colorWithCalibratedRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:255.0/255.0];
    }

    return self;
}

- (BOOL)isFlipped
{
    return YES;
}

- (void)setBackgroundColor:(NSColor*)color;
{
    backgrounColor = color;

    [self setNeedsDisplay:YES];
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];

    CGMutablePathRef path00 = CGPathCreateMutable();

    CGPathMoveToPoint(path00, NULL, 0, 0);
    CGPathAddLineToPoint(path00, NULL, self.frame.size.width, 0);
    CGPathAddLineToPoint(path00, NULL, self.frame.size.width, self.frame.size.height);
    CGPathAddLineToPoint(path00, NULL, 0, self.frame.size.height);
    CGPathCloseSubpath(path00);

    CGContextSaveGState(context);
    CGContextAddPath(context, path00);
    CGContextSetFillColorWithColor(context, backgrounColor.CGColor);
    CGContextFillPath(context);
    CGContextRestoreGState(context);

    CGRect borderRect = NSMakeRect(0.5, 0.5, 24, 24);
    CGMutablePathRef borderPath = CGPathCreateMutable();
    CGPathAddRect(borderPath, NULL, borderRect);
    CGPathCloseSubpath(borderPath);

    CGContextSaveGState(context);
    CGContextAddPath(context, borderPath);
    CGContextSetStrokeColorWithColor(context, [NSColor redColor].CGColor);
    CGContextSetLineWidth(context, 1);
    CGContextStrokePath(context);
    CGContextRestoreGState(context); // => Missing funtion

    CGMutablePathRef path2 = CGPathCreateMutable();
    CGRect aRect = NSMakeRect(10, 11, 4, 4);
    CGPathAddRect(path2, NULL, aRect);
    CGPathCloseSubpath(path2);

    CGContextSaveGState(context);
    CGContextAddPath(context, path2);
    CGContextSetShouldAntialias(context, NO);
    CGContextSetStrokeColorWithColor(context, [NSColor blueColor].CGColor);
    CGContextSetLineWidth(context, 1);
    CGContextStrokePath(context);
    CGContextRestoreGState(context); // => Missing funtion
}

@end


text:
Q: Как объявить переменную через eval / new Function? Столкнулся с такой проблемой, что переменные, объявленные в eval, не видны при следующем вызове eval. Что можно придумать? Пытаюсь сделать js REPL на js.

// Вот так работает -
console.log(eval(`
  let t = 1;
  ++t;
`)); // > 2

// А вот так уже нет -
eval('let t = 1;');
try{
    eval('++t;'); // > t is not defined!
}catch(e){console.error(e)}

A:

eval('let a = 1;');
eval('var b = 1;');

console.log(typeof a);
console.log(typeof b);

{let c = 1;}
let d = 1;

console.log(typeof c);
console.log(typeof d);

let e = {};
eval('e.a = 1;');
console.log(e);


text:
Q: how to hide a dynamic data bind column after checking a condition in vue-table2 I used the Vue-table2 component for tables. I want to hide a column in my table after checking the value of the isAllowColorPlate.If that value is False, I want to  hide the column called Color.Data bind using an API called apiUrl using fields.Please help me to hide the column.
vuetable :
            <vuetable
              :css="css.table"
              ref="vuetable"
              :api-url="apiUrl"
              http-method="post"
              :fields="fields"
              data-path="data"
              pagination-path="summary"
              @vuetable:pagination-data="onPaginationData"
              :append-params="moreParams"
              @vuetable:loading="onLoading"
              @vuetable:load-error="onLoadError"
              @vuetable:loaded="onLoaded"
              :sort-order="sortOrder"
              :per-page="perPage"
              track-by="ItemId"
            >
              <template slot="FoodCategoryName" scope="props">

              </template>
              <template slot="ItemName" scope="props">

              </template>
              <template
                v-if="this.isAllowColorPlate == 'True'"
                slot="Color"
                scope="props"
              >

                  <input type="Color" v-model="props.rowData.Color" disabled />

              </template>
              <template slot="Status" scope="props">

              </template>
              <template slot="action-edit" scope="props">

              </template>
              <template slot="action-delete" scope="props">

              </template>
            </vuetable>

Return values :
    return {
      isAllowColorPlate: "True",
      isLoading: false,
      recordCount: 0,
      apiUrl: this.$http.defaults.baseURL + "/api/xxxx/search",
      fields: [
        {
          name: VuetableFieldCheckbox,
          title: "checkbox",
          width: "30px",
          titleClass: "center aligned",
          dataClass: "center aligned",
        },
        {
          name: "FoodCategoryName",
          title: "Catagory Name",
          sortField: "FoodCategoryName",
        },
        {
          name: "ItemName",
          title: "Item Name",
          sortField: "ItemName",
        },
        {
          name: "Color",
          title: "Colour",
          sortField: "Color",
        },
        {
          name: "Status",
          title: "Status",
          sortField: "IsInActive",
          width: "10%",
        },
        {
          name: "action-edit",
          title: "Edit",
          width: "5%",
        },
        {
          name: "action-delete",
          title: "Delete",
          width: "5%",
        },
      ],
      sortOrder: [
        {
          field: "ItemName",
          direction: "asc",
        },
      ],
      filterText: "",
      perPage: 10,
      moreParams: {},
      css: {
        table: {
          tableClass: "table table-bordered",
          loadingClass: "loading",
          ascendingIcon: "glyphicon glyphicon-chevron-up",
          descendingIcon: "glyphicon glyphicon-chevron-down",
          handleIcon: "glyphicon glyphicon-menu-hamburger",
        },
        pagination: {
          wrapperClass: "pagination float-right",
          activeClass: "active",
          disabledClass: "disabled",
          pageClass: "page-item",
          linkClass: "page-link",
          paginationClass: "pagination",
          paginationInfoClass: "float-left",
          dropdownClass: "form-control",
          icons: {
            first: "fa fa-chevron-left",
            prev: "fa fa-chevron-left",
            next: "fa fa-chevron-right",
            last: "fa fa-chevron-right",
          },
        },
      },
    };
  },

A: In vuetable2, you can use the visible prop to hide/show the fields. Like this-
let fields = [
  {
    name: 'name',
    sortField: 'name'
    visible: false,
  },
  {
    name: 'email',
    title: 'Email Address',
    visible: 4 == 4
  },
]

On another note, I would like to add a few things -

*

*The visible prop accepts boolean values but I can see you are using "True/False" which is a string, so either use the boolean or make sure to provide the boolean by any logic.

*If your fields are not modifiable, then it's better to make a computed property of fields so you can use data properties inside it for comparison (it would make code clearer) and that would be reactive too.

Now, as per your requirement, you can use the visible prop like this-
data() {
  return {
    isAllowColorPlate: "False",
  };
},

computed: {
  fields() {
    return [
      {
        name: "Color",
        title: "Colour",
        sortField: "Color",
        visible: this.isAllowColorPlate === "True",
      },
      {
        name: "FoodCategoryName",
        title: "Catagory Name",
        sortField: "FoodCategoryName",
      },
    ];
  },
},


text:
Q: Puppet facter, how to set custom facts from yaml file? I want to be able to set a number of different custom facts for puppet.  It looks like there is a way to list all of these out in a yaml file and then load them in, but the documentation does not have the exact command to do that.
How can I set custom facts from a yml file?  If I cant do this, is there any other method that I can set facts without having to build custom ruby scripts that all run through Facter.add functions?

A: These types of facts are known as "external facts." They can either be executables, or files in text or supported markup formats. The proper location to store them is in the facts.d directory within the relevant module. Note the documentation on where to store external facts here: https://docs.puppet.com/facter/3.8/custom_facts.html#fact-locations. These fact files will automatically be copied over to client nodes and loaded during pluginsync near the beginning of a Puppet agent execution. Recall that this will occur for any catalog that includes the modulepath this module is located in (normally the relevant directory environment).
Given an example module foo, the directory structure would look like:
foo
|__facts.d
   |__ bar.yaml
   |__ bar.json
   |__ bar.txt

With example content like the following:
# foo/facts.d/bar.yaml
fact_name: fact_value

# foo/facts.d/bar.json
{
  fact_name: fact_value
}

# foo/facts.d/bar.txt
fact_name=fact_value

You can then use these facts as per normal in your Puppet code like $facts['fact_name'] or on older Facter $::fact_name. You can also view them on clients using the puppet plugin argument to Facter via facter -p.

A: You can just write your facts in a yaml file in the facts.d directory.
For example, you can create a /etc/facter/facts.d/my_custom_fact.yaml :
my_fact: 42

This will create a fact my_fact, with value 42.
You can check if it worked by typing facter, and check if you fact is present.


text:
Q: TypeScript error when setting a component's state: Argument of type 'X' is not assignable to parameter of type '() => void' I am having a TypeScript error when calling setState:

That's what I am actually doing:
  updateRequests(requests: any, cb:Function|null = null) {
    this.setState(
      {
        requests: {
          ...this.state.requests,
          items: requests,
          loading: false,
        },
      },
      () => {
        if (cb) cb();
      }
    );

Here's a Component state:
export interface IServersScreenState {
  requests: {
    items: [];
    loading: boolean;
    statuses: {};
    page: number;
    lastPage: number;
    scrollLoading: boolean;
  };
}

Don't actually understand why it's happening like that, because I don't have any declaration in the state, that requests needs to be look like ()=>void
here's my setState:
  setState<T>(...args: T[]) {
    if (this.__mounted__) {
      //@ts-expect-error spread error
      super.setState(...args) as $TSFixMe;
    }
  }

A: You've defined setState to accept a generic, and then aren't filling in the generic when it's called. Try replacing
this.setState(
with
this.setState<IServersScreenState>(
That should get you closer to following the type you've set up.


text:
Q: Building a grid of Youtube Videos I am trying to make a grid of youtube videos on a web page, the grid itself will be made up of the thumbnails of the videos - once I click them then the video opens up.
I am nearly at the end but I have hit a major wall which I cant seem to get past - i am an amateur programmer btw.
So, once I get the json data back from the youtube api, Ive used the datacontractjsonserializer class to store all of the information within classes i have defined. This leaves me with essentially, with an array of items - videos - which i can run through and do whatever.
I want to be able to run through the array of videos, and create a new every time and also add properties to it such as give it a css class etc. This is so that the website is not limited to a certain amount of videos and can display as many as the youtube api returns.
any ideas appreciated thanks,
this is what i have so far;
foreach (var vid in playlist.items)
{
    System.Web.UI.HtmlControls.HtmlGenericControl createDiv =
        new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
    createDiv.Style = "float: left";
    System.Web.UI.HtmlControls.HtmlImage img =
        new System.Web.UI.HtmlControls.HtmlImage();
    img.Src = vid.snippet.thumbnails.@default.url;
    img.Border = 0;
    img.Style = "width:80px; height:55px; margin-right:10px; margin-bottom:10px;";
    createDiv.InnerHtml = img;

}

The above code simply doesn't compile and even if it did it wouldnt work.
I also created an image for the thumbnail
            System.Web.UI.HtmlControls.HtmlImage img =
                new System.Web.UI.HtmlControls.HtmlImage();
            img.Src = vid.snippet.thumbnails.@default.url;

which needs to be stored within the div class. I also need them to follow certain css styles-how do i link it to my css sheet?
I am basically trying to replicate

within the loop. Where XXXX and AAAA isdata retrieved from the yt api.
As requested, this is an example of a json response
{
 "kind": "youtube#playlistItemListResponse",
 "etag": "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/b7tV9rFfqslF-60lBe43V9qWMqA\"",
 "nextPageToken": "CAUQAA",
 "pageInfo": {
  "totalResults": 26,
  "resultsPerPage": 5
 },
 "items": [
  {
   "kind": "youtube#playlistItem",
   "etag": "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/5sFoyW9dWRWrqgXNUY935g7zYGw\"",
   "id": "UkQwOVI4XzJuSnRqZy4wOVI4XzJuSnRqZw==",
   "snippet": {
    "publishedAt": "2015-01-14T15:00:11.000Z",
    "channelId": "UCBR8-60-B28hp2BmDPdntcQ",
    "title": "Maroon 5 - Sugar",
    "description": "Buy Sugar on iTunes: http://smarturl.it/M5V\n\nTickets for Maroon 5's North American with Rozzi Crane and European Tour with Nick Gardner are on-sale now! http://www.maroon5.com/\n\nMusic video by Maroon 5 performing Sugar. (C) 2015 Interscope Records",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/09R8_2nJtjg/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/09R8_2nJtjg/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/09R8_2nJtjg/hqdefault.jpg",
      "width": 480,
      "height": 360
     },
     "standard": {
      "url": "https://i.ytimg.com/vi/09R8_2nJtjg/sddefault.jpg",
      "width": 640,
      "height": 480
     }
    },
    "channelTitle": "YouTube Spotlight",
    "playlistId": "RD09R8_2nJtjg",
    "position": 0,
    "resourceId": {
     "kind": "youtube#video",
     "videoId": "09R8_2nJtjg"
    }
   }
  },
  {
   "kind": "youtube#playlistItem",
   "etag": "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/8qf4tj_LOI5PwxemtJWYiNACZ5s\"",
   "id": "UkQwOVI4XzJuSnRqZy5PUGYwWWJYcURtMA==",
   "snippet": {
    "publishedAt": "2014-11-19T14:00:18.000Z",
    "channelId": "UCBR8-60-B28hp2BmDPdntcQ",
    "title": "Mark Ronson - Uptown Funk ft. Bruno Mars",
    "description": "Mark Ronson – Uptown Funk ft. Bruno Mars\nFrom the album Uptown Special, out now: http://smarturl.it/UptownSpecial?IQid=yt \n\n-------------------------\n\nFollow Mark Ronson online:\nWebsite: http://www.markronson.co.uk\nTwitter: http://twitter.com/MarkRonson\nFacebook: http://www.facebook.com/markronson\nInstagram: http://instagram.com/iammarkronson\nSpotify: http://smarturl.it/RonsonStrm?IQid=yt\n\nMusic video by Mark Ronson feat. Bruno Mars performing Uptown Funk. (C) 2014 Sony Music Entertainment UK Ltd.",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/OPf0YbXqDm0/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/OPf0YbXqDm0/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/OPf0YbXqDm0/hqdefault.jpg",
      "width": 480,
      "height": 360
     },
     "standard": {
      "url": "https://i.ytimg.com/vi/OPf0YbXqDm0/sddefault.jpg",
      "width": 640,
      "height": 480
     }
    },
    "channelTitle": "YouTube Spotlight",
    "playlistId": "RD09R8_2nJtjg",
    "position": 1,
    "resourceId": {
     "kind": "youtube#video",
     "videoId": "OPf0YbXqDm0"
    }
   }
  },
  {
   "kind": "youtube#playlistItem",
   "etag": "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/k0QjzQlUFBtx9xt7sa3G8xyGFwc\"",
   "id": "UkQwOVI4XzJuSnRqZy5BSnREWElhenJNbw==",
   "snippet": {
    "publishedAt": "2015-01-22T08:00:06.000Z",
    "channelId": "UCBR8-60-B28hp2BmDPdntcQ",
    "title": "Ellie Goulding - Love Me Like You Do (Official Video)",
    "description": "iTunes: http://ell.li/EGLMLYDiTYT\nSpotify: http://ell.li/LMLYDspotify\n\nFrom the forthcoming Fifty Shades of Grey film and soundtrack.\n\nMore Ellie:\nhttp://www.elliegoulding.com\nhttp://www.facebook.com/elliegoulding\nhttp://www.twitter.com/elliegoulding\nhttp://www.instagram.com/elliegoulding\nhttps://play.spotify.com/user/elliegouldingofficial\n\n\nMusic video by Ellie Goulding performing Love Me Like You Do. (C) 2015 Polydor Ltd. (UK)",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/AJtDXIazrMo/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/AJtDXIazrMo/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/AJtDXIazrMo/hqdefault.jpg",
      "width": 480,
      "height": 360
     },
     "standard": {
      "url": "https://i.ytimg.com/vi/AJtDXIazrMo/sddefault.jpg",
      "width": 640,
      "height": 480
     },
     "maxres": {
      "url": "https://i.ytimg.com/vi/AJtDXIazrMo/maxresdefault.jpg",
      "width": 1280,
      "height": 720
     }
    },
    "channelTitle": "YouTube Spotlight",
    "playlistId": "RD09R8_2nJtjg",
    "position": 2,
    "resourceId": {
     "kind": "youtube#video",
     "videoId": "AJtDXIazrMo"
    }
   }
  },
  {
   "kind": "youtube#playlistItem",
   "etag": "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/eAcdGURRFc7MFSYaeTUSnzUQtU8\"",
   "id": "UkQwOVI4XzJuSnRqZy5lLU9SaEVFOVZWZw==",
   "snippet": {
    "publishedAt": "2014-11-10T17:05:44.000Z",
    "channelId": "UCBR8-60-B28hp2BmDPdntcQ",
    "title": "Taylor Swift - Blank Space",
    "description": "Watch Taylor's new video for \"Blank Space\".  No animals, trees, automobiles or actors were harmed in the making of this video.  Taylor's new release 1989 is Available Now on iTunes http://www.smarturl.it/TS1989.",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/e-ORhEE9VVg/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/e-ORhEE9VVg/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/e-ORhEE9VVg/hqdefault.jpg",
      "width": 480,
      "height": 360
     },
     "standard": {
      "url": "https://i.ytimg.com/vi/e-ORhEE9VVg/sddefault.jpg",
      "width": 640,
      "height": 480
     },
     "maxres": {
      "url": "https://i.ytimg.com/vi/e-ORhEE9VVg/maxresdefault.jpg",
      "width": 1280,
      "height": 720
     }
    },
    "channelTitle": "YouTube Spotlight",
    "playlistId": "RD09R8_2nJtjg",
    "position": 3,
    "resourceId": {
     "kind": "youtube#video",
     "videoId": "e-ORhEE9VVg"
    }
   }
  },
  {
   "kind": "youtube#playlistItem",
   "etag": "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/v5Vm-iso_u1p8rya8nb-IevUHGQ\"",
   "id": "UkQwOVI4XzJuSnRqZy5scC1FTzVJNjBLQQ==",
   "snippet": {
    "publishedAt": "2014-10-07T13:57:37.000Z",
    "channelId": "UCBR8-60-B28hp2BmDPdntcQ",
    "title": "Ed Sheeran - Thinking Out Loud [Official Video]",
    "description": "The official video for 'Thinking Out Loud', Ed learnt to dance! \n'x', available to buy via iTunes here: http://smarturl.it/x-itunesdlx\nFeaturing and taught by @dance10Brittany and @dance10Paul\n\nSubscribe to my channel: http://bit.ly/SubscribeToEdSheeran\nGo behind the scenes of the video: http://bit.ly/ThinkingOutLoudBTS\nHear the rest of my album, 'x': http://bit.ly/XOfficialPlaylist\nAudio of 'Thinking Out Loud': http://youtu.be/WpyfrixXBqU\n\nHey German fans! View here: http://smarturl.it/ThinkingOutLoud-DE\n\nBuy on CD & Vinyl here: http://smarturl.it/x-album\nBuy on Google Play: http://smarturl.it/x-googleplaydlx\n\nFollow me on...\nFacebook: http://www.facebook.com/EdSheeranMusic\nTwitter: http://twitter.com/edsheeran\nInstagram: http://instagram.com/teddysphotos\nOfficial Website: http://edsheeran.com",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/lp-EO5I60KA/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/lp-EO5I60KA/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/lp-EO5I60KA/hqdefault.jpg",
      "width": 480,
      "height": 360
     },
     "standard": {
      "url": "https://i.ytimg.com/vi/lp-EO5I60KA/sddefault.jpg",
      "width": 640,
      "height": 480
     },
     "maxres": {
      "url": "https://i.ytimg.com/vi/lp-EO5I60KA/maxresdefault.jpg",
      "width": 1280,
      "height": 720
     }
    },
    "channelTitle": "YouTube Spotlight",
    "playlistId": "RD09R8_2nJtjg",
    "position": 4,
    "resourceId": {
     "kind": "youtube#video",
     "videoId": "lp-EO5I60KA"
    }
   }
  }
 ]
}

A: Modified your wrong code:
 System.Web.UI.HtmlControls.HtmlGenericControl createDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
    createDiv.Style.Add("float", "left");
    System.Web.UI.HtmlControls.HtmlImage img =
        new System.Web.UI.HtmlControls.HtmlImage();
    img.Src = "Your source code.";
    img.Border = 0;
    img.Style.Add("width", "80px");
    img.Style.Add("margin-right", "10px");
    img.Style.Add("margin-bottom", "10px");
    createDiv.Controls.Add(img);

    tstPanel.Controls.Add(createDiv);

aspx:
 <asp:Panel runat="server" ID="tstPanel"></asp:Panel>

Atleast this is compiling and working at my end.


text:
Q: Why we can't see objects smaller than wave length of light? I would like to ask, why we can't see objects smaller than wave length of light under traditional microscope. I know that there is some way to see them and the scientists who discover this.

Why we can't see objects smaller than wave length of light?
And who were these scientists?

A:
I would like to ask, why we can't see objects smaller than wave length of light under traditional microscope.

The wavelength of light is any wavelength.  There's visible light (which is what I think you mean) and then there's every possible wavelength above and below that.
Our eyes don't detect light (electromagnetic radiation) outside of the visible region (hence the name :-)) but we can use and do machines to detect these wavelengths and you've probably experienced them : X-ray machines, UV lights for security purpose, infra-red lights for remote controls.
Whatever wavelength you use is going to diffraction limited for resolution.  As this detailed article explains, the limit for resolution (and that's assuming everything else is optimal) is about half the wavelength used.
Optical microscopes are designed for the visible wavelengths of light and focus light outside of this region well.  You can use special optics designed for that purpose if your interest is outside of visible light.
The development and use of microscopes, not just visible light microscopes, is called Microscopy.  That link should provide you with enough information to start with.

I know that there is some way to see them and the scientists who discover this.

Beyond light microscopes, scientists developed the electron microscope and later the scanning tunneling microscope.  The principles of these devices are explained at those links.
The 1986 Nobel prize for Physics was shared between three people for their work on these inventions.  Another man, Hans Busch, had made a major contribution to the design of the electron microscope but died in 1984 and the Nobel Prize is never awarded posthumously, so even if the committee had thought it appropriate to award him, the rules would have forbidden it.


text:
Q: Simultaneous MySQLdb connections not seeing updates I'm creating a few different scripts that all interact with a central MySQL database to share data but I'm finding that some changes I make to the database wont propagate through or be readable to certain scripts until the database connection has been closed and re opened.
For example using the following code read_script will only print items that have been added to the database using write_scriptafter I quit and restart write_script. I'm new to MySQL so I'm not sure if there is a problem in my SQL or my python
read_script
connection = MySQLdb.connect(...)
while True:
    cur = connection.cursor()
    cur.execute("SELECT * FROM my_table")
    print cur.fetchall()
    cur.close()

write_script
connection = MySQLdb.connect(...)
cur = connection.cursor()
cur.execute("INSERT INTO my_table VALUES(some_data)")
cur.close()
connection.commit()

What do I need to do to ensure I get up to data data from the database?

A: Default transaction isolation is REPEATABLE READ. This means that your read_script will always read and show the same data. Put commit in your while-loop. Side note: Probably good to temporise reading using time.sleep(1).

A: Yes, it looks like the assumption is that you are only going to perform a single transaction and then disconnect. If you have a different need, then you need to work around this assumption. You can put in a commit (though I would use a rollback if you are not actually changing data). Or you can change the isolation level on the cursor as mentioned by @geertjanvdk - from this discussion I used this:
dbcursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
Or, it looks like you can set auto commit to true on the connection:
dbconn.autocommit(True)
Though, again, this is not recommended if actually making changes in the connection.


text:
Q: how to change value on mysql with php and view it dynamically without redirection refresh page <?php echo"\".$bookstatus.\"	"; ?>

this link reach to s_bookstatus then change the value of bookstatus.
else if(isset($_GET['s_bookstatus']))
{
    $id_commission = $_GET['id_commission'];
    $qrycheck = "select * from commission where id_commission='$id_commission'";
    $rscheck = mysqli_query($con,$qrycheck) or die(mysqli_error($con));
    $rowcheck = mysqli_fetch_array($rscheck);
    $s_bookstatus = $rowcheck['book_status'];
    $id_book = $rowcheck['id_book'];

    $qrybooklist = "select * from booklist where id_book='$id_book' ";
    $rsbooklist = mysqli_query($con,$qrybooklist) or die(mysqli_error($con));
    $rowbooklist = mysqli_fetch_array($rsbooklist);
    $stock = $rowbooklist['stock'];

    if($s_bookstatus == 'Available')
    {
        $check = 'Not Available';
        $newstock = $stock - 1;

    }
    else if($s_bookstatus == 'Not Available')
    {
        $check = 'Available';
        $newstock = $stock + 1;

    }

    mysqli_query($con,"update booklist set stock = $newstock where id_book = '$id_book' ");
    $qry = "update commission set book_status ='$check' where id_commission ='$id_commission' ";
    mysqli_query($con,$qry) or die(mysqli_error($con));
    echo "<meta http-equiv='refresh' content='0; url=home.php?commission'>";

}

How to change this code to ajax without meta http-equiv refresh so the data changed dynamically in one page.
thank you..

A: if(isset($_GET['query'])){
            $query = $_GET['query'];
            $result = mysqli_query($con,$query) or die(mysqli_error($con));
        }
        else
        {
        $query = "select * from commission c left join booklist b on c.id_book = b.id_book $filterqry $search";
        $result = mysqli_query($con,$query) or die(mysqli_error($con));
        }

".$bookstatus."

else if(isset($_GET['s_bookstatus']))
{
    $id_commission = $_GET['id_commission'];
    $query = $_GET['query'];

    $qrycheck = "select * from commission where id_commission='$id_commission'";
    $rscheck = mysqli_query($con,$qrycheck) or die(mysqli_error($con));
    $rowcheck = mysqli_fetch_array($rscheck);
    $s_bookstatus = $rowcheck['book_status'];
    $id_book = $rowcheck['id_book'];

    $qrybooklist = "select * from booklist where id_book='$id_book' ";
    $rsbooklist = mysqli_query($con,$qrybooklist) or die(mysqli_error($con));
    $rowbooklist = mysqli_fetch_array($rsbooklist);
    $stock = $rowbooklist['stock'];

    if($s_bookstatus == 'Available')
    {
        $check = 'Not Available';
        $newstock = $stock - 1;

    }
    else if($s_bookstatus == 'Not Available')
    {
        $check = 'Available';
        $newstock = $stock + 1;

    }

    mysqli_query($con,"update booklist set stock = $newstock where id_book = '$id_book' ");
    $qry = "update commission set book_status ='$check' where id_commission ='$id_commission' ";
    mysqli_query($con,$qry) or die(mysqli_error($con));
    echo "<meta http-equiv=\"refresh\" content=\"0; url=home.php?commission&query=$query \">";

}


text:
Q: Image Target recognizing in play mode but not in HoloLens I'm trying to develop an app for HoloLens. The problem I'm facing here now is, when I try to test this app in unity playmode, it's working well and good. But when the same app when deployed to HoloLens, the image targets are not being recognized.
I have enabled my database, Internet and Webcam options in Build settings, Selected virtual reality SDK  as windows mixed reality but I don't know what's wrong with this. Is there a fix for this?

A: I am not sure if I understand your question or not. From your post, I making the following assumptions:

*

*To do Image Target, you need to use the camera.

*I am assuming you are using UnityEngine.XR.WSA.WebCam.PhotoCapture.

*I am assuming you are using Unity 2018 since your post is recent.

If my assumptions are correct
Then there is a bug from Unity side that throws silent exceptions and failing to execute photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory) in the HoloLens. So, OnCapturedPhotoToMemory actually never get called.
Unity Public Issue Tracker:
https://issuetracker.unity3d.com/issues/windowsmr-failure-to-take-photo-capture-in-hololens
Workarounds:

*

*Go to older version of Unity that does NOT have the bug.

*Use the following workaround until Unity fixes the bug:
https://github.com/MSAlshair/HoloLensMediaCapture
Good Luck!


text:
Q: Exercise (2.16) from Isaacs Character Theory of Finite Groups
Let $H \le G$ and let $\chi$ be a character of $G$ which vanishes on $G-H$. Assume that either $H=1$ or $G$ is abelian. Show $|G:H| | \chi(1)$.
Hint: Let $\lambda $ be an irreducible constituent of $\chi_H$. Under either hypothesis, find $\mu \in Irr(G)$ with $\mu_H = \lambda$. Compute $[\chi, \mu] $ and conclude $|G:H| |[\chi_H , \lambda ] $.

I am a bit lost at how the hint works:
(0)  If $H=1$ then I think I can do it: then an irreducible constituent of $\chi_H$ is $1_H$. This is the restriction of $1_G$. We have $[\chi, 1_G] |G| = |H| [ \chi_H, 1_H]$. Thus, $|G:H| | [\chi_H, 1_H] = \chi(1)$.
(i)  I am lost at how one find $\mu$ when $G$ is abelian.
(ii)  I have $|G| [\chi, \mu] = |H|[\chi_H, \lambda]$, hence $|G:H| | [ \chi_H, \lambda] $. But I cannot end the proof from here.

A: Here is the fully worked answer to the Exercise (2.16) in Isaacs' book.

Lemma Let $H \le G$ and let $\phi$ be a (not necessarily irreducible) character of $G$ vanishing on $G-H$. Assume that either $H=1$ or $G$ is abelian. Then $|G:H| | \phi(1)$.

Proof Assume first that $H=1$. Now $|G|[\phi,1_G]=\sum_{g \in G}\phi(g)=\phi(1)$. Since $\phi$ is a character, $\phi(1) \neq 0$ and $[\phi,1_G]$ is a positive integer, it follows that $|G|$ divides $\phi(1)$. In fact, in this case $\phi=b\rho$, where $b=\frac{\phi(1)}{|G|}$ and $\rho$ is the regular character of $G$, see Exercise (3.8) of the same book.
Now assume that $G$ is abelian and $\phi\equiv0$ outside $H$. We can write $\phi=\sum_{\mu \in Irr(G)} a_{\mu}\mu$, with $a_{\mu}$ non-negative integers and not all equal to $0$. Note that the $\mu$ are of course all linear since $G$ is abelian. Hence their restrictions $\mu_H$ are also linear and irreducible. This implies that $\phi_H=\sum_{\mu \in Irr(G)} a_{\mu}\mu_H$ is the decomposition of $\phi_H$ as a sum of irreducible characters of $H$. Note that different $\mu's$ can be equal when restricted to $H$. So in this last sum some of the irreducible constituents may coincide. Put $\phi_H=\sum_{\lambda \in Irr(H)} b_{\lambda}\lambda$ with $b_{\lambda}$ non-negative integers. Fix such $\lambda$, then $\lambda=\mu_H$ for some irreducible constituent $\mu$ of $\phi$. Since $\phi$ vanishes off $H$, $$b_{\lambda}|H|=\sum_{h \in H}\phi(h)\overline{\lambda(h)}=\sum_{g \in G}\phi(g)\overline{\mu(g)}=|G|a_{\mu}$$So we see that each of the $b_{\lambda}=|G:H|a_{\mu}$ is hence divisible by $|G:H|$. Since $\phi(1)=\sum_{\lambda \in Irr(H)} b_{\lambda}\lambda(1)=\sum_{\lambda \in Irr(H)} b_{\lambda}$, we now see that $|G:H|$ divides $\phi(1)$, as wanted.$\square$
Note 1 A natural common generalization of the situation $H=1$ and $G$ is abelian is $H \subseteq Z(G)$. However, under these hypotheses the above result is not true. By the way, in this situation, owing to Lemmata (2.27)(c) and (2.29) of Isaacs' book, $\phi(1)^2=|G:H|[\phi,\phi]$, hence $|G:H|$ divides $\phi(1)^2$.
Here is a counterexample that shows that $|G:H|$ not necessarily divides $\phi(1)$. The character table of the quaternion group $Q$ of order $8$ looks as follows. Here $Q=\{\pm 1,\pm i, \pm j,\pm k \}$, where $i^2=j^2=k^2=-1, ij=k,jk=i,ki=j$. $Q$ has five conjugacy classes.
$$ \begin{array}{c|c|c|c|c|c}
\hline
&1& -1 & \{\pm i \} & \{\pm j \} & \{\pm k \} \\ \hline
1_Q & 1 & 1  & 1 & 1 & 1 \\ \hline
\chi_2 & 1 & 1 & 1 & -1 & -1 \\ \hline
\chi_3 & 1 & 1 & -1 & -1 & 1 \\ \hline
\chi_4 & 1 & 1 & -1 & 1 & -1 \\ \hline
\chi_5 & 2 & -2 & 0 & 0 & 0 \\ \hline
\end{array}
$$
So, $\chi_5$ vanishes off the center $Z(Q)=\{\pm 1\}$. But $|Q:Z(Q)|=4$ does not divide $\chi_5(1)=2$.
Note 2 The above lemma is being used in the proof of Theorem (3.13).


text:
Q: Ionic / Angular 2 Countdown timer solutions I am looking to build a simple Angular 2 (4) / Ionic 2 Countdown timer for my application, but I can't seem to find any open-source solutions available, so I wanted to see what suggestions you guys had.
Here's an example of what I'm looking for:

Now the best 'solution' that i've found is: MobiScroll CountdownTimer
But the catch with MobiScroll is that it has a pretty hefty licensing fee associated with it (almost $200). Which isn't really feasible considering I'm just trying to make something for fun right now.
So I was wondering if there were any open-source solutions out there, that I could utilize, or if i'll have to implement a custom solution, what animation / libraries you think I should start looking at?
I've searched the StackOverflow questions for a solution, but I have yet to find a solid source yet, so I apologize if this is a duplicate, but I don't think that it is.

A: it would be much easier "in my opinion" and less time consuming to create your own very easily.
you can go here : https://ionicframework.com/docs/api/components/datetime/DateTime/
to use the datetime picker from ionic, which will give your picker a native look, and simply use typescript to count down to zero from the time the user inputs.
Example:
private timer;
private maxTime = //get this from user input in the ionic time picker and convert it to seconds maybe.
StartTimer() {
    this.timer = setTimeout(x =>
       {
           if(maxTime <= 0) { alert("timer done";}
           maxTime -= 1;
           StartTimer();

       }, 1000);


text:
Q: using [ngClass] on Material Design table row I have an Angular Material Design table as follows. I would like to add a certain class to rows depending on the value of the relationship column. With a standard HTML table I could add a 'dependent' class to these rows as such:
<tr [ngClass]="{'dependent': element.relationship !== 'Primary'}"

How can I do this with my material table?

<ng-container matColumnDef="employeeName">
   Employee Name
   {{element.employeeName}}
</ng-container>

<ng-container matColumnDef="relationship">
   Relationship
   {{element.relationship}}
</ng-container>

A: It's not possible to do so from html for mat-table. Instead, you can set the class on the td or th element.

A: Try like this


text:
Q: PHP with mysqli loop until condition met. when boolean is 0 to 1 in table page will redirect to other page Here some my code for see if boolean is 1 then go to google.com.
if(isset($_POST['submit']))
        {
            $acc_num = $_POST['acc_num'];
        }
        $sql = "SELECT * FROM security_protocol WHERE acc_num='$acc_num'";
        $result = mysqli_query($con, $sql);
        if (mysqli_num_rows($result) > 0) {
            // output data of each row
            while($row = mysqli_fetch_assoc($result)) {
                $boolean =$row["boolean"];
        if($boolean > 1) {
            $t_slot_times = $t_slot_time + 1;
            for ($i = 1;$i<=20;$i++)
            {
              header("Location: google.com");
             }}}

A: I can't post a comment yet, so I'll show you what I understood from your question.
There are a couple of things I would like to tell you:

*

*You didn't close your if(mysqli_num_rows($result) > 0) statement.

*Please make your code easier to read.

*Why do you have a for loop when you don't use $i and why does the for loop loop 20 times?

*Escape the $_POST variable or use prepared statements to prevent SQL injection.

*What does $t_slot_times store?

Here's what I have for you right now:
if(isset($_POST['submit'])) {
    $acc_num = $_POST['acc_num'];
    $acc_num = mysqli_real_escape_string($acc_num);
}

$sql = "SELECT * FROM security_protocol WHERE acc_num='$acc_num'";
$result = mysqli_query($con, $sql);

if (mysqli_num_rows($result) > 0) {
    // Go trough the received data
    while($row = mysqli_fetch_assoc($result)) {
        $boolean = $row["boolean"];

        if($boolean == 1) {
            $t_slot_times = $t_slot_time + 1;

            header("Location: google.com");
        }
    }
}

It will be much easier to help you if you could give us more information.


text:
Q: Товар по цене Помогите, пожалуйста. Как вывести товар с ценой больше 100,
A: Upd
select
    p.*
    from products p
    where
        p.id_product in
            (select distinct pr.id_product
            from prices pr
            where pr.price > 100
        )
        and p.id_product in
            (select distinct ms.id_product
            from magazine_sales ms
            join sale s on s.id_sale = ms.id_sale
            where year(s.date_sale) < 2012
        )
        and (select count(distinct s1.id_customer)
            from sale s1
            join magazine_sales ms1 on ms1.id_sale = s1.id_sale
            where ms1.id_product = p.id_product
        ) = 1

проверить негде, но должно работать.


text:
Q: Birt Barcode Plugin slows PDF creation by 6s? I have a BIRT template which contains a barcode element. Removing this element changes the time it takes to generate a PDF from ~6 to 0,3 seconds.
<cell id="7689">
    <property name="paddingTop">0pt</property>
    <property name="paddingLeft">0pt</property>
    <property name="paddingBottom">0pt</property>
    <property name="paddingRight">0pt</property>
    <extended-item extensionName="Barcode" id="7972">
        <property name="barcodeType">6</property>
        <expression name="data">row["barcode"]</expression>
        <property name="supSpace">10.0</property>
        <property name="msiCheckSumType">0</property>
        <property name="dmDataMode">0</property>
        <property name="dmFormatMode">0</property>
        <property name="dmFNC1Mode">0</property>
        <property name="pdfDataMode">0</property>
        <property name="pdfEcl">2</property>
        <property name="pdfRowCount">0</property>
        <property name="pdfXYRatio">1.0</property>
        <property name="qrDataMode">0</property>
        <property name="qrEcl">0</property>
        <property name="qrVersion">0</property>
        <property name="uom">2</property>
        <property name="xModule">11.0</property>
        <property name="yModule">20.0</property>
        <property name="leftMargin">0.0</property>
        <property name="rightMargin">0.0</property>
        <property name="topMargin">0.0</property>
        <property name="resolution">100</property>
        <property name="showText">0</property>
        <property name="marginLeft">8pt</property>
        <property name="height">11mm</property>
        <property name="width">11mm</property>
    </extended-item>
</cell>

There seems to be no newer version of the plugin, but this delay is totally inacceptable. Am I using it wrong? Where could I make changes to increase performance while using a barcode element?
Edit: putting it this way performs well ( <0,5s ):
<extended-item extensionName="Barcode" id="8675">
    <property name="barcodeType">20</property>
    <expression name="data">row["barcode"]</expression>
    <property name="marginLeft">8pt</property>
    <property name="height">11mm</property>
    <property name="width">11mm</property>
</extended-item>

Using BIRT 4.4.1 and Onbarcode Plugin 2.2.1


text:
Q: custom options validation
generated output custom option magento admin without any programming, but what I'm looking if default quantity set 0, product does not add in basket until any 1 field (greater then 0).

A: The Product does not add in basket because that option fiels is required. thats why that is not added.once go toadmin panel-->catalog-->manage products-->select product-->custom options-->fields required set to "No"


text:
Q: How to use services or factories in angularjs I am new to angularjs and i am currently working on a dummy shopping website project for practice.
I am a little confused about how to link the app.js with the files present in other modules.
I am working on a login module which has its own LoginController and LoginService in their respective folders inside the loginmodule.
In the LoginService I have defined two properties i.e. isLogged and username. when the user is successfully logged in using the $http.post() method(through the user table in database) the values are changed to true and username respectively.
How can I make sure that the loginService is available throughout the website accross different modules so that the user remains logged in.
Thanks in advance.

A: You don't need to make each section into its own module. You can use one module for your entire application. So instead of call angular.module('newModuleName', []) for each item, you would call angular.module('app') (without the []), and it would continue adding new components onto your single application.
The other option is to create new modules like angular.module('loginModule', []), and then you add it as a dependency into your app, like angular.module('app', ['loginModule']). From this point, any service/factory in your loginModule app will now be available for $injection within your app.
But generally, you may want to refrain from making separate modules for each section, unless that module acts like a "plugin" that is completely distinct and separate from the rest (ie. doesn't depend on anything within app to function). If you need two-way dependency, like app needs to make calls to login, but login needs to also make calls to app, it should all be within the same application.
You should also look at OAuth2 authentication and JSON Web Tokens (JWT) for the correct way to do authorization within AngularJS.


text:
Q: How to combine multiple arrays (that represent columns of data) into a nested/jagged array (or even a 2D) array I have a program that I'm writing to extract certain data from various excel spreadsheet.
The process so far is:
for each spreadsheet identified:
-read in the data as a multidimensional array using interop excel (Even though it is slow, it is the best choice due to all of the different file formats I need to read in)
    Sample: object[,] cellValues = (object[,])range.Value2;

-Identify the columns that I actually need and what order I need them in.  This is stored in a jagged array of bytes:
    byte[][] targetColumns

-THe jagged array essentially is (columnIndexFromSpreadsheet, preferredColumnOrder) e.g. if the first column in the spreadsheet should be read in as column 10 it would be (1, 10)
-I sort the jagged array by the preferred column order (that way I can just loop through the array in that order and extract those columns):
        public static byte[][] SortTargetColumns(byte[][] targetColumns)
        {
            return targetColumns.OrderBy(x => x.Skip(1).First()).ToArray();
        }

-I then extract that column by creating an array from that column index of the multidimensional array.  This is the method that is called:
    public static object[]  ExtractColumn(object[,] dataArray ,byte columnIndex)
    {
        return Enumerable.Range(ArrayIndexStart, dataArray.GetLength(0)).Select(x => dataArray[x, columnIndex]).ToArray();
    }

    Usage:

    array = ExtractColumn(dataArray, (byte) colIndex);

Now I am trying to piece these extracted arrays back together to make it readable.  I will need to do some manipulation on some of the columns and then write to a text file after consolidating.  The only problem is that I have no idea how to do this correctly.  I have tried the following methods but continue to get a null reference exception:
// Get Row Count of dataArray
int rowCount = dataArray.GetLength(0);

// Create List to store extracted arrays
List<object[]> extractedDataList = new List<object[]>();

// Loop through target columns and extract the column as an array
for (byte colIndex = 1; colIndex <= targetColumns.Length + 1; colIndex++)
{
    object[] array = ExtractColumn(dataArray, (byte) colIndex);
    extractedDataList.Add(array);
}

// Create jagged array
object[][] extractedDataArray = new object[rowCount][] ;

for(int i = 0; i < extractedDataArray.GetLength(0); i++)
{
    List<object> row = new List<object>();
    for (int j = 0; j < extractedDataList.Count; j++)
    {
        row.Add(extractedDataList[j][i].ToString());
        //extractedDataArray[i][j] = extractedDataList[j][i].ToString(); <-- null reference
    }
    extractedDataArray[i] = row.ToArray();
}

I'm at a loss of what else to try to put these column arrays back in a form that I can easily work with.  Any and all tips/recommendations would be greatly appreciated.

A: Whenever you get confused like this, break the problem down into small pieces, and use meaningful names.
Let's say you have an array of columns, each of which has one element per row. That might be declared like this:
object[][] columns;

First, let's get the row and column counts:
var columnCount = columns.Length;
var rowCount = columns[0].Length;

Now write a small local function to accept a row and column index and return the right cell. In case not all of your columns have the same number of rows, you can include a boundary check and just return null if a cell isn't there.
object Getter(int row, int col)
{
    bool outOfBounds = (row >= columns[col].Length);
    return outOfBounds ? null : columns[col][row];
}

Now all we have to do is iterate over the rows to create the inner arrays:
object[][] target = new object[rowCount][]
for (int row = 0; row < rowCount; row++)
{
    target[row] = new object[columnCount];
}

And add in the code that uses the getter to populate the cells:
object[][] target = new object[rowCount][];
for (int row = 0; row < rowCount; row++)
{
    target[row] = new object[columnCount];
    for (int col = 0; col < columnCount; col++)
    {
        var cellValue = Getter(row, col);
        target[row][columnCount] = cellValue;
    }
}

All together, it is simple to read:
var columnCount = columns.Length;
var rowCount = columns[0].Length;

object Getter(int row, int col)
{
    bool outOfBounds = (row >= columns[col].Length);
    return outOfBounds ? null : columns[col][row];
}

object[][] target = new object[rowCount][];

for (int row = 0; row < rowCount; row++)
{
    target[row] = new object[columnCount];
    for (int col = 0; col < columnCount; col++)
    {
        var cellValue = Getter(row, col);
        target[row][columnCount] = cellValue;
    }
}