the breakpoint will not be hit, the source code is different than the original version - VS 2008

Question: VS 2008 is randomly giving me an error after working on a project for weeks. When I set a debug point, I get a warning: The breakpoint will not currently be hit. No symbols have been loaded for this document.
I have tried different things
1. Deleted the .suo file
2. Tried devenv /ResetSettings
3. deleted the temp files from Windows/Microsoft.net/framework/v2.0.50727\Temporary ASP.NET Files/
Does anyone has any idea how to fix this?
While debugging I get this in my Modules window
<code> mscorlib.dll    Skipped loading symbols.  70B60000-71658000   C:\Windows\assembly\GAC_32\mscorlib\18.104.22.168__b77a5c561934e089\mscorlib.dll
 System.Web.dll  Skipped loading symbols.  6D3F0000-6DF36000   C:\Windows\assembly\GAC_32\System.Web\184.108.40.206__b03f5f7f11d50a3a\System.Web.dll
 System.dll      Skipped loading symbols.  703C0000-70B59000   C:\Windows\assembly\GAC_MSIL\System\220.127.116.11__b77a5c561934e089\System.dll
 System.Configuration.dll Skipped loading symbols.  701D0000-702C1000   C:\Windows\assembly\GAC_MSIL\System.Configuration\188.8.131.52__b03f5f7f11d50a3a\System.Configuration.dll
 System.Xml.dll  Skipped loading symbols.  6FC90000-701C6000   C:\Windows\assembly\GAC_MSIL\System.Xml\126.96.36.199__b77a5c561934e089\System.Xml.dll
 System.Web.RegularExpressions.dll Skipped loading symbols.  508F0000-50926000   C:\Windows\assembly\GAC_MSIL\System.Web.RegularExpressions\220.127.116.11__b03f5f7f11d50a3a\System.Web.RegularExpressions.dll
 Microsoft.JScript.dll Skipped loading symbols.  5D700000-5D93D000   C:\Windows\assembly\GAC_MSIL\Microsoft.JScript\188.8.131.52__b03f5f7f11d50a3a\Microsoft.JScript.dll
 CppCodeProvider.dll Skipped loading symbols.  44C10000-44C2C000   C:\Windows\assembly\GAC_MSIL\CppCodeProvider\126.96.36.199__b03f5f7f11d50a3a\CppCodeProvider.dll
 System.Data.dll Skipped loading symbols.  6C2E0000-6C933000   C:\Windows\assembly\GAC_32\System.Data\18.104.22.168__b77a5c561934e089\System.Data.dll
 System.Web.Services.dll Skipped loading symbols.  51DA0000-51F65000   C:\Windows\assembly\GAC_MSIL\System.Web.Services\126.96.36.199__b03f5f7f11d50a3a\System.Web.Services.dll
 System.Drawing.dll Skipped loading symbols.  5F040000-5F1C7000   C:\Windows\assembly\GAC_MSIL\System.Drawing\188.8.131.52__b03f5f7f11d50a3a\System.Drawing.dll
 System.EnterpriseServices.dll Skipped loading symbols.  6B430000-6B4CD000   C:\Windows\assembly\GAC_32\System.EnterpriseServices\184.108.40.206__b03f5f7f11d50a3a\System.EnterpriseServices.dll
 System.EnterpriseServices.Wrapper.dll Skipped loading symbols.  03E20000-03E68000   C:\Windows\assembly\GAC_32\System.EnterpriseServices\18.104.22.168__b03f5f7f11d50a3a\System.EnterpriseServices.Wrapper.dll
 System.Web.Mobile.dll Skipped loading symbols.  77B10000-77D2F000   C:\Windows\assembly\GAC_MSIL\System.Web.Mobile\184.108.40.206__b03f5f7f11d50a3a\System.Web.Mobile.dll
 DundasWebChart.DLL Skipped loading symbols.  11000000-1106E000   C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\iep_31_base\d311e736\8bee08e7\assembly\dl3\d9d476fd\00ba2da1_9469c201\DundasWebChart.DLL
 IEP_31_Base.DLL Symbols loaded.           02990000-02FC0000   C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\iep_31_base\d311e736\8bee08e7\assembly\dl3\c47ce5b2\9cd8c9b4_ca85cb01\IEP_31_Base.DLL
 NetchemiaFoundationClasses.DLL Skipped loading symbols.  02000000-0207C000   C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\iep_31_base\d311e736\8bee08e7\assembly\dl3\f3cbc113\035f09b7_5066cb01\NetchemiaFoundationClasses.DLL
 NetchemiaFoundations.DLL Skipped loading symbols.  030C0000-03174000   C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\iep_31_base\d311e736\8bee08e7\assembly\dl3\dbd1286a\eef01e76_d07acb01\NetchemiaFoundations.DLL
 netIEPManagementClasses.DLL Skipped loading symbols.  01130000-01148000   C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\iep_31_base\d311e736\8bee08e7\assembly\dl3\254fc8c5\1ada8ebe_5066cb01\netIEPManagementClasses.DLL
 System.Runtime.Serialization.dll Skipped loading symbols.  6E070000-6E2B1000   C:\Windows\assembly\GAC_MSIL\System.Runtime.Serialization\22.214.171.124__b77a5c561934e089\System.Runtime.Serialization.dll
 System.IdentityModel.dll Skipped loading symbols.  6E2D0000-6E3D9000   C:\Windows\assembly\GAC_MSIL\System.IdentityModel\184.108.40.206__b77a5c561934e089\System.IdentityModel.dll
 System.ServiceModel.dll Skipped loading symbols.  6E4E0000-6F57C000   C:\Windows\assembly\GAC_MSIL\System.ServiceModel\22.214.171.124__b77a5c561934e089\System.ServiceModel.dll
 System.ServiceModel.Web.dll Skipped loading symbols.  6D0F0000-6D293000   C:\Windows\assembly\GAC_MSIL\System.ServiceModel.Web\18.104.22.168__31bf3856ad364e35\System.ServiceModel.Web.dll
 System.WorkflowServices.dll Skipped loading symbols.  6D2A0000-6D3F0000   C:\Windows\assembly\GAC_MSIL\System.WorkflowServices\184.108.40.206__31bf3856ad364e35\System.WorkflowServices.dll
 System.Core.dll Skipped loading symbols.  51880000-51AB4000   C:\Windows\assembly\GAC_MSIL\System.Core\188.8.131.52__b77a5c561934e089\System.Core.dll
 System.Data.DataSetExtensions.dll Skipped loading symbols.  02080000-020A5000   C:\Windows\assembly\GAC_MSIL\System.Data.DataSetExtensions\184.108.40.206__b77a5c561934e089\System.Data.DataSetExtensions.dll
 System.Web.Extensions.dll Skipped loading symbols.  6CD20000-6CF6E000   C:\Windows\assembly\GAC_MSIL\System.Web.Extensions\220.127.116.11__31bf3856ad364e35\System.Web.Extensions.dll
 System.Web.Abstractions.dll Skipped loading symbols.  50460000-50486000   C:\Windows\assembly\GAC_MSIL\System.Web.Abstractions\126.96.36.199__31bf3856ad364e35\System.Web.Abstractions.dll
 System.Xml.Linq.dll Skipped loading symbols.  77AA0000-77B06000   C:\Windows\assembly\GAC_MSIL\System.Xml.Linq\184.108.40.206__b77a5c561934e089\System.Xml.Linq.dll
 A_495e38af_86f6_4a92_91e6_eee0640b999b No symbols loaded.        00000000-00000000   A_495e38af_86f6_4a92_91e6_eee0640b999b
 M_495e38af_86f6_4a92_91e6_eee0640b999b No symbols loaded.        00000000-00000000   M_495e38af_86f6_4a92_91e6_eee0640b999b
 App_global.asax.7p2wok51.dll Symbols loaded.           03030000-0303A000   C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\iep_31_base\d311e736\8bee08e7\App_global.asax.7p2wok51.dll
 Microsoft.VisualBasic.dll Skipped loading symbols.  51080000-5121B000   C:\Windows\assembly\GAC_MSIL\Microsoft.VisualBasic\184.108.40.206__b03f5f7f11d50a3a\Microsoft.VisualBasic.dll
</code>
>
Comment: Do a Clean Solution, then Build Solution to clear out any stale PDBs and DLLs.
Comment: Are you using attach to process to debug?
Comment: @ryudice - yes, I am using the "attach to process" to attach the w3wp.exe
Comment: @Oded - I tried that...did not help.Also FYI..I am running VS 2008 on Windows 7 Machine
Answer: stop the debugger
close the IDE
close the hosting application
Restart Vs using command devenv /resetsettings
rebuild the project
Answer: The resetsettings didn't work for me so shutdown visual studio and went into the project that contained the file and deleted the bin and obj directories.


Access VNC server running in Android from Ubuntu

Question: I am running ubuntu in an android phone and I have the address of its vnc server. Is it possible to access the vncserver from another computer in the same network?
I connected the laptop to the mobile phone's Ethernet hotspot and tried to connect to localhost:1 (which works with the mobile phone's vnc viewer) in Real VNC but it said that the remote computer refused to connect.
Answer: Go to the phone settings --> about. Find the IP address.
Then, in VNC viewer, connect to IP:address:5901 (5901 stands for localhost:1)


Can OCaml dune build a project that has a flat directory structure?

Question: Suppose I want to use dune to build a project that has a flat directory structure:
my_project/
├── dune
├── basics.ml
├── basics.mli
├── utils.ml
├── utils.mli
└── main.ml

main.ml is the main program (the entry point). main.ml depends on utils.ml, while utils.ml in turn depends on basics.ml. main.ml calls functions in utils.ml using prefix Utils (e.g. Utils.example_function x y).
The question: What should I write in the dune file in order to compile this project?
So far, all the dune examples I have seen use this directory structure instead:
my_project/
├── dune
├── main.ml
└── mylib
    ├── dune
    ├── basics.ml
    ├── basics.mli
    ├── utils.ml
    └── utils.mli

Where my_project/dune is:
(executable
  (name main)
  (libraries mylib))

and my_project/mylib/dune is:
(library (name mylib))

and main.ml calls functions in utils.ml using prefix Mylib.Utils (e.g. Mylib.Utils.example_function x y).
I do not want this directory structure; I do not want to create a separate directory for utils.ml and basics.ml. I want all source files to be in the same directory as main.ml. Is there a way to do this using dune?
Answer: You have to list modules of each library/executable for this to work:
(executable
  (name main)
  (modules main)
  (libraries mylib))

(library
  (name mylib)
  (modules utils basics))

Or you can just put everything in your executable:
(executable
  (name main)
  (modules basics main utils)) ; and this line is not needed anymore

Comment: Does the order in the `(modules ...)` matter?


Why does C++ allow passing the array size at run-time to a function in order to construct a fixed-size array?

Question: According to my opinion, the following piece of code should not compile. Yet, it does and prints perfectly:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
In fact, it does even if I remove "const" from the parameter.
void arrayTest(const int size) {

    int myArray[size];
    for(int i=0; i<size; i++) {
        myArray[i] = i;
    }
    for(int i=0; i<size; i++) {
       cout << myArray[i] << " ";
    }
    cout << endl;

}

int main() {
   arrayTest(15);
   return 0;
}

I am puzzled because I know that the size of an array is a constexp which must be evaluated at compile time. Also, I do not involve any sort of dynamic allocation (i.e. I do not use malloc(), new, etc). The function's local variables are all created on the stack. No heap involvement, whatsoever!
So, why is it compiling?
Comment: Some compilers (unfortunately) allow variable length arrays by default. For GCC, check this question on how to disable it: [Disable variable-length automatic arrays in gcc](https://stackoverflow.com/questions/31710642/disable-variable-length-automatic-arrays-in-gcc)
Comment: No, VLAs are allocated on the stack. You may want to look at this question: [How does the compiler allocate memory without knowing the size at compile time?](https://stackoverflow.com/questions/46387111/how-does-the-compiler-allocate-memory-without-knowing-the-size-at-compile-time) to learn what's under the hood. But still, this is not valid C++ syntax and it's only compiling because of compiler extension.
Comment: Yksisarvinen, are you suggesting that under the hood the compiler is using dynamic allocation?
Comment: "Under the hood" compiler is using kind-of "dynamic allocation" _on stack_. [alloca](http://man7.org/linux/man-pages/man3/alloca.3.html).
Answer:
Why does C++ allow passing the array size at run-time to a function in order to construct a fixed-size array?

C++ language does not allow you to use a function parameter as the length of an array variable. The length of an array must be a compile time constant expression.
The length of myArray in your example is not a compile time constant expression, therefore the program is ill-formed.

So, why is it compiling?

Because your compiler chose to do so. The C++ language merely allows the compiler to fail compilation of ill-formed programs. They are allowed to compile succesfully, which lets the compiler to extend the language. You are using a language extension.
The C++ standard does require the compiler to diagnose ill-formed programs (except when allowed not to do so by a specific rule), and if it did not issue a diagnostic message for you, then the compiler does not conform to the standard.
Here is example output from a conforming compiler:

warning: ISO C++ forbids variable length array 'myArray' [-Wvla]
Comment: @softwarelover That would make the compiler conform to C++14. You can see the list of supported options in the manual of your compiler.
Comment: After adding this flag, my compiler is now considering it an error and does not compile anymore:
-Werror=vla
Comment: @softwarelover If you're using Clang or GCC, then you can instead use the `-std=c++17 -pedantic`, which ask the compiler to conform to the particular standard given as argument. That way you aren't limiting yourself to disabling only one language extension.
Comment: That's wonderful, eerorika. Could I use -std=c++14 -pedantic, instead of 17?


How to specifiy content template based on type

Question: I have a TabControl with a single specific tab, that holds a user control (ui:GeneralControl), and a collection bound to a collection of VMs, using another user control (ui:ModelControl). To do this I use a CompositeCollection and DataTemplates.
I have defined DataTemplates in the control's resources with the target type, but it doesn't get selected as correctly as ContentTemplate.
What's wrong with this code?
<TabControl>
    <TabControl.Resources>
        <CollectionViewSource x:Key="modelsCollection" Source="{Binding OpenedModels}" />
        <DataTemplate DataType="{x:Type main:ProjectViewModel}">
              <ui:GeneralControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type models:ModelViewModel}">
            <ui:ModelControl />
        </DataTemplate>
    </TabControl.Resources>
    <TabControl.ItemsSource>
        <CompositeCollection>
            <TabItem Header="General" />

            <CollectionContainer Collection="{Binding Source={StaticResource modelsCollection}}"/>
        </CompositeCollection>
    </TabControl.ItemsSource>
    <TabControl.ItemTemplate>
        <DataTemplate DataType="models:ModelViewModel">
            <TextBlock Text="{Binding Name}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>

Comment: Automatic template selection based on DataType only works if you do not explicitly specify the tabControl's ItemTemplate.
Comment: You have to use `DataTemplateSelector`.
Comment: @AnjumSKhan You don't have to use DataTemplateSelector.
Comment: @Clemens if I don't specify explicitely ItemTemplate, it works correctly. But then how can I correctly bind tab item's name?
Comment: Don't you see the ModelControl / GeneralControl  when you select the tabs or what's your issue?
Comment: Have you tried setting the `TabControl`'s [ContentTemplateSelector](https://msdn.microsoft.com/en-us/library/system.windows.controls.tabcontrol.contenttemplateselector(v=vs.110).aspx) to return which template to use for each item?
Comment: @Clemens I guess I still have a problem with template selection conflicting with specifying ItemTemplate... I posted another question https://stackoverflow.com/q/44457888/11343
Comment: @Clemens that's confusing it should be `ContentTemplate` which shouldn't be specified explicitly, however the comment was still helpful for me as I was able to figure it out
Comment: @PiotrGolacki It is also the ItemTemplate of an ItemsControl that should not be set explicitly if you want automatic DataTemplate selection. Be aware that ItemTemplate is the DataTemplate that is used as ContentTemplate by the item container.
Comment: @Clemens it works for me with the `ItemTemplate` specified, and if I don't specify it the tabs don't show and I have my templates stacked horizontally instead
Answer: Thanks to Clemens I figured out I was on the right way, I was just missing binding on one tab:
I have a Data Error, but it's in another question :)
<TabControl>
    <TabControl.Resources>
        <CollectionViewSource x:Key="modelsCollection" Source="{Binding OpenedModels}" />
        <DataTemplate DataType="{x:Type main:ProjectViewModel}">
              <ui:GeneralControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type models:ModelViewModel}">
            <ui:ModelControl />
        </DataTemplate>
    </TabControl.Resources>
    <TabControl.ItemsSource>
        <CompositeCollection>
            <TabItem Header="General" Content="{Binding ProjectViewModel}"/>

            <CollectionContainer Collection="{Binding Source={StaticResource modelsCollection}}"/>
        </CompositeCollection>
    </TabControl.ItemsSource>
    <TabControl.ItemTemplate>
        <DataTemplate DataType="models:ModelViewModel">
            <TextBlock Text="{Binding Name}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>


Why the value of id="demo2: is still zero evene it is incrementing by one

Question: So what I am trying to do is, animate using javascript. It is working fine but I also want to show the value of pos(variable) in code, to show the value gradually.
problem:
the value of demo2 is not changing even the scope of the variable is same. why not #demo2 not changing.
Please let me know the reason and solution that value of the id #demo2 also change as the value of id #demo changing.
<!DOCTYPE html>

    function myMove() {
      let id = null;
      const elem = document.getElementById("animate");
      let pos = 0;
      clearInterval(id);
      id = setInterval(frame, 5);
      function frame() {
        if (pos == 350) {
          clearInterval(id);
        } else {
          pos++;
          elem.style.top = pos + "px";
          elem.style.left = pos + "px";
        }
        document.getElementById("demo").innerHTML = pos;
      }

      document.getElementById("demo2").innerHTML = pos;
    }
    </script>

<button onclick="myMove()">Click Me</button>

function myMove() {
      let id = null;
      const elem = document.getElementById("animate");
      let pos = 0;
      clearInterval(id);
      id = setInterval(frame, 5);
      function frame() {
        if (pos == 350) {
          clearInterval(id);
        } else {
          pos++;
          elem.style.top = pos + "px";
          elem.style.left = pos + "px";
        }
        document.getElementById("demo").innerHTML = pos;
      }

      document.getElementById("demo2").innerHTML = pos;
    }
#container {
      width: 400px;
      height: 400px;
      position: relative;
      background: yellow;
    }
    #animate {
      width: 50px;
      height: 50px;
      position: absolute;
      background-color: red;
    }

<button onclick="myMove()">Click Me</button>

<button onclick="myMove()">Click Me</button>

Answer: The function frame() is executed after every other instructions in your function myMove().
If you want to change the value of #demo2 you have to put it in the same scope as the function frame() because that is where the value is updated. Otherwise you will get the value pos has when it is initialized.
function myMove() {
    let id = null;
    const elem = document.getElementById("animate");
    let pos = 0;
    clearInterval(id);
    id = setInterval(frame, 5);
    function frame() {
        if (pos == 350) {
            clearInterval(id);
        } else {
            pos++;
            elem.style.top = pos + "px";
            elem.style.left = pos + "px";
        }
        document.getElementById("demo").innerHTML = pos;
        document.getElementById("demo2").innerHTML = pos;
    }
}

Comment: so it means that If there is any kind of wait I t will execute the next lines of code.(what this kind of behavior called?)
can we deal with this, first do this then move next?
Comment: If you want to execute in a certain order you can chain your code using [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) but it can complexify your code


How to have the type of boot detected by the kernel and written to a file (perhaps in /proc)

Question: This is probably not possible, but I want to know how to have the kernel detect what caused the motherboard to start and possibly store that in a file in the /proc folder.
With "what caused the motherboard to start" I mean if it was because the power button was pressed, because a Wake On Lan signal was received, because of a scheduled boot, or something else.

I need this because I frequently use my iPhone to start my computer when I get home via Wake On Lan, and I have configured Ubuntu to log in automatically so that when I start using my PC it is ready loading and starting everything scheduled to start at login, such as Skype or Steam.
However, when I use WOL to start it, and Skype goes online, people may think I'm there when I'm not and start messaging me but get no reply from me. When I start the PC using the power button I am usually going to use it right after it's logged in, so my skype contacts won't think I'm there when I'm not. So if I could configure it to not start Skype if a WOL signal initated the boot, but do start Skype if the power button initiated the boot.
Answer: The way a computer is started is not saved and not passed onto the operating system.

and Skype goes online, people may think I'm there when I'm not

I would assume it would be less trouble to start Skype with your status set to "off line" or "invisible".

and start messaging me but get no reply from me.

I do not see a problem here. If you do not respond you are not there.
Comment: Well, ok then. I didn't think it was possible to do it anyway.
Comment: :D  "If you do not respond, you're not there"...  Just that is worthy of an upvote!


probability puzzle, expected payoff for game

Question: This was a question at a programming contest that finished recently at interviewstreet:

Alice and Bob play a game. The operations at round $i$ ($i ≥ 1$) is as follows:

Alice pays Bob $2i - 1$ dollars,
Alice tosses a biased coin,
If the result of the coin was heads for $k$ consecutive rounds, the game stops, otherwise the game continues.

Given $k$ and the probablity $p$ that the outcome of a toss is heads, your program should find the expected number of dollars Alice pays Bob, and also the expected number of rounds played.

I had gotten the first part of the problem, i.e the expected number of rounds of the game. I got it with the following code
<code>if __name__ == '__main__':
    t = int(raw_input())
    while t :
        t -= 1
        temp = str(raw_input())
        p,k = temp.split(' ')
        p = float(p)
        k = int(k)
        num = k * (p**k)
        den = 1
        q = 1.0 - p
        for N in range(1,k+1):
            den = den - ((p**(N-1))*q)
            num = num + (N*(p**(N-1))*q)
            #print (N*(q**N))

        print int(num/den)
</code>
But the second part of the problem is still puzzling me, i.e the expected number of dollars Alice pays bob. How can expected payoff be calculated?
Answer: Call $N$ the number of rounds played, then the number of dollars paid by Alice is $N^2$. The usual one-step recursion yields
$$
\mathrm E_i(s^N)=s(p\mathrm E_{i+1}(s^N)+(1-p)\mathrm E_0(s^N)),
$$
for every $0\leqslant i\leqslant k-1$, with $\mathrm E_k(s^N)=1$. One is after $\mathrm E_0(N)$ and $\mathrm E_0(N^2)$ and the linear system above yields
$\mathrm E_0(s^N)=u(s)$ with
$$
u(s)=\frac{(1-ps)(ps)^k}{1-s+(1-p)s(ps)^k}=1-(1-s)\frac{1-(ps)^k}{1-s+(1-p)s(ps)^k},
$$
hence $u'(1)=\mathrm E_0(N)$, that is,
$$
\mathrm E_0(N)=\frac{1-p^k}{(1-p)p^k}.
$$
Similarly, $u''(1)=\mathrm E_0(N(N-1))$. This yields a slightly more complicated, but explicit, formula for $\mathrm E_0(N^2)$.
Comment: Thank you for your answer. I don't quite understand, some of the notation, what is s, and how did you calculate u(s)?
Comment: The argument $s$ can be any number such that $|s|\leqslant1$. One computes $u(s)$ by considering, for each such $s$, the affine system the vector $(\mathrm E_i(s^N))_{0\leqslant i\leqslant k}$ solves.


Transcoding with dynamic arguments and validator problems

Question: I'm receiving the following csv
0000595182;3
0000504290;
0000710842;3
0000754608;1
0000489193;6
0000793814;4
0000580308;5
0000399045;
0000068910;
0000210986;2
0000908352;5
0000130721;
0000097876;2
0000185893;
0000218924;
0000456669;4
0000671520;4
0000796097;1
0000709024;3
0000203990;
0000205763;8
0000218211;4
0000409543;
0000994506;5

I'm trying to transcode the one digit number on the right (2nd Column) to the CodeOT on the following json table.
[
  {
    "CodeSap": null,
    "CodeOT": 1
  },
  {
    "CodeSap": 0,
    "CodeOT": 1
  },
  {
    "CodeSap": 1,
    "CodeOT": 2
  },
  {
    "CodeSap": 2,
    "CodeOT": 2
  },
  {
    "CodeSap": 3,
    "CodeOT": 2
  },
  {
    "CodeSap": 4,
    "CodeOT": 2
  },
  {
    "CodeSap": 5,
    "CodeOT": 2
  },
  {
    "CodeSap": 6,
    "CodeOT": 3
  },
  {
    "CodeSap": 7,
    "CodeOT": 3
  },
  {
    "CodeSap": 8,
    "CodeOT": 3
  },
  {
    "CodeSap": 9,
    "CodeOT": 3
  }
]

So I need to match the digit on the right of the csv to the CodeSAP and then change it to the CodeOT that matches to get this output:
{
  "listeMaj": [
    {
      "refSig": "0000595182",
      "risqueFinancier": "2"
    },
    {
      "refSig": "0000710842",
      "risqueFinancier": "2"
    }
  ]
}

To get there I tried this but i seem to be getting an unusual error as if I can't pass dynamic arguments.
Here's my code :
%dw 2.0
input payload application/csv header=false,separator=";"
output application/json
var pldFix= payload map ((value,key)->
                {refSig: value.column_0,
                indicateur: value.column_1}
                )
fun Find(val) = (trTable.CodeSap find (if(val == "" or val == null) null else val as Number))

var test = pldFix map ((value, key) ->
            if (value.refSig == null or sizeOf(value.refSig) == 10)
                okLines :{
                    refSig: value.refSig,
                    risqueFinancierBF: (trTable[Find(value.indicateur)[0]].CodeOT)
                }
            else
            {
               koLines: {
                        refSig: value.refSig,
                        risqueFinancierBF: if(value.indicateur == "") null else value.indicateur as Number
                    }
            }
)
var koLines = flatten([test.*koLines])
var okLines = flatten([test.*okLines])
---
okLines

And the error is about dynamic arguments passed to the function, which I don't understand why?
You called the function 'Dynamic Selector' with these arguments:
  1: Array ([{CodeSap: null,Libelle: "",CodeOT: 1}, {CodeSap: 0,Libelle: "Elle a demandé ...)
  2: Null (null)

But it expects one of these combinations:
  (Array, Range)
  (Array, Number)
  (Array, Name)
  (Array, String)
  (Binary, Range)
  (Binary, Number)
  (Date, Name)
  (DateTime, Name)
  (LocalDateTime, Name)
  (LocalTime, Name)
  (Object, Name)
  (Object, Number)
  (Object, String)
  (Period, Name)
  (String, Range)
  (String, Number)
  (Time, Name)

14|                     risqueFinancierBF: (trTable[Find(value.indicateur)[0]].CodeOT)
                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Trace:
  at main::main (line: 14, column: 41)

The constraint is I also have to get the data from a database so it might change over time. And I have to check for the refSig to be at 10 characters exactly. I didn't get successfull as I keep getting "Cannot coerce Null(null) to Number" errors too. Any advice or help ?
Answer: The code that you provided is working with the inputs that you have shared. Probably you are getting a indicateur that does not exists as any CodeSap and due to which your Find function is returning a blank array [] and therefore your expression trTable[Find(value.indicateur)[0]] results as trTable[null] due to which you are getting the error.
As an additional suggestion you can try to use join and avoid writing all the extra functions. Join will join the two arrays based on the parameter that you will provide and give a joined array as output that you can easily map as per your output.
For details on the output structure you can refer to the official doc. The output can be confusing initially but it works the same way as join works in SQL. You can use leftJoin or outerJoin if you want to including the records that does not have corresponding CodeSap
%dw 2.0
import join from dw::core::Arrays
input payload application/csv header=false,separator=";"
output application/json
---
join(
    payload filter (sizeOf($.column_0) == 10),
    vars.trTable,
    (record) -> record.column_1,
    (code) -> code.CodeSap default "" // in csv there are no null, so null needs to be treated as blank string for matching with corresponding csv record
)
map {
    refSig: $.l.column_0,
    risqueFinancierBF: $.r.CodeOT
}

Comment: @Zyoumir Added `filter` for exclude values where size of first column is not equal to 10
Comment: NIce. just want to point out that using `join` will exclude those records that does not match with the corresponding `codeSAP`
Comment: I will try this right now and be right back with the feedback, thank you for you response


Javascript DOM-event origin and dependencies

Question: Imagine that there's a button on one web page (not mine) and when it's clicked it performs some
Javascript. I want to have a button on my web page that performs exactly the same. So I need to
attach all necessary js files (but first I have to find them) to my html page and sometimes add some js to my html page.
What I usually do in this case? I inspect this button html element to see if there's onclick attribute for this button. If it is, I see the function called when button is clicked and then I try to search for this function in current html page and all js files attached to page. Also I need to find all dependencies (like jQuery, fancybox etc.).
If the button doesn't have onclick attribute I have to look for direct getElementById or jQuery selector   pointing to this button with rest of code there. Sometimes there's no such a selector and I have to find a nested selector - really hard and annoying thing.
Is there any better, automated way for doing things above. Ideally after selecting the element in DOM (button in this case) and pressing some magic button I will be able to see all js files involved in processing this click and also js code in html page.
Answer: It's going to involve digging no matter what you do. But Chrome's Dev Tools can help with the attached event handlers, to an extent. When you right-click an element and inspect it, on the right-hand side there's a panel showing various tabs: [Styles] [Computed] [Event Listeners] [DOM Breakpoints] [Properties]. The [Event Listeners] one shows the listeners directly attached to that element. Of course, on a site using jQuery (which is more than half the sites using JavaScript at all), looking at the handler will dump you into the jQuery event handling code, but it's a start.

Just as a side point: While it's fine to look at the source of pages for inspiration, or to see how they solved a particular problem, or what plugins they're using to get an effect, etc., I assume you're not grabbing large sections of their actual code (as opposed to libraries and plugins with liberal licenses) without their permission, which is probably not cool.
Comment: actually I'm creating page on web-site where previous developer created another one. And it's his page from where I want to copy functionality.


Supremum of sequence of piecewise linear functions

Question: Suppose we have a sequence of continuous and piecewise linear functions $(f_n)_{n\in\mathbb{N}}$ mapping from $\mathbb{R}^d$ to $\mathbb{R}$. Assume this sequence of functions converge pointwise to some continuous function $f:\mathbb{R}^d \to \mathbb{R}$.
I want the show that there exists a continuous piecewise linear function $\bar f \neq f$ such that
$$
\sup_{n\in\mathbb{N}} f_n(x) = \max \{f(x), \bar f(x)\}.
$$
Is the above true??? Is the below also true for some continuous piecewise linear function $\bar f \neq f$?
$$
|\sup_{n\in\mathbb{N}} f_n(x)| \leq \max \{|f(x)|, |\bar f(x)|\}.
$$
Answer: Neither is true. For a function $g$ to be bounded above by a continuous function, it is necessary and sufficient that it is bounded above on compact intervals.
For a counterexample, consider the functions $f_n$ taking values $0,n,0$ on $0,1/n,2/n$ respectively and extending by linear interpolation to $\mathbb R\to\mathbb R.$ These converge pointwise to zero. But their pointwise supremum is unbounded on $[-1,1]$ so cannot be bounded by a continuous function.
If the function $g$ defined by $g(x)=\sup_nf_n(x),$ or $g(x)=|\sup_nf_n(x)|$ for the second question, is bounded above on compact intervals, and if you allow infinitely many domains in the definition of "piecewise", then it is easy to construct a piecewise upper bound. You can define
$$f_1(x)=\max(0,\sup_{r\in [-1,1]^d} g(x+r))\qquad\text{ for $x\in\mathbb Z^d$}$$
Let $\phi(x)=\max(0,2-\max(1,|x_1|,\dots,|x_d|)).$ Define $\overline{f}(x)=\sum_{y\in\mathbb Z^d}\phi(x-y)f_1(y).$ Note the only non-zero terms have $|y_i|<1,$ and since there is at least one integer point $y$ with $\max(|x_i-y_i|)\leq 1$ we get $\overline{f}(x)\geq f_1(y)\geq f(x).$
You do need infinitely many domains for $\overline{f}$ even in this case. Consider $f(x)=x^2,$ with $f_n$ linearly interpolating $f$ at multiples of $1/n$ in the range $[-n,n].$
Comment: Thanks. So if I replace pointwise convergence with uniform convergence, then the first equality should hold right? What about with compact convergence (uniform convergence on all compacts sets)?
Comment: @master_goon: if you have uniform convergence then $\|f_1-f\|_\infty\leq C$ for some $C$, which means $|\sup f_n(x)|$ is bounded by $|f_1(x)|+C,$ which is already piecewise linear (it might have infinite boundary due to the absolute value, though this can probably be avoided with a bit of care). The same argument applies for the restriction to a compact set.
Comment: Thanks again. I'm not familiar with your linear extension i.e. $\bar f(x + \theta)$ and I'm struggling to see its intuition. Can you explain this to me or point me to a reference, please?
Comment: @master_goon: sorry, that wasn't actually linear (it was the "Lovasz extension"). It should be pretty intuitive that you can get SOME piecewise linear function as long as the function is locally bounded. I've added another suggested construction but basically anything linear should work.


Regular Expression for multiple folder names in URL and Excluded Extension Flags

Question: I'm processing multiple js files to build bundles via webpack. However I need to target multiple js files to process across multiple folders, while being able to exclude js files with certain flags in the filename.
I have the following files:
/styles/portal/version2/libraries/jquery.js
/styles/portal/version2/libraries/library.exclude.js
/styles/portal/version2/components/componenta.js
/styles/portal/version2/konstructs/konstructa.js
/styles/portal/version2/konstructs/konstructb.js
/styles/portal/version2/konstructs/konstructc.js
/styles/portal/version2/konstructs/konstructd.disabled.js
/styles/portal/version2/vendors/vendor.js
/styles/portal/version2/vendors/vendor.exclude.js

And this should only grab the following files to bundle:
/styles/portal/version2/libraries/jquery.js

/styles/portal/version2/konstructs/konstructa.js
/styles/portal/version2/konstructs/konstructb.js
/styles/portal/version2/konstructs/konstructc.js

/styles/portal/version2/vendors/vendor.js

So essentially any .js file out of the specific libraries, konstructs, vendor folders and then don't include anything with disabled.js or exclude.js
Comment: A single regex would be terribly cluttering to do this (not to mention maintaining) . How does your bundle engine work? Is it Javascript? If so, you'd be better off writing some code and implementing a dictionary-like structure to filter the files.
Comment: Would the regex be for inclusion or exclusion ? Because if using exclusion, it might miss something. Is it better to be %100 sure using just inclusions or less sure using exclusions ?
Comment: @EricWu I'm writing this for a glob match pattern for webpack entry point
Comment: @x15 The files grabbed are for inclusion so include only those in librarires/konstructs/vendors, and that don't have the disabled.js or exclude.js file extensions
Answer: To get the three directories libraries, konstructs or vendors that contain
non-disabled nor exclude in the file name parts of .js files would be this:
/^.*?\/(?:libraries|konstructs|vendors)(?=\/)(?:[^\/.]*\/)*(?![^\/]*?\b(?:disabled|exclude)(?=\.)[^\/]*?\.js$)[^\/]*?\.js$/gm
https://regex101.com/r/rTUfeQ/1
Note, use the multi-line modifier if looking at multi-line strings.
If not, no need for it.
Answer: You can try exclude option in rule-condition with this pattern
/\.(exclude|disabled)\.js$/

\. - Matches .
(exclude|disabled) - Match exclude or disabled word
\.js - Matches . followed by js
$  - End of string
Comment: You misspelled `disabled` in the regex code. Can't edit: less than 6 characters :man-facepalming:
Comment: @SethDuncan those you can consider those in test or include, something like. `/(konstructs|vendor)\.js$/`
Comment: So that solves the exclusion of the disabled.js & exclude.js types, how would I solve for konstructs, libraries, vendors folder requirements ?


Kafka-pyspark Streaming: KafkaException: Failed to construct kafka consumer

Question: I am trying to subscribe to a Kafka topic through pyspark with the following code:
spark = SparkSession.builder.appName("Spark Structured Streaming from Kafka").getOrCreate()

lines = spark.readStream.format("kafka").option("kafka.bootstrap.servers", "localhost:9092").option("kafka.partition.assignment.strategy","range").option("subscribe", "test-events").load()

words = lines.select(explode(split(lines.value, " ")).alias("word"))

wordCounts = words.groupBy("word").count()

query = wordCounts.writeStream.outputMode("complete").format("console").start()

query.awaitTermination()

and using the following command:
spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.0 test_events.py

and versions for spark, kafka, java and scala:
spark=2.4.0
kafka=2.12-2.3.0
scala=2.11.12
openJDK=1.8.0_221

I keep getting the following errors:
Current State: ACTIVE
Thread State: RUNNABLE

Logical Plan:
Aggregate [word#26], [word#26, count(1) AS count#30L]
+- Project [word#26]
   +- Generate explode(split(cast(value#8 as string),  )), false, [word#26]
      +- StreamingExecutionRelation KafkaV2[Subscribe[test-events]], [key#7, value#8, topic#9, partition#10, offset#11L, timestamp#12, timestampType#13]

    at org.apache.spark.sql.execution.streaming.StreamExecution.org$apache$spark$sql$execution$streaming$StreamExecution$$runStream(StreamExecution.scala:295)
    at org.apache.spark.sql.execution.streaming.StreamExecution$$anon$1.run(StreamExecution.scala:189)
Caused by: org.apache.kafka.common.KafkaException: Failed to construct kafka consumer
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:827)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:629)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:610)
    at org.apache.spark.sql.kafka010.SubscribeStrategy.createConsumer(ConsumerStrategy.scala:62)
    at org.apache.spark.sql.kafka010.KafkaOffsetReader.consumer(KafkaOffsetReader.scala:85)
    at org.apache.spark.sql.kafka010.KafkaOffsetReader$$anonfun$fetchLatestOffsets$1$$anonfun$apply$9.apply(KafkaOffsetReader.scala:199)
    at org.apache.spark.sql.kafka010.KafkaOffsetReader$$anonfun$fetchLatestOffsets$1$$anonfun$apply$9.apply(KafkaOffsetReader.scala:197)
    at org.apache.spark.sql.kafka010.KafkaOffsetReader$$anonfun$org$apache$spark$sql$kafka010$KafkaOffsetReader$$withRetriesWithoutInterrupt$1.apply$mcV$sp(KafkaOffsetReader.scala:288)
    at org.apache.spark.sql.kafka010.KafkaOffsetReader$$anonfun$org$apache$spark$sql$kafka010$KafkaOffsetReader$$withRetriesWithoutInterrupt$1.apply(KafkaOffsetReader.scala:287)
    at org.apache.spark.sql.kafka010.KafkaOffsetReader$$anonfun$org$apache$spark$sql$kafka010$KafkaOffsetReader$$withRetriesWithoutInterrupt$1.apply(KafkaOffsetReader.scala:287)
    at org.apache.spark.util.UninterruptibleThread.runUninterruptibly(UninterruptibleThread.scala:77)
    at org.apache.spark.sql.kafka010.KafkaOffsetReader.org$apache$spark$sql$kafka010$KafkaOffsetReader$$withRetriesWithoutInterrupt(KafkaOffsetReader.scala:286)
    at org.apache.spark.sql.kafka010.KafkaOffsetReader$$anonfun$fetchLatestOffsets$1.apply(KafkaOffsetReader.scala:197)
    at org.apache.spark.sql.kafka010.KafkaOffsetReader$$anonfun$fetchLatestOffsets$1.apply(KafkaOffsetReader.scala:197)
    at org.apache.spark.sql.kafka010.KafkaOffsetReader.runUninterruptibly(KafkaOffsetReader.scala:255)
    at org.apache.spark.sql.kafka010.KafkaOffsetReader.fetchLatestOffsets(KafkaOffsetReader.scala:196)
    at org.apache.spark.sql.kafka010.KafkaMicroBatchReader$$anonfun$getOrCreateInitialPartitionOffsets$1.apply(KafkaMicroBatchReader.scala:195)
    at org.apache.spark.sql.kafka010.KafkaMicroBatchReader$$anonfun$getOrCreateInitialPartitionOffsets$1.apply(KafkaMicroBatchReader.scala:190)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.sql.kafka010.KafkaMicroBatchReader.getOrCreateInitialPartitionOffsets(KafkaMicroBatchReader.scala:190)
    at org.apache.spark.sql.kafka010.KafkaMicroBatchReader.org$apache$spark$sql$kafka010$KafkaMicroBatchReader$$initialPartitionOffsets$lzycompute(KafkaMicroBatchReader.scala:83)
    at org.apache.spark.sql.kafka010.KafkaMicroBatchReader.org$apache$spark$sql$kafka010$KafkaMicroBatchReader$$initialPartitionOffsets(KafkaMicroBatchReader.scala:83)
    at org.apache.spark.sql.kafka010.KafkaMicroBatchReader.setOffsetRange(KafkaMicroBatchReader.scala:87)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$org$apache$spark$sql$execution$streaming$MicroBatchExecution$$constructNextBatch$1$$anonfun$5$$anonfun$apply$2.apply$mcV$sp(MicroBatchExecution.scala:353)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$org$apache$spark$sql$execution$streaming$MicroBatchExecution$$constructNextBatch$1$$anonfun$5$$anonfun$apply$2.apply(MicroBatchExecution.scala:353)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$org$apache$spark$sql$execution$streaming$MicroBatchExecution$$constructNextBatch$1$$anonfun$5$$anonfun$apply$2.apply(MicroBatchExecution.scala:353)
    at org.apache.spark.sql.execution.streaming.ProgressReporter$class.reportTimeTaken(ProgressReporter.scala:351)
    at org.apache.spark.sql.execution.streaming.StreamExecution.reportTimeTaken(StreamExecution.scala:58)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$org$apache$spark$sql$execution$streaming$MicroBatchExecution$$constructNextBatch$1$$anonfun$5.apply(MicroBatchExecution.scala:349)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$org$apache$spark$sql$execution$streaming$MicroBatchExecution$$constructNextBatch$1$$anonfun$5.apply(MicroBatchExecution.scala:341)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
    at scala.collection.AbstractTraversable.map(Traversable.scala:104)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$org$apache$spark$sql$execution$streaming$MicroBatchExecution$$constructNextBatch$1.apply$mcZ$sp(MicroBatchExecution.scala:341)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$org$apache$spark$sql$execution$streaming$MicroBatchExecution$$constructNextBatch$1.apply(MicroBatchExecution.scala:337)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$org$apache$spark$sql$execution$streaming$MicroBatchExecution$$constructNextBatch$1.apply(MicroBatchExecution.scala:337)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution.withProgressLocked(MicroBatchExecution.scala:554)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution.org$apache$spark$sql$execution$streaming$MicroBatchExecution$$constructNextBatch(MicroBatchExecution.scala:337)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$runActivatedStream$1$$anonfun$apply$mcZ$sp$1.apply$mcV$sp(MicroBatchExecution.scala:183)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$runActivatedStream$1$$anonfun$apply$mcZ$sp$1.apply(MicroBatchExecution.scala:166)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$runActivatedStream$1$$anonfun$apply$mcZ$sp$1.apply(MicroBatchExecution.scala:166)
    at org.apache.spark.sql.execution.streaming.ProgressReporter$class.reportTimeTaken(ProgressReporter.scala:351)
    at org.apache.spark.sql.execution.streaming.StreamExecution.reportTimeTaken(StreamExecution.scala:58)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution$$anonfun$runActivatedStream$1.apply$mcZ$sp(MicroBatchExecution.scala:166)
    at org.apache.spark.sql.execution.streaming.ProcessingTimeExecutor.execute(TriggerExecutor.scala:56)
    at org.apache.spark.sql.execution.streaming.MicroBatchExecution.runActivatedStream(MicroBatchExecution.scala:160)
    at org.apache.spark.sql.execution.streaming.StreamExecution.org$apache$spark$sql$execution$streaming$StreamExecution$$runStream(StreamExecution.scala:279)
    ... 1 more
Caused by: org.apache.kafka.common.KafkaException: range ClassNotFoundException exception occurred
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstances(AbstractConfig.java:425)
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstances(AbstractConfig.java:400)
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstances(AbstractConfig.java:387)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:772)
    ... 50 more
Caused by: java.lang.ClassNotFoundException: range
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.kafka.common.utils.Utils.loadClass(Utils.java:348)
    at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:337)
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstances(AbstractConfig.java:423)
    ... 53 more

During handling of the above exception, another exception occurred:
pyspark.sql.utils.StreamingQueryException: 'Failed to construct kafka consumer\n=== Streaming Query ===\nIdentifier: [id = 671c0c25-2f29-49f9-8698-c59a89626da7, runId = 37b4d397-4338-4416-a521-384c8853e99b]\nCurrent Committed Offsets: {}\nCurrent Available Offsets: {}\n\nCurrent State: ACTIVE\nThread State: RUNNABLE\n\nLogical Plan:\nAggregate [word#26], [word#26, count(1) AS count#30L]\n+- Project [word#26]\n   +- Generate explode(split(cast(value#8 as string),  )), false, [word#26]\n      +- StreamingExecutionRelation KafkaV2[Subscribe[test-events]], [key#7, value#8, topic#9, partition#10, offset#11L, timestamp#12, timestampType#13]\n'
2020-02-07 10:03:38 INFO  SparkContext:54 - Invoking stop() from shutdown hoo

There are multiple similar questions online but no answer has worked for me so far.
I have also tried the above with spark 2.4.4 with the following:
spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.4 test_events.py
but I keep getting the same errors.
Answer: This error can also be drawn when you provide a faulty value for kafka.bootstrap.servers.   This could be a non-existent broker/port, or even a broker list in list form, as opposed to string form.   Meaning, ["broker1:9092", "broker2:9092"] instead of "broker1:9092,broker2:9092".
Depending on where you are running the code, the true cause of the error can be hidden, as well.
Here's the error in Jupyter
StreamingQueryException: Failed to construct kafka consumer
=== Streaming Query ===
Identifier: [id = 39eb0e9d-9487-4838-9d15-241645a04cb6, runId = 763acdcb-bc05-4428-87e1-7b56ae736423]
Current Committed Offsets: {KafkaV2[Subscribe[fd]]: {"fd":{"2":4088,"1":4219,"0":4225}}}
Current Available Offsets: {KafkaV2[Subscribe[fd]]: {"fd":{"2":4088,"1":4219,"0":4225}}}

Current State: ACTIVE
Thread State: RUNNABLE

Logical Plan:
WriteToMicroBatchDataSource     org.apache.spark.sql.kafka010.KafkaStreamingWrite@457e8cfa
+- StreamingDataSourceV2Relation [key#7, value#8, topic#9, partition#10, offset#11L, timestamp#12, timestampType#13],     org.apache.spark.sql.kafka010.KafkaSourceProvider$KafkaScan@2b34a4    79, KafkaV2[Subscribe[fd]]

No mention of any problems with the broker list... Now here's the same error via spark-submit:
2021-08-13 20:30:44,377 WARN kafka010.KafkaOffsetReaderConsumer: Error in attempt 3 getting Kafka offsets:
org.apache.kafka.common.KafkaException: Failed to construct kafka consumer
at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:823)
at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:632)
at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:613)
at org.apache.spark.sql.kafka010.SubscribeStrategy.createConsumer(ConsumerStrategy.scala:107)
at org.apache.spark.sql.kafka010.KafkaOffsetReaderConsumer.consumer(KafkaOffsetReaderConsumer.scala:82)
at org.apache.spark.sql.kafka010.KafkaOffsetReaderConsumer.$anonfun$partitionsAssignedToConsumer$2(KafkaOffsetReaderConsumer.scala:533)
at org.apache.spark.sql.kafka010.KafkaOffsetReaderConsumer.$anonfun$withRetriesWithoutInterrupt$1(KafkaOffsetReaderConsumer.scala:578)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
at org.apache.spark.util.UninterruptibleThread.runUninterruptibly(UninterruptibleThread.scala:77)
at org.apache.spark.sql.kafka010.KafkaOffsetReaderConsumer.withRetriesWithoutInterrupt(KafkaOffsetReaderConsumer.scala:577)
at org.apache.spark.sql.kafka010.KafkaOffsetReaderConsumer.$anonfun$partitionsAssignedToConsumer$1(KafkaOffsetReaderConsumer.scala:531)
at org.apache.spark.util.UninterruptibleThreadRunner.runUninterruptibly(UninterruptibleThreadRunner.scala:48)
at org.apache.spark.sql.kafka010.KafkaOffsetReaderConsumer.partitionsAssignedToConsumer(KafkaOffsetReaderConsumer.scala:531)
at org.apache.spark.sql.kafka010.KafkaOffsetReaderConsumer.fetchLatestOffsets(KafkaOffsetReaderConsumer.scala:311)
at org.apache.spark.sql.kafka010.KafkaMicroBatchStream.latestOffset(KafkaMicroBatchStream.scala:87)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution.$anonfun$constructNextBatch$3(MicroBatchExecution.scala:394)
at org.apache.spark.sql.execution.streaming.ProgressReporter.reportTimeTaken(ProgressReporter.scala:357)
at org.apache.spark.sql.execution.streaming.ProgressReporter.reportTimeTaken$(ProgressReporter.scala:355)
at org.apache.spark.sql.execution.streaming.StreamExecution.reportTimeTaken(StreamExecution.scala:68)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution.$anonfun$constructNextBatch$2(MicroBatchExecution.scala:385)
at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:238)
at scala.collection.immutable.Map$Map1.foreach(Map.scala:128)
at scala.collection.TraversableLike.map(TraversableLike.scala:238)
at scala.collection.TraversableLike.map$(TraversableLike.scala:231)
at scala.collection.AbstractTraversable.map(Traversable.scala:108)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution.$anonfun$constructNextBatch$1(MicroBatchExecution.scala:382)
at scala.runtime.java8.JFunction0$mcZ$sp.apply(JFunction0$mcZ$sp.java:23)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution.withProgressLocked(MicroBatchExecution.scala:613)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution.constructNextBatch(MicroBatchExecution.scala:378)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution.$anonfun$runActivatedStream$2(MicroBatchExecution.scala:211)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
at org.apache.spark.sql.execution.streaming.ProgressReporter.reportTimeTaken(ProgressReporter.scala:357)
at org.apache.spark.sql.execution.streaming.ProgressReporter.reportTimeTaken$(ProgressReporter.scala:355)
at org.apache.spark.sql.execution.streaming.StreamExecution.reportTimeTaken(StreamExecution.scala:68)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution.$anonfun$runActivatedStream$1(MicroBatchExecution.scala:194)
at org.apache.spark.sql.execution.streaming.ProcessingTimeExecutor.execute(TriggerExecutor.scala:57)
at org.apache.spark.sql.execution.streaming.MicroBatchExecution.runActivatedStream(MicroBatchExecution.scala:188)
at org.apache.spark.sql.execution.streaming.StreamExecution.$anonfun$runStream$1(StreamExecution.scala:334)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:775)
at org.apache.spark.sql.execution.streaming.StreamExecution.org$apache$spark$sql$execution$streaming$StreamExecution$$runStream(StreamExecution.scala:317)
at org.apache.spark.sql.execution.streaming.StreamExecution$$anon$1.run(StreamExecution.scala:244)

Important part!
Caused by: org.apache.kafka.common.config.ConfigException: Invalid url in bootstrap.servers: ['192.168.1.162:9092'
at         org.apache.kafka.clients.ClientUtils.parseAndValidateAddresses(ClientUtils.java:59)
at     org.apache.kafka.clients.ClientUtils.parseAndValidateAddresses(ClientUtils.java:48)
at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:734)
... 41 more

Change kafka.bootstrap.servers from ["192.168.1.162:9092","192.168.1.161:9092","192.168.1.160:9092"] to "192.168.1.162:9092,192.168.1.161:9092,192.168.1.160:9092" and all is well.
Confirm by using kafkacat to ensure that your broker is where you are saying it is.
e.g. kafkacat -C -b 192.168.1.162:9092,192.168.1.161:9092 -t fd
Version Info:

Spark 3.1.2

PySpark 3.1.1

Key .jars:
sparkSesh = SparkSession.builder.config("spark.driver.extraClassPath", "/home/username/jars/spark-sql-kafka-0-10_2.12-3.1.2.jar,/home/username/jars/commons-pool2-2.11.0.jar")\ .appName("Kafka to Stream") \ .master("local[*]").getOrCreate()
Answer: Solved with the following:
kafka version 2.12-2.2.0
spark 2.4.0-bin-hadoop2.7
scala 2.11.12
Comment: You need to use Scala 2.12 with those
Answer:
java.lang.ClassNotFoundException: range

Unless you explicitly need the assignment strategy, then remove the option.
Otherwise, it must be the fully qualified Java class name
Answer: Try changing the kafka.partition.assignment.strategy to roundrobin from range and see if it works.
lines = spark.readStream.format("kafka").option("kafka.bootstrap.servers", "localhost:9092").option("kafka.partition.assignment.strategy","roundrobin").option("subscribe", "test-events").load()

If it doesnt works even after that then try adding kafka-clients-0.10.0.1.jar while submitting the spark job.
spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.0 --jars local:///root/sources/jars/kafka-clients-0.10.0.1.jar --driver-class-path local:///root/sources/jars/kafka-clients-0.10.0.1.jar test_events.py

Comment: I would suggest using a newer kafka clients of 0.10.2 or higher
Comment: Hello, thanks for the answer. Tried both and still getting the saem error.


Why is Pandas Dataframe so slow when multiplying by a scalar?

Question: I've noticed that when you multiply a dataframe by a scalar, it's an order of magnitude slower than multiplying the numpy array instead.  The slowness increases more than linearly with dataframe size.  Python 3.6, Pandas 0.24.0.
Is there a better workaround?
Why is multiplying by a scalar so slow in Pandas?  It seems like a performance bug to me.
df0 = pd.DataFrame(np.random.randn(1000, 400))

# Time to make a copy
%timeit df = df0.copy();
1.25 ms ± 5.64 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# Multiplying by a scalar is absurdly slow
%timeit df = df0.copy(); df = df * 1
64.7 ms ± 265 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# Using numpy is much faster
%timeit df = df0.copy(); df[:] = df.values * 1
3.54 ms ± 251 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# Multiplying by another dataframe with the same indexes is much faster
%timeit df = df0.copy(); df = df * df0
1.68 ms ± 5.31 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Comment: Working with the underlying numpy arrays will always benefit performance. Note that you're also modifying in-place in the second case, which also contributes to efficiency
Answer:
Is there a better workaround?

You can working with numpy array and DataFrame constructor, if performance is important:
In [219]: %timeit df = df0.copy()
2.78 ms ± 37 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [220]: %timeit df = df0.copy(); df = df * 1
129 ms ± 3.74 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [221]: %timeit df = df0.copy(); df[:] = df.values * 1
9.35 ms ± 118 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [222]: %timeit df = df0.copy(); df = pd.DataFrame(df.values * 1,
                                                     index=df.index,
                                                     columns=df.columns)

4.88 ms ± 40.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Answer: Is it really that bad?
In the following I wanted to show you how you can make your code faster. But then I realized, that it depends also on the size of the dataset in use. Nonetheless, let us first have a look at your problem. I will run the same code on my machine in order to gauge the comparison. I will do everything for a big dataset (100 times yours) and a small one (your dataset).
Pandas is slow on some numerical computations. Let's see how slow compared to equivalent numpy operations.
Using pandas 0.23.4 on Linux 32 Cores, within a jupyter notebook
(Using pandas 1.0.4 on Windows 2 Cores for the results at the end, within a jupyter notebook)
Note, that all results have been found within a jupyter notebook. I did not change any settings. It might be, that under real world conditions, the results would differ.
Measurements
In the following my measurements.
Big DataSet
import pandas as pd
import numpy as np

a = np.random.randn(10000, 4000)
df0 = pd.DataFrame(a.copy())
df = df0.copy()

Note, that I use a bit more data, 100 times more. Additionally, I use the magic %%time command for measurement instead of the %%timeit.
df.shape

(10000, 4000)

I run the following cell twice. The first time you run it, the kernel might still load libraries or compile something. It will show different results. But you can assume, that there is no internal state changed or results cached on the DataFrame when performing a simple multiplication (as it does when you perform a groupby and aggregation).
Furthermore, I do not create a copy in each cell as you did. Nonetheless, the following creates a new DataFrame and keeps the old one. It is not only a view on the left hand sides' dataframe.
%%time
_ = df * 1

CPU times: user 78 ms, sys: 90.6 ms, total: 169 ms
Wall time: 24.3 ms

If we assign the resulting DataFrame instance to the df pointer, the execution of the cell takes longer. Maybe, because the garbage collector frees the DataFrame from the left hand side: There is no reference left in the notebook to this one anymore. So be careful in your performance tests, what you are measuring!
%%time
df = df * 1

CPU times: user 84.4 ms, sys: 94.7 ms, total: 179 ms
Wall time: 31.7 ms

Or with inplace multiplication
%%time
df *= 1

CPU times: user 77.1 ms, sys: 97 ms, total: 174 ms
Wall time: 31 ms

Observations to the above: Note, that total time is higher than wall time (your wall clock or smartphone clock, nowadays). This tells us, that some multiprocessing or concurrent multithreading works in the background.

Let's continue now in how to make things faster. You tried the following, basically:
%%time
df[:] = df.values * 1.

CPU times: user 258 ms, sys: 234 ms, total: 492 ms
Wall time: 491 ms

This is not faster, because the __setitem__, which is quite sophisticated on pandas.Dataframes, is slow. The same you get for the loc.
%%time
df.loc[:] = df.values * 1.

CPU times: user 260 ms, sys: 224 ms, total: 485 ms
Wall time: 483 ms

Accessing the data directly

You can access the data directly, and set the values. This seems to be faster. (But you might have problems, if you have mixed datatypes in the DataFrame.)
%%time
df.values[...] = df.values * 1.

CPU times: user 95.7 ms, sys: 78.5 ms, total: 174 ms
Wall time: 173 ms

Or even faster, do everything inplace. (As long as df.values[...] returns a reference to the data store.)
%%time
df.values[...] *= 1

CPU times: user 43.4 ms, sys: 0 ns, total: 43.4 ms
Wall time: 42.6 ms

Can it be faster than that? Let's compare this with the following multiplications. First by multiplying the initial dataset, the numpyarray a ...
%%time
_ = a * 1

CPU times: user 45.9 ms, sys: 82.7 ms, total: 129 ms
Wall time: 128 ms

... and by performing the corresponding inplace multiplication.
%%time
a *= 1

CPU times: user 43.5 ms, sys: 0 ns, total: 43.5 ms
Wall time: 42.9 ms

It shows, that less then about 43 milliseconds cannot be expected. Therefore, accessing the data directly and operating on it is as fast as operating on numpy arrays directly.
But note, in my example, even the initial quess is faster than that. Showing, that there is some optimization taking place with pandas, which does not with numpy. Strange!
Small Dataset
Here I make the same observations as you did. The trick with accessing the data directly, works out best again (df.values[...] *= 1).
import numpy as np
import pandas as pd

a = np.random.randn(1000, 400)
df0 = pd.DataFrame(a.copy())
df = df0.copy()

df.shape
(1000, 400)

%%time
_ = df * 1
CPU times: user 4.23 ms, sys: 1.28 ms, total: 5.51 ms
Wall time: 2.83 ms

%%time
df = df * 1
CPU times: user 4.68 ms, sys: 188 µs, total: 4.87 ms
Wall time: 2.22 ms

%%time
df *= 1
CPU times: user 2.66 ms, sys: 1.76 ms, total: 4.42 ms
Wall time: 1.71 ms

%%time
df[:] = df.values * 1.
CPU times: user 4.28 ms, sys: 21 µs, total: 4.3 ms
Wall time: 3.51 ms

%%time
df.loc[:] = df.values * 1.
CPU times: user 3.77 ms, sys: 0 ns, total: 3.77 ms
Wall time: 3.13 ms

%%time
df.values[...] = df.values * 1.
CPU times: user 2.19 ms, sys: 0 ns, total: 2.19 ms
Wall time: 1.38 ms

%%time
df.values[...] *= 1
CPU times: user 211 µs, sys: 1.05 ms, total: 1.26 ms
Wall time: 681 µs

%%time
_ = a * 1
CPU times: user 1.61 ms, sys: 0 ns, total: 1.61 ms
Wall time: 818 µs

%%time
a *= 1
CPU times: user 379 µs, sys: 950 µs, total: 1.33 ms
Wall time: 671 µs

Open Questions
It looks that simple multiplications are sometimes faster with pandas as with numpy. Here for the big dataset from above.
%%timeit
_ = df * df
22.8 ms ± 590 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
_ = a * a
133 ms ± 4.85 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

It does not matter whether I call timeit or time. The results are the same.
%%time
_ = df * df
CPU times: user 62.3 ms, sys: 99.2 ms, total: 162 ms
Wall time: 23.8 ms

%%time
_ = a * a
CPU times: user 57.6 ms, sys: 82.3 ms, total: 140 ms
Wall time: 139 ms

I did not expect this. And you?
I cross-checked this on Windows 10, 2 Cores with pandas 1.0.4. The results look basically the same. Althought the relative differences are not that big anymore.
%%timeit
df * df
165 ms ± 5.96 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
a * a
251 ms ± 9.71 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Comment: Meanwhile I found the reason, why pandas is faster then numpy in my case compared to your case: pandas uses numexpr in the background, if and only if it is installed.
Answer: Make pandas faster then numpy on simple mathematical operations
You can make pandas perform better then numpy (alone) if you install the module numexpr (and don't switch off it's usage. It is switched on by default).
Look at this for more explanations:
Why is pandas faster then numpy on simple mathematical operations?
By doing so, your example above will for sure perform better. I tested pandas'  behaviour for multiplications and other operators: left and right hand side  multiplication with scalars, row vectors, column vectors and matrices.


Commutativity among the elements in the quotient group $G$ and the ful group $H$ under homomorphism $H \overset{r}{\to} G$

Question: Say the full group is $H$, and we pick up a normal subgroup $N$, and we define the quotient group $$G=H/N.$$
There is a group homomorphism $r$ from $H$ to $G$
$$
H \overset{r}{\to} G.
$$
My question concerns the following relations are true in general or whether there are counter examples?

$ g \cdot r(h) \cdot g^{-1}=r(h)$,  for $\forall h \in H$, $\forall g \in G$.
$ r(h) \cdot g \cdot r(h)^{-1}=g$, for $\forall h \in H$, $\forall g \in G$.

If some of them is not true, please give the simplest (counter) example (especially the finite group).
Comment: FOr an even simpler counterexample, pick any non-ablelian group $H$ and let $N = \{e\}$.
Answer: Since $r$ is a group homomorphism, your relations are in general not true: Try a pair $(h_1,h_2)$ of (non-commuting elements), of a non-abelian group $H$, such that: $h_1h_2h_1^{-1}h_2^{-1}\notin N$,  for providing counterexamples:
$$
r(h_1h_2)=r(h_1)r(h_2)=r(h_2)r(h_1)=r(h_2h_1)\Leftrightarrow \\r(h_1)r(h_2)r(h_1)^{-1}r(h_2)^{-1}=1_N
\Leftrightarrow \\
r(h_1h_2h_1^{-1}h_2^{-1})=1_N=r(N)
\Leftrightarrow \\
h_1h_2h_1^{-1}h_2^{-1}\in N
$$
thus, (taking the contrapositive of the above) we get:
$$
h_1h_2h_1^{-1}h_2^{-1}\notin N \Leftrightarrow r(h_1)r(h_2)=r(h_1h_2)\neq r(h_2h_1)=r(h_2)r(h_1)
$$
Maybe the simplest counterexample (reflecting the above argument in its most simplistic  form) is one already mentioned by user  Jason DeVito in his comment above: Pick any non-abelian group $H$ and let $N=\{e\}$. It is easy to see that, in that case: $$H= H/N= H/\{e\}$$
Thus, any pair of non-commuting elements of $H$ would do.
Comment: The example I have in mind is that $G$ is nonAbelian, how about yours? It seems not to be clear enough, your answer.
Comment: yes of course I am speaking about a non-abelian group. I mention that explicitly in the post.
Answer: They do not hold in general.
Consider $H= D_8 = <\sigma, \tau | \sigma^8 = 1, \tau^2 = 1, \tau \sigma^i \tau = \sigma^{8-i}>$ and consider its normal subgroup $N=<1, \sigma^4>$.
Now $G=H/N$ has order $8$ and has elements $1, \tau, \sigma, \sigma^2, \sigma^3, \sigma\tau, \sigma^2 \tau,\sigma^3 \tau$.
Consider $r:H \to G$ the usual projection. Now $g=\tau, h=\sigma^5\tau$ gives you
$$\tau r(\sigma^5\tau) \tau = r(\tau\sigma^5) = \tau\sigma$$
while $r(\sigma^5 \tau) = \sigma\tau$. You can do the same for the other relation.


Does anyone know why making 1000s of small Labels takes so long? Python, Tkinter

Question: Does anyone know why printing the contents of a 100x100 matrix using Labels takes so long? Below is an example. I am also open to any alternative ideas.
try:
    from Tkinter import *
except:
    from tkinter import *
import numpy as np

dbnm = Tk()
a = np.zeros([100,100])
for i, ii in enumerate(a):
    for j, k in enumerate(ii):
        Label(dbnm, text = '  ', k, '  ').grid(row=i,column=j)

dbnm.mainloop()

Thanks for your time
Comment: You are creating 100x100 (i.e 10000) labels, not 1000.  And `tkinter` is not a high performance library.
Comment: `import *` is generally bad practice, and so are bare `except` statements, be careful!
Comment: There is a 's' on that 1000 in the title.... Either way, does "not a high-performance library" mean that there is no way to print large grids you can scroll around in with Tkinter?
Comment: Instead of creating 10000 separate widgets, it would be nice to have one scrollable table widget. I'm not sure how to accomplish this in Tkinter, but In PyQt you could do this easily with QTableWidget. I recommend learning PyQt anyway, it's much better than Tkinter.
Answer: It is simply because tkinter isn't designed to make 10,000 widgets. grid has to do a fair number calculations for every cell. Doing those calculations 10,000 times adds up. Even switching to place where you explicitly put each cell at a specific location is going to be very slow.
If you draw text on a canvas rather than using labels and grid it will perform orders of magnitude faster, but at 10,000 text items even the canvas will start to bog down.


How to find a pair of integers closest to perfect square of a number?

Question: I need to make graphs in a software that are grouped in subplots. For this, I need to specify how many rows and how many columns of plots there will be. However, I do not know the total number of plots there will be.
I am therefore looking for a pseudo-code (or small algorithm) that would allow me to automatically define the number of rows and columns for those subplots.
Here is the objective of the problem:

The number of rows and columns should be as close as possible from a perfect square.

Here are the constraints of the objective:

The two numbers should be integers
The number of rows should be larger than or equal to the number of columns
The product of the two numbers should be larger than or equal to the number of subplots

I realize now that the problem resembles the maximization of the area of a four-sided figure with four right angles given its perimeter, with the perimeter being the number of subplots and the rows and columns being the length and width.
I am using Matlab, how would the code look like?
Here is what I have so far, but trying with in=7 and in=10 shows it is not correct:
function [rr,cc]=number_subplots(in)

sqrt_in=sqrt(in);
floor_in=floor(sqrt_in);
ceiling_in=ceil(sqrt_in);

[out]=sort([floor_in ceiling_in],'descend')

rr=out(1);
cc=out(2);

Answer: I figured it out:
function [rr,cc]=number_subplots(in)

sqrt_in=sqrt(in);
floor_in=floor(sqrt_in); % round down to nearest integer
ceiling_in=ceil(sqrt_in); % round up to nearest integer

round_in=round(sqrt_in); % round to nearest integer

if round_in>floor_in % case where sqrt_in is above .5 mark
[out]=sort([round_in round_in],'descend'); % square of ceiling is enough
else
  [out]=sort([round_in round_in+1],'descend'); % floor*ceiling is enough
end

rr=out(1);
cc=out(2);


$|\frac{\sin(nx)}{n\sin(x)}|\le1\forall x\in\mathbb{R}-\{\pi k: k\in\mathbb{Z}\}$

Question: Find all real number $n$ such that  $|\frac{\sin(nx)}{n\sin(x)}|\le1\forall x\in\mathbb{R}-\{\pi k: k\in\mathbb{Z}\}$.
Answer: The inequality is true for all $n \in \mathbb{Z}^+$, which also implies immediately that it is true for $n \in \mathbb{Z}^-$. The proof follows immediately from induction.
For $n = 1$, it is true.
Assume it is true for $n=k$ i.e. we have $$\left\lvert \dfrac{\sin(kx)}{k \sin(x)} \right\rvert \leq 1$$
Then $$\sin((k+1)x) = \sin(kx) \cos(x) + \cos(kx) \sin(x)$$
$$\left \vert \sin((k+1)x) \right \vert = \left \vert \sin(kx) \cos(x) + \cos(kx) \sin(x) \right \vert \leq \left \vert \sin(kx) \cos(x) \right \vert + \left \vert \cos(kx) \sin(x) \right \vert\\ \leq k \left \vert \sin(x) \right \rvert + \left \vert \sin(x) \right \rvert$$
If $n \notin \mathbb{Z}^+$, then $\left\lvert \dfrac{\sin(kx)}{k \sin(x)} \right\rvert $ can be made arbitrarily large by choosing $x$ close to say $\pi$.
Answer: Let $\phi_n(x) = |\frac{\sin(nx)}{n\sin(x)}|$. $\phi_0$ is undefined, so $n \neq 0$. Since $\phi_n = \phi_{-n}$, we can assume $n>0$.
Suppose $n>0$ is not an integer, and consider the sequence $x_k = \pi-\frac{1}{k}$. Then $x_k \to \pi$, but $n x_k \to n \pi \notin \pi \mathbb{Z}$. Consequently, $\lim_k \phi_n(x_k) = \infty$.
Now suppose $n>0$ is an integer, and
let $z = e^{ix}$. Then $\phi_n(x) = |\frac{z^{n}-z^{-n}}{n(z-z^{-1})}| = |\frac{z^n}{k z}\frac{1-z^{-2n}}{1-z^{-2}}| = |\frac{z^n}{k z} \sum_{k=0}^{n-1} (z^2)^k| $. Since $|z| = 1$, we have
$$\phi_n(x) \leq \frac{1}{k} \sum_{k=0}^{n-1} (1) = 1.$$
It follows that $\phi_n(x) \leq 1 $ for all appropriate $x$ iff $n$ is a non-zero integer.
Answer: Notice that, for $n=2^m \,,\,\, m = 0,1,2\dots\,,$ and using the identity $\sin(2x)=2\sin(x)\cos(x)\,,$ we have
$$ \sin( 2^m x ) = 2^m \sin(x) \cos(2x)\cos(4x)\dots\cos(2^{m-1}x) $$
$$ \implies \left|\frac{\sin{2^mx}}{2^m\sin(x)}\right|= |\cos(2x)\cos(4x)\dots\cos(2^{m-1}x)|\leq 1 \,. $$
Comment: This does not seem to answer the question.


How do I make a kill counter in MCBE without using XP?

Question: How do I make a kill counter in mcpe without using XP?
The problem is, if there are 2 or more players on my server, if I snipe a player across the map, the nearest player from the player I sniped gets the kill instead of me. What commands can I use?
Comment: Please see [What to do before asking a minecraft-commands question?](https://gaming.meta.stackexchange.com/q/13507/4797)
Comment: Have you tried using a scoreboard?
Comment: @FTL'saccountwillbedeleted I dont think mcbe scoreboard can do that, only java
Answer: This is not possible in the Bedrock version of the game, as the closest you can get is what you seemed like you used, an @p. You could do something where you tag whoever is in a block radius of the arrow and then figure out who died and who is still alive but it would be buggy and more trouble than its worth.


Golang nested structs unmarshaling with underscores

Question: I am writing an app using the Instagram API.
I am receiving a JSON request and that gets Unmarshal'ed into nested structs.
// the nested structs
type ResponseData struct {
    ID   string `json:"id"`
    Link string `json:"link"`
    Type string `json:"type"`
    User struct {
        FullName       string `json:"full_name"`
        ID             int    `json:"id"`
        ProfilePicture string `json:"profile_picture"`
        Username       string `json:"username"`
    }
    Images struct {
        Standard_Resolution struct {
            URL string `json:"url"`
        }
    }
}

For the Image url to be added it needs to have the underscore in Standard_Resolution , I am using Go Plus Package for Atom and I get the lint warning:

don't use underscores in Go names; struct field Standard_Resolution
  should be StandardResolution

Is there another way for me fix the error and still have the value in my struct.
Update:
I can add an identifier after the last brace for StandardResolution.
StandardResolution struct {
    URL string `json:"url"`
} `json:"standard_resolution"`

Comment: I think you can use tags on struct types too. Just "rename" your StandardResolution struct via `json: "Standard_Resolution"`. Go is really dead regular. I didn't try it .
Comment: @ikrabbe The "no underscores" issue is a *style* recommendation from `go vet` (which Go Plus would run) rather than a "breaks the OP's program" issue.
Comment: But adding a `json:"Standard_Resolution"` should help too and should make things clearer.
Comment: A minimal working example would help on debugging with a plain go compiler. My golang.org Language Specification says http://golang.org/ref/spec#IdentifierList that underscore is a valid part of an identifier
Comment: I didnt realize that I could rename my struct by adding ``json:"standard_resolution"`` after the brace, I was adding it after the word `struct`, hence i was getting an error. thanks @volker @ikrabbe
Comment: You realize that if you translate into non-nested structure definitions, as in my attempt to answer, below.
Answer: Anyway it is easier to read if you don't use nested structs.
type RDUser struct { ... }
type RDStandardResolution struct { ... }
type RDImages struct {
    StandardResolition RDStandardResolution `json:"standard_resolution"`
}
type ResponseData struct {
    ...
    User RDUser `json:"user"`
    Images RDImages `json:"images"`
}


How would someone implement mathematical formulae in Java?

Question: How would someone implement mathematical formulae in Java?
What I mean, the user inputs a string with multiple variables. Like a simple quadratic formula: x^2 + 5x + 10. Or in Java: (Math.pow(x,2)) + (x * 5) + 10. The user would then enter that and then the program would solve for x. I will be using the BeanShell Interpreter class to interpret the string as an equation. But how would I solve for x?
Comment: FYI, `^` in Java is not exponentiation. See http://stackoverflow.com/questions/1991380/what-does-the-operator-do-in-java/2672217#2672217
Comment: Also, see http://en.wikipedia.org/wiki/Equation_solving
Comment: I am sorry. I dont understand this quite well. If a question can be converted to a programming language, so well the answer can be. Is it not? - for this QE - find what is a, b , c and implement the formula (-b + Math.sqrt(Math.pow(b,2) - 4*a*c))/2a and so on.
Comment: @gurupriyan.e -- it's not so simple; a quadratic equations might be easy, but the form of all possible equations is going to be a pretty large list; extending, for example, to cubic, quartic, and nth-degree polynomials is already hard enough.  You could conceivably create special cases for trigonometric functions, exponentials, variables in the denominator, etc...
It's not impossible, but just not as trivial as you imply.
Comment: If you can state what you require I'm sure I can help. But your description makes no sense. Are you trying to evaluate strings like `x^2 + 5x + 10` for some value of `x`? Or are you trying to solve an equation? If you're solving an equation, which one? You haven't given any equations. Are you trying to solve `x^2 + 5x + 10 = 0`? If so, there are some nice methods you can implement, that'll often work, that I can help with, that don't need anything like an algebra package.
Answer: This is a hard problem, unless you restrict yourself to simple equation types.
Here are some links for you to chase:

Wikipedia page on Computer Algebra Systems
Wikipedia Comparison of Computer Algebra Systems.

Trawling through the second link, I spotted 3 open-source Java systems.
Answer: As @nuriaion suggests you could use a Computer Algebra System, though I think that Mathematica or Maple or Sage or Macsyma would have been better suggestions.  There are others too.  I'm not sure that many would regard either Matlab or Octave as CAS, they are more like numerical computing environments.  Though the Matlab Symbolic Toolbox might provide enough CAS-ability for your needs.
It is relatively easy to integrate Mathematica into a Java-programmed system.  Possibly not cheap mind you.
Answer: I don't think this is a homework (way too hard!), and I don't think it's a research problem either (what's new?), so depending on the context of the problem, the easiest solution may just be to leverage Wolfram Alpha.

WolframAlpha: solve x^2 + 5x + 10
x = -1/2 i (sqrt(15)-5 i) ~~ -2.5-1.93649 i
x = 1/2 i (sqrt(15)+5 i) ~~ -2.5+1.93649 i

Links

WolframAlpha Web Service API
Answer: I'm using the Java Algebra System (JAS) library in my Symja project to solve univariate polynomials.
Example input for the symbolic mode:
Roots[x^2 + 5x + 10]

Answer: Maybe you can use a CAS like MATLAB, Octave, etc.
Octave is open Source and I believe it has a Java binding (joPas).
Edit:
MATLAB with a symbolic toolbox can solve a lot. Octave also have some symbolic toolbox, but I don't know how good it is.
I propose Octave because it is open source. Most CASes are very expensive.
Comment: But those are numerical, so how would you solve for a variable?
Answer: You can map coefficients of x to power of x's. For example;
assume you have a formula like this:
3x^2 - 5x + C = 0
But this simple approach is just for small degree equations. For example equation i gave is in degree of 2 (biggest x power); so it has 2 solution values for x, and can be computed with Vieta equations.
PS: I'm studying Math Engineering in college and i'm pretty satisfied with Gnu Octave.
http://mathworld.wolfram.com/PolynomialRoots.html
http://en.wikipedia.org/wiki/Root-finding_algorithm
Answer: One possibility is to use Maxima compiled with ABCL to solve the equations (and do any other algebra you need). ABCL is an implementation of Common Lisp in Java. Your front end program would take the input and pass it to Maxima to solve it, then display the result. Essentially you could use Maxima as a big math library.
Comment: Do you links, pics, or code snippets as examples of this?
Answer: It is better if you study the data structure algorithms for converting expressions from infix to postfix & to & fro. Then in the data structure there is an algorithm for evaluating expressions. This evaluation is done by using a stack.
You can study the data structure books. Some of the books are "Fundamentals of data structures" by Ellis Horowitz, Schaum's Outline of Data Structures with Java, etc.


How can add Tab widget to the botton in android?

Question: I am working on android, i want to add tab widget to the bottom of page. this is the code of my xml file:-

    <HorizontalScrollView android:id="@+id/ScrollView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:fillViewport="true" android:scrollbars="none">
       <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_marginLeft="0dip" android:layout_marginRight="0dip"
        android:layout_alignParentBottom="true"/>
 </HorizontalScrollView>
 <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp" />

</RelativeLayout>

by this code the tabwidget is adding to the top of the layout as shown in below picture:-

please tell what should i so to add these "Albums" tabWidget ?
Thank you in advance...
Answer: here is code for bottom tab,
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:layout_weight="1"/>

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"/>

</LinearLayout>

Comment: just paste this on your main.xml
Answer: This is the correct way to do this.

<RelativeLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp">

   <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp"
        android:layout_alignParentTop="true"
        android:layout_above="@+id/ScrollView01"/>

    <HorizontalScrollView android:id="@+id/ScrollView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:fillViewport="true" android:scrollbars="none" android:layout_alignParentBottom="true">

       <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="0dip" android:layout_marginRight="0dip"
        android:layout_alignParentBottom="true"/>
   </HorizontalScrollView>

</RelativeLayout>


sigmoid function - TypeError

Question: Apologies if I don't get this right the first time, as I am new to both this forum and Python. I am attempting to do logistic regression and would like to calculate the sigmoid function.
Code:
import numpy as np

csv_file_object = csv.reader(open('train.csv', 'rb'))
header = csv_file_object.next()

train_data=[]

for row in csv_file_object:
    train_data.append(row[1:])

train_data = np.array(train_data)

X = train_data

X = np.c_[ np.ones(N), X ]   # print type(X) gives <type 'numpy.ndarray'>

def sigmoid(z):
    s = 1.0 / (1.0 + np.exp**(-1.0 * z))
    return s

print sigmoid(X)

Error
When I run this I get the following error:
Traceback (most recent call last):
  File "C:\Users...", line 63, in
print sigmoid(X)

File "C:\Users...", line 59, in sigmoid
s = 1.0 / (1.0 + np.exp**(-1.0 * z))

TypeError: unsupported operand type(s) for *: 'float' and 'numpy.ndarray'
I have tried switching the 1.0's to 1's and then get 'int' instead of 'float' in the error and using '.astype(np.float)' and other attempts. I have looked for similar questions and have looked at the documentation but have been unable to find a solution (or understand that I was indeed reading a solution!):
http://docs.scipy.org/doc/numpy/reference/generated/numpy.exp.html
How to calculate a logistic sigmoid function in Python?
My understanding is the exponential function should perform an element-wise exponentiation for each element in the array.
What am I missing?
Comment: exp(-1.0*z) should solve your problem, (numpy.exp is the exponential function, not the euler-number)
Answer: Remove the ** and it will be fixed
np.exp has the power function inside of it that's why you get an error
Answer: numpy.exp is a function, and you are trying to apply the exponentiation operator to that function.  Python clearly has no idea what you are talking about.
You need to pick either numpy exponentiation or Python exponentiation, not both.  Look at the syntax in the documentation that you linked to.
Comment: Ah yes, I _was_ staring at the solution. Thanks.
Answer: Aside from the syntax error pointed out by @roippi, you can use the numpy I/O functions; there's no need to go via the csv module.
Another problem is that the csv module is giving you strings, and so your train_data winds up not being an ndarray with float dtype (the jargon for what kind of objects are being stored in a numpy array).
For example, something like this should work:
>>> !cat train.csv
a,b,c
1,2,3
2,3,4
4,5,6
>>> train_data = np.loadtxt("train.csv", skiprows=1, delimiter=",")
>>> train_data
array([[ 1.,  2.,  3.],
       [ 2.,  3.,  4.],
       [ 4.,  5.,  6.]])
>>> np.exp(train_data)
array([[   2.71828183,    7.3890561 ,   20.08553692],
       [   7.3890561 ,   20.08553692,   54.59815003],
       [  54.59815003,  148.4131591 ,  403.42879349]])

Alternatively, you can simply force a conversion.  Starting from what you have, which might be something like this:
>>> train_data
array([['2', '3'],
       ['3', '4'],
       ['5', '6']],
      dtype='|S1')

(Note the dtype here.)  You can specify the type:
>>> train_data.astype(float)
array([[ 2.,  3.],
       [ 3.,  4.],
       [ 5.,  6.]])
>>> np.array(train_data, dtype=float)
array([[ 2.,  3.],
       [ 3.,  4.],
       [ 5.,  6.]])

Comment: Excellent, this is simpler I/O method.  And this was also necessary to fix the problem as I had an array of strings. Thank you.

sigmoid function - TypeError


Why does useRouter() and router parameters not work in my Nuxt project

Question: I have a file in pages/products called [id].vue and my code in it is
<template>

Hello {{ id }}

</template>

So when I open localhost:3000/products/123 I should land on a page which says Hello 123 but I land on a 404 page instead.
I also doesnt get the useRoute function suggested in code as if it doesnt exist. Do I have to install/add it extra?
My normal routes work just fine.
I followed this tutorial
I followed this tutorial https://www.youtube.com/watch?v=QS8MwC8S4o8&list=PL4cUxeGkcC9haQlqdCQyYmL_27TesCGPC&index=5
My nuxt.config.js:
export default {
  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    title: 'meineSeite',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' },
      { name: 'format-detection', content: 'telephone=no' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [
  ],

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
  ],

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/typescript
    '@nuxt/typescript-build',
    // https://go.nuxtjs.dev/tailwindcss
    '@nuxtjs/tailwindcss',
  ],

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
  ],

  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
  }
}

my Projekt structure:
.nuxt
components
    Main.vue
    NuxtLogo.vue
nodemodules
pages
    products
        [id].vue
        index.vue
    index.vue
static
store
.editorconfig
.gitignore
nuxt.config.js
package-lock.json
package.json
README.md
tsconfig.json

Comment: have you try rebuild your project?
Comment: Please share your project structure and your `nuxt.config.js` file.
Comment: @Jazuly Yes I tried that but it didnt work.
Comment: @Erik your nuxt.config.js is in Nuxt 2 format. Update it in Nuxt 3 format: https://nuxt.com/docs/getting-started/configuration Other then that, the param should just work.
Comment: Yes I made the Mistake of using Nuxt 2. Thanks
Answer: This looks a bit like you are using Nuxt 2, buildModules for example is deprecated in Nuxt 3. You have to update to Nuxt 3 for useRoute and to follow this guide.


$\sum_{j=i}^n\binom nj\binom jix^{n-j}=\binom ni\left(\frac1x+1\right)^{n-i}x^{n-i}$

Question: Question :
$$\sum_{j=i}^n\binom nj\binom jix^{n-j}=\binom ni\left(\frac1x+1\right)^{n-i}x^{n-i}$$
I can't prove this identity. Any helps would be appreciated.
Comment: If it is true, it should be true for each coefficient of $x^k$
Answer: $$
\begin{aligned}
\binom{n}{i}\left(\frac{1}{x}+1\right)^{n-i} x^{n-i} &=\sum_{l=0}^{n-i}\binom{n}{i}\binom{n-i}{l}x^{n-i-l}\\
&=\sum_{j=i}^n \binom{n}{i}\binom{n-i}{j-i}x^{n-j}\\
&=\sum_{j=i}^n \frac{n!}{i! (n-j)! (j-i)!} x^{n-j}\\
&=\sum_{j=i}^n \binom{n}{j}\binom{j}{i} x^{n-j}
\end{aligned}
$$
(I leave you the task of filling in the details :))
Answer: Re-write the right hand side as
$$\binom{n}{i}\left(\frac{1}{x}+1\right)^{n-i}x^{n-i}=\binom{n}{i}\left(1+x\right)^{n-i}$$
then using the "find the coefficient of $y^i$" operator $\left[y^i\right]$ the above is clearly
$$\left[y^i\right]\left(y+(1+x)\right)^n$$
which may alternatively be written
$$\begin{align}
\left[y^i\right]\left((1+y)+x\right)^n&=\left[y^i\right]\sum_{j=0}^{n}\binom{n}{j}x^{n-j}\left(1+y\right)^j\\[1ex]
&=\left[y^i\right]\sum_{j=0}^{n}\binom{n}{j}x^{n-j}\sum_{i=0}^{j}\binom{j}{i}y^i\\[1ex]
&=\left[y^i\right]\sum_{j=0}^{n}\sum_{i=0}^{j}\binom{n}{j}\binom{j}{i}x^{n-j}y^i\\[1ex]
&=\left[y^i\right]\sum_{i=0}^{n}\sum_{j=i}^{n}\binom{n}{j}\binom{j}{i}x^{n-j}y^i\\[1ex]
&=\left[y^i\right]\sum_{i=0}^{n}y^i\left(\sum_{j=i}^{n}\binom{n}{j}\binom{j}{i}x^{n-j}\right)\\[1ex]
&=\sum_{j=i}^{n}\binom{n}{j}\binom{j}{i}x^{n-j}\qquad\qquad\qquad\qquad\qquad\qquad\blacksquare\end{align}$$
Answer: As your question currently stands, note that proving what you want is equivalent to proving $\displaystyle \sum_{j=i}^{n}\binom{n}{j}\binom{j}{i}x^{n-j}= \binom{n}{i}(1+x)^{n-i}$
Also note that both the LHS and RHS are polynomials in $x$ of degree $n-i$, so if we want to prove the above $\forall \, x \in \mathbb{R}$, it suffices to prove it $\forall \,  x \in \mathbb{N}$ since two polynomials each of degree $d$ agreeing on at least $d+1$ values, agree everywhere.
Let $x \in \mathbb{N}$ and let $[x]$ denote the set $\{1,2 \ldots, x\}.$ Here's a combinatorial proof via double-counting.
The RHS counts the number of ways of choosing a core committee of $i$ members out of $n$ people while labeling the $n-i$ non-core committee members with a label from $[x+1].$ This can be done in $\displaystyle \binom{n}{i}(x+1)^{n-i}$  ways.
Alternatively, for a fixed $j, \, i\leq j \leq n,$ from a group of $n$ people, first choose a $j$-member committee in $\displaystyle \binom{n}{j}$ ways and from this committee choose an $i$-member core committee in $\displaystyle \binom{j}{i}$ ways such that the $n-j$ non-committee members get a label from $[x]$ in $x^{n-j}$ ways and the $j-i$ committee members who are $\textbf{not}$ on the core committee get the label $(x+1).$ This can be done in $\displaystyle \binom{n}{j}\binom{j}{i}x^{n-j}$ ways.
Summing over $j = i, i +1, \ldots, n$, covers all the possible strengths of the intermediate committee from which an $i-$member core committee can be chosen and at each value of $j,$ exactly $n-j+j-i = n-i$ people have a label from $[x+1]$, like in the RHS scenario.
The desired identity follows.
Comment: I am reading your argument now.  Please specify whether $i \geq 0$ or $i \geq 1$.  (I will delete this comment.)
Comment: Why do you say that the $j - i$ committee members who are not on the core committee get the same label?
Comment: It should be $i \geq 0.$ We fix the label of the $j-i$ committee members who are not on the core committee to be $[x+1]$ for 2 reasons: so we can obtain a factor of exactly $x^{n-j}$ in the sum on the LHS and so that the situation corroborates with the one described for the RHS.
Comment: Yes, I agree that $i \geq 0$.  That should have been specified with the identity in the post.


My Reciprocating saw locked up and won't unlock what can I do

Question: How can I unlock my Reciprocating saw it was working and locked up now it won't unlock
Comment: What is the name of the manufacturer of the saw? What is the saw's model number? What was the saw doing when it "locked up?" What have you tried to get the saw to work again?
Comment: The hard way is to take it apart see what is jammed or broken and try to repair it.  You then have to put it back together right.  Unless it is/was quite expensive, the easy way is to get a new one.
Comment: Bad news, something is broken in the gear box
Comment: Try moving the saw blade with a pair of pliers.
Answer: Well you will have to open it to see what is going on.
Recommended method would be to take pictures for each step so you know how to put it back together.
After you open it, you can see if it is was your fault of not maintaining it (grease).
There are quite few parts in the gear box, for converting the rotary motion into linear motion, so first to find out is if there is a rotary motion or is the motor simply burned up.
Comment: I've never greased a reciprocating saw. I've used them on jobsites for many hundreds of hours. I'd be surprised if the manufacturer even calls for that.
Comment: Sure, but who does that? It's a bit of a stretch to assign "fault" here.
Comment: @isherwood just years of experience. Every gear box has moving parts in it, and it is happy if lubricated once in a while.
Comment: @isherwood **HOW TO GREASE THE GEAR ASSEMBLY ON THE DEWALT DC385K RECIPROCATING SAW**
Comment: https://duckduckgo.com/?q=greese+reciprocating+saw+gear&t=osx&ia=web
Comment: Agree that nobody I know considers greasing a reciprocating saw to be regular maintenance. But to the OP: tell us the brand and model and we'll tell you if it's worth saving.
Answer: First, it it's still under warranty, call the manufacturer.
If it's out of warranty, you may still want to call the manufacturer and ask if they have a repair center anywhere near you.
Check the manufacturer's website, and search the web generally, to see if anyone else has had this problem with this specific make and model and how they resolved it if they did.
If none of that helps, you're down to trying to carefully repair it yourself -- the manufacturer may have exploded parts diagrams that could help -- or hit it with a hammer and see if you can knock free whatever seized up. Either may destroy it beyond repair.
Or you can skip to considering it beyond repair, and shop for a replacement. Then maybe try to repair it just for fun.


Changing $_SERVER['REQUEST_URI']

Question: i tried to construct a RewriteRule in my .htaccess to get a more pretty URL for displaying a thread forum using Zend Framework.
Target URL is:
/forum/display/thread/i/1

What I want:
/forum/display/thread/1

Since Zend Framework builds GET Variabels from the URL (in this case beginning after /thread/) my original URL gives me a GET variable 'i' = 1, and the second URL gives me no GET variabels at all.
What I want, is either a way, to get the /1 into a GET variable respecting, that there may be more coming (e.g. /p/2 for the page number) OR a way to rewrite the URL using mod_rewrite so that the $_SERVER['REQUEST_URI'] is set to /forum/display/thread/i/1.
Anybody has an idea how to do that?
Answer: In your bootstrap:
protected function _initRouter()
{
    $route = new Zend_Controller_Router_Route_Regex(
        '/forum/display/thread/(.+?)',
        array('controller' => 'forum', 'action' => 'display'),
        array(1 => 'thread'),
        '/forum/display/thread/%d'
    );
    $front->getRouter()->addRoute('routeName', $route);
}

The code is not tested, please post any erros if they occure :)
Comment: I needed to modify your answer a bit for testing. its now:

    `private static function _setupRouter(Zend_Controller_Front $fc) {
        $route = new Zend_Controller_Router_Route_Regex(
            'forum/display/t/(.+?)',
            array('module' => 'forum', 'controller' => 'display', 'action' => 'thread'),
            array('i' => 1)
        );
        $fc->getRouter->addRoute('routeName' $route);
    }`

now i get the following error:
Comment: `Cannot assemble. Reversed route is not specified.
#0 /library/Zend/Controller/Router/Rewrite.php(470): Zend_Controller_Router_Route_Regex->assemble(Array, false, true)
#1 /library/ViewRenderer.php(131): Zend_Controller_Router_Rewrite->assemble(Array)`

sry for the bad formatting. I can't get it to display the code in a propper block

Changing $_SERVER['REQUEST_URI']