text:
Q: Javascript CreateElement(br) I am trying to create a score keeper display.
I want to keep track of the score using html and javascript. I have everything figured out I think but I can't figure out why the line doesn't break here.
Relevant code:
var br = document.createElement("br");
var nes = document.createTextNode("---------");
scorechart.appendChild(br);
scorechart.appendChild(nc);
if(tot) {
    scorechart.appendChild(br);
    scorechart.appendChild(nes);
    scorechart.appendChild(br);
    scorechart.appendChild(tot);
}

(For a full view: https://hastebin.com/osuduluvaj.js)
It breaks for everything but the "------" part: https://media.discordapp.net/attachments/240883852350980096/497957073481629696/sAAAAASUVORK5CYII.png
(I cant upload images yet as a new member)
Thank you :)

A: document.createElement() creates a single element, which you can only append to the DOM once.  If you want to reuse the
 element you created, you need to clone it and you can insert the cloned copy into the DOM.  See: Node.cloneNode().

var score = [];

var scoreadd_button = document.querySelector('#scoreadd-button');
var scoreadd_input = document.querySelector('#scoreadd-input');

let sc1 = 0;
let sc2 = 0;

var scorechart = document.querySelector('.scores');

function totalScores() {
    var i;
    var sum = 0;
    for (i = 0; i < score.length; i++) {
        sum += score[i];
    }
    return sum;
}

function newScore(amm) {
    score.push(amm);
    if (!score[1]) {
        var nc = document.createTextNode(amm)
    } else {
        var nc = document.createTextNode(" + " + amm);
    }

    if (sc1 == 0) {
        sc1 = amm;
    } else {
        sc2 = amm;
    }

    if (sc2 != 0) {
        var tot = document.createTextNode("= " + totalScores());
        sc1 = amm;
        sc2 = 0;
    }

    var br = document.createElement("br");
    var nes = document.createTextNode("---------");
    scorechart.appendChild(nc);
    if (tot) {
        scorechart.appendChild(br.cloneNode(true));
        scorechart.appendChild(nes);
        scorechart.appendChild(br.cloneNode(true));
        scorechart.appendChild(tot);
    }
}

scoreadd_button.addEventListener('click', function() {
    var amm = scoreadd_input.value;
    newScore(parseInt(amm, 10));
});
<button id="scoreadd-button">button</button>
<input type="text" id="scoreadd-input" />

A: Okay so I fixed the issue by instead of using a variable just creating the element in the statement.
var nes = document.createTextNode("---------");
scorechart.appendChild(document.createElement("br"));
scorechart.appendChild(nc);
if(tot) {
    scorechart.appendChild(document.createElement("br"));
    scorechart.appendChild(nes);
    scorechart.appendChild(document.createElement("br"));
    scorechart.appendChild(tot);
}

Thank you :)

A: You just need to defined unique variables for each new created element on javascript, otherwise they will counted as one.
This code should works

var scorechart = document.querySelector('.scores');

    var br = document.createElement("br");
    var br2 = document.createElement("br");
    var nes = document.createTextNode("---------");

        scorechart.appendChild(br);
        scorechart.appendChild(nes);
        scorechart.appendChild(br2);

text before

after text


text:
Q: Can i use an equation as a parameter in python I am making a graph creating program in python and need to pass an equation as a parameter in a function (as needed to create a graph) and in that equation I need some variables that change while the function runs.
Thanks for helping its mutch appreciated.
I have tried to find solutions but I ain't that good so I haven't understand and what som explanation if you can.
#inside a class and this is also simplified.
def function(self, e):
    x = 0
    for i in range(100):
        print(e)
        x += 1

classObj.function(x * 2)

I expect you to be able to add the x variable in the e parameter so i can make it more flexible but that variable is created functions for loop.

A: Argument expressions are evaluated before calling the function.
If you want to pass something dynamic, use a callback function. If the function is simple it can be written as a lambda.
def function(self, f):
    for i in range(100):
        print(f(i))

classObj.function(lambda x: x * 2)

A: I'm not sure if I understood your question correctly, but in Python you can pass a function as a parameter. To describe it we say that function are first-class citizens or that a language supports higher order functions.
Here's example of how you can achieve it:
class YourClass:
    def function(self, e):
        x = 0
        for i in range(100):
            result = e(x)  # you can call a function passed as a parameter
            print(result)  # do something with a result
            x += 1

def multiply_by_2(x):
    return x * 2

def add_2(x):
    return x + 2

obj = YourClass()
obj.function(multiply_by_2)  # just use function name without parenthesis
obj.function(add_2)  # you can also pass different function!

A: Since you haven't defined x, you will get an error thrown when you call classObj.function(). You could pass the equation in as a string and call exec() or eval() on it.
For example:
def function(self, e):
    x = 0
    for i in range(100):
        print(exec(e))
        print(eval(e))# does same thing as above line
        x += 1

classObj.function("x * 2")

The difference between eval() and exec() is that eval() only evaluates one expression, but exec() can run large chunks of code. I recommend using the only what is necessary, so exec() would be overkill.
Maybe see this post on passing expressions to functions, but I'm not sure if that's what you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Paypal Standard (express checkout) After success not return to the site We have two sites in magento
Both site have same paypal account.
but one site is working fine but another not.
Auto return is on in my paypal account
Site1.com is working fine its redirect to site1.com success page after purchasing
site2.com -- After purchasing at site2.com I don't get redirected back to site2.com Thank you for purchasing page. Remains at Paypal page.

A: When request is posted to Paypal in that a return URL should get posted.
Log the form thats posted to Paypal aling with values and check whether it has that return URL or not.


text:
Q: Java console - Remove element from arraylist, still shows up when printing I have an arraylist which I can add to using constructors. That works perfectly fine, and they show up when printing, but when I remove them, it still shows up in the list when printing, even though when I try to remove it for a second time, it says "NullPointerException", or goes to my failsafe else if. The problem therefore have to be in the printing part, or am I thinking completely incorrectly? Is it not updating the arraylist after removing an element?
Thank you.
Instance stuff - Creating Arraylist/constructor(employeeVar = int)
static Employees[] employee = new Employees[employeeVar];
static List<Employees> EmployeesAL = new ArrayList<>(Arrays.asList(employee));

Printing Arraylist
else{
    System.out.println("id: " + EmployeesAL.get(i).getEmployeeID() + "Name: " + EmployeesAL.get(i).getEmployeeName());
}

Removing element
else if (employee[idToRemove].getEmployeeID() == idToRemove && customer[idToRemove].getEmployeeName() != null){
    EmployeesAL.remove(idToRemove);
    employee[idToRemove] = null;
}
}

A: The way you set it up, EmployeesAL and employee are completely unbound. A change in one is not reflected in the other.
So, when you have: [Jane, Joe, Jack] in your employee, that means at first, EmployeesAL is also [Jane, Joe, Jack]. But if you then remove an employee, the effect is that the entry in the array is nulled out, but the entry in the arraylist is removed. So, removing Joe results in employee being [Jane, null, Jack] and EmployeesAL being [Jane, Jack]. Now Jack's position in the array is index 2 (employee[2]) and in the arraylist it's 1: EmployeesAL.get(1). Your code checks employee[idToRemove] and then asks EmployeeAL to remove that index, which, obviously, is going to fail.
Why do you have 2 data structures with the same data? Stop doing that. Pick one: Either have Employee[] employees, or have List<Employee>. You probably want only the latter:
List<Employee> employees = new ArrayList<>();
employees.addAll(Arrays.asList(new Employee("Jane"), new Employee("Joe"), etc);


text:
Q: serial communication with ARDUINO in C++ #include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;

char j='a';
main()
{
fstream arduino;
arduino.open("/dev/ttyACM0",ios::in | ios::out);
//Opening device file

if(!arduino)
cout<<"error";
arduino<<2;
arduino.clear();
if(arduino >> j)
cout << "Value received: " << j << '\n';
else if(arduino.eof())
cerr << "Premature EOF\n";
else if(arduino.bad())
cerr << "Attempt to read from device failed.\n";
else
cerr << "Logical I/O error.\n";
arduino.close();
return 0;
}

arduino code:
      int p;
      void setup()
      {
          pinMode(13,OUTPUT);
          Serial.begin(9600);
       }
   void loop()
   {
       if(Serial.available())
       {
           p=Serial.read();
           if(p!=-1)
           {
               Serial.write(1);
               digitalWrite(13,HIGH);
               delay(5000);
            }
        }
        else
        {
            digitalWrite(13,LOW);
            delay(1000);
        }
    }

i have tried this code in C++ for serial communication with the arduino. i got an error "premature eof". what is  the problem here??

A: Assuming your arduino is actually connected to that port and echoing what it receives, you have to take two things into account:
a) Before your arduino code gets control of the serial port, it first tries to load the serial bootloader, so it is possible for the first bytes of communication to never reach your code.
b) Even if it does, arduino is probably way slower than your computer and it may not have time to process the answer before you do the check.


text:
Q: Android Studio Chipmunk fails to build and run tests in parallel on multiple emulators I just upgraded Android Studio to Chipmunk | 2021.2.1 Patch 1 (detailed version below). When I run tests on one emulator and then try to start tests on another the build fails.
I noticed that building tests for the second emulator gradle is trying to access test-result.pb file in the same folder as already created for the first emulator. Te file is being used, so access is refused, so build fails.
How to solve this and allow AS to run tests in parralel on multiple emulators? (It worked perfectly on up to 7 emulators in previous version, before the upgrade).

Example:
The emulator running first is named "23-xxhdpi-small".
The emulator to receive tests next is named "29-560dpi-big":
You can see the name of the first emulator in the path below.
This is how the error logs:

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:connectedDevDebugAndroidTest'.
java.nio.file.FileSystemException: C:\MyApp\app\build\outputs\androidTest-results\connected\flavors\dev\23-xxhdpi-small(AVD) - 6.0\test-result.pb: The process cannot access the file because it is being used by another process."

AS detailed version:
Android Studio Chipmunk | 2021.2.1 Patch 1
Build #AI-212.5712.43.2112.8609683, built on May 18, 2022
Runtime version: 11.0.12+7-b1504.28-7817840 amd64
VM: OpenJDK 64-Bit Server VM by Oracle Corporation
Windows 10 10.0
GC: G1 Young Generation, G1 Old Generation
Memory: 4096M
Cores: 16
Registry: external.system.auto.import.disabled=true, search.everywhere.settings=true
Non-Bundled Plugins: Lombook Plugin (211.7628.21), org.jetbrains.kotlin (212-1.7.10-release-333-AS5457.46)


text:
Q: Microsoft CRM 4.0 Workflow: How can I email a list of related Entities? I'm building a workflow in Microsoft CRM 4.0 for an Entity E1. In this wf, I have to send an email. In the email, I have to print all entities of E1 that match certain conditions.
For example, it would be great the following mail:

Hi Carl, this is your list of account created until yesterday:

*

*account1, info

*account2, info

*account3, info

Ho can I do it? It seems I can't!

A: You will have to code a custom workflow assembly to create this type of email.

A: Depending on when you need this kicked off there is actually a convoluted way to handle using native workflows. If it will be kicked off when a field on the parent entity changes to a certain value then do this.

*

*On the child entity create a workflow that runs on create and is a child workflow. The first step should be to wait until the relevant field on the parent entity has the correct value.

*Then under the wait condition, send your email

*Finally start the workflow again as a child workflow

*Then end the current workflow.

You can do also sorts of neat hacks if you aren't afraid of waiting workflows


text:
Q: How to create an efficient group by function without mutation? Is there a way to efficiently implement a group by function without mutation?
Naive implementation:

*

*ReScript playground

*JavaScript (see below)

var messages = [
  {insertedAt: "2021-01-10"},
  {insertedAt: "2021-01-12"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-14"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-16"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-18"},
  {insertedAt: "2021-01-18"},
]

var messagesGroupedByDate = messages.reduce(function (data, message) {
  if (
    data.some(function (point) {
      return point.date === message.insertedAt;
    })
  ) {
    return data.map(function (point) {
      if (point.date === message.insertedAt) {
        return {
          date: point.date,
          count: (point.count + 1) | 0,
        };
      } else {
        return point;
      }
    });
  } else {
    return data.concat([
      {
        date: message.insertedAt,
        count: 1,
      },
    ]);
  }
}, []);

console.log(messagesGroupedByDate);

For the sake of argument, there's no need to make this more generic. The problem I'm facing is that I'm looping three times:

*

*once with Array.prototype.reduce which is necessary to loop over messages

*once with Array.prototype.some to see if the date key already exists in the resulting array

*in the case where a date key already exists, we loop again with Array.prototype.map to update a specific element of an array

*otherwise, a new array is returned that contains the new element

If there's not really any good way to make this efficient in ReScript, then I can always use raw JavaScript for this function, but I'm curious if it's possible to do this efficiently without mutation.

A: You can group more simply by building an object of counts by date, and then using Object.entries and Array.map to convert that to an array of objects as required:

var messages = [
  {insertedAt: "2021-01-10"},
  {insertedAt: "2021-01-12"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-14"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-16"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-18"},
  {insertedAt: "2021-01-18"},
];

var messagesGroupedByDate = Object.entries(
  messages.reduce((data, message) => {
    data[message.insertedAt] = data[message.insertedAt] || 0;
    data[message.insertedAt]++;
    return data;
  }, {})
).map(([date, count]) => ({ date, count }));

console.log(messagesGroupedByDate);

You can also create an object directly from the values in messages and then update the counts by looping over messages:

var messages = [
  {insertedAt: "2021-01-10"},
  {insertedAt: "2021-01-12"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-14"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-16"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-18"},
  {insertedAt: "2021-01-18"},
]

const data = Object.fromEntries(messages.map(({ insertedAt: date }) => [ date, 0 ]));

messages.forEach(({ insertedAt: date }) => data[date]++);

const messagesGroupedByDate = Object.entries(data).map(([date, count])=> ({date, count}));

console.log(messagesGroupedByDate);

A: Just add data to a Map() and then convert to array, then to object. It doesn't mutate anything as per your request.
We may simplify this even more but it is 5:00 AM right now and my brain is asleep now.

var messages = [
  {insertedAt: "2021-01-10"},
  {insertedAt: "2021-01-12"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-14"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-16"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-18"},
  {insertedAt: "2021-01-18"},
];

const mapped = new Map();

messages.forEach(message => {
    // if date already seen before, increment the count
    if (mapped.has(message.insertedAt)) {
        const count = mapped.get(message.insertedAt);
        mapped.set(message.insertedAt, count+1);
    } else {
        // date never seen before, add to map with initial count
        mapped.set(message.insertedAt, 1);
    }
});

const msgArr = Array.from(mapped);

const final = msgArr.map(([date, count])=> ({date, count}));

console.log(final);

A: You need a map as an intermediate data structure:
{"2021-01-18": 2, /*…*/}

Then you deconstruct it into pairs and remap the pairs into objects:

const count =
  xs =>
    Object.entries(
      xs.reduce((acc, {insertedAt: k}) =>
        (acc[k] = (acc[k] ?? 0) + 1, acc), {}))
          .map(([k, v]) => ({date: k, count: v}));

// similar to count above but 100% pure
const count_pure =
  xs =>
    Object.entries(
      xs.reduce((acc, {insertedAt: k}) =>
        ({...acc, [k]: (acc[k] ?? 0) + 1}), {}))
          .map(([k, v]) => ({date: k, count: v}));

console.log(count(messages));
console.log(count_pure(messages));
<script>
var messages = [
  {insertedAt: "2021-01-10"},
  {insertedAt: "2021-01-12"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-14"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-16"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-18"},
  {insertedAt: "2021-01-18"},
]
</script>

It is common when doing this to use the spread operator … but depending on how many items you need to process, this may very quickly turn out to be inefficient. See gist I wrote on the subject https://gist.github.com/customcommander/97eb4b3f1600773db59406d39f3f9cd7

A: Though the question is little old, i thought i will share my code for future readers. The below code is written in rescript and completely immutable because I have used Immutable Map from rescript.
type message = {insertedAt: string}

let messages = [
  {insertedAt: "2021-01-10"},
  {insertedAt: "2021-01-12"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-13"},
  {insertedAt: "2021-01-14"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-15"},
  {insertedAt: "2021-01-16"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-17"},
  {insertedAt: "2021-01-18"},
  {insertedAt: "2021-01-18"},
]

// Map Values
// Reduce into an immutable map
// Convert to tuple Array
// Log it

messages
->Belt.Array.reduce(Belt.Map.String.empty, (m, v) =>
  // Here Every set is creating a new map
  m->Belt.Map.String.set(v.insertedAt, m->Belt.Map.String.getWithDefault(v.insertedAt, 0) + 1)
)
->Belt.Map.String.toArray
->Js.log

Run In Rescript Playground. More on Immutable Map in rescript here.
Output:
[ [ '2021-01-10', 1 ],
  [ '2021-01-12', 1 ],
  [ '2021-01-13', 3 ],
  [ '2021-01-14', 1 ],
  [ '2021-01-15', 2 ],
  [ '2021-01-16', 1 ],
  [ '2021-01-17', 3 ],
  [ '2021-01-18', 2 ] ]


text:
Q: Is the fine structure constant a rational number? Since the fine structure constant (denoted alpha) is a pure real number, it just occured to me to ask if it is a rational number or not.

A: The fine structure constant is given as: $$\alpha = \frac {k_{e} e^2} {\hbar c^2}$$
Immediately we have a problem in determining the rationality or otherwise of $\alpha$. The Coloumb constant, Planck constant (maybe not?) and speed of light are all either exact numbers or pre-defined. Since the elementary charge $e$ is an empirically derived constant we can only measure a finite number of digits of this number. This is true for two reasons: First any measurement device will have $\it{some}$ degree of imprecision. Second, the uncertainty principle tells us we cannot measure electron motion+position simultaneously with perfect precision anyway.
Taking this into account we can only know a finite number of significant figures of $\alpha$ and so it must be rational empirically.
As @CuriousOne points out though, this is a rather meaningless concept.

A: As other people have stated, we are currently getting this quantity experimentally, so thus far this is not an appropriate question.
The origin of the value ~1/137 remains unexplained; There is currently no theoretical explanation for why is has the value that is has. In the future, physicists might be able to explain its origin, perhaps by deriving it from other more fundamental constants. Then we would be able to answer your question.
Contrast this with, say, the gyroscopic factor, which characterizes the magnetic moment of quantum particles. There is a theoretical derivation for this dimensionless quantity which can be derived from the theory of quantum electrodynamics.
Someday, we hope, the same will be true of $\alpha$.


text:
Q: Question about the matrix representation of the differentiation map on the subspace generated by $\{1, t, e^{t}, e^{2t}\}$ As mentioned in a previous post (I think), I've been trying to learn some linear algebra, and so I've begun to post little questions whose answers I'm sure are obvious to most here; this is just a way for me to clarify my thinking and reassure myself that I am on the right track/get myself back, as it were, on the right track.
Let $D = \partial /\partial t$ be the differentiation map on the space $V$ of smooth functions $\mathbb{R} \to \mathbb{R}$.  Let $U$ be the subspace generated by the set $\{1, t, e^{t}, e^{2t}\}$.  I am trying to find the matrix associated to $D \big |_U$ (restricting $D$ to $U$) relative to the ordered basis $\{1, t, e^{t}, e^{2t}\}$.  I am pretty sure that this matrix should be
\begin{pmatrix} 0 & 0 & 0 & 0 \\ 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 2 \end{pmatrix}
considering the derivatives of each basis vector.  However, I was wondering if the matrix
\begin{pmatrix} 0 & 0 & 0 & 0 \\ 0 & 1/t & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 2 \end{pmatrix}
might also be an alternative candidate.

A: Your alternative doesn't work because the matrix should not depend on $t$.
At least, as long as you view the function space as a real vector space the matrix elements have to be members of $\mathbb R$. Your $1/t$ is (at best) a function rather than a real number, and therefore does not belong as a matrix element.
If you want to be all fancy about it, you could view your vector space as one over a larger scalar field than $\mathbb R$, for example the field of rational functions in $t$. If you do that, you'll be allowed to write $1/t$ as a matrix element -- but on the other hand your basis is then not a basis anymore, because $1$ and $t$ are linearly dependent when $t$ is just a scalar. And differentiation is then not a linear map anymore, so suddenly no matrix will work to represent it.


text:
Q: Passing post data to other pages in Sinatra This seems to work fine:
views/index.haml:
%form{:method => 'POST' :action => '/'}
  %label{:for => 'name'} Name:
    %input{:type => 'text, :value => @values[:name] || ""}
  %input{:type => 'submit'}

app.rb:
post '/' do
  @values = params
  haml :review
end

views/review.rb
Hello #{params[:name]}!

However, when I try to send my post-data to the same view on a different URL I get an error, or in other words:
app.rb:
post '/' do
  @values = params
  redirect '/review'
end

get '/review' do
  @values = params
  haml :review
end

The data is not going through, but no error is raised.
How do I send the post-data across pages like this? Ideally, I do not want to create a database.

A: You can store the parameters in a session or specify the query string explicitly. Browser Redirect from Sinatra Documentation
As specified in the documentation, you may use sessions or convert the POST params to a query string and use it in the redirect method. A crude example would be:
Say the POST params hash inside the '/' block is:
{
  :name => "Whatever",
  :address => "Wherever"
}

This hash can be made into a string like so:
query = params.map{|key, value| "#{key}=#{value}"}.join("&")
# The "query" string now is: "name=Whatever&address=Wherever"

Now use this inside the post '/' do
redirect to("/review?#{query}")


text:
Q: Transferring data from android to PC via bluetooth Anybody could give a working example of bluetooth server client(from android to Computer),which can transfer files or message from one end to other?I make it using TCP,but i can't successful with bluetooth for last 2 days.
I found some articles from Google,but i can't success with those.From This tutorial i try for myself,but got exception in onResume() that connection failed.
I want to transfer data from my android mobile to my PC running windows 7.At now i work with below code which works good,because from logcat i see the connection is set successfully and read data perfectly,but still it don't transfer data to my computer(may be can't write those data).
So my question is,am i missing something or need such a code for server end?Or can anyone suggest some piece of code that should successfully transfer a message or a file from client android to server PC?
MY code:
Button btnSend = null;
TextView txtPath = null;
Socket s = null;
BluetoothAdapter objBluetoothAdapter = null;
BluetoothDevice device = null;
BluetoothSocket socket = null;
String strPath = "/sdcard/bluetooth/IMG0245A.jpg";
byte [] buffer = null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btnSend = (Button)findViewById(R.id.send_button);
    btnSend.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
        // TODO Auto-generated method stub

        String address="MY_COMPUTER_BLUETOOTH_ADDRESS";

        objBluetoothAdapter =  BluetoothAdapter.getDefaultAdapter();
        if(objBluetoothAdapter==null){
                Toast.makeText(this, "BT not supported", Toast.LENGTH_LONG);
                return;
        }

        //objBluetoothAdapter.enable();

        if(!objBluetoothAdapter.isEnabled()){
                Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivity(enableBT);
        }
        try{
                device = objBluetoothAdapter.getRemoteDevice(address);

                final UUID uuid= UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

                try{
                        File f = new File(strPath);
                        buffer = new byte[(int)f.length()];
                        FileInputStream fis = new FileInputStream(f);
                        BufferedInputStream bis = new BufferedInputStream(fis);
                        bis.read(buffer,0,(int)f.length());

                        socket = device.createRfcommSocketToServiceRecord(uuid);
                        Log.d("BT","RF Connection Created"+socket);
                        //objBluetoothAdapter.startDiscovery();
                        for(int i=0;i<3;i++){
                                try{

                                        objBluetoothAdapter.cancelDiscovery();
                                        socket.connect();
                                        Log.d("BT","Socket Connected = "+socket);

                                        break;
                                }catch (Exception e) {
                                        // TODO: handle exception
                                        Log.d("BT","Socket Connection exception = "+e);
                                }
                        }
                }catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                        Log.d("BT","Connection NOT OK");
                }

                OutputStream os = socket.getOutputStream();
                os.write(buffer);//,0,buffer.length);
                os.flush();
                os.close();
                socket.close();

        } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(this,"exception "+e, Toast.LENGTH_LONG);
        }
}

A: Have you taken a look at the samples provided in the SDK?  If not, you'll find one called "Bluetooth Chat".  It provides the basis for everything you'll need.  I used it some time ago to do what you're trying to do.  Rip out what you don't need and add what you do, and you're off to the races.
I'd provide sample code except I don't have it anymore, sorry.  In any event, you'll find Bluetooth Chat to be a very complete example.


text:
Q: Call Preference from SQLite DB Activity I am developing a dictionary app. I have the following code which show 20 most recent history word.
public List<Bean> getHistoryWords() {

        SQLiteDatabase db = initializer.getReadableDatabase();

        String sql = "SELECT * FROM " + HISTORY_NAME +
                " WHERE " + STATUS + " ORDER BY " + STATUS + " DESC LIMIT 20" ;

        Cursor cursor = db.rawQuery(sql, null);

        List<Bean> wordList = new ArrayList<Bean>();
        while(cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String english = cursor.getString(1);
            String bangla = cursor.getString(2);
            String status = cursor.getString(3);
            wordList.add(new Bean(id, english, bangla, status));
        }

        cursor.close();
        db.close();
        return wordList;
    }

I would like to provide an option for user to change the number of history item from LIMIT 20 to LIMIT 50 or LIMIT 100 through Preferences.
I follow this tutorial, but I was stuck in "5) Saving/reading data". I tried to put the SharedPreferences under getHistoryWords, but I got error cannot resolve getBaseContext.
public List<Bean> getHistoryWords() {
    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

Where should I put the code?

A: There is a simplest way for it.
First, create YourAppName , that extends Application
Declare Context as static and init it on Application 's onCreate method,
public YourApp extends Application {

    private static Context context;

    public void onCreate() {
        super.onCreate();
        YourApp.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return YourApp.context;
    }
}

declare YourApp in Manifest.xml
android:name="com.yourpackagename.app.YourApp" in application tag,
Now, you can get for Context, every where you need like this,
 YourApp.getAppContext()

I hope this will help for you.


text:
Q: How to show all contacts on Skype I enabled a setting that hides my Skype contacts when they are not online. I want to undo this setting - how can I do this on Skype?

A: Under the "Contacts" dropdown menu you can select "Show All Contacts."


text:
Q: UPDATE only provided fields in MySQL table using PHP I have a user table with and id field and 10 other fields storing user details of various types that the user can change via various web forms. I want to have a PHP script that gets POSTed changed values for some subset of these fields, and UPDATEs only those fields that are received in the POST data. I'm finding this surprisingly difficult to do in a way that doesn't suck. We use mysqli for all database interaction in the rest of this application so mysqli-based solutions are strongly preferred.
The options I've considered and dismissed so far:
1) Run a separate UPDATE query for every field provided in the POST data - yuck, I don't want to hit the database up to 10 times for something that could be done in one query.
2) Have a dictionary mapping field names to the fields' data types, and iteratively construct the query by looping through the provided fields, checking whether they are text fields or not, calling mysqli_real_escape_string on the string fields and otherwise sanitizing the others (e.g. by type checking or sprintf with '%i' placeholders). - Yuck! I could probably safely do things this way if I was careful, but I don't want to make a habit of using this kind of approach because if I'm careless I'll leave myself open to SQL injection. Parameterized queries don't give me the potential to screw up dangerously, but this approach does. My ideal is to never concatenate any data into an SQL query manually and always rely upon parameterized queries; the database libraries of other languages, like Python, let me easily do this.
3) Use a parameterized query - this is my ideal for everything, since as long as I insert all externally-provided data into my query via the bind_param method of a mysqli statement object, I'm immune to SQL injection and don't have to worry about sanitization, but using parameterized queries seems to be impossible here. The trouble is that bind_param requires that the data be passed as variables, since all arguments after the first are passed by reference. I can reasonably elegantly iteratively construct a query with ? placeholders, and while I'm at it construct the string of types that gets passed as the first argument to bind_param ('ssiddsi' etc.), but then there's no way I can see to choose at runtime which of my 10 fields I pass to bind_params (unless I have a switch statement with 10^2 cases).
Is there some PHP language construct I'm missing (something similar to array unpacking) that will allow me to choose at runtime which variables to pass as arguments to bind_param? Or is there some other approach I haven't considered that will let me solve this simple problem cleanly and safely?

A: You can easily combine 2 and 3 by means of my SafeMySQL library.
The code will look like
$allowed = array('title','url','body','rating','term','type');
$data    = $db->filterArray($_POST,$allowed);
$sql     = "UPDATE table SET ?u WHERE id=?i";
$db->query($sql, $data, $_POST['id']);

note that $allowed array doesn't make all these fields necessarily updated - it just filters POST fields out. So, even $_POST with only id and url would be correctly updated.
Nevertheless, using prepared statements, although toilsome, also quite possible.

A: See the code below
public function update($data, $table, $where) {
    $data_str = '' ;
    foreach ($data as $column => $value) {
        //append comma each time after first item
        if (!empty($data_str)) $data_str .= ', ' ;
        $data_str .= "$column = $value" ;
    }
    $sql = "UPDATE $table SET $data_str WHERE $where";
    mysqli_query($sql) or die(mysqli_error());
    return true;
}

$data is an array, in your case it's $_POST.
If you want to be more specific about the data to be saved from $_POST array, you can define an array of allowed columns. For example,
$allowed = array('id', 'username', 'email', 'password');

By doing this, you can filter your $_POST array and pass it to update() function.


text:
Q: Zoom and center marker on click in leaflet I have a problem with my leaflet map. I have some markers on my map and when clicking on one, the marker is centered. Now I want when clicking on one marker it is not only centered but I want to zoom in to the marker. When I add this
    map.setZoom((16), {animate: true});

to
    map.on('popupopen', function(centerMarker) {
        var cM = map.project(centerMarker.popup._latlng);
        cM.y -= centerMarker.popup._container.clientHeight/2
        map.setZoom((16), {animate: true});
        map.panTo(map.unproject(cM),{animate: true});
    });

my code the centering doesn't really work because it zooms in but it doesn't center the marker. But all the other markers are centered if I'm in the expected zoom level (16). What can I do that the map zooms to the marker AND the marker is centered as well if I'm outside the zoom level 16? I'm quite new to leaflet and jquery...

A: Instead of using setZoom and panTo, you can use single method setViewwith zoomoption.
map.on('popupopen', function(centerMarker) {
        var cM = map.project(centerMarker.popup._latlng);
        cM.y -= centerMarker.popup._container.clientHeight/2
        map.setView(map.unproject(cM),16, {animate: true});
    });

A: What I did to center the icon popup on my screen was devide the clientHeight by zoom and it centered the popup:
mymap.on('popupopen', function(centerMarker) {
  const zoomLvl = 13;
  let cM = mymap.project(centerMarker.popup._latlng);

  cM.y -= centerMarker.popup._container.clientHeight / zoomLvl
  console.log(mymap.unproject(cM));
  mymap.setView(mymap.unproject(cM), zoomLvl, {animate: true});
});

A: All solutions Apart, here is basic and auto zoom on point solution:
const map = L.map("map", { layers: [osm], minZoom: 13 });
map.setView([latlng[0], latlng[1]], 13);

latlng[0], latlng[1] are points coming from your db object or from REST api.
this will automatically zoom at center of point.


text:
Q: drop down menu and seo "Hidden links and contents are not good for seo". Whether drop down menu affects seo. If yes any perfect solution for drop down menu with seo perspective?

A: drop down menus are not "hidden" in terms of SEO. If the drop down menu is rendered in standard HTML then any bot will be able to "see" it. Now, if you are using Javascript to create your drop down menu, that is a different story - most bots don't currently execute Javascript. From an SEO perspective, you may just want to make sure that the keywords you use in your drop down menu are appropriate for your site and the audience you are targeting. If they are not, then you may want to consider rendering the dropdown in Javascript. Hope this helps

A: I'm assuming you're talking about CSS driven drop down menus? Don't worry, they are SEO friendly and will be treated as normal static links regardless of how they are displayed.
Javascript however hasn't been conclusive whether it is really SEO friendly or not. I've had my experiments and it is really hit or miss so I can't really say for sure.

A: It is best to keep things simple. Search engines still do not read JavaScript very well. If your site navigation is based on JavaScript, it will be difficult to get all of your pages indexed. If the decorative drops down type menus are important to you, always provide a back up of plain text links. I suggest you should make a site map for google crawler bot.

A: Look at your page source. If your drop down menu is standard HTML with the links specified by <a href="..."> tags, then it's fine.
Google may not find the links if you use Javascript to generate the menu/links. Same goes if you use a <select> element, which I've seen a lot.

A: It is a known issue for the Google bot to potentially confuse drop down menus with hidden links - particularly if the code is something like:
< div id="menu1" style="visibility: hidden;">< a href="">Home< /a >< /div>

Its an AI complete problem to detect if that kind of code is designed to trick or not, so there will always be occasional issues.
However, any popular menu is likely to be ok as someone else would have filed a reconsideration request if there was a noticeable issue. Also remember that there are many trust factors, so the effect may be subtle.


text:
Q: How to calculate the exponential ratio between a few numbers? If I go onto Wolfram alpha and type 2 **x == 56 I see that x is around 5.8. What is a formula I can use to find the exact number (given use of a calculator)?
For example I have the following two times which are runtimes of a computation:
a = 0.005689493999852857
b = 151.89659522200054

I want to find the value of x such that a^x = b
So tried log a (b) which gave me -0.9717681977154843
My hunch is that since a is less than one, it needs to be given a negative exponent. However I'm not sure how to use this negative value, as opposed to a positive one. Should I just add one to both a and b before doing the logarithm, to ensure it's a positive exponent?

A: If
$$
2^x = 56
$$
then
$$
x = \log_2 (56).
$$
Your calculator probably has a $\log$ key, but that will give you the base $10$ logarithm.
You can look up the formula for changing the base of a logarithm. (Search for
log change base does the job.)

A: Taking logarithms of both sides will convert this to a linear equation which is easily solved:
$$2^x=56$$
$$\log(2^x)= \log 56 \tag{take $\log$ of both sides}$$
$$x\log 2 = \log 56\tag{property of logarithms}$$
$$x=\frac{\log 56}{\log 2}\tag{solve linear equation}$$
This works for any base of the logarithm. Calculators typically have $\log_{10}$ or $\log_e$ (often denoted "LOG" and "LN", respectively). Using the latter, I get the approximation
$$x \approx \frac{4.02434}{0.69315}\approx \boxed{5.80735}$$
The property of logarithms we used in the third line was $\log a^b=b\log a$.


text:
Q: Taking Log to find MAXIMIZE summation of variables I have been reading IEEE papers on communication and in several papers the authors formed objective function like:
$\text{Maximize }    \sum_k \log r_k $
to maximize the total rate of the system of $k$ users. Here $r_k$ is the rate of the $k$'th user. Now I cant understand how taking logarithm is relevant with maximizing. This is a common case in 'Entropy Maximization'. Is there any general mathematical explanation of this? Any explanation is highly appreciated.

A: Maximizing a sum of logs over a convex set is called achieving proportional fairness. This is a standard goal in communication networks.  Here, $r_k$ is the communication rate achieved by user $k$.  Each user wants to maximize its own rate.  However, there are shared resources.  Let $\Lambda$ be the (typically convex) set of all possible rate vectors $(r_1, r_2, \ldots, r_K)$ that the system can support.  We want to find a Pareto optimal point.  Maximizing a sum of increasing and concave utility functions is used because concave functions have a diminishing returns property, which says that we would prefer to make allocations relatively even (pushing up those who have lower rate).
The log function is analyzed in particular in:
Frank Kelly, "Charging and Rate Control for Elastic Traffic," European Transactions on Telecommunications, vol. 8, no. 1 pp. 33-37, Jan.-Feb. 1997.
If $\Lambda$ is a convex set, it can be shown that finding a vector $r^*=(r_1^*, \ldots, r_K^*)$ that maximizes $\sum_{k=1}^K \log(r_k)$ subject to $(r_1, \ldots, r_K) \in \Lambda$ means that:
$$ \sum_{k=1}^K\frac{r_k-r_k^*}{r_k^*} \leq 0 $$
for all vectors $(r_1, \ldots, r_K) \in \Lambda$.  This can be interpreted as the "proportionally fair" criterion:  Consider changing from the $r^*$ vector to some other vector $r \in \Lambda$. You might be able to increase rates of particular users by deviating from  $r^*$, but the overall proportional change is never positive, where this change weights users with currently low rates $r_k^*$ more heavily, which is a fairness feature.

Example 1: A simple example is when the set $\Lambda$ is the set of all nonnegative rates that sum to less than or equal to 1.  Then one solution to maximizing the linear function $\sum_k {r_k}$ over $r \in \Lambda$ is $(1, 0, 0, ..., 0)$, which is clearly unfair since it gives one user everything.  Howevever, maximizing the strictly concave function $\sum_k \log(r_k)$ over the same set $\Lambda$ gives the (much more fair) solution $r^*=(1/K, 1/K, ..., 1/K)$.
Example 2:  Suppose $\Lambda$ is the set of all $(r_1, ..., r_K) \geq 0$ such that $r_1/2 + \sum_{k=2}^K r_k \leq 1$.  Maximizing the linear utility function $\sum_k r_k$ over $\Lambda$ gives the (unfair, and unique)  solution $(2, 0, 0, ..., 0)$.  Yet, maximizing the $\sum_k \log(r_k)$ over the same set gives the (more fair, in fact, "proportionally fair") solution: $(\frac{2}{K},  \frac{1-1/K}{K-1}, ..., \frac{1-1/K}{K-1})$.


text:
Q: How can you adjust the height of a jQuery UI accordion? In my UI I have an accordion setup like this:

Section 1

...content...

    // More sections

The accordion works properly when it is first formed, and it seems to adjust itself well for the content inside each of the sections.  However, if I then add more content into the accordion after the .accordion() call (via ajax), the inner  for the section ends up overflowing.
Since the accordion is being formed with almost no content, all the inner divs are extremely small, and thus the content overflows and you get accordions with scrollbars inside with almost no viewing area.
I have attempted to add min-height styles to the object_list div, and the content divs to no avail.  Adding the min-height to the inner divs kind of worked, but it messed up the accordion's animations, and adding it to the object_list div did absolutely nothing.
How can I get a reasonable size out of the content sections even when there is not enough content to fill those sections?

A: autoHeight was deprecated in 1.9, and removed in 1.10.
Use:
$('#id').accordion({heightStyle: 'content'});

to auto size your inner div.
UPDATE:
I see that this is still quite an active post, so I decided to make sure my answer is still valid. It looks like this may no longer work in jQuery UI 1.11. It notes that the [content] property has been deprecated, and to use [panel] instead. Making the code snippet now look something more like this:
$('#id').accordion({heightStyle: 'panel'});

I HAVE NOT YET TESTED THIS, JUST FOUND, AND WILL RETURN AND REMOVE THIS COMMENT WHEN I HAVE TIME TO TEST

A: Setting the DIV's height will do the trick.
$(document).ready(function() {

    $("#accordion").show().accordion({
        autoHeight: false
    });

    $("#accordion div").css({ 'height': 'auto' });
});

A: When you declare the accordion control div, you can put a height in the style tag for the div.  Then you can set the fillSpace: true property to force the accordion control to fill that div space no matter what.  This means you can set the height to whatever works best for you page.  You could then change the height of the div when you add your code
If you want the accordion to dynamically resize to the content it contains as needed you can do the following trick posted on the jQuery UI website.
//getter
var autoHeight = $( ".selector" ).accordion( "option", "autoHeight" );
//setter
$( ".selector" ).accordion( "option", "autoHeight", false );

This means when you select an area with a lot of text, the accordion will recalculate it.

A: Use heightStyle option to control the height of the accordion and each panel.
$("#accordion").accordion({
  heightStyle: "content"
});

Possible values:

*

*"auto": All panels will be set to the height of the tallest panel.

*"fill": Expand to the available height based on the accordion's parent height.

*"content": Each panel will be only as tall as its content.

A: Turning off auto will work... (with any string besides auto or fill) such as the solution telling to use "panel". But...
That is the same as putting in any garbage string for "heightStyle".  The "heightStyle" you are looking for is "content".

*

*http://api.jqueryui.com/accordion/#option-heightStyle

*https://github.com/jquery/jquery-ui/blob/master/tests/unit/accordion/options.js

*https://github.com/jquery/jquery-ui/blob/master/ui/widgets/accordion.js
(values for option "heightStyle" in jQuery UI 1.12)

*

*"auto": All panels will be set to the height of the tallest panel.

*"fill": Expand to the available height based on the accordion's parent height.

*"content": Each panel will be only as tall as its content.
Example:
https://jsfiddle.net/qkxyodpq/5/
Hope that helps.

A: From the docs it sounds like you'll need to set
clearStyle: true

...and also
autoHeight: false

I believe that using clearStyle allows you to dynamically add content without Accordion getting in the way.
So try this...
$( ".selector" ).accordion({ clearStyle: true, autoHeight: false });

A: It looks like all the answers here are now using deprecated options.
With the latest version of jQuery UI (1.10.x), you should initialize your accordion with heightStyle: "fill" to get the intended effect..
$(".selector").accordion({ heightStyle: "fill" });

You can read more at the jQuery UI API docs here: http://api.jqueryui.com/accordion/#option-heightStyle
If your page dimensions change dynamically and you need to recalculate your accordion size, you should refresh your accordion using the refresh method:
$(".selector").accordion("refresh");

This is preferred as the resize method is now deprecated.

A: for me doing following worked accurately.
$( "#accordion" ).accordion({
    autoHeight: false,

});

A: In your jquery-ui.js search for the following section and change heightstyle: "auto" to heightstyle: "content" so the updated file will look like this.
var accordion = $.widget( "ui.accordion", {
  version: "1.11.4",
  options: {
    active: 0,
    animate: {},
    collapsible: false,
    event: "click",
    header: "> li > :first-child,> :not(li):even",
    heightStyle: "content",
    icons: {
        activeHeader: "ui-icon-triangle-1-s",
        header: "ui-icon-triangle-1-e"
    },

    // callbacks
    activate: null,
    beforeActivate: null
},

A: Just call the accordions .resize() method, this will recalculate its size.
http://docs.jquery.com/UI/Accordion#method-resize

A: I recently set up an accordion that retrieves content via ajax when a tab is activated and ran into the same problem.  I tried using some of the suggestions posted here, but they never quite grew the panel correctly until I set the heightStyle to content.
$("#myaccordion").accordion({
  heightStyle: "content",
  activate: function(event ui) {
    //use ajax to retrieve content here.
  }
});

I'm using jQuery-UI version 1.10.4.


text:
Q: Check if list contains any dict keys d = {('shot',): ['V'], ('I',): ['NP']}
s = ["I", "shot"]
s1 = ["I"]
s2 = ["shot"]

print(str(tuple(s,)))
print([i in d for i in tuple(s,)])
print(bool(set(tuple(s,)).intersection(d)))
print(d[tuple(s1,)])
print(d[tuple(s2,)])
for i in set(tuple(s,)).intersection(d):
    print("Element "+i+" was found.")

Suppose I have a dict like aforementioned with each key being a tuple. Why is this the result:
('I', 'shot')
[False, False]
False
['NP']
['V']

Instead of this:
('I', 'shot')
[True, True]
True
['NP']
['V']

A: Neither I or shot are keys in d, so both will be False. When you're creating the tuple from the list, each value in the list is used to create the tuple:
>>> tuple(["I", "shot"], )
('I', 'shot')

So when you're iterating over that list in your list comprehension:
[i in d for i in tuple(s,)]

What you're effectively doing is:
for i in ('I', 'shot'):
  if i in d:  # this will be 'I' in the first iteration, 'shot' in the next
      ...

Since neither of I or shot by themselves are keys, the result is False. The keys actually used in your dictionary are tuples, not strings (which is what you end up looking for).
However, what you might have wanted to achieve instead (since the tuple(s, ) conversion doesn't do anything useful), is to look up a tuple with the string as the first element in the dictionary instead of iterating over it:
>>> [(i, ) in d for i in s]
[True, True]

To sum it up:
>>> 'I' in d
False
>>> 'shot' in d
False
>>> ('shot', ) in d
True
>>> ('I', ) in d
True

The last two examples create a tuple and then checks if that tuple is a key in the dictionary.
The same confusion about the keys and their values might also be the cause for your issue with set, but you'd want to be more explicit there - use d.keys() if you want an iterator that only gives you the keys in the dictionary and then intersect the two sets as you find necessary to achieve what you want.


text:
Q: directory for portable app (Fiji) I downloaded the .zip of Fiji from its web, and then I extracted the files to my $HOME directory. I can run it correctly when running the executable file. However, I think that this is not a well suited directory, and I would like to know where would be the best place to move it.
I read in some posts that portable apps may be installed at /opt, but I am not sure that it would be my case.

A: I don't believe there is an objectively chosen place to put portable apps. They are portable, after all.
The best thing to do with any portable app is to move it and its files into a directory and put that directory somewhere you know it won't be accidentally deleted. Definitely do not keep it in Downloads, especially if you regularly delete items from there.
If you want it to be easily accessible, put the folder containing the app on your desktop. It probably won't be accidentally deleted, and it'll be right there to click on. You can even make a link to the executable if you want even more convenience. You could also put the folder in your documents.
As far as I know, Ubuntu doesn't have designated space for portable apps. Just put them where they won't be removed.


text:
Q: How to add a color picker to React Quill toolbar I want to use react-quill for my react rich text editor but I couldn't find a way to add a color picker in the toolbar.
I'm also using typescript.
here is my component:
const modules = {
  toolbar: [
    [{ font: ['', 'times-new-roman', 'arial'] }],
    [{ header: [1, 2, 3, false] }],
    ['bold', 'italic', 'underline', 'strike', 'blockquote'],
    [{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
    ['link'],
    ['clean']

  ],
}
function RichTextEditor() {
  return <ReactQuill theme="snow" modules={modules} formats={formats} preserveWhitespace />
}

A: You can use custom toolbar with javascript like this, it might works!

var quill = new Quill('#editor-container', {
  modules: {
    toolbar: [
      [{
        header: [1, 2, false]
      }],
      ['bold', 'italic', 'underline'],
      ['image', 'code-block'],
      [{
        'color': ['#F00', '#0F0', '#00F', '#000', '#FFF', 'color-picker']
      }]
    ]
  },
  placeholder: 'Compose an epic...',
  theme: 'snow' // or 'bubble'
});

function showColorPicker(value) {
  if (value === 'color-picker') {
    var picker = document.getElementById('color-picker');
    if (!picker) {
      picker = document.createElement('input');
      picker.id = 'color-picker';
      picker.type = 'color';
      picker.style.display = 'none';
      picker.value = '#FF0000';
      document.body.appendChild(picker);

      picker.addEventListener('change', function() {
        quill.format('color', picker.value);
      }, false);
    }
    picker.click();
  } else {
    quill.format('color', value);
  }
}

var toolbar = quill.getModule('toolbar');
toolbar.addHandler('color', showColorPicker);
#editor-container {
  height: 375px;
}

.ql-color .ql-picker-options [data-value=color-picker]:before {
  content: 'Pick Color';
}

.ql-color .ql-picker-options [data-value=color-picker] {
  background: none !important;
  width: 100% !important;
  height: 25px !important;
  text-align: center;
  color: blue;
  text-decoration: underline;
}
<script src="//cdn.quilljs.com/1.3.6/quill.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<link href="//cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet" />
<link href="//cdn.quilljs.com/1.3.6/quill.bubble.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/monokai-sublime.min.css" rel="stylesheet" />
<div id="editor-container">
</div>

This is an example with javascript, you can convert into typescript if you want.
Thank you.


text:
Q: Uniform convergence - is this too easy? Let $f_n:\mathbb{R} \rightarrow \mathbb{R}$ converge uniformly to $f$  with $f$ is uniformly continous. Show that $f_n(x+a_n)$ converges uniformly to $f$ where $a_n \rightarrow 0$ for $n \rightarrow \infty$.
So whats the point here? I think the problem is solved just with $\lim_{n \rightarrow \infty} f_n(x+a_n) = f(x+\lim_{n \rightarrow \infty }a_n) = f(x)$ ??
This is actually a homework so I guess it cant be that easy. Is there something wrong?

A: Yes, there's something wrong. What you did would prove, at most, that $(f_n)_{n\in\mathbb N}$ converges pointwise to $f$.
Let $\varepsilon>0$. Take $\delta>0$ such that $|x-y|<\delta\implies\bigl|f(x)-f(y)\bigr|<\varepsilon$. Take $p\in\mathbb N$ such that $n\geqslant p\implies|a_n|<\delta$. Then $\bigl|(x+a_n)-x\bigr|<\delta$ (for each real $x$). So $\bigl|f(x+a_n)-f(x)\bigr|<\varepsilon$. In other words, $\bigl|f_n(x)-f(x)\bigr|<\varepsilon$.

A: No, your proof idea has problems. Where did you use uniform converge and uniform continuity?
Here's a hint for a proof:
$$|f_n(x+a_n)-f(x)| \le |f_n(x+a_n)-f(x+a_n)| + |f(x+a_n)-f(x)|.$$


text:
Q: Closedness of the subset $AcB$ when $AB$ is closed in a topological group Let $G$ be a topological group and $A,B$ be two subgroups of $G$ such that $AB$ is a closed subset. I wonder if for any element $c\in G$, the subset $AcB$ is always closed?
In the original question I was thinking about, there is either a $T_1$ condition on $G$ or better, $G$ is locally compact Hausdorff. So please feel free to add such mild conditions if the above assertion fails.

A: The set $AcB$ can be non-closed. For instance, let $G$ be a Cartesian product of topological spaces  $\Bbb R$ and $\Bbb Z$ endowed with a specific operation of a semidirect product $(x,n)(y,m)=(x+n\sqrt{2}y, m+n)$. It is easy to check that $G$ is a topological group. Now if we put $A=B=\Bbb Z\times \{0\}$ and $c=(0,1)$, we obtain that $c^{-1}AcB=(\Bbb Z+\sqrt{2}\Bbb Z)\times \{0\}$ is a non-closed subgroup of $G$.


text:
Q: One file for all virtual, downloadable product variations Does any know if it is possible to have one file download for all variations of a product? OR a better way to setup what I need to achieve?!
To explain, I've built a type foundry site for a client and they have multiple weights and license combinations, but they effect only the price rather than what is downloaded.
I've used attributes & variations to map this out, but am wondering if there is a simpler way, as there's currently 48 variations for each weight. Obviously this poses an administration and maintenance nightmare, considering they all require the same file! I was considering programmatically adding the file reference, but again this isn't plausible going forward.

Whilst I'm a competent freelance developer of 10 years, I rarely, if ever, go near the configuration of eCommerce sites!
Thanks in advance,
Tom


text:
Q: Sql substring function with variable length parametres I got next error message:
SQL Error [500310] [42725]: [Amazon](500310) Invalid operation: function pg_catalog.substring(character varying, smallint, smallint) is not unique;

when trying execute query:
select SUBSTRING(a.string,b.index,b.length)
  from a
  JOIN
  b
  ON a.id=b.id

A: That is odd and i think you have found a bug! its not happy with smallint.
But you can get around it easily like this
select SUBSTRING(a.string,b.index::integer,b.length::integer)
  from a
  JOIN
  b
  ON a.id=b.id


text:
Q: Firebase Authentication - UpdateEmail - Don't Send Confirmation Email If I don't want to send any email verification/confirmation, after I update and Email address, how can I accomplished that?
After I call this:
Auth.auth().currentUser?.updateEmail(to: emailTextField.text!, completion: { (error) in

                    if error != nil {

                        print("Firebase Change Email Error: \(String(describing: error))")

                    } else {

                        print("Firebase Change Email Successful")

                    }

                })

An automatically email is sent, but I don't want it.
Thanks
CR

A: This is highly not recommended and a bad idea, This email is sent for security reasons. If an account is hijacked and the email changed. The owner of the account will not have the ability to recover their account.
That said, the only way around it is to use the Admin SDK updateUser API: https://firebase.google.com/docs/auth/admin/manage-users#update_a_user
admin.auth().updateUser(uid, {
  email: "modifiedUser@example.com",
})
.then(function(userRecord) {
  // Email changed.
})
.catch(function(error) {
  console.log("Error updating user:", error);
});


text:
Q: Display a different side-nav on a different page using materialize css I am making a simple page where I wanted to display different side-nav class when going to another page. I am using materialize css and I made a custom css to override the side-nav class now I wanted to display the normal side-nav when going to another page. Is there a better way to do it? I need some advice from you guys and that would be a big help.
Example HTML:

Login

Register

        User

        Search

    menu

CSS:
.side-nav {
 background-color: #27AEEB;
 color: #ffffff;
 margin-top: 75px;
 margin-left: 8px;
 height: 47%;
 overflow: hidden;
}

A: If by normal side-nav you mean to load the default side-nav, then you may have all your side-nav specific CSS in an altogether different class, rather than the .side-nav class which you are currently using. You can have a, let's say a .custom-side-nav class, meaning your ul tag having .side-nav class should look like
. And your CSS should look like:
.custom-side-nav {
    background-color: #27AEEB;
    color: #ffffff;
    margin-top: 75px;
    margin-left: 8px;
    height: 47%;
    overflow: hidden;
}

Then, whenever you navigate to another page you can get back your so-called 'normal' side-nav using jQuery by removing the .custom-side-nav class from your side-nav. You can do it using .removeClass() method, like $("#nav-mobile").removeClass("custom-side-nav"). This way, you can later have your custom CSS applied again on your side-nav if you visit this page again simply by having a $("#nav-mobile").addClass("custom-side-nav").
Let me know if I misinterpreted your question, in which case you may have to put some more light on what you exactly desire to achieve so that we can all work on a concrete solution.


text:
Q: Intuition for higher moments in circular statistics In circular statistics, the expectation value of a random variable $Z$ with values on the circle $S$ is defined as
$$
m_1(Z)=\int_S z P^Z(\theta)\textrm{d}\theta
$$
(see wikipedia).
This is a very natural definition, as is the definition of the variance
$$
\mathrm{Var}(Z)=1-|m_1(Z)|.
$$
So we didn't need a second moment in order to define the variance!
Nonetheless, we define the higher moments
$$
m_n(Z)=\int_S z^n P^Z(\theta)\textrm{d}\theta.
$$
I admit that this looks rather natural as well at first sight, and very similar to the definition in linear statistics. But still I feel a little bit uncomfortable, and have the following
Questions:
1.
What is measured by the higher moments defined above (intuitively)? Which properties of the distribution can be characterized by their moments?
2.
In the computation of the higher moments we use multiplication of complex numbers, although we think of the values of our random variables merely as vectors in the  plane or as angles. I know that complex multiplication is essentially addition of angles in this case, but still:
Why is complex multiplication a meaningful operation for circular data?

A: The moments are the Fourier coefficients of the probability measure $P^Z$.  Suppose (for the sake of intuition) that $Z$ has a density.  Then the argument (angle from $1$ in the complex plane) of $Z$ has a density on $[0,2\pi)$, and the moments are the coefficients when that density is expanded in a Fourier series.  Thus the usual intuition about Fourier series applies -- these measure the strengths of frequencies in that density.
As for your second question, I think you already gave the answer: "complex multiplication is essentially addition of angles in this case".


text:
Q: Why is NSFileManager unable to find these png files? I have written code to open image files after studying answers to the questions found here (a, b, c, d, e, f & g). But NSFileManager is unable to find them even though I added the png files to the project. I'm reasonably confident my code should be able to recognise either of the png files if they were in the right directory.
e.g.

- (void)viewDidLoad {
    [super viewDidLoad];

    NSFileManager *fileManager = [[NSFileManager alloc] init];

    NSArray  *dirPaths;
    NSString *docsDir;

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    NSLog(@"\ndirPaths %@ \n\ndocsDir \n%@", dirPaths, docsDir);

    NSString *imageFilePath = [docsDir stringByAppendingPathComponent:@"iTunesArtwork1024.png"];

    NSLog(@"\n\nfile path should be \n\n%@ \n\n", imageFilePath);

    NSData *imageData = [NSData dataWithContentsOfFile:imageFilePath];

    if ([fileManager fileExistsAtPath:imageFilePath])

    {
        NSLog(@"\nFound file path : %@", imageFilePath);
    }

    else

    {
        NSLog(@"\nImage file not found");
    }

    UIImage  *image = [UIImage imageWithData:imageData];

    UIImageView *logo = [[UIImageView alloc] init];
    logo.image = image;
    [self.view addSubview:logo];

}

But here is the log in the debug window
    2017-07-14 18:26:35.679 IconShape[1089:348564]
    dirPaths (
    "/Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents"
    )

    docsDir
    /Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents
    2017-07-14 18:26:35.679 IconShape[1089:348564]

    file path should be

    /Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents/iTunesArtwork1024.png

    2017-07-14 18:26:35.679 IconShape[1089:348564]
    Image file not found

Here is the state of the project after two png files were added.

Yet the log shows they are not visible to NSFileManager. So where would they be found ? i.e. what changes do I need to make to my code in order to find them ?

EDIT
This draft finds the png file following Subramanian's recommendation.
    - (void)viewDidLoad {
    [super viewDidLoad];

    NSFileManager *fileManager  = [[NSFileManager alloc] init];

    NSString *imageFilePath     = [[NSBundle mainBundle]pathForResource:@"iTunesArtwork1024" ofType:@"png"];

    if ([fileManager fileExistsAtPath:imageFilePath])

    {
        NSLog(@"\nFound file path : %@", imageFilePath);
    }

    else

    {
        NSLog(@"\nImage file not found");
    }

    UIImage  *image     = [UIImage imageNamed:@"iTunesArtwork1024.png"];
    UIImageView *logo   = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];
    logo.image          = image;
    [self.view addSubview:logo];
}

The log now reads
     Found file path :  … .app/iTunesArtwork1024.png

and the image also appears in the subview.
__

A: Image is not in theDocument Directory, It's inside the bundle.
You have added the image files inside the project. But You are checking the image on Document Directory, Which is wrong. Image is inside app bundle.
You can simply assign the Image to UIImageView by the name of the image.
UIImage  *image = [UIImage imageNamed:@"iTunesArtwork1024.png"];

UIImageView *logo = [[UIImageView alloc] init];
logo.image = image;

If you want to get the path of the image, then you have to use [NSBundle mainBundle]
[[NSBundle mainBundle]pathForResource:@"iTunesArtwork1024" ofType:@"png"];

A: You can access images with names which are added in projects. Try with below code
 UIImage  *image = [UIImage imageNamed:@"iTunesArtwork1024.png"];

A: The path where your are looking for the image is inside your device (real or simulator).
To load an image that is stored in your XCode project just do:
UIImage* image = [UIImage imageNamed:@"iTunesArtwork1024.png"];


text:
Q: I want to reload the same page when add button is clicked in flutter I am creating a page where i can add the category details and after clicking the plus button i want to add the category into a list and should reload the same page again how to do that using a floating action button?
FloatingActionButton(
      onPressed: () => {
        AddNewItemNext(),

      },
      tooltip: 'Increment',
      child: Icon(Icons.add),
    ),

A: You should use a StatefulWidget and setState.
Here you append the new data to the list.
FloatingActionButton(
      onPressed: () => {
        setState(() {
          list.add(data);
        });
      },
      tooltip: 'Increment',
      child: Icon(Icons.add),
    ),


text:
Q: Matching a "text" in line by line file with XText I try to write the Xtext BNF for Configuration files (known with the .ini extension)
For instance, I'd like to successfully parse
[Section1]
a = Easy123
b = This *is* valid too

[Section_2]
c = Voilà # inline comments are ignored

My problem is matching the property value (what's on the right of the '=').
My current grammar works if the property matches the ID terminal (eg a = Easy123).
PropertyFile hidden(SL_COMMENT, WS):
    sections+=Section*;

Section:
    '[' name=ID ']'
    (NEWLINE properties+=Property)+
    NEWLINE+;

Property:
    name=ID (':' | '=') value=ID ';'?;

terminal WS:
    (' ' | '\t')+;

terminal NEWLINE:
// New line on DOS or Unix
    '\r'? '\n';

terminal ID:
    ('A'..'Z' | 'a'..'z') ('A'..'Z' | 'a'..'z' | '_' | '-' | '0'..'9')*;

terminal SL_COMMENT:
// Single line comment
    '#' !('\n' | '\r')*;

I don't know how to generalize the grammar to match any text (eg c = Voilà).
I certainly need to introduce a new terminal
    Property:
        name=ID (':' | '=') value=TEXT ';'?;
Question is: how should I define this TEXT terminal?
I have tried

*

*terminal TEXT: ANY_OTHER+;
This raises a warning

The following token definitions can never be matched because prior tokens match the same input: RULE_INT,RULE_STRING,RULE_ML_COMMENT,RULE_ANY_OTHER

(I think it doesn't matter).
Parsing Fails with

Required loop (...)+ did not match anything at input 'à'

*terminal TEXT: !('\r'|'\n'|'#')+;
This raises a warning

The following token definitions can never be matched because prior tokens match the same input: RULE_INT

(I think it doesn't matter).
Parsing Fails with

Missing EOF at [Section1]

*terminal TEXT: ('!'|'$'..'~'); (which covers most characters, except # and ")
No warning during the generation of the lexer/parser.
However Parsing Fails with

Mismatch input 'Easy123' expecting RULE_TEXT
Extraneous input 'This'  expecting RULE_TEXT
Required loop (...)+  did not match anything at 'is'

Thanks for your help (and I hope this grammar can be useful for others too)

A: This grammar does the trick:
grammar org.xtext.example.mydsl.MyDsl hidden(SL_COMMENT, WS)

generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"
import "http://www.eclipse.org/emf/2002/Ecore"

PropertyFile:
    sections+=Section*;

Section:
    '[' name=ID ']'
    (NEWLINE+ properties+=Property)+
    NEWLINE+;

Property:
    name=ID value=PROPERTY_VALUE;

terminal PROPERTY_VALUE: (':' | '=') !('\n' | '\r')*;

terminal WS:
    (' ' | '\t')+;

terminal NEWLINE:
// New line on DOS or Unix
    '\r'? '\n';

terminal ID:
    ('A'..'Z' | 'a'..'z') ('A'..'Z' | 'a'..'z' | '_' | '-' | '0'..'9')*;

terminal SL_COMMENT:
// Single line comment
    '#' !('\n' | '\r')*;

Key is, that you do not try to cover the complete semantics only in the grammar but take other services into account, too. The terminal rule PROPERTY_VALUE consumes the complete value including leading assignment and optional trailing semicolon.
Now just register a value converter service for that language and take care of the insignificant parts of the input, there:
import org.eclipse.xtext.conversion.IValueConverter;
import org.eclipse.xtext.conversion.ValueConverter;
import org.eclipse.xtext.conversion.ValueConverterException;
import org.eclipse.xtext.conversion.impl.AbstractDeclarativeValueConverterService;
import org.eclipse.xtext.conversion.impl.AbstractIDValueConverter;
import org.eclipse.xtext.conversion.impl.AbstractLexerBasedConverter;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.util.Strings;

import com.google.inject.Inject;

public class PropertyConverters extends AbstractDeclarativeValueConverterService {
    @Inject
    private AbstractIDValueConverter idValueConverter;

    @ValueConverter(rule = "ID")
    public IValueConverter<String> ID() {
        return idValueConverter;
    }

    @Inject
    private PropertyValueConverter propertyValueConverter;

    @ValueConverter(rule = "PROPERTY_VALUE")
    public IValueConverter<String> PropertyValue() {
        return propertyValueConverter;
    }

    public static class PropertyValueConverter extends AbstractLexerBasedConverter<String> {

        @Override
        protected String toEscapedString(String value) {
            return " = " + Strings.convertToJavaString(value, false);
        }

        public String toValue(String string, INode node) {
            if (string == null)
                return null;
            try {
                String value = string.substring(1).trim();
                if (value.endsWith(";")) {
                    value = value.substring(0, value.length() - 1);
                }
                return value;
            } catch (IllegalArgumentException e) {
                throw new ValueConverterException(e.getMessage(), node, e);
            }
        }
    }
}

The follow test case will succeed, after you registered the service in the runtime module like this:
@Override
public Class<? extends IValueConverterService> bindIValueConverterService() {
    return PropertyConverters.class;
}

Test case:
import org.junit.runner.RunWith
import org.eclipse.xtext.junit4.XtextRunner
import org.xtext.example.mydsl.MyDslInjectorProvider
import org.eclipse.xtext.junit4.InjectWith
import org.junit.Test
import org.eclipse.xtext.junit4.util.ParseHelper
import com.google.inject.Inject
import org.xtext.example.mydsl.myDsl.PropertyFile
import static org.junit.Assert.*

@RunWith(typeof(XtextRunner))
@InjectWith(typeof(MyDslInjectorProvider))
class ParserTest {

    @Inject
    ParseHelper<PropertyFile> helper

    @Test
    def void testSample() {
        val file = helper.parse('''
            [Section1]
            a = Easy123
            b : This *is* valid too;

            [Section_2]
            # comment
            c = Voilà # inline comments are ignored
        ''')
        assertEquals(2, file.sections.size)
        val section1 = file.sections.head
        assertEquals(2, section1.properties.size)
        assertEquals("a", section1.properties.head.name)
        assertEquals("Easy123", section1.properties.head.value)
        assertEquals("b", section1.properties.last.name)
        assertEquals("This *is* valid too", section1.properties.last.value)

        val section2 = file.sections.last
        assertEquals(1, section2.properties.size)
        assertEquals("Voilà # inline comments are ignored", section2.properties.head.value)
    }

}

A: The problem (or one problem anyway) with parsing a format like that is that, since the text part may contain = characters, a line like foo = bar will be interpreted as a single TEXT token, not an ID, followed by a '=', followed by a TEXT. I can see no way to avoid that without disallowing (or requiring escaping of) = characters in the text part.
If that is not an option, I think, the only solution would be to make a token type LINE that matches an entire line and then take that apart yourself. You'd do that by removing TEXT and ID from your grammar and replacing them with a token type LINE that matches everything up to the next line break or comment sign and must start with a valid ID. So something like this:
LINE :
    ('A'..'Z' | 'a'..'z') ('A'..'Z' | 'a'..'z' | '_' | '-' | '0'..'9')*
    WS* '=' WS*
    !('\r' | '\n' | '#')+
;

This token would basically replace your Property rule.
Of course this is a rather unsatisfactory solution as it will give you the entire line as a string and you still have to pick it apart yourself to separate the ID from the text part. It also prevents you from highlighting the ID part or the = sign as the entire line is one token and you can't highlight part of a token (as far as I know). Overall this does not buy you all that much over not using XText at all, but I don't see a better way.

A: As a workaround, I have changed
Property:
    name=ID ':' value=ID ';'?;

Now, of course, = is not in conflict any more, but this is certainly not a good solution, because properties can usually defined with name=value
Edit: Actually, my input is a specific property file, and the properties are know in advance.
My code now looks like
Section:
    '[' name=ID ']'
    (NEWLINE (properties+=AbstractProperty)?)+;

AbstractProperty:
    ADef
        | BDef

ADef:
    'A' (':'|'=') ID;

BDef:
    'B' (':'|'=') Float;

There is an extra benefit, the property names are know as keywords, and colored as such. However, autocompletion only suggest '[' :(


text:
Q: Get Android device ID shown in adb How can I get Android device ID to string (with Java code Android 2.2+) that is shown when I connect it to computer (example from eclipse "Serial number" field) or enter "adb devices" to cmd? I know it's not ANDROID_ID or telephonyManager.getdeviceId() or Build.SERIAL but I can't find what is it...

A: the only universal way is to pull the number from USB interface settings:
/sys/class/android_usb/android0/iSerial

Other than that it is up to every vendor to choose the way to store the serial number. Some of them choose not to populate ro.serialno property.

A: If you need the id shown by the adb devices command, then it is indeed Build.SERIAL.
The value shown in Eclipse seems to be just a concatenation of Build.MANUFACTURER, Build.MODEL and Build.SERIAL.
At least these are the results when testing on Nexus devices.

A: Try using the SERIAL string from android.os.build class
http://developer.android.com/reference/android/os/Build.html#SERIAL

A: If u want to get android_id , u can use
 private String getAndroidID() {
            String androidId = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
            return androidId;
        }

In case u want device id , u can use
private TelephonyManager getTelephonyManager() {
        TelephonyManager telephonyManager = ( TelephonyManager )getSystemService( Context.TELEPHONY_SERVICE );
        return telephonyManager;
    }

private String getIMEIStringOfDevice() {
       String imeiString = getTelephonyManager().getDeviceId();
        return imeiString;
    }

A: add android:name="android.permission.READ_PHONE_STATE" to your manifest
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String id = telephonyManager.getDeviceId();


text:
Q: Azure Deployment Failed when trying to create a storage account Following these steps https://azure.microsoft.com/en-us/documentation/articles/storage-create-storage-account/
once I click 'Create' I get the error "Deployment failed" here are the full details;
OPERATION IDE03BAC94EFAA1295
TRACKING ID5c3b3e63-e86a-4f98-9f3f-f31cc21621c7
STATUSBadRequest
PROVISIONING STATEFailed
TIMESTAMP4/28/2016, 10:12:57 AM
DURATIONPT2.0055957S
TYPEMicrosoft.ClassicStorage/StorageAccounts
RESOURCE ID/subscriptions/b2385f44-XXXX-4ff1-XXXX-
f09cbed8a333/resourceGroups/vmstorage/providers/Microsoft.ClassicStorage/Storage
Accounts/appsrv

STATUSMESSAGE{
  "error": {
    "code": "StorageAccountOperationFailed",
    "message": "Unable to create storage account 'appsrv': 'The location constraint is not valid'."
  }
}
RESOURCEappsrv

I have been searching online for a while with no real answers as to how to resolve this. Am I missing a step? could it be because I just signed up and it is using the Free trial subscription? Has anyone seen this before?

A: I think this is a restriction of the free Azure account - try changing your availability zone to us north.

The location constraint is not valid

A: Blob storage accounts are region locked, just like nearly everything in Azure.
There is a comprehensive and up to date list maintained by microsoft.
In your case, you want to look at the Blob Storage Accounts tab.
There are also ways to check using powershell or other means.
((Get-AzureRmResourceProvider -ProviderNamespace Microsoft.Web).ResourceTypes | Where-Object ResourceTypeName -eq sites).Locations

A: Thanks to you both! I got this from MS Tech support - makes no sense why i cannot create a storage account on a system in my own region, but whatever - no big deal.
"Hello Erick,
Thank you for your swift response.
I regret to inform you that both the regions (East US and East US 2) that you are trying to deploy are not enabled on your subscription hence it is not letting you create the storage account. The list of regions already available for your subscription are :

*

*South Central US

*Central US

*North Europe

*West Europe

*Southeast Asia

*Japan West

*Japan East

If you like to deploy in any of these regions there should not be any error. However, if you like to deploy in East US / East US 2 we will need to place a request with Capacity Planning Team to enable these region for your subscription. I would request you to please advise if you want to deploy in any of the existing region or would you like to place a request with the Capacity Planning Team to enable East US and East US 2 region for your subscription."


text:
Q: Draw 2D Mesh Grid using GLSL in 3D space I'm hoping to draw a 2D Grid within a finite space on the X axis using OpengGL 4.0.
I wish to use GLSL using vert/frag shaders etc for rending the light (making them appear).
It can be done with the simplest code using older OpenGL 2.0 methods but then of course it doesn't use lighting/shaders to colour them:
    void Draw_Grid()
    {
     for(float i = -500; i <= 500; i += 5)
        {
         glBegin(GL_LINES);
            glColor3ub(150, 190, 150);
            glVertex3f(-500, 0, i);
            glVertex3f(500, 0, i);
            glVertex3f(i, 0,-500);
            glVertex3f(i, 0, 500);
         glEnd();
        }
    }

But I can'd find any tutorials other than this one which I don't understand well enough to convert from a graph to a simple 2D Grid in 3D space.

A: Yes, you can use just shaders to generate your geometry...

*

*Don't bind any VBOs.

*Call glDrawArrays()

*Use gl_VertexID in the vertex shader or gl_PrimitiveID in the geometry shader to procedurally generate your stuff.

It can be faster exactly because there are no vertex attributes or input data. Not to mention the space saved and initialization time is next to nothing.
Here's an example of a vertex shader that draws a grid with GL_TRIANGLES:
#version 150

uniform mat4 modelviewMat;
uniform mat3 normalMat;
uniform mat4 projectionMat;

uniform ivec2 dim;

out vec3 esNorm;

const vec2 triOffset[] = vec2[](
    vec2(0,0),
    vec2(0,1),
    vec2(1,1),
    vec2(0,0),
    vec2(1,1),
    vec2(1,0));

void main()
{
    int triVert = gl_VertexID % 6;
    int gridIndex = gl_VertexID / 6;
    vec2 coord = vec2(gridIndex / dim.x, gridIndex % dim.x);
    coord = (coord + triOffset[triVert]) / vec2(dim);
    vec4 esVert = modelviewMat * vec4(coord * 2.0 - 1.0, 0.0, 1.0);
    gl_Position = projectionMat * esVert;
    esNorm = normalMat * vec3(0.0, 0.0, 1.0);
}

I did have some trouble drawing without VBOs bound on my ancient ATI card. This approach works fine on my Nvidia cards with new drivers. Discussed further here: Opengl, DrawArrays without binding VBO, where glDrawArraysInstanced/gl_InstanceID is suggested as an alternative.
A further note. I've noticed modulo % arithmetic can be a little slow in some cases. Using simpler bitwise operations or other tricks may speed things up.


text:
Q: Are there simple criteria for determining if there is a finite, non-zero Hausdorff measure of a set? It's kind of a wide question, so I'd like to motivate it: When trying to determine the Hausdorff dimension of a set, I found that it is often reasonably easy to find it heuristically, but very difficult to actually prove it.
For example, we can split the Cantor set $\mathcal C$ into two parts $ \mathcal{C} \cap [0;\frac13] $ and $ \mathcal{C} \cap [\frac23; 1] $ which are just copies of $\mathcal C$, scaled by a factor of $\frac13$. Thus we have
$$
\mathcal{H}^s(\mathcal{C}) = \mathcal{H}^s(\frac13 \mathcal{C}) + \mathcal{H}^s(\frac 13 \mathcal{C}) = \frac{2}{3^s} \mathcal{H}^s({\mathcal{C})}
$$
for all $s$. Now, if we assume that there is an $s$ with $\mathcal{H}^s(\mathcal{C})$ finite and non-zero, we can derive from this, that $s = \frac{\log 2}{\log 3}$ is the Hausdorff dimension of $\mathcal C$, by dividing both sides by $\mathcal{H}^s(\mathcal{C})$ and solving for $s$.
I found it quite difficult to prove this assumption—which, of course, doesn't hold for any set—but I wonder if there are some criteria on which one can determine if such an $s$ exists. As discussed in this question, it is always true for Cantor sets, but I wonder if there are some nice criteria for fractals in general or even arbitrary sets.

A: $\newcommand\h{\mathcal{H}^s}$
Of course showing that $\h(E)=0$ (when true) is often no big deal; you can often simply write down an open cover that demonstrates this. But showing that $\h(E)>0$ directly from the definition is typically not so simple. Frostman's Lemma is often very useful here.
For example if $C$ is the Cantor set then the "Cantor measure" on $C$ shows that $\h(C)>0$ for $s\le\log(2)/\log(3)=\alpha$. (And it's  then clear that $\h(C)=\infty$ for  all  $s<\alpha$, since  $\mathcal H^\alpha(C)>0$.) Again, showing that $\h(C)=0$ for $s>\alpha$ is trivial from the definition.)


text:
Q: Using Azure RM Powershell how do I find out which Recovery Services Vault VM is connected to? I can clearly see they can do that in the Portal, so must be the way - without looping through all available recovery services vaults - to get the RSV VM belongs to.
In other words: I know only VM - Name, Id etc. I want to know the Vault it belongs to.
Without traversing through all the vaults in the subscription - I know how to achieve this, but it's too slow with many Vaults.
Traversing / Looping / FOREACHing through all vaults trying to find the VM is not an acceptable, although working, solution.


text:
Q: Getting selected thing into clipboard c# My question is how I get selected text or marked text into the clipboard (ex. user have selected some text in web and when he presses CTRL + A + S, what he got selected or marked get into the clipboard).
I already setup the keyboard hook and background running so now I need to get selected thing into the clipboard.
I tried to get the answer on web but almost 90% of them is for a textbox and i don't need it for a textbox.
Thank you for all your answers,
-DF

A: You can get the selected text of a TextBox through the property SelectedText.
You can put something on the clipboard using the static method:
Clipboard.SetText(textBox1.SelectedText);

And get text from the clipboard (also the one copied into the clipboard in the browser) with:
if (Clipboard.ContainsText()) {
    textBox1.Text = Clipboard.GetText();
}

See: Clipboard Class.

If you only want to do that on the current form, you can get the current control with the form property ActiveControl. But will have to use different methods for different types of controls in order to get the selected text. Controls deriving from TextBoxBase have a SelectedText property. All controls have a Text property. All controls deriving from ListControl (like ComboBox) have a SelectedValue property. ComboBox has a SelectedItem property.
As you can see, you will have to make experiments and find the strategy which works best.

Also have a look into the Object Browser of Visual Studio, especially into the namespace System.Windows.Forms.


text:
Q: AWS Lambda/Secrets Manager permission no longer working (Pulumi) This stack was working at one point... I'm not sure what's going on. This permission is no longer doing what it did before, or has become invalid.
I have a Lambda function that rotates a Secret, so naturally it must be triggered by Secrets Manager. So I built up the Permission as follows
import * as aws from '@pulumi/aws'

export const accessTokenSecret = new aws.secretsmanager.Secret('accessTokenSecret', {});

export const smPermission = new aws.lambda.Permission(`${lambdaName}SecretsManagerPermission`, {
  action: 'lambda:InvokeFunction',
  function: rotateKnacklyAccessTokenLambda.name,
  principal: 'secretsmanager.amazonaws.com',
  sourceArn: accessTokenSecret.arn,
})

And the Policy,
{
        Action: [
          'secretsmanager:GetResourcePolicy',
          'secretsmanager:GetSecretValue',
          'secretsmanager:DescribeSecret',
          'secretsmanager:ListSecrets',
          'secretsmanager:RotateSecret',
        ],
        Resource: 'arn:aws:secretsmanager:*:*:*',
        Effect: 'Allow',
      },

Running pulumi up -y yields
  aws:secretsmanager:SecretRotation (knacklyAccessTokenRotation):
    error: 1 error occurred:
        * error enabling Secrets Manager Secret "" rotation: AccessDeniedException: Secrets Manager cannot invoke the specified Lambda function. Ensure that the function policy grants access to the principal secretsmanager.amazonaws.com.

This error confuses me, because the Policy created for the Lambda will not accept the Principal param (which makes sense, the same behaviour happens in the AWS Console), so I'm sure they mean Permission instead of Policy.
Based on the log I can tell that the Permission is being created way after the Lambda/Secrets Manager is, I'm not sure if this is a Pulumi issue similar to how it destroys stacks in the incorrect order (Roles and Policies for example).
I can see the Permission in the AWS Lambda configuration section, so maybe it's ok?


text:
Q: Problems with the .NET Framework version I have an ASP.Net MVC 5 application and WebApi, in .NET version 4.5.2 and post them to my FTP server I have the following error (attached image) ...
And asking the company's technical support, they answered the following:

From the .Net Framework 4.0, Microsoft has modified an internal
  component of the so-called CAS (Code Access Security), which
  determines how classes can access one others.
In order for your application to be functional on our servers, you
  will need to have the following three items:

*

*Medium trust

*MVC4

*Integrated

Is there any way to make my current project have these specifications without having to create another project?
Error.png

A: For first point, have you checked out that and this posts?
For second, you need to update framework and MVC versions to appropriate on your hosting


text:
Q: Uncheck a checkbox in ComponentView Im trying to uncheck a checkbox in the ComponentView of Tridion by jquery using the document ready event in a GUI extension:
$j(document).ready(function(){
    alert("is loaded");
    var field = $j('[type=checkbox][value=Aceptar]')
    field.attr("checked",false);
    console.log("field = " + field.is(':checked'));
    alert("is checked field = " + field.is(':checked'));
});

The problem is that on "$j(document).ready" the field values don't seem to be loaded in the ComponentView. My alert returns that the field is unchecked, but when the view finishes loading the checkbox is checked.It seems that the "$j(document).ready" fires before the values are loaded. Does anybody know which event I should use?

A: @Adrian Salazar @Sogo Thanks for your help, maybe I should use better "prop" instead of "attr" to change that property, but the problem was the same, the fields weren't still loaded so I couldn't change that property.
@Frank I tried with "$evt.addEventHandler($display, "start", onDisplayStarted);" on the "ComponentView" display, and extending that view on the configuration of my GUI extension,  but on that event the fields are still not loaded also, and everytime I tried to access my checkbox field it said that was "undefined".
Finally I managed to uncheck the checkbox suscribing to the load event of the component :
"EventSystem.Subscribe <Component, LoadEventArgs> (OnComponentLoad, EventPhases.Processed);"

as Nuno explains here http://www.tridiondeveloper.com/inheriting-metadata-on-organizational-items#more-1073, he uses it on an OrganizationalItem but works the same for a component.
Thanks for your help!!

A: try with,
field.prop("checked",false);

field.is(':checked') is working fine and if you need, you can use prop('checked') instead of that.anyway make sure your jquery version is 1.6 or higher if you are going to use prop()


text:
Q: Give permanent access to a computer via Chrome Remote Desktop? Is it possible to give someone else permanent access to a computer via Chrome Remote Desktop?
My use case is simply that I want to be able to assist my elderly father with his Windows computer. I tried having him access the Chrome Remote Desktop support interface (it generates a code that you can share with someone to remote in temporarily)... but even that was too much for him to handle.
Ideally, I'd want Chrome Remote Desktop to just be running all the time and I'd have permanent access to it without him having to intervene in any way. Basically, he'd be logged in with his Google account but have given my Google account permanent permission to access his computer.
Any ideas? I'm open to better ideas!

A: There are tools designed to support this function; Chrome Remote Desktop is not. Any "fix" you do to Chrome Remote Desktop to enable this will be inferior to using a tool designed for the job.
This may not appear to be an answer, but it is the correct answer. When you want a tool you can rely on to be available when you need it to be available, you want a tool that's designed to do that, not a tool you have to manipulate or tweak or coax to do that.


text:
Q: how to join two tables in sql server with out duplication Hi I have two tables A and B
Table A:
Order        Pick up
100          Toronto
100          Mississauga
100          Scarborough

Table B
Order              Drop off
100                Oakvile
100                Hamilton
100                Milton

Please let me know how can I can get this output (ie I just want to join the fields from in B in right hand side of A)
Order    pickup        Dropoff
100      Toronto       oakvile
100      Mississauga   Hamilton
100      Scarborough   Milton

How can I write query for the same I try to join a.rownum = b.rownum but no luck.

A: As OP has not mention any RDBMS
I am taking the liberty for taking SQL SERVER 2008 as his RDBMS. If OP wants the following Query can be converted to any other RDBMS easily.
select A.[Order],
    ROW_NUMBER() OVER(ORDER BY A.[Pick up]) rn1,
    A.[Pick up]
    into A1
FROM A
;
select B.[Order],
    ROW_NUMBER() OVER(ORDER BY B.[Drop off]) rn2,
    B.[Drop off]
    into B1
FROM B
;
Select A1.[Order],
    A1.[Pick up],
    B1.[Drop off]
FROM A1
INNER JOIN B1 on A1.rn1=B1.rn2

SQL FIDDLE to Test

A: From the use rownum, I'm presuming that you are using Oracle.  You can attempt the following:
select a.Order as "order", a.Pickup, b.DropOff
from (select a.*, rownum as seqnum
      from a
     ) a join
     (select b.*, rownum as seqnum
      from b
     ) b
     on a.order = b.order and a.seqnum = b.seqnum;

(This assumes that all orders match up exactly.)
I must emphasize that although this might seem to work (and it should work on small examples), it will not work in general.  And, it will not work on data that has deleted records.  And, it probably won't work on parallel systems.  If you have a small amount of data, I'd suggest dumping it in Excel and doing the work there -- that way, you can see if the pairs make sense.
Also, if you do have a column that specifies the ordering, then basically the same structure will work:
select coalesce(a.Order, b.Order) as "order", a.Pickup, b.DropOff
from (select a.*,
             row_number() over (partition by "order" order by <ordering field>) as seqnum
      from a
     ) a join
     (select b.*,
             row_number() over (partition by "order" order by <ordering field>) as seqnum
      from b
     ) b
     on a.order = b.order and a.seqnum = b.seqnum;

A: I'd use a CTE along with the ROW_NUMBER windowing function.
WITH keyed_A AS (
  SELECT
    ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS id
   ,[Order]
   ,[Pick Up]
  FROM A
), keyed_B AS (
  SELECT
    ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS id
   ,[Order]
   ,[Drop Off]
  FROM B
)
SELECT
   a.[Pick Up]
  ,b.[Drop Off]
  FROM keyed_A AS a
  INNER JOIN keyed_B AS b
    ON a.id = b.id
;

The CTE can be thought of as a virtual table with an id that crosses the two tables.  The OVER clause with the Windowing function ROW_NUMBER can be used to create an id in the CTE.  Since we are relying on the physical storage of the records (not a good idea, please add keys to the tables) we can ORDER BY (SELECT NULL) which means just use the order in will be read in.
SQLFiddle to test