How to manage panels docking in Notepad++

Question: I am using Notepad++ recently I installed the Explorer plugin
But I can only find how to dock it on the left/right in tab with the other panels what I want is to dock it above the other panel so I can see the content of both at the same time
To clarify this is what I have:

But this is what I want: notice the difference in panel placement on the left

I know that i can put it on top/buttom/right of text area but that is not what I want
Comment: I'm with notepad++ v18.104.22.168 and I just installed Explorer plugin.
Answer: Use Ctrl + Alt + Shift + E (Or check the option Plugin>Explorer>Explorer)
I'm with notepad++ v188.8.131.52 and I just installed Explorer plugin and this shortcut dock the explorer in the left side of my notepad+9
Comment: This I can do to but it is not what I want to make it  mor clear i have added photo-shoped pictures to the question
Comment: OK Jens, with your screenshot it's now clear for me. But i'm afraid it's not possible right now.
Comment: You can go to notepad++ forum to ask them directly (I'm interested by answer to this question too) : https://notepad-plus-plus.org/community/
Answer: Not exactly the solution you are looking for, but I need the same thing, and this works for me.
Use any window you can dock there that you don't use (I use menu View->Document structure) and dock it to the location where you want your multi docked windows to be and resize it accordingly, then in undocked state, resize the panels and hover them above the panel that you placed there as placeholder.
Its not perfect, because you lose space due to the titlebar and if you move NP++ this undocked window will not move, but it is a workaround that in most cases will be useful enough.
For me, its NppFTP with Function List. Given that NppFTP also has an output window on the bottom, I have the docked window on the right side, so that I can actually overlap the non-used space of nppFTP's output window too! Win-win.
Answer: It's possible to redesign and rebuild the docking system, since it's an opensource editor, and the layout system is relatively simple, It won't take years to add such a feature.
Below is what I've achieved in a few hours:

https://github.com/KnIfER/Textrument (WIP)
description: while moving a floating panel or a preview window of a docked panel, holt alt to place it into the sub panel, or if the sub panel is already visible, you can simply drag and dock panels into it, just as usual.
Unlike that of MFC, Textrument's layout system doesn't allow you to split panels "infinitely". Split the original top and bottom panels horizontally, left and right vertically —— that's all, no further splits.
In my design, top and bottom panels have two extra properties  Extrude Left、Extrude Right which decide where to reside their left and right boundaries:

(Related code see DockingManager::reSizeTo)


QThread blocks in decoding UTF-16 when python code is freezed by cx_Freeze?

Question: In fact, the problem is a serious bug in a huge system, and we simplifiy the problem into code snippet below. We wanna figure out why the thread behaviors are different in python code and exe file.
The code includes two threads, and we expect both the two threads could run simutaneously and terminate in Windows 7 (64 bit) with python 2.7.
The code runs correctly when I use CPython directly, say, using "python tThread.py" in console. Both the two threads run and finish normally.
However, when the code is freezed into exe with cx_Freeze 5.0.1 and executed, the sub-thread blocks in the line uu = u16.decode("utf-16") , while the main thread goes into dead loop.
Below is tThread.py :
<code># -*- coding: UTF-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import time
from PySide import QtGui, QtCore
from PySide.QtCore import *
from PySide.QtGui import *

class Worker(QObject):
    done = QtCore.Signal()
    def longRun(self):
        count = 1
        while count < 20:
            print "Worker Thread", count
            u16 = u"ABCD".encode("utf-16")
            uu = u16.decode("utf-16")     # Block here <---
            count += 1
        self.done.emit()

def mainThread():
    app = QApplication([])

    objThread = QThread()
    obj = Worker()
    obj.moveToThread(objThread)
    obj.done.connect(objThread.quit)
    objThread.started.connect(obj.longRun)
    objThread.start()

    i = 1
    while not objThread.isFinished():
        QCoreApplication.processEvents()
        print "Main Thread", i
        time.sleep(0.1)
        i+=1

    print "Main Thread Over"

mainThread()
sys.exit()
</code>
Below is the setup.py file for cx_Freeze :
(console command is "python setup.py build_exe -b build")
<code>from cx_Freeze import setup, Executable
import platform

build_exe_options = {
    "packages": [ "PySide"],
    "include_msvcr": True
};

exe = Executable(u".\\tThread.py", base=None, targetName="tThread.exe" )

setup(  name = "tThread",
        version = "0.1",
        description = u"tThread",
        options = {"build_exe": build_exe_options},
        executables = [exe])
</code>
We suspect that there is bug in cx_Freeze, which leads to the different behaviors between raw code and exe .
Please help us find solution to make the thread pass the decode code, thanks.

After difficult debugging for several days, we find the thread blocks in this line in $Python27$\Lib\encodings\__init__.py
<code>    mod = __import__('encodings.' + modname, fromlist=_import_tail,level=0)
</code>
cx_Freeze has a bug for runtime module-import in multi-threading.

Finally, we bypass the blocking code using hack-code, say, manually import the modules outside the thread code. However, we do not think it is an elegant solution since there is still hidden import bug which may happen in future.
Hopes that the author of cx_Freeze can fix the bug and provide the perfect solution to our question.
Answer: The author of cx_Freeze has solved the bug and update it to 5.0.2 .
The related issue is Here


Is this function decreasing in $x$?

Question: Consider
$$x \mapsto \frac{\int_{x-b}^{x+b} e^{-\frac{z^2}{2} }\text d z}{\int_{x-c}^{x+c} e^{-\frac{z^2}{2} }\text d z}$$
decreasing in $x\in [0,\infty)$, if $c > b > 0$ ?
What I tried:
taking the derivative in $x$ yields:
$$\frac{\left( e^{-\frac{(x+b)^2}{2}} - e^{-\frac{(x-b)^2}{2}} \right)\int_{x-c}^{x+c} e^{-\frac{z^2}{2}}\text d z - \left( e^{-\frac{(x+c)^2}{2}} - e^{-\frac{(x-c)^2}{2}} \right)\int_{x-b}^{x+b} e^{-\frac{z^2}{2}}\text d z}{\left( \int_{x-c}^{x+c} e^{-\frac{z^2}{2}}\text d z \right)^2} $$
where the sign is determined by the numerator, so the question is if
$$\frac{e^{-\frac{(x+b)^2}{2}} - e^{-\frac{(x-b)^2}{2}}}{e^{-\frac{(x+c)^2}{2}} - e^{-\frac{(x-c)^2}{2}}} - \frac{\int_{x-b}^{x+b} e^{-\frac{z^2}{2} }\text d z}{\int_{x-c}^{x+c} e^{-\frac{z^2}{2} }\text d z} \geq 0 \ ?$$
Comment: The equality for the derivative is equivalent to that for a fixed $x$ a function $f(b)=\frac{e^{-\frac{(x+b)^2}{2}} - e^{-\frac{(x-b)^2}{2}}}{\int_{x-b}^{x+b} e^{-\frac{z^2}{2} }dz}$ is non-decreasing for $b>0$ and the computer experiments suggest that this is true.
Comment: I tried to consider the derivative. But even in "explicit" form I think  its sign is hardly to determine (I have not managed it). So maybe someone else has another idea.
Comment: It seems that the last inequality whoud have the opposite sign, because $ e^{-\frac{(x+c)^2}{2}} - e^{-\frac{(x-c)^2}{2}}<0$.
Comment: Why not applying Leibnitz rule?
Comment: It makes sense, intuitively, that it is decreasing. As $x$ increases, the slices of $e^{-\frac{x^2}{2}}$ get smaller.
Comment: Yes, but also the denominator is decreasing. But you can easily verify that the function tends to $0$ when $x\to \infty$. Further, you see that at $x=0$ there is an extrem value.
Comment: It might help to first tackle the case when $c$ is an integer multiple of $b$. That way, the denominator turns into a sum of shifted copies of the numerator, which might simplify matters. Then you could tackle the case when $c$ is a rational multiple of $b$, and finally appeal to some continuity argument to get the full statement.
Comment: Try using the estimates $(y-x) e^{-y^2/2} \leq \int_x^y e^{-z^2/2} \, dz \leq (y-x) e^{-x^2/2}$.
Comment: @Alex Ravsky: You are right. Thanks.
Answer: Let me just show you a few tricks so the next time you'll be able to figure such things out without pen or paper, not to mention MSE.
First, drop the common part. We need to show that
$$
x\mapsto \frac{\int_{[x-b,x+b]}e^{-z^2/2}dz}{\int_{[x-c,x+c]\setminus[x-b,x+b]}e^{-z^2/2}dz}
$$
is decreasing for $x\ge 0$.
Next, use symmetry and the fact that the integral of a family of decreasing functions over the parameter is still a decreasing function. Thus, it suffices to show that for every $0<s<b$,
$$
x\mapsto \frac{e^{-(x-s)^2/2}+e^{-(x+s)^2/2}}{\int_{[x-c,x+c]\setminus[x-b,x+b]}e^{-z^2/2}\,dz}
$$
is decreasing for $x\ge 0$.
Turn the fraction upside down and use the same logic to conclude that it suffices to show that for all $0<s<b<t$,
$$
x\mapsto \frac{e^{-(x-t)^2/2}+e^{-(x+t)^2/2}}{e^{-(x-s)^2/2}+e^{-(x+s)^2/2}}
$$
is increasing for $x\ge 0$.
Now open parentheses and cancel inessential stuff. We just need to show that for $0<s<t$,
$$
x\mapsto \frac{e^{xt}+e^{-xt}}{e^{xs}+e^{-xs}}
$$
is increasing for $x\ge 0$.
This can be done by hand, but here is a general principle that makes it a no-brainer. Let $f(x)=\sum_{k\ge 0}a_k x^k$ and $g(x)=\sum_{k\ge 0}b_k x^k$. If $a_k,b_k\ge 0$ and $a_k/b_k$ increases with $k$, then $f(x)/g(x)$ increases for $x\ge 0$. Indeed, let $\mu=f(x)/g(x)$ for some $x$. Then $0=f(x)-\mu g(x)=\sum_{k\ge 0}(a_k-\mu b_k)x^k$. Note that the coefficients $a_k-\mu b_k$  must change sign just once from $-$ to $+$ as $k$ increases. Let them change sign between $K$ and $K+1$. Then, if we replace $x$ by $x'>x$, all negative terms will be multiplied by at most $(x'/x)^K$ while all positive terms will be multiplied by at least $(x'/x)^{K+1}$, so the difference $f(x')-\mu g(x')$ will be positive.
The rest should be clear.
Comment: @Falrach "I do not understand how your general principle can be apllied here" We have $f(x)=e^{xt}+e^{-xt}=2\sum_{k=0}^\infty \frac{t^{2k}}{(2k)!}(x^2)^k$ and similarly for the denominator $g(x)$ with $s$ instead of $t$. Thus $a_k/b_k=(t/s)^{2k}$ (if you view $x^2$ as a new variable), which is clearly increasing. The symmetry is crucial, indeed :-)
Comment: Took me a while to verify all your steps. The last part I have done by hand. Somehow I do not understand how your general principle can be apllied here.
By the way, it seems to be crucial to make use of the symmetry as you did. I tried it first without this symmetry argument, cause the resulting quotient is simpler. But then it does not work in the end.
Comment: Got it. Thanks for your help

Is this function decreasing in $x$?


Media player and .NET 4.0

Question: I have some WinForm code (.NET 2.0) using Windows Media Player utilizing the COM (AxInterop.WMPLib.dll and Interop.WMPLib.dll).
I am trying to push it to .NET 4.0 but it doesn't load the DLL.
It seems that 4.0 doesn't support that specific version (or any version) of the WMP.
Does anyone know why? Is there any other way to deal with it? (Before I go to WPF)
Comment: Don't make us guess at what you see on your screen.
Comment: Precisely.  Say exactly what the problem is?
Answer: You can copy C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\WMPLib.dll and AxInterop.WMPLib.dll to your bin directory and reference these assemblies. These assemblies are compiled for 'AnyCPU'.
Answer: If your error log shows
"Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config"
You are loading a 32bit COM into a 64bit process. That will cause an exception . You need to switch to use the 64bit version of Windows Media Player, or change your process to target 32bit.
i.e. Change your build settings from AnyCPU to x86 or X64, and reference the 32bit or 64bit of WMP accordingly.

Media player and .NET 4.0


Upload PageBlob To Azure Storage Using Java

Question: I want to upload a file with BlobType="PageBlob" to Azure Storage using Java.
On command line, I am able to do it by simply specifying --blob-type PageBlob argument to azcopy command. In Java, I have:
BlobClient blobClient = containerClient.getBlobClient("test.bmp");
blobClient.uploadFromFile("data/test.bmp");

However, it uploads a file with BlockBlob type.
I am aware of getPageBlobClient() method but it does not offer an uploadFromFile() method that takes file path as an argument as shown above. How can I do it? Thanks.
Answer:
I am aware of getPageBlobClient() method, but it does not offer an uploadFromFile() method that takes a file path as an argument, as shown above. How can I do it? Thanks.

As of now, there is no direct command to upload a page blob using the Azure Java SDK.
According to this MS-Docs:
Page blobs are a type of data storage in Azure that are designed for storing index-based and sparse data structures like OS and data disks for Virtual Machines and Databases. Page blobs are made up of 512-byte pages, which can be read and written to individually, making them ideal for storing data structures that require random access. For example, Azure SQL DB uses page blobs to store its databases. Additionally, page blobs are often used for files that require range-based updates.
You can use the Put page REST API request, which is used to create a page blob and write the blob aligned with a 512-byte boundary.
Request:
https://myaccount.blob.core.windows.net/mycontainer/myblob?comp=page

You can refer to this SO-Thread by Gaurav Mantri for uploading a page blob using Python code.


Ajax e link como fazer com que funcione o a:visited quando se usa ajax

Question: Fiz um site recentemente esta semana, vhtvshows.com.br.
Quando se clica em alguma série para assistir e escolhe o episódio o ajax pega o link e coloca na minha div, porém quando eu volto o link acessado não fica na cor que coloquei no CSS:
#exemplo a:visited{
color:#0099ff;
}

Já quando eu abro o link em nova aba aonde o ajax não ira surtir efeito funciona perfeitamente o a:visited.
Alguém sabe o que posso fazer para que valide o a:visited mesmo usando ajax ? não quero ter que usar " iframe".
Comment: Você precisária fazer o ajax carregar de baseado na url, usando uma hash como [nesse site](http://www.pauletsconsorcio.com.br/#!/quem-somos). Repare que ao trocar de página é carregado com ajax, porem a url tbm troca, e quando você entra em uma url diferente diretamente o conteudo correto já é carregado... fazendo o site dessa forma você consegue usar o a:visited
Comment: O blz cara acho que usar o $_GET vou ter o resultado esperado pois vai ser carregado no historico do computador fazendo assim o a:visited funcionar. Obrigadão ai.
Answer: Infelizmente não acho que seja possivel, pois o :visited só irá funcionar para os sites que estão presentes no historico do navegador.
Porém você ainda pode adicionar uma classe aos links visitados.
Caso o browser suporte html5, você pode utilizar objeto history para forçar que o link do AJAX entre no historico:
var linkOpen = document.getElementById("<ID do seu Link>");
var hrefAtual = window.location.href;
history.pushState(null, null, linkOpen.href);
history.pushState(null, null, hrefAtual);

JSFIDDLE
Comment: Poderia fornecer a origem da informação que fala sobre a depreciação do :visited?
Comment: pode me dar um exemplo de oque fazer neste caso sem usar visited ? obbrigado
Comment: @Guilhermenascimemto, procurei aqui, mas não achei, o que achei foi que alguns elementos do foram depreciados no HTML4 em favorecimento dos do CSS, possivelmente eu assimilei está informação de forma errada.
Comment: @Gabriel, você o link está no mesmo domínio? Pode ser uma solução baseada em HTML5?


CPU load for C process with respect to core(s)

Question: I am about to find out how a specific process, in C, loads the CPU over a certain time frame.
The process may switch processor core during runtime, therefore
I need to handle that too. The CPU is an ARM processor.
I have looked at different ways to get the load, from standard top,
perf and also to calculate the load through the statistics given in the
/proc/[pid]/stat-file.
My thoughts is to have a program that read the /proc/[pid]/stat-file as suggested in the thread:
"How to calculate the CPU usage of a process by PID in Linux from C?" and calculate the load accordingly.
But how would I treat core switching? I need to notice it and adjust the load calculation.
How would you recommend me to achieve this?
Update: How can I see which core the process runs in and by that examine if it has switched core since the last chack assuming I poll the process figures/statistics at least twice?
Comment: Which cpu core the process scheduler happens to put the process shouldn't affect the accounting of the amount of cpu time the process has received.
Comment: possible duplicate of [total cpu usage of an application from /proc/pid/stat](http://stackoverflow.com/questions/16726779/total-cpu-usage-of-an-application-from-proc-pid-stat)
Comment: @Jahaja That post was good but it lacks the handling of when the process is executed first on core A and after a while on core B?
Comment: Alright, you are right about that @Jahaja.
Answer: The perf tool can tell you the amount of cpu-migrations your process has made. That is, how many times the process has switched cpu. It won't tell you which cpu cores though.


Why do these points lie in different half planes?

Question: I'm reading Conway's complex analysis book and I'm having problems to understand one comment on page 51.
First of all, Conway begins with the definition of symmetry:

Definition: Let $\Gamma$ be a circle through points $z_2, z_3, z_4$. The points $z,z^*$ in $\mathbb C_{\infty}$ are said to be
  symetric with respect to $\Gamma$ if
  $$(z^*,z_2,z_3,z_4)=\overline{(z,z_2,z_3,z_4)}.$$

Afterwards, he begins to investigate what it means two points to be symmetric:

So my question is why do we have $z$ and $z^*$ lie in different half planes determied by $\Gamma$ if $\text{Im} \frac{z^*-z_3}{z_2-z_3}=-\text{Im}\frac{z-z_3}{z_2-z_3}$?
Comment: What "different half planes determined by Γ" are, please?
Answer: The argument of $w = \frac{z - z_3}{z_2 - z_3}$ is the oriented angle between the ray from $z_3$ to $z_2$ and the ray from $z_3$ to $z$ (the first ray being the initial side of the angle). The sign of $\operatorname{Im} w$ tells you whether this angle is between $0$ and $\pi$ or between $\pi$ and $2\pi$, hence which side of the line from $z_2$ to $z_3$ the point $z$ is on. The equation here implies that the answer to this question must be different for $z^{*}$ than it is for $z$.
Comment: Why is the argument of $w$ the oriented angle between the ray from $z_3$ to $z_2$ and the ray from $z_3$ to $z$? thank you!
Comment: $\arg w = \arg(z - z_3) - \arg(z_2 - z_3)$.


How to pass an object with private variables from Laravel to Inertia

Question: Im new using laravel with inertia
Version of my laravel is: 9.10.1, Inertia version: 0.11 and Vue: 3.2
I have my class RefundManager
class RefundManager
{
    private int $id;
    private string $refund;

    public function __construct(
        int $id,
        string $refund,
    ) {
        $this->id = $id;
        $this->refund = $refund;
    }

    public function id(): int
    {
        return $this->id;
    }

    public function refund(): string
    {
        return $this->refund;
    }

}

I have in my controller an object of that class, and I can access perfectly at $id and $refund through his respective methods id() and refund().
But when I try to pass it to inertia I receive an empty object. Steps:
return Inertia::render("Ppo/Sat/RefundCases/Index", [
   'refund' => $myRefundObject
]);

In my vue component I have declared prop as object:
props: {
  'refund': Object
}

And when I change variables $id,$refund to public, then it works.
But when $id and $refund are privates I only receive an empty object and I cannot to access public functions...
How can I make it works with private variables by accessing them through the public methods?
Answer: To convert a PHP object to a JS object, you need to convert it to a string with json format.
Laravel does it automatically when you send an object to the view by trying to call toJson() if defined in the class (by default it is present in Model classes)
So add these two function (will not hurt to add toArray() too)
/**
 * Convert the object instance to an array.
 *
 * @return array
 */
public function toArray()
{
    return [
        'id' => $this->id,
        'refund' => $this->refund,
    ];
}

/**
 * Convert the object instance to JSON.
 *
 * @param  int  $options
 * @return string
 *
 * @throws \Exception
 */
public function toJson($options = 0)
{
    $json = json_encode($this->toArray(), $options);

    if (JSON_ERROR_NONE !== json_last_error()) {
        throw new \Exception(json_last_error_msg());
    }

    return $json;
}


Importing a JavaScript file into JSP page: why this is not working?

Question: This code is executed when I run it inside a .jsp page enclosed by

After that, code ran unincidentally.
Comment: uhm. if that works, this would likely work too: `$(document).ready(function () {$('#dgProjects').datagrid({
            onSelect: function(index, row){
                alert(index + ' - ' + row)
            }
        });});` which is what i was hinting at in my comment.


Restrict editing of content based on form value in content type

Question: I'm not sure of the exact way to word this. I'm "just the designer". Where I'm working we've traditionally made a role per content type to limit access to editing/creating certain kinds of content. On a new (D8) site we're working on, we'd like to have a single content type ("Room") and have different people be maintainers of those rooms depending on what's set in the "Building" field.
The idea is to avoid having a ton of mostly-similar Room content types (that would all require updating when we want a change). And also of course to avoid people from other buildings editing rooms that don't belong to them.
(I think it'd be fine to have either 1) the rooms originally created by an admin and just have the building field hidden/disabled/limited when non-admins edit, or 2) even let them create new rooms with the building field limited based on their role/permissions.)
I don't know if there's a built-in way to do this, or perhaps modules you could recommend.
The developer I'm working with seems convinced that the only way to accomplish this is to build a custom form in PHP that essentially duplicates Drupal's built-in form for the Rooms content type we've made (I'd really like to avoid this route, since it'd be a lot of hard-coded stuff that needs dev time, testing, maintenance, etc.). Thanks!
Comment: I think this is achievable with a user reference field and extending hook_node_access to check the current user as being in the list of those users, if so, Grant the same CRUD permissions that the owner would have (or whatever suits).
Answer:
(I think it'd be fine to have either 1) the rooms originally created
  by an admin and just have the building field hidden/disabled/limited
  when non-admins edit, or 2) even let them create new rooms with the
  building field limited based on their role/permissions.)

You could do this via a custom module or in your theme's mytheme.theme
<code>function mytheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // check form id for edit
  if($form_id == 'node_room_edit_form') {
    // Load the current loggedin user.
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    // Check if user does not have administrator role
    if(!$user->hasRole('administrator')) {
      // get current node id
      $nid = \Drupal::routeMatch()->getParameter('node');
      // load the node
      \Drupal\node\Entity\Node::load($nid);
      // check if building field is not set to something
      if($node->field_building->value != 'something') {
        // remove access to field, make field not required so when
        // they save they don't get an error.
        $form['field_name']['widget']['#access'] = FALSE;
        $form['field_name']['widget']['#required'] = FALSE;
      }
    }
  }
  // check id for create
  if($form_id == 'node_room_form') {
    // logic goes here.
  }
}
</code>
Comment: Thank you! Your code example has been very useful to me. So far I'm using something like your code in a custom module, along with the [Taxonomy Access Control Lite module](https://www.drupal.org/project/tac_lite), and it's looking promising.


Asynchronous Iframe not working

Question: I have the following code to load iframe content after the main page loads
<code><head>
    <title></title>
</head>
<body>
    <script>
    (function(d){
    var iframe = d.body.appendChild(d.createElement('iframe')),
    doc = iframe.contentWindow.document;

    // style the iframe with some CSS
    iframe.style.cssText = "position:absolute;width:200px;height:100px;left:0px;";

    doc.open().write('<body onload="' +
   'var d = document;d.getElementsByTagName(\'body\')[0].' +
   'appendChild(d.createElement(\'script\')).src' +
   '=\'http:\/\/google.com\'">');

   doc.close();

   })(document);
 </script>
</body>
</code>
Unfortunately, this code is not working as expected. Could anyone point out what is wrong here?
Thanks!
Answer: It's probably because this function is never called.
Give your function the name and call it from somewhere, for example body onLoad event
Comment: When i change google.com to `mydomain.com`, `mydomain.com` is also not loaded, but the weird thing is that i still get a hit from my IP in the statistic in my cPanel
Comment: @aye where do u start your page? The reason could be cross domain access. If your page is on localhost, try to set the iframe to local page too
Comment: I tried changing it to the same domain, but it still did not work. In all cases, i see the iframe loaded, but the content inside the iframe was not displayed
Comment: @aye where do you run your function?
Comment: http://totgia.com/testiframe.html is the main page. http://totgia.com/time.html is inside the mainpage's iframe

Asynchronous Iframe not working


Leveraging field_get_items variable in a custom field template

Question: I can use a template preprocess function for node to simply get the alt tag of an image field image using the venerable field_get_items as such:
function MYTHEME_preprocess_node(&$vars, $hook) {
// Global node.
  $node = $vars['node'];

 $field_image_items = field_get_items('node', $node, 'field_image');
  // Load individual data from 'field_image'.
    $vars['alt_caption'] = $field_image_items[0]['alt'];
}

Then in node.tpl.php, I can render the alt tag of the image from the variable we created above as:
<?php print $alt_caption; ?>

... and that works great.
However, I'd like to customize the template for the image itself so when I create a field--field_image.tpl.php template, sure enough the image renders fine but if I add the $alt_caption variable, that does not render. I'm guessing this will simply not work or there is an extra step I need to do for the variable to render in this new template.
Answer: You need TEMPLATE_preprocess_field() function at template.php
You can use this preprocess function in same way as you are doing for NODE. Like -
function MYTHEME_preprocess_field(&$vars) {
  if ($node = menu_get_object()){
    $node = $vars['node'];
    $field_image_items = field_get_items('node', $node, 'field_image');
    $vars['alt_caption'] = $field_image_items[0]['alt'];
  }
}

Then go to your TPL made for your particular field and print it where ever you like just like you have mentioned --
<?php print $alt_caption; ?>

And it will work like charm!! I have implemented like this several times.
But yeah...don't forget to clear your cache after this implementation.
Comment: I'm getting a nasty error with that even after clearing cache: `Notice: Undefined index: node in gratis_preprocess_field() (line 266 of template.php).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7663 of /includes/common.inc).` -- It seems preprocess field does not like the node variable defined? (Note gratis is the name of my theme).
Comment: @DannyEnglander - Edited my answer after seeing my own template.php, please check now after updating your code :)
Otherwise there are other option to get relevant info of field by the machine name of field as it's available in $vars at TEMPLATE_preprocess_field()
Comment: Ok this now works but without `$node = $vars['node'];`, that still throws the error but if I take it out, it works well on a node page but not on my main page with teasers. There, I'm getting this error: `Notice: Undefined variable: alt_caption in include() (line 54 of field--field_image.tpl.php).` So not sure if this will end up being a good solution unless there is a way to make the variable available in the teaser?
Comment: @DannyEnglander - Because it expect menu_get_object() to get executed which take place on full node load.
Can you please output $vars inside this preprocess function by doing dsm($vars) & give me the result ?
Comment: @DannyEnglander - You can chat with me on IRC, I am in room #drupal & #drupal-support with name RajeevK
Comment: Hey thanks, I added the vars to a fiddle, too long for here: http://jsfiddle.net/highrockmedia/nMv7Z/1/
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9389/discussion-between-rajeevk-and-danny-englander)
Answer: As I was having issues with this working in teaser mode, another way to do this is to forgo the preprocess function altogether and render this in your custom image field template using the #item var that's already available:
 <?php if ($item['#item']['alt']): ?>

<?php print $item['#item']['alt']; ?>

 <?php endif; ?>

This will render a nice HTML5 caption under the image based on your alt tag. What's interesting about this is that the default field.tpl.php template in D7 does not give item as a possible variable. Inspiration for this method here.


Cannot read property [function] of undefined

Question: I have this in my return part of my render function:

          {nums.map(function(num, index){
            return
{num} <input type="submit" value="unmatch" onClick={this.unMatchButtonClicked} />

;
          })}

But when I load the page I get an error saying: Cannot read property 'unMatchButtonClicked' of undefined
Even though it is the function directly before render:function()
unMatchButtonClicked: function(){
  console.log('called');
},

so what is the scope of this and why is it undefined?
Comment: set `this` for `.map` callback  - `nums.map(function(num, index){ /* code */ }, this)`
Comment: @AlexanderT. cheers bro
Comment: @AlexanderT. I have one issue with this though. it is now changing the `this` in other parts of the code and setting a variable elsewhere to be == to mouse click rather than the `this` it should be elsewhere. can elaborate if you need
Answer:
Option: Array.map(function () {/*...*/}, this)
Option: var unMatchButtonClicked = this.unMatchButtonClicked and onClick={unMatchButtonClicked}

Apart from that you should consider using an arrow-function for your click-handler or bind this to your function.
http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html


Is there a way to remove a menu item from the active trail without removing it from the menu parent?

Question: I'm a relative newcomer to Drupal and I'm not sure how to handle this. On this page:
http://staging.stvincentdepaul.net/volunteer
You can see that Volunteer is highlighted in the main nav but so is Today. If you hover over those L1 links, you'll see that each one has a Donate and Volunteer button. These are all part of the main navigation menu in the admin section so each Donate and Volunteer button falls under each L1 link. The Today section was the last to have Donate/Volunteer added so it is attaching the active-trail class to that link since it can only have one.
Is there a way to keep those Donate/Volunteer links in the menu but not part of the active trail?
Answer: This is a common headache. I keep meaning to write a contrib module to address this by letting users define a "canonical" menu item in the event there are several menu items that point to the same page in the same menu.
That said, there are some workarounds you can use.
The best option is to use the Redirect module. You create a redirect to your Donate and Volunteer pages then put the redirects in the menus.
So if your volunteer page is at /volunteer and donate is at /donate, then you can create two redirects. One called /go-volunteer and another called /go-donate which redirect to their respective pages. Then you'd put /go-volunteer and /go-donate in the menu which, when clicked, will take the user to the appropriate page.
Since they're redirects, they won't trigger the active trail.
Comment: Oh wow! That's a great idea, man. Thanks for bringing it up.
Comment: Hello, I voted up too fast because I must say that Druvision solution doesn't work without [this module installed](https://drupal.org/project/any_menu_path). Because you cannot create menu item with path that do not exist. But I don't want anyway to vote it down. Thanks for the idea, with 2 modules I made it work.


Notating using ties on a 4/4 music

Question: I am required to notate a note that is played on the 'and' of 1 and ring for the remaining beats of a 4/4 measure.
My choices is:

I use a quaver rest followed by a quaver tied to a dotted minim in which case I will not be distinguishing the half way mark at 3.
Or should I have a quaver rest followed by a dotted crotchet tied to a minim where I will be emphasizing on the midpoint of the bar.

Which one of the two options is correct and why?
Comment: If not marking the middle of the bar is an option, why use ties at all? You could simply write a double-dotted note.
Comment: The main point of seeing a 4/4 bar to be split into halves is to be able to read what's in the second half more easily. Here there's little point, as the note carries through to the end.
Answer: There are actually four possibilities:

IMHO all of these are acceptable, although I find the first one easiest to read. The third one looks unneccessarily complicated and the fourth looks a bit 'unusual', but would probably be a good choice if there was half a page of this rhythm.
Answer: I would do it differently. Eighth rest, eighth note tied to quarter note tied to half note. (I can't post graphics easily.) The suggested pattern avoids breaking any "normal" divisions and makes sight reading easier.

Notating using ties on a 4/4 music


OpenGL error 0x0500 in -[CCTextureAtlas drawNumberOfQuads:fromIndex:] 556

Question: I am following BOX2D tutorial from Learn COCOS2D book and I started to see this error like 10 times every second on console. I googled this error but couldn't find any relevant information. Some people are talking about shader files but I don't know what are those. Some people are saying not to use multiple GLVIEWs but I don't see I am doing that. Below is the entire code of implemenation file.
ERROR MSG:
OpenGL error 0x0500 in -[CCTextureAtlas drawNumberOfQuads:fromIndex:] 556
<code>- (void)dealloc
{
    if(world){
        delete world;
        world = NULL;
    }
    if(debugDraw){
        delete debugDraw;
        debugDraw = nil;
    }
    [super dealloc];
}

+(id)scene{
    CCScene *scene = [CCScene node];
    PuzzleLayer *layer = [self node];
    [scene addChild:layer];
    return scene;
}

-(void)setupWorld{
    b2Vec2 gravity = b2Vec2(0.0f, -10.0f);
    //bool doSleep = true;
    world = new b2World(gravity);
}

-(void)createBoxAtLocation: (CGPoint)location withSize:(CGSize)size{
    CCLOG(@"Box location: %.0f, %.0f", location.x, location.y);
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
    b2Body *body = world->CreateBody(&bodyDef);

    b2PolygonShape shape;
    shape.SetAsBox(size.width/2/PTM_RATIO, size.height/2/PTM_RATIO);
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &shape;
    fixtureDef.density = 1.0;
    body->CreateFixture(&fixtureDef);
}

-(void)setupDebugDraw{
    debugDraw = new GLESDebugDraw(PTM_RATIO * [[CCDirector sharedDirector] contentScaleFactor]);
    world->SetDebugDraw(debugDraw);
}

-(void)draw{
    glDisable(GL_TEXTURE_2D);
    world->DrawDebugData();
    glEnable(GL_TEXTURE_2D);
}

-(id)init{
    if(self = [super init]){
        [self setupWorld];
        [self setupDebugDraw];
        [self scheduleUpdate];
        self.isTouchEnabled = YES;
    }
    return self;
}

-(void)registerWithTouchDispatcher{
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}

-(void)update:(ccTime)dt{
    int32 velocityIterations = 3;
    int32 positionIterations = 2;
    world->Step(dt, velocityIterations, positionIterations);
}
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
    CGPoint touchLocation = [touch locationInView:[touch view]];
    touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
    touchLocation = [self convertToNodeSpace:touchLocation];
    b2Vec2 locationWorld = b2Vec2(touchLocation.x/PTM_RATIO, touchLocation.y/PTM_RATIO);
    [self createBoxAtLocation:touchLocation withSize:CGSizeMake(50, 50)];
    return TRUE;
}
</code>
Answer: OpenGL error 0x0500 = GL_INVALID_ENUM, For more details about openGL Error: Check Here
I guess your cocos2d version is 2.0 or higher. Cocos2d 2.0 uses openGLES2.0, in that opengl immediate mode calls are not allowed...see your code glEnable is used.
Replace your draw function with
<code>-(void) draw
{
    [super draw];
    ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
    kmGLPushMatrix();
    self.world->DrawDebugData();
    kmGLPopMatrix();
}
</code>
Here is one other thread, refer my answer in same for more details:
Comment: I found the issue: I missed setting the flags on debugDraw as     debugDraw->SetFlags(GLESDebugDraw::e_shapeBit);
Comment: You are right, it's problem with GLES version. Thanks a lot to give me correct draw method. But I still don't see any box getting drawn on screen although createBoxAtLocation method is getting called fine. Any thoughts on that?
Comment: GLES-Render.h and GLES-Render.m from Cocos2D 2.0
Comment: Will appreciate if you can please elaborate more on why createBoxAtLocation still not drawing blocks as I am still getting blank screen?
Comment: Just to let you know, I have #import "GLES-Render.h" at top of my .h file. So it's included. But still nothing is drawn by BOX2D on screen.


How to compare two binary classification models

Question: I am training two different binary classification models (LGBM, Catboost) on the same CV splits of a moderately imbalanced dataset.
I would like to compare their performance. Obviously, if we are to compare them globally we can compare their corresponding metrics (e.g. AUC).
However, I am interested to compare their error profile - e.g. do they make the same mistakes?
This is meant to check whether ensembling them is likely to be of benefit or not. Obviously, the best way to check that is to ensemble them and see how the ensemble would perform. But I am still curious in how different their individual predictions are. I wonder what metric would be meaningful?
Maybe rank correlation in the way they rank the samples according to the confidence score of the sample belonging to the minority class?
Answer: To assess the ranking of ranking models, it is common to use metrics such as precision and recall. Another very interesting metric is the F1-score, which provides an average (harmonic) between precision and recall.
There are a number of metrics to measure ranking that allow you to compare 2 models like the ones you are using. There is no single metric. Generally, the problem you are working on will require either high accuracy (low errors, eg plant species classification) or high recall (low false positives, eg disease diagnosis). As there is a trade-off between these two metrics, what they usually do is evaluate the scenario, seeking greater accuracy or recall. The same goes for other metrics.
On this site there is a list of metrics, many quite common, others more specific that they evaluate considering global and local aspects, data with the presence of outliers, etc:
https://scikit-learn.org/stable/modules/model_evaluation.html
Additionally, to measure dissimilarity between classes, you can use some dissimilarity metric like Jaccard index.

One way of applying precision/recall/f1 to analyze each of the classes would be to analyze its support (number of occurrences of each classes in the set of predictions made).
For example, with sklearn.metrics.precision_recall_fscore_support:
If the metric is (here best value is 1 and worst is 0)
precision_recall_fscore_support(y_true, y_pred, average='micro') = (0.3., 0.3, 0.5).
we could say that there were similar mistakes for samples i=0, 1 (both given 0.3) but not for the i=2.
For individual samples, you can apply the Jacard index. For example,
jaccard_score(y_true[k], y_pred[k]) = 0.6
will be better than the prediction that has jaccard_score(y_true[j], y_pred[j]) = 0.3.
If jaccard_score(y_true[q], y_pred[q]) = jaccard_score(y_true[p], y_pred[p]), then samples corresponding to index pandq` had similar mistakes.
Comment: Welcome to Cross Validated! It is not clear how this answers the question about how to compare the particular predictions made instead of overall performance in terms of, say, precision or recall. Could you please clarify?
Comment: @Nick, that's not a problem, the AI has been quite efficient in many tasks. However, I confess that I spent more than 1 hour typing and exploring the question until I got to a reasonable level that maybe can contribute. Many questions with an "open formulation" character end up having a more open answer, possible paths. As a philosopher would say, as important as an answer is question formulation. Furthermore today, that AI can help a lot. If the person wants to compare bananas with apples, there is probably a metric that can help them, although some comparisons may not be as usual/meaningful.
Comment: @Student I really hope you don't consider this discouraging but this post almost reads like it is generated by AI.


Como utilizar funções externas dentro do server usando Shiny?

Question: Estou criando uma interface gráfica para um algoritmo que desenvolvi em linguagem R. O algoritmo possui diversos scripts com funções que conversam entre si, e após iniciado, demora horas para ser finalizado.
Estou usando o pacote Shiny com suas entradas para coletar os parâmetros do algoritmo, e assim colocar ele para rodar. Entretanto, não estou conseguindo.
O algoritmo não possui saídas gráficas, somente escreve arquivos na própria máquina.
O código segue, onde algoritmo é o código a ser chamado, e algoritmo.R é onde se encontra todos os scripts com as funções.

ui <- ... (
  ...
  tabPanel ("Resultados",
    textOutput ("resultados")
  )
)

server <- function (input, output) {
  ...
  output$resultados <- eventReactive ({
    if (input$iniciar)
      isolate (algoritmo (input))
  })
}

source ('algoritmo.R')

Answer: É só colocar source() no início do código. Seja histogramaVermelho.R um arquivo com uma função que faz um histograma vermelho:
histogramaVermelho <- function(x, breaks = 10){
  hist(x, breaks, col="red")
}

Basta salvar este código no arquivo histogramaVermelho.R e construir a seguinte app:
source("histogramaVermelho.R")

library(shiny)

# ui

ui <- fluidPage(

   titlePanel("Old Faithful Geyser Data"),

   sidebarLayout(
      sidebarPanel(
         sliderInput("bins",
                     "Number of bins:",
                     min = 1,
                     max = 50,
                     value = 30)
      ),

      mainPanel(
         plotOutput("distPlot")
      )
   )
)

# server

server <- function(input, output) {

   output$distPlot <- renderPlot({

      x    <- faithful[, 2]
      bins <- seq(min(x), max(x), length.out = input$bins + 1)

      histogramaVermelho(x, breaks = bins)
   })
}

# Run the application
shinyApp(ui = ui, server = server)

Além disso, os arquivos app.R e histogramaVermelho.R devem estar na mesma pasta. Se isto não for possível, o caminho do arquivo histogramaVermelho.R no sistema deve ser atualizado dentro da função source().


Delete all comments in an excel-sheet using xlwings python on MacOS?

Question: I am looking for a method to delete all comments in an Excel-sheet using python.
On Windows i can do this using the following command:
ws2.used_range.api.ClearComments()

But this is not working on Mac.
How can i delete all comments in an excel-sheet using xlwings on Mac?
Comment: So what about a loop for all cells with comments? How to check if cells have comments?
Answer: In openpyxl you'd have to do it cell by cell.
In Xlwings you can do cell by cell or range.
For example to clear all cells in a range, either set the range e.g. 'A1:B5' or you can select the range of 'used cells' in the sheet;
(Code works on Windows I do not have MACOS PC)
import xlwings as xw

wb = xw.Book('foo.xlsx')
ws = wb.sheets["Sheet1"]

### Clear comments from all cells in range A1:B5
ws.range('A1:B5').api.ClearComments()
### Clear comments from all 'used cells' on the sheet
ws.used_range.api.ClearComments()

...

Comment: I like the answer and this works well on Windows - but i need a solution for Mac
Comment: Did you try on MACOS and it didn't work? As you know from Felix that Xlwings with MACOS support is now reduced and unless somebody has already done this you may be on your own. I'd be happy to try by as mentioned I don't have any access to a MACOS PC. The command  `ClearComments()` is basically a duplication of the VBA operation so although it's probably not ideal you can use Xlwings to add and call a VBA macro to do this instead.
Comment: I tried the comment also on Mac.
On Windows it works fine - but i get an error on Mac.


drush sql-sync fails with PHP Fatal Error

Question: drush sql-sync @devyau @stageyau returns:

Unable to load class Drupal\Driver\Database\Drush
   PHP Fatal error:  Call to a member function dump() on a
  non-object in
  /root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc on line
  275

Drush command terminated abnormally due to an unrecoverable error.

Error: Call to a member function dump() on a non-object in
  /root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc, line
  275
Comment: what verion of Drupal is this (I think I know, but I don't want to 'guess' what the question is actually about ...)? And what version of Drush are you using?
Comment: I'm using Drupal 7.38 and Drush 7.0.0. Fixed my alsias files and moved Directory /var/www/vhosts/stage.youngamericansunited.net>
                Options -Indexes +FollowSymLinks -MultiViews
                AllowOverride All
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FNAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Answer: First you run this command on console. if command is run successfully after then you check your drush library, I think this is drush library problem.
Second is you can try other command like :-
drush ard
Comment: drush ard returns The external command could not be executed due to an application error.                                                                                [error]
Unable to determine sites directory for devyau
Comment: How do I fix a drush library problem...have searched all over and can't figure it out.
Answer: You should ensure that your remote alias is correctly declared:
$aliases['remote'] = array (
  'root' => 'absolute_path_to_your_drupal',
  ...
)

try other commands like
drush @devyau uli
drush @stageyau uli

If doesn't work the path may be the problem.
Comment: I'm working with the devyau stageyau and prodyau directly on the server...not running Drush on my desktop computer
Comment: drush @devyau uli and stage uli return:PHP Fatal error:  Call to a member function db_spec() on boolean in /root/.composer/vendor/drush/drush/includes/environment.inc on line 370
Comment: OH, I see...my remote aliases ARE OK. THey are on the server.
Comment: drush ard returns: Call to undefined function drush_sql_get_class() in /root/.composer/vendor/drush/drush/includes/environment.inc on line 366
Comment: echo $PATH returns: /root/.composer/vendor/bin:/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
Comment: drush @devyau uli returns:
PHP Fatal error:  Call to undefined function drush_sql_get_class() in /root/.composer/vendor/drush/drush/includes/environment.inc on line 366
Comment: And do your remote server has drush installed?
Answer: My alias file was the problem:
<?php
$aliases['devyau'] = array(
'uri'=> 'dev.[sitename]',
'root'=> '/var/www/vhosts/dev.[sitename]/',
'db-url' => 'mysql://[username]:[password]/devDBname',
  );
?>

My alias file apparently didn't have enough data to function.
See my previous question at:
    drush sql-sync fails
burnsjeremy provided this model alias file, which answered my question and allowed me to use Drush again! Thanks!
$remote_sites = '/path/to/site'; // usually /var/www/drupal-root-name
$aliases['site.dev'] = array(
 'uri' => 'sitename.com',
 'remote-host' => '{ip to remote}',
 'remote-user' => '{remote ssh user}',
 'root' => $remote_sites,
 'ssh-options' => '-p {if you ssh in on another port like 2222}',
 'path-aliases' => array(
 '%drush-script' => '/root/.composer/vendor/bin/drush', // This is so you can
 have multiple drush installs and use different ones on different sites.
 'php'=> '/usr/local/bin/php', // Again if you have different php's for
 different sites.
 '%site' => 'sites/default/', // This is the important part here, it will
 ensure the proper bootstrap
 '%dump-dir' => '/path/to/drush.dbdumps', // This is where you want to dump
 your databases, normally /tmp folder I think.
 '%files' => $remote_sites . '/files' // Your sites file folder, incase it is
 somewhere else.
),
// You may actually need this, especially if you are running D7 since I
   haven't ever tested the db-url thing on D7 or above.
 'databases' => array (
   'default' => array (
    'default' => array (
     'driver' => 'mysql',
     'database' => '{db_name}',
     'username' => '{db_user}',
     'password' => '{db_pass}',
   ),
  ),
 ),
);


Eclipse Spring Boot need declare Maven dependency explicitly

Question: I have 2 development PCs, both have following specification:

Windows 10 1909 64 bit
Installed Oracle JDK 1.8.0_281-b09
Eclipse IDE for Java Developers 2020-12 (4.18.0)

The application under development is a Spring Boot project with following Maven file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.my_company.example</groupId>
    <artifactId>test</artifactId>
    <version>1.0.0</version>
    <packaging>pom</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <maven.compiler.target>${java.version}</maven.compiler.target>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.7.0</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.7</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.7</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4-rule-agent</artifactId>
            <version>2.0.7</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-javaagent</artifactId>
            <version>2.0.7</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <modules>
        <module>core</module>
        <module>module1</module>
        <module>module2</module>
    </modules>
</project>

When importing the project into Eclipse, one of development PC (called PC1) cannot build with following error:

On the other side PC (called PC2), the error does not happen, it can build and run successfully.
I checked both PCs, the Maven dependency still available:

To resolve the error, we added following dependency to POM.xml file:
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
</dependency>

However, I want to ask why in PC1, it is needed to explicitly add the dependency, while in PC2 it is not necessary?
Later,  I also build the JAR+WAR file from Eclipse (Run As > Maven Build... > select "package" in Goals field).
Then deploy the JAR+WAR file to Docker container (base image is tomcat:9.0.11-jre8).
The similar problem happen, the JAR file build from PC1 cannot run, while the JAR file build from PC2 still able to run. Error message:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.cfg.beanvalidation.IntegrationException: Error activating Bean Validation integration

I also think that the problem come from PC1 as above.
Could anyone help check if any possible cause for these problems?
Update
Based on answers from @M.Deinum and @OneCricketeer, I solved the problem.
In PC1, I installed JDK8, added to PATH.
The Eclipse IDE is downloaded from following link:
https://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/2021-03/R/eclipse-java-2021-03-R-win32-x86_64.zip

When check the Configuration, it still using the default Java 15 as follow:

So, the solution is to click Add... as in the above image, then select the installed JDK (C:\Program Files\Java\jdk1.8.0_291).
Update 2
This is feedback for @OneCricketeer.
Uninstalled JDK from computer, but Eclipse still able to run the Java project.
Comment: Let me guess, different java version one is using JDK9+ while the other has JDK8. JDK9+ removed jaxb from the JDK, while previously it was still part of the JDK.
Comment: @M.Deinum Your guest is correct, thank you.
On my PC1, installed JDK8 but the Eclipse still using the default Java 15 shipped inside the Eclipse ZIP file.
Comment: Last I checked, Eclipse doesn't come with any JDK
Comment: @OneCricketeer, please see my updated post. The Eclipse IDE (2021-03) actually come with the "built-in" JRE 15.
Comment: That's for running the IDE itself, though, a JRE cannot compile any projects
Comment: @OneCricketeer, please see my Updated2 in the post. I uninstalled JDK from computer, create a new Java project in Eclipse. It still able to run. I also checked that inside folder `D:\eclipse\plugins\org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_15.0.2.v20210201-0955\jre\bin`, the file `javac.exe` does exist.
Answer:
Installed Oracle JDK 1.8.0_281-b09

Few things

One of the computer isn't compiling the code with Java 8, otherwise jaxb would be available

Unless you're maintaining old code, you should be using Java 11 at a minimum

If you absolutely need Java 8, it's best to migrate to OpenJDK rather than Oracle's distribution

And if it's a brand new project, you can use any newer Java version, but worth pointing out that Spring Boot version should also be newer
Comment: Thank you for point out. Because I'm maintaining old code, so I still used Java 8


changing memory allocation of a kubernetes worker node

Question: My set up
I have one physical node K8s cluster where I taint master node so it can also act a worker. the node has Centos7 with total of 512 GB memory. I am limiting my experiments to one node cluster; once a solution is found, I  will test it on my small scale k8s cluster where master and worker services are on separate nodes.
What I am trying to do
I want k8s worker to use only 256GB of memory to begin with. later on with if a particular node condition is met I want to increase memory allocation for k8s worker to  (lets say) 400GB
Where I am right now with this

I reboot my machine and node is up with full 512 GB memory.
I use chmem -d <range> to offline 256 GB memory.  Now OS only sees 256 GB memory is available.
I follow steps from  kubeadm init  to kubectl taint  nodes --all node-role.kubernetes.io/master-
My single node K8s set is up and I can deploy upto 2 pods. each pod requests 100Gi and limited to 200Gi memory usage. Pod are executing sleep 100000. so there is no memory stress.
When I try to launch third pod; pod is stuck in pending state because scheduler detects that the only worker node its managing is out of allocatable memory resource.  This make sense. the third pod is simply stuck in pending state forever.
Now after some time; the node met the required condition; at this point I used chmem -e <range> to enable some memory and now OS sees 400GB.
At this point I want to make k8s worker aware of this memory resource capacity change so the third pod stuck in pending stage can be deployed.
This is where I need your help. how can I update memory resource capacity of a worker without restarting my k8s. If I restart the cluster, it can see 400GB memory; but it means I need to kill already running pods and killing already running pod is not acceptable.
Comment: Hello, please tell if you tried what Bernard Halas linked you in the comments i.e.: https://kubernetes.io/docs/tasks/administer-cluster/reserve-compute-resources/ ?
Answer: It's a long shot, but you can try to restart kubelet via systemctl restart kubelet. The containers should not be restarted this way and there's a hope that once restarted, it'll notice the increased memory configuration.
Comment: Thanks Bernard; restarting kubelet worked... everytime i online/offline memory, os memory maps and metrics were updated immediately, but in order for K8s to get these changes- i restarted kubelet and within few seconds it was reflected at K8s level as well. Pods/containers kept running as kubelet was getting restarted; which was a surprise; i was under impression that if i restart kubelet on a running worker; it would kill/restart all the pods.
Comment: I checked kubelet logs; it reflects change in memory capacity as I online/offline memory. but it has no impact on scheduling decision for third pod; it remains in pending stage. On the other side when I check `kubectl describe nodes` details  memory capacity remains unchanged and does not reflect changes due to memory/online/offline.  I also tried restarting kubelet as you suggested but no change in scheduling behavior or pod status
Comment: Hm, in the etcd there's likely the old information about the node memory size and the scheduler uses that when making decisions about scheduling new pods. Not sure yet how to force an update here. On a side-note: pls keep in mind that K8s treats pods as ephemeral and they will get killed over time eventually.
Comment: So unless the change you did takes effect in a few mins, there's another long shot: By modifying one of the memory reservation parameters for `kubelet`, you might be able to force a re-configuration of the node in the database. E.g. change the value for `system-reserved` and observe: https://kubernetes.io/docs/tasks/administer-cluster/reserve-compute-resources/
Comment: I see that you used `kubeadm` to provision your cluster but have you made any changes to the `kubelet` configuration?
Answer:
Please provide output of below command

kubectl describe nodes

Restarting kubelet with below command should work because kubelet recalculates the allocatable cpu and memory every time it starts

systemctl restart kubelet

Did you try removing and recreating the third pod after restarting kubelet ?
Comment: Thanks Sagar restarting kubelet worked... everytime i online/offline memory, os memory maps and metrics were updated immediately, but in order for K8s to get these changes- i restarted kubelet and within few seconds it was reflected at K8s level as well.  Pods/containers kept running as kubelet was getting restarted; which was a surprise; i was under impression that if i restart kubelet on a running worker; it would kill/restart all the pods.
Comment: kubelet system daemon calls the Container Runtime APIs to create Containers. So actually it is the container runtime like Docker, Containerd, etc. that is running the containers. So, you can restart kubelet system daemon anytime without fear of containers getting restarted. But if due to some reason, kubelet daemon does not start and it is down for long time, then Kubernetes things that node is down and Kubernetes evicts Pods from the Node which causes Deployment/ReplicaSet to start the pods on other nodes. In this case, you will have over capacity problem.


"Maximum call stack size exceeded" Correct method but not efficient enough? Codewars Kata "Stop the Zombie Apocalypse!"

Question: I am attempting to solve this kata- https://www.codewars.com/kata/stop-the-zombie-apocalypse/train/javascript
I think I have a method that should work, but is too slow/inefficient and I am getting the error "Maximum call stack size exceeded". I would greatly appreciate all responses as dumbed down as possible as I am new to this. If you could point me in the direction of a different way of doing this, or somehow tweaking my method preferably.

function findZombies(matrix) {
    var n = matrix.length;
    var value = 0;
    //create 2 new arrays with 2 extras row and columns
    var arr1 = [...Array(n + 2)].map(e => Array(n + 2).fill(value));
    var arr2 = [...Array(n + 2)].map(e => Array(n + 2).fill(value));

    //change arr1 so that all infected numbers = 2, everything else = 0
    //leaving first and last rows and columns blank
    for (var i = 0; i < n; i++) {
        for (var j = 0; j < n; j++) {
            if (matrix[i][j] == matrix[0][0]) {
                arr1[i + 1][j + 1] = 2;
            }
        }
    }
    //if element in arr1 has a link back to arr[1][1] call the function recursively until there is no link
    //Then return arr2 with changed elements.
    function recur(arr1, arr2, i, j) {
        if (arr1[i][j] == 2 && arr1[i][j] == arr1[i + 1][j]) {
            arr2[i][j] = 1;
            recur(arr1, arr2, (i + 1), j)
        }
        if (arr1[i][j] == 2 && arr1[i][j] == arr1[i][j + 1]) {
            arr2[i][j] = 1;
            recur(arr1, arr2, i, (j + 1))
        }
        if (arr1[i][j] == 2 && arr1[i][j] == arr1[i - 1][j]) {
            arr2[i][j] = 1;
            recur(arr1, arr2, (i - 1), j)
        }
        if (arr1[i][j] == 2 && arr1[i][j] == arr1[i][j - 1]) {
            arr2[i][j] = 1;
            recur(arr1, arr2, i, (j - 1))
        } else {
            return arr2;
            console.log(arr2)
        }
    }

    recur(arr1, arr2, 1, 1);

    //clean up array by removing empty outside rows and columns
    arr2.shift();
    arr2.pop();
    for (var i = 0; i < n; i++) {
        arr2[i].shift();
        arr2[i].pop()
    }
    console.log(arr2);
}

var matrix = [
    [9, 1, 2],
    [9, 9, 9],
    [7, 4, 9],
    [7, 9, 7]
];

var matrix2 = [
    [8, 2, 3, 8, 8],
    [8, 0, 8, 8, 8],
    [1, 2, 8, 4, 8],
    [8, 2, 3, 8, 8],
    [8, 8, 8, 0, 5]
];

findZombies(matrix)
Comment: That error means that your recursive function is calling itself endlessly.
Answer: You could store all valid points (zombies) in a nested hash table with the all zombies and their adjacent zombies.
At the end start with the known zombie at [0][0] and take the array of the ahsh table to visit all connected field. For preventing visiting already visited items, replace the array with undefined.

function findZombies(matrix) {
    function go([i, j]) {
        if (!tree[i] || !tree[i][j]) return;
        result[i][j] = 1;
        var temp = tree[i][j];
        tree[i][j] = undefined;
        temp.forEach(go);
    }

    var i, j,
        result = [],
        zombie = matrix[0][0],
        tree = {};

    for (i = 0; i < matrix.length; i++) {
        result.push([]);
        for (j = 0; j < matrix[i].length; j++) {
            result[i].push(0);
            if (matrix[i][j] !== zombie) continue;
            if (!tree[i]) tree[i] = {};
            tree[i][j] = [[i, j - 1], [i, j + 1], [i - 1, j], [i + 1, j]].filter(([x, y]) => matrix[x] && matrix[x][y] === zombie);
        }
    }

    go([0, 0]);

    return result;
}

var matrix = [[9, 1, 2, 3, 4, 1, 2, 9], [9, 9, 9, 2, 1, 5, 9, 9], [9, 2, 9, 3, 7, 9, 1, 9], [6, 9, 9, 9, 0, 9, 2, 9], [5, 4, 3, 9, 9, 9, 4, 9], [9, 3, 9, 5, 8, 9, 9, 9], [9, 9, 9, 9, 9, 9, 7, 9], [9, 9, 1, 2, 3, 9, 8, 9]],
    result = findZombies(matrix);

result.forEach(a => console.log(...a));
.as-console-wrapper { max-height: 100% !important; top: 0; }

"Maximum call stack size exceeded" Correct method but not efficient enough? Codewars Kata “Stop the Zombie Apocalypse!”


Code Igniter support for NetBeans 8.0 (OS - Ubuntu 14.04)

Question: I want to use CI on my Netbeans IDE 8.0 installed on an Ubuntu 14.04. I searched a lot but all methods I found were for earlier versions of Netbeans.  How can I install CI on NetBeans 8.0?
Answer: Please try this.
http://mansoorin.wordpress.com/2013/05/21/netbeans-7-2-netbeans-7-3-autocomplete-for-ci-2/
Its working in Netbeans8 in Windows8. I'm using it.
Comment: @user2552922 Sorry I didn't understand.
Comment: is there any difference between autocompete feature and using a plugin for CI?


Dell Perc5/E and Poweredge 1950 PCI-X

Question: Today I have been to my datacenter and could not put Perc5/E into PCI-X card, there is like 0,5mm difference in card length, so physically it does not fit.
Do I need PCIe for this Perc?
Btw. when removed PCI-X, the system did not want to boot due to missing card, both cards have to be installed, is it the same with PCIe? So I have to buy only a pair?
Thanks for your advices :)
Answer: The Per5/E is a PCIe card.  You need the correct slot open to install the card.  I believe the Perc5/i is the PCI-X "equivalent".

Dell Perc5/E and Poweredge 1950 PCI-X


Sharepoint Reporting Services on Intranet Farm

Question: We have a Intranet Farm with two load balanced front end servers and a separate database, Report server is installed on box 1, so enysys data extenstions can access the sharepoint DOM.
IIS-BOX 1 + Report Server
IIS_BOX 2
SQL Server
The problem is RS fails if the user is accessing box 2, through the load balancer. If we remove Box 2 from the LB - then RS works. Put it back and it intermittently fails.
Anybody got any idea if this topology should work and how to resolve the problem?
Comment: I working this problem through - we think it is caused by RS integrated mode not working with NTLM authorization. Box 2 cannot connect to the RS on behalf of the user. Switching to Negotiate and ensuring Kerberos Authorization can take place should solve this.
Answer: We needed to configure the iis server to use Kerberos Authentication
see this question for more details
Answer: On Box 2 are you trying to access reports that are local or load them remotely from box 1? If you are accessing them remotely from Box 1 how are you referencing it?
Also does Reporting Services work on Box 1 when accessed from the load balancer?


move each div into the one previous to it

Question: I'm unsure if this is classed as a child and parent div.

content

content

content

content

My CMS is putting the footer outside the post container, for each .footer I would like to move them into the closest previous .container. I hope this makes sense.

content 2

content 2

My poor attempt looks like this:
    $(".container").each(function() {
    $(".project_footer ")
        .appendTo(".container");
});

Answer: try .prev() assuming that the footer always comes after the container:
$(".footer").each(function() {
    var currentFooter = $(this)
    currentFooter.appendTo(currentFooter.prev());
});

here's the demo
Comment: Bingo! I didn't know about .prev() Thanks @Joseph
Comment: well, if you can "translate the code into a sentence", there's a jQuery function bound to exist somewhere with that function.
Answer: try:
$(".footer").each(function() {
    currentFooter.appendTo($(this).prev());
});


Consultar inserções no banco de dados em tempo real

Question: Existe uma tabela no Mysql que sofre muitas inserções.
A aplicação precisa mostrar essas alterações para o cliente.
Atualmente a aplicação existente consulta, a cada 10 segundos, a tabela e mostra na tela o conteúdo dela.
Existe alguma forma que o próprio banco informa quando houver alterações na tabela? Ou existe uma forma de melhorar esse tipo de cenário?
A problemática é o loop infinito que o jquery fica, mandando a cada 10 segundos um post para capturar as informações no banco.
Answer: Também estou com esse problema, então durante algumas pesquisas encontrei uma funcionalidade chamada Triggers(Gatilho) no MySql.
A minha ideia é criar uma outra tabela com um Trigger que registre a alteração(tabela_atualizacao), onde ela tem seu campo(atualizacao tipo int) alterado sempre que houver algum UPDATE, DELETE ou INSERT.
Assim trazer as informações somente quando esse campo int for diferente e não sempre que mandar o $.post.
Sei que tem técnicas bem melhores mas estou deixando apenas uma opção ;).
Comment: Cogitou Long Polling ?
Comment: Estou dando uma estudada, nunca havia visto.
Comment: E WebSocket, já leu a respeito?
Comment: Acabei de encontrar isso tambem, mas onde trabalho se usa asp classico :( to achando que não funciona.
Comment: Li uma resposta aqui no stack, onde é mencionado que o Long Polling é uma boa idéia, no entanto ainda pode gerar uma sobrecarga de recursos pq vai contra ao seu propósito de criação. Menciona-se então que o WebSocket é a verdadeira solução... https://pt.stackoverflow.com/questions/254506/o-que-%C3%A9-long-polling


Trying TDD with PHPUnit

Question: I'm trying out the built in test driven development method in Drupal 8 but I'm running in to a problem..
I'm getting the following errors when trying to run ./core/vendor/bin/phpunit --list-groups ./modules/ in my cli:

PHP Fatal error:  Class 'Drupal\Tests\UnitTestCase' not found in
      /Applications/MAMP/htdocs/drupal/modules/custom_cookie_compliance/
      tests/CustomCookieComplianceTest.php on line 10
Fatal error: Class 'Drupal\Tests\UnitTestCase' not found in
      /Applications/MAMP/htdocs/drupal/modules/custom_cookie_compliance/tests/
      CustomCookieComplianceTest.php on line 10

I have created a module folder called custom_cookie_compliance in my modules folder. In turn I have a custom_cookie_compliance.info.yml file containing the following.
 name: Custom Cookie Compliance
 description: Displays a cookie compliance information window at the top of the website.
 core: 8.x
 type: module

I also have a tests folder containing a src folder which then contains a CustomCookieComplianceTest.php file with the following code.
<?php
namespace Drupal\custom_cookie_compliance\Tests;

use Drupal\Tests\UnitTestCase;

/**
 * @group cookie
 */

class CustomCookieComplianceTest extends UnitTestCase {
  public function testSetCookies() {
    if (!isset($cookie_set)) {
      $cookie_set = TRUE;
    }

    $this->assertTrue($cookie_set);
  }
}

I have written the code by following this guide.
I understand it can't find the UnitTestCase class, but the guide says that is should work, so why isn't it?
Answer: My guess is that you're not including the phpunit.xml.dist file, which sits in the core folder.
Either run tests from there (./vendor/bin/phpunit ../modules/your_module) or specify that file with -c.
You can also provide your own phpunit.xml.dist file (see the Payment module as an example); then you can run PHPUnit from your module folder.
Comment: Thanks a bunch. This fixed my issue. For those looking at this, I ran this command from CLI: vendor/bin/phpunit -c web/core/phpunit.xml.dist web/modules/custom
Answer: I ran into the same issue today and noticed that I was using an older version of PHP Unit. After upgrading to the latest, the tests worked.

Trying TDD with PHPUnit


UITableView cell text is not showing xml data in iPhone application development

Question: I am newer in iPhone application development. I want to find out why tableview cell is not showing data. I tried a lot of ways. I am giving my code below.
Note that I am seeing data at my console which is coming from XML file but it's not displaying in UITableView cell.

    @synthesize newsTable;
    @synthesize  activityIndicator;
    @synthesize rssParser;
    @synthesize  stories;
    @synthesize  item;
    @synthesize  currentElement;
    @synthesize  currentTitle, currentDate, currentSummary, currentLink;

    // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    /*
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization.
        }
        return self;
    }
    */

    #pragma mark -
    #pragma mark Parsing

    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad {
        [super viewDidLoad];
    }

    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        if ([stories count] == 0) {
            NSString * path = @"http://icms7.bitmascot.com:8080/webcommander2.0S2/rest/services/catalogue/getAllDummyCategoryProduct";
            [self parseXMLFileAtURL:path];
        }
        cellSize = CGSizeMake([newsTable bounds].size.width, 60);
    }

    - (void)parseXMLFileAtURL:(NSString *)URL
    {
        stories = [[NSMutableArray alloc] init];
        //you must then convert the path to a proper NSURL or it won't work
        NSURL *xmlURL = [NSURL URLWithString:URL];
        // here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
        // this may be necessary only for the toolchain
        rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
        // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
        [rssParser setDelegate:self];
        // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
        [rssParser setShouldProcessNamespaces:NO];
        [rssParser setShouldReportNamespacePrefixes:NO];
        [rssParser setShouldResolveExternalEntities:NO];
        [rssParser parse];
    }

    - (void)parserDidStartDocument:(NSXMLParser *)parser
        {
            NSLog(@"found file and started parsing");
        }
    - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
        {
            NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
            NSLog(@"error parsing XML: %@", errorString);
            UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [errorAlert show];
        }
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
        NSLog(@"found this element: %@", elementName);
        currentElement = [elementName copy];
        if ([elementName isEqualToString:@"ProductData"])
        {
            // clear out our story item caches...
            item = [[NSMutableDictionary alloc] init];
            currentTitle = [[NSMutableString alloc] init];
            currentDate = [[NSMutableString alloc] init];
            currentSummary = [[NSMutableString alloc] init];
            currentLink = [[NSMutableString alloc] init];
        }
    }
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
        //NSLog(@"ended element: %@", elementName);
        if ([elementName isEqualToString:@"ProductData"])
            { // save values to an item, then store that item into the array...
                [item setObject:currentTitle forKey:@"id"];
                [item setObject:currentLink forKey:@"productNumber"];
                [item setObject:currentSummary forKey:@"name"];
                [item setObject:currentDate forKey:@"dateCreated"];
                [stories addObject:[item copy]];
                NSLog(@"adding story: %@", currentTitle);
            }
    }
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
        NSLog(@"found characters: %@", string);
        // save the characters for the current item...
        if ([currentElement isEqualToString:@"ProductData"])
            {
                [currentTitle appendString:string];
            }
        else if ([currentElement isEqualToString:@"id"])
            {
                [currentLink appendString:string];
            }
        else if ([currentElement isEqualToString:@"ProductNumber"])
        {
            [currentSummary appendString:string];
        }
        else if ([currentElement isEqualToString:@"dateCreatrd"])
        {
            [currentDate appendString:string];
        }
    }
    - (void)parserDidEndDocument:(NSXMLParser *)parser {
        [activityIndicator stopAnimating];
        [activityIndicator removeFromSuperview];
        NSLog(@"all done!");
        NSLog(@"stories array has %d items", [stories count]);
        NSLog(@"data in stories: %@",[stories description]);
        [newsTable reloadData];
    }

    #pragma mark tableView

    - (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
    {
        return [stories count];
    }

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
    {
        return 1;
    }

    - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *MyIdentifier = @"MyIdentifier";
        UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:MyIdentifier];
        if (cell == nil)
        {

            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: MyIdentifier];

        }

        // Set up the cell
        int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
        //[cell setText:[[stories objectAtIndex: storyIndex] objectForKey: @"title"]];
        //[cell setLabelText:[[stories objectAtIndex:storyIndex] objectForKey: @"ProductData"]];
        //[cell setText:[stories objectAtIndex:storyIndex]];
        cell.textLabel.text = [stories objectAtIndex:storyIndex];
        NSLog(@"%@ ",cell.textLabel.text);

        //cell.detailTextLabel.text = [stories objectAtIndex:indexPath.row];

        return cell;
    }

    /*
    - (void)setLabelText:(NSString *)_text{
        UILabel *cellText;
        cellText.text= _text;
        [cellText sizeToFit];
    }
    */
    /*
    // Override to allow orientations other than the default portrait orientation.
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
        // Return YES for supported orientations.
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }
    */

    - (void)didReceiveMemoryWarning {
        // Releases the view if it doesn't have a superview.
        [super didReceiveMemoryWarning];

        // Release any cached data, images, etc. that aren't in use.
    }

    - (void)viewDidUnload {
        [super viewDidUnload];
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
    }

    - (void)dealloc {
            [currentElement release];
            [rssParser release];
            [stories release];
            [item release];
            [currentTitle release];
            [currentDate release];
            [currentSummary release];
            [currentLink release];
            [super dealloc];
        }

    @end

Answer: Try to set value of property textLabel, not detailedTextLabel :
cell.textLabel.text = [[stories objectAtIndex:storyIndex] valueForKey:@"productNumber"];

Also try to create cell using predefined styles:
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: MyIdentifier];

Comment: sorry bro now app is crashing.
Comment: Sorry little mistake app is not crashing...app is being unable to retrieve data from xml file                                      [Session started at 2011-10-06 12:25:03 +0600.]
2011-10-06 12:26:05.897 cmsCommander[1689:207] error parsing XML: Unable to download story feed from web site (Error code 5 )
Comment: `cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];` i am using this for making cell and `int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];` using this for indexPath and `cell.detailTextLabel.text = [stories objectAtIndex:storyIndex];
 NSLog(@"%@ ",cell.detailTextLabel.text);` using this for celltext now app can download the value and can display in the console but cell is being empty and one more thing at that time `NSLog(@"%@ ",cell.detailTextLabel.text);` printing `null` at console.
Comment: Crashing.....2011-10-06 12:54:39.111 cmsCommander[1859:207] -[__NSCFDictionary isEqualToString:]: unrecognized selector sent to instance 0x4b2afd0
2011-10-06 12:54:39.114 cmsCommander[1859:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary isEqualToString:]: unrecognized selector sent to instance 0x4b2afd0'
Comment: i have updated my above code.now please anyhow solve it,its really urgent...thank you for helping
Comment: I don't see any changes.. replace `cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];` with `cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: MyIdentifier];`
Comment: i have changed the code again now tell me..i have run the code again and again...continuosly its crashing.
Comment: Does `NSLog(@"%@ ",cell.textLabel.text);` printing something?
Comment: I've found the problem: replace `cell.textLabel.text = [stories objectAtIndex:storyIndex];` with `cell.textLabel.text = [[stories objectAtIndex:storyIndex] valueForKey:@"productNumber"];`
Comment: sorry bro `NSLog(@"%@ ",cell.textLabel.text);` does not printing anything.before that app is crashing.
Comment: Have your looked at my previous comment?
Comment: dont be angry bro...still now its not woking using your previous comment.now app is not crashing but it's becoming unable to retrieve data not only in tableview but also in console. and showing that 2011-10-06 13:28:53.195 cmsCommander[2215:207] error parsing XML: Unable to download story feed from web site (Error code 5 )
Comment: but NOTE THAT: when i am using previous cell making sys then data is being retrieve and displaying.
Answer: cell.detailTextLabel.text = [stories objectAtIndex:storyIndex];

replace above statement with belo wstatement iy will work i think
 cell.detailTextLabel.text = [stories objectAtIndex:indexPath.row];

Comment: change  UITableViewCell initialization as Nekto said
Comment: Sorry now app is crashing using Nekto's solution.
Comment: your cellForRowAtIndexPath calling or not
Comment: so problem with you cellForRowAtIndexPath code but if you want detailTextLabel you should initialize table as said  Nekto. k
Answer: Instead of giving,
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
//[cell setText:[[stories objectAtIndex: storyIndex] objectForKey: @"title"]];
//[cell setLabelText:[[stories objectAtIndex:storyIndex] objectForKey: @"ProductData"]];
//[cell setText:[stories objectAtIndex:storyIndex]];
cell.detailTextLabel.text = [stories objectAtIndex:storyIndex];

try this code:
cell.detailTextLabel.text = [stories objectAtIndex:indexPath.row];

before that ,just check your array(stories)having content?
Thank You..
Comment: At first thanks for response.i tried your solution but still now its not working and i have checked stories has content which i can see in console.but its not displaying in cell
Answer: To make a cell you should use
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

method. By default the detailTextLabel is not visible in the cell.
Try to use other styles - UITableViewCellStyleValue1, for example.


The classification of possible singular supports

Question: I need to find the solutions of $D_{x_1}u=0$ on $\mathbb{R}^{n}$ and to classify the possible singular supports.
Any one have an idea how to solve this kind of question?
Thanks!
Answer: The equation says that $u$ kills all test functions $\varphi$ such that $\varphi=\psi_{x_1}$ for some other test function $\psi$. So, the first step is to observe that

$\varphi=\psi_{x_1}$ for some $\psi$ if and only if the integral of $\varphi$ over every line in $x_1$ direction is zero.

To move this further, introduce the operator $I:\mathcal D(\mathbb R^n)\to\mathcal D(\mathbb R^{n-1})$ which sends $\varphi$ to $\int \varphi\,dx_1$. We just saw that $u$ vanishes on the kernel of $I$. Therefore, $u$ factors through $I$: namely, $u=v\circ I$ for some $v\in\mathcal D'(\mathbb R^{n-1})$. This is a characterization of the solutions of $u_{x_1}=0$.
The singular support of $v$ above can be any closed set   $A\subset \mathbb R^{n-1}$. The singular support of $u$ is $\mathbb R\times A$.


Em qual linguagem de programação um crawler/scrapper varre a DOM com mais rapidez?

Question: Eu desenvolvi um script no qual eu utilizo a classe DOMDocument do PHP para fazer um crawler em um site de terceiro.
A velocidade do script não atende ao objetivo esperado, gostaria de saber em qual linguagem de programação um script para a mesma finalidade me trará um resultado de varredura da DOM com mais velocidade?
Answer: Linguagens de programação não possuem velocidade como característica. Algumas possuem características que ajudam ter mais velocidade. Bibliotecas já podem ter velocidade, mas a padrão não precisa ser usada. Se a padrão não atende os requisitos de performance, raro, bem raro, então procure outra biblioteca.
O que mais dá velocidade é usar a estrutura de dados certa e o algoritmo certo. A diferença entre a escolha certa e a errada pode ser de demorar menos de 1 segundo para fazer ou levar séculos. Tem casos que é nessa proporção, e não são poucos.
Escolher uma linguagem mais rápida pode fazer algo que leve 1 minuto levar menos de 1 segundo, não mais que isto, e em poucos casos dá tanta diferença. E estamos falando de linguagens com diferenças gritantes, por exemplo uma das piores implementações de Ruby comparando com Assembly muito bem escrito.
Assembly é a linguagem que permite a melhor performance possível. Mas na prática hoje é tão difícil escrever um código correto e rápido em Assembly que quase sempre um escrito em C será mais rápido. Em alguns casos em C++, ou Rust, ou Fortran pode ser melhor. Mas em Delphi, Java e C#, só para citar algumas, a maioria das tarefas serão executadas com mínima diferença para estas linguagens e mesmo nas que elas são ruins a diferença é dela levar uns 3 segundos onde em C levaria menos de 1 (quase tudo a diferença é muito inferior, muito mesmo, chega ser quase irrisório).
Se quiser manter-se em linguagens de script então JavaScript (quem sabe Typescript) e Lua, principalmente no dialeto LuaJIT, devem ser as melhores opções.
PHP não tem uma performance tão ruim assim, principalmente nas versões mais novas.
Mas se não dominar bem a linguagem, a programação e os conceitos descritos acima, o resultado não será bom.
A maioria das aplicações não precisam de tanta performance quanto as pessoas acham, as que precisam geralmente exigem um trabalho de engenharia árduo e complexo. Então se é possível ter um grande ganho de performance mudando algo é porque o original estava muito errado (mas funcionando, o que faz as pessoas acharem que estava certo).
Se fizer direitinho é provável que o gargalo seja trazer as informações pela rede, mesmo em "linguagens lentas".
É possível ver uma comparação das linguagens. Mas preste atenção que isto é chamado de "jogo", não é um método científico. Se usar isto para tomar decisões importantes pode quebrar a cara.
Comment: Pessoalmente aconselho python por simplicidade e resultados satisfatórios. Há dias fiz um script em PHP, não sei se pode chamar um web crawler, foi mais um page fetcher e a velocidade ficou um bocado aquem. Porém, ja havia feito um bot em python para imagens do imgur e fiquei impressionado com a velocidade da linguagem. Mas no fundo o que conta é a implementação do algoritmo e a velocidade/frequência dos seus pedidos.
Comment: @lazyFox embora a implementação padrão de PHP costume ser bem mais rápido que a implementação padrão de Python na maioria das tarefas. Só confio em comparações que eu vi o fonte do código das linguagens, os dados usados e outras informações para ver o quanto são comparáveis.
Comment: C#, mas eu sou suspeito :) Ainda que seja mesmo.
Comment: Resumindo: A performance é uma característica da *implementação*, não do *modelo*. (mas alguns modelos privilegiam implementações mais performáticas, evidentemente).
Comment: Obrigado pela resposta, entendi que o segredo é "limar" o algoritmo.
Comment: Agora na opinião de vocês, para essa finalidade e visando a performance seria melhor utilizar: PHP, Phyton, Node.js, C# ? @Maniero
Comment: @Gabriel exato.
Comment: @CharlesFay - Quanto ao seu último comentário: Eu já estive envolvido com projetos de mineração de dados onde eu tive que criar vários crawlers para coletar dados da internet, então tive a oportunidade de testar vários ambientes e bibliotecas. A linguagem mais rápida que encontrei foi Go (e o aproveitamento de memoria de Go é absurdamente incrível). No entanto, minha linguagem preferida para isso foi Python, pois a performance é **suficiente** e o código é muito sucinto e flexível, além de haver uma variedade muito grande de ferramentas para web scraping.


In which file we add dependencies in gradle? Like while using maven we can add dependencies in pom.xml

Question: I have this code:
import org.springframework.web.bind.annotation.RequestMapping;@RequestMapping("/login")

After importing this, I get the error

cannot resolve symbol requestMapping

I am not able to resolve this.
Could anybody suggest a solution?
Comment: Check whether the symbol `requestMapping` is defined in the scope where the error occured.
Answer: add dependencies in build.gradle file.
dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}


What do these extra solutions mean?

Question: I'm trying to find a constant $a$ such that $n(n+1)(n+2)(n+3)$ is equivalent to $(n^2+an)(n^2+an+2)$.
Clearly by inspection, we have $a=3$. However, say I wish to substitute $n=-1$. We get our desired solution, but we also have another value $a=-1$.
My question is, what does this extra value mean, and why does it appear there?
Answer: $a = -1$ satisfies the equation only if $n = -1$. It does not hold true for all values of $n$. On the other hand, $a = 3$ satisfies the equation for all values of $n$.
You can write an equation which expresses $a$ in terms of $n$ (I do not know how hard this will be). This equation will allow you to determine the values of $a$ which will "work" for each corresponding value of $n$.
However the solutions of $a$ for a particular value of $n$ may not work for all other values of $n$. Of course, $a = 3$ will always be a result inferable from the equation derived.
Comment: Of course $\frac{1}{x(x + 1)} = \frac{7}{x} - \frac{3}{x + 1}$ can also be true, but it holds only for some value(s) of $x$, namely $x = -\frac{3}{2}$.
Comment: A simple example would be, "find a constant $a$ such that $n$ is equivalent to $an$." Clearly $a=1$ is the (only) solution to _this_ problem, but the _equation_ $n=an$ has also other solutions when $n=0$.
Comment: Thanks for your answer.

In that case, why is it that substituting values works for computing partial fractions, whereas it doesn't work here?
Comment: @Trogdor The decomposition of partial fractions will always hold true regardless of the value that the variable takes. For example, $\frac{1}{x(x+1)} = \frac{1}{x} - \frac{1}{x + 1}$ is always true for all values of $x$ (of course, except for $x = 0$ and $-1$).
Answer: Solving $$n(n+1)(n+2)(n+3)=(n^2+an)(n^2+an+2)$$
for a yields
$$a=-2n-\frac{2}{n}-3$$
when $n\neq0$
Comment: Can you elaborate? The number $a$ should be a constant, independent of $n$.
Answer: Subtracting the first expression from the second and factoring gives $n(a-3)(na+2n^2+3n+2) = 0$.  Therefore, there are three solutions we should consider:
\begin{align*}
n &= 0\\
a &= 3\qquad\text{and} \\
a &= -(2n+3+2/n) \leftrightarrow n=\frac{-(3+a)\pm\sqrt{(a-1)(a+7)}}4
\end{align*}
Which of these three you want would depend on the precise wording of the problem.  If the problem asked for "all $a$ and $n$", you'd want all three, and a graph in the $an$-plane may be a nice addition to the solution (by the way, $n=-1$ gives $a=1$).  If the problem asked for "$a$ such that ... for all $n$", you'd want the second.  If the problem asked for "$n$ such that ... for all $a$", you'd want the first.  In this context, "is equivalent to" means "equals … for all [other variables]", so the problem could be written "find $a$ such that … equals … for all $n$", and the answer is $a=3$.

What do these extra solutions mean?


Add Attribute to Textfields in Admin Theme

Question: I'm often working with Pages in RTL Languages where the default Theme and also the admin theme are using RTL languages.
What often bothers me, is to use LTR texts like Tokens or Paths in Textfields, because the specialchars like / or [ are shifted.
To solve this, i would like to add the dir=auto attribute to all Textfields in admin Theme.
So the textfields should look like this:

< input type="text" id="edit-file-public-path" name="file_public_path" value="sites/default/files" size="60" maxlength="255" class="form-text" dir="auto">

My idea was to create a Subtheme of Seven and use the template_preprocess_field function to add the dir attribute to all fields.
My issue is, that my Preprocess function is never called.
Are the preprocess functions called in admin Theme? And is there an another way to do this?
myseven.info file:
name = My Seven
description = Admin theme based on seven admin Theme
package = Core
version = 1.0
core = 7.x
base theme = seven
stylesheets[all][] = css/myseven.css
settings[shortcut_module_link] = 1
regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[sidebar_first] = First sidebar
regions_hidden[] = sidebar_first

template.php Function
function myseven_preprocess_field(&$variables, $hook){
    dsm($variables);
    watchdog("Hello World!","The preprocess_field Works!"); //if this function is ever called there should be an entry in Reports
    }

Answer: template_preprocess_field is for field output themeing not input field themeing, you maybe looking for theme_textfield or hook_field_widget_form_alter