text:
Q: Scanner For Console Input Error Given the following as console input:
F 6 100

I want the 6 to be assigned to the duration,  and the 100 assigned to speed:
if(command.equalsIgnoreCase("F"))
myf.setWheelVelocities(speed,speed,duration);

The above code does not seem to work, however. The full code is below: how do I correctly assign the console input to the setWheelVelocities method parameters of the Finch robot?
import edu.cmu.ri.createlab.terk.robot.finch.Finch;
import java.util.Scanner;
public class CS1810 {

    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        Finch myf = new Finch();

        // Welcome Message
        System.out.println("Welcome to Finch Robot Remote Navigation!!!");
        System.out.println();

        // Instructions
        System.out.println("Instructions on how to navigate and commands to be used:");
        System.out.println("To move forward type in 'F' followed by a space and then enter an integer representing 'duration' followed by a space and then enter an integer representing 'speed'.");
        System.out.println("To move left or right type in 'L' or 'R' followed by a space and then enter an integer representing 'duration' followed by a space and then an integer representing 'speedLeft' followed by a space and then an integer representing 'speedRight'.");
        System.out.println("To backtrack type in 'B' followed by a space and then enter an integer representing 'track' which is the number of commands you want to backtrack.");
        System.out.println("To stop the program type in 'S'.");
        System.out.println();

        // Rules
        System.out.println("Rules for commands and values entered:");
        System.out.println("You can only enter 'F,L,R,B and S' as commands.");
        System.out.println("You can only enter a 'duration' value which is less than or equal to 6.");
        System.out.println("You can only enter a 'speed','speedLeft' and 'speedRight' value between -100 and 100.");
        System.out.println("You can only enter a 'backtrack' value equal to or less than the number of commands you have entered before:");
        System.out.println();

        //Enter Command
        System.out.println("Enter your command below:");
        String command = ("");
        int duration = scan.nextInt();
        int speed = scan.nextInt();

        // Ignore Cases
        while((command.equalsIgnoreCase("F"))||(command.equalsIgnoreCase("L"))||(command.equalsIgnoreCase("R"))||(command.equalsIgnoreCase("B"))||(command.equalsIgnoreCase("S")))
        {
           if(command.equalsIgnoreCase("F"))
           myf.setWheelVelocities(speed,speed,duration);
           System.out.println("Enter a new command");
           command = scan.nextLine();
        }
        myf.quit();
     }
}

A: You have to split , and in this link provided is the answer how to split by whitespaces in strings :
How do I split a string with any whitespace chars as delimiters?


text:
Q: Does bounding mutual information restrict the defined meter? Suppose $I(X;Y)$ denotes mutual information and on the other hand there is a relationship as follows.
\begin{align}
|p(y)-p(y|x)|<\delta p(y),\qquad\forall x,y.
\end{align}
Then we can say about mutual information:
\begin{align}
I(X;Y)=\sum_{x,y}p(x,y)\log\frac{p(y|x)}{p(y)}\leq\sum_{x,y}p(x,y)\log\frac{(1+\delta)p(y)}{p(y)}=\log(1+\delta)\leq\delta.
\end{align}
Is the opposite true? That is, if mutual information is less than $\epsilon$, can it be said that there is a $\delta$ in which first relationship is established?

A: $\newcommand\ep\varepsilon$Of course not.
E.g., suppose that $P(X=0,Y=0)=t\ep$, $P(X=0,Y=1)=1/2-t\ep$, $P(X=1,Y=0)=(1-t)\ep$, and $P(X=1,Y=1)=1/2-(1-t)\ep$, where $t$ and $\ep$ are in the interval $(0,1)$. Then
$$I(X;Y)\sim c_t\ep\to0$$
as $\ep\downarrow0$, where $c_t:=\ln2+t\ln t+(1-t)\ln(1-t)$.
However, here $P(Y=0|X=0)=2t\ep$, which is not relatively close to $P(Y=0)=\ep$ if (say) $t=1/4$. (Or you can let $t\downarrow0$; then $c_t\to\ln2$.)

The idea of this counterexample is quite simple: it is to let the conditional probability mass function (pmf) of $Y$ given $X$ differ substantially from its unconditional pmf only on a set of values rather unlikely to be taken by $Y$. This will affect the mutual information only little.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to print the values of slices I want to see the values which are in the slice. How can I print them?
projects []Project

A: If you just want to see the values of an array without brackets, you can use a combination of fmt.Sprint() and strings.Trim()
a := []string{"a", "b"}
fmt.Print(strings.Trim(fmt.Sprint(a), "[]"))
fmt.Print(a)

Returns:
a b
[a b]

Be aware though that with this solution any leading brackets will be lost from the first value and any trailing brackets will be lost from the last value
a := []string{"[a]", "[b]"}
fmt.Print(strings.Trim(fmt.Sprint(a), "[]")
fmt.Print(a)

Returns:
a] [b
[[a] [b]]

For more info see the documentation for strings.Trim()

A: If you want to view the information in a slice in the same format that you'd use to type it in (something like ["one", "two", "three"]), here's a code example showing how to do that:
package main

import (
    "fmt"
    "strings"
)

func main() {
    test := []string{"one", "two", "three"}     // The slice of data
    semiformat := fmt.Sprintf("%q\n", test)     // Turn the slice into a string that looks like ["one" "two" "three"]
    tokens := strings.Split(semiformat, " ")    // Split this string by spaces
    fmt.Printf(strings.Join(tokens, ", "))      // Join the Slice together (that was split by spaces) with commas
}

Go Playground

A: I wrote a package named Pretty Slice. You can use it to visualize slices, and their backing arrays, etc.
package main

import pretty "github.com/inancgumus/prettyslice"

func main() {
    nums := []int{1, 9, 5, 6, 4, 8}
    odds := nums[:3]
    evens := nums[3:]

    nums[1], nums[3] = 9, 6
    pretty.Show("nums", nums)
    pretty.Show("odds : nums[:3]", odds)
    pretty.Show("evens: nums[3:]", evens)
}

This code is going produce and output like this one:

For more details, please read: https://github.com/inancgumus/prettyslice

A: For a []string, you can use strings.Join():
s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
// output: foo, bar, baz

A: fmt.Printf() is fine, but sometimes I like to use pretty print package.
import "github.com/kr/pretty"
pretty.Print(...)

A: You could use a for loop to print the []Project as shown in @VonC excellent answer.
package main

import "fmt"

type Project struct{ name string }

func main() {
    projects := []Project{{"p1"}, {"p2"}}
    for i := range projects {
        p := projects[i]
        fmt.Println(p.name) //p1, p2
    }
}

A: I prefer fmt.Printf("%+q", arr) which will print
["some" "values" "list"]

https://play.golang.org/p/XHfkENNQAKb

A: You can try the %v, %+v or %#v verbs of go fmt:
fmt.Printf("%v", projects)

If your array (or here slice) contains struct (like Project), you will see their details.
For more precision, you can use %#v to print the object using Go-syntax, as for a literal:
%v  the value in a default format.
    when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value

For basic types, fmt.Println(projects) is enough.

Note: for a slice of pointers, that is []*Project (instead of []Project), you are better off defining a String() method in order to display exactly what you want to see (or you will see only pointer address).
See this play.golang example.


text:
Q: QMap values as structs Let's say we have this sample:
struct test
{
    QString name;
    int count = 0;
};

QMap<QString,test> map;
test test1;
test1.name = "doc1";
map.insertMulti("pen",test1);

test test2;
test2.name = "doc2";

map.insertMulti("pen",test2);

if(map.contains("pen"))
{
    map.value("pen",test1).count++; // Here goes the error
  //map["pen"].count++; //works but increments count of last inserted struct
}

foreach (test value, map) {
    qDebug() << value.name << " " << value.count;
}

So what I am trying to do is check if key is already there then increment the count of the struct I need.
Please advise how to do this properly.

A: value() returns a constant value that can not be modified, instead You must use an iterator using the find() method:
struct Test{
    QString name;
    int count = 0;
};

QMultiMap<QString, Test> map;
Test test;
test.name = "doc1";
map.insert("pen", test);

if(map.contains("pen")){
    qDebug() << "before: " << map.value("pen").count;
    QMultiMap<QString, Test>::iterator it = map.find("pen");
    it->count += 10;
    qDebug() << "after: " << map.value("pen").count;
}

Output:
before:  0
after:  10

Update:
In the case of QMap you must use the operator [] that returns the reference of the stored value:
struct Test{
    QString name;
    int count = 0;
};

QMap<QString, Test> map;
Test test1;
test1.name = "doc1";
map.insertMulti("pen",test1);

Test test2;
test2.name = "doc2";
map.insertMulti("pen", test2);

if(map.contains("pen")){
    qDebug() << "before: " << map.value("pen").count;
    map["pen"].count++;
    qDebug() << "after: " << map.value("pen").count;
}

Output:
before:  0
after:  1

Update:
You have to use find() to get the iterator of the first element with the key, and if you want to access an element with the same key you must increase the iterator.
struct Test{
    QString name;
    int count = 0;
};

QMap<QString, Test> map;
Test test1;
test1.name = "doc1";
map.insertMulti("pen",test1);

Test test2;
test2.name = "doc2";
map.insertMulti("pen", test2);

if(map.contains("pen")){
    // get the first item with the key
    QMap<QString, Test>::iterator it = map.find("pen");
    // the next element
    it++;
    // update value
    it->count++;
}

for(const Test & value: map){
    qDebug() << value.name << " " << value.count;
}

Output:
"doc2"   0
"doc1"   1


text:
Q: HTML Imports not working I am trying to use HTML import for the header & footer on my site as I will be updating these frequently and want to avoid manually updating every page individually.
Here is the import code, which is contained within the  tags in my index.html file:
<link rel="import" href="/includes/header.html">

This does not work (nothing changes) and likewise for the footer.
Here is the contents of the header.html file:

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

    </button>

Our Mission

A: HTML Import only work natively in Chrome. Google Chrome has had support since version 31, but you still need to enable the feature manually. For more details Click enter link description here
Not supported in Firefox.
So, I suggest you can use PHP function include and require_once

A: Try using:
<link rel="import" href="./includes/header.html">

the "." says look in the folder in the path

A: Try using <?php include "/includes/header.html"; ?>
or add your link tag inside head tag if it's not.


text:
Q: Trap delete key My problem is fairly trivial: I need to apply logic to the delete button in Excel. In a related question I asked for means to clear cells in a pivot table, and realising now that this might not be the right approach, this is yet another alternative I'm considering. Unfortunately, I admittedly have little experience with Visual Basic, and this task is proving such a challenge (quite surprisingly).
Is it possible to trap (as in listen to) the delete-key in Excel and trigger a subroutine in VBA when pressed?
I'd appreciate all kind of input! Thanks!

A: Yes.
You case use Application.Onkey to assign code to keys
If you
(1) add this code to a sheet module that contains your pivottable (right-click your sheet tab, View Code and past the code below)
This code activates and then de-activates the intercept when the user enters then leaves this particular sheet:
Private Sub Worksheet_Activate()
Application.OnKey "{DELETE}", "Intercept"
End Sub

Private Sub Worksheet_Deactivate()
Application.OnKey "{DELETE}"
End Sub

(2) add this code to a regular module
Sub Intercept()
MsgBox "user just pressed delete"
End Sub

then delete on that sheet will be trapped and the user given a message


text:
Q: В чём отличие FixedUpdate и Update? Когда они вызываются? Я начинаю изучать Unity3d и одна из вещей, которая мне не ясна - это разница между методами Update() и FixedUpdate().
В своих проектах я использую метод Update() и всё работает хорошо. В чём отличие метода FixedUpdate() и обычного Update()?

A: Быстрое описание: Update вызывается каждый кадр, а FixedUpdate с фиксированной частотой независимо от FPS. При этом частоту можно изменить в настройках Unity.
Его частота зависит от того, насколько быстро компьютер способен отображать изображения. На более медленном компьютере Update вызывается реже, чем на более быстром. Если вы выполняете расчеты на основе времени, вы можете нормализовать их, используя Time.deltaTime, который скажет сколько времени прошло с момента последнего вызова Update. Обычно его используют для выполнения задач, связанных с отображением (например, обновление элемента пользовательского интерфейса)
FixedUpdate вызывается с фиксированной частотой независимо от FPS. При этом частоту можно изменить в настройках Unity. Вызывается фиксировано независимо от того, как часто изображение обновляется.
Обычно используют для выполнения задач, связанных с игровым процессом (например, обновление физики).

Чуть подробнее:
Я сначала напишу псевдокод и добавлю диаграммы ниже, которые, возможно, помогут понять что к чему.
В приведенном ниже (полностью вымышленном) коде сначала выполняется соответствующее количество физических шагов, чтобы «догнать» текущее время (и на каждом шаге вызывается FixedUpdate() для каждого объекта, который его реализует). Затем отрисовывается графика для кадра, за которым уже следует Update() для каждого объекта, который ее реализует.
var physicsTimeSimulated = 0;
var lastUpdateTime = 0;

 while (Unity is Running) {
     while (physicsTimeSimulated < Time.time) {
         Engine.ExecutePhysicsStep();
         Engine.FixedUpdate(); // <-- отправляется всем объектам
         physicsTimeSimulated += physicsTimeStep;
     }

     deltaTime = Time.time - lastUpdateTime;
     Engine.RenderFrame();
     Engine.Update(); // <-- отправляется всем объектам
     lastUpdateTime = CurrentTime;

     // повтор...
 }

Если игра работает с низкой частотой кадров, между каждым видимым рендером кадра будет множество обновлений физики. И наоборот, если игра работает с очень высокой частотой кадров, между рендерингом некоторых кадров может вообще не быть шагов физики, потому что время, прошедшее с момента последнего рендеринга кадра, еще не превысило период времени одного физического шага.
У Юнити можно настроить количество обновлений физики в секунду. По-умолчанию это "0,02", т.е. это примерно 50 обновлений физики в секунду (каждый шаг физики имитирует движение, которое происходит в течение двух сотых секунды).
Итак, для начала простая диаграмма, где показан период в одну десятую секунды. Точки, разделяющие линию, обозначают сотые доли секунды. А "F", чтобы показать, равные деления вызова метода FixedUpdate
0                                                0.1 seconds
|                                                 |
.____.____.____.____.____.____.____.____.____.____.___
F         F         F         F         F         F

Теперь, если бы наша игра работала хорошо и быстро со скоростью 100 кадров в секунду, у нас было бы два рендера кадра для каждого шага физики и, следовательно, два вызова наших функций Update для каждого вызова наших функций FixedUpdate
(«F» обозначает вызов FixedUpdate, «U» - Update)
0                                                0.1
|                                                 |
.____.____.____.____.____.____.____.____.____.____.___
F         F         F         F         F         F
U    U    U    U    U    U    U    U    U    U    U

Если наша игра работает медленнее, скажем, со скоростью 30 кадров в секунду (и, следовательно, 30 вызовов всех функций Update в секунду), это будет означать, что на самом деле у нас иногда бывает более одного физического шага между рендерингом каждого кадра. В случае 30 кадров в секунду результатом будет то, что иногда между кадрами выполняются два физических шага, а иногда один, который будет выглядеть примерно так, в течение первых 10 долей секунды:
0                                                0.1
|                                                 |
.____.____.____.____.____.____.____.____.____.____.___
F         F         F         F         F         F
 U                U               U                U

Таким образом, в большинстве обычных обстоятельств вы всегда будете получать желаемое и постоянное количество физических шагов в кадре, и вместе с ними будут чередоваться обновления визуального кадра с максимально возможной скоростью.
По этой причине FixedUpdate следует использовать когда используются силы (Force) к объекту, крутящих моментов или других функций, связанных с физикой, потому что вы знаете, что он будет выполняться точно синхронно с самим физическим движком.
В то время как Update может отличаться от физического движка, быстрее или медленнее, в зависимости от того, какую нагрузку графика накладывает на движок рендеринга на текущий момент времени (что при использовании данного метода для физики дало бы не постоянную и не корректную работу)
Исключением было бы то, что если бы ваша сцена оказывала такую нагрузку на физический движок, что она приближалась бы к точке, когда становится невозможным выполнить необходимое количество физических шагов по времени, чтобы идти в ногу с «реальным временем». Это означает, что вашу игру стало невозможно моделировать в реальном времени, и в этом случае вам нужно серьезно подумать о переработке вашей игры! Это может произойти, если у вас есть большое количество сложных объектов (например, коллайдеров сетки твердого тела), которые сгруппированы вместе, поэтому на каждом шаге возникает множество столкновений «многие ко многим».

Частичный перевод: http://answers.unity.com/answers/11002/view.html с дополнениями, вставками, размышлениями....


text:
Q: NOT getting updated content with every render I'm new to Next.js. I'm facing a problem where I am not able to load my new content on the page. Next.js keeps showing the old content which I already deleted from the code. Why does prior content show?
Here is the last code which I delete but still it is showing on the source tab of chrome.
export const UploadWrapper = () => {
    // const img__isClicked = ;
    const img__isClicked = useSelector(state => state);

    useEffect(() => {
        console.log('uploadWrapper', img__isClicked);
    }, [img__isClicked])

    return (

            <UploadDropzone />
            {(img__isClicked) ? console.log('hurray I got you') : null }

    )
}

Here is the updated code which is not showing on the page:
export const UploadWrapper = () => {
    // const img__isClicked = ;
    const img__isClicked = useSelector(state => state.img__isClicked);

    useEffect(() => {
        console.log('uploadWrapper', img__isClicked);
    }, [img__isClicked])

    return (
      <>

            <UploadDropzone />

            {(img__isClicked === true) ? <TagsWrapper /> : null }

      </>
    )
}

If I wish to see fresh content then I have to restart the whole server again.
event the console is showing me

Hurray I got you

A: It is because new render doesn't happen when you don't change the state inside the component. You could create imgClicked state like this:
export const UploadWrapper = () => {
  const [imgClicked, setImageClicked] = useState(false);
  const img__isClicked = useSelector(state => state.img__isClicked);

  useEffect(() => {
    setImageClicked(img__isClicked); // <--- This state change will trigger re-render of the component.
  }, [img__isClicked])

  return (
    <>
      {imgClicked ? <TagsWrapper /> : null}
    </>
  )
}


text:
Q: imshow opencv doens't show image this is my code, when I try to use imshow the image is black
    cv::Mat src(height, width, CV_16U);
    for (int i = 0; i < width* height; ++i)
    {
        src.at<unsigned short>(i) = input_image[i]/1023;
    }
    cv::Mat temp;
    cv::resize(src, temp, cv::Size(), 0.3, 0.3, cv::INTER_LINEAR);
    cv::imshow("image1", temp);
    cv::waitKey(0);

    cv::Mat imageData;
    cv::cvtColor(src, imageData, cv::COLOR_BayerGR2RGB);

    cv::resize(imageData, temp, cv::Size(), 0.3, 0.3, cv::INTER_LINEAR);
    cv::imshow("image1", temp);
    cv::waitKey(0);

if I change my code to
cv::Mat src(height, width, CV_32F);
for (int i = 0; i < width* height; ++i)
{
    src.at<float>(i) = input_image[i]/1023;
}

can you explain how to display the image?

A: Since your input_image is in the range 0..1023, by dividing by 1023 you're getting a value between 0 and 1. When you cast that to an unsigned integer type, your image is all zeros. (It might round some of them to 1, but that's not really going to be visible anyway.)
To get the number to use the full range of unsigned short, you need to multiply by 65535:
src.at<unsigned short>(i) = input_image[i]/1024*65536;

or
src.at<unsigned short>(i) = input_image[i]*64;


text:
Q: Way to add all the missing imports in one go in Flutter? Let's say, initially I have a screen which currently contains all the UI as well as the logic.
But now I want to separate the UI and the logic into two different files, and maybe some UI too.
Question:
Is there any extension or a terminal command that I can execute so that all the missing files will get imported?
NOTE: I know I can just copy all the imports from the original file, but then I would have also copied some unwanted imports. I just want to import the filed that are needed.


text:
Q: Difference of a recursive sequence Maybe someone can help me with this..
Given this sequence:
$$f_n=\frac{f_{n-1} + f_{n-2}}{2},$$
$$f_0=0, f_1=1$$
Find an explicit formula for the difference:
$$F_n:=f_n-f_{n-1}$$
I have the solution but I don't understand one step. The solution is:
$$F_n:=f_n-f_{n-1}=\frac{1}{2}(f_{n-1}+f_{n-2})-f_{n-1}=\frac{1}{2}(-f_{n-1}+f_{n-2})=-\frac{1}{2}F_{n-1}
\\it follows\\
F_n=\left(-\frac{1}{2}\right)^{n-1}F_1
=\left(-\frac{1}{2}\right)^{n-1}(f_1-f_0)=\left(-\frac{1}{2}\right)^{n-1}$$
The step that I didn't understand is:
$$F_n=\left(-\frac{1}{2}\right)^{n-1}F_1$$
How do I get there? They write in the answers sheet it follows but from what and why?

A: Keep applying the recurrence $F_n=-\frac12F_{n-1}$:
$$\begin{align*}
F_n&=-\frac12F_{n-1}\\
&=-\frac12\left(-\frac12F_{n-2}\right)\\
&=\left(-\frac12\right)^2F_{n-2}\\
&=\left(-\frac12\right)^2\left(-\frac12F_{n-3}\right)\\
&=\left(-\frac12\right)^3F_{n-3}\\
&\;\;\vdots\\
&=\left(-\frac12\right)^kF_{n-k}\\
&\;\;\vdots\\
&=\left(-\frac12\right)^{n-1}F_{n-(n-1)}\\
&=\left(-\frac12\right)^{n-1}F_1
\end{align*}$$
If still in doubt, you can then prove it by induction on $n$.

A: alternatively, solving the auxiliary  equation $2x^2-x-1$ gives roots $1,-\frac12$ so the solution is
$$
f_n=A+B(-\frac12)^n
$$
and the values for $n=0,1$ show that $A=\frac23,B=-\frac23$. consequently:
$$
F_n=(-\frac23)\left( \left( -\frac12 \right)^n -\left( -\frac12 \right)^{n-1} \right) \\
=\left( - \frac12 \right)^{n-1}
$$


text:
Q: Angular PWA in ASP.Net Core Server - Serviceworker-Cache not working I created a Angular PWA and moved it into a ASP.Net Core Spa - Application. I can run it offline when served and installed via "npm http-server".
When I run it in the ASP.Net Server the Serviceworker loads with an error "Cannot read property 'put' of undefined" in ngsw-worker.js:
        write(key, value) {
          return this.cache.put(this.request(key), this.adapter.newResponse(JSON.stringify(value)));
        }

I am trying to cache requests from the webapi and configured them in the ngsw-config.json - file
    {
      "$schema": "./node_modules/@angular/service-worker/config/schema.json",
      "index": "/index.html",
      "dataGroups": [
        {
          "name": "api-freshness",
          "urls": [
            "/odata/**"
          ],
          "cacheConfig": {
            "strategy": "freshness",
            "maxSize": 500,
            "maxAge": "3d",
            "timeout": "2s"
          }
        }
      ],
      "assetGroups": [
        {
          "name": "app",
          "installMode": "prefetch",
          "resources": {
            "files": [
              "/favicon.ico",
              "/index.html",
              "/*.css",
              "/*.js"
            ]
          }
        },
        {
          "name": "assets",
          "installMode": "lazy",
          "updateMode": "prefetch",
          "resources": {
            "files": [
              "/assets/**",
              "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
            ]
          }
        }
      ]
    }

In the first place the manifest.webmanifest file was served with wrong content-type, so I added a provider in my startup.cs. But this didn't help.
        provider.Mappings[".webmanifest"] = "application/manifest+json";

        app.UseSpaStaticFiles(new StaticFileOptions() {
            ContentTypeProvider = provider
        });

A: I realized that the chrome browser which is used from Visual Studio in the debugging mode causes the issue. The serviceworker doesn't get proberly registered when I launch the browser from VS. The error disappears when I copy the URL and paste it to a new instance of chrome.
Also the caching worked after I used the the "clear site data" - button in the "Clear storage" tab.


text:
Q: Integration test through message broker There are two programs that are communicating using message broker and I want to cover some interactions between them using integration tests.
So I want to write the integration test that will use JUnit, in before stage want to run the external program and in "after" stage it should be cleaned up.
Is there a good way to do this, or I'm just going the wrong path?


text:
Q: A set having the same mean, median, mode, and range Is it possible to have a set with the same mean, median, mode, and range?
If not, how can the following question be solved:

Set $H$ contains five positive integers such that the mean, median,
mode, and range are all equal. The sum of the data is $25$.
Using the above information, indicate which one will be greater:
a) the smallest possible number in set $H$.
b) 6.

If I assume that all the elements in set $H$ are equal to $5$, it doesn't satisfy the conditions for range, as the range will become zero then.

A: The multiset $[3, 4, 5, 5, 8]$ will fit the bill.
You know, though, that even if you didn't have an example of a set on hand, the smallest element must be less than or equal to $5$ since the median is $5$ (since the mean is $5$).

A: Hint:  If I allow non-integers and let the set contain duplicates (I think duplicates are allowed, though generally a set does not allow them.  To have a mode you need duplicates), $\{2.5,5,5,5,7.5\}$ satisfies the constraints.  Can you modify it to use only integers?


text:
Q: Incorrect tile loading with MapProxy I am trying to publish my WMS map that I created from GeoServer with Leaflet using MapProxy. But what could be wrong with the MapProxy and Leaflet are not the same?

services:
  demo:
  tms:
    use_grid_names: true
    # origin for /tiles service
    origin: 'sw'
  kml:
      use_grid_names: true
  wmts:
  wms:
    md:
      title: MapProxy WMS Proxy
      abstract: This is a minimal MapProxy example.

layers:
  - name: osm3122
    title: Omniscale OSM WMS - osm.omniscale.net
    sources: [osm_cache]

caches:
  osm_cache:
    grids: [webmercator]
    sources: [osm_wms]

sources:
  osm_wms:
    type: wms
    req:
      url: http://localhost:8080/geoserver/cite/wms?
      layers: cite:dunya
      grid: webmercator

grids:
    webmercator:
        srs: EPSG:900913
        origin: nw

globals:

Leaflet code:
  var a =  L.tileLayer('http://localhost:8011/tms/1.0.0/osm3122/webmercator/{z}/{x}/{y}.png', {
         transparent: true,
         attribution: "",
         tiled:true
    }).addTo(map);


text:
Q: Applescript to emulate key strokes I want applescript to input into microsoft excel "No, (tab, tab again), Yes". I can't seem to make this work. I would preferably like it to start whenever I press a hotkey or something, but having to swipe over and activate the script should be ok.
Thanks, Nick

A: There is a lot of information about how to write Applescript code in general and how to use it to send keystrokes available on the net. System Events, Key Code and Keystroke looks kind of interesting in your case and should get you started.


text:
Q: BottomNavigationView hides some part of the screen at the bottom in my app (Android studio java) BottomNavigationView hides some part of the view which behinds the screen.
How can I show view above the footer (BottomNavigationView)
I have edited the below and updated the mainactivity.xml file
Also, the xml file which I have added the another xml like below

one of my xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/refresh_layout"
    android:layout_width="match_parent"
    app:layout_constraintBottom_toTopOf="@id/bottom_navigation"
    android:layout_height="match_parent"

    android:background="@color/colorPrimary"
    tools:ignore="NotSibling,RtlHardcoded">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@null">
/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

mainactivity.xml

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/root_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        android:background="@null"
        tools:ignore="NotSibling,UnknownId">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@null">

            <FrameLayout
                android:id="@+id/fragment_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@null"
                android:paddingBottom="?attr/actionBarSize"
                android:paddingTop="?attr/actionBarSize"/>

            <View
                android:id="@+id/divider_toolbar"
                android:layout_width="match_parent"
                android:layout_height="@dimen/stroke"
                android:layout_marginTop="?attr/actionBarSize"
                android:background="@color/colorPrimary"/>
            <FrameLayout
                android:id="@+id/footer_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                >
                <com.google.android.material.bottomnavigation.BottomNavigationView
                    android:layout_gravity="bottom"
                    android:background="@drawable/curved_shape_footer"
                    android:id="@+id/bottom_navigation"
                    android:layout_width="match_parent"
                    app:itemBackground="?selectableItemBackgroundBorderless"
                    app:itemHorizontalTranslationEnabled="false"
                    app:menu="@menu/bottom_navigation"
                    app:labelVisibilityMode="unlabeled"
                    android:layout_alignParentBottom="true"
                    android:layout_height="wrap_content"/>
            </FrameLayout>
</...>
</...>
</...>

A: Use constraints layout and set constraint to your top root view as app:layout_constraintBottom_toTopOf="@id/bottomNavigationView".
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/refresh_layout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="@color/colorPrimary"
    tools:ignore="NotSibling,RtlHardcoded"
     app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toTopOf="@id/bottom_navigation">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@null">

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

<com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: Tkinter: "Bad label anchor specification" I've been working with the same Python/Tkinter code for a week now, and seemingly out of nowhere I am getting the error "Bad label specification":
Traceback (most recent call last):
    File "C:/Users/shapirju/Desktop/NumericalAnalysis-Project2/gui.py", line 1188, in <module>
        gui = App()
    File "C:/Users/shapirju/Desktop/NumericalAnalysis-Project2/gui.py", line 62, in __init__
self.createWidgets()
    File "C:/Users/shapirju/Desktop/NumericalAnalysis-Project2/gui.py", line 70, in createWidgets
self.interpLabelframe = LabelFrame(self.root, text = "Interpolation", labelanchor=N)
    File "C:\Program Files\Python27\lib\lib-tk\ttk.py", line 776, in __init__
Widget.__init__(self, master, "ttk::labelframe", kw)
    File "C:\Program Files\Python27\lib\lib-tk\ttk.py", line 555, in __init__
Tkinter.Widget.__init__(self, master, widgetname, kw=kw)
    File "C:\Program Files\Python27\lib\lib-tk\Tkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: Bad label anchor specification 443664640LN

It is caused by the line self.interpLabelframe = LabelFrame(self.root, text = "Interpolation", labelanchor=N)
As this worked a few hours ago, maybe this is an environmental issue? I cannot find anything about this issue on Google.

A: Changing it to self.interpLabelframe = LabelFrame(self.root, text = "Interpolation", labelanchor='n') fixes the issue.
According to the source code for LabelFrame, the label anchors are defined as strings 'n', 'we', etc.


text:
Q: Showing alert dialog on notification click when sent from Firebase Push Notification I am using firebase push notification in my project.But whenever I click notification the else part is displayed always.I want to display notification text in that dialog when the notification is clicked.
Here is my code in NotifService.class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FCM Service";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.icon_main)
                .setContentTitle("Update from Refer Ncert")
                .setContentText(""+remoteMessage.getNotification().getBody())
                .setAutoCancel(true)
                .setLights(Notification.DEFAULT_LIGHTS,1000,20000)
                .setVibrate(new long[] { 1000, 1000})
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("notifmsg",remoteMessage.getNotification().getBody());
        PendingIntent pi = PendingIntent.getActivity(this,0,intent,Intent.FLAG_ACTIVITY_NEW_TASK);
        mBuilder.setContentIntent(pi);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());
    }
}

Here is the code in MainActivity's onCreate() to display the notification:
String notifmsg=getIntent().getStringExtra("notifmsg");

    if(notifmsg != null){
        new SweetAlertDialog(this)
                .setTitleText("Hello Readers!")
                .setContentText(notifmsg)
                .show();
    }
    else{
        new SweetAlertDialog(this)
                .setTitleText("Welcome Back")
                .setContentText("Continue reading your previous book by clicking on RECENT BOOK button below.")
                .show();
    }

A: As far as I see, you define the intent, but you dont "send" it.
Add this to code your code after defining the pendingIntent and it should work:
pi.send();

A: You can use this:
Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("Notification")
            .setContentText(messageBody)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());


text:
Q: C# Blazor app - get the duration of an audio file I'm not quite sure where to start on this one so wanted to ask for some help.
In a Blazor web app, I am downloading an MP3 audio file from S3 without any problems. It's kept in memory only at the moment via a MemoryStream (for further processing).
I now need to figure out the duration of the audio eg. 90 seconds or whatever.
Is it possible to do this via the MemoryStream ? Or do I need to download and write the file to disk, then inspect it ? Also what library can I use to inspect the MP3 file so as to determine the duration of the audio ?
Here's the relevant piece of code which is downloading (from S3) the file:
MemoryStream ms = null;

GetObjectRequest getObjectRequest = new GetObjectRequest
{
    BucketName = bucketName,
    Key = fileName
};

using (var response = await s3Client.GetObjectAsync(getObjectRequest))
{
   if (response.HttpStatusCode == HttpStatusCode.OK)
   {
      using (ms = new MemoryStream())
      {
          await response.ResponseStream.CopyToAsync(ms);
      }
   }
}

return ms;

A: Figured it out. With the help of this library (there are many but this worked well): https://github.com/Zeugma440/atldotnet
Once you've got the MemoryStream, you need to convert it to a FileStream. From there, the library will help to provide the Duration (which is the only thing I needed in this case).
Here's the method I'm using.
private static double GetMediaDuration(MemoryStream ms)
{
    using FileStream stream = File.Create("<any-file-name-u-like-here>.mp3");
    stream.Write(ms.ToArray(), 0, ms.ToArray().Length);

    Track theTrack = new Track(stream, mimeType: "audio/mp3", null);

    return theTrack.Duration;
}


text:
Q: Force to stop spring boot when junit it's over actually i have a Spring Boot application, and i use kafka embedded without use spring-kafka but with the use of confluent library.
I configured the custom Topology, and when i start the junit, the stream remains to listening and spring boot server does not to end.
I tried the use of @DirtiesContext but the problem remains.
For start the junit i use
@RunWith(SpringRunner.class)
@SpringBootTest

When the consumer is in loop i see this message in console:

[Producer
  clientId=application1-3c4587c8-23f0-4c8b-8ef0-75bc1e0f966c-StreamThread-1-producer]
  Connection to node -1 could not be established. Broker may not be
  available.

Tips?
Thanks

A: It seems that the error occurs because the broker is not running. But KafkaStreams is running.
In order to fix it, I think you need to prevent KafkaStreams from running when testing.
The @SpringBootTest annotation provides an attribute classes. You can specify the classes that will be registered as beans
You can prevent the KafkaStreams related beans from being registered by specifying the classes attribute.
For example, you can test as follows. In this case, the above problem will not occur because KafkaStreams related beans are not registered.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ServiceImpl.class, CommonConfig.class})
public class SomeClassTest {
    @Autowired
    private ServiceImpl articleServiceImpl;

    // do test
}

When you use @SpringBootTest, it is best to register only the beans you want to test.
If you are unfamiliar with this approach, try mocking the bean that manages the KafkaStreams object
For example, I create the following bean to start and end the KafkaStreams object.
@Component
public class ManageableStream implements DisposableBean, InitializingBean {

    private final KafkaStreams kafkaStreams;

    public ManageableStream() {
        StreamsConfig config = buildStreamConfig();
        StreamsBuilder builder = new StreamsBuilder();

        KStream<String, String> inputStream = builder.stream("source.topic");
        inputStream.to("destination.topic");

        Topology topology = builder.build();
        kafkaStreams = new KafkaStreams(topology, config);
    }

    @Override
    public void destroy() throws Exception {
        kafkaStreams.close();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        kafkaStreams.start();
    }

    private StreamsConfig buildStreamConfig() {
        Map<String, Object> properties = new HashMap<>();
        properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");

        properties.put(StreamsConfig.APPLICATION_ID_CONFIG, "test-stream-application");
        properties.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, AT_LEAST_ONCE);
        properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
        properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);

        return new StreamsConfig(properties);
    }
}

When testing, Mock the bean that manages the KafkaStreams object.
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @MockBean
    private ManageableStream manageableStream;

    @Test
    public void contextLoads() {
    }

}

Then KafkaStreams will not start, so the above problem will not happen.
If you want to test the topology of KafkaStreams, Please see the link below
https://kafka.apache.org/11/documentation/streams/developer-guide/testing.html
I hope my answer was helpful


text:
Q: Irreducible Markov chain and finite sets Let $(X_n)_{n\geq 0}$ be a irreducible Markov chain defined on a countable state space $S.$ Let $F \subset S$ a finite set and
$\tau=inf\{n \geq 1; X_n \notin F\}$. If $x \in F$ how to prove that $\mathbb{P}_x[\tau < \infty]=1.$ I tried to use that a Markov chain defined on a closed finite class is recurrent.

A: With some help I figure out how to prove it.
First of all, using irreducibility one can prove that there is constants $a>0$ and $n \geq 1$ such that $\mathbb{P}_x[\tau>n]\leq 1-a$ for every $x \in F$. It is easy to conclude that indeed $$\mathbb{P}_x[\tau>n]\leq 1-a, \forall x \in S.$$
Now, applying the Markov property, we can prove that
$$\mathbb{P}_x[\tau>kn]\leq (1-a)^k, \forall k \in \mathbb{N}.$$
The result follows easily from the last claim.


text:
Q: How to add additional fonts like google fonts in django-ckeditor? I have installed django-ckeditor by PIP and using it for writing blog in django admin panel.
How can I add additional fonts?
Link: https://github.com/django-ckeditor/django-ckeditor

A: django-ckeditor does supports the plugins developed by ckeditor team,they have one made for google web fonts ckeditor google web fonts plugin.
or the other way around is adding the fonts to the ckeditor config using javascript add(programatically) google fonts to ckeditor

A: Add the fonts you want in 'font_names' inside CKEDITOR_CONFIGS.
Then you need to add "contentsCss" to add google fonts with link.
For Example:
If you want Popins in ckeditor fonts then add bellow lines in CKEDITOR_CONFIGS:
'font_names': 'Poppins;serif;sans serif;monospace;cursive',
'contentsCss': ['https://fonts.googleapis.com/css?family=Poppins']

Note: Use https in contentsCss link.


text:
Q: Loading a language file in oo php So i am new to oo php and i-m building a sample app for learning purpses , one thing i must do is load a language file according to some settings
The code, as you will discover below is divided between two classes , a settings class witch should load the language file and another class in this case "contact" witch should read the array in the language files and display the propper message.
this is the Settings class
the lang variable sets the default language it can take 2 values at the moment : ro- for romanian and en - for english ,
    class Settings
{
  static public $lang = 'ro';
  static public $load;

  static public function get_language()
   {
    if(self::$lang == 'ro')
    {
      self::$load = require 'ro.php';
    }
    elseif(self::$lang == 'en')
    {
     self::$load = require 'en.php';
    }
    return self::$load;
   }

}

The second class :
class Contact extends Settings {
   //proprietati

   public $nume;
   public $subiect;
   public $mesaj;
   public $dincs;

   //comportament - metode

   public function __construct()
   {
     //$this->dincs = 'Din construct';
     parent::get_language();
   }

   public function write_file()
   {

     if(empty($this->nume))
     {
       return $mess['name_error'];
     }
     else
     {
       $fp = fopen('data.txt', 'w');
       fwrite($fp, $this->nume.".".$this->subiect .".". $this->mesaj."|".$this->dincs ."|".parent::$load);
       fclose($fp);

       return $mess['file_written'];
     }
   }

}

A sample from the language file:
   $mess = array ("name_error"  => "You must insert your name",
                  "file_written" => "the file has been written",

   );

I have looked up on google , and tried some other stuff and can't seem to get it to work , and that may be because i am approaching this problem incorectly.
Plese help.

A: `

class Settings
{
    protected $language = 'ro';
    protected $load;

    public function setLanguage($language = 'ro')
    {
        $this->language = $language;

        // file_get_contents()
        $this->load = require($this->language . '.php');
    }

    public function getLanguage()
    {
        return $this->language;
    }

}

class Contact extends Settings
{
   protected $name;
   protected $subject;
   protected $message;
   protected $dincs;
   protected $settingsObject;

   // set all the properties below...

   public function setName($name)
   {
        $this->name = $name;
   }

   public function setSubject($subject)
   {
        $this->subject = $subject;
   }

   public function setMessage($message)
   {
        $this->message = $message;
   }

   public function setDincs($dincs)
   {
        $this->dincs = $dincs;
   }

   // get all the properties...
   public function getName()
   {
        return $this->name;
   }

   // This function only accepts an instance of Settings as the parameter
   public function setSettingsObject(Settings $settings)
   {
        $this->settingsObject = $settings;
   }

   public function writeContentsToFile()
   {
        // if there is nothing in name, throw a new exception
        if (empty($this->name))
        {
            throw new Exception('name has not been set! Set name before calling '. __METHOD__);
        }
        else
        {
           // get the file
           $fp = fopen('data.txt', 'w');

           // formatted string
           $contents = sprintf('%s . %s . %s | %s | %s', $this->name, $this->subject, $this->message, $this->dincs, $this->settingsObject->getLanguage());

           // write to the file
           fwrite($fp, $contents);

           // close the handler
           fclose($fp);

           return ('File written! Contents written: ' . $contents);
        }
    }
}

// instantiate settings
$settings = new Settings();
$settings->setLanguage('en');

// instantiate contact and set the settings object
$contact = new Contact();
$contact->setName('Joe Smith'); // if this is not set, ::writeContentsToFile will throw an Exception
$contact->setSettingsObject($settings);

// try and catch the Exception that ::writeContentsToFile may throw
try
{
    echo $contact->writeContentsToFile();
}
catch (Exception $exception)
{
    var_dump($exception);
}

?>
`

A: self::$load = require 'en.php';

You assign here a return value from the file inclusion to self::$load; not the variable $mess you defined in your language file.
So, there are two ways now: return the array $mess (return $mess;) from the language file.
Or you can just write:
require 'en.php';
self::$load = $mess;

Little side note: I'd check in your Settings::getLanguage() method if (self::$load) and return then the self::$load variable instead of refetching the language file…)


text:
Q: Sending parameters with Fine Uploader upload requests I need to send parameters to a REST service called from AngularJs. I need to send some data besides the file, how can I send it, and how can I specify the file parameter?
Regards,

A: Either via the request.params option:
request: {
    params: {
        param1: "foo",
        param2: "bar"
    }
}

or via the setParams method:
uploader.setParams({param1: "foo", param2: "bar"});
You can adjust the name of the file parameter via the request.inputName option.
All of this is documented.  Please see the documentation for additional information and supported workflows related to setting parameters.


text:
Q: Powershell: Search object list for variable value? I am working on a script for some of my users to identify if they have the current required Windows hotfix installed.
I am trying to put the KB number in a variable so I don't have to hardcode it within the script, but I am not having any luck. When I replace the $1809 in the get-hotfix line with the actual 'KB4577668', it returns the correct value of "TRUE". But when I leave it as the variable, it returns "FALSE" which is not correct. Any ideas?
    $1809 = "KB4577668"
    (get-hotfix).hotfixID -contains $1809

A: try this :
$1809 = "KB4577668"

#method 1
$Founded=Get-HotFix -id  $1809

#or method 2
$Founded=Get-HotFix | where HotFixID -eq $1809

#test result
if($Founded)
{
  "hotfix founded"
}
else
{
  "hotfix not founded"
}

A: The string seems to be fixed which is a literal string, so if you are not using variables in the string enclosed with speech marks, then using single quotes is advised.
$1809 = 'KB4577668'
More information on this from the Microsoft documentation,
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7.1
and also another article from Microsoft Scripting Guy,
https://devblogs.microsoft.com/scripting/weekend-scripter-understanding-quotation-marks-in-powershell/


text:
Q: active a profile during release prepare in maven 3 does not work I have a need to active a profile during release:prepare.
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-release-plugin</artifactId>
            <version>2.1</version>
            <configuration>
                <arguments>-Prelease</arguments>
                <preparationGoals>clean validate</preparationGoals>
                <goals>test-compile</goals>
            </configuration>
        </plugin>
    </plugin>
</build>

But when I run:
mvn release:prepare -DdryRun=true help:active-profiles

it never show profile release in active list. and it is not show up on active profile list when I do:
mvn release:perform help:active-profiles

I could not not use <releaseProfiles> since I want this profile to be used in both prepare and perform
Thanks!

A: One thing that I have used in this case is not using the -P argument, but rather triggering the profile through an environment setting using -Denv=release. Then in the POM, I have the profile activation based on the value of env. This has always worked for me. So in the arguments parameter, you could put something like
<arguments>-Denv=release</arguments>

Similar questions can be found here:

*

*Profile activation on both release:prepare and release:perform

*maven release plugin ignores releaseProfile

A: I think there's some misunderstanding here: mvn release:prepare -DdryRun=true help:active-profiles will never show the active profiles used during the release, but it shows the current active profiles. release:prepare will start another Maven thread (separate executable), and only then the release profile is activated.
In the maven-release-plugin-2.4 a lot has been fixed with regards to profiles, especially for Maven3, since some information was not available anymore when using Maven 2 but now is with Maven 3.
See the release notes


text:
Q: How do I limit the number of columns of a basic table field? I have a basic table field.
I only need three columns but it displays more.
How do I limit it to three?
And how do I set the width of the columns?

A: If you have a 600 pixel wide field named "Data" with tab delimited data;
set the tabStops of field "Data" to "200,400,600"

will set the column widths.  The last tab stop at 600 throws any content beyond the third column outside of the visible area of the field.

A: set the tabStops of fld "Data" to 100,0,150,0,0

will hide column 2 and 4, 5, 6, ..., n.
If you want to hide the column, set it's width to 0. If the last parameter is 0 then the rest of columns will be not visible, and it'll be missing vertical line of last visible column. If you want vertical line after last field, add additional 0 [set ... to 100,0,200,0,0]


text:
Q: AutoCompleteBox issue when having multiple items with same values My issue is that if I have objects with the same value in ValueMemberPath then the AutoCompleteBox selects the first item after it selects the correct item.
I've bound SelectedItem to a Property and I can see it get's fired twice if there are multiple items with the same value.
I've bound my AutoCompleteBox to an ObservableCollection of Person objects.
public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string FullName
    {
        get
        {
            return Name + " - " + ID;
        }

    }
}

My XAML looks like this:
<StackPanel>
    <inputtoolkit:AutoCompleteBox x:Name="autoCompleteBox" ValueMemberPath="Name" ItemsSource="{Binding Persons}" SelectedItem="{Binding SelectedPerson, Mode=TwoWay}">
        <inputtoolkit:AutoCompleteBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding FullName}" FontSize="14" FontWeight="Bold"></TextBlock>
            </DataTemplate>
        </inputtoolkit:AutoCompleteBox.ItemTemplate>
    </inputtoolkit:AutoCompleteBox>

    <TextBlock x:Name="textBlock" Text="{Binding SelectedPerson.ID}"></TextBlock>
</StackPanel>

My Window_Loaded looks like this:
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Persons = new ObservableCollection<Person>();

        Persons.Add(new Person() { ID = 1, Name = "Person" });
        Persons.Add(new Person() { ID = 2, Name = "Person" });
        Persons.Add(new Person() { ID = 3, Name = "Person" });
        Persons.Add(new Person() { ID = 4, Name = "Person" });

        autoCompleteBox.DataContext = this;
        textBlock.DataContext = this;
    }

When I write "Per" 4 items will be shown in the DropDown. Now when I selected the fourth, it gets selected and the binding updates. However it then goes back to the first item. Is this a bug or intended behaviour and can anyone help me with this issue?

A: I'm having this same issue.  I haven't tried it yet, but I found this link and it looks to have solution.
http://www.yumasoft.com/node/45
Edit
I just confirmed that this does work.
For the comments asking how the user will tell the difference.  The ItemTemplate providers more detail than is shown in just the TextBox portion.  This allows the user to decide which record to use.


text:
Q: A question on zero set of a real analytic function of two variables Let $D$ be an open connected subset in $\mathbb{R}^n.$ Assume that the non-trivial/non-zero function
$f \equiv f(x,y): D \times (0, \infty) \to \mathbb{R} $ is real analytic in both $x$ and $y.$
Denote by $f_y(x):=f(x,y), f_x(y)=f(x,y).$ Assume that $f_x(.), f_y(.)$ are not identically zero. I'm trying to check, if possible that the set
$S:= \{y \in  (0, \infty): f(x,y) = 0 \text{ for at least one $x \in D$ } \}$  has measure zero or not.
To solve the problem, I've written:
$$S= \bigcup_{x \in D}\{y \in  (0, \infty): f(x,y) = 0  \}$$
Next we take the complement of $S,$ denoted by $S':$
$$S'= \bigcap_{x \in D}\{y \in  (0, \infty): f(x,y)= f_y(x) \ne 0  \}$$
Next, we note that since for each fixed $y, f_y(x)$ is a continuous function of $x,$ therefore if $f_y(x) \ne 0,$ then $f_y(z) \ne 0 \forall z$ sufficiently near $x.$ Therefore, the above intersection  $\bigcap_{x \in D}$ is essentially a countable intersection where $x$ have rational coordinates (this is where I'm hesitating a bit, and please check if this rationale is correct!). Therefore we have:
$$S'= \bigcap_{x \in D \cap \mathbb{Q}^n}\{y \in  (0, \infty): f(x,y)=f_y(x) \ne 0  \}$$.
So taking complement again:
$$S= \bigcup_{x \in D \cap \mathbb{Q}^n}\{y \in  (0, \infty): f(x,y)=f_x(y) = 0  \}$$.
We already know that the zero set of a real analytic function (of one or several variables) is of zero Lebesgue measure in the corresponding dimension, c.f. Zeros of analytic function of several real variables, https://arxiv.org/abs/1512.07276. So each $\{y \in  (0, \infty): f(x,y)=f_x(y) = 0  \}$ above has measure zero in $\mathbb{R}$, since $f_x(y)$ is real analytic in $y\in \mathbb{R}.$
But this implies that $S$ is a countable union $x \in D \cap \mathbb{Q}^n$ of measure zero subsets $\{y \in  (0, \infty): f_x(y) = 0  \}$ of $\mathbb{R}.$ So we conclude that $S$ has measure zero in $\mathbb{R}.$
Is my argument correct?

A: It is not true. Let $f: \mathbb{R} \times (0, \infty) \rightarrow \mathbb{R}$, $(x,y) \mapsto x-y$. Then given $y$, letting $x=y$ shows $y \in S$, so $S = (0, \infty)$ does not have measure zero.  This example also shows that
$$\bigcap_{x \in D}\{y \in  (0, \infty): f(x,y)= f_y(x) \ne 0  \} \neq \bigcap_{x \in D \cap \mathbb{Q}^n}\{y \in  (0, \infty): f(x,y)=f_y(x) \ne 0  \}.$$
For $x = \sqrt{2}$, we have $x-y \neq 0$ for all $x \in \mathbb{Q}$ but we cannot conclude $x-y \neq 0$ for all $x \in \mathbb{R}$. (Note though that from $f(x,y) = 0$ for all $x \in D \cap \mathbb{Q}^n$ we could conclude that $f(x,y) = 0$ for all $x \in D$, by continuity; perhaps that is the confusion.)


text:
Q: Dynamically adding preview not working properly in Grapes js I am using GrapesJs in React Js, When I have a preview page, I have to show the builder with the preview mode. Preview is executing, but that grapes Js sidebar component is not hiding and the builder is also editable.

  const {template, loading} = props; //getting grapes js data from props
  let editor = grapesjs.init({
    container: '#root',
    height: '100%',
    fromElement: true,
    plugins: ['gjs-preset-webpage', 'gjs-blocks-flexbox'],
    assetManager: {
      storageType   : '',
      storeOnChange  : true,
      storeAfterUpload  : true,
      credentials: 'include',
  },
  });
useEffect(()=>{
  if(loading){
    editor.setComponents('
loading....
');
  }else{
      editor.runCommand('preview');
  }
},[template, loading])

return (

)
}


text:
Q: Verify method never called or only once called using Minitest::Mock Is there any way to verify a method never called or only a number of times called using Minitest::Mock
Thanks in advance

A: Was looking for a "proper" way to test that something isn't called in minitest (I hate minitest) and stumbled upon this question.
I ended up doing it like this:
def test_foo_isnt_called
  Foo.stub(:call, proc { raise "shouldn't happen" }) do
    subject(x, y)
  end
end

A: Specific number of times:
Minitest::Mock forces the developer to be explicit about message expectations, so if you expect a given method to be called x times, you'll need to be very literal about it.
my_mock = Minitest::Mock.new
x.times { my_mock.expect :some_method, :return_val }

Never called:
Philosophically, Minitest shies away from testing that something doesn't happen.  While it's not completely analogous, have a look at this post or google "minitest assert nothing raised".
Minitest::Mock will raise a NoMethodError whenever an unexpected method is called on it.  That's not exactly an assertion, but probably has the desired effect.  Still, you don't particularly need a mock to do what you're asking.  You can do the same by patching your real object instance.
def test_string_size_never_called
  str = "foo"
  def str.size
    raise NoMethodError, "unexpected call"
  end

  # test logic continues...
end


text:
Q: When hibernate is capable of doing, Why JPA has been introduced? When Hibernate is capable of doing everything, Why JPA has been introduced.

A: JPA is just specifications and Hibernate is an implementation, you can find further details here in this question What's the difference between JPA and Hibernate? .
If you use JPA with hibernate then you can swap out hibernate with any other alternate ORM. without modifying much code.
Its like List interface, now you use any implementation of list according to your need example LinkedList, ArrayList etc


text:
Q: Regex to mimic the js split function and extract the text I have a text where I need to extract the community name
The delimiter for spliting is " - "
Hence Iowa - Cedar Rapids - Meth-Wick Community
must give result as Meth-Wick Community
if input is Iowa - Cedar Rapids - The Gardens of Cedar Rapids
result must be The Gardens of Cedar Rapids
I have tried with
"Iowa - Cedar Rapids - The Gardens of Cedar Rapids".match(new RegExp(/([A-Z])\w{3}/gi))

A: Try this one out for size:

console.log("Iowa - Cedar Rapids - The Gardens of Cedar Rapids".replace(/([\w\s]+)\s-\s([\w\s]+)\s-\s([\w\s]+)/i,'$3'));

A: You can do a negative lookahead to find the last occurrence of the delimiter as mentioned here https://stackoverflow.com/a/8374980/5417843
and then extract the community name from it.
input = "Iowa - Cedar Rapids - The Gardens of Cedar Rapids"
communityName = input.match(new RegExp('- (?:.(?!- ))+$')) // '- The Gardens of Cedar Rapids'
communityName[0].substring(2) // 'The Gardens of Cedar Rapids'

A: Here's a simple solution, used less regex as much as possible:
"Iowa - Cedar Rapids - Meth-Wick Community".split(/ - /g).slice(-1)[0]
"Iowa - Cedar Rapids - The Gardens of Cedar Rapids".split(/ - /g).slice(-1)[0]

A: Use

const string = "Iowa - Cedar Rapids - The Gardens of Cedar Rapids"
console.log((string.match(/.*\s+-\s+(.+)/) || [''])[1])

See regex proof.
EXPLANATION
--------------------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  -                        '-'
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .+                       any character except \n (1 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
  )                        end of \1


text:
Q: Совместить php и html Всем привет. Вопрос делаю проверку на логин. Хочу сделать что если человек авторизовался то вывел этот html код иначе другой html код.
if ($_SESSION['admin_auth']==1) ?>
Авторизовался

<?php;else
        form_auth();

        ?>

Можно конечно вывести через echo но это сразу нет. Так как я буду выводить много таблиц и тд. Подскажите что можно сделать? Например товары через цикл вывожу так
<?php $categories=get_cat();
             foreach ($categories as $item):?>

              <a href="index.php?view=cat&id=<?php echo $item['category']?>"><?php echo $item['name']?>

            <?php endforeach;?>

A: Добрый день!
В скрипте есть ошибки
   <?php if ($_SESSION['admin_auth']==1){ ?>

Авторизовался

   <?php } else {
                form_auth();
         }
   ?>

Ну а так, не совсем понятен ваш вопрос...
P.S. Вы можете использовать и старый синтаксис (только исправьте ошибки), просто мне приятнее C подобный синтаксис


text:
Q: Using Picklists and MultiPicklists with Salesforce1 I'm creating a visualforce page that I plan to run in Classic and SF1 (and eventually Lightning) but I'm struggling a little bit with the design and functionality of the picklists/multipicklists.
I have tried to use the Lightning Design System but it appears that new picklist fields are being wrapped in  tags so are not holding the design.  This is of course using the standard  tags.  I looked at trailhead and at the examples in the LDS page and those use standard html tags and I'd have to completely build out and maintain the picklist values and behaviour, which is not ideal.  The trailhead examples use basic input text components and use remote objects, but even if I moved over to use remote objects, it will not fix my style and hard coding issue with the picklists.
We are not geared towards lightning yet, so no aura or actual lightning code is being utilized yet.
Does anyone have any suggestions or experience with this?

A: Well, I have figured out the issue.  It seems as though salesforce is stripping out the styleClass property on a newer field in Salesforce1.  I added it in jquery and had to put a setTimeout on it to add a class back to it after the page loads and at the end.


text:
Q: Execute XSLT Transform from Java with parameter I am executing an XSLT transform from within my java web application with no problems, as follows:
Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource);
transformer.transform(xmlInput, xmlOutput);

In my XSLT transform I am now adding a call to the document() function to load the response from a RESTful web service:
<!-- do stuff -->
<xsl:variable name="url">
   http://server/service?id=<xsl:value-of select="@id"/>
</xsl:variable>
<xsl:call-template name="doMoreStuff">
   <xsl:with-param name="param1" select="document($url)/foo"/>
</xsl:call-template>

Ok cool, no problem. But now, I want to read the base URL from a utils class in java and pass it in to the stylesheet.
//java
String baseUrl = myUtils.getBaseUrl();

<!-- xslt -->
<xsl:variable name="url">
   <xsl:value-of select="$baseUrl"/>
   <xsl:text>/service?id=</xsl:text>
   <xsl:value-of select="@id"/>
</xsl:variable>

Any suggestion on how to do this? My Java utils class loads the value from a myApp.properties file on the classpath, but I'm not sure I can utilize that from XSLT...

A: Declare an xsl:param in your stylesheet, so that the baseUrl value can be passed at invocation time:
<xsl:param name="baseUrl" />

Set the parameter on the Transformer object:
Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource);
transformer.setParameter('baseUrl', myUtils.getBaseUrl());
transformer.transform(xmlInput, xmlOutput);

If you are using XSLT 2.0, then you may consider using the resolve-uri() function when you are constructing the url variable value:
<xsl:variable name="url"
              select="resolve-uri(concat('/service?id=', @id), $baseUrl)" />

resolve-uri() can help compensate for trailing slashes, hashtags, and other things in the baseUrl that might otherwise result an invalid URL to be constructed by simply concatenating the $baseUrl with the fragment and @id.

A: Call setParameter on your Transformer instance, with the name and value of your parameter. Then inside your XSLT document declare the parameter using <xsl:param name="yourParamName" /> and you can then use it in your XSLT for example this way: <xsl:value-of select="$yourParamName" />


text:
Q: Understanding rubygems 'require' in sudo vs rvmsudo I'm using Ubuntu 12.04.4 TLS
I wrote a simple shell script in /home/abdo/sample_serv.sh that executes a Ruby file:
#!/bin/bash
/home/abdo/.rvm/rubies/ruby-2.1.0/bin/ruby /home/abdo/sample_serv.rb

and /home/abdo/sample_serv.rb containing the code below:
puts $:

require 'sinatra'

set :port, 8084

get '/' do
  %{ Hello from Abdo }
end

Executing rvmsudo ./home/abdo/sample_serv.sh works just fine but I would like to get sudo ./home/abdo/sample_serv.sh to work by passing the necessary environment variables because I am having issues with upstart.
The issue arises in my /etc/init/foo.conf
description "webserver test"

start on runlevel [23]
stop on shutdown

pre-start script
  exec >> /var/log/unicorn_test.log 2>&1
  echo starting
end script

script
  exec >> /var/log/unicorn_test.log 2>&1

  /bin/bash /home/abdo/.rvm/bin/rvmsudo /home/abdo/sample_serv.sh
  echo started
end script

When the line /bin/bash /home/abdo/.rvm/bin/rvmsudo /home/abdo/sample_serv.sh is reached, I get
/home/abdo/.rvm/rubies/ruby-2.1.0/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in
`require': cannot load such file -- sinatra (LoadError)

I was able to get the same ruby -v as that of my user but it looks like the GEM_PATH (even if I set it inside the upstart config file), is not helping.
Basically, if I can understand how (and where -- gem env is not helping since gem is not a command when I do sudo) rubygems looks for a file being required, I should be able to move forward.

A: When you run under sudo you run in a different environment, where gem is not installed, the $PATH is different, so things may not run smoothly.
You may want to try this:

Changing sudo's strict defaults
There are 3 things needed to mitigate this situation if you encounter
  it:

*

*the user that is invoking sudo must have export rvmsudo_secure_path=0 set on his shell environment (think .bashrc,
  .bash_profile or .zshrc)

*comment out Defaults secure_path=... on /etc/sudoers

*add Defaults env_keep +="rvm_bin_path GEM_HOME IRBRC MY_RUBY_HOME rvm_path rvm_prefix rvm_version GEM_PATH rvmsudo_secure_path
  RUBY_VERSION rvm_ruby_string rvm_delete_flag" to /etc/sudoers in
  rare cases it is required to add more variables - they should be
  reported by first run of rvmsudo.

  After these changes, you should be able to use rvmsudo preserving
  the same password/no-password directives as "normal" sudo calls.

Edit
If you don't want to change the defaults, you can try to synchronize the values of the environment values stated above (rvm_bin_path GEM_HOME IRBRC MY_RUBY_HOME rvm_path rvm_prefix rvm_version GEM_PATH rvmsudo_secure_path RUBY_VERSION rvm_ruby_string rvm_delete_flag) to your root user.
If that doesn't work, you can try installing rvm as root, and using that environment (instead of /home/abdo/.rvm/bin/rvm) to run your code.


text:
Q: Devtools not waiting for less to recompile css I have a grunt configuration to generate css files from less.  I have a watcher set, which is also generating the source-map and everything seems to be working fine except...
When I change the .less file in devtools, I get a message in console saying:
http://localhost/url/to/my.css?ver=3.9 resource missing.  Please
reload the page.

Which means my styles don't auto-refresh after I've changed the .less inside dev tools.  I have also noted that this message pops up before grunt is finished re-generating the .css file.
What am I missing here?

A: Okay found it!!  The problem turns out to be with wordpress.
when using wp_enqueue_style(...) it automatically appends a version number in the link to the resource (both CSS and JS).
To remove this, you can add this code inside your functions.php file
function remove_cssjs_ver( $src ) {
        if( strpos( $src, '?ver=' ) )
            $src = remove_query_arg( 'ver', $src );
        return $src;
    }
        add_filter( 'style_loader_src', 'remove_cssjs_ver', 10, 2 );
add_filter( 'script_loader_src', 'remove_cssjs_ver', 10, 2 );

Then your devtools should be running like a bomb!!  Who would have thought?  WordPress :(


text:
Q: What is the equivalent of 'Installer squeaksource' in Pharo? I want to execute this in the context of Pharo, was initially for Squeak.
Installer squeaksource
 project: 'MetacelloRepository';
 install: 'ConfigurationOfMagritte2'.
(Smalltalk at: #ConfigurationOfMagritte2) project latestVersion load: 'Magritte-Seaside'.

A: This code will work:
Gofer new
    squeaksource: 'MetacelloRepository';
    configurationOf: 'Magritte2';
    load.
(Smalltalk at: #ConfigurationOfMagritte2) project latestVersion load: 'Magritte-Seaside'.

There are other ways, but this is the most "direct" translation :)

A: That won't result in working code in a recent version of Pharo. Magritte2 is old and unsupported. Use Magritte3. That is maintained on Smalltalkhub.

A: For anyone with the same question today, in Pharo 6.x - current (9.0 as of writing):
Metacello new
  baseline: 'Magritte';
  repository: 'github://magritte-metamodel/Magritte';
  load


text:
Q: VBA code change to 64 bit. Macro to factor sales not working I inherited a very useful macro that now doesn't work on our new 64bit machines - I have amended the front to have the PtrSafe code which seems to work but am now getting a fault on the below macro that I use all the time. The macro works by amending the highlighted cells value to that of the new inputted number: The error seems to highlight the first = Mid code, but it also highlights in yellow the first line.

(Public Function ConcatAll(rngCells As Range, Optional pstrSep$ = "") As String)

Any help would be awesome.
Option Explicit

Public Function ConcatAll(rngCells As Range, Optional pstrSep$ = "") As String
  'Concatenates the text values in the specified range
  'Useful when coverting weeks to months

  Dim c As Range
  ConcatAll = ""

  For Each c In rngCells
    If c.Value <> "" Then
      ConcatAll = ConcatAll & pstrSep & c.Value
    End If

  Next

  ConcatAll = Mid(ConcatAll, Len(pstrSep) + 1)

End Function

Public Function ConcatUnique(rngCells As Range, Optional pstrSep$ = "") As String
  'Concatenates the text values in the specified range, only if the value has not been concatenated already
  'Useful when coverting weeks to months

  Dim c As Range, strConcat$
  strConcat = ""

  For Each c In rngCells

    If c.Value <> "" Then
      If InStr(1, strConcat, c.Value) = 0 Then
        strConcat = strConcat & pstrSep & c.Value
      End If

    End If

  Next

  ConcatUnique = Mid(strConcat, Len(pstrSep) + 1)

End Function

Public Function RPad(pstrSubj$, pintLen%, Optional pstrPad$ = " ") As String
'Pads out the right hand end of a given string with another character

  If Len(pstrSubj) >= pintLen Then
    RPad = pstrSubj

  Else
    Dim irpt%, strRes$
    strRes = pstrSubj
    Do Until Len(strRes & pstrPad) > pintLen
      strRes = strRes & pstrPad
    Loop

    If Len(strRes) < pintLen Then
      strRes = strRes & Left(pstrPad, pintLen - Len(strRes))
    End If

    RPad = strRes

  End If

End Function

Public Function LPad(pstrSubj$, pintLen%, Optional pstrLPad$ = " ") As String
'Pads out the left hand end of a given string with another character

  If Len(pstrSubj) >= pintLen Then
    LPad = pstrSubj

  Else
    Dim irpt%, strRes$
    strRes = pstrSubj
    Do Until Len(strRes & pstrLPad) > pintLen
      strRes = pstrLPad & strRes
    Loop

    If Len(strRes) < pintLen Then
      strRes = Left(pstrLPad, pintLen - Len(strRes)) & strRes
    End If

    LPad = strRes

  End If

End Function

Public Function ConcatIf(rngCells As Range, psCond$, Optional pstrSep$ = "", Optional prngVals As Range) As String
  'Concatenates the text values in the specified range if the condition is satisfied
  'Useful when coverting weeks to months

  ConcatIf = ""

  Dim rngVals As Range

  If Not (prngVals Is Nothing) Then
    If RngShapeEq(rngCells, prngVals) = True Then
      Set rngVals = prngVals

    Else
      'Ranges do not equal - return blank
      ConcatIf = "#Error"
      Exit Function

    End If

  Else
    Set rngVals = rngCells

  End If

  Dim iCell%, c As Range
  iCell = 1

  For Each c In rngCells

    If IsError(c) Then
      ConcatIf = "Error in cell " & c.Address
      Exit Function
    ElseIf IsError(rngVals.Cells(iCell)) Then
      ConcatIf = "Error in cell " & rngVals.Cells(iCell).Address
      Exit Function
    Else

      If Application.CountIf(c, psCond) > 0 Then

        ConcatIf = ConcatIf & pstrSep & rngVals.Cells(iCell).Value

      End If
    End If

    iCell = iCell + 1

  Next

  ConcatIf = Mid(ConcatIf, Len(pstrSep) + 1)

End Function

Private Function RngShapeEq(prng1 As Range, prng2 As Range) As Boolean
'Determines if the range shapes are equal

  RngShapeEq = False

  If prng1.Rows.Count = prng2.Rows.Count Then
    If prng1.Columns.Count = prng2.Columns.Count Then

      RngShapeEq = True

    End If
  End If

End Function

Public Function LTrim(pText$, Optional pTrimCh$ = " ") As String
'Trims the left end of the string with pTrimCh

  Dim intTrimChLen%
  intTrimChLen = Len(pTrimCh)

  LTrim = pText

  Do While Left(LTrim, intTrimChLen) = pTrimCh

    LTrim = Mid(LTrim, intTrimChLen + 1)

  Loop

End Function

Public Function RTrim(pText$, Optional pTrimCh$ = " ") As String
'Trims the right end of the string with pTrimCh

  Dim intTrimChLen%
  intTrimChLen = Len(pTrimCh)

  RTrim = pText

  Do While Right(RTrim, intTrimChLen) = pTrimCh

    RTrim = Left(RTrim, Len(RTrim) - intTrimChLen)

  Loop

End Function

A: The immediate issue I see is:
Public Function ConcatAll(rngCells As Range, Optional pstrSep$ = "") As String
  'Concatenates the text values in the specified range
  'Useful when coverting weeks to months
  Dim c As Range
  ConcatAll = ""
  For Each c In rngCells
    If c.Value <> "" Then
      ConcatAll = ConcatAll & pstrSep & c.Value ' *** Problem Here
    End If
  Next
  ConcatAll = Mid(ConcatAll, Len(pstrSep) + 1) ' Problem Here
End Function

The call to ConcatAll on the right hand side would expect to recursively call the Function. The VBA IDE would recognise that as ill-formed code and will stop, which also explains why it is highlighting the line in yellow. Use a temporary variable, and then assign to ConcatAll at the end of the Function.
Review all your remaining code, because you have repeated this error throughout.
Additionally, why redefine in interpreted code Native RTrim and LTrim functions? VBA is not very good for overloading. At least give them some other name to indicate they are custom functions.
In LPad you declare irpt but you don't use it.
And you declare a lot of integers. In this day and age, use Long at least! Or you can use Short if you really think space is an issue.


text:
Q: What is the easiest way to disable the touch pad on a laptop? What is the easiest way to disable the touch pad on a laptop?
I have a laptop which lacks a means to turn off the touchpad with a simple Function key sequence.  I would like to disable the touchpad so that it stops detecting movement when I am typing.  This is quite an annoyance as it sometimes results in deletions of sections of a sentence I am typing.  Right now I have a thick piece of paper over the top to decrease the sensitivity.
Any other suggestions on how to do this?

A: The simplest is often the best method. All (almost) windows-based laptops have touchpad / touchstyk running on drivers that are based on synaptics. These are easily accessible from :

Control Panel > Mouse > Choose Tab: Device Settings

Here you can Disable the touchpad.

A: Most touch pads can be disabled via it's preferences. The laptops I have all have a small app running in the system tray where I can access it's preferences.
But if you can't do it that way you could always disable it using the device manager found under "My Computer"->Preferences and it's on one of the tabs found there.
I don't know precisely what the tab/menu says because I have a Swedish version of windows.
Found a link: http://www.microsoft.com/windowsxp/using/setup/learnmore/devicemgr.mspx

A: Original post isn't real clear on if you need something that can be quickly turned back on or not.  Typically, the connector from the touchpad to the mobo is easily reached under the keyboard.  You could unplug it as long as you don't need to be able to turn it on/off on the fly (and you're not worried about warranty/possible accidental damage concerns).  Obviously, don't do this unless you're quite certain of what you're doing, etc.  Poking/proding the wrong thing could cause permanent damage.  Insert additional disclaimers here, etc.

A: I've not tried this myself, but you could try using the DevCon utility, which is kind of like Device Manager for the command line. You could, therefore, use it to write a couple of batch scripts to enable/disable your touchpad device. You could then bind these scripts to a couple of hotkey combos using Autohotkey or the like. Like I say, I've not tried this, though, so I'm not sure if it will work.
I found the following tutorial for using Devcon to enable/disable a wireless card, which is very similar to what you're trying to do.
http://www.wlanbook.com/enable-disable-wireless-card-command-line/

A: It might be worth a close inspection of the funny extra key combinations that most laptops have, often mapped onto normal keys along with a special shift key. My netbook has a touchpad, and the combination Fn+F3 toggles it on and off which is quite handy. Most of its F keys have an extra function accessed with the Fn key. My only real complaint is that Fn shares real estate with the left-shift key which is narrower than I'd like as a result.
I've seen similar features on other laptops. In one case, the touch pad was controlled by a non-obvious button along the top edge of the pad.
It'd be a shame to unplug it if such a feature is already there... Of course, it is also likely that the maker didn't think that feature would be important... but I personally would disable the pad with extreme prejudice if it didn't have a soft key to turn it off!

A: Often the manufacturer will have custom software that does this.

A: On Linux, just install syndaemon and run it when your session starts. I suggest you use the -k and -t options

A: If you were using a Mac you can turn off the trackpad when an external mouse is plugged in by by using the Keyboard & Mouse Preference Pane in System Preferences (< 10.5.6), or the Trackpad Preference Pane (10.5.7+).

A: I disabled the ability of the touchpad to do mouse clicks.
Even when I might touch the touchpad accidently it will only move the mouse curser with isn't any problem while typing.

A: Try http://tpp.desofto.com/. This disables the touchpad during typing.


text:
Q: Given K how do represent all of it's Binary Numbers I was asked a question that I could not solve.
The question was essentially.

given k is one and our output is ['0','1'], given that k is two and our output is ['00','01','10','11']

So essentially k represents the number of binary values to represent. If k is three we would want a list of binary numbers from 0-7, k is four we would want a list of binary numbers from 0-16.
For me I got lost on how to program it dynamically so given a number k we get our desired output.

A: These are binary representations of all numbers with the given number of digits. So iterate those numbers and format them as binary with padded zeroes. You can use the format specification mini language for this, for instance with an f-string:
def binary_numbers(k):
    return [f"{i:0>{k}b}" for i in range(1 << k)]

If you are supposed to do this with recursion, and not formatting of numbers into binary, then maybe this:
def binary_numbers(k):
    if k == 0:  # base case
        return [""]
    return [s + dig for s in binary_numbers(k-1) for dig in "01"]

A: Since the output grows exponentially with k, I'd recommend an iterable.
from itertools import product

def binary_numbers(k):
    return product('01', repeat=k)

From there you can do what you need with it.
for x in binary_numbers(3):
    print(''.join(x))

000
001
010
011
100
101
110
111


text:
Q: What does DISM Return Code 0x800F081E mean when installing WMF 4.0 on Windows 7 machines? (online) I'm using the Windows Update Agent to install WMF 4.0 on my Windows 7 workstations. I unpacked the MSU to get the cab files and install them using DISM online mode with the following commands (one for x86, one for x64 systems)
dism.exe /online /add-package /packagepath:.\Windows6.1-KB2872035-x86.cab /packagepath:.\Windows6.1-KB2872047-x86.cab /packagepath:.\Windows6.1-KB2819745-x86.cab /quiet /norestart
dism.exe /online /add-package /packagepath:.\Windows6.1-KB2809215-x64.cab /packagepath:.\Windows6.1-KB2872035-x64.cab /packagepath:.\Windows6.1-KB2872047-x64.cab /packagepath:.\Windows6.1-KB2819745-x64.cab /quiet /norestart
I get 0x800F081E as a return code, which isn't a Windows Error Message, so I think it's either a message from DISM or WIMGAPI, from what I found at http://msdn.microsoft.com/en-us/library/windows/desktop/hh825833.aspx. Restarting the system after receiving this error code results in a successful installation on all systems in testing, so I've flagged this return value to tell the Windows Update Agent that the system needs a reboot if that error code is detected. I just don't know what this message is supposed to be telling me, so I don't know if there's any action I need to take post-installation, or if I need to modify the command to make it work better.

A: Error 0x800F081E is CBS_E_NOT_APPLICABLE which means that the update can't be installed on the current system. This happens when a requirement is missing or the installed files have higher fileversion.
To see this in detail, share the CBS.log and DISM.log.


text:
Q: How to pass a if statement argument to scale_y_continuous()? I'm trying to pass an argument to scale_y_continuous() without luck. My last attempt using noquote() is below. My instinct tells me this is doable, but I haven't figured it out after a number of tries.
What I am trying to accomplish is this:
If the maximum of the y-variable (per group) is < 10, fix the y-axis limits at c(0,10). Else fix at c(0,20). An alternative: Else let the y-axis free scale, i.e, just
scale_y_continuous(pretty.breaks, 10) or some such.
Hopefully my example code is clear enough. The actual code will process several thousand id's, and so needs to be somewhat robust.
thanks in advance!
data1 <-
structure(list(group = c("AA", "AA", "AA", "AA", "AA", "AA",
"AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "BB", "BB",
"BB", "BB", "BB", "BB", "BB", "BB", "BB", "BB", "BB", "BB", "BB",
"BB", "BB", "CC", "CC", "CC", "CC", "CC", "CC", "CC", "CC", "CC",
"CC", "CC", "CC", "CC", "CC", "CC"), variable = c(11.453027,
10.600175, 9.886923, 8.942422, 11.585849, 10.604372, 8.813456,
9.388578, 9.403585, 10.078807, 10.170484, 10.31884, 10.307227,
10.720575, 10.974219, 0.7718116, 1.5862548, 0.5691476, 1.3747248,
1.6671187, 1.5524076, -0.3567432, 0.6318082, 0.681686, 1.9085089,
0.4098754, 0.2254707, 0.3161615, 0.2456526, 2.66832, 7.776831,
8.316334, 8.200448, 7.70843, 8.026592, 7.647327, 11.008817, 7.953072,
8.611409, 9.021719, 8.794007, 8.282669, 9.230021, 9.580956, 6.784829
), xval = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L,
13L, 14L, 15L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 15L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 13L, 14L, 15L)), class = "data.frame", row.names = c(NA,
-45L), .Names = c("group", "variable", "xval"))

Example Code:
if(max(data1$variable) < 10) my.scale <- noquote("limits=c(0,10), breaks=seq(0,10, 1)") else my.scale <- noquote("limits=c(0,20), breaks=seq(0,20, 1")

lapply(split(data1,data1$group), function(gg) {

    p1 <-   ggplot(gg,aes(x = xval, y = variable)) + geom_point() +
            geom_line() + theme_bw() +
                scale_y_continuous(my.scale)

p1
}
)

A: p1 <- ggplot(gg,aes(x = xval, y = variable)) + geom_point() +
        geom_line() + theme_bw()
if(max(data1$variable) < 10){
  p1 <- p1 + scale_y_continuous(limits=c(0,10), breaks=seq(0,10, 1))
}

Add conditions as necessary...


text:
Q: Problems calling a method from another Java class I am having a runtime error that states Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Status.copyState(Status.java:29) This is a class that is call the an instance of the Status calls (st): Main class is:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
/**
 *
 *
 * @author (Jason Sizemore)
 * @version (11-20-09 HW09)
 */
public class BetterCalculator extends Calculator
{
    //attributes
    private JButton undo;
    private String undoText;
    private Status st;

    public BetterCalculator()
    {
        super();
        st = new Status();

    }
    public void createUserInterface3()
    {
        createUserInterface2();
        undo = new JButton("undo");
        jPanel.add(undo);
        undo.setBackground(Color.red);
       undo.setToolTipText("This is the undo feature");
       undo.addActionListener(this);

    }
     public void actionPerformed(ActionEvent e)
     {
     super.actionPerformed(e);
     while(displayBox.getText() != null)
     {
         st.copyState();

        }
     if(e.getSource() == undo)
      {

        Status st;
        st = new Status();
       undoText = st.returnState();
        displayBox.setText(undoText);

      }

    }
    public static void main(String[] args)
    {

        BetterCalculator myCalc;
        myCalc = new BetterCalculator();
        myCalc.createUserInterface3();
    }
}

It is call the an instance of Status (st) Here is the Status class
import java.util.*;
import java.awt.event.*;
import java.awt.*;
/**
 * Write a description of class Status here.
 *
 * @author (Jason Sizemore )
 * @version (HW09 11-21-09)
 *  This is a class to get the status for the undo feature
 */
public class Status extends BasicCalculator
{
    //attributes
   private ArrayList<String> lastState;
   public String ls;

   public String rls;
    //constructors

    public Status()
    {
       lastState = new ArrayList<String>(10);

    }

    //Methods
    public void copyState()
    {
         //operand1 = Double.parseDouble(displayBox.getText());
          ls = displayBox.getText();
        lastState.add(ls);

    }
    public String returnState()
    {
       int sizeOfArrayList;
       sizeOfArrayList = lastState.size();
        rls = lastState.get(sizeOfArrayList);
        return rls;

    }
}

I know the issue is with the line ls = displayBox.getText(); I have a object take the return of a method on a object. what am I missing here.
Thanks for any help.

A: My guess is that displayBox is not set to anything by the time copyState is called.
Where is displayBox even declared?

A: As others have said it is likely that the displayBox variable is null.
The best way to deal with this is at compile time... if you get into the following habit you will catch that sort of mistake early:
public class TestFrame
    extends JFrame
{
    private final JButton aButton;
    private JButton bButton;

    public TestFrame()
    {
        // fails to compile since aButton is not instantiated
        // aButton = new JButton("A");
    }

    public init()
    {
        add(aButton);
        add(bButton);
        aButton.addActionListener(....);

        // crash at runtime since bButton is null
        bButton.addActionListener(....);
    }
}

by declaring variables as "final" the compiler forces you to give them a value.  Since the buttons (and other GUI items) are not likely to change you should be able to make them all final.  Once you have that you will have the com;iler help you out to avoid this sort of thing.

A: Try adding the following line as the first line of Status.Status():
super();

Let me know if that fixes the problem!


text:
Q: Why does taking a long step increase the chance of slipping? Me and my friend were walking and it was raining. He didn't have any grip on the slippers so he took smaller steps to avoid slipping. We both were wondering why does taking a long step increase the chance of slipping on the slippers and not on a short step?

A: You probably intuitively know the answer but just don't have the math, but it's because the angle relative to vertical your leg makes is smaller with small steps than with large steps. As a result, deviations in the angle your leg makes with the ground (ie, error in foot placement) correspond to changes in torque your leg needs to keep stable which are proportional to $\mbox{Sin}(\theta)$, where $\theta$ is the angle your leg makes with the normal to the ground (assuming flat ground). For small angles, this counterbalancing your brain and muscles need to make is proportional to the angle $\theta$. Thus placing your foot down with small steps make it easier to maintain balance.
How does surface slipperiness come in to play? Consider what happens when you aren't able to provide that compensating torque. Your foot will have a force component which points horizontally (you will try to slide forward). If this force component is above the static friction threshold your foot makes with the ground, you slip. When the ground is icy, this static friction threshold is small, and so when you make a small mistake in foot placement and your foot begins to push horizontally, you slip. Note that the horizontal force component that a vector with an angle $\theta$ relative to surface normal is proportional to $\mbox{Sin}(\theta)$. Thus large steps both increase the likelihood that you will make a mistake, and that the mistake will result in slippage.


text:
Q: Getting surrounding zip codes from a location using Apple Map Kit I'm getting started on Map Kit for my job and I have a IOS project I am working on where it involves Map Kit, I know how to search for a location and pin point it but my issues is that part of my project involves getting the next 10-15 zip codes of the surrounding areas of my central location and receive the cities that are in each zip code, i really don't know how to implement it and I need help. an explanation or a snippet of code would be much appreciated.

A: Zip codes like this aren't available in MapKit. You need to find a third-party source of zip code data (e.g. codes + bounding geometries), figure out a way to index them (perhaps be using or precalculating the centroid of each), and then figure out what's close to the selected point.

A: Use Google Places API for this.
You can go for a Radar or NearbyPlaces search and get zip codes of the returned places (you can use a custom location and set the radius for your search as you are wishing to do).
There is a really good iOS library for querying Google Places API which is FTGooglePlacesAPI
Eventually you can also do everything manually using
NSData* data = [NSData dataWithContentsOfURL:YOUR-googleRequestURL];

and handling the fetched data.