text:
Q: Wordpress return JSON and resolve "plugin spaceholder" I' building a wordpress theme which should be able to lazy load specific pages etc. Therefore my idea was to have something like this:
/pages/contact => displays the page
/pages/contact?json => returns json
All in wall this is working good, but i have a problem when i use a ninja form for example. The content of the page will have something like this: [ninja_form id=1] - when i now lazy load the page, this snippet is not resolved. Is there a function to resolve it?
Code example
while ( have_posts() ) : the_post();

    $data = array(
        'title' => get_the_title(),
        'content' => get_the_content(),
        'image' => wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) )
    );

endwhile;

// return json
header('Content-Type: application/json');

wp_send_json($data);
//echo json_encode($data);

Any ideas?

A: I found the solution. I had to call this with my content string:
$data = array(
  'title' => get_the_title(),
  'content' => apply_filters('the_content', get_the_content()),
  'image' => wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) )
);

calling apply_filters was the solution


text:
Q: What does angle brackets mean in JS? I see the following example JSX code:
const AppBar = styled(MuiAppBar, {
  shouldForwardProp: (prop) => prop !== 'open',
})<AppBarProps>(({ theme, open }) => ({
  zIndex: theme.zIndex.drawer + 1,
  transition: theme.transitions.create(['width', 'margin'], {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  ...(open && {
    marginLeft: drawerWidth,
    width: `calc(100% - ${drawerWidth}px)`,
    transition: theme.transitions.create(['width', 'margin'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.enteringScreen,
    }),
  }),
}));

and I don't understand what  is doing.
So I used babel to translate and get:
const AppBar = styled(MuiAppBar, {
  shouldForwardProp: prop => prop !== 'open'
}) < AppBarProps > (({
  theme,
  open
}) => ({
  zIndex: theme.zIndex.drawer + 1,
  transition: theme.transitions.create(['width', 'margin'], {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen
  }),
  ...(open && {
    marginLeft: drawerWidth,
    width: `calc(100% - ${drawerWidth}px)`,
    transition: theme.transitions.create(['width', 'margin'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.enteringScreen
    })
  })
}));

What does this ... < AppBarProps > ... mean?  (The rest I  I understand just fine)
Sorry if this seems like the dummest question ever, but can't imagine what is going on here.

A: It's a way to declare generic type parameter in typescript. styled returns a HOC that creates a component with the styles attached. I'll breakdown the code to make it more easier to digest:
const hoc = styled(MuiComponent)

// StyledMuiComponent now can accept the props with type MuiComponentProps
const StyledMuiComponent = hoc<MuiComponentProps>(styles)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Override Rails scaffold generator The scaffold generator in rails generates the MVC layers from the templates located in lib/rails/generators/erb/scaffold/templates railties path and from the lib/templates folder in your project.
If you copy the original files from the railties folder to your projects lib folder, then you'll be able to customize the original scaffold generator, as Daniel Fone explain in his blog.
The original Rails generator uses 5 files in the views layer:

*

*_form.html.erb

*edit.html.erb

*index.html.erb

*new.html.erb

*show.html.erb
I was wondering if the there is a way to extend this behavior by adding another file to the set. like _header.html.erb or _info.html.erb (some partials that I've design).

A: For those who are lazy, here is a quick command to copy the default railties erb templates to the correct location in Rails:
mkdir -p lib/templates/erb/scaffold && \
cp $(bundle info railties --path)/lib/rails/generators/erb/scaffold/templates/* lib/templates/erb/scaffold

A: Well after a couple months I've found the solution. Instead of creating a new generator as the Rails documentation states, I override the default generator but in my projects lib folder.

The original scaffold_generator.rb is located at ~/.rvm/gems/ruby-2.1.0/gems/railties-4.2.4/lib/rails/generators/erb/scaffold. To add the new file (_info.html.erb) we will add it to the available_views method.
def available_views
    %w(index edit show new _form _info)
end

Hope it helps someone.


text:
Q: How can I disable software update notifications in kde/plasma I keep getting popups about updates and it's annoying. The window below is from the taskbar icon settings that I think is causing the popup. Is there a workaround? If I knew which package was the culprit maybe I could uninstall it.

A: Go to Panel settings:

Then go to System tray settings:

A: Don't know for other distros, but for Fedora
dnf remove plasma-pk-updates

should solve it.

A: for fedora 35
dnf remove plasma-discover-notifier

A: Or you can just End "Discover-notifier" process from system-monitor, although this needs to do it everytime u boot.


text:
Q: "! You can't use `\end' in internal vertical mode." Error I am using TEX editor and have written the following code:
\documentclass[10  pt,a4paper,twoside,reqno]{amsart}
\usepackage{amsfonts,amssymb,amscd,amsmath,enumerate,verbatim,calc}
\renewcommand{\baselinestretch}{1.2}
\textwidth = 12.5 cm
\textheight = 20 cm
\topmargin = 0.5 cm
\oddsidemargin = 1 cm
\evensidemargin = 1 cm
\pagestyle{plain}
\begin{document}
\title{Some Title}
\author{My Name}
\date{July 25, 2015}
\maketitle
\abstract{Some text....
......................}
\section{Introduction}
Some text.....
.............

\end{document}

When I click "Quick Build" I get the following error ! You can't use `\end' in internal vertical mode. on Line 27 (Line containing \end{document}). Please explain why does this error occur and how should I got about fixing it.

A: The abstract for an amsart document should be given in environment for
\begin{abstract}
...
\end{abstract}

Given as just \abstract, TeX is collecting a box, and you can't end the run the document in that situation. As there's no \end{abstract} you never close the box properly.

A: The same error occurs if you by accident delete or forget to close a curly bracket
}

Such as in this example
\begin{table}
…
\label{This is a caption after which you forgot to close the bracket, exactly here -->
\end{table}


text:
Q: Clear HTML canvas I want an HTML canvas that displays mouse position on its JS grid on mouse move, but I can't seem to clear my canvas, I tried using ctx.clearRect(0,0 canvas.width, canvas.height) and clearing with a click, but it somehow remembers the previous draw it had. I want only one black square to be displayed on canvas at a time depending on the mouse position. Heres demo on code pen and some code

<canvas id="myMap" style="width: 300px;height: 300px;background-color: beige;"></canvas>
<script>
  var findDivisible = (x, scale) => {
    while (x % scale !== 0 && x > 0) {
      x = x - 1;
    };
    return x
  };

  var map = document.getElementById("myMap");
  map.width = 300;
  map.height = 300;
  var mapContext = document.getElementById("myMap").getContext("2d");
  map.addEventListener("mousemove", function(e) {
    mapContext.clearRect(0, 0, map.width, map.height);
    mapContext.rect(findDivisible(e.clientX - map.offsetLeft, 50), findDivisible(e.pageY - map.offsetTop, 50), 50, 50);
    mapContext.stroke();

  });
  map.addEventListener("click", function() {
    mapContext.clearRect(0, 0, 500, 500);
  })
</script>

A: You're not starting a new stroke for each rectangle, but "piling them up" so they get re-re-redrawn with .stroke().
Use .beginPath():

function findDivisible(x, scale) {
  while (x % scale !== 0 && x > 0) {
    x = x - 1;
  }
  return x;
}

var map = document.getElementById("myMap");
map.width = 300;
map.height = 300;
var mapContext = map.getContext("2d");
map.addEventListener("mousemove", function(e) {
  mapContext.clearRect(0, 0, map.width, map.height);
  mapContext.beginPath();
  mapContext.rect(
    findDivisible(e.clientX - map.offsetLeft, 50),
    findDivisible(e.pageY - map.offsetTop, 50),
    50,
    50,
  );
  mapContext.stroke();
});
map.addEventListener("click", function() {
  mapContext.clearRect(0, 0, 500, 500);
});
<canvas id="myMap" style="width: 300px;height: 300px;background-color: beige;"></canvas>

A: You can try this:
map.addEventListener("mousemove", function(e){
  map.width = map.width;
  mapContext.rect(findDivisible(e.clientX-map.offsetLeft,50) , findDivisible(e.pageY - map.offsetTop,50), 50, 50);
  mapContext.stroke();
});

map.addEventListener("click", function(){
  map.width = map.width;
});

One of the ways that is implicitly endorsed in the spec and often used in people's apps to clear a canvas
  https://dzone.com/articles/how-you-clear-your-html5


text:
Q: Prove maximum number of rotations for two trees to become equal In the book Introduction To Algorithms - A Creative Approach, Question 4.24:

Let T1, and T2 be two arbitrary trees, each having n nodes. Prove that it is sufficient to apply at most 2n rotations to T1, so that it becomes equal to T2.

For binary search trees, I figured out an algorithm:

*

*Find the element which is equal to T2's root, let's call it target-root.

*Using AVL rotation strategy, rotate target-root to make it T1's new root.
  During this process, multiple rotations may be performed.

*For the left sub tree of T1 and T2, process them as above recursively.
  For the right sub tree of T1 and T2, process them as above recursively.
This algorithm, when in worst-case, runs in O(N^2).
I don't quite understand the phrase "arbitrary trees", and I can't figure out how to make T1 equal to T2.
Could anyone help on this question?

A: From whatever i have got i can propose an algorithm that can solve this problem in O(N) rotations but could not get the exact upper bound but think you can build on this:-
Here is pseudo code for algorithm:-
 //Method to make T1 equivalent to T2

    alignTree(T1,T2) {

     if(length(T1)==1)
        return

     else {

        Node k = FindRoot(T1,T2)
        rotateAbout(k)
        align(T1.left,T2.left)
        align(T1.right,T2.right)
     }

    }

Suppose FindRoot finds the node of T1 which is considered to be root of new Tree which is equivalent tree. Suppose rotateAbout(K) makes appropriate rotation to root to get equivalent nodes on left and right subtrees of new tree. Then we can recursively solve for smaller sub-problems on smaller subtrees.
No of Rotations: As you can see in pseudo code the no of rotation is equivalent to pre-order traversal of tree which is O(N)
Note: You can always extend the above pseudo code for general tree and still get same complexity.


text:
Q: Using conditional statement to select different templated matrix class at run-time I'm working with the templated Matrix class in the Eigen linear algebra library (link).  The Matrix class takes three nominal template parameters:
Matrix<type, rows, cols>

In the above, an example of type is double, or std::complex<double>.  In addition, rows is the number of rows, and cols is the number of columns in the Matrix.
As shown by the code below, what I would like to do is use a different templated Matrix class at run-time using a conditional statement.
The first solution that comes to mind might be to use void pointers.
#include <iostream>
#include <Eigen/Dense>
#include <complex>

using namespace Eigen;

int main()

{
    // this flag is set at run-time, but it is only set here
    // in the code as an example
    int create_complex = 1;
    void *M;

        if(create_complex)
    {
        Matrix<std::complex<double>,3,3> m0;
        M = &m0;
    }
    else
    {
        Matrix<double,3,3> m0;
        M = &m0;
    }
    // de-reference pointer here and use it

 return 0;
}

Although this code compiles, the void *M pointer needs to be explicitly de-referenced before use.  This is inconvenient, since I then have to write different code blocks for the same program logic.
I am wondering if there is something similar to polymorphism that might be applied here, where I don't have to use void pointers.

A:
This is inconvenient

If you read "inconvenient" as "illegal", then you're spot on.
The local variables are destroyed when their scope ends (i.e. the closing }), so you're left with a dangling pointer. So you'll run into undefined behavior when trying to de-reference it.
There's no easy way to do this, because Matrix<std::complex<double>,3,3> and Matrix<double,3,3> are completely unrelated classes. I'll say it again. They are completely unrelated classes.
An alternative is that Matrix has a base type and you have a pointer to that, but then you'd need dynamic allocation. Something like:
BaseMatrix* m;
if ()
    m = new Matrix<std::complex<double>,3,3>;
else
    m = new Matrix<double,3,3>;

A: You can write your own function as a template based on the matrix type and call different versions of that in the conditionals.
This is the only way because templates are for generating code at compile time. You must generate all code paths at compile time and then just select one of them.

A: You should templatize your method too:
template<class T>
my_main() {

   Matrix<T,3,3> m0;

   // ...

}

UPDATE
Or you can define your class
#ifndef CREATE_COMPLEX
    typedef double MyClass;
#else
    typedef std::complex<double> MyClass;
#endif

main() {

   Matrix<MyClass,3,3> m0;

   // ...

}

you can switch these definitions with preprocessor definition.


text:
Q: British Maths Olympiad (BMO) 2003 Round 1 Question 5 does a solution with fermat's theorem or crt exist? The question states:
Let $p,q$ and $r$ be prime numbers.
It is given
$p$ divides $qr − 1$,
$q$ divides $rp − 1$,
$r$ divides $pq − 1$.
Determine all possible values of $pqr$
My specific question is does a solution with fermat's theorem or crt exist? My attempt along those lines follows:
We know that $p,q,r$ cannot all be odd, in-fact exactly one of them must be event. $w.l.o.g$ we let $p = 2$ then we have $q,r$ are odd. This means

$qr - 1$ mod $p = 0$ $\Rightarrow$ $qr$ mod $2 = 1$
$2r - 1$ mod $q = 0$ $\Rightarrow$ $2r$ mod $q = 1$
$2q - 1$ mod $r = 0$ $\Rightarrow$ $2q$ mod $r = 1$

Thus we have $r$ is the inverse modulo $q$ of 2 and similarly for q modulo $r$. Not sure if any of this is useful...
P.S I know this question has been asked on this website but here I am specifically asking if a type of solution exists

A: It is unlikely that there would be any meaningful solutions using these theorems. Fermat's little theorem would only be useful in situations involving powers, but this question contains none. Furthermore CRT would produce an infinite number of possibilities based on a modulo and the bounding argument would still be required to fix these.


text:
Q: Is it idiomatic to say "you can throw the ball by swinging your hand from bottom up / from top down" in everyday English?
There are 2 ways to throw a ball.
-You can throw the ball by swinging your hand from bottom up as the man in red in the picture.
or
-You can throw the ball by swinging your hand from top down as the woman in blue in the picture.
But I am not sure the phrase "to throw the ball  by swinging your hand from bottom up / from top down" expresses accurately the 2 movements in everyday English as shown in the picture?


text:
Q: Cannot resolve symbol addFormDataPart MultipartBody.Builder builder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("title", "title");
                builder.addFormDataPart("contact",  "9876543210");

I am using okhttp 3.9.0 ( 'com.squareup.okhttp3:okhttp:3.9.0')


text:
Q: Jest Failed after upgrading : _jestWatcher(...).TestWatcher is not a constructor I have been working on upgrading a NextJS projet from version 9 to 12 :
During the updates, i had to update React from 16 to 17 and Jest from 23 to 28.
My final package.Json looks like :
"next": "^12.2.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"devDependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.3.0",
    "@testing-library/react-hooks": "^3.2.1",

    "jest": "^28.1.0",
    "jest-environment-jsdom": "^28.1.3",

Till now everything works "almost" fine (few test failed after upgrade) with @testing-library/react V10.
When I upgraded the @testing-library/react to V13 : I got a this error :
TypeError: _jestWatcher(...).TestWatcher is not a constructor. Have been searching for this error but I did not find anything.
Does anyone face this error recently ?
Error


text:
Q: SQL query error or is it somewhere else? I am trying to query an sql database and I am having trouble. Is there an error with the syntax below or is it something else that I am missing?
SELECT Name, DateTime, num1, num2
FROM names_E6
WHERE DateTime between '2012-1-27' AND '2012-1-27'
WHERE num1 between '0' AND '5'
WHERE num2 between '0' AND '6'

A: Yes, you can't have multiple WHERE clauses in one SELECT.  Separate the conditions with an AND or an OR (by the looks of your query, I'm guessing you want AND).
SELECT Name, DateTime, num1, num2
FROM names_E6
WHERE DateTime between '2012-1-27' AND '2012-1-27'
AND num1 between '0' AND '5'
AND num2 between '0' AND '6'

A: In addition to the answers regarding the syntax, I would like to add a comment on the usage of value literals:
If num1 and num2 are numbers, the condition should be
AND num1 between 0 AND 5
AND num2 between 0 AND 6

Note the missing single quotes around the numbers. Some DBMS will not even allow a conversion from a character literl '5' to a number, others might surprise you with strange results and most of them will not use an index on the column if such an implicit type casting is successful.
You should also be aware that the expression DateTime between '2012-1-27' AND '2012-1-27' might not always work correctly due to the implicit type casting (String -> Date) and locale settings of the server and/or client. To be on the safe side you should use e.g. the ANSI standard for a date literal:
 DateTime between DATE '2012-01-27' AND DATE '2012-01-27'

Note the keyword DATE to start a date literal and the month given with two digits.


text:
Q: How to use TestKit to not process messages sent to Self I'm trying to test an Actor. On one scenario I want to focus on how it processes a message. For various design reasons, I want to split up an action in to 2 separate distinct steps / messages for the same actor. Mainly, it is possible that the 2nd stage (i.e. the second message) will not be able to be processed and may have to be rescheduled. So for my unit tests, I want to focus on the stage 1 behavior, but using Test Kit it automatically processes the message, because I call this this.Self.Tell("2");.
I've simplified the code and put it here. The following is the actor code:
public class TestSelfActor : UntypedActor
{
    protected override void OnReceive(object message)
    {
        switch (message)
        {
            case string s:
                if (s == "1")
                {
                    Console.WriteLine("one");
                    this.Self.Tell("2");
                    this.Sender.Tell("test");
                }
                else if (s == "2") { Console.WriteLine("two"); }
                break;
        }
    }
}

Here is the test method
public void TestSendingMessage()
{
    target = Sys.ActorOf(Props.Create(() => new TestSelfActor()));
    target.Tell("1");

    actual = this.ExpectMsg<string>();
    Assert.AreEqual("test", actual);
}

If I run this, it will pass, and the output will show
one
two

Ideally, there is some way to setup the test so I can send it the first message and then assert that it told itself the message "2", without it every outputting to the console "2".
Some extra info, I'm running .NET Framework 4.8, and akka/akka.testkit 1.3.8, although I think the code and problem are simple enough that it doesn't matter the version?

A: In your test project you can inherit from TestSelfActor and override AroundReceive method (then you can fake it with NSubstitute, Moq, ...),
In AroundReceive you can intercept messages and decide how to handle them (e.g. return false for "2" in your case)
Below is example using XUnit and NSubstitute. I could also extend it and create fake MessageHandler in XUnit fixture to make it reusable. You can always pass null if you want to test default behavior.
Hope this helps
using Akka.Actor;
using Akka.TestKit.Xunit;
using NSubstitute;
using System;
using Xunit;

namespace ActorTests
{
    public class TestSelfActor : UntypedActor
    {
        protected override void OnReceive(object message)
        {
            switch (message)
            {
                case string s:
                    if (s == "1")
                    {
                        Console.WriteLine("one");
                        this.Self.Tell("2");
                        this.Sender.Tell("test");
                    }
                    else if (s == "2") { Console.WriteLine("two"); }
                    break;
            }
        }
    }

    public interface IMessageHandler
    {
        Func<object, bool> AroundReceiveHandler { get; }
    }

    public class FakeActor : TestSelfActor
    {
        private readonly IMessageHandler _messageHandler;

        public FakeActor(IMessageHandler messageHandler)
        {
            _messageHandler = messageHandler;
        }
        protected override bool AroundReceive(Receive receive, object message)
        {
            var acceptMessage = _messageHandler?.AroundReceiveHandler?.Invoke(message) ?? true;
            return acceptMessage && base.AroundReceive(receive, message);
        }
    }

    public class SelfActorSpecs : TestKit
    {
        [Fact]
        public void When_Sender_TellsOne_Actor_Should_RespondWith_Test_NotSending_Two_ToSelf()
        {
            var messageHandler = Substitute.For<IMessageHandler>();
            messageHandler.AroundReceiveHandler(Arg.Any<string>()).Returns(true);
            messageHandler.AroundReceiveHandler("2").Returns(false);

            var target = Sys.ActorOf(Props.Create(() => new FakeActor(messageHandler)));
            target.Tell("1");
            ExpectMsg<string>(x => x == "test");
        }
    }
}


text:
Q: word-wrap break-word doesn't work properly in dompdf HTML code is given bellow

〒135-8730

神奈川県幕張本郷張西メールアドレ幕張西

フォメーシ市区町村名市売上区分

東京都江東区潮見2-9-15内田洋行幕潮見オフィス市区町村名市区町村名市区町村

ウチダインフォメーションテクノロジー 株式会社

UIT TK

システム課システム課システム課システム課システム課シス

良夢チャン良夢チャン良夢チャン様

お客様コード 00600201001

When generating pdf loading this HTML the output like this

There is available space after 2-9- in line 4 but it breaks to the next line. How to fix it.


text:
Q: Write to a specific value in dataframe without overwriting the csv I have a dataframe like such:
 master_contact_id  Agent_Disposition        QA_Disposition Comments
0           37284773    Not Serviceable       Not Serviceable      NaN
1           37284829  Existing Customer      Customer Service      NaN
2           37284880      Closed - Sale         Closed - Sale      NaN
3           37284887  Existing Customer  Hang up/Disconnected      NaN
4           37284943      Closed - Sale         Closed - Sale      NaN

I'm going through each contact id, finding the specific index, and writing a comment to replace "NaN" with:
df.at[1, 'Comments'] = "Test Comment"

However, when I write to csv, with
export = df.to_csv('set1_output.csv')

the exported csv keeps overwriting. I want to be able to append comments continually.

A: If I understand your question correctly, you want to append the new data to the csv.
Make a copy of the dataframe, do your operations, append the new array to the old array, and save the whole copy.
dfcopy = df.copy()
dfcopy.at[1,"Comments"] = "Test Comment"
df.append(dfcopy)
export = df.to_csv('set1_output.csv')


text:
Q: Making sure only a single if-else statement is allowed to execute I'm a bit lost as to what kind of statement I could use to solve my problem.
I am writing a program that will take four randomNumbers and four playerGuesses. If the first, second, third or fourth randomNumber matches with the first, second, third or fourth playerGuess respectively, they are awarded a Red pin for each match (So a maximum of 4, a minimum of 0). If the playerGuess number does appear in the randomNumber sequence, but is in the wrong place, the player is rewarded with a White pin. If a red pin is awarded for a randomNumber (meaning a correct guess on the correct place), no white pin can be rewarded for that number anymore.
Example:
randomNumber sequence (0, 1, 2, 3) matched with playerGuesses (0, 2, 2, 1) will result in 2 red pins and 1 white pin).
The code below shows the process for determining the red and white pins. Please note that both randomNumber and playerGuesses are arrays of four integers.
//Determining the amount of red and white pins
if (randomNumbers[0] == playerGuesses[0])
    {Red = Red+1;}
        else if (randomNumbers[0] == playerGuesses[1] || randomNumbers[0] == playerGuesses[2] || randomNumbers[0] == playerGuesses[3])
            {White = White+1;}
if (randomNumbers[1] == playerGuesses[1])
    {Red = Red+1;}
        else if (randomNumbers[1] == playerGuesses[0] || randomNumbers[1] == playerGuesses[2] || randomNumbers[1] == playerGuesses[3])
            {White = White+1;}
if (randomNumbers[2] == playerGuesses[2])
    {Red = Red+1;}
        else if (randomNumbers[2] == playerGuesses[0] || randomNumbers[2] == playerGuesses[1] || randomNumbers[2] == playerGuesses[3])
            {White = White+1;}
if (randomNumbers[3]==playerGuesses[3])
    {Red = Red+1;}
        else if (randomNumbers[3] == playerGuesses[0] || randomNumbers[3] == playerGuesses[1] || randomNumbers[3] == playerGuesses[2])
            {White = White+1;}

One very specific problem occurs when multiple if-else statements turn up true. It is best shown with an example:
Computer generates: (4 9 7 7)
Player guesses: (1 7 1 1)
The console returns: 2 white pins, 0 red pins.
In this example, none of the if-statements that determine red pins are triggered. So, all if-else statements are run for determining white pins.
The problem is that the "7" in the player's guesses triggers both the third and fourth if-else statement for adding white pins, resulting in two white pins. The game is meant to award only one white pin for this, however.
Do you guys have any idea how to make sure any playerGuess is only able to trigger one white pin, when no red pins are awarded.
(I hope all information needed to answer my question is provided!)

A:         if (randomNumbers [0] == playerGuesses [0])
{Red = Red+1;}
    else if (randomNumbers[0] == playerGuesses[1] || randomNumbers[0] == playerGuesses[2] || randomNumbers[0] == playerGuesses[3])
        {White = White+1;}
if (randomNumbers[1] == playerGuesses[1])
    {Red = Red+1;}
        else if (randomNumbers[1] == playerGuesses[2] || randomNumbers[1] == playerGuesses[3])
            {White = White+1;}
if (randomNumbers[2] == playerGuesses[2])
    {Red = Red+1;}
        else if ( randomNumbers[2] == playerGuesses[3])
            {White = White+1;}
if (randomNumbers[3]==playerGuesses[3])
    {Red = Red+1;}

This should fix your code. You rechecked some conditions up to 3 times, like if randomNumbers[0] == playerGuesses[1].
This has the effect inflating the number of times a condition is actually met, as you checked
for it more than one time.
Using your example and your original code,
Computer generates: (4 9 7 7)
Player guesses: (1 7 1 1)
Your code checks if randomNumbers[2] == playerGuesses[3] in your 3rd else if statement, and then
if randomNumbers[3] == playerGuesses[2] in your fourth else if statement . As you can see,
this checks the same condition twice, and so will give 2 white pins instead of 1 white pin.
The re-made code will ensure that this doesn't happen.

A: I suggest a different approach,
with a simpler logic and fewer if statements.
It also solves your problem of too many white pins.

*

*Determine the number of red pins.

*Determine the total number of pins (red + white):
For every possible number (0, 1, 2, 3, ... 9) count how many times it
occurs in both arrays.
The smaller of these two counts contributes to
the total number of pins.

*Calculate the number of white pins (total - red).

public static void main(String[] args) {
    int[] randomNumbers = {4, 9, 7, 7};
    int[] playerGuesses = {1, 7, 1, 1};
    compare(randomNumbers, playerGuesses);
}

/**
 * Determine the amount of red and white pins
 */
private static void compare(int[] randomNumbers, int[] playerGuesses) {
    int red = 0;
    for (int i = 0; i < randomNumbers.length; i++) {
        if (randomNumbers[i] == playerGuesses[i]) {
            red++;
        }
    }
    int total = 0;
    for (int x = 0; x < 10; x++) {
        total += Math.min(frequency(randomNumbers, x), frequency(playerGuesses, x));
    }
    int white = total - red;
    System.out.println(white + " white pins, " + red + " red pins");
}

/**
 * Determine how many times the value x occurs in the array
 */
private static int frequency(int[] array, int x) {
    int result = 0;
    for (int i = 0; i<array.length; i++) {
        if (array[i] == x) {
            result++;
        }
    }
    return result;
}


text:
Q: How to determine the type of a numerical value passed as a string without losing data or being converted to wrong datatype I want to allow users to submit numerical values through an online form but I've ran into a problem trying to validate the correct datatype(integer or float) for the submitted value.
Lets say a user submits:
3.14

I cannot use is_float() because the user-value is technically a string.
floatval() would work, except when the user only supplies an integer floatval() still considers it a float instead of an integer.
gettype(floatval("3"))

returns float, but I need it to return integer.
I even tried checking if it was an integer like this:
is_int(floatval(3)) // returns false

But why does the above return false?
The below prints 3 as if it was an integer:
echo floatval(3)

Therefore, I need a function that can be able to tell the difference between a float and integer passed as a string so it doesn't

*

*pass an integer off as a float.

*doesn't truncate a float into an integer.

Pattern checking with regular expressions could possibly be a solution, but are there any other alternatives?
NOTE: I am not using classes or objects and I prefer not to if possible.

A: Convert it to a float and integer, then check if they're equal.
$i = intval($input);
$f = floatval($input);
if ($i == $f) {
    $type = "int";
} else {
    $type = "float";
}

A: Below function will solve your problem
function checkType($inputNumber){
    if (strpos($inputNumber, '.') !== false) {
        return 'Number is float';
    } else {
        return 'Number is integer';
    }
}

echo checkType(3.5);  o/p Number is float.
echo checkType(3);  o/p Number is integer.

A: First of all, If you checking float then obviously it will only return true or false on float value weather or not it's a integer.
You are checking for float then how can you expect that it will return integer. Use intval() to check integer value.
<?php
    echo intval(42);                      // 42
    echo intval(4.2);                     // 4
    echo intval('42');                    // 42
    echo intval('+42');                   // 42
    echo intval('-42');                   // -42
    echo intval(042);                     // 34
    echo intval('042');                   // 42
    echo intval(1e10);                    // 1410065408
    echo intval('1e10');                  // 1

Or you can do one thing you can check if dot(.) exist then check with floatval() and not then check with intval()

You can alos do something like following

<?php

  $a = '1.6';

  if(str_pos($a, '.') !== 'false){
     $a = intval($a);
  }else{
     $a = floatval($a);
  }


text:
Q: Android Authentication FAILS in AsyncHttpClient but it's okay with browser I'm trying to be authenticate from android (Device Samsung GT-i9300 Android 4.3 (API18)) to my platform using the loopj library for AsyncHttppClient. The authentication with browser it's fine, after  user+pass i'll be redirect to my welcome page.
Here is my logcat view:
15760-15760/Jac.example.com.my_login I/System.out﹕ Entity content encoding:    null
15760-15760/Jac.example.com.my_login I/System.out﹕ Entity content type: Content-Type: text/plain; charset=ISO-8859-1
15760-15760/Jac.example.com.my_login I/System.out﹕ Entity content: java.io.ByteArrayInputStream@427a66b8
15760-15760/Jac.example.com.my_login I/System.out﹕http://mysite.example.net:8145/
15760-16179/Jac.example.com.my_login D/AsyncHttpClient﹕ Headers were overwritten! (Content-Type | application/json) overwrites (Content-Type | text/plain; charset=ISO-  8859-1)
15760-15760/Jac.example.com.my_login V/AsyncHttpResponseHandler﹕ Progress 12 from 1 (1200%)
15760-15760/Jac.example.com.my_login W/JsonHttpResponseHandler﹕ onFailure(int, Header[], String, Throwable) was not overriden, but callback was received org.apache.http.client.HttpResponseException: Unauthorized
at com.loopj.android.http.AsyncHttpResponseHandler.sendResponseMessage(AsyncHttpResponseHandler.java:404 )**
at com.loopj.android.http.AsyncHttpRequest.makeRequest(AsyncHttpRequest.java:161)
at com.loopj.android.http.AsyncHttpRequest.makeRequestWithRetries(AsyncHttpRequest.java:178)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:390)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)

I'll try to explain something:

*

*15760-16179/Jac.example.com.my_login D/AsyncHttpClient﹕ Headers were overwritten! (Content-Type | application/json) overwrites (Content-Type | text/plain; charset=ISO-  8859-1)

I dont understand if it is a good msg or a bad one. I receive this because if I dont set Header manually it gave to me:
    W/AsyncHttpClient﹕ Passed contentType will be ignored because HttpEntity sets content type
so i decide to set client.setHeader("Content-Type","application/json"),

*15760-15760/Jac.example.com.my_login W/JsonHttpResponseHandler﹕ onFailure(int, Header[], String, Throwable) was not overriden, but callback was received org.apache.http.client.HttpResponseException: Unauthorized

I suppose to be something wrong in the Base64.encode so i have try with Base64.DEFAULT and NO_WRAP but nothing has changed.
if (user != null && password != null)
{
String orig = user + ":" + password;

//byte[] encoded = Base64.encode(orig.getBytes(), Base64.DEFAULT);
byte[] encoded = Base64.encode(orig.getBytes(), Base64.NO_WRAP);
String credentials = new String(encoded);

// set header
// HEADER_CONTENT_TYPE = "Content-Type";
// HEADER_APPL_JSON = "application/json";
client.setHeader(HEADER_AUTHORIZATION, HEADER_BASIC + " " +credentials);
client.setHeader(HEADER_CONTENT_TYPE, HEADER_APPL_JSON);
}

This is mylogin:
public static void login(Context context, String user, String password) throws JSONException,   UnsupportedEncodingException {

    JSONObject jsonParams = new JSONObject();
    jsonParams.put("username", user);
    jsonParams.put("password", password);
    StringEntity entity = new StringEntity(jsonParams.toString());

    if (user != null && password != null){
        String orig = user + ":" + password;
        //byte[] encoded = Base64.encode(orig.getBytes(), Base64.DEFAULT);
        byte[] encoded = Base64.encode(orig.getBytes(), Base64.NO_WRAP);
        String credentials = new String(encoded);

        // set header
        // HEADER_CONTENT_TYPE = "Content-Type";
        // HEADER_APPL_JSON = "application/json";
        client.setHeader(HEADER_AUTHORIZATION, HEADER_BASIC + " " +credentials);
        client.setHeader(HEADER_CONTENT_TYPE, HEADER_APPL_JSON);
    }

    client.post(context, "oauth2/auth-token", entity, null, new JsonHttpResponseHandler()
    {
        /*
        @Override
        public void onStart(){
            // called before request is started
        }*/

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response){
            // called when response HTTP status is "200 OK"
            try {
                System.out.println("Status code: "+statusCode);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)
            System.out.println("Status code: "+statusCode);
            System.out.println("Failure - JSONObj");
        }
        /*
        @Override
        public void onRetry(int retryNo) {
            // called when request is retried
            System.out.println("Retry No: "+retryNo);
        }*/
    });
}

What wrong I am doing? The URL I am using is correct and also the port.
Thank you in advance.


text:
Q: SQL Server version problem when database restore
Possible Duplicate:
Sql server version problem when database restore

I would like to restore a database, but I get follow error message:

the database backup on a server
  running version 10.50.1600 that
  version incompatible with this server
  which is running version 10.00.4000

What should I do to update my SQL Server 2008 to this version?
I have already installed service packs 1 & 2 for SQL Server. But the restore of the database still doesn't work.

A: *

*Your backup is from SQL Server 2008 R2 (version 10.5)

*You are trying to restore onto SQL Server 2008 (version 10.0)

It can't be done
You'll need to:

*

*upgrade target server to SQL Server 2008 R2

*use SSIS to migrate the schema and data

*use SSMS wizards to migrate the schema and data


text:
Q: if $C$ is a filtered coalgebra, does Gr($B\Omega C)\backsimeq B\Omega ($Gr $C)$ hold? I have heard that under some assumptions, the functor 'Gr' from filtered graded objects with exhaustive filtration to graded objects $X\rightarrow$ Gr$(X)$ commutes with direct sums (this seems to be clear) and tensor products. If so, the question on the title is solved. Can anybody please tell me an example of such assumptions so that this properties are true?. Above all for tensor products, I mean, when does Gr$(X^{\otimes j})\backsimeq$ $($Gr$(X))^{\otimes j}$ hold?.

A: The claim is obvious if you are working with vector spaces: If you have a filtered object $X = \bigcup X_{\leq n}$, then you can choose a basis of $X_{\leq 0}$, extend it to a basis of $X_{\leq 1}$, extend to a basis of $X_{\leq 2}$, and so on. Then this basis provides you a filtered isomorphism $X \cong \mathrm{gr}X$, and moreover provides an isomorphism $\mathrm{gr}(X\otimes Y) \cong \mathrm{gr}X \otimes \mathrm{gr}Y$. Finally, you can check directly that the latter isomorphism actually doesn't depend on the choice of basis, and so is a natural isomorphism, and makes $\mathrm{gr}$ into a symmetric monoidal functor.
If you don't have access to bases, the claim can fail. Consider the category of filtered abelian groups. Set $X = \mathbb{Z}/4$, with its filtration $X_{\leq 0} = \{0,2\} \subset X_{\leq 1} = X = \{0,1,2,3\}$. Then $X \otimes X \cong \mathbb{Z}/4$ with some filtration. But $\mathrm{gr}X = \mathbb{Z}/2 \oplus \mathbb{Z}/2$, with the first summand in degree $0$ and the second summand in degree $1$, and so $\mathrm{gr}X \otimes \mathrm{gr}X = \mathbb{Z}/2 \oplus (\mathbb{Z}/2)^2 \oplus \mathbb{Z}/2$, supported in degrees $0,1,2$.


text:
Q: Is it possible to change language? I've got a Nintendo 2DS system and Pokémon X. I now have a nice progress in the game, but I'm playing in German localization.
As I'm keen on playing competitive online, I also experience that most of the up-to-date sites are English written. No problem, but it's always a pain the Froslass to look for attack, item and miscellanious names in German.
I read in the interwebs that changing the language is only possible with wiping the game data. I would like to avoid this.
Is there a way to change the language of the Pokémon X/Y module without erasing the game data?

A: You can't change the language after you start the game. If you want to change the language, you will have to erase your save data and start over from scratch.

A: No, when you start the game, he shows a warning for you about this.

A: You can't, unless you have a Powersave Action Replay system. It's about $20 and there is a code on there that will change the language of your game. However, I don't know if it will change any foreign named Pokemon in your boxes, but it will change the attacks and items to the English version if you do choose English.


text:
Q: Is composer available as a set of PHP scripts? I haven't found any way of installing composer on my shared hosting. I don't understand the insistence of using a phar, surely composer could comfortably be ported to plain PHP scripts? Is there such a port? Or a way of achieving the same?

A: A phar file is a PHP archive. So download the composer file locally and upload them to your server. You need only a PHP-Interpreter installed on your CLI.
Then you can run them php composer.phar or without PHP if your host is correctly configured.
http://php.net/manual/de/phar.using.intro.php
https://getcomposer.org/download/
Normally you can install composer with the given command on the composer site.
php -r "readfile('https://getcomposer.org/installer');" | php


text:
Q: Wolfram Language kernel not visible in VSCode I want to use the Wolfram Language with Jupyter notebooks, and VSCode is the application of my choice. I did all the procedure to generated a WolframLanguage kernel for Jupyter.
If I launch the Jupyter notebook from terminal by running jupyter notebook in my terminal, a Jupyter notebook opens in my browser and it shows the Wolfram kernel. These are the kernels returned by terminal.

They show up in the browser-version of Jupyter too.

Now I go to VS Code. I start a new Jupyter notebook by using the following command by using shift+command+P.
Create: New Jupyter Notebook

Now the kernel picker prompts me to choose kernels. Not only does it not have the WolframLanguage kernel, but it also shows completely different kernels from what were returned by the terminal.
Please guide me on how do I make my WolframLanguage kernel appear in my VS Code.
Thanks!!!


text:
Q: Why my tar.gz file was truncated in the process of transfer by ssh2_scp_send function? There is a file in my local pc.
ls -al /tmp/back.tar.gz
-rw-r--r-- 1 root root 11219553 Nov 29 23:13 /tmp/back.tar.gz

Let's upload the back.tar.gz with ssh2_scp_send into my remote vps.
<?php
    $vps_ip= 'xxxx';
    $port = 'yyyy';
    $user = 'root';
    $passwd = 'zzzz';
    $connection = ssh2_connect($vps_ip, $port);
    ssh2_auth_password($connection,$user,$passwd);
    ssh2_scp_send($connection,'/tmp/back.tar.gz','/home/back.tar.gz');
?>

Login into ssh with ssh -p yyyy root@xxxx to execute ls command in my vps.
ls  -al  /home/back.tar.gz
-rw-r--r-- 1 root root 11206656 Nov 29 10:10 /home/back.tar.gz

Where is the 12897 bytes left?
Now i upload the file /tmp/back.tar.gz  in my local pc into remote vps the second time,when the php program executed.
Login into ssh with ssh -p yyyy root@xxxx to execute ls command in my vps.
ls  -al  /home/back.tar.gz
-rw-r--r-- 1 root root 11219505 Nov 29 10:10 /home/back.tar.gz

I think that there is a bug in  ssh2_scp_send function ,it is unstable.
I have tested also with scp command for three times:
scp -P  $port root@$vps_ip:/home/back.tar.gz    /tmp

Login into ssh with ssh -p yyyy root@xxxx to execute ls command in my vps.
ls  -al  /home/back.tar.gz
-rw-r--r-- 1 root root 11219553 Nov 29 10:10 /home/back.tar.gz

It is my conclusion that some bug in ssh2_scp_send function.

A: Buffer works here.
ssh2_exec($connection, 'exit');

To write bytes in buffer before closing the connection.


text:
Q: What's the best way to validate currency input in UITextField? My application allows the user to enter a numeric value (currency) in a UITextField control, but the keyboard layout that I wish was available is unfortunately not one of the built-in options, so I had to choose the "Numbers & Punctuation" option in Interface Builder. Here's the corresponding dialog window in IB:

So when my application asks the user for the input, it is displaying the following:

Which is perfectly fine, but look at all of the extra keys available to the user! One could easily enter "12;56!" in the text field, and I assume I have to validate that somehow.
So my question is: how do I validate currency values entered into a UITextField?

A: Perhaps you could attach a UITextFieldDelegate on the control and have it implement textField:shouldChangeCharactersInRange:replacementString:  That way, if it sees any characters that you don't want in the field, it can reject them.

A: In conjunction with the textField:shouldChangeCharactersInRange:replacementString: suggestion made by Marc, you should pass the text through an NSNumberFormatter using an NSNumberFormatterCurrencyStyle. This will handle the quirks of currency formatting and handle locale specific options.
There's a "Data Formatting Programming Guide for Cocoa" section in the iPhone documentation if you search for it. Sadly, most of the UI information here is Mac OS X specific (doesnt work on iPhone) but it'll show you how to use the formatter classes.

A: I found that the shouldChangeCharactersInRange screws up the pop-up keyboard, backspace and "Done" button as well.  I found if I handled 0 length strings and allowed control characters though, it worked fine.
I don't like using NSNumberFormatter because it insists that the number is well-formed at all stages while the user is editing and that can be infuriating if you, say, want to have two decimal points in the number for a moment until you delete the one that's in the wrong spot.
Here's the code I used:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string length] < 1)    // non-visible characters are okay
        return YES;
    if ([string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]].length == 0)
        return YES;
    return ([string stringByTrimmingCharactersInSet:[self.characterSet invertedSet]].length > 0);
}

Where self.characterSet holds the characters that are acceptable, I used this method to create it for a currency:
- (NSCharacterSet *)createCurrencyCharacterSet
{
    NSLocale *locale = [NSLocale currentLocale];
    NSMutableCharacterSet *currencySet = [NSMutableCharacterSet decimalDigitCharacterSet];

    [currencySet addCharactersInString:@"-"];       // negative symbol, can't find a localised version
    [currencySet addCharactersInString:[locale objectForKey:NSLocaleCurrencySymbol]];
    [currencySet addCharactersInString:[locale objectForKey:NSLocaleGroupingSeparator]];
    [currencySet addCharactersInString:[locale objectForKey:NSLocaleDecimalSeparator]];

    return [[currencySet copy] autorelease];
}

The somewhat unhappy code [[currencySet copy] autorelease] returns an immutable NSCharacterSet.
Using [NSCharacterSet decimalDigitCharacterSet] also includes the Indic and Arabic equivalent characters which hopefully means that people use those languages can use their alphabet's digits to enter numbers.
It's still necessary to check that NSNumberFormatter can parse the user's input and alert if it can't; nonetheless, it makes a nicer experience when only legit characters can be entered.

A: I keep seeing that people don't know how to properly determine the resulting string when implementing shouldChangeCharactersInRange.
Here's how you get the new text that would be entered if you returned YES:
NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];

Once you have this new text, it's easy to check if that text is a valid number or not, and return YES or NO accordingly.
Keep in mind that all other solutions, such as those shown here, where one checks the length of "string", and such, may not work properly if the user tries to edit the string using a bluetooth keyboard with cursor keys or using the advanced editing features (select, cut, paste).

A: I have the urge to answer because this was the first entry I saw when I googled and the highest ranked answer wouldn't allow me to enter a currency.
I'm german, and in germany (and in many other countries) we use , as the decimalseparator.
I just wrote a similar method and this is what I have right now.
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    static NSString *numbers = @"0123456789";
    static NSString *numbersPeriod = @"01234567890.";
    static NSString *numbersComma = @"0123456789,";

    //NSLog(@"%d %d %@", range.location, range.length, string);
    if (range.length > 0 && [string length] == 0) {
        // enable delete
        return YES;
    }

    NSString *symbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
    if (range.location == 0 && [string isEqualToString:symbol]) {
        // decimalseparator should not be first
        return NO;
    }
    NSCharacterSet *characterSet;
    NSRange separatorRange = [textField.text rangeOfString:symbol];
    if (separatorRange.location == NSNotFound) {
        if ([symbol isEqualToString:@"."]) {
            characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbersPeriod] invertedSet];
        }
        else {
            characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbersComma] invertedSet];
        }
    }
    else {
        // allow 2 characters after the decimal separator
        if (range.location > (separatorRange.location + 2)) {
            return NO;
        }
        characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbers] invertedSet];
    }
    return ([[string stringByTrimmingCharactersInSet:characterSet] length] > 0);
}

A: While you can putz around in the NSNumberFormatter, I found it easier to just screen out anything but 0-9 and .
This is working well for me:

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];

return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);

}

A: If you want them to only be able to enter numbers - you might also consider the number keypad

A: After finding a quick solution on stack overflow to handle US currency, I rewrote the function to safely handle international currencies as well.  This solution will dynamically validate user input from a UITextField, correcting as they type.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

   NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];

   [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
   [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
   [numberFormatter setMaximumFractionDigits:2];
   [numberFormatter setMinimumFractionDigits:0];

    // Grab the contents of the text field
    NSString *text = [textField text];

    // the appropriate decimalSeperator and currencySymbol for the current locale
    // can be found with help of the
    // NSNumberFormatter and NSLocale classes.
    NSString *decimalSeperator = numberFormatter.decimalSeparator;
    NSString *currencySymbol = numberFormatter.currencySymbol;

    NSString *replacementText = [text stringByReplacingCharactersInRange:range withString:string];
    NSMutableString *newReplacement = [[ NSMutableString alloc ] initWithString:replacementText];

    // whenever a decimalSeperator or currencySymobol is entered, we'll just update the textField.
    // whenever other chars are entered, we'll calculate the new number and update the textField accordingly.
    // If the number can't be computed, we ignore the new input.
    NSRange decimalRange = [text rangeOfString:decimalSeperator];
    if ([string isEqualToString:decimalSeperator] == YES &&
        [text rangeOfString:decimalSeperator].length == 0) {
        [textField setText:newReplacement];
    } else if([string isEqualToString:currencySymbol] == YES&&
              [text rangeOfString:currencySymbol].length == 0) {
        [textField setText:newReplacement];
    } else if([newReplacement isEqualToString:currencySymbol] == YES) {
        return YES;
    }else {

        NSString *currencyGroupingSeparator = numberFormatter.currencyGroupingSeparator;

        [newReplacement replaceOccurrencesOfString:currencyGroupingSeparator withString:@"" options:NSBackwardsSearch range:NSMakeRange(0, [newReplacement length])];
        [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

        NSNumber *number = [numberFormatter numberFromString:newReplacement];

        if([newReplacement length] == 1) {
            [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
            number = [numberFormatter numberFromString:newReplacement];
        }

        if (number == nil) {
            [newReplacement release];
            return NO;
        }
        [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
        text = [numberFormatter stringFromNumber:number];
        [textField setText:text];
    }

    [newReplacement release];

    return NO; // we return NO because we have manually edited the textField contents.
}

A: I found this to be a relatively clean approach. I haven't tested it with non-US currencies but since it uses the NSNumberFormatter's properties I believe it should handle them correctly.
Start by setting up a formatter some place:
    formatter = [NSNumberFormatter new];
    [formatter setNumberStyle: NSNumberFormatterCurrencyStyle];
    [formatter setLenient:YES];
    [formatter setGeneratesDecimalNumbers:YES];

Use the formatter to parse and reformat their input. It also handles shifting the number when digits are added and removed.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *replaced = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSDecimalNumber *amount = (NSDecimalNumber*) [formatter numberFromString:replaced];
    if (amount == nil) {
        // Something screwed up the parsing. Probably an alpha character.
        return NO;
    }
    // If the field is empty (the initial case) the number should be shifted to
    // start in the right most decimal place.
    short powerOf10 = 0;
    if ([textField.text isEqualToString:@""]) {
        powerOf10 = -formatter.maximumFractionDigits;
    }
    // If the edit point is to the right of the decimal point we need to do
    // some shifting.
    else if (range.location + formatter.maximumFractionDigits >= textField.text.length) {
        // If there's a range of text selected, it'll delete part of the number
        // so shift it back to the right.
        if (range.length) {
            powerOf10 = -range.length;
        }
        // Otherwise they're adding this many characters so shift left.
        else {
            powerOf10 = [string length];
        }
    }
    amount = [amount decimalNumberByMultiplyingByPowerOf10:powerOf10];

    // Replace the value and then cancel this change.
    textField.text = [formatter stringFromNumber:amount];
    return NO;
}

A: Using an NSNumberFormatter is the correct answer. It will handle validation and converting the string to and from the correct object type.

A: You can also use Gamma-Point solution and evaluate if *aNumber is Nil, if its Nil, then it means a character that wasnt 0-9 . or , was entered, this way you can validate just numbers, it will nil the variable if any no-number char is entered.

A: I Couldn't find the appropriate implementation for currency validate. Here is my variant:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

   NSString* proposedString = [textField.text stringByReplacingCharactersInRange:range withString:string];

   //if there is empty string return YES
   if([proposedString length] == 0) {
       return YES;
   }

   //create inverted set for appripriate symbols
   NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789.,"] invertedSet];

   //if side symbols is trimmed by nonNumberSet - return NO
   if([proposedString stringByTrimmingCharactersInSet:nonNumberSet].length != [proposedString length]) {
       return NO;
   }

   //if there is more than 1 symbol of '.' or ',' return NO
   if([[proposedString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@".,"]] count] > 2) {
      return NO;
   }

   //finally check is ok, return YES
   return YES;
}

A: Using    shouldChangeCharactersInRange screws up the pop-up key board as the backspace button doesn't work.
Number formatter is the way to go. Here's a sample I used to find positive decimals. I call it  during the validation check- for e.g. when the user clicks on the save button.
    -(BOOL) isPositiveNumber: (NSString *) numberString {

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

    NSNumber *aNumber  =  [numberFormatter numberFromString:numberString];
    [numberFormatter release];

    if ([aNumber floatValue] > 0) {
        NSLog( @"Found positive number %4.2f",[aNumber floatValue] );

        return YES;
    }
    else {
        return NO;
    }
}


text:
Q: android send action_call from broadcastreceiver i want to forward all phone calls after receive a sms , so i have to using broadcastreceiver to listen incoming sms , this is my code :
public class SMSListiner extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equalsIgnoreCase("android.provider.Telephony.SMS_RECEIVED")) {
        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Uri.encode("*21*02164371348#")));
        callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(callIntent);
    }}

and this is manifest
`
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.arash.SMSListiner">
    <uses-sdk android:minSdkVersion="10"/>
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"></action>
                <action android:name="android.intent.category.LAUNCHER"></action>
            </intent-filter>
        </activity>
        <receiver android:name=".SMSListiner">
            <intent-filter android:priority="999">
                <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
                <action android:name="android.intent.action.BOOT_COMPLETED"></action>
            </intent-filter>
        </receiver>
    </application>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
    <uses-permission android:name="android.permission.READ_SMS"></uses-permission>
    <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
    <uses-permission android:name="android.permission.BROADCAST_SMS"></uses-permission>
    <uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />

</manifest>

`
call is sent but i have an error :
"call forwarding , connection problem or invalid MMI Code"
but when i try this code to send action_call in activity i have no problem and it work correctly ,
any idea ?


text:
Q: Which files should be commited in SVN for an Angular project? creating a project based on Angular as the frontend results on many automatically generated files. I would like to commit the project into SVN including the necessary files only.
Below is the current frontend folders structure:

Which files/folders should be commited in SVN ?

A: Indeed as mentioned by Robert and Stepan, the following folders could/should be ignored:

*

*node

*node_modules

*dist


text:
Q: Which layer to handle response code decision in Clean Architecture Currently implementing Clean Architure using MediatR with
     IRequestHandler<IRequest<ResponseMessage>, ResponseMessage>
     IRequest<ResponseMessage>

The implementation now separates between business logic layer, infrastructure and controller and they rely on dependency injection and decoupled.
Currently the implementation is in Asp.Net Core and this framework supports response code generation done in controller as example below.
    [HttpGet]
    [ProducesResponseType(200)]
    [ProducesResponseType(404)]
    public async Task<IActionResult> GetObject([FromQuery] int Id)
    {
      ...
      return Ok(some_result_to_show);   // This generates code 200
    }

I wonder where in Clean Architecture layer should translate business rule decisions made into correct response codes and what would be good practice or set methodology doing this adaption.
Seems quick implementation would be still doing it in controller however wonder if this decision belongs to business rules or application business rules and should be handled in different layer before translating into response code in presentation layer.
If then Asp.Net core or MediatR (or any other library) has in-built framework or features to support such design.

A: One way I found is as below
In the business layer,
  RequestMessageValidator : AbstractValidator<RequestMessage>
  {
     RuleFor(r => r).{ConditionSyntax}().WithErrorCode(ResponseCodeString);
  }

Then in the controller,
  return StatusCode(
                Convert.ToInt32(ValidationResult.Errors[0].ErrorCode),
                ValidationResult.Errors[0].ErrorMessage);

A: It is definitely the application / presentation layer which is MVC or your controllers. I would suggest you to throw specific exceptions that serve only one purpose.
For instance when you query data you will have a request-handler that looks for the data that should be found using a given id (a guid, or whatever). Now that identifier is valid but it is none existence on your database. You don't want to access the httpcontext (even though you could) in your handler because than your businesslogic would be coupled to asp.net. Throw an exception that tells you, that a resource was not found to produce a 404 error response (let's call it ResourceNotFoundException i.e.). For that exception you can then use an exception-filter instead of data-annotation above your controller-endpoints. You can have many exception-filter. Each serves its own purpose.
If you do it like that, your businesslogic will be decoupled from any application / presentation layer and can easily be reused where ever you want.
If you want to see an example of how an exception-filter works, I've created a simple solution for that a while ago. You can find it here.
Not directly related to your question but instead of returning an IActionResult, you could also return a data-transfer-object when you want to send data to the client. It will also produce a Http.OK statuscode.


text:
Q: Create an On-touch expand ListView in android How to create a listview in android so that when I want to click on of the list items, it expand to show more details?

A: Just override the methods below
     setOnChildClickListener(ExpandableListView.OnChildClickListener onChildClickListener)
 setOnGroupClickListener(ExpandableListView.OnGroupClickListener onGroupClickListener)

This inside this, you can to whatever you need, when you click on child or group item

A: You can use the expandable list methods


text:
Q: Unable to detect letter C in tesseract using jQuery I am creating a pregnancy test site and using tesseract. I have created a layout using svg and trying to detect letter C and t but letter C is not detecting but T is detected.

Here is my OCR code. I am new in tesseract so I have developed this using multiple example.
<script src='https://unpkg.com/tesseract.js@2.1.5/dist/tesseract.min.js'></script> this is the package I am using.
Here is my code.
const doOCR = async () => {
    if (!streaming || foundDeviceRecord || scheduler.getNumWorkers()===0) {
        console.log("1");
        scheduler.terminate();
        return;
    }

    let imageData = canvasInputCtx.getImageData(0, videoHeight/2 - videoHeight*0.15, videoWidth, videoHeight/2+videoHeight*0.15)
    let newCan = document.createElement('canvas');
    newCan.width = videoWidth;
    newCan.height = (videoHeight/2 + videoHeight*0.15) - (videoHeight/2 - videoHeight*0.15);
    let newCtx = newCan.getContext('2d');
    newCtx.putImageData(imageData, 0, 0);

    // processDevice(newCan);
    const image_canvas = newCan;
    scheduler.addJob('recognize', image_canvas).then(function(resp) {
        if(foundDeviceRecord) {
            scheduler.terminate();
            return;
        }

        let termObjects = {};
        for (let i = 0; i < resp.data.words.length; i++) {
            let word = resp.data.words[i].text.toLowerCase();
            if(word === 'C' || word === 'T' || word === 'c' || word === 't'){
                console.log(word);
                termObjects[word] = resp.data.words[i].bbox;
            }
        }
        if (Object.keys(termObjects).length !== 2){
            $('.cls-4').css({'stroke': 'red', 'stroke-width': '0.16px', 'opacity': '1'});
            return;
        }
        // Identify response via opencv
        $('.cls-4').css({'stroke': 'green', 'stroke-width': '0.16px', 'opacity': '1'});
        getActiveState(image_canvas, termObjects).then( (state) => {
            console.log('Status Detected', state, Date.now());
            responses[state] = responses[state] + 1;

            let decision = decisionCalc();
            if (decision){
                console.log('Inference Complete', Date.now())
                console.log(decision);
                document.cookie = "Result:"+decision;
                console.log(document.cookie);
            }
        });
    }).finally(async () => {
        if(foundDeviceRecord) {
            console.log('Process finished | Queue length: ', scheduler.getQueueLen());
            scheduler.terminate();
        }
    });
}

I have added second picture as well. If by using only color detection in that specific area, we can bring the output, then too it will be great help. We can use opencv but I am not sure how to do that?


text:
Q: Installing time zone data on MariaDB 10.0 Yesterday, I set the time zone on our DB server (as explained here).  Doing so required using the mysql_tzinfo_to_sql executable.  Fortunately, this already existed on the server, and conversion of the time zone data went smoothly.
However, today I can see that our slave is generating the same error.  The problem is that the slave doesn't seem to have the mysql_tzinfo_to_sql executable.  apt-get tells me that it exists in these other packages:
root@slave:~# mysql_tzinfo_to_sql /usr/share/zoneinfo/|mysql -u root mysql
The program 'mysql_tzinfo_to_sql' can be found in the following packages:
 * mysql-server-5.5
 * mariadb-server-5.5
 * mysql-server-5.6
 * percona-xtradb-cluster-server-5.5
Try: apt-get install <selected package>

I'm concerned that installing one of these (probably would choose mariadb-server-5.5) would conflict with our currently-installed version of MariaDB (10.0.17-MariaDB-1~precise-log).
How should I go about installing this time zone data on the slave?

*

*Can it be easily copied over from the master's DB?

*Is my concern about installing mariadb-server-5.5 unwarranted?

*Is there a totally different approach I'm missing?

A:
I'm concerned that installing one of these (probably would choose mariadb-server-5.5) would conflict with our currently-installed version of MariaDB (10.0.17-MariaDB-1~precise-log).

Ubuntu Precise was released 12.04. It's super ridiculous old, and it was when you asked the question. That's why the version of MariaDB was so old too. MariaDB dropped support for precise in 10.0.31. Because you're running on an unofficial in Debian/Ubuntu's eyes version of MariaDB, it's not guaranteed to work with the system.
All of that said, the question is essentially who packaged your MariaDB. It seems likely you got it from MariaDB upstream. So while you have a workaround, the question is better phrased like this

*

*Where does MariaDB install mysql_tzinfo_to_sql?

Clearly it's not in your path, you can find it by

*

*running the package you downloaded through dpkg -c.

*using apt-file

*Running: sudo updatedb; locate mysql_tzinfo_to_sql;

A: I figured out a solution.  The key to this solution is that I already had a system (the master) that I knew I could generate the timezone SQL on.  I simply generated the SQL on the master, transferred it to the slave, and executed it!
On Master
user@master [~]# mysql_tzinfo_to_sql /usr/share/zoneinfo/ > timezones.sql

On Slave
root@slave:~# scp -P2223 user@master:timezones.sql .
user@master's password:
stdin: is not a tty
timezones.sql                                                                                100% 4562KB   2.2MB/s   00:02
root@slave:~# cat timezones.sql | mysql -u root mysql

After executing START SLAVE on the slave, everything worked great!
Still curious if someone has answers to the questions I posed originally, though!


text:
Q: How to redirect data to a particular page using url in c#? I am working on jQuery fileupload now here I am saving images once saved some data I need to post to my page
Here I have two applications (two separate applications) html.page to I am posting images to mvc upload controller and I had saved the image success fully
Now to get the respose data I need to redirect through url so I am redirecting through like this
 public void ReturnResult(string jsonObj)
       {

           var hostName = " http://localhost:8988/cors/postmessage.html?MyURL=";
           var s = jsonObj;
           var filterUrl = hostName + s;
           HttpContext.Current.Response.Redirect(filterUrl);

       }

Once redirection to this page how could I get those data?
And I don't have any idea is this redirecting the data or not how could could I know that
data is redirecting or not could u plz help me get the data
this is my
redirected to  this  page
       <!DOCTYPE HTML>

<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery File Upload Plugin postMessage API</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script>

    'use strict';

    var origin = /^http:\/\/example.org/,
//var origin = 'http://localhost:4071/Upload/UploadHandler.ashx',
    target = new RegExp('^(http(s)?:)?\\/\\/' + location.host + '\\/');
    alert(1);
    alert(origin);
$(window).on('message', function (e) {
    e = e.originalEvent;
    var s = e.data,
        xhr = $.ajaxSettings.xhr(),
        f;
    if (!origin.test(e.origin)) {
        throw new Error('Origin "' + e.origin + '" does not match ' + origin);
    }
    if (!target.test(e.data.url)) {
        throw new Error('Target "' + e.data.url + '" does not match ' + target);
    }
    $(xhr.upload).on('progress', function (ev) {
        ev = ev.originalEvent;
        e.source.postMessage({
            id: s.id,
            type: ev.type,
            timeStamp: ev.timeStamp,
            lengthComputable: ev.lengthComputable,
            loaded: ev.loaded,
            total: ev.total
        }, e.origin);
    });
    s.xhr = function () {
        return xhr;
    };
    if (!(s.data instanceof Blob)) {
        f = new FormData();
        $.each(s.data, function (i, v) {
            f.append(v.name, v.value);
        });
        s.data = f;
    }
    $.ajax(s).always(function (result, statusText, jqXHR) {
        if (!jqXHR.done) {
            jqXHR = result;
            result = null;
        }
        e.source.postMessage({
            id: s.id,
            status: jqXHR.status,
            statusText: statusText,
            result: result,
            headers: jqXHR.getAllResponseHeaders()
        }, e.origin);
    });
});
</script>
</body>
</html>

Any help will greately appreciated thanks in advance

A: If you need to get data from the query string returned from the controller in your HTML page then you can use this function.
function getUrlVars() {
                var vars = [], hash;
                var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                for (var i = 0; i < hashes.length; i++) {
                    hash = hashes[i].split('=');
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
                }
                return vars;
            }

you can get you values on page load like:
var MyURL= getUrlVars()['MyURL'];


text:
Q: Http request without verifying SSL Certificate I'm trying to fetch the data from this API and I was getting a SSL Certificate error and found this solution, but the I don't know if this is the best solution for handling this, is there a better way instead of using withoutVerifying() in this case? My code:
Route::get('/test', function () {

    $response = Http::withoutVerifying()->get('https://api.coingecko.com/api/v3/coins/bitcoin');

    return $response;
});

A: Then use SSL on your server. That's the best way.


text:
Q: Go back 'n' lines in file using Stream.lines I need to build an application which scans through a large amount of files. These files contain blocks with some data about a sessions, in which each line has a different value. E.g.: "=ID: 39487".
At that point I have that line, but the problem I now face is that I need the value n lines above that ID. I was thinking about an Iterator but it only has forward methods. I also thought about saving the results in a List but that defies the reason to use Stream and some files are huge so that would cause memory problems.
I was wondering if something like this is possible using the Stream API (Files)? Or perhaps a better question, is there a better way to approach this?
Stream<String> lines = Files.lines(Paths.get(file.getName()));
Iterator<String> search = lines.iterator();

A: You can't arbitrarily read backwards and forwards through the file with the same reader (no matter if you're using streams, iterators, or a plain BufferedReader.)
If you need:

*

*m lines before a given line

*n lines after the given line

*You don't know the value of m and n in advance, until you reach that line

...then you essentially have three options:

*

*Read the whole file once, keep it in memory, and then your task is trivial (but this uses the most memory.)

*Read the whole file once, mark the line numbers that you need, then do a second pass where you extract the lines you require.

*Read the whole file once, storing some form of metadata about line lengths as you go, then use a RandomAccessFile to extract the specific bits you need without having to read the whole file again.

I'd suggest given the files are huge, the second option here is probably the most realistic. The third will probably give you better performance, but will require much more in the way of development effort.
As an alternative if you can guarantee that both n and m are below a certain value, and that value is a reasonable size - you could also just keep a certain number of lines in a buffer as you're processing the file, and read through that buffer when you need to read lines "backwards".

A: Try my library. abacus-util
try(Reader reader = new FileReader(yourFile)) {
    StreamEx.of(reader)
        .sliding(n, n, ArrayList::new)
        .filter(l -> l.get(l.size() - 1).contains("=ID: 39487"))
        ./* then do your work */
}

No matter how big your file is. as long as n is small number, not millions


text:
Q: Incorrect shipping calculation in Magento I have a Magento site which uses the webshopapps matrixrates plugin for shipping rates.
The shipping cost doesn't seem to be calculating correctly and appears to apply a discount to the product cost.
In the screenshot below, the basket contains one product that has a price of €30, the shipping option 'European Airmail' (€5.50) has been selected.
Therefore the total cost should be €35.50
However the cost comes out at €30.55.
It's almost as if the Delivery cost is subtracted from the total (ignoring euro cents)
Interestingly there are two instances of this site, the UK instance appears to work correctly but I can't find anything different in the config.

I've tried comparing a CSV export of shipping rates but can't see anything obviously different.
What do I need to do to get the cost to come out as the correct amount (€35.50)?
Any suggestions welcome!
EDIT
If I dump out the quote object, the price for the product shows up as 25

But if I just load the product and dump it's data, I get the actual price which is €30:

I've got the tax amount with:

<?php

$taxAmount = $quote->getShippingAddress()->getData('tax_amount');

?>

And that comes back as 0.000
So I'm at a bit of a loss as to what is going on here.

A: Got to the bottom of this, it was a catalogue price rule for free shipping upto 4.95..
I had removed all shopping cart price rules already but wasnt aware that anyone had created a catalogue price rule so didnt consider it. Thanks for the suggestions guys.


text:
Q: Why does stmfd/ldmfd jump back to sub? I am doing a project for UNI and have a problem.
We are learning how to push/pop registers onto stack when calling a subroutine.
I need to write a subroutine to convert a decimal number 0-15 into a corresponding hex ASCII code, and keep the value of all registers except r0, where the result should be stored. I have a table of ASCII codes, and basically just add the number*4 to the starting address of the ASCII table, and store the value back into r0.
I get the right result, but the subroutine loops. It keeps jumping from ldmfd to sub endlessly. Any idea why?
main:
adr r0,num
adr r1,ascii
ldr r2,[r0]
bl  sub
sub:  stmfd sp!,{r1-r2,lr}
      ldr r0,[r1,r2,LSL #2]
      ldmfd sp!,{r1-r2,pc}

/* variables here */
num:    .word 15
ascii:  .word 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x41,0x42,0x43,0x44,0x45,0x46
/* end variables */

A: There are a couple of issues with your code.

*

*The main code never returns anywhere, which means after your code returns from the sub it will start again at "sub:" because thats your return point. As lr did not change, it will be stuck in a loop between stmfd/ldmfd. You need to call the exit-function of your system.

*There is no reason to save r1, r2, lr. You're not changing them in your code, also r0-r3 and r12 are caller saved registers anyway.

A: Note that you have placed your subroutine directly following the instruction that calls it:
bl  sub
sub:  stmfd sp!,{r1-r2,lr}
      ldr r0,[r1,r2,LSL #2]
      ldmfd sp!,{r1-r2,pc}

So what happens when you return from the first call to sub? It will return to the instruction following the bl, i.e. the stmfd sp!,{r1-r2,lr}. So the subroutine effectively returns to the beginning of itself. And it will keep doing so because there are no additional implicit or explicit writes to lr.

A: I'm no ARM assembly expert, but I can at least read some local compiler output.
It seems gcc prefers not to store lr on the stack (which makes sense, the point of the register is to avoid stack access when possible).
Instead, subroutines end by doing a branch on the link register:
bx  lr

Note: it seems the bx (branch exchange) instruction is only available on Thumb-capable processors, so perhaps it doesn't apply for you then.


text:
Q: не отправляется сообщение в телеграм боте Я создаю бота для телеги и когда отправляю начальное сообщение нечего не происходит
вот код
import COVID19Py
import telebot

covid19 = COVID19Py.COVID19()
bot = telebot.TeleBot('')

@bot.message_handler(commands=['start'])
def start(message):
    send_mess = f"<b>Привет {message.from_user.first_name}!</b>\nВведите страну"
    bot.send_message(message.chat.id, send_mess, parse_mode='html')

bot.polling(none_stop=True)

вроде бы всё правильно, но вот результат

A: У меня все работает с моим токеном, но  только с VPN.
Попробуйте обновить telebot и pyTelegrammBotApi(pip install pyTelegramBotAPI)


text:
Q: How to convert selection in JavaFX ComboBox to String I have a form which is to be submitted to a mySQL database, where one of the inputs is a ComboBox (JavaFX).
When submitting the input from the ComboBox, the value added to the database is
"ComboBox[id=rolePicker, styleClass=combo-box-base combo-box]"

not a String value.
How can I solve this issue, so that the data submitted to the database is a String of the value selected?
(Partial) JAVA Controller Code:
public class NewUserController implements Initializable, ControlledScreen {

    @FXML
    TextField nameField;
    @FXML
    TextField usernameField;
    @FXML
    TextField emailField;
    @FXML
    ComboBox rolePicker;

    @FXML
    public void submitUser(ActionEvent event) {
        String dbUsername = "root";
        String dbPassword = "secret";
        String dbURL = "jdbc:mysql://localhost:3306/uia";

        try {
            Connection conn = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
            Statement statement = (Statement) conn.createStatement();
            statement.execute("INSERT INTO user (name, username, password, email, userrole) VALUES ('" + nameField.getText() + "', '" + usernameField.getText() + "', '" + usernameField.getText() + "', '" + emailField.getText() + "', '" + rolePicker + "');");

        } catch (SQLException e) {
            System.out.println(e);
        }
    }

(Partial) FXML Code:
<ComboBox id="rolePicker" fx:id="rolePicker" editable="true" maxHeight="25.0" maxWidth="225.0" minHeight="25.0" minWidth="225.0" prefHeight="25.0" prefWidth="225.0" promptText="Role.." visibleRowCount="4">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="TEACHER" />
            <String fx:value="STUDENT" />
        </FXCollections>
    </items>
</ComboBox>

A: On the following line you use rolePicker in a string expression, therefore the compiler will call the toString() method on this object to get the string representation of the object, that causes the mentioned output:
statement.execute("INSERT INTO user (name, username, password, email, userrole) VALUES ('" +
nameField.getText() + "', '" + usernameField.getText() + "', '" + usernameField.getText() + "', '" + emailField.getText() +
"', '" + rolePicker + "');");

You should get the selected value of the ComboBox with getValue method:
rolePicker.getValue();

and you can use the returned value in the expression.
Note: getValue will return the type which type the ComboBox has as generic parameter (the type of the items stored in the ComboBox): public final T getValue(). In your current situation you have a ComboBox that stores String values (ComboBox<String>), therefore the returned value can be used directly.


text:
Q: Port AngularJS Web Application to Windows Phone8 I'm developing web application using AngularJS and jQuery and use Node.JS as web server.
I found the video from Microsoft that we can port web application to Windows Phone 8 as HTML5 app easily just copy and past code to Visual Studio but it cannot be run in both emulator and device.
I'm still confuse that it can be worked? Because my web cannot run as static without using Node.JS but I've tried making static web and port into Windows Phone.... It works!!
I would like to know how can I port the my current web app into Windows Phone? Do I need to install Node.JS into there? (I'm kidding....)
Thanks to advice :)


text:
Q: Using $index for ng-model I am building a SPA where one can add a table-row on button-click:

    Lieferscheinnummer
    Stück

    <input type="text">
    <input type="text">

Controller
$scope.positions = ['1'];
$scope.addPosition = function(){
    $scope.positions.push( $scope.positions.length + 1 );
}

Now I have to apply an unique ng-model to each  of every row in order to send the given input to my database.
I searched for a solution and stumbled over ng-repeat's $index.
Unfortunately, $index seems to be not available for element attributes:

    <input type="text" ng-model="{{$index +1}}">
    <input type="text">

How would I apply an unique ng-model to each row while using ng-repeat?

A: You could change your model. Currently, you are using the ng-repeat like a counter. You have a model that stores the elements - you are not using the elements in anyway, just making use of the number of elements in the list and looping that many times.
What you could instead do is have a list of unique models itself.
Considering that you are using it inside a table, each entry could have an ID field to uniquely identify each row.
Thus, your model would look something like this:
//Will contain the data entered in the table
$scope.tableData = [
    {
        id: 1,
        data: ""
    },
    {
        id: 2,
        data: ""
    }
];

//Will keep track of the last used ID
$scope.currentId = 2;

//Will add a record to the table each time it is called
$scope.addRecord = function () {
    var newRecord = {
        id: $scope.currentId++;
        data: ""
    };
    $scope.tableData.push(newRecord);
};

In your view, you can now use tableData to loop over the actual data itself rather than the count of the records:

        <input type="text" ng-model="entry.data">

For another input, you could simply add another attribute to each record. ng-repeat will create a scope for each record so entry.data will always point to the data attribute for the record located at that row.
Note: For an ID, you may have to use another approach of generating unique Ids for large amounts of records. Simply increment a counter will not be the best approach.


text:
Q: C# float to decimal conversion Any smart way to convert a float like this:
float f = 711989.98f;

into a decimal (or double) without losing precision?
I've tried:
decimal d = (decimal)f;
decimal d1 = (decimal)(Math.Round(f,2));
decimal d2 = Convert.ToDecimal(f);

A: This may be a compiler bug because it seems like a valid float should convert directly to a decimal. but it wont without losing resolution.
Converting 125.609375 from float to decimal will lose resolution.
However, converting it from float to double and then double to decimal will keep resolution.
    float float_val = 125.609375f;

    decimal bad_decimal_val = (decimal)float_val;   //125.6094

    double double_val = (double)float_val;
    decimal good_decimal_val = (decimal)double_val;

A: have you tried?
decimal.TryParse()

http://forums.asp.net/t/1161880.aspx

There are no implicit conversions between float/double and decimal. Implicit numeric conversions are always guaranteed to be without loss of precision or magnitude and will not cause an exception.

A: You lost precision the moment you've written 711989.98f.
711989.98 is decimal. With f in the end you are asking the compiler to convert it to float. This conversion cannot be done without losing precision.
What you probably want is decimal d = 711989.98m. This will not lose precision.

A: It's too late, the 8th digit was lost in the compiler.  The float type can store only 7 significant digits.  You'll have to rewrite the code, assigning to double or decimal will of course solve the problem.

A: try this
float y = 20;

decimal x = Convert.ToDecimal(y/100);

print("test: " + x);


text:
Q: Update other models field when new record adds I am working on Question-Answer Website.
In that i want to mark Question hasAnswered whenever new Answer adds for that question.
Question Model
class Question(models.Model):

    question = models.CharField(max_length=400)
    uid = models.ForeignKey("User",on_delete=models.SET_DEFAULT,default=1,related_name='user_q_id_set')
    vote = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    catitle = models.ForeignKey("Category", on_delete=models.CASCADE)
    editUser = models.ManyToManyField("User",related_name='user_q_edit_set',null=True,blank=True)
    hasAnswer = models.BooleanField(default=False)

Answer Model
class Answer(models.Model):
    answer = models.TextField()
    qid = models.ManyToManyField("Question")
    uid = models.ForeignKey("User",on_delete=models.CASCADE,related_name='user_a_id_set')
    vote = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    editUser = models.ManyToManyField("User",related_name='user_a_edit_set',null=True,blank=True)

    class Meta:
        ordering = ['-vote']

    def save(self,*args, **kwargs):
        self.qid.hasAnswer=True

This is what i tried but got error
ValueError at /admin/qa/answer/add/
"<Answer: None>" needs to have a value for field "id" before this many-to-many relationship can be used.

So how i get change hasAnswer to True whenever new Answer Adds ?

A: Instead of having a field like Question.hasAnswer you could rather use a property for that relation:
class Question(models.Model):
    ...
    @property
    def has_answer(self):
        return self.answers.exists()

class Answer(models.Model):
    ...
    questions = models.ManyToManyField("Question", related_name="answers")
    ...

A: the problem is that, when you try to reach questions there is no data, since first of all question entry should be created in db and then m2m relationship fields should attach. I think, the solution is to use signals - specifically m2m_changed, where action would be post_add.
On the other hand, if you would like to get rid of Question.hasAnswer field. For question model, you can use cached_property to check if question has answers, like that:
class Question(models.Model):
    ...
    @cached_property
    def has_answer(self):
        return self.answer_set.exists()


text:
Q: Sign ambiguity when going from position to momentum space evaluating Feynman diagrams When calculating a simple diagram I came across an ambiguity in the conservation of momentum, i.e. it seems to me that the particle could come out of the process with opposite momentum with respect to its initial state. This might be a complete triviality, in that case I apologize, but I can't find my mistake. Take the following Feynman diagram in $\lambda \phi^4$ theory
Call $x$ and $y$ the two external points, $z_1$ and $z_2$ the two internal points. Using Feynman's rules in position space this is proportional to the integral
$$\int dz_1 dz_2 D_F(x-z_1)D_F(z_1-z_2)^2D_F(z_2-z_2)D_F(z_1-y) $$
Where $D_F$ is the Feynman propagator of the Klein Gordon field
$$ D_F(x-y)=\int\frac{d^4p}{(2\pi^4)}\frac{i}{p^2-m^2+i\varepsilon}e^{-ip(x-y)}$$
Inserting this into the diagram, and writing $dq=\frac{d^4p_x}{(2\pi)^4}\frac{d^4p_y}{(2\pi)^4}\frac{d^4p_1}{(2\pi)^4}\frac{d^4p_2}{(2\pi)^4}\frac{d^4p_3}{(2\pi)^4}$ for the sake of brevity
$$ \int dz_1 dz_2 D_F(x-z_1)D_F(z_1-z_2)^2D_F(z_2-z_2)D_F(z_2-y)=\\=\int dz_1 dz_2 \int dq
\frac{e^{-ip_x(x-z_1)}}{p_x^2-m^2+i\varepsilon}\frac{e^{-ip_1(z_1-z_2)}}{p_1^2-m^2+i\varepsilon}\frac{e^{-ip_2(z_1-z_2)}}{p_2^2-m^2+i\varepsilon}\frac{1}{p_3^2-m^2+i\varepsilon}\frac{e^{-ip_y(z_1-y)}}{p_y^2-m^2+i\varepsilon}=\\=\int dz_1 dz_2 \int dq
\frac{e^{-iz_1(-p_x+p_1+p_2+p_y)}}{p_x^2-m^2+i\varepsilon}\frac{e^{-iz_2(-p_1-p_2)}}{p_1^2-m^2+i\varepsilon}\frac{e^{-i(p_x x-p_y y)}}{p_2^2-m^2+i\varepsilon}\frac{1}{p_3^2-m^2+i\varepsilon}\frac{1}{p_y^2-m^2+i\varepsilon}
$$
The momenta in the exponentials are gonna give $$ \delta^{(4)}(p_x-p_1-p_2-p_y)\delta^{(4)}(p_1+p_2)$$
Which implies conservation of momentum, and everyone is happy. But let's get back to the first expression of the integral, where I wrote
$$\int dz_1 dz_2 D_F(x-z_1)D_F(z_1-z_2)^2D_F(z_2-z_2)D_F(z_1-y) $$
I could have written
$$\int dz_1 dz_2 D_F(x-z_1)D_F(z_1-z_2)^2D_F(z_2-z_2)D_F(\color{red}{y-z_1}) $$
because the propagator is symmetric. This seemingly harmless change changes the exponential that yields the delta in
$$ e^{-iz_1(-p_x+p_1+p_2-p_y)}$$
and the conservation of momentum will be
$$\delta^{(4)}(p_x-p_1-p_2 \color{red}{+p_y} )\delta^{(4)}(p_1+p_2)$$
which in the end implies $p_x=-p_y$, or, the particle comes out with opposite momentum, which seems weird to me. Have I made a mistake or is the sign of the momentum not important in some way?

A: Let's call the OP's diagram $\Sigma(x-y)$, which can be rewritten as
$$
\Sigma(x-y)=A\int dp_xdp_y \delta(p_x-p_y) e^{-i (p_x x-p_y y)}D_F(p_x)D_F(p_y),
$$
where $A$ is a constant which comes from the two loops contained in the diagram, and $D_F(p)=(p^2-m^2+i\epsilon)^{-1}$.
Playing the game of the second part of the question (i.e. replacing $D_F(z_1-y)$ by $D_F(y-z_1)$), we would end up with
$$
\Sigma(x-y)=A\int dp_xdp_y \delta(p_x+p_y) e^{-i (p_x x+p_y y)}D_F(p_x)D_F(p_y),
$$
which is obviously equivalent to the first expression, by the change of variable $p_y\to-p_y$. There is therefore no contradiction, and both way of doing the calculation are equivalent.
What confuses the OP is the question of momentum conservation, which looks strange in the second equation. This is because we should look at momentum conservation in momentum space (whereas we are still in real space here), i.e. we should compute
$ \Sigma(p_1,p_2)=\int dx dy e^{ip_1 x-ip_2 y}\Sigma(x-y)$.
Starting from either expression, we obtain
$$ \Sigma(p_1,p_2)=\delta(p_1-p_2) A D_F(p_1)D_F(p_2),$$
which obviously conserve momentum. One usually factors out the delta function and introduce the function $\Sigma(p)=A D_F(p)D_F(p)$ such that $\Sigma(p_x,p_y)=\delta(p_x-p_y)\Sigma(p_x)$.


text:
Q: Scraping data from a java generated webpage with R The Dutch government publicizes the subsidies it gives on a website:
http://www.hetlnvloket.nl/databank-eu-subsidiegegevens-2012#
However, it is not straighforward to get the data from the website. If you go to the site, choose 'Gemeenschappelijk Landbouw Beleid' (Common Agricultural Polici, the EU subsidy schedule) and press 'zoek' (zoek means 'search') at the bottom of the page you get a table from 100 entries. But I can't get it into R. It seems the page is generated with a JavaScript after you press 'zoek'.
My questions are:

*

*How do I scrape this from the website?

*How do I get the other 900 pages (there are a total of 90K records)
I asked the government to give me this data in XLS but they won't, for 'privacy reasons'. But this way nobody can check. I don't like that. ;-)

A: If you don't see the url change, the request is usually done via ajax, or via a post-request to the same page. In this case it is done via an ajax POST-request to a certain page with some parameters. To find out what page is loaded with what parameters, open your developer console. You can do so by right-clicking in most browsers and clicking 'inspect element', or by hitting F12. Go to the network tab and click the search button. You'll see a request in the network tab pop up. Inspect this request. You'll notice that this is a request to /pls/feed/glb2012. You can find the request parameters around there too.
As for the question "how" to scrape this. Use a programming language and your favorite scraping library. To suggest a library is out of the scope for StackOverflow.

A: Use a tool better suited for scraping than R.  For example, Scrapy or BeautifulSoup in python, Mojolicious or Web::Scraper in perl, ...  You want to scrape with a scraping tool, output data in csv (or something similarly standard), and then get it into R.
You need to figure out what the browser-server communication is exactly.  The data is probably not at the url you see when you go to that page.  A quick capture in Wireshark and look at the HTTP requests will show that.
It looks like, based on your level of experience (and likely, not wanting to learn new tools just for this) you probably want to have someone do it for you.  Post it on elance, make sure whoever does it has done a bunch of scraping projects, it should take only a couple of hours max.
If you do want to do it, then follow scraping tutorials and cookbook examples, but remember to check the actual communication in Wireshark as you do that.