text:
Q: Edit Stripe embedded form I'm using the custom approach of the embedded checkout form for Stripe, on my website. I need to edit the form so the "Payment Info" button (when billing address is on), and the "Pay" button are of a different color. I tried adding some CSS rules on my style files using the ids and classes they use on their embedded form, and adding some css rules to the elements using jquery, but neither worked. Is this possible?

A: The embedded form is an iFrame thus you have no access to edit it via css or javascript. The Stripe documentation provides you some ways to edit items (like the text on the buttons), but the only thing you can really modify the css for is the button that opens the embedded form.


text:
Q: In FastReport4, How to align 3 memo lines vertically where if the 2nd memo line is empty the remaining 2 can be align togather automatically? Using FastReport4 in Delphi XE3.
I have 3 Memo fields as it shown in Fig-1, I want if one of the fields is empty they can automatically align vertically, but my problem is lets say if memo2 is empty I get what's in Fig-2 an empty space between memo1 and memo3, I've tried stretching, shifting modes with no use, I want it to be as Fig-3, So any idea how to do it?
Thanks.

A: You must examine that is the Memo empty or not using below code in Delphi in before print event:
if TfrxMemoView(frxReport.FindObject('Memo2')).Text = '' then
  TfrxMemoView(frxReport.FindObject('Memo3')).Top := TfrxMemoView(frxReport.FindObject('Memo2')).Top;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Splice removing smallest ID not specific item Live counter of who is viewing a news article on a website. Laravel Jetstream.
 .leaving(user => {
     this.participants.splice( this.participants.indexOf(user, 1));
})

 .joining(user => {
             this.participants.push(user);
            this.count++;
   })

However I noticed that if there are two users on the page it keeps removing the one with the smallest ID value. Tested the theory successfully.
So if joe logs in user ID 100 and then Jimmy logs in ID 200. Shows both users in a list.
Jimmy's screen:

*

*Joe

*Jimmy

If Joe refreshes the page it removes Jimmy from the active users and places him in again as an active,  Shows him twice on his screen after the refresh. The items remain correct for Joe regardless of who refreshes (enters or leaves).
Jimmy's screen:

*

*Joe

*Joe

It's like the index isn't correct and hence not splicing properly just removing the last item on the list and repopulating it with the lower ID user.

A:
However I noticed that if there are two users on the page it keeps
removing the one with the smallest ID value.

Makes sense because probably you have the array ordered and indexOf return the first ocurrence found.

The indexOf() method returns the first index at which a given element
can be found in the array, or -1 if it is not present.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
So probably you have to filter differently before doing the splice...


text:
Q: Microsoft Visual Studios 2012 Can't open "python33.lib" I'm using the Boost libraries in MicroSoft Visual Studios 2012 for a C++ program that is going to have Python embedded into it. The problem is when I try to Build Solution [F7]; I get this ::
Error  1   error LNK1104: cannot open file 'python33.lib'  C:\Users\usr\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\LINK
The problem is, I have no idea what this is, means, or any clue of how to fix it.
I have already tried to move my python folder into my Desktop, as it was originally in the C:\, I thought maybe it was a permissions error, but that didn't do anything.
Here is my code from a tutorial that I was reading in preparation for the porject::
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <boost/lambda/lambda.hpp>
#include <boost/python.hpp>

using namespace boost::python;

int main( int argc, char ** argv ) {
  try {
    Py_Initialize();

    object main_module((
      handle<>(borrowed(PyImport_AddModule("__main__")))));

    object main_namespace = main_module.attr("__dict__");

    handle<> ignored(( PyRun_String( "print \"Hello, World\"",
                                     Py_file_input,
                                     main_namespace.ptr(),
                                     main_namespace.ptr() ) ));
  } catch( error_already_set ) {
    PyErr_Print();
  }
}

--Visual Studios 2012
--Windows 7 x64
--Python 3.3.2
--Boost libraries
--Python Embedded C++ program
--Link to tutorial page:: http://wiki.python.org/moin/boost.python/EmbeddingPython

A: Thanks for all the help David.
For anyone else who runs into this problem, here's what you need to do.
Right click on the Project name (ConsoleApplication1, ect) and under C/C++ general insure that your additional include directories include youe python include, Lib, and libs folders. As well as the boost root and the boost lib(32/64) folder.
Under the linker menu, in the input sub catagory, for additional dependencies, you'll need to add this into there.
C:\Python33\libs\python33.lib
C:\boost_1_54\lib32-msvc-11.0\boost_python-vc110-mt-gd-1_54.lib

Or whatever your install directory is. As well as any other required files.
Once that's done your project should build.
Once you're ready to run it you'll need to copy whatever .dll files are needed into the folder where the executable is built.


text:
Q: Declaring a duplicate variable within a loop in Java I want to be able to declare a selenium driver within a loop dependant on a user choice. I want the driver to be called driver regardless of which kind it is, so that I can then use it for everything instead of having one separate set of code for IE and for Firefox. I hope that made sense, I am very new to Java.
 switch (browserId){
    case 1:
            FirefoxDriver driver = new FirefoxDriver();

    case 2:

        InternetExplorerDriver driver = new InternetExplorerDriver();

    default:
            System.out.println("An error has occurred, the program will now close.");
        System.exit(0);
    }

This creates a compile error as I have two variables called driver, however I should never have them both existing at the same time. Is there a way around this?

A:
I want the driver to be called driver regardless of which kind it is,
  so that I can then use it for everything instead of having one
  separate set of code for IE and for Firefox.

If both of those classes implement a Driver interface (or is it WebDriver?), then you can simply do
Driver driver = null;
switch (browserId){
case 1:
    driver = new FirefoxDriver();
    break;
case 2:
    driver = new InternetExplorerDriver();
    break;
default:
    System.out.println("An error has occurred, the program will now close.");
    System.exit(0);
}

Now you can use driver, but check for null.
The reason you can't do this is that a switch block begins a scope. If you declare a variable with name driver, you can't redeclare another variable with the same name in that same scope.

A: You could do it like this:
WebDriver driver;                     // <-- move outside the switch
switch (browserId){
    case 1:
        driver = new FirefoxDriver();
        break;                        // <-- add breaks
    case 2:
        driver = new InternetExplorerDriver();
        break;
    default:
        // exceptions are more welcome than System.exit();
        throw new IllegalArgumentException("wrong browserId: " + browserId);
}

A: If they all derive from a common type, declare the variable outside the switch.
Driver d = null;

switch(browserId){
     case 1:
         d = new FireFoxDriver();
         break; // don't forget!!
     case 2:
         d = new InternetExplorerDriver();
         break;
     ... // omitting other cases and default

}

If not, then you need to use different names in each case statement.


text:
Q: A kind of exponential concavity for polynomials? Is there $C > 0$ such that the inequality
$$
\prod_{n\in\mathbb{N}} p(n)^{a_n} \leq p\left(C\prod_{n\in\mathbb{N}} n^{a_n}\right)
$$
holds for all finitely supported sequences $(a_n)$ with $a_n\geq 0$ and $\sum_n a_n = 1$ and polynomials with nonnegative coefficients $p\in \mathbb{R}_+[X]$?
Is it even possible to take $C=1$?
It's clear that the inequality trivially holds with $C = 1$ whenever $p$ is a monomial.

A: The example by Philipp Lampe can be modified to prove that no such $C$ exists:
Suppose $k$ is an arbitrary positive integer and take $p(x)=x(x+k^2-1)$. Now choose $a_1=a_n=\frac{1}{2}$ for some $n\geq 1$ and we get that $C$ must satisfy
$$\sqrt{p(1)p(n)}\le p(C\sqrt{n})$$
$$\iff \sqrt{k^2n(n+k^2-1)}\le C\sqrt{n}(C\sqrt{n}+k^2-1)$$
but we notice that as we let $n\to \infty$ the left side is $\sim kn$ and the right side is $\sim C^2 n$ which gives $C\geq \sqrt{k}$. Since $k$ was arbitrary we conclude that no such constant exists.

A: It is not possible to take $C=1$.
We consider the polynomial $p=x^2+x$ and the sequence $(a_n)$ with $a_1=a_2=1/2$ and $a_n=0$ otherwise. Then
\begin{align*}
\prod_{n\in\mathbb{N}} p(n)^{a_n}=\sqrt{2}\sqrt{6}=2\sqrt{3};
&&p\left(\prod_{n\in\mathbb{N}}n^{a_n}\right)=p\left(\sqrt{2}\right)=2+\sqrt{2}.
\end{align*}
However, $2\sqrt{3}>2+\sqrt{2}$.


text:
Q: Qt and OpenCV 2.0 integration problems I have a Qt application that uses OpenCV for image processing.
Everything was working fine with OpenCV 1.0 but when I upgraded to
OpenCV 2.0 it started crashing.
I noticed that it only crashes whenever OpenCV functions are called
inside Qt slots.
For instance, the following slot:
void TestClass::on_testButton_clicked() {
   IplImage* src = cvLoadImage("test.jpg");
   IplImage* dst = cvCreateImage(cvGetSize(src), src->depth, src->nChannels);
   cvThreshold(src, dst, 100, 255, CV_THRESH_BINARY);
}

crashes when testButton is clicked.
However, if I call the same cvThreshold function in any other place,
such as inside the main() function
or inside the Widget constructor, it works fine. Also, if I put the
same code in a separate function and
call that function with QtConcurrent::run() inside the same slot, it
works fine too.
Why this behaviour? Are there any restrictions about the operations
that can be done inside Qt slots? Which changes in OpenCV 2.0 functions
may be causing the conflict?
Thanks in advance

A: Never mind, I was using OpenCV's precompiled libraries,
which were created with a different version of mingw.
I compiled the library with cmake+mingw and using
the generated libraries solved the problem.


text:
Q: Calculating the Kernel, dimension of linear equations, real numbers and galois field Given these problems below, how would one calculate the result?
By intuition, I have managed to solve two of them but cannot crack the last one.
Btw, I am not sure that the approach of my intuition is the right one.
I am interested in learning about how to solve these (formulas and approach).
Problems Below:

1) Let $f:  ℝ^7 \rightarrow ℝ^4$ be a surjective (onto) linear function. What is the dimension of $Ker \space f$? (answer = 3)
2) Let $f: GF(2)^8 \rightarrow GF(2)^9$ be a linear funktion with $dim \space Im \space f=5$. How many vectors are in $Ker f$? (answer = 8)
3) Let $f: ℝ^7 \rightarrow ℝ^{14}$ be a injective (one-to-one) linear function. Determine $dim \space Im \space f$? (answer = 7)

Could determine the answers for problem 1 and 3 by intuition (but not by formula). Here is the intuition below:

1 - Intuition: The function is surjective so the dimension must be $7 - 4 = 3$
3 - Intuition: The function is injective so the dimension must be $14 - 7 = 7$

(First question on site, so open for constructive feedback regarding the question.)

A: All you need here is the dimension theorem: if $f:U\to V$ is any linear map, then
$$\dim\ker f+\dim\mathrm{im} f\,=\, \dim U$$

 Choose bases $u_1,\dots, u_k$ for $\ker f$ and $v_1,\dots, v_r$ for $\mathrm{im} f$ and arbitrary preimages $w_j$ of $v_j$. Then show $u_1,\dots, u_k, w_1,\dots, w_r$ is a basis of $U$.

This resolves your uncertainty for a) and c), and gives $\dim\ker f=3$ for b).
So that $\ker f\cong GF(2)^3$ (by coordinating the vectors) which has $2^3$ elements.


text:
Q: Filter chain halted as :doorkeeper_authorize! rendered or redirected I am building a Rails API and am currently using doorkeeper and devise to authenticate users with the ResourceOwnerFromCredentials flow. All works fine however, I cannot get the authentication to work in Rspec.
Here is how am integrating the app in rspec:
    let(:app_country) { FactoryGirl.create(:app_country)}
    let(:valid_attributes) { FactoryGirl.attributes_for(:app_city, {:app_country_id => app_country.id}) }
    let(:valid_session) { {:format => :json} }

    let(:application) { Doorkeeper::Application.create!(:name => "App HQ dashboard", :redirect_uri => "https://localhost:3000/callback") }
    let(:hq_user) { app_country.hq_users.create!(FactoryGirl.attributes_for :hq_user) }
    let(:token) { Doorkeeper::AccessToken.create! :application_id => application.id, :resource_owner_id => hq_user.id }

But each time I try to test a protected action, the tests fail and I get the following output from the console:
Filter chain halted as :doorkeeper_authorize! rendered or redirected
Completed 403 Forbidden in 5ms (ActiveRecord: 1.2ms)

This was working fine with the previous version of doorkeeper. The tests broke when I upgraded the doorkeeper gem. What am I doing wrong? Or is there a new way of testing doorkeeper protected controllers?
UPDATE
Below is an actual test sample
    describe "POST create" do
        describe "with valid params" do
            it "creates a new AppCity" do
                expect {
                    post :create, {:app_city => valid_attributes, :v => "HEAD", :payload_type => "NODE", :access_token => token.token}, valid_session
                }.to change(AppCity, :count).by(1)
            end

            it "persists the AppCity" do
                post :create, {:app_city => valid_attributes, :v => "HEAD", :access_token => token.token}, valid_session
                response_body = JSON.parse(response.body, symbolize_names: true)
                expect(response_body[:id]).to be_present
            end

            it "returns a 201 status" do
                post :create, {:app_city => valid_attributes, :v => "HEAD", :access_token => token.token}, valid_session
                response.status.should eq(201)
            end
        end

        describe "with invalid params" do
            it "returns validation error message" do
                post :create, {:app_city => { "name" => "" }, :v => "HEAD", :access_token => token.token}, valid_session
                response_body = JSON.parse(response.body, symbolize_names: true)
                expect(response_body[:name]).to include "can't be blank"
            end

            it "returns a 422 status" do
                post :create, {:app_city => { "name" => "" }, :v => "HEAD", :access_token => token.token}, valid_session
                response.status.should eq(422)
            end
        end
    end

A: I finally found the problem. I was getting a 403 Forbidden because my I was sending a request with insufficient scope. I had defined the following scopes in doorkeeper.rb
# Define access token scopes for your provider
# For more information go to https://github.com/applicake/doorkeeper/wiki/Using-Scopes
default_scopes  :public
optional_scopes :write, :update

For my specs to pass again I had to specify which actions required a specific access token scope e.g:
class Api::V1::ProductsController < Api::V1::ApiController
  before_action -> { doorkeeper_authorize! :public }, only: :index
  before_action only: [:create, :update, :destroy] do
    doorkeeper_authorize! :admin, :write
  end
end

I initially only had before_action :doorkeeper_authorize!, except: [:index, :show]. What I needed to do was define the :write and :update scopes on the :create, :update and :destroy actions. Or alternatively do away with the scopes completely.
I am also using CanCanCan so I guess the scopes should be redundant in my case.
Further reading here


text:
Q: How to use a specific directory Audio.Media.EXTERNAL_CONTENT_URI (android) I want to use the music files that are in a specific folder I created on the sdcard to do a playlist.
But I dont know how to replace the Audio.Media.EXTERNAL_CONTENT_URI
by my repertory URL in
audioCursor = this.managedQuery(Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);

of the `MediaStore.audio.
Do you think this is possible?
If yes, how?
thank you!


text:
Q: Flutter abstract class with different widgets in a list view I'm trying to figure out how to show a list view with mixed items.  I can't figure out how to show the list items.  Please consider the following code.  This should just run (except for the error on line 82 now.
I've created an abstract class and a class that implements a Text area and a class that implements a button area.  I'm mixing them up as that would be the way the data flows in.  Randomly.
So I can build the mixed class, I just don't know how to do the final display on my screen.
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

abstract class  MixedWidgets{
  //Different type of widgets I want to mix randomly;
  Widget buildText(BuildContext context);
  Widget buildButton(BuildContext context);
}

//this should show some text
class TextClass implements MixedWidgets{
  Widget buildButton(BuildContext context) => null;

  TextClass({this.textStringToPrint});

  String textStringToPrint;

  Widget buildText(BuildContext context){
    return Container(
      child: Text(textStringToPrint),
    );
  }
}

//This should show a button
class ButtonClass implements MixedWidgets{
  Widget buildText(BuildContext context) => null;

  ButtonClass({this. buttonNumber});

  int buttonNumber;

  Widget buildButton(BuildContext context){
    return FlatButton(
        onPressed: null,
        child: Text('This is button number $buttonNumber'),
    );
  }
}

//List<MixedWidgets> myListOfMixedWidgets = [];
final firstN = ButtonClass(buttonNumber: 1);
final secondN = ButtonClass(buttonNumber: 2);
final thirdN = ButtonClass(buttonNumber: 3);
final fourthN = ButtonClass(buttonNumber: 4);
final fifthN = ButtonClass(buttonNumber: 5);

final firstT = TextClass(textStringToPrint: 'one');
final secondT = TextClass(textStringToPrint: 'two');
final thirdT = TextClass(textStringToPrint: 'three');
final fourthT = TextClass(textStringToPrint: 'four');

class MyApp extends StatelessWidget {
  //Mix up my different classes and widgets in here
  List<MixedWidgets> myListOfMixedWidgets = [
    firstN,
    secondN,
    firstT,
    thirdN,
    fourthN,
    secondT,
    thirdT,
    fourthT,
    fifthN,
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
      appBar: AppBar(),
      body: SafeArea(
        child: Container(
          child: ListView(
            //How do I do this?  I need to show the mixed list here?
            children: myListOfMixedWidgets,
          ),
        ),
      )
    )
    );
  }
}

A: The strategy you will want to use here is polymorphism. Use Widget, the super class of StatelessWidget and StatefulWidget, to create a heterogenous List of Widgets (List<Widget>).
If TextClass and ButtonClass inherit from some descendant of Widget then they can all be added to the list of widgets. This works for ListView because its children parameter is only aware of Widget.
class TextClass extends StatelessWidget {
  const TextClass({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Text("Text!");
  }
}

class ButtonClass extends StatelessWidget {
  const ButtonClass({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      onPressed: null,
      child: Text("Button!");
    );
  }
}

final ButtonClass firstN = ButtonClass();
final TextClass firstT = TextClass();

class MyApp extends StatelessWidget {
  // Polymorphism here:
  List<Widget> myListOfMixedWidgets = [
    firstN,
    firstT,
  ];

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: myListOfMixedWidgets,
    );
  }
}


text:
Q: Learning assembly - echo program name I am trying to write a simple program in assembly that will write out the name of the program. Using gdb to debug, I've determined that the call to sys_write is returning -14 (EFAULT).  I've also been able to verify that my strlen function is working correctly.  It seems like there is some sort of memory access issue, but I don't understand what could be wrong given that strlen is accessing the same memory and working fine.  What is going wrong?
Thanks!
The full code:
section .text
    global _start

_start:
    mov rax, [rsp+8]
    push rax
    call strlen
    add rsp, 8

    mov rdx, rax ; bytes to write
    mov rax, 4 ; sys_write
    mov rbx, 1 ; stdout
    mov rcx, [rsp+8] ; addr of string
    int 0x80

    ; exit
    mov rax, 1
    mov rbx, 0
    int 0x80

strlen:
    mov rax, 0
    mov rbx, [rsp+8]
strlen_loop:
    cmp byte [rbx+rax], 0
    je strlen_end
    inc rax
    jmp strlen_loop
strlen_end:
    ret ; len in rax

A: As I wrote in a comment, x86_64 uses a different method for syscalls than 32-bit linux. In particular int $0x80 is no longer the way to do it (though it might semi-work if you have the 32-bit libraries installed....). See for instance this previous discussion.
Where on 32-bit x86 you would do:
mov eax, SYSCALL_NUMBER
mov ebx, first_param
mov ecx, second_param
mov edx, third_param
int 0x80

You should do the following on x86_64:
mov rax, SYSCALL_NUMBER_64 ; This is usually different from the 32-bit version!
mov rdi, first_param
mov rsi, second_param
mov rdx, third_param
syscall

To print the program name, change your program to the following and it should work. For anyone else interested in how the program environment looks on startup, see here.
section .text
    global _start

_start:
    mov rax, [rsp+8]
    push rax
    call strlen
    add rsp, 8

    mov rdi, 1 ; fd = stdout
    mov rsi, [rsp+8] ; buf = addr to string
    mov rdx, rax ; count = strlen(string)
    mov rax, 1 ; write
    syscall

    mov rdi, 0 ; status = 0
    mov rax, 60 ; exit
    syscall

strlen:
    mov rax, 0
    mov rbx, [rsp+8]
strlen_loop:
    cmp byte [rbx+rax], 0
    je strlen_end
    inc rax
    jmp strlen_loop
strlen_end:
    ret ; len in rax

Compiled using:
nasm -g -f elf64 -o sc.o sc.asm
gcc -nostartfiles -o sc sc.o

A: You add rsp with 8 at the beginning causing the sys_write call to get another string than your strlen function. The strlen does not alter the stack and the pushed rax is not used later? Why don't you drop the push rax and add rsp, 8 statements and see how that works our for you?


text:
Q: Getting element from list. Dojo I using dojo.
  dojo.ready(function ()
    var input = dojo.query(".dojo_input"); //i have about 5 elements with ".dojo_input" class
    input.on("click", function(i) {
       console.log(input[i]);
       // function
       });
    });

So question is: I get undefined element, so i can't use any function on it. How i can get uniqe element from list.
Thanks

A: EDIT1:
Have a look at the jsfiddle over here http://jsfiddle.net/frank123/YYyH9.
you can use the foreach function on the query result as shown below
dojo.ready(function (){
    var input = dojo.query(".dojo_input"); //i have about 5 elements with ".dojo_input" class
    input.forEach(function(node, index, arr){ // node is the elment
        console.log("Index"+index);
        dojo.on(node,"click", function() {
            console.log("Clicked!");
            // function
        })
    });
});

A: The parameter passed to on's callback is an Event object, not an index. Try doing
input.on("click", function(e) { //event object is conventionally named "e" or "evt"
    console.log(e);
});

IIRC, the input node itself should be available in the e.target property.
https://dojotoolkit.org/reference-guide/1.10/dojo/on.html#id4

A: I take code that proposed by frank and use dojo.connect instead of dojo.on
dojo.ready(function (){
    var input = dojo.query(".dojo_input"); //i have about 5 elements with ".dojo_input" class
    input.forEach(function(node, index, arr){ // node is the elment
        dojo.connect(node, "onclick", function() {
        console.log("Clicked!" + node);
        // function
            dojo.query(node).after("");
        });
    });
});

And to use any function on node, i use dojo.query(node).
Thanks.


text:
Q: Combine Cocoa App and Commandline Tool into one App Bundle How may I combine a Commandline Tool and a Cocoa Application into one App using XCode?
Finally I need to show the output of the Commandline Tool (stdout and stderr) to a NSTextBox.

A: Drag the binary project (or add) as a dependency of the main project. This means that it will always be built before the main projects.
Next add a copy bundle resources build phase (or use an existing one) and drag the binary product from the binary project in. This will copy the resulting binary from the first build into the bundle created by the second build.
To run the binary you need to get its path using NSBundle and then run it using NSTask.


text:
Q: Iterating through a List Collector and not displaying certain values I have a Service Catalog item in ServiceNow (Geneva release) that personnel use to request access to additional ServiceNow groups.  A list collector displays the all of the groups available.  We want to limit it and disallow a few choices from appearing.  When you build a List Collector variable, you can specify a List table, but you cannot construct a filter on it.
Is it possible to use a Catalog Client Script to check each item being loaded into the List Collector and skip it, perhaps by checking sysID or another value?  I assume a glide record call is being done somewhere in order to populate the list collector, but I'm unsure how to modify it or interrupt it.
For this example, the List Collector is named 'bucket'.
I can probably try to start with:
var lcFilter = g_form.getControl('bucket')

There is probably a way to manipulate the contents from that object.  I just need help figuring out what part of the object I need to manipulate.  We currently use a similar function to rename the headers of the List Collector like this:
var headers = g_form.getControl('bucket').parentElement.querySelectorAll('.col-xs-4');

headers[0].childNodes[0].firstChild.data = 'All Available Groups';
headers[1].childNodes[0]firstChild.data = 'Groups you wish to add';

A: You may want to try a solution that allows you to directly apply a filter to your list collector that I've used from http://www.servicenowguru.com/scripting/client-scripts-scripting/changing-filter-list-collector-variable-client-script/
The code below is a copy and paste from there, so I don't take too much credit, but you want to  put your list collector name here
var collectorName = 'bucket';

Then an encoded query here to filter it on.
var filterString = 'group_nameNOT LIKEApproval^active=true'

This would be in a Catalog Client Script for onLoad
function onLoad() {
   //Apply a default filter to the list collector variable
   var collectorName = 'configuration_items';
   var filterString = 'name!=NULL^sys_class_nameANYTHING';
   //Hide the list collector until we've set the filter
   g_form.setDisplay(collectorName, false);
   setCollectorFilter();

   function setCollectorFilter(){
      //Test if the g_filter property is defined on our list collector.
      //If it hasn't rendered yet, wait 100ms and try again.
      if(typeof(window[collectorName + 'g_filter']) == 'undefined'){
         setTimeout(setCollectorFilter, 100);
         return;
      }
      //Find and hide the filter elements (optional)
      //Simple method for items with only one list collector
      //$('ep').select('.row')[0].hide();
      //Advanced method for items with more than one list collector (more prone to upgrade failure)
      //var el = $('container_' + g_form.getControl(collectorName).id).select('div.row')[0].hide();

      //Reset the filter query
      window[collectorName + 'g_filter'].reset();
      window[collectorName + 'g_filter'].setQuery(filterString);
      window[collectorName + 'acRequest'](null);
      //Redisplay the list collector variable
      g_form.setDisplay(collectorName, true);
   }
}


text:
Q: ASP.NET MVC form post parameter I have a form in MVC:
<% using (Html.BeginForm("Get", "Person"))
  { %>
      <%= Html.TextBox("person_id")%>
      <input type="submit" value="Get Person" />
  <% } %>

This redirects me to Person/Get. Okay. The question:
How do I make this Form so it redirects me to Person/Get/{person_id}?
Edit:
<% using (Html.BeginForm("Get", "Person", new { id = ??? }))
  { %>
      <%= Html.TextBox("person_id")%>
      <input type="submit" value="Get Person" />
  <% } %>

What do I write in ???

A: I think the most difficult way would be using a javascript clientside.
The more straightforward way is to retrieve it on the action Person/Get and from there return a RedirectResult pointing to Person/Get/{person_id}
[HttpPost]
public ActionResult Get(string person_id)
{
    return RedirectToAction("Get", "Person", new { id = person_id });
}

[HttpGet]
public ActionResult Get(string id)
{
     //Do your thing
}

The redirect is usually so fast that the user will never notice. He/she will arrive at /Person/Get/{person_id}

A: What you want to do is specify the route values as the third parameter on the BeginForm method.
<% using (Html.BeginForm("Get", "Person", **new { person_id = this.Model}**))
{ %>
   <%= Html.TextBox("person_id")%>
   <input type="submit" value="Get Person" />
<% } %>

Then your controller action would look something like this
public ActionResult Get(int person_id)
{
    return View(person_id);
}


text:
Q: Cannot connect IBAction to table view from xib I am using this open source framework in swift https://github.com/uacaps/PageMenu for my view controller.
I am using xib for the tableview cells and the tableview as shown in the demo projects.
However, when I go to connect my buttons from the tableview cell to the table view controller Xcode will not let me. I am working on the NotificationTableViewCell and NotificationTableVC files.
I have set up the project properly and can get the cell up and running as well as the project itself. However if I can't get the buttons to connect I cannot add the needed functionality.
The demo projects also have this behaviour when I cloned some from the repository. I looked through the issues and no one seemed to mention anything about connecting IBActions to the view, so I did, but I assume there is something I am missing.
I have attached screen shots to help you see my issue. I need to access the cellForRowIndexPath as well.

My xib is given the class of my table view cell which still wont allow me to interact with the tableview controller.

A: Okay, so I have figured out a working solution. Thanks to Gurtej Singh.
Here is the code:
1) I added this line in the cellForRowIndexPath
cell.mybutton.addTarget(self, action: "declineRequest:", forControlEvents: .TouchUpInside)

2) Now I am able to access the button if I write a function called declineRequest
Since I want to delete the cell based on its data I use this function and add the Parse query logic.
 func declineRequest(sender: UIButton) {
    var cell: NotificationsTableViewCell = sender.superview!.superview as! NotificationsTableViewCell
     .... }

A: I don't think you will be able to connect a table view cell element to a table view controller class via IB (and from what I know, it's not correct to do so as well, because there will be multiple cells and re-usability).
Connect the element from the IB to your Cell class (.h/.m), create one if you don't have it , like NotificationTableViewCell.m, and then access the connected element from the delegate methods inside your Table View controller class.
Hope this helps.


text:
Q: Using Bubble notification for incoming call Below is my code for bubble notification,
Notification.BubbleMetadata bubbleData =
                    new Notification.BubbleMetadata.Builder()
                            .setIcon(Icon.createWithResource(this, R.drawable.notification_logo))
                            .setIntent(incomingCallPendingIntent)
                            .build();

// Create notification
            Person chatBot = new Person.Builder()
                    .setBot(true)
                    .setName("BubbleBot")
                    .setImportant(true)
                    .build();

            Notification.Builder builder =
                    new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
                            .setContentIntent(incomingCallPendingIntent)
                            .setLargeIcon(getCircleBitmap(drawable.getBitmap()))
                            .setOngoing(true)
                            .setColor(ContextCompat.getColor(context, R.color.blue))
                            .setContentTitle(displayName)
                            .setContentText("Incoming call from "+number)
                            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
                            .setFullScreenIntent(incomingCallPendingIntent, true)
                            .setSmallIcon(R.drawable.notification_logo)
                            .setAutoCancel(false)
                            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE))
                            .setVibrate(vibrate)
                            .setCategory(NotificationCompat.CATEGORY_CALL)
                            .setSmallIcon(R.drawable.notification_logo)
                            .addAction(0,"Answer",answerPendingIntent)
                            .addAction(0,"Cancel",cancelPendingIntent)
                            .setBubbleMetadata(bubbleData)
                            .addPerson(chatBot)
            startForeground(2,builder.build());

In this, setDefaults,setSound, setVibrate, addAction are deprecated.
And when receiving Incoming call Notification, on tapping the notification not able to get full screen Intent. Instead of that White screen came and goes off. Meanwhile Action buttons are working fine.Only able to see full screen intent activity when  the device is in DO NOT DISTURB MODE. I doesn't know whats wrong with my code. Anybody help me with this. Thanks in advance.
If anybody faced this issues, then please
share me your ideas


text:
Q: GCD or LCM confusion Rosa is making a game board that is 16 inches by 24 inches. She wants to use square tiles.
What is the largest tile she can use and
how many square tile will be on her board?
Need explanation on why GCF is applied not the LCM

A: The side length of the square needs to divide both 16 and 24 evenly. The largest such integer is (by definition) the greatest common factor.

A: If the side length of the tile is $d$ you need to fit an exact number of tiles in each direction. So you need $md=16$ and $nd=24$. So $d$ has to be a common factor of $16$ and $24$. If you want the largest possible $d$, then you need the highest/greatest common factor/divisor.
The biggest confusion comes because the terminology is not constant. Highest and greatest are both used, as are factor and divisor. They all mean the same thing.


text:
Q: Excel VBA - Move Columns depending on name without having a load of variables I'm trying to organise my columns in some VBA code. I need them in a particular order depending on the value in Row A. I know i can do it using the following method but it's very long winded and looks horrible. Is there any more efficient way to do it?
Current Code
    Set Name = Cells.Find(What:="Name", LookAt:=xlWhole)

Then activate the cell, find column and then paste to where i want it. So if the columns went like this:
It would change the order to this
I can't just delete the columns that I don't want because they change position. So if i was to delete columns C:C it might delete what i need on occasion.
I need it so that no matter what columns are there, or how many, it will also go in the same order as shown above.
Thanks

A: Try this.
Dim Rng As Range
Set Rng = ActiveSheet.UsedRange

If Range("A2").Value = "x" Then
    Range("A1,C1,D1").EntireColumn.Hidden = True
    Rng.SpecialCells(xlCellTypeVisible).Copy Destination:=Sheets("Sheet2").Range("A1")
End If


text:
Q: Name for number format used in "Section 3.2.1" Does that kind of numbering style have a common name or names? To be fair, it is really more of an "identifier" since it certainly not a scalar (one-dimensional) number. It isn't fair to call it a floating point number either.
If I were to hazard two guesses, I would say:

*

*a document identifier (but that seems so vague)

*a multi-dotted number (silly, yes, but it gets the points across)

So in reality, I've got nothing.

A: The Chicago Manual of Style calls the actual instantiation of such an identifier a "numbered subhead" or sometimes a "numbered division" or "numbered section." It also points out that this particular style of referencing the various sections is called "multiple numeration." See section 1.55 for more info.

A: I think "section number" makes sense.
Interestingly, Wikipedia's page on Section Numbers redirects to ISO 2145:

International standard ISO 2145 defines a typographic convention for the "numbering of divisions and subdivisions in written documents". It applies to any kind of document, including manuscripts, books, journal articles, and standards.

So, this standard defines the number format I'm looking for. Great. (Note that to satisfy this standard, only Arabic numerals can be used; letters and roman numerals are outside this particular definition.)

A: Even though, when we hear the word decimal, we might instinctively think of only one decimal point in a number (as in 3.14159265358979), the format you refer to is called a decimal outline.
In addition to the Wikipedia link just provided, the Purdue OWL uses the same terminology, as shown at the end of this handout.  This guideline also uses the term decimal outline.
With that in mind, I'd have no problem with someone referring to the 3.2.1 as a decimal identifier, decimal header, or decimal section ID – certainly not in that context – and I don't see any need to specify multi-, as in multi-dotted number.

A: You might try numbered multilevel list or outline numbered list.
From Microsoft Word 2010 Complete by Pasewark et al. (p. WD 124):

A multilevel list is a list with two or more levels of bullets or
  numbering. A numbered multilevel list is sometimes called an outline
  numbered list.


text:
Q: CIFS mounts and Kerberos - permissions on access or best practice Currently our Ubuntu-Clients connect to cifs shares during system boot via /etc/fstab. This has the following disadvantages:

*

*Passwords are written in plain text as mount option

*The password should expire, but if it does, the /etc/fstab has to be changed on every client. So most passwords used for mounts simply don't expire at the moment

*The CIFS share is mounted under the connecting user and his permissions, so the user actually working with the share on Ubuntu is not displayed. A side effect is a blur of permissions, because the Ubuntu-users are not listed in the Windows file system permissions.

What I already successfully tested on our Ubuntu-Clients:
Using kerberos authentication on user login - so there is a kerberos ticket available for the user.
Using that kerberos ticket to (sudo) mount the cifs share within a systemd userservice

*

*PRO: Works on graphical login as well as ssh

*PRO: Share is accessible like the local file system

*CON: If I mount on a global mountpoint like /servers/mymount, I have to take care, that I don't overlay mounts by multile users. And the connecting user then would be the one who's permissions would be used by any following user.

Using that kerberos ticket to dynamically mount the share from the file browsers nautilus and thunar

*

*PRO: If the connection to the share is established via file browser, no extra script or service is necessary

*PRO: The share is mounted into the user context, so definitely with the users permission. If the user has no permission, there is still the possibility to connect the share with another user.

*PRO: The mounts could be automated by /etc/profile using gvfs-mount

*PRO: No sudo-rights are neccessary, the user can gvfs-mount and -unmount as he wishes, very intuitive via file browser

*CON: There is no actual mountpoint, standard unix commands like ls, cp and so on don't work. I would have to use gvfs-* alternatives. At this point the above solution with mount.cifs appears to be better.

So what I would like is to access the cifs share like I access an nfs share.

*

*No passwords used during the mount

*The permissions of the accessing user should be used

*The filesystem should behave like the local file system (standard unix commands should work)

I could mount a CIFS share multiple times, separately for each user into his home directory, but
Is there a way to mount the CIFS share during boot by the user root, not specifying a connecting user and then using the permissions from an accessing user (for example via kerberos ticket)?
Thank you in advance,
Bastian

A: Use automount + multiuser option of mount.cifs
You can achieve this using automount and the multiuser option for mount.cifs. Install the required packages:
sudo apt install autofs keyutils cifs-utils

The following example assumes that the cifs server exports a share that is named after the user that is accessing it. Normally that would be suitable for home directories.
Add this to your /etc/auto.master:
/cifs /etc/auto.cifs

In /etc/auto.cifs put this:
*   -fstype=cifs,multiuser,cruid=${UID},sec=krb5    ://server.domain/&

Make sure to replace server.domain by your file server. You could also use a fixed share this way. Just replace the * by a fixed name and also the &.
An important detail in the above configuration is the cruid=${UID}. It will make the kernel look for a kerberos ticket in the context of the user accessing the share. Otherwise it would be trying roots ticket cache.
Finally reload automount:
sudo service autofs reload

If you have a kerberos ticket, it will mount the file system /cifs/$USER on first access. That means you need to explicitly type e. g. cd /cifs/myuser or a similar action in a GUI file browser. To avoid this you could place symbolic links pointing to this from somewhere else and tell users to access those.
If you are using a fixed share (not using * and &) of course you would have to type cd /cifs/sharename.
Subsequent access by other users to the same share will be using their permissions, made possible by the multiuser option. No additional mount will be made but the existing one reused.
From mount.cifs(8):

   multiuser
       Map user accesses to individual credentials when accessing
       the server. By default, CIFS mounts only use a single set of
       user credentials (the mount credentials) when accessing a
       share. With this option, the client instead creates a new
       session with the server using the user's credentials whenever
       a new user accesses the mount. Further accesses by that user
       will also use those credentials. Because the kernel cannot
       prompt for passwords, multiuser mounts are limited to mounts
       using sec= options that don't require passwords.

It is also possible to add the required automount maps to an LDAP server for central management, but this is probably beyond the scope of this answer.
In your question you asked for the mount to be mounted as root on boot. Technically this is done here in form of a place holder mount for autofs. Practically the real mount is only done on first access by a user.
We are using this setup for ~100 clients at my workplace for accessing quite a big lustre file system and it works reliably.


text:
Q: Taking a String and making an object from a class that String represents in Java Scenario:

*

*I have two classes named ListLayout and GridLayout which both implement CustomLayout.

*The user enters a String representing the layout they wish to use ("ListLayout" for example)

How can I create a ListLayout object based on the string entered by the user? I would need to be equivalent to just doing this:
CustomLayout layout = new ListLayout();

Ideally I would need to find a solution which would allow me to check if the String entered corresponds to a predefined class which implements CustomLayout before actually making the object (because it will throw an error if it doesn't exist and I don't check beforehand).
This is really getting me thinking.... thanks in advance for your help

A: If you don't want to use reflection here, a map of factories could be the right thing:
interface LayoutFactory {

   public CustomLayout makeLayout();

}

Map<String, LayoutFactory> factories = new HashMap<String, LayoutFactory>();
factories.put("GridLayout", new LayoutFactory() {
    public CustomLayout makeLayout() { return new GridLayout(); }
});
factories.put("ListLayout", new LayoutFactory() {
    public CustomLayout makeLayout() { return new ListLayout(); }
});

String layoutName = ...; // user input
CustomLayout l = factories.get(layoutName).makeLayout();

Of course, you also should handle the case where the user did give an unknown layout name (factories.get then returns null).

A: This is the code used to obtain an instance of a class if you have a String with the fully qualified name:
try {
    CustomLayout layout = (CustomLayout) Class.forName("your.package.ListLayout").newInstance();
} catch (Exception ex) {

}

The exception can be of type: LinkageError, ExceptionInInitializerError, ClassNotFoundException, IllegalAccessException, InstantiationException and SecurityException and it is recommended to have catch clauses for each of them if you want to handle them differently.

A: Do something like this:
String userInput = //get user's input
while(!userInput.equalsIgnoreCase("ListLayout") && !userInput.equalsIgnoreCase("gridLayout")){
   System.out.println("Please enter a valid option");
   userInput = //get user's input again
}
CustomLayout layout;
if(userInput.equalsIgnoreCase("ListLayout")
   layout = new ListLayout();
else
   layout = new GridLayout();

A: I would personally not recommend using reflection; as refactoring becomes a pain.
Better would be to do a string check and instantiate the correct class.
For example
if(userInput.equals("ListLayout")) {
    CustomLayout layout = new ListLayout();
} else if (userInput.equals("GridLayout")) {
    CustomLayout layout = new GridLayout();
}

This can also be implemented using java reflection as others pointed out. But if you want to refactor the code later on (say using eclipse refactoring for example), then the reflection code will not be auto-refactored. For example, if you used reflection and if you changed the class name of ListLayout to FancyListLayout, and do eclipse auto refactoring, the reflection code will be left untouched and your code will break.

A: Two steps :

*

*Find if text entered by user corresponds to an existing class (this can be done using the reflections framework, I guess)

*Instanciate an object of that class, which is usually done using Class.forName(String)

A: Ok. What you should be looking into is called Reflection (wiki on reflection) and java offers a rich API for that. THis basically allows you to generate objects from a String and catch the execption if there is no such class accordingly. This has however some drawbacks, please check on the API for further reference.
Cheers!

A: Reflection is the natural answer, but you could create a Factory for it.
public class CustomLayoutFactory {
    public CustomLayout createInstance(String layoutName) {
        if("ListLayout".equals(layoutName) {
            return new ListLayout();
        } else if("GridLayout".equals(layoutName) {
            return new GridLayout();
        }
        return null;
    }
}

While not the most elegant solution, it is useful in cases where the SecurityManager is too restrictive for reflection.

A: Reading all the answers I'd like to strongly recommend against the reflection based ones, since you will have to be very careful in renaming your classes afterwards.
Also instead of:
if ("ListLayout".equals(userInput)) {
   return new ListLayout();
}

you can add a protected field inside your base Layout class:
public abstract class Layout {
    protected String userInputName;
}

and modifying its extenders like so:
public class ListLayout {

    public ListLayout() {
        userInputName = "listLayout"; // set protected field
    }
}

Then you can do:
for (Layout l : setOfAllLayouts) {
    if (userInput.equals(l.getInputName)) {
        return l.clone();
    }
}

A: This ought to do it:
Class.forName(userInput).newInstance();

You can then use instanceof to test for what class you ended up with. However, I'd test the value of userInput before doing this, to make sure it's a recognized class name. You might also need to prepend the package name if your users just input the simple class name.


text:
Q: @ExceptionHandler doesn't catch MethodArgumentNotValidException I have the following @ControllerAdvice:
@ControllerAdvice
public class ExceptionHandlingController {

    @ExceptionHandler(value = { MethodArgumentNotValidException.class,
            EntityExistsException.class, BadCredentialsException.class, MismatchedInputException.class })
    public ResponseEntity<ExceptionResponse> invalidInput(RuntimeException ex) {
        ExceptionResponse response = new ExceptionResponse();
        response.setErrorCode("BAD_REQUEST");
        response.setErrorMessage(ex.getMessage());
        return new ResponseEntity<ExceptionResponse>(response,
                HttpStatus.BAD_REQUEST);
    }

}

And the validator is bound to the controller this way:
@RestController
@RequestMapping("/api/authentication")
public class UserAccountControllerImpl implements UserAccountController {

    @Autowired
    private UserAccountService userAccountService;

    @Override
    public UserAccountEntity login(@Valid @RequestBody UserAccountEntity account,
            HttpServletResponse response) throws BadCredentialsException {
        return userAccountService.authenticateUserAndSetResponsenHeader(
                account.getUsername(), account.getPassword(), response);
    }

    @Override
    public UserAccountEntity create(@Valid @RequestBody UserAccountEntity userAccount,
            HttpServletResponse response) throws EntityExistsException {
        String username = userAccount.getUsername();
        String password = userAccount.getPassword();
        userAccountService.saveIfNotExists(username, password);
        return userAccountService.authenticateUserAndSetResponsenHeader(
                username, password, response);
    }

    //used to bind the validator to the incoming request
    @InitBinder
    public void binder(WebDataBinder binder) {
        binder.addValidators(new UserAccountValidator());
    }
}

And this is the UserAccountValidator used to validate the incoming UserAccountEntity:
public class UserAccountValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return UserAccountEntity.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        UserAccountEntity userAccount = (UserAccountEntity) target;
        String password = userAccount.getPassword();
        String username = userAccount.getUsername();
        EmailValidator emailValidator = EmailValidator.getInstance();
        if (!emailValidator.isValid(username)) {
            errors.reject("Username must be a valid email address");
        }
        if (password.length() > 30 || password.length() < 8) {
            errors.reject("Password must be at least 8 and at most 30 characters");
        }
        if (!Pattern.compile( "[0-9]" ).matcher(password).find()) { // it doesn't contain any digit
            errors.reject("Password must have at least one digit");
        }
        if (password.toUpperCase().equals(password)) { //it's all upper-case
            errors.reject("Password must have at least one lower case character");
        }
        if (password.toLowerCase().equals(password)) { //it's all lower-case
            errors.reject("Password must have at least one upper case character");
        }
    }
}

When I pass in an invalid password/username, I get the following error:
java.lang.IllegalStateException: Could not resolve method parameter at index 0 in public org.springframework.http.ResponseEntity<com.myproject.project.core.controller.ExceptionResponse> com.myproject.project.core.controller.ExceptionHandlingController.invalidInput(java.lang.RuntimeException): No suitable resolver for argument 0 of type 'java.lang.RuntimeException'
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:175) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]

Why doesn't it catch MethodArgumentNotValidException?

A: At least, an exception MethodArgumentNotValidException is not a RuntimeException, but you use RuntimeException argument in that exception handler.
For test change RuntimeException to Exception in method's argument.


text:
Q: TestMethod do not support getContent call I have a requirement to send a specific report as an attachment on schedule basis.
So, i have created a schedule class with future annotation to send.But now when i'm trying to setup apex class I'm getting below error.

Error Message Methods defined as TestMethod do not support getContent
  call

Apex class:
global class CallSubscriptionReportScheduler {
@future(callout=true)
    public static void SentSubscriptionData()
    {
        Id userdetail=[Select id from user where email='xyz@gmail.com'].id;
        OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = 'info@xyz.com' Limit 1];
        ApexPages.PageReference report = new ApexPages.PageReference('/00O6F00000CGpHH?csv=1');
        Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
        attachment.setFileName('Data_Report.csv');
        attachment.setBody(report.getContent());
        attachment.setContentType('text/csv');
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
        message.setSubject('Data');
        message.setPlainTextBody('The report is attached.');
        message.setOrgWideEmailAddressId(owea.get(0).Id);
        message.setReplyTo('sfdcadmin@xyz.com');
        message.setTargetObjectId(userdetail);
        message.setSaveAsActivity(false);
        Messaging.sendEmail( new Messaging.SingleEmailMessage[] { message } );
    }
}

Test class:
@isTest
public class TestWeeklySubscriptionData {
    public static String CRON_EXP = '0 0 1 ? * MON';
    static testmethod void testsubscription() {
            Test.startTest();
            WeeklySubscriptionData uca = new WeeklySubscriptionData();
            String jobId = System.schedule('ScheduledApexTest',CRON_EXP,new WeeklySubscriptionData());
            Test.stopTest();
            // after the testing stops, assert records were updated properly
            //System.assertEquals(6, [select count() from Lead where Lead_Type__c='Insurance' AND RecordTypeId ='0126F0000016MZP']);
    }
}

Could someone help me.

A: I have found no way to handle this other than using the last resort Test.isRunningTest:
PageReference pr = ...;

Blob pdf = !Test.isRunningTest() ? pr.getContentAsPdf() : Blob.valueOf('Fake content');

or in your class:
attachment.setBody(!Test.isRunningTest() ? report.getContent() : Blob.valueOf('Fake content'));


text:
Q: Cassandra NodeTool Showing value as NaN In my 3 node Cassandra cluster I tried to get node info by executing "nodetool info" but I can see some NaN values in Cache details.
Rack                   : 2a
Exceptions             : 0
Key Cache              : entries 478610, size 36.52 MiB, capacity 50 MiB, 251452781 hits, 292195506 requests, 0.861 recent hit rate, 14400 save period in seconds
Row Cache              : entries 0, size 0 bytes, capacity 0 bytes, 0 hits, 0 requests, NaN recent hit rate, 0 save period in seconds
Counter Cache          : entries 0, size 0 bytes, capacity 25 MiB, 0 hits, 0 requests, NaN recent hit rate, 7200 save period in seconds
Chunk Cache            : entries 18, size 1.12 MiB, capacity 219 MiB, 259 misses, 9648 requests, 0.973 recent hit rate, NaN microseconds miss latency

Can't figure out why it is returning NaN values.
Using Cassandra ReleaseVersion: 3.11.6

A: It happens because there is no activity in corresponding caches, and as result, hit ratio couldn't be calculated as 0 hits divided by 0 requests gives you a NaN (not a number).  You can see this discussion about NaNs


text:
Q: Сумма классов js Нужно получить сумму классов у которых data-option равны

100

100

200

200

Получить нужно массив

A: Попробуйте такой вариант.
function func() {
    // берем все элементы с классом sum
    var elements = document.getElementsByClassName('sum');
    var obj = {}
    // проходим по всем элементам
    for (var i = 0; i < elements.length; i++) {
        var attribute = elements[i].getAttribute('data-option') // берем значение аттрибута
        var value = Number(elements[i].innerHTML) // берем значение и переводим в число
        // если такой ключ уже существует, то прибавляем к значению текущее значение
        if (obj[attribute]) {
            obj[attribute] += value
        // если такого ключа нет, то создаем
        } else {
            obj[attribute] = value
        }
    }
    // берем только значения объекта
    var result = Object.values(obj)
}


text:
Q: Function that return a pointer to a struct with ctypes The prototype of my C function is:
typedef struct {
    int a;
    int b;
} foo_t;

foo_t* foo(int a);

In Python I have to redefine my structure:
class Foo(Structure):
    _fields_ = [("a", c_int), ("b", c_int)]

My question is how do I properly cast my return value in Foo?
>>> dll.foo.restype = POINTER(Foo)
>>> ret = dll.foo(42);
>>> print ret
<dll.LP_Foo object at 0xffe7c98c>
>>> print ret.a
AttributeError: 'LP_Foo' object has no attribute 'a'

I have also tried Foo instead of POINTER(Foo). With this I can access Foo members but the values are wrong.
From ctypes I can read this:

ctypes.POINTER(type)
  This factory function creates and returns a new ctypes pointer type. Pointer types are cached an reused internally, so calling this function repeatedly is cheap. type must be a ctypes type

So type cannot be Foo. I probably have to find another way.

A: From documentation:

Pointer instances have a contents attribute which returns the object to which the pointer points

So try:
>>> print ret.contents.a

Be aware that the documentation states:

Note that ctypes does not have OOR (original object return), it constructs a new, equivalent object each time you retrieve an attribute


text:
Q: VS2008 C++ Release mode slower than Debug mode I am working with mixed Native and Managed Visual C++, using STL in the Native. I have a strange problem. It seems that when I compile my software in Release mode with all the optimizations set, my software consistently runs slower than in Debug mode. What could be wrong here?
These are my Debug command line options:
/Od /D "WIN32" /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /FD /EHa /MDd /Fo"Debug\" /Fd"Debug\vc90.pdb" /W3 /nologo /c /Zi /clr /TP /errorReport:prompt /FU "c:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll" /FU "c:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Data.dll" /FU "c:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll" /FU "c:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll" /FU "c:\Windows\Microsoft.NET\Framework\v2.0.50727\System.XML.dll"
These are my Release command line options:
/Oi /Ot /Oy /GT /GL /D "WIN32" /D "_SECURE_SCL=0" /D "_HAS_ITERATOR_DEBUGGING=0" /D "VC_EXTRALEAN" /D "_UNICODE" /D "UNICODE" /FD /EHa /MD /Fo"Release\" /Fd"Release\vc90.pdb" /W3 /nologo /c /clr /TP /errorReport:prompt /FU "c:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll" /FU "c:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Data.dll" /FU "c:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll" /FU "c:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll" /FU "c:\Windows\Microsoft.NET\Framework\v2.0.50727\System.XML.dll"

A: That's utterly impossible to diagnose from the command line switches, you have to use a profiler.
One thing that's relevant however is you using the /clr option.  Unless you explicitly use #pragma managed in your code, everything will be translated to IL, even the STL template code.  Which means that your optimization settings have no effect whatsoever since they only apply to generated machine code.  You are then subject to what the JIT compiler does for optimization.  It will not optimize by default when you have a debugger attached for example.

A: Try profiling the release version to see if you notice any obviously incorrect slowness. If needed, compare it to a profile output from the debug version.
Alternately if the debug version is subjectively "fast enough", just release that (although there might be reverse-engineering implications).


text:
Q: How do I use 2 columns of a CSV file in a single command? I want to use serverip and ram which is in same csv file in a command which have $serverip and $ram . So I want to use corresponding serverip and ram value in foreach loop at once.
csv file is like this:
sw02111 8
sw02014 4
sw02020 16

now i want to use this value to below command in for-each loop:
Set-VM -VM $serverip -MemoryMB $ram

A: If your CSV file has a header row of RAM, ServerIP then you could do the following
Import-CSV YourFile.csv -header serverip,ram -delimiter ' ' | ForEach-Object {
    Set-VM -VM $_.ServerIP -MemoryMB $_.RAM
}

Explanation:

*

*Import-CSV loads the CSV file in to a PowerShell object and then passes it via the pipeline to ForEach-Object.

*Based on your CSV sample in your question I've explicitly defined in the Import-CSV command the header as serverip,ram and the delimiter as a space character. If your CSV is formatted differently these may need to be changed or these settings might not be necessary at all if you have a well defined CSV.

*Each item in the object is evaluated one at a time and represented in the loop as $_.

*Because the CSV has ServerIP and RAM headers the object has the equivalent properties which are accessed via .


text:
Q: Print Jasper Report without pages I'm creating HTML (popup window), EXCEL and PDF report and would like to show my reports on one page. This report is not going to be used for printing, so there is no need separate my report into pages. Plus later users would like to use Buildin Excel sorting.
Is there an option to ignore pages?

A: Toggle pagination during report filling. For example, Excel or HTML output should not be paginated. Sample code:
parameters.put(JRParameter.IS_IGNORE_PAGINATION, true);
JasperPrint print = JasperFillManager.fillReport(report, parameters, data);

A: I don't know if there an option to ignore pages, but you can change the page height to a very big number (10000)?
In the XML, set the pageHeight attribute to "10000", or similar.

A: As an alternative to checking "Ignore pagination", you should be able to get a similar effect by setting the page bands' height to zero. At least for Excel and HTML reports, not sure about PDF.
This is helpful for large reports when you want to use Jasper's Virtualizer feature. The reason is that the virtualizer stores entire pages on disk, and if you enable ignore pagination, you will not get the benefit from the virtualizer and risk running out of memory.

A: Under the Report Properties in the "More . . ." section.  There is a Ignore Pagination option.  Check this box and it should work

A: My project is using net.sf.jasperreports.engine.JasperReport ver 3.6.1 to generate csv file and surprisingly I see the csv output file is inserted with alternate ,,1,,, and ,,9,,, at every 42nd line.
Refer here: http://jasperreports.sourceforge.net/sample.reference/nopagebreak/
I added the following setting in the jrxml template
<jasperReport ... isIgnorePagination="true" ...>
...
</jasperReport>

and the empty line is gone.


text:
Q: Updating database table with new form values I've been tasked to fix a problem on our website and I'm not very well versed in SQL/PHP but we have a system that uses a front page datatable, displaying records from our database. When you click a serial number link in that table, it brings up a web based form/tables filled by the data from the specified record. I've now been told to make two of the tables editable so that it still shows the current fields from the database, but this way we would have the option to change them, hit the submit button and save the new values to the database.
The code below covers the instance from the front page and the query that selects the right row from our 'staging' database table and displays the info from only that record. This works fine and since I upded the code with input tags I can now edit the fields, but I've yet to implement the option to save them.
If I understand right, I would create a 'Submit' button on this page (although I was thinking of an option that may have a save button for every html table) and when the button is pressed, I would attach a SQL UPDATE statement.
I have two questions here:

*

*If I were to edit every one of the input fields in the below code, what is the proper way to run that UPDATE statement to properly set each of those values?

*If you see below, I have a formula that averages some values and I put that result in $testFinalForm. This is all done on the web page and that value doesn't exist in the database table. If I were to add testFinalForm to my database table, I would like to save that value as well.
Again, this is not something I usually have to do and I'm a bit overwhelmed so I'm just hoping for some helpful guidance.
if(isset($_GET['id']))
{

$query1 = "SELECT * FROM staging WHERE serialNumber = ".$_REQUEST['id'].";";
$result1 = mysqli_query($connect,$query1);

while($row = mysqli_fetch_array($result1)){
?>
<form>

        Meter Test
        Test 1
        Test 2
        Test 3
        Test 4
        Test 5
        Test 6
        Test 7
        Test 8

        Test Rate GPM:
        <input type="text" value="<? echo $row['test1TestRateGPM'];?>">
        <input type="text" value="<? echo $row['test2TestRateGPM'];?>">
        <input type="text" value="<? echo $row['test3TestRateGPM'];?>">
        <input type="text" value="<? echo $row['test4TestRateGPM'];?>">
        <input type="text" value="<? echo $row['test5TestRateGPM'];?>">
        <input type="text" value="<? echo $row['test6TestRateGPM'];?>">
        <input type="text" value="<? echo $row['test7TestRateGPM'];?>">
        <input type="text" value="<? echo $row['test8TestRateGPM'];?>">

        Meter Volume:
        <input type="text" value="<? echo $row['test1MeterVol'];?>">
        <input type="text" value="<? echo $row['test2MeterVol'];?>">
        <input type="text" value="<? echo $row['test3MeterVol'];?>">
        <input type="text" value="<? echo $row['test4MeterVol'];?>">
        <input type="text" value="<? echo $row['test5MeterVol'];?>">
        <input type="text" value="<? echo $row['test6MeterVol'];?>">
        <input type="text" value="<? echo $row['test7MeterVol'];?>">
        <input type="text" value="<? echo $row['test8MeterVol'];?>">

        Tester Volume:
        <input type="text" value="<? echo $row['test1TesterVol'];?>">
        <input type="text" value="<? echo $row['test2TesterVol'];?>">
        <input type="text" value="<? echo $row['test3TesterVol'];?>">
        <input type="text" value="<? echo $row['test4TesterVol'];?>">
        <input type="text" value="<? echo $row['test5TesterVol'];?>">
        <input type="text" value="<? echo $row['test6TesterVol'];?>">
        <input type="text" value="<? echo $row['test7TesterVol'];?>">
        <input type="text" value="<? echo $row['test8TesterVol'];?>">

        Tester Accuracy:
        <input type="text" value="<? echo $row['test1Accuracy'];?>">%
        <input type="text" value="<? echo $row['test2Accuracy'];?>">%
        <input type="text" value="<? echo $row['test3Accuracy'];?>">%
        <input type="text" value="<? echo $row['test4Accuracy'];?>">%
        <input type="text" value="<? echo $row['test5Accuracy'];?>">%
        <input type="text" value="<? echo $row['test6Accuracy'];?>">%
        <input type="text" value="<? echo $row['test7Accuracy'];?>">%
        <input type="text" value="<? echo $row['test8Accuracy'];?>">%
        Overall

        Corrected Accuracy:

            <?php
        $sum=0;

        for($i=1; $i<=8; $i++){

        if($row["test".$i."TesterVol"] == 0){
        $row["test".$i."TesterVol"] = 0.001;
        }

        $testFormA = $row["test".$i."MeterVol"] / $row["test".$i."TesterVol"];
        $testFormB = $testFormA * $row["test".$i."Accuracy"];
        $testFinalForm = $testFormB;
        $sum += $testFinalForm;

        ?>
        <?php echo round($testFinalForm,3) ?>%

        <?php }
        $average = $sum / 7 ;

        ?>

        <?php echo round($average,5)?>%

</form>


text:
Q: Update select dropdown list on filtering js-grid data I want to update the select box list on filtering event of jsgrid.
I read the documentation but there is no such feature for JsGrid.In the fiddle there is a country dropdown which has different countries.
When i give input in Age as 29 it return 2 rows with country as China & Russia.
So on this filtering i want to update the select box list with only China & Russia and on giving blank input or removing all the filter items it should update the dropdown with original countries list.
I had searched a lot ,i didn't find any solution.
Fiddle link -
fiddle


text:
Q: How to override the response body of AuthenticationFailure using AbstractPreAuthenticatedProcessingFilter? I'm using a Custom Filter to make the request Authetincation. Configuring the AutheticationFailureHandler, I want put the message error content, but it is attached to a existent default content, my goal is put together on the same body or just a new one.
Handler impl.:
 protected void configure(HttpSecurity httpSecurity) throws Exception {
APIKeyAuthFilter apiKeyAuthFilter = new APIKeyAuthFilter(HEADER_USER_AGENT, HEADER_APIKEY);

apiKeyAuthFilter.setAuthenticationFailureHandler((request, response, exception) -> {
                if(exception.getMessage().equals(MESSAGE_USER_AGENT_NOT_FOUND)) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("message",MESSAGE_USER_AGENT_NOT_FOUND);
                    response.getOutputStream()
                            .println(objectMapper.writeValueAsString(data));
                }
            });
}

Response body:
{
    "message": "User-Agent not found."
}
{
    "timestamp": "2020-07-16T16:26:59.438+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Access Denied",
    "path": "/api"
}

Like shows, this is returning two JSON contents. How I set just one or append to existent?
Whole code:
public class APIKeyAuthFilter extends AbstractPreAuthenticatedProcessingFilter {

    private String userAgentRequestHeader;
    private String apiKeyRequestHeader;

    public APIKeyAuthFilter(String userAgentRequestHeader, String apiKeyRequestHeader) {
        this.userAgentRequestHeader = userAgentRequestHeader;
        this.apiKeyRequestHeader = apiKeyRequestHeader;
    }

    @Override
    protected RequestAuthVo getPreAuthenticatedPrincipal(HttpServletRequest request) {
        String userAgent = request.getHeader(userAgentRequestHeader);
        String apiKey = request.getHeader(apiKeyRequestHeader);
        RequestAuthVo requestAuthVo = new RequestAuthVo(userAgent,apiKey);
        return requestAuthVo;
    }

    @Override
    protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
        return "N/A";
    }

}

Configure:
        @Override
        @Order(2)
        protected void configure(HttpSecurity httpSecurity) throws Exception {
                APIKeyAuthFilter apiKeyAuthFilter = new APIKeyAuthFilter(HEADER_USER_AGENT, HEADER_APIKEY);

            apiKeyAuthFilter.setAuthenticationManager(authentication -> {
                RequestAuthVo requestAuthVo = (RequestAuthVo) authentication.getPrincipal();

                if (!mapAuths.containsKey(requestAuthVo.getUserAgent())) {
                    throw new UserAgentNotFoundException(MESSAGE_USER_AGENT_NOT_FOUND);
                }

                if(mapAuths.containsKey(requestAuthVo.getUserAgent()) && mapAuths.get(requestAuthVo.getUserAgent()).equals(requestAuthVo.getApiKey())) {
                    authentication.setAuthenticated(true);
                    return authentication;
                }

                return authentication;
            });

            ObjectMapper objectMapper = new ObjectMapper();

 apiKeyAuthFilter.setAuthenticationFailureHandler((request, response, exception) -> {
                    if(exception.getMessage().equals(MESSAGE_USER_AGENT_NOT_FOUND)) {
                        Map<String, Object> data = new HashMap<>();
                        data.put("message",MESSAGE_USER_AGENT_NOT_FOUND);
                        response.getOutputStream()
                                .println(objectMapper.writeValueAsString(data));
                    }
                });

            httpSecurity.antMatcher("/**").
                    csrf().disable().
                    sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
                    and()
                    .addFilter(apiKeyAuthFilter).authorizeRequests().anyRequest().authenticated();
        }

    }

A: Can you try this?
    apiKeyAuthFilter.setAuthenticationFailureHandler(
            (request, response, exception) -> {
        if(exception.getMessage().equals(MESSAGE_USER_AGENT_NOT_FOUND)) {
            Map<String, Object> data = new HashMap<>();
            data.put("message",MESSAGE_USER_AGENT_NOT_FOUND);
            request.setAttribute("AGENT_NOT_FOUND",
                                 objectMapper.writeValueAsString(data));
        }
    });

    http.exceptionHandling()
      .authenticationEntryPoint((request, response, e) ->
      {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        String value = request.getAttribute("AGENT_NOT_FOUND").toString();
        response.getWriter().write(value);
      });
    }


text:
Q: Is there any good generic JPA DAO implemenation?  According this article, generic JPA DAO(Data Access Object) is a pretty nice pattern.
Is there any good implementation?

A: You could take a look into the Spring Data JPA.
A few new concepts were introduced into Spring Data JPA, for instance the Query creation based on the method name, so you can declare a method like findById(String id) and the "generic" implementation will interpret the method's name and execute something like select Entity from Entity where id = 'given string'
Methods like findByNameAndLastName(String name, String lastName) or even findByNameOrInternalId(String name, int internalId) are supported too.

A: Just wanted to mention a couple more generic dao implementations for JPA:

*

*Generic DAO toolkit - http://code.google.com/p/generic-dao/

*Related Question in SO -
Single DAO & generic CRUD methods (JPA/Hibernate + Spring)

*A good blog article on
JPA DAO -
http://blog.xebia.com/2009/03/09/jpa-implementation-patterns-data-access-objects/

A: Querydsl supports JPA and has an extensive support for building complex predicates for queries.
It doesn't support updates and inserts but you can use Spring Data for that, as Querydsl also integrates with Spring repositories.


text:
Q: jQuery Horizontal Scroll Animation This is probably a very basic question and it's because I'm such a noob to jQuery that I don't know this.
I have a wide web site with all content laid out horizontally. Instead of using a scroll bar at the bottom I have a button on either side so that when you click it, it moves you left or right in the site.
I have the jQuery here:
$(".timeline_page a.flex-prev").click(function(){
$(".timeline_page_wrapper").scrollLeft(Math.max(0, $(".timeline_page_wrapper").scrollLeft() - 500));
});

$(".timeline_page a.flex-next").click(function(){
$(".timeline_page_wrapper").scrollLeft(Math.min(1200, $(".timeline_page_wrapper").scrollLeft() + 500));
});

So far so good. But I would like to animate it and I can't figure out how to do so. Everything I try causes it not to run.
On a related note is there a way for me to know when the user is at the end of the right or left side so I can change the button state?
EDIT:
Ok so now I've got the following code and managed to animate it. But what am I doing wrong with adding or removing a class if it reaches a certain point?
$(".timeline_page a.flex-prev").click(function(){
$(".timeline_page_wrapper").animate({
    scrollLeft: Math.max(0, $(".timeline_page_wrapper").scrollLeft() - 500)}, 650);
});

$(".timeline_page a.flex-next").click(function(){
$(".timeline_page_wrapper").animate({
    scrollLeft: Math.min(4080, $(".timeline_page_wrapper").scrollLeft() + 500)}, 650);
});

if ($(".timeline_page_wrapper").scrollLeft() === 0 {
    $(".timeline_page a.flex-prev").addClass("flex-disabled");
} else {
    $(".timeline_page a.flex-prev").removeClass("flex-disabled");
}
);

});

A: I have used it before and it works! See demo and tutorial here.

A: Take a look at the JQuery Animate() method. Try animating the position in increments of the view/page width.
http://api.jquery.com/animate/
You can tell the user is at the end by checking the scrollLeft() for timeline_page_wrapper and comparing it to the entire content width. Scrollleft should also give you the amount left to be displayed. A little arithmetic will tell you if you've come to the end of the page.
http://api.jquery.com/scrollLeft/
Hope this helps


text:
Q: Backbone/RequireJS and multiple models I am having trouble wrapping my mind around primarily RequireJS. I see that it is a good/necessary technology, but implementing it, for me, has been a real stretch. I greatly appreciate your help!
I am trying to develop a fairly flexible application with Backbone and RequireJS. The problem is that I am totally used to syntax like new Person() without having to specify dependencies. Is there an efficient way to use RequireJS with quite a number of models? I think my problem is always working with returns. I considered using a factory method to create the model with the require function, but doing so necessitates that the require function is synchronous, which completely defeats the purpose of RequireJS.
It just doesn't seem right to have to require all of my models first and then include those in the instantiation function - or do I?
Do you have any suggestions or tutorials about how to structure and model an application like this?
Thank you for helping me out!
JMax

A: You can use what I call require js module pattern. If you know a group of classes are often used together you can do something like this.
First you define each class in a separate file and then you define a module to hold them together
Module.js

define([

    './models/FirstModel',
    './models/SecondModel',
    './views/FirstView',
    './views/SecondView',
    'txt!./templates/template.tpl'

], function(FirstModel, SecondModel, FirstView, SecondView, template) {

    return {
        FirstModel: FirstModel,
        SecondModel: SecondModel,
        FirstView: FirstView,
        SecondView: SecondView,
        template: template
    }

});

And then when you want to use class from this module you just do
define(['./Module'], function(Module) {

    var AView = Module.FirstView.extend({

        model: Module.FirstModel,

        render: function() {

            this.html(_.template(Module.template)(this.model.attributes));

            if (something) {

                this.$el.append(new Module.SecondView().render().el);
            }
        }
    })

    return AView;
});

I don't believe using modules defined with requirejs we should return an instance - we should always return a constructor or an object.
You should totally embrace the defining and requiring - with time you'll start to love it - without having to think much about adding/tracking dependencies etc. everywhere by hand or (so 2005!) having most of the stuff in one file :)


text:
Q: nhibernate freeware disgner plugin for visual studio 2010? I'm new to and ORMs.
Does anyone know of a recommended free nhibernate designer plugin for visual studio 2010?
mainly for easy mapping.

A: There is NHibernate Designer from mindscape, but it's only free for 10 entities or less.
It's also available for download here.

A: If you are willing to consider something outside visual studio, you can try Visual Nhibernate


text:
Q: How to use word embeddings for prediction in Tensorflow I'm trying to work through the Tensorflow tutorials and have gotten stuck trying to enhance the RNN/language model tutorial so that I can predict the next word in a sentence. The tutorial uses word embeddings as the representation for the words.
Since the model learns on the word embeddings, I'm assuming that any sort of prediction I add will output the same embeddings. What I can't figure out is how to convert from those embeddings back to the word ids from the dataset. The only example I have seen kept an in memory data structure with the reverse of the mapping of wordid -> embedding and used that for lookups. This obviously won't work for all problems. Is there a better way?

A: Assuming you have both word_to_idx and idx_to_word from the vocabulary, this is the pseudocode for what you do
Imagine the input for prediction is "this is sample"
batch_size = 1
num_steps = 3 # i.e each step for the word in "this is sample"
hidden_size = 1500
vocab_size = 10000
translate the `word_to_idx` for the input `"this is sample"`
get the word embeddings for the each word in the input
Input to model will be word embedding of size 1x1500 at each time step
Output of model at each time step will be of size 1x1500
y_pred is output at last step from model for the given input
adding projection to output (i.e y_pred x Weights(hidden_size, vocab_size) + bias(vocab_size, )  = 1x10000)
now sample the output through the below function to get the index with max probability
generate idx_to_word from the index we just got
use the generated word along with the previous input to generate next word until you get `<eos>` or some predefined sentence stopping.

Here's an example of sampling from here:
def sample(a, temperature=1.0):
    # helper function to sample an index from a probability array
    a = np.log(a) / temperature
    a = np.exp(a) / np.sum(np.exp(a))
    return np.argmax(np.random.multinomial(1, a, 1))


text:
Q: run bash script from html I have read in several questions here how to run a bash script from html. Most of them referred me to php. I followed everything in here but no go.
I don't have any experience with html or php.
So I set up everything as it should be (I think...).
I installed nginx (and its working fine).
I installed php and php-fpm.
My simple webpage is:
<!DOCTYPE html>

<title>My page</title>

<button type="button" onclick="run.php">Click Me!</button>

My default nginx server config is:
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.html index.htm;

    # Make site accessible from http://localhost/
    server_name localhost;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        #try_files $uri $uri/ =404;
        try_files $uri $uri/ /index.html;
        # Uncomment to enable naxsi on this location
        # include /etc/nginx/naxsi.rules
    }

    # Only for nginx-naxsi used with nginx-naxsi-ui : process denied requests
    #location /RequestDenied {
    #   proxy_pass http://127.0.0.1:8080;
    #}

    #error_page 404 /404.html;

    # redirect server error pages to the static page /50x.html
    #
    #error_page 500 502 503 504 /50x.html;
    #location = /50x.html {
    #   root /usr/share/nginx/html;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
    #   # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    #
    #   # With php5-cgi alone:
        fastcgi_pass 127.0.0.1:9000;
    #   # With php5-fpm:
    #   fastcgi_pass unix:/var/run/php5-fpm.sock;
    #   fastcgi_index index.php;
    #   include fastcgi_params;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #   deny all;
    #}
}

I tried both options: With php5-cgi alone / With php5-fpm
My php script that should trigger on button click:
<?php
shell_exec("ls");
header('Location: https://www.google.com');
?>

But nothing happens (for now, I run just simple ls. when this will work i'll change it to some /path/script.sh)
What did I do wrong?

A: So as I mentioned before, I don't have any experience with html or php.
The problem was I separated the html and php  files. When combined, everything worked ok.
<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  exec("ls");
  header('Location: https://www.google.com');
}
?>

<title>My page</title>

Click Me!


text:
Q: MySQL + Grafana: slow queries on time series data I'm new to Grafana and MySQL, .
I have an IoT device sending data every 1 second to an Amazon RDS Aurora database running with MySQL (db.t3.small). With Grafana, I added the RDS Datasource and created a Dashboard to visualize a sensor value on a chart (5 minutes of data displayed, so 300 values).
I noticed that for the first hours, the queries run fast and the dashboard refreshes in less of a second.
However, after 24 hours of data sent to the database, it takes more than 20 seconds to refresh the dashboard. I tried with a Unix timestamp type stored as an integer and with the TIMESTAMP type of MySQL, but I got the same problem. Here is my query:
SELECT
  ts_timestampFormat AS "time",
  LAeq
FROM testsGrafanaTable
WHERE
  $__timeFilter(ts_timestampFormat ) AND
  station_id = 'station-1'
ORDER BY ts_timestampFormat

*

*Could you help me to understand why this is happening?  Is this related to the query? Or to the database performance?

*How I can get a faster query?
I also tried to use a time range in the WHERE statement, ts_timestampFormat >= $__timeFrom() AND ts_timestampFormat <= $__timeTo() AND, but I got the same issue.
Thanks!


text:
Q: To Understand More about Encoding U+30C9 vs U+30C8U+3099 ド(U+30C9) vs ド(U+30C8U+3099)
Fyi, the situation is

*

*a user uploaded a file with name containing ド(U+30C8U+3099) to AWS s3 from a web app.

*Then, the website sent a POST request containing the file name without url encoding to AWS lambda function for further processing using Python. The name when arrived in Lambda became ド(U+30C9). Python then failed to access the file stored in s3 because of the difference in unicode.

I think the solution would be to do url encoding on frontend before sending the request and do url decoding using urllib.parse.unquote to have the same unicode.
My questions are

*

*would url encoding solve that issue? I can't reproduce the same issue probably because I am on a different OS from the user's OS.

*How exactly did it happen since both requests (uploading to s3 and sending the 2nd request to lambda) happened on the user's machine?
Thank you.

A: Your are hitting a common case (maybe more common in Latin scripts): canonical equivalence. Unicode requires to handle canonical equivalent sequences in the same manner.
If you look in UnicodeData.txt you will find:
30C8;KATAKANA LETTER TO;Lo;0;L;;;;;N;;;;;
30C9;KATAKANA LETTER DO;Lo;0;L;30C8 3099;;;;N;;;;;

so, 30C9 is canonical equivalent to 30C8 3099.
Usually, it is better to normalize Unicode strings to a common canonical form. Unfortunately we have two of them: NFC and NFD: Normalization Form Canonical Composition and Normalization Form Canonical Decomposition. Apple prefers the later (and Unicode original design/preference is about this form), and most of the other vendors the first.
So do no trust web browsers to keep the same form. But also consider that input methods on user side may give you different variations (and with keyboards you may have also non-canonical forms which should be normalized [this can happens with several combining characters]).
So, on your backend you should choose a normalization form, and transform all input data in such form (or just be sure that all search and comparing functions can handle equivalent sequences correctly, but this requires a normalization on every call, so it may be less efficient).
Python has unicodedata.normalize() (in standard library, see unicodedata module), to normalize Unicode strings. Eventually on other languages you should use ICU library. In any case, you should normalize Unicode strings.
Note: this has nothing about encoding, but it is in built directly in Unicode design. The reason is about requirement to be compatible with old encoding and old encodings had both ways to describe the same characters.


text:
Q: Set field Accessibility to Custom Salesforce Lead field from Java code I am working around with Salesforce and force.com API and metadata API, version 36.
I can create a custom field in a Lead object but by default I can see it's hidden and this means I cannot create a new Lead with these custom fields because  it returns a bad request (400 status code).
Is there any way by Code to set the custom field Visible?
public boolean createCustomExtTextField(String name, LoginResult metadataLoginResult, int length) {
    boolean success = false;
    CustomField cs = new CustomField();
    cs.setFullName("Lead."+name+"__c");
    cs.setLabel("Custom"+name+"Field");
    cs.setType(FieldType.LongTextArea);
    cs.setLength(length);
    cs.setVisibleLines(50); // max 50

    try {
        MetadataConnection metadataConnection = createMetadataConnection(metadataLoginResult);
        SaveResult[] results = metadataConnection.createMetadata(new Metadata[] { cs });

        for (SaveResult r : results) {
            if (r.isSuccess()) {
                success = true;
            } else {
                System.out.println("Errors were encountered while creating " + r.getFullName());
                for (com.sforce.soap.metadata.Error e : r.getErrors()) {
                    System.out.println("Error message: " + e.getMessage());
                    System.out.println("Status code: " + e.getStatusCode());
                }
            }
        }
    } catch (ConnectionException e) {
        e.printStackTrace();
    }
    return success;
}

I am googling a lot and don't find something that actually helped. So, any hints are welcomed. Thank you.

A: Finally found a solution to this. I final one for me was to make all custom fields REQUIRED.
CustomField cs = new CustomField();
cs.setFullName("Lead.YourCompanyName" + name + "__c");
cs.setLabel("YourCompanyName" + name);
cs.setRequired(true);

...
com.sforce.soap.enterprise.LoginResult metadataLoginResult = operations.loginToMetadata(username, password, "https://login.salesforce.com/services/Soap/c/36.0");

...
private boolean createFieldInMetadata(LoginResult metadataLoginResult, CustomField cs) {
        boolean success = false;
        try {
            MetadataConnection metadataConnection = createMetadataConnection(metadataLoginResult);
            SaveResult[] results = metadataConnection.createMetadata(new Metadata[] { cs });

            for (SaveResult r : results) {
                if (r.isSuccess()) {
                    success = true;
                } else {
                    System.out.println("Errors were encountered while creating " + r.getFullName());
                    for (com.sforce.soap.metadata.Error e : r.getErrors()) {
                        System.out.println("Error message: " + e.getMessage());
                        System.out.println("Status code: " + e.getStatusCode());
                    }
                }
            }
        } catch (Exception e) {
        }
        return success;
    }

And so it will appear in the page layout. Very important to know, a required field cannot have just an empty value set, it must be something. So if not all custom fields are required in your logic and you wanna avoid the entire process of unzipping page layout and zipping it back (however it may be done) just add "N/A" or any char at choice to the required by code but not your project custom fields.
I managed to make the custom Field Level Security visible for "Admin" profile but not Field Accessability to visible. The latter is untested.


text:
Q: Rails 5 and AJAX - can't do autocomplete and saving a nested form There is a model of teams in which there are a lot of users. Users are associated with the model of teams like has_many :through.
Need to make a field autocomplete when searching for users and adding nested fields when you select a user.
app/controllers/teams_controller.rb
class TeamsController < ApplicationController

  # GET /teams/new
  def new
    @team = Team.new #(parent_id: params[:parent_id])
  end

  # GET /teams/1/edit
  def edit
  end

  # POST /teams
  def create
    @team = Team.new(team_params)

    respond_to do |format|
      if @team.save
        format.html { redirect_to @team, success: t('.flash.success.message') }
      else
        format.html { render :new, danger: t('.flash.danger.message') }
      end
    end
  end

  # GET /teams/1/search_team_user
  def search_team_user
    @users = User.order(:first_name).where("first_name like ?", "%#{params[:term]}%")
    render json: @users.map { |u| { value: u.id, label: u.name } }
  end

  # GET /teams/1/new_team_user
  def new_team_user
    @team = Team.find(params[:id])
    @new_team_user = @team.team_users.build(user_id: params[:user_id])
  end

  private

    # Never trust parameters from the scary internet, only allow the white list through.
    def team_params
      params.require(:team).permit(
        :name,
        :parent_id,
        team_users_attributes: [:_destroy, :id, :user_id]
      )
    end
end

app/config/routes.rb
resources :teams do
  get :search_team_user, on: :member
  get :new_team_user, on: :member
end

app/views/teams/_form.html.erb
<%= form_for(@team) do |f| %>

    <div class='<%= column_class %>'>

        <div class='<%= dynamic_small_column_class %>'>
          Team membership

        <div class='<%= dynamic_large_column_class %>'>

            <%= text_field_tag 'search_team_users', nil, class: 'form-control autocomplete autocomplete-search new-nested-object', data: { autocomplete_object_id: true, autocomplete_source: search_team_user_team_path(@team), new_nested_object_path: new_team_user_team_path(@team) } %>
            <%= hidden_field_tag 'user_id', nil, class: 'autocomplete autocomplete-value new-nested-object' %>

            <%= render 'team_user_fields', f: f, team_users: @team_users, child_index: nil %>

    <div class='<%= column_class %>'>

        <%= cancel_link %>
        <%= save_link %>

<% end %>

app/views/teams/new_team_user.js.erb
$('#team-users').append("<%= j(fields_for(@team) { |f| render('team_user_fields', f: f, team_users: @new_team_user, child_index: Time.now.to_i) }) %>");

app/assets/javascripts/nested_form.coffee
# # Autocomplete plagin
#
$.fn.customAutocomplete = ->
  @each (i, el) ->
    el = $(el)
    el.autocomplete
      minLength: 1
      source: el.data('autocomplete-source')
      focus: (event, ui) ->
        el.val ui.item.label
        false
      select: (event, ui) ->
        el.val ''
        el.next('.autocomplete.autocomplete-value').val ui.item.value

        url = el.data("new-nested-object-path")
        data = $('.new-nested-group :input, .new-nested-object').serialize()

        $.ajax
          url: url
          data: data
          dataType: 'script'
        false

# # Delete nested item
removeNestedObject = (element, objName) ->
  $("[name='"+objName+"[_destroy]']").val true
  $(element).closest('.removable-nested-object').remove()

$(document).on 'click', 'a.remove-nested-object', ->
  objName = $(this).data('object-name')
  removeNestedObject(this, objName)

# # On load
#
$(document).on 'turbolinks:load', ->

  $('a.add-nested-object').click (e) ->
    e.preventDefault()

    url = @href
    data = $('.new-nested-group :input, .new-nested-object').serialize()

    $.ajax
      url: url
      data: data
      dataType: 'script'

  $('.autocomplete.autocomplete-search').customAutocomplete()

This code generates this error at the transition to the team new page:

Showing
  /Users/nikolaylipovtsev/Documents/Projects/inbox_task/app/views/teams/_form.html.erb
  where line #23 raised:
No route matches {:action=>"search_team_user", :controller=>"teams",
  :id=>#, :locale=>:ru} missing required
  keys: [:id]

What needs to change?

A: The following route means a team with a valid id is required
get :search_team_user, on: :member

In the new team page, @team is created with @team = Team.new so its id attribute is nil. That's exactly what the error says

No route matches {:action=>"search_team_user", :controller=>"teams", :id=>#, :locale=>:ru} missing required keys: [:id]

In TeamsController#search_team_user, I can see that this action doesn't need a team to run correctly. So to fix the problem, you can change your route to
resources :teams do
  get :search_team_user, on: :collection
  get :new_team_user, on: :member
end