text:
Q: Problem VHDL process maintaing a signal modified I am writing a VHDL code of a simple counter which receives as an input a number and that is a time in ms, and a 50 MHz clock, for example if 200 is received it has to count 200 ms so 200* 50e3 cycles, then it has to give an output named Terminal_count_end that has to remain high until a new reset signal is given (which by the way is active when '0')
I created a testbench to test it and i discovered that Terminal_count_end becomes 1 but only for one period of the clock, then it returns to 0 forever.
I am a begginer in VHDL and I really don't know what's I am doing wrong so I thank in advance anyone who can help me with this code!
The code is:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity counter_start is
    generic (N : integer := 16);
    port    (enable,clearn, Clk : in std_logic;
            end_time_ms : in unsigned (7 downto 0);
            Terminal_count_end : out std_logic);
end counter_start;

architecture behavior of counter_start is

signal count : unsigned (N-1 downto 0);
signal cifra : unsigned (3 downto 0);
signal T_c : std_logic;
signal T_c_end : std_logic;

begin
    process(clk,clearn)
    begin
        if clearn = '0' then
            T_c <= '0';
            count <= (others => '0');
        elsif (Clk'event and clk = '1') then
            if  T_c = '1' then
                T_c <= '0';
                count <= (others => '0');
            elsif (enable = '1') then
                count <= count + 1;
                if count = to_unsigned(49999, N) then
                    T_c <= '1';
                end if;
            end if;
        end if;
    end process;
    cifra_process: process(clk,clearn)
    begin
        if clearn = '0' then
            cifra <= "0000";
            t_c_end <= '0';
        elsif clk'event and clk = '1' then
            if (T_c = '1') then
                cifra <= cifra + 1;
                if cifra = end_time_ms-1 then
                        cifra <= "0000";
                        T_c_end <= '1';
                end if;
            end if;
        end if;
    end process;
    terminal_count_end <= T_c_end;
end behavior;

A: cifra keeps advancing, and you are checking =.
FYI, using async clear is not good practice in modern FPGAs if that's your future target.


text:
Q: Only show dropdown menu on hovering the parent li I am trying to build a dropdown menu. My problem is that hovering the content also shows the dropdown menu. I am currently using this code:

/* actual dropdown menu */

#menu-hauptmenue {
  height: 45px;
}

.sub-menu {
  opacity: 0;
  background: #4d4d4d;
  display: block;
  z-index: 200;
  width: 250px;
  position: absolute;
  margin-top: 23px;
}

.sub-menu li {
  display: block;
  width: 250px;
  line-height: 2.7;
  padding: 10px 15px 10px 15px;
  z-index: 220;
  color: #fff;
  font-family: 'Roboto', sans-serif;
  font-size: 1em;
}

.sub-menu li a {
  color: #fff;
  font-family: 'Roboto', sans-serif;
  font-size: 1em;
  text-decoration: none;
}

.sub-menu li:hover {
  background-color: #333333;
  cursor: pointer;
}

.sub-menu a:hover {
  border-bottom: none;
}

#menu-hauptmenue li:hover .sub-menu {
  opacity: 1;
}

#billboard img {
  z-index: 1;
}

li {
  z-index: 20;
}

.clearfix:after {
  display: block;
  clear: both;
}

nav>ul>li {
  position: relative;
}

nav.open .sub-menu {
  padding-top: 0px;
  display: none;
}

/* styling of the nav */

nav ul {
  list-style: none;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

nav ul li {
  display: inline-block;
}

nav ul li a {
  color: #4D4D4D;
  font-family: 'Roboto', sans-serif;
  font-size: 1em;
  text-decoration: none;
}

nav ul li a:hover {
  border-bottom: 1px solid #4D4D4D;
}

Parent 1

Dropdown 1

Dropdown 2

Dropdown 3

Parent 2

Parent 3

As you can see, hovering the content below the navigation also displays the dropdown menu. It would be better to only display the navigation when hovering the parent li element, in this case 'Parent 1'. How can I achieve this the best way? Thank you for your advice.

A: It's because your element is present with 0 opacity so you are able to interact with it. You may try using display:none/block like this:

/* actual dropdown menu */

#menu-hauptmenue {
  height: 45px;
}

.sub-menu {
  opacity: 0;
  background: #4d4d4d;
  display: none;
  width: 250px;
  position: absolute;
  margin-top: 23px;
}

.sub-menu li {
  display: block;
  width: 250px;
  line-height: 2.7;
  padding: 10px 15px 10px 15px;
  z-index: 220;
  color: #fff;
  font-family: 'Roboto', sans-serif;
  font-size: 1em;
}

.sub-menu li a {
  color: #fff;
  font-family: 'Roboto', sans-serif;
  font-size: 1em;
  text-decoration: none;
}

.sub-menu li:hover {
  background-color: #333333;
  cursor: pointer;
}

.sub-menu a:hover {
  border-bottom: none;
}

#menu-hauptmenue li:hover .sub-menu {
  opacity: 1;
  display:block;
}

#billboard img {
  z-index: 1;
}

li {
  z-index: 20;
}

.clearfix:after {
  display: block;
  clear: both;
}

nav>ul>li {
  position: relative;
}

nav.open .sub-menu {
  padding-top: 0px;
  display: none;
}

/* styling of the nav */

nav ul {
  list-style: none;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

nav ul li {
  display: inline-block;
}

nav ul li a {
  color: #4D4D4D;
  font-family: 'Roboto', sans-serif;
  font-size: 1em;
  text-decoration: none;
}

nav ul li a:hover {
  border-bottom: 1px solid #4D4D4D;
}

Parent 1

Dropdown 1

Dropdown 2

Dropdown 3

Parent 2

Parent 3

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grouping and counting fields on a query in Access I've got a query like this (in Access 2016):

SELECT r01.Comuni, r01.Beneficiari, r02.Ricorsi, r03.[Ricorsi Urgenti],
r04.Istanze, r05.Rendiconti, r06.Consulenze, r07.Pratiche
FROM r07 RIGHT JOIN (r06 RIGHT JOIN (r05 RIGHT JOIN (r04 RIGHT JOIN (r03 RIGHT
JOIN (r02 RIGHT JOIN r01 ON r02.comune = r01.Comuni) ON r03.comune =
r01.Comuni) ON r04.comune = r01.Comuni) ON r05.comune = r01.Comuni) ON
r06.comune = r01.Comuni) ON r07.comune = r01.Comuni
ORDER BY r01.Comuni;

and this is what I get:

What I'd like to get is something like this:

Basically, I'd like to get:

*

*Comuni field picked once as unique

*Beneficiari field picked once if unique and summed whereas is different

*all other fields counted

Any idea?


text:
Q: LLVM::predecessors could return duplicate basic block pointers We used the predecessors() to get the predecessors of a basic block based on LLVM's IR. The code is like:
for (llvm::BasicBlock* pred_bb : predecessors(cur_bb)) {
   printf("prev_bb=%p\n", pred_bb);
}

However, we found that the predecessors() could return duplicate basic block pointers. The output of above code could be:
prev_bb=0x56407eaee190
prev_bb=0x56407eaee190
prev_bb=0x56407eaee190
prev_bb=0x56407eaee190
prev_bb=0x56407eaee190

If there exists better methods to get the predecessors of a basic block? Or we have to check the duplicate predecessors before usage?

A: This behaviour is known and desired (although I personally don't see it as overall desirable).
It happens for some switch statements and could happen for conditional branches too. Put briefly, there is one incoming entry in predecessors() for each outgoing target in switch/br, even if the targets are not unique.
If block baz ends with br i1 %bar, label %foo, label %foo, that is, a conditional branch that branches to block %foo in both cases, then that block has two predecessors, which you may think of as "block baz, outgoing condition false" and "block baz, outgoing condition true". If your code doesn't distinguish between outgoing conditions, this will not be what you want. But you can filter quite easily.


text:
Q: Web page renders, but crashes the server the first time, then renders without crashing the server subsequent times I am using NodeJS, Express, and Express-handlebars to render a webpage using data pulled from an SQLITE3 database.
The code works, and the page renders properly, but the first time it loads, it crashes my server with this error: TypeError: Cannot read property 'user_name_tag' of undefined
The error says it cannot read this property, but displays the information from it correctly before the server crashes. However, if restart the server and reload the page, it doesn't crash, it also doesn't crash if I open a new instance with a different user and different data set after the initial load.
Here's the index.js code:
const express = require('express');
const app = express();
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('../database.sqlite');
const exphbs = require('express-handlebars');
const hbs = exphbs.create({
    defaultLayout: 'main',
//custom helpers
    helpers: {
        iff: function(a, b, opts) {
            if (a == b) {
                return opts.fn(this);
            } else {
                return opts.inverse(this);
            }
        }
    }
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

app.get('/:userid', async (reg, res) => {
    const findUser = reg.params.userid;
    console.log('I am findUser ',findUser);
      let query = "SELECT users.user_id, users.balance, users.user_avatar, users.user_name_tag, user_collections.user_stamina, user_collections.collection_switch,";
      query += "COALESCE((SELECT SUM((SELECT (currency_shops.cost * user_items.amount) FROM currency_shops WHERE currency_shops.id = user_items.item_id)) FROM user_items WHERE user_items.user_id = users.user_id GROUP BY user_items.user_id), 0) as totalItems, ";
      query += "COALESCE((SELECT SUM((SELECT (craft_shops.cost * user_craft_items.amount) FROM craft_shops WHERE craft_shops.id = user_craft_items.item_id)) FROM user_craft_items WHERE user_craft_items.user_id = users.user_id GROUP BY user_craft_items.user_id), 0) as totalCraftItems, ";
      query += "COALESCE((SELECT SUM((SELECT (stonk_shops.cost * user_stonks.amount) FROM stonk_shops WHERE stonk_shops.id = user_stonks.item_id)) FROM user_stonks WHERE user_stonks.user_id = users.user_id GROUP BY user_stonks.user_id), 0) as totalStonks ";
      query += "FROM users, user_collections WHERE users.user_id = ? AND users.user_id = user_collections.user_id";
    await db.get(query, [findUser], (err, row ) => {
            (err, rows) => {
        };
                res.render('profile', {
                title: 'User Profile',
                user_name: ([row.user_name_tag]),
                user_id:([row.user_id]),
                user_balance:([row.balance]),
                user_avatar:('src','https://cdn.discordapp.com/avatars/' + [row.user_id] + '/' + [row.user_avatar] + '.png'),
                user_stamina:([row.user_stamina]),
                user_networth:([row.balance + row.totalItems + row.totalCraftItems + row.totalStonks]),
                collection_switch:([row.collection_switch]),
                isCollectionOn:([row.collection_switch]),
            })

   });

});
const PORT = process.env.PORT || 6999;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

Here is the HTML:

Welcome to your profile page {{user_name}} !

This is your ID number {{user_id}} .

This is your current credits balance {{user_balance}} .

This is your face!

This is your current stamina {{user_stamina}} .

This is your networth {{user_networth}}

{{#iff isCollectionOn 0}}

Your collection switch is set to {{collection_switch}}, you are free to collect!

{{else}}

This worked, congrats!

{{/iff}}

I hope this enough information, feel free to ask me to provide more if needed.

A: So I was using sublime and decided to switch to visual studio code. Visual studio codes linter answered my question. It told me my await was doing nothing and suggested deleting a redundant function I had in there for some unknown reason(probably leftovers of my trying different things). It was solved by changing this:
await db.get(query, [findUser], (err, row ) => {
            (err, rows) => {
        };
                res.render('profile', {

To this
    db.get(query, [findUser], (err, row ) => {
            res.render('profile', {

Also, I should note, it appears my favicon had something to do with some of the crashes I was getting. I found out that with Express, favicons are handled with middleware inside the index.js file rather than the html file.


text:
Q: Нужно отобразить цвета светофора через определенный период времени Смотрел на библиотеку datatime, но не знаю как это реализовать.
Из условий:

*

*все должно происходить в классе TrafficLight

*должен быть 1 метод running

*атрибут класса __сolor в котором будут цвета ("Красный", "Желтый", "Зеленый")

*они должны отображаться в консоли в промежутках времени ("Красный": через 7 секунд, "Желтый" через 2 секунды, "Зеленый" - через 7 секунд)

Попытка, но как отобразить их через время не понятно
class TrafficLight:

    def __init__(self, color):
        self._color = color

    def running(self):
        for key, value in self._color.items():
            print(key)

traf = TrafficLight(color={
    "Красный": 7,
    "Желтый": 2,
    "Зеленый": 7})
traf.running()

A: Если не вдаваться в подробности смысла задачи, то как пример можно реализовать вот так.
from time import sleep

class TrafficLight:
    def __init__(self, color):
        self._color = color
    def running(self):
        for key, value in self._color.items():
            sleep(value)
            print(key)

traf = TrafficLight(color={
    "Красный": 7,
    "Желтый": 2,
    "Зеленый": 7})
traf.running()

Оговорка вначале потому, что это работает не совсем логично для реального мира. Но задача решена согласно вашим условиям и с вашим же кодом в основе.


text:
Q: MongoDB Zone sharding limitations - tag ranges Mongo DB supports zoned sharding (as described here) by associating each shard with zone sh.addShardTag(<shard name>, "ZONENAME") and applying zone chunk ranges based on sharding key values with sh.addTagRange().
The questions are:

*

*Are there any limitations for sh.addTagRange()?

*Does the big number of such ranges affect performance anyhow?

*Is it OK to have for example 60000 tag ranges or they are designed to be dozens?
Can't find the answer in docs & community forums
to give more context on use case:
e.g. there are 10K accounts in system. There is sharded inventory collection. Each item is associated with inventoryClass (80K types). Each account creates huge number of inventory items (SKU) by different types. There are 3 zones in sharded cluster. Shard key is: {accountId: 1, inventoryClass: 1}.
Goal: to have zone distribution for particular list of accounts (home-zone defined for account manually). E.g. accounts
[1, 294, 906847 ...] -> zone "A",
[7879079, 852 ...] -> zone "B",
[3457, 45...] -> zone "C"

Inventory item document itself doesn't containt explicit value for zone mapping (only implicit relation accountId -> zone mapping). It means that each accontId data must be associated with zone by adding corresponding tag range with sh.addShardTag() e.g.
sh.addTagRange(
  "inventory",
  { "accountId" : 1, "inventoryClass" : MinKey },
  { "accountId" : 1, "inventoryClass" : MaxKey },
  "A")
....
sh.addTagRange(
  "inventory",
  { "accountId" : 294, "inventoryClass" : MinKey },
  { "accountId" : 294, "inventoryClass" : MaxKey },
  "A")

so that 1 tag range per 1 account. And it results in tag ranges == accounts count


text:
Q: How to use Huawei EC156 modem on 10.10? How to configure Tata Photon+ USB Modem Huawei EC156 on Ubuntu 10.10 Maverick Meerkat.
It is not getting detected in network manager nor in media. Is there any way out to configure and use internet with the modem on ubuntu 10.10 .

A: try this:
    sudo apt-get install usb-modeswitch

These sticks come with a ZeroCD setup. When you first plug it it, you only see it as a pendrive for windows drivers. But the kernel already has the drivers, but not the information, that it needs a switch. This package solves the problem.

A: i think there is no difference in 10.10
Configuring Tata Photon + USB Modem Huawei EC156


text:
Q: Is there a way to optimize citation order to reduce the number of superscript numbers in text? I want to know if there is a way to optimize the order my citations are in, such that they output the minimum number of numbers in the text.
So, if I have citations \cite{A,B,C} and later \cite{A,C,D} it will realize that if I had instead done \cite{B,A,C} and \cite{A,C,D} it would give a shorter output. That is, the first case one of these will have (1-3) and the second (1,3,4). But if they are reordered you would instead get (1-3) and (2-4).
Another example: \cite{A,B,C}, \cite{D,E,F}, \cite{A,D,F} could be optimized to \cite{B,C,A}, \cite{D,F,E}, \cite{A,D,F}. Which would go from (1-3), (4-6), (1,4,6) to (1-3), (4-6), (3-5).
Now that way only removes one number from displaying, but I regularly have 9+ citations inside each \cite{} command (i.e. \cite{Miro2012,Ling2010,Takao2010,Unruh2009,Goff2008,Kubatko2007,DeAquino2001,Rose1994,David1993}) so an optimization like this could change thing from (1,3,5,7,9,11,13,15,17) to (1-9) at an extreme (going from 22 characters to 3).
I don't have a way to do this outside of LaTeX. If I had to do it by hand I would first make a list of every group of citations with more then 3 citations that also occur earlier in the document. Then I would find if any of those occurred in the same citation block and put them next to one another, provided that doesn't make other blocks worse. Then I would find if any of the citations that occur in earlier blocks occur in adjacent blocks, and try and move those to the ends, if I could do so without messing up other blocks. This would not generate an optimized solution, but I suspect it would generate a better one. If doing this by computer, I would also do multiple trials of optimizing the blocks in different orders so that you don't have an early reordering preventing later ones.
Potentially you could do something with a badness score so that you could mess up one citation block if it made two others better, or one a LOT better?
Rewrite inspired by @JosephWright explained well in the comments:

I think the point here is that if one has several multiple citation,
  \cite{A,B,C}, \cite{A,D,E}, \cite{B,D,F}, there will be an optimal
  approach to the ordering in each argument which places as many as
  possible in continuous runs so reduces the output complexity. -Joseph Wright, May 14 '16 at 5:30
The optimisation might for example spot that if you have a first use
  \cite{A,B,C} and later \cite{B,D,E} then reordering the first case to
  \cite{A,C,B} will swap two refs and go from output 1---3 (A = 1, B =
  2, C = 3) and 2,4,5 (D = 4, E = 5), to 1--3 (A = 1, C = 2, B = 3) and
  3--5 (D = 4, E = 5). The point here is that the refs are all still in
  use order, but within sets used at one time the order is optimised to
  globally-minimise the number of numbers which need to be printed. –
  Joseph Wright May 14 '16 at 13:34

Original text:
Currently, within each citation block, I'm listing citations by date. So I'll have a command with something like:\cite{Miro2012,Ling2010,Takao2010,Unruh2009,Goff2008,Kubatko2007,DeAquino2001,Rose1994,David1993}
This works quite well, LaTeX does the order for me, and gives me an output like 14,19,62,70,71,75–78
That is pretty ugly and takes up a good inch of space. However, most of those are all referenced in the same citation block earlier in the paper. So really, if I'd cited them in order I'd get something more like 14,19,62-68 Given that most of my citation order is arbitrary within each citation (date) I'm wondering if there is a citation optimizer that goes through and tries to compress your later citation references as much as possible by reordering your earlier ones? Has anyone done something like this in LaTeX?
It would be better still if I could specify times not to do this (i.e. this citation must be first within this block, if it hasn't been cited already) or if it could work with `achemso' but I'm mostly curious if this is possible at all.
(MWE removed, as they didn't add anything except making it look like I was trying to do this with a specific citation package, when I am curious if it is possible to do this at all).


text:
Q: payfort Invalid extra parameters I am using the payfort Merchant page.
When I am making a token the request succeeds but when I tried to make a purchase I got  " Invalid extra parameters" code 00027
This the request of TOKENIZATION
Request Log
card_security_code  ***
card_number 523761******2016
service_command TOKENIZATION
signature   $signature
merchant_identifier ZDFytEce
merchant_reference  $merchant_ref
access_code $access_code
expiry_date ***
return_url  TOKEN_RETUEN_URL
language    en

Response Log
response_code   18000
card_number
signature   i have removed signature
merchant_identifier
expiry_date ***
access_code
language    en
response_message    Success
service_command TOKENIZATION
merchant_reference   i have removed it
token_name  E61B3D3066C611EAB1270AC1838006C8
return_url   i have removed it
status  18
card_bin     i have removed it

and this is the PURCHASE Request which fails
Request Log
amount  10000
signature   $signature
merchant_identifier $merhcanct
access_code $accees_code
customer_ip ::1
language    en
command PURCHASE
merchant_reference  $merchant_ref
customer_email  ahmed@email.com
token_name  1551899mwGbPzTwdbP3JAX9eCmENqu
return_url  PRUCHASE_RETURN
currency    EGP
customer_name   Ahmed

Response Log
amount  10000
response_code   00027
signature   i have removed it
merchant_identifier i have removed it
access_code i have removed it
customer_ip ::1
language    en
command PURCHASE
response_message    Invalid extra parameters   // error here
merchant_reference  11125-1584279525
customer_email  ahmed@email.com
currency    EGP
customer_name   Ahmed
status  00

A: It works now, it just was that curl was used to send the request and getting back the response, but it was disabled in my php.ini, so after adding the curl extension it worked out.


text:
Q: Eigenvalues and eigenvectors of $A^TA$ and $A$ For a square matrix $A$, I was wondering what the condition(s) are for the eigenvalues of $A^TA$ to be the same as the eigenvalues of $A$.
Also what are the condition(s) for the eigenvectors of $A^TA$ to be the same as the eigenvectors of $A$. It seems that if $A$ is symmetric, then the eigenvectors of $A$ are the same as the eigenvectors of $A^TA$ (as $A^T=A$ so $A^TA=A^2$ and the eigenvectors of $A^2$ are the same as the eigenvectors of $A$), but what are the general condition(s)?
Can anyone please help as I can't find an answer to this?

A: Assuming $A$ is a real matrix, using singular value decomposition we can write
$$ A = U S V^T$$
where $S$ is a real valued diagonal matrix (i.e., $S=S^T$); $U$ is the left Eigenvector and $V$ the right Eigenvector. Then, you can write
$$A^TA = V S^T U^T  U S V^T = VS^2V^T$$.
However, if $A$ is positive symmetric, then $U=V$ and you can use eigenvalue decomposition instead of singular value decomposition. i.e., $A = USU^T$


text:
Q: Doctrine entity form type onetomany relationship I have a user class that has a onetomany self-referencing relationship (ancestor and decendents). And I have an invoice class, which references two users based on the ancestor-decendents relationship. Meaning that, a user creates an invoice, so the form's "from" property will have the logged in user, while the form's "to" property should be a selection from the logged in user's decendets.
This is the invoice's buildForm method
public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('createdDate')
        ->add('from')
        ->add('to', 'entity', array('class' => 'Disty\SystemBundle\Entity\User'))
    ;
}

To keep it short, I want to somehow only show options of decendent users. Right now it shows all users registered.

A: You should take a look at the query_builder parameter that should do the trick.

A: If you look at the documentation you can find query_builder option of the entity form type. So you just need to modify query builder to retrieve only users which belong to the current logged in user.


text:
Q: Solving this nonlinear system (a localization problem) with gradient descent. I have the following algorithm designed to find the global minimum of the simple function $y=(x+5)^2$.
cur_x = 3                  # the algorithm starts at x=3
rate = 0.01                # learning rate
precision = 0.000001       # this tells us when to stop the algorithm
previous_step_size = 1
max_iters = 10000          # maximum number of iterations
iters = 0                  # iteration counter
df = lambda x: 2*(x+5)     # gradient of our function

while previous_step_size > precision and iters < max_iters:
    prev_x = cur_x                                # store current x value in prev_x
    cur_x = cur_x - rate * df(prev_x)             # grad descent
    previous_step_size = abs(cur_x - prev_x)      # change in x
    iters = iters+1                               # iteration count
    print("Iteration",iters,"\nX value is",cur_x) # print iterations

print("The local minimum occurs at", cur_x)

I'd now like to apply this to a localization problem, the Time Difference of Arrival problem, in 3-dimensions. That is, given the velocity $v$ of some signal, the coordinates $[x_i,y_i]$ of four observers (or, in general, $n+1$ observers for an $n$ dimensional solution), and the time of arrival at each observer, I want to reconstruct the coordinates $[x,y]$ of the signal source.
I've accomplished this in two dimensions using a slight variation of the approximation search algorithm found here: https://stackoverflow.com/questions/63707712/how-to-localize-a-signal-given-the-location-of-three-receivers-and-the-times-at/64318443#64318443. I'd now like to try doing so with gradient descent, although I'm not entirely sure how to apply it here (although I know it has been done).
I also know that the 2-dimensional solution can be described by the following nonlinear system:
$\sqrt{(x-x_1)^2+(y-y_1)^2}+s(t_2-t_1) = \sqrt{(x-x_2)^2 + (y-y_2)^2}$
$\sqrt{(x-x_2)^2+(y-y_2)^2}+s(t_3-t_2) = \sqrt{(x-x_3)^2 + (y-y_3)^2}$
$\sqrt{(x-x_3)^2+(y-y_3)^2}+s(t_1-t_3) = \sqrt{(x-x_1)^2 + (y-y_1)^2}$
How, precisely, might gradient descent be used to solve the problem in 3-dimensions?
I've had a look in the usual places (e.g., Wikipedia: https://en.wikipedia.org/wiki/Gradient_descent#Solution_of_a_non-linear_system), however I'm used to thinking of this "computationally" and I'm not familiar with the terminology/symbolism used there.

A: Having worked this problem, what I found is that it is much better to work with absolute times in order to decouple the equations.
In three dimensions, eash equation write as
$$f_i=\sqrt{(X-x_i)^2+(Y-y_i)^2+(Z-z_i)^2}-v(t_i-T)=0$$ and you need to minimize
$$\Phi(X,Y,Z,T)=\frac 12\sum_{i=1}^n f_i^2$$ which is extremely nonlinear; this means that you need "reasonable" estimates of the four variables $(X,Y,Z,T)$ before starting anything.
What I did is to consider in a preliminary step the equations
$$g_i=(X-x_i)^2+(Y-y_i)^2+(Z-z_i)^2-v^2(t_i-T)^2$$ and built the $\frac {n(n-1)}2$ equations $(g_j-g_i)$ ($i$ varying from $1$ to $(n-1)$ and $j$ from $(i+1)$ to $n$); they write
$$2 (x_j- x_i) X+2 (y_j- y_i) Y+2 (z_j- z_i) Z+2 v^2 (t_i-t_j)T=$$
$$(x_j^2+y_j^2+z_j^2-v^2 t_j^2)-(x_i^2+y_i^2+z_i^2-v^2 t_i^2)$$ This system is very easy to solve in the least-square sense using matrices. So, at this point, we have the estimates  for the four variables $(X,Y,Z,T)$.
Now, we need to minimize $\Phi(X,Y,Z,T)$. Writing the partial derivatives, we have to solve the four equations
$$\frac{\partial \Phi(X,Y,Z,T)} {\partial X}= \sum_{i=1}^n f_i \,\frac{\partial f_i} {\partial X}=0$$
$$\frac{\partial \Phi(X,Y,Z,T)} {\partial Y}= \sum_{i=1}^n f_i \,\frac{\partial f_i} {\partial Y}=0$$
$$\frac{\partial \Phi(X,Y,Z,T)} {\partial Z}= \sum_{i=1}^n f_i \,\frac{\partial f_i} {\partial Z}=0$$
$$\frac{\partial \Phi(X,Y,Z,T)} {\partial T}= \sum_{i=1}^n f_i \,\frac{\partial f_i} {\partial T}=0$$
with
$$\frac{\partial f_i} {\partial X}=\frac{X-x_i}{\sqrt{(X-x_i)^2+(Y-y_i)^2+(Z-z_i)^2}}$$
$$\frac{\partial f_i} {\partial Y}=\frac{Y-y_i}{\sqrt{(X-x_i)^2+(Y-y_i)^2+(Z-z_i)^2}}$$
$$\frac{\partial f_i} {\partial Z}=\frac{Z-z_i}{\sqrt{(X-x_i)^2+(Y-y_i)^2+(Z-z_i)^2}}$$
$$\frac{\partial f_i} {\partial T}=v$$ This system of equations is quite easy to solve with Newton-Raphson method.


text:
Q: System.FormatException On ConvertFromBase64String This is such a great place to ask questions!
I'm facing one problem.
I'm trying to send an image from an AutoIT client over to a server that is written in VB.NET
Here is the code for the AutoIT Client:
    TCPStartup()
$MainSocket = TCPConnect("127.0.0.1", 9832)

$PATH = _ScreenCapture_Capture("")
$Data2Send = "RemoteDESK|" & _Base64Encode(HBITMAP_To_Bytes($PATH)) & "<EOF>"
TCPSend($MainSocket, $Data2Send)

And here is the code for the VB.NET server:
Data handler:
Private Sub GotInfo(ByVal Data As String, ByVal Sender As Socket)
        Dim Cut() As String = Data.Split("|")
        Select Case Cut(0)
            Case "RemoteDESK"
                Dim ImgString As String = Cut(1)
                PictureBox1.Image = B64ToImage(ImgString)
        End Select
    End Sub

Base 64 String to Image Fucntion:
Private Function B64ToImage(ByVal B64 As String) As Image
        Dim ByAr() As Byte = Convert.FromBase64String(B64) 'Exception Happens here
        Dim img As Image
        Dim MS As New MemoryStream(ByAr)

        Try
            img = Image.FromStream(MS)
        Catch ex As Exception
            Return Nothing
        End Try

        Return img
    End Function

The OnReceive Sub:
 Private Sub OnReceive(ByVal ar As IAsyncResult)
        Dim Content As String = String.Empty
        Dim State As StateObject = DirectCast(ar.AsyncState, StateObject)
        Dim Handler As Socket = State._MySocket
        Try
            Dim BytesRead As Integer = Handler.EndReceive(ar)
            If BytesRead > 0 Then
                State._SB.Append(Encoding.ASCII.GetString(State.Data))
                Content = State._SB.ToString
                If Content.IndexOf("<EOF>") > -1 Then
                    Dim ReadContent As String = Content.Remove(Content.IndexOf("<EOF>"))
                    RaiseEvent GotInfo(ReadContent, State._MySocket)
                Else
                    Handler.BeginReceive(State.Data, 0, State.BufferSize, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), State)
                End If
            End If
        Catch ex As Exception
            RaiseEvent ClientDC(Handler)
        End Try

    End Sub

A: Alright, so now I used a text comparing tool, and every time on line 53, the received string has changed, as in the the 2 lines of text are on the same line compared to the autoit's output.
The autoit output is the readable one.


text:
Q: Figure as superscript in section title I would like to have a section title of special type: I need it to be a letter with a figure in superscript. My code (that does not work) would be:
\documentclass[12pt,a4paper]{article}
\usepackage[slovak]{babel}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{palatino,verbatim}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{float}

\begin{document}
\section{$\Sigma_1^{\includegraphics[scale=0.15]{example-image-a}}$}
\end{document}

Is it possible to do this?

A: You can either \protect the command from expanding via
\protect\includegraphics[..]{...}

or make it robust using something like etoolbox:

\documentclass{article}
\usepackage{graphicx,etoolbox}
\robustify{\includegraphics}
\begin{document}
\section{$\Sigma_1^{\includegraphics[scale=0.05]{example-image-a}}$}
\end{document}


text:
Q: How can I disable only specific errors in Eclipse/Geppetto? I am using Geppetto 2.1.2 build R201202021616, which is based off the Eclipse engine. I'm using the standalone install, rather than the Eclipse plugin version.
I have a few common warnings that show up in my puppet files, due to the module I am coding being part of a larger project that Geppetto is not aware of.
I would like to have it ignore certain warnings.
I've found how to disable all errors and warnings, and how to disable based on types such as "Xtext Check", but this doesn't quite cover what I want to do.
The two specific warnings I want to make it ignore are:

Hyphen '-' in name only unofficially supported in some puppet
  versions.

and

Unqualified and Unknown variable: '$<varname>'

Can this be done, and if so how? I've only been able to find info on disabling/ignoring much broader categories of warnings and errors.
Thank you.

A: Neither of those errors/markers are configurable by a user in Geppetto (2.2.0 is the current version). Suggest you log enhancement requests with the Geppetto issue tracker. (The checks that can be configured error/warning/ignore are found under Preferences/Puppet and these tabs are called Potential Problems, and Stylistic Problems.)
There are two tricks that can be used to introduce variables that are missing because all modules are not present.

*

*You can add those variables to a "platform" .pptp file as described in the Geppetto FAQ Entry How do I make global variables known to Geppetto?.

or

*

*Create a dummy puppet project, add a manifest and define the variables with dummy values. Then add the dummy project as a "project dependency". This will expose the variables to all code in the project and variables will be resolved.


text:
Q: Get data in string using TcpClient I have a requirement to get the data into a string using TcpClient. The site requires authentication as well. I found a snippet to get data into stream but it is throwing

exception that the connection terminated unexpectedly

. Below is the sample code
TcpClient oClient = new TcpClient();
oClient.Connect("xxx.xxx.xxx.xxx", 80);
NetworkStream ns = oClient.GetStream();
StreamWriter sw = new StreamWriter(ns);
sw.Write(
      string.Format(
                    "GET /{0} HTTP/1.1\r\nUser-Agent: {1}\r\nHost: iq\r\n\r\n",
                             "/",
                             "MyTCPClient")
                      );
sw.Flush();
StringBuilder sb = new StringBuilder();
while (true)
{
    int i = ns.ReadByte(); // Inefficient but more reliable
    if (i == -1) break;  // Other side has closed socket
    sb.Append((char)i);   // Accrue 'c' to save page data
}
oClient.Close();

How can I include the authentication step as well.
P.S.: Just to summarize, I want to get the html of a page in string using TcpClient which involves authentication as well.
Edit: I am going for this approach as the URL had period at the end which was being removed by URI.


text:
Q: Switched from Sublime to PhpStorm: Magento can't find class anymore I get suddenly the following error:
Fatal error: Class 'Mage_Sales_Model_Order' not found in
/projecs/magento/htdocs/lib/Varien/Data/Collection.php on line 562

I did not change any files, even reverted with my git to a commit which I already deployed to stage and live and they are working.
The only thing I changed is, that I switched from Sublime to PhpStorm.
But I don't get why it's not working any more, when my git is not showing any changes.
Any ideas?
EDIT: Seemed like the changes of the log file were not shown by the tail command. After reopening them, I found out, that PhpStorm changed the owner to "me:me", but I need "me:www-data"

A: *

*Settings/Preferences | Appearance & Behaviour | System Settings

*Disable Use "Safe write" option

This will tell IDE to overwrite edited file directly instead of making temp copy first and then replacing original file. This usually solves such "wrong owner/permission" problems.


text:
Q: I'm trying to find the sum of all primes below 2 million in python ls = []
total = 0

for i in range(0,2000000):
    ls.append(i)

for i in range(2,2000000):
    for x in range(2,int(float(2000000/i)+0.5)):
        ls[int(float(i*x))] = 0
ls[1] = 0

for j in range(0,2000000):
    total += ls[j]
print total

This code is giving me the wrong answer. It includes large numbers that are not prime. It includes 25 more numbers than there are prime numbers.

A: Your algorithm is giving the wrong result, couldn't figure out what approach do you use, it would be better if you could give more details.
There is an algorithm called Sieve of Eratosthenes algorithm to generate prime number effectively. You find that algorithm explained in this thread, with details to write the algorithm.
import math
def primeNumbers(n):
    A = range(2, n + 1)
    B, C= [],A
    while C[0]< math.sqrt(n):
        firstElement= C[0]
        B+= [firstElement]
        C= [x for x in C if x%firstElement!=0]
    return B+C

t= sum(primeNumbers(2000000)) #you summ the prime numbers numbers
print t

A: The problem is with this line:
    for x in range(2,int(float(2000000/i)+0.5)):

float(2000000/i) doesn't do much in this context, did you mean float(2000000)/i? You're still doing integer division and then converting the result to float. So, when i is 947, this returns 2111.0 instead of 2111.93. As a result, adding 0.5 to that and calling int() effectively does nothing and you still end up with 2111.
This then ends up running the loop till 2110, so you fail to mark 947 * 2111, which gives you a false positive.
You can rewrite the loop slightly to fix this:
for i in range(2,2000000):
    for x in range(2 * i, 2000000, i):
        ls[x] = 0

This way, instead of dividing and then multiplying, you're simply going through and marking all the multiples of i until 2000000.
Obviously, there are other (better) ways to solve the problem, but I just wanted to point out how you can improve your current solution.


text:
Q: Upload file to server using js Good day Gurus! I just want to ask how to upload a file using js. I need to copy the file a user selected, from the file upload dialog, to the server. I wonder if it can be done through js. If not, is there a way to upload a file to the server without using fileUpload tool from the toolbox.? Any suggestion or advice is highly appreciated. Thanks in advance.

A: U can use some upload tools such as Uploadify.It's a Jquery tools that upload a file in Ajax.

A: In case other people would need something like this without using other tool. I'll attach here the link of the site that helped me solved the problem. Hope it helps. Thanks.
Cheers. :)
Ajaxfileupload


text:
Q: Why are the view*Disappear methods not being called in iOS? I try to do something when the home button and power button has been clicked. I am developing in iOS.
This is the code I use:
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    NSLog(@"viewDidDisappear");
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    NSLog(@"viewWillDisappear");
}

- (void)applicationFinishedRestoringState{
    NSLog(@"applicationFinishedRestoringState");
}

Why is the above function not being called when I click the power button or home button on the iPhone?
Did I miss something?

A: viewDidDisappear: and viewWillDisappear: will get called if the view is pushed or popped or in anyway gets disappeared in your own runloop, going to background by pressing home or power button doesn't count as view' related events, but rather app related events. you should register for UIApplicationWillResignActiveNotification notification instead.
e.g.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disappearSelector) name:UIApplicationWillResignActiveNotification object:nil];

A: According to Apple's documentation

This method is called before the receiver's view is about to be added
  to a view hierarchy and before any animations are configured for
  showing the view. You can override this method to perform custom tasks
  associated with displaying the view. For example, you might use this
  method to change the orientation or style of the status bar to
  coordinate with the orientation or style of the view being presented.
  If you override this method, you must call super at some point in your
  implementation.

To get notified, when your application resumes you should use:
- (void)applicationDidBecomeActive:(UIApplication *)application This method is implemented in your AppDelegate.m
On the other hand
A notification called UIApplicationDidEnterBackgroundNotification is posted when the user locks their phone. Here's how to listen for it:
In viewDidLoad: of your ViewController:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(screenLocked) name:UIApplicationDidEnterBackgroundNotification object:nil];

Then add some stuff in your method
-(void)screenLocked{
    //do stuff
}


text:
Q: Aspose Library Tiff file format issue after .Net6 migration in linux environment I am using aspose library to generate Tiff images. Here the problem is I am able to generate the file successfully, but the file is not loading properly, may be I guess fonts are missing
I have attached the screenshot below for ref.
Note: The issue occured in the linux server after .Net6 migration(Before .Net6 it's working fine)


text:
Q: putting an image in each category in Highcharts I have this code:
http://jsfiddle.net/waqLq62d/
and let me know how to put an image at the beginning of the category. so as it is shown in this picture.

I do not know how, thank you very much.
$('#container').highcharts({

        xAxis: {
            categories: [data.d[300].nomindicador, data.d[500].nomindicador, data.d[600].nomindicador,data.d[700].nomindicador, data.d[900].nomindicador],
            title: {
                text: null
            },
            labels: {

            align: 'left',
            x: 10,
            y: -20

            }

        },
        yAxis: {

            title: {
                text: 'Resultado',
                 align: 'right'
            }

        },
        tooltip: {
            valueSuffix: ' dollars'
        },
        plotOptions: {
            bar: {
                dataLabels: {
                    enabled: false
                }
            }
        },
        legend: {
            layout: 'vertical',
            align: 'center',
            verticalAlign: 'bottom',
            x: -40,
            y:40 ,
            floating: true,
            borderWidth: 1,
            backgroundColor: '#FFFFFF',
            shadow: true
        }

A: To achieve this, you have to have to use the useHTML property on the labels object and set it to true.
Then, you have to use the format property to inject an HTML image in your label.
Full working example here:
http://jsfiddle.net/u3o416xb/
The code should look something like this:
labels: {
    x: -5,
    y: -20,
    useHTML: true,
    format: '
 my label
 '
}


text:
Q: ssh: Use cases of fingerprints and randomart I am looking at what is being written about rssh fingerprints and randomart with some confusion.
This comes down to two questions which I think most people have but which descriptions seem to squirm around.

*

*
Do I need to save the fingerprint and/or randomart someplace in case I need them in the future?

*
What are detailed use cases of these objects?

A: A fingerprint of the (remote) host key is there to verify that you are talking to the correct remote machine. Fingerprints are hard to remember though.
That's where random art comes into play.
The idea is that humans can tell much easier if two images are different than if two hexadecimal strings are different. If the remote host key changes all of the sudden you can tell by the different image that maybe something fishy is in the works.
To activate to be shown the random art of the remote machine on login, add
  VisualHostKey=yes to your .ssh/config file


text:
Q: I want to get the filename in a string from a directoy using c++ I have a directory called test. This directory is created dynamically while running another part of the code. And test contains different files. These files are also generated automatically. Suppose I have generated a1.txt,a2.txt,a.c,a3.txt,b.c in the directory test. I want to get the a3.txt file name in a variable. That means I want to iterate on the content of the directory and get the name of the ".txt" file associated with the largest number. Please help me regarding this issue.

A: Using the opendir function,
DIR *opendir(const char *name);

After opening that directory, using the readdir get the files in that directory.
struct dirent *readdir(DIR *dirp);

Using the structure you can get the file name and You can use that file.

A: The following gives you both directories and files in a given directory.
using namespace std;

int getDirContent (string dir, vector<string> &files) {
    DIR *dp;
    struct dirent *dirp;

    if ((dp  = opendir(dir.c_str())) == NULL) {
        cout << "Error(" << errno << ") opening " << dir << endl;
        return errno;
    }

    while ((dirp = readdir(dp)) != NULL) {
        files.push_back(string(dirp->d_name));
    }

    closedir(dp);
    return 0;
}

string dir = string(".");
vector<string> files = vector<string>();
getDirContent(dir,files);


text:
Q: Cannot downcast UIButton to a subclass I have searched around and cannot figure out what I am doing wrong. I am trying to downcast a UIButton to a subclass in the following line of code:
var currentButton: FileButton = UIButton(type: .System) as! FileButton

FileButton is a simple subclass of UIButton that just stores a couple variables with the button. Code is below:
import UIKit

class FileButton: UIButton {

     var fileAddress: String = ""
     var fileMsgId: String = ""
     var fileAppId: String = ""

}

I am getting the following error in the console when I try to execute this code:

Could not cast value of type 'UIButton' (0x19e9c9e40) to
  'CollectionFun.FileButton' (0x100127490).

Any thoughts? This seems like it should be simple but I can't figure it out. Thanks.

A: Just simply call:
var currentButton: FileButton = FileButton(type: .System)

A: You can not downcast object in your example. You create UIButton type object and try to convert it to other object that not the parrent for it or is higher in the inheritance hierarchy , in this case new object have more functionality and need to allocate more memory for example. You can make your code compiled without error like this:
var currentButton = UIButton(type: .System) as? FileButton

but it will be useless code, because it will always return nil
To explain more clearly give an example. You can do this:
var button1 = FileButton()
button1.fileAddress = "qwerty"
var button2 = button1 as UIButton
var button3 = button2 as? FileButton
print(button3.fileAddress)

print will be

Optional("qwerty")

And it will be work becoause first object was FileButton type.
But this code:
var button1 = UIButton()
var button2 = button1 as? FileButton
print(button2?.fileAddress)

will print

nil

And you try to do like second example

A: Like other object oriented languages, if you initialize a variable as a superclass (in your case UIButton) you cannot downcast it to a subclass (in your case FileButton). This is because you are initializing a UIButton object, which is not a FileButton. Simply change your code to initialize a FileButton object, and it should work.
You should therefore replace UIButton(type: .System) as! FileButton with FileButton(type: .System). Note that the cast is not necessary now, as we are directly initializing a FileButton object.


text:
Q: Retrieving file via Ubuntu One API brings back webpage I'm playing around with the Ubuntu One API (coding in Java) and can successfully make calls using:
GET /api/file_storage/v1
and
GET /api/file_storage/v1/~/path/to/volume/path/to/node
to get information about the directory structure and files.
When I make a GET request for:
https://files.one.ubuntu.com/YgLpi504etc.etc.etc.
I get a webpage back (works in a browser obviously, but not in my code):
<html>
    <head>
        <title>OpenID transaction in progress</title>
    </head>
    <body onload="document.forms[0].submit();">
        <form id="openid_message" action="https://login.launchpad.net/+openid" method="post" accept-charset="UTF-8" enctype="application/x-www-form-urlencoded"><input type="hidden" name="openid.return_to" value="https://files.one.ubuntu.com/auth/complete/?next=%2FYgLpi504SI6eOmbTtQuRWw%2F&janrain_nonce=2012-01-10T23%3A20%3A10ZjM6Ttj"/><input type="hidden" name="openid.realm" value="https://files.one.ubuntu.com/"/><input type="hidden" name="openid.ns" value="http://specs.openid.net/auth/2.0"/><input type="hidden" name="openid.sreg.optional" value="email,fullname,nickname"/><input type="hidden" name="openid.claimed_id" value="http://specs.openid.net/auth/2.0/identifier_select"/><input type="hidden" name="openid.ns.sreg" value="http://openid.net/extensions/sreg/1.1"/><input type="hidden" name="openid.assoc_handle" value="{HMAC-SHA1}{4efc9f73}{E6WEdg==}"/><input type="hidden" name="openid.mode" value="checkid_setup"/><input type="hidden" name="openid.identity" value="http://specs.openid.net/auth/2.0/identifier_select"/><input type="submit" value="Continue"/>
    </form>
        <script>
            var elements = document.forms[0].elements;
            for (var i = 0; i < elements.length; i++) {
                elements[i].style.display = "none";
            }
        </script>
    </body>
</html>

Is this the wrong URL to be using in code?

A: In order to fetch the file content, you need to use https://files.one.ubuntu.com/ + content_path URL, the links that are used for https://one.ubuntu.com/files/ will not work with OAuth.


text:
Q: How to run a Sencha Touch 2 app without a web server? Does anyone have any idea on how to run a sencha touch 2 app without installing a web server (like LAMP/XAMP).  (PS : I'm new to Sencha Touch)
I know there is one way - Including phonegap's javascript file in the app.json of the Sencha Touch 2 app. Which'll look like this
"js":
    {
        "path": "cordova-2.5.0.js"
    }

After this the sample application runs on the browser without the web server.

*

*Is there ANY other way?

*How does adding the phonegap js file help in running the sencha touch app without web server anyway??

A: Starting chrome with --allow-file-access-from-files --disable-web-security flags also does the trick.
Sencha requires web server because if app is in development mode microloader in sencha make Ajax request for app.json file and from it, it loads other files.  You can see this in

../sencha-sdk/mircroloader/development.js

file with following code -
var xhr = new XMLHttpRequest();
xhr.open('GET', 'app.json', false);

When you start chrome with above mentioned flags, chrome does allow making ajax requests even if file opened with file://.... url scheme.
When you deploy the app after compressing js/css with sencha cmd, all files are bunched into one single file. You no more need a webserver in that case.

Update
From Cordova docs for Whitelisting domain

Domain whitelisting in Apache Cordova is a security model that controls access to outside domains, such as http://google.com. The default security policy is to block all network access. The application developer can then declare access to specific network domains and subdomains.

And

In the Widget Access specification, the  element is used to declare access to specific network domains. In the future, Apache Cordova will abstract the platform whitelisting implementations to the W3C Widget Access specification. However, for now each platform must implement it's own domain whitelisting.

Moreover, W3C Widget Access does not enclose the security and user agent enforce policy. It is defined in XMLHTTPRequest.
So what Cordova essential does is, adds an exception in policy to allow access to certain network resource outside app domain with whitelisted domains.


text:
Q: AngularJS Table row span How to do a row span in bootstrap table with Angular JS?  My table is created using ng-repeat.
With ng-repeat I think it is not possible. So I look at ng-grid and ng-table, both have  grouping.
but they  create a collapsible column. not exactly a row span. so please let me know my options.
I am trying to achieve  like:

        First Name
        Last Name
        Points

        Jill
        Smith
        50

        Smith2
        60

        Smith3
        70

      Eve
      Jackson
      94

http://plnkr.co/edit/1VBQGVoamQbqv9uYmnWB?p=preview
But it is not a static data, it will be a list of object from server.
Any help appreciated

A: You can add a rowspan property to your JSON. Like:
myJson = [{attr1:'foo', attr2:'bar',rowspan:2},{attr1:'foo', attr2:'bar',rowspan:0}];

Then you can use both ng-if and rowspan like this:

    0" rowspan="{{item.rowspan}}">{{item.attr1}}
    {{item.attr2}}

You can iterate through the JSON and add the rowspan conditionally:
data.forEach(function(item){
    if(someCondition){
        item.rowspan = 2; // or 0, 1, 2, 3...
    }
});

Here's the plunker.


text:
Q: Entity framework Code First SQL Server View I defined a view in my DB and then I wrote the entity definition in the code:
    [Persistence]
    [Table("ADMV_APPLICATION_OPTION")]
    public partial class ADMV_APPLICATION_OPTION
    {
        public string ID_APPLICATION_OPTION { get; set; }
        public string DS_APPLICATION_OPTION { get; set; }
        public byte FL_TYPE { get; set; }
        public Nullable<double> OPTION_NUM_VALUE { get; set; }
        public string OPTION_STR_VALUE { get; set; }
        public string OPTION_XML_VALUE { get; set; }
        public System.Guid GUID_DIVISION_SAP { get; set; }
        public string ID_DIVISION_SAP { get; set; }
        public string ID_PLANT { get; set; }
    }

When I execute my application I get the error

One or more validation errors were detected during model generation:
MES.Core.ADMV_APPLICATION_OPTION: : EntityType
  'ADMV_APPLICATION_OPTION' has no key defined. Define the key for this
  EntityType.

Do I need a key also for the views?
thanks

A: Your error clearly tell that you need add PrimaryKey. Views in EntityFramework also need PK. You can tell EF, some column may be used as PK, using ISNULL when you create view in SQL:
Create view SomeView
As
  Select
      IsNull(YourUniqueId, -1) as YourUniqueId,
      ...
  From TableName

Or using Data Annotation use [Key] attribute, setting this attribute to ID_APPLICATION_OPTION be sure it is unique.
    [Persistence]
    [Table("ADMV_APPLICATION_OPTION")]
    public partial class ADMV_APPLICATION_OPTION
    {
        [Key]
        public string ID_APPLICATION_OPTION { get; set; }
        public string DS_APPLICATION_OPTION { get; set; }
        public byte FL_TYPE { get; set; }
        public Nullable<double> OPTION_NUM_VALUE { get; set; }
        public string OPTION_STR_VALUE { get; set; }
        public string OPTION_XML_VALUE { get; set; }
        public System.Guid GUID_DIVISION_SAP { get; set; }
        public string ID_DIVISION_SAP { get; set; }
        public string ID_PLANT { get; set; }
    }


text:
Q: Function fails to return a value I am using a sass snippet from this website to create color stacks.
$color-stack:
(group: foo, id: normal, color: #e67835),
(group: foo, id: pale, color: #f8a878),
(group: foo, id: dark, color: #ad490c),
(group: bar, id: normal, color: #426682);

// Color  Function
@function color($group, $shade:normal, $transparency:1){
  @each $color in $color-stack{
    $c-group: map-get($color, group);
    $c-shade: map-get($color, id);
    @if($group == map-get($color, group) and $shade == map-get($color, id)){
      @return rgba(map-get($color, color), $transparency);
    }
  }
}

Later in my code I want to use @each to give some elements different colors depending on their parent class
@each $category in foo, bar {
    .cat-#{$category} {
        .some-class {
            background-color: color(#{$category}, pale);
        }
    }
}

I would expect this to compile to:
.cat-foo .some-class {
    background-color: #f8a878; //the value of foo pale on the $color-stack map
}

Instead it throws and error: Function color did not return a value
If I replace the #{$category} with the string foo it works as expected.

A: This is because you are looking for a group with the value bar and with an id of pale. This does not exist in your map so the function does not return a value.
Add that and it works.
$color-stack:
(group: foo, id: normal, color: #e67835),
(group: foo, id: pale, color: #f8a878),
(group: foo, id: dark, color: #ad490c),
(group: bar, id: normal, color: #426682),
(group: bar, id: pale, color: #000);


text:
Q: Couchbase & ElasticSearch Replication on Vagrant Box I have successfully setup couchbase and elasticsearch on my machine, and configured the XDCR (cross datacenter replication) without a problem. Now, however I am trying to achieve the same setup on a vagrant box. I have elasticsearch and couchbase running without a problem, and port forwarding setup so I can access the couchbase admin console from my browser.
When I try and setup the replication though I get the following error
Error {econnrefused,[{lhttpc_client,send_request,1}, {lhttpc_client,execute,9},
lhttpc_client,request,9}]} happened during REST call get to http://127.0.0.1:9091/pools.

I am setting up the replication with IP/hostname 127.0.0.1:9091, which is what worked when I was doing it locally, i.e. without vagrant. Could this be the problem? Since localhost isn't  referring to the vagrant machine?

A: At a guess you are trying to use the wrong port for replication - Couchbase uses port 8091 not 9091.

A: Ok, despite using versions of couchbase and elasticsearch that were supposed to be compatible, I decided to try the same approach with different versions, namely
couchbase-server-enterprise_2.5.1_x86_64.deb
elasticsearch-1.0.1.deb
elasticsearch-transport-couchbase-1.3.0

Instead of port forwarding in my Vagrant file I also made sure I was using a private network
config.vm.network "private_network", ip: "192.168.33.10"

and then when I attempted to setup replication using 192.168.33.10:9091 as the hostname it worked.


text:
Q: In Orchard CMS, how do I customize the Blog widget? I'm still new to Orchard and don't quite understand how it fits together.
The home page shows a blog post list, which is what I want. Except that right on top of the list is a summary of the blog. I only want the blog entries to show and not the general blog summary/header.
How do I customize the Blog widgets(?) to not show the summary/header?
I am using a custom derivative of the "TheThemeMachine" theme.


text:
Q: Skip Entities while flushing when they are a Duplicate i'm playing a little bit with Symfony2 and Doctrine2.
I have an Entity that has a unique title for example:
class listItem
{
    /**
     * @orm:Id
     * @orm:Column(type="integer")
     * @orm:GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @orm:Column(type="string", length="255", unique="true")
     * @assert:NotBlank()
     */
    protected $title;

now i'm fetching a json and updating my database with those items:
$em = $this->get('doctrine.orm.entity_manager');

foreach($json->value->items as $item) {
    $listItem = new ListItem();
    $listItem->setTitle($item->title);
    $em->persist($listItem);
}

$em->flush();

works fine the first time. but the second time i'm getting an sql error (of course): Integrity constraint violation: 1062 Duplicate entry
sometimes my json file gets updated and some of the items are new, some are not.
Is there a way to tell the entity manager to skip the duplicate files and just insert the new ones?
Whats the best way to do this?
Thanks for all help. Please leave a comment if something is unclear
Edit:
what works for me is doing something like this:
$uniqueness = $em->getRepository('ListItem')->checkUniqueness($item->title);
    if(false == $uniqueness) {
        continue;
    }

    $listItem = new ListItem();
    $listItem->setTitle($item->title);
    $em->persist($listItem);
    $em->flush();
}

checkUniqueness is a method in my ListItem Repo that checks if the title is already in my db.
thats horrible. this are 2 database queries for each item. this ends up about 85 database queries for this action.

A: How about retrieving all the current titles into an array first and checking the inserting title against the current titles in that array
$existingTitles = $em->getRepository('ListItem')->getCurrentTitles();

foreach($json->value->items as $item) {
  if (!in_array($item->title, $existingTitles)) {
    $listItem = new ListItem();
    $listItem->setTitle($item->title);
    $em->persist($listItem);
  }
}

$em->flush();

getCurrentTitles() would need to be added to ListItem Repo to simply return an array of titles.
This only requires one extra DB query but does cost you more in memory to hold the current titles in an array. There maybe problems with this method if your dataset for ListItem is very big.
If the number of items your want to insert each time isn't too large, you could modify the getCurrentTitles() function to query for all those items with the titles your trying to insert. This way the max amount of $existingTiles you will return will be the size of your insert data list. Then you could perform your checks as above.
// getCurrentTitles() - $newTitles is array of all new titles you want to insert
return $qb->select('title')
   ->from('Table', 't')
   ->in('t.title = ', $newTitles)
   ->getArrayResult();

A: If you are using an entity that may already exists in the manager you have to merge it.
Here is what I would do (did not test it yet) :
$repository = $this->get('doctrine.orm.entity_manager');

foreach($json->value->items as $item) {
    $listItem = new ListItem();
    $listItem->setTitle($item->title);
    $em->merge($listItem); // return a managed entity
    // no need to persist as long as the entity is now managed
}

$em->flush();


text:
Q: Simplicial Approximation Theorem Simplicial Approximation Theorem for maps roughly states:
If $X$ and $Y$ are two finite simplicial complexes and $f:|X|→|Y|$ is a continuous map between their geometric realizations, then there exists a subdivision $X'$ of $X$ and a simplitial map $g: X' \to Y$ such that $|g|$ is homotopic to $f$.
Can someone help me how to show (by using this theorem) that the set $[X,Y]$ of homotopy classes $f: X \to Y$ is at most countably infinite.

A: The point here is that one can choose $X'$ to be an iterated barycentric
subdivision $X^{(k)}$ of $X$. There are finitely many simplicial maps
from $X^{(k)}$ to $Y$ for a given $k$, so countably many overall.


text:
Q: Error in displaying multiple values returned by AJAX function in PHP Page 1:
I have a drop down menu whose values are passed to an AJAX function on selecting a particular option. And the AJAX function does multiple functionality & produces multiple values in page2. And I want to display all those values at multiple locations in page1. And when I tried doing this, error occurred.
My Page 1:
<selectid="ddl" name="ddl" onchange="show_details(this.value)">
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
</select>

 display blah here

 display woo here

 display dope here

My AJAX function:
function show_details(eid)
{

    if(window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();

    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()//callback fn
    {
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {

          document.getElementById("blah").innerHTML=xmlhttp.responseText;
          document.getElementById("woo").innerHTML=xmlhttp.responseText;
          document.getElementById("dope").innerHTML=xmlhttp.responseText;

        }
    }

    xmlhttp.open("GET","page2.php?variable4="+eid,true);

    xmlhttp.send();
}

Page2:
<?php
$envv_idd=$_GET["variable4"];

//does operation blah & returns $x

$x= value of blah;
echo $x;

//does operation woo & returns $y

$y= value of woo ;
echo $y;

//does operation dope& returns $z

$z= value of dope;
echo $z;
?>

I want to show $x in div blah, $y in div woo & $z in div dope.
Is there any method?

A: $x= value of blah;
$y= value of woo ;
$z= value of dope;

$xyz = array(
         'x' => $x,
         'y' => $y,
         'z' => $z
       );

echo json_encode($xyz);

In your script
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
    // Your xmlhttp.responseText message returned json value like this
    // {"x":"x text", "y":"y text", "z":"z text"}

    var jsonStr = JSON.parse(xmlhttp.responseText);

    document.getElementById("blah").innerHTML= jsonStr.x;
    document.getElementById("woo").innerHTML = jsonStr.y;
    document.getElementById("dope").innerHTML= jsonStr.z;
}


text:
Q: Unable to generate java files from UPS Void wsdl: void is a Java keyword I'm working on generating Java code from the UPS Void wsdl. However, this wsdl generates java classess with the package of:
package com.ups.wsdl.xoltws.void.v1_1;
Which doesn't compile. Void is a reserved keyword in Java.
I'm using the Maven cxf codegen plugin.
This seems like a problem that anyone generating Java code from this wsdl would run into. Has anyone done this before and found a workaround for this problem?
Here's the wsdl:
<?xml version="1.0" encoding="UTF-8"?>
<!-- UPS Void Shipment Service WSDL Release Date Mar 11, 2008 -->
<!-- Copyright 2007-2008 United Parcel Service of America, Inc. All rights reserved.   -->
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:error="http://www.ups.com/XMLSchema/XOLTWS/Error/v1.1" xmlns:upss="http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0" xmlns:common="http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0" xmlns:voida="http://www.ups.com/XMLSchema/XOLTWS/Void/v1.1" xmlns:tns="http://www.ups.com/WSDL/XOLTWS/Void/v1.1" targetNamespace="http://www.ups.com/WSDL/XOLTWS/Void/v1.1">
    <wsdl:types>
        <xsd:schema>
            <!-- This schema defines the UPS Security header used for authorization purposes -->
            <xsd:import namespace="http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0" schemaLocation="UPSSecurity.xsd"/>
            <!--  This schema defines the error detail data types returned within SOAPFaults to provide more specific information pertaining to the problem. -->
            <xsd:import namespace="http://www.ups.com/XMLSchema/XOLTWS/Error/v1.1" schemaLocation="Error1.1.xsd"/>
            <!-- This schema defines the Void Shipment service data types -->
            <xsd:import namespace="http://www.ups.com/XMLSchema/XOLTWS/Void/v1.1" schemaLocation="VoidWebServiceSchema.xsd"/>
        </xsd:schema>
    </wsdl:types>
    <wsdl:message name="VoidRequestMessage">
        <wsdl:part name="Body" element="voida:VoidShipmentRequest"/>
        <wsdl:part name="UPSSecurity" element="upss:UPSSecurity"/>
    </wsdl:message>
    <wsdl:message name="VoidResponseMessage">
        <wsdl:part name="Body" element="voida:VoidShipmentResponse"/>
    </wsdl:message>
    <wsdl:message name="VoidErrorMessage">
        <wsdl:part name="VoidError" element="error:Errors"/>
    </wsdl:message>
    <wsdl:portType name="VoidPortType">
        <wsdl:operation name="ProcessVoid">
            <wsdl:input name="VoidShipmentRequest" message="tns:VoidRequestMessage"/>
            <wsdl:output name="VoidShipmentResponse" message="tns:VoidResponseMessage"/>
            <wsdl:fault name="VoidError" message="tns:VoidErrorMessage"/>
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="VoidBinding" type="tns:VoidPortType">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="ProcessVoid">
            <soap:operation soapAction="http://onlinetools.ups.com/webservices/VoidBinding/v1.1" style="document"/>
            <wsdl:input name="VoidShipmentRequest">
                <soap:body parts="Body" use="literal"/>
                <soap:header message="tns:VoidRequestMessage" part="UPSSecurity" use="literal">
                    <soap:headerfault message="tns:VoidErrorMessage" part="VoidError" use="literal"/>
                </soap:header>
            </wsdl:input>
            <wsdl:output name="VoidShipmentResponse">
                <soap:body parts="Body" use="literal"/>
            </wsdl:output>
            <wsdl:fault name="VoidError">
                <soap:fault name="VoidError" use="literal"/>
            </wsdl:fault>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="VoidService">
        <wsdl:port name="VoidPort" binding="tns:VoidBinding">
            <!-- Production URL -->
            <!-- <soap:address location="https://onlinetools.ups.com/webservices/Void"/> -->
            <!-- CIE (Customer Integration Environment) URL -->
            <soap:address location="https://wwwcie.ups.com/webservices/Void"/>
        </wsdl:port>
    </wsdl:service>
</wsdl:definitions>

A: I was able to fix this through some flags in my Maven config:
<wsdlOption>
    <wsdl>${project.basedir}/src/main/resources/wsdl/ups/ship/Void.wsdl</wsdl>
    <extraargs>
        <extraarg>-client</extraarg>
        <extraarg>-verbose</extraarg>
        <extraarg>-compile</extraarg>
        <extraarg>-p</extraarg>
        <extraarg>com.ups.wsdl.xoltws.voidservice</extraarg>
        <extraarg>-autoNameResolution</extraarg>
    </extraargs>
</wsdlOption>

More details on this in: Specifying Package Name When Using Maven to Generate Java from WSDL


text:
Q: Copy music from Ubuntu 14.04 LTS to iPhone5s iOS 8.1 I have a problem in copying music to my iPhone 5s (iOs 8.1) from my Ubuntu 14.04. On connecting the iPhone to my laptop via a usb chord, I can see a folder representing the iPhone. But I can't find a folder representing the music in the iPhone.
CopyTrans Manager helped copying music to iPhone from Windows. It was not working with Ubuntu. I tried opening the iPhone with Rhythmbox. But it wasn't showing any playlist or music from the iPhone.
Please recommend an ubuntu alternative for CopyTrans Manager.

A: Banshee could be useful. You can install it with the following command line help.
sudo add-apt-repository ppa:banshee-team/ppa
sudo apt-get update
sudo apt-get install banshee

For more info, go for the ubuntu official documentation.

A: aTunes, Floola and Eina may be some good linux alternatives for CopyTrans Manager. more here.

A: PWNTunes works for iOS 8 and 9. It is a jailbreak tweak which allows you to drag and drop music to/from the "My Music" folder of your iPhone, just like on an Android phone or mp3 player.
This requires you to have a jailbroken iPhone.
Right now, iOS 8.4, 9.0, 9.0.1, 9.0.2, (but not iOS 9.1) can be jailbroken. If you're running iOS 9.1, you will need to downgrade to 9.0.2 (if Apple's still signing it), before jailbreaking.
To jailbreak iOS 8.4/9.0 is simple:
iOS 8: Use the Taig jailbreak tool, available from: http://www.taig.com/en/
iOS 9: Use the Pangu jailbreak tool, available from: http://en.pangu.io/
Once jailbroken, search for "PWNTunes" in cydia.


text:
Q: os.getlogin() doesn't get the right account name The real account name of my windows is "Administrator.SC-201712271504", but os.getlogin() only gets "Administrator" and I can't export file to my desktop. The error is like No such file or directory: 'C:/Users/Administrator/Desktop/..."
How can I get the full account name "Administrator.SC-201712271504"?

A: import getpass
print(getpass.getuser())

or
import pwd
pwd.getpwuid(os.getuid())[0]


text:
Q: PHP File Uploads -- Original filename is being changed I have a tiny project going that acts as a bit of a file host for temporary storage of user files. Similar to UploadPie, if you know what that is. It's all been working fine, and I was just adding in some new features (namely, syntax highlighting upon viewing Javascript files) and suddenly things went all wonky with the uploads.
By "wonky", I mean the $_FILES['upload']['name'] entry ("upload" is the file form element's name) is being changed upon uploading to some seemingly random, extensionless name beginning with "php". Which is annoying, since my script does its own renaming while retaining the original file extensions--and now it doesn't even GET the file extension.
The weirdest part is that it was working before, even during this testing round, and I have only been changing the viewing script, I haven't even TOUCHED the upload script. When I noticed the extensions weren't being retained, I did a bit of digging and that's how I found the filename issue. For example, when I upload a file called "css-tricks.js" and print_r the $_FILES superglobal, I get this output:
Array (
    [upload] => Array (
        [name] => php6pVzJG
        [type] => application/octet-stream
        [tmp_name] => C:\wamp\tmp\phpD7E6.tmp
        [error] => 0
        [size] => 1326
    )
)

Notice the filename was changed to "php6pVzJG"? That's never happened before. I tried restarting PHP and it continues doing this. I looked for a setting in php.ini and found nothing. Has anyone had this issue before?
If you need more info, I can post the code from the upload.php file, though as I said, I haven't changed that file at all since the last time it worked.


text:
Q: Rolle's Theorem to Prove $f^{(n)}$ has a zero in interval (Use Rolle's Theorem) Let $f\in C^n[\alpha, \beta ]$. Suppose that $f$ has a zero of multiplicity $m$ at $\alpha$ and a root of multiplicity $k$ at $\beta$, where $m \geq 1, k \geq 1$ and $m+k-1=n$. Prove that $f^{(n)}$ has at least one zero in $(\alpha, \beta)$.
Not really sure where to start with this one.
Thank you in advance for any help/suggestions.

A: Prove, as usual, that $f^{(j)}$ has $m+k-j$ roots in the interval $[α,β]$, counted with multiplicity.
As example, in the first step you get per Rolle one root of $f'$ inside $(α,β)$ and the multiplicities at $α$ and $β$ reduce to $m-1$ and $k-1$, so that the total count of roots for $f'$ is $$(m-1)+(k-1)+1=m+k-1.$$


text:
Q: How to create an embedded javascript form widget for an rails app? In my Ruby on Rails app, bike rental companies can manage all their bikes (reservations, payments etc.).
Context
I would like to offer a bike rental companies (shops) the option to redirect guests to an online reservation process on my platform, so they can let customers make a reservation for a bike of the shop. (e.g. online reservation process is just for their shop)
Current state
After reading some documentation online (iFrame and embedded JS) I decided an embedded JS form would fit this purpose best.
The first step would be to create an embedded JS form with

*

*arrival

*departure

*bike_category [optional]

And after submitting this form, the reservation continues with an index page displaying all available bike_categories.
Question
It's the first time I'm doing this and I'm not sure how the flow in my Rails app should be to generate the widget and where all the respective files should be located.
As I look at it now,

*

*I should first create a javascript file in app/javascript/component/bike_search_form.js,

*

*here I somehow need to grasp who sends the request and if they are allowed

*furthermore, the javascript file should wait till the external page is loaded and then load the css of the form and the form itself

*The form is generated via a widget controller which directs to a file in views/widget/bike_search_form.html.erb
Is this flow and are there files + their locations correct or am I missing something/a lot?
Code
script to implement by shop

app/javascript/component/bike_search_form.js
(function() {
var jQuery;
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
    if (script_tag.readyState) {
      script_tag.onreadystatechange = function () { // For old versions of IE
          if (this.readyState == 'complete' || this.readyState == 'loaded') {
              scriptLoadHandler();
          }
      };
    } else {
      script_tag.onload = scriptLoadHandler;
    }
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
    jQuery = window.jQuery;
    main();
}

function scriptLoadHandler() {
    jQuery = window.jQuery.noConflict(true);
    main();
}
function main() {
    jQuery(document).ready(function($) {
        var css_link = $("", {
            rel: "stylesheet",
            type: "text/css",
            href: "<%= URI.join(root_url, path_to_stylesheet("widget.css")).to_s %>"
        });
        css_link.appendTo('head');

       #Something to generate the form?
    });
}
})();


text:
Q: Find executables associated with Homebrew Formula Some Homebrew formulas have names that do not correspond with any of the installed commands (e.g., coreutils, speech-tools), other formulas provide an command that matches up with the name, but also provide others alongside it (e.g., lua).
Is there a simple way to determine what commands are associated with a given formula? Ideally as a brew <arg> command before installing, but even a shell script I could use post-install would help.
I thought I might be able to figure this info out with a brew link --dry-run <formula>, but that typically just gives me a warning that the formula is already linked (even with --overwrite or --force added to the command). I don't want to have to unlink each time I want to see the commands, so this route doesn't seem helpful.

A: I wrote Homebrew-command-not-found to do the reverse thing: get a formula from an executable. There isn't any easy way to get a formula's executables as other answers pointed out; so I installed all Homebrew formulae and recorded all executables in one file.
You can find it here. Each formula has its own line with the following format:
<name>: <executable-1> <executable-2> <...>

It's as easy as grep ^git: executables.txt to get the executables installed by the git formula.
The file is regularly updated and covers 17k+ commands for 5k+ core formulae.

A: As bmike's answer points out, aside from digging through the projects source to determine what executables they install, there's no good way to determine what commands come with a given formula before installing it.
After a formula is installed, running
brew unlink --dry-run formula | grep "$(brew --prefix)/bin"

is a workable option now that --dry-run is available for brew unlink.
Before that was added I wrote an external command called brew executables that still has some benefits over the above (mainly in formatting and handling some links a bit differently). I'll include a simplified (and probably non-working, due to missing some variable assignments) version of it here:
version_in_use=$(echo "$brew_info" | grep "$HOMEBREW_PREFIX.*\*$" | sed -e "s|.*$formula/\([^ ]*\).*|\1|i")

cd "$HOMEBREW_CELLAR/$formula/$version_in_use"
for dir in `find . -type d -mindepth 1 -maxdepth 1 -name "bin"`; do
    for file in `find "$dir" -type f -o -type l -perm +111`
    do
            filename=$(basename $file)
            echo $filename
    done
done

In short, it pulls the list of executables out of $(brew --prefix)/$formula/$version_in_use/bin. The version on my GitHub is a bit more fleshed out, including some added ability to identify/indicate when there are commands that link to each other in this bin directory.

A: I think the accepted answer is not (or is no longer) correct, precisely.
While it's true Homebrew lacks the general feature you're asking for, there's at least one tap with at least two methods of using it:
https://github.com/Homebrew/homebrew-command-not-found
Here's what I do! Method 1:
> brew tap homebrew/command-not-found
> brew which-formula when
when
> brew install when
> when
...
Fri 2022 May 27   4:40

Method 2: eval "$(brew command-not-found-init)" # in ~/.{ba,z}shrc
N.B. There may be some significant slow-down to shells with this 2nd method.
For that reason, I enjoy using brew which-formula (method 1) when necessary.

A: In general - no.
Homebrew doesn't install package receipts which is the manner in which current tools decide what is installed where in an exhaustive and correct fashion.
Sometimes you can use brew list to check things, but I've found the best way to check on homebrew is via github - which publishes the source code for all the tools and all the packages.
My favorite search engine, Duck Duck Go even has ! commands to make it easy to search github:

!gh homebrew
lua

Google does a decent job as well ranking homebrew fairly high as well as github

!g homebrew
lua

Also, brew info and brew home often give you a direct link to the project source to check if your suspicions are correct. As you surmise, the real check is to uninstall / reinstall and watch. Not fun, but effective.


text:
Q: Reasoning behind choosing an EKS node instance type? I use EKS
Curious to know how to choose what instance type (for EKS node) I'd need for my application.
Number of pods should be considered? Just trying to find any info on this as I am not sure where to start really for deciding on a particular instance type.

A: The best bet is to start off small and build up from there. One of the awesome things about Kubernetes is that swapping out the nodes for bigger or smaller instances is fairly easy.
Some things that would inform your decision are:

*

*Do your applications require special hardware such as GPUs or Inferentia Chips?

*What are the resource requirements for your largest applications?

*How many pods of each application are you hoping to run (minimum of 3 per service is good)?

*Would you prefer a high density of pods (lots of pods on one node) for lower costs overall; or have pods more spread out on more nodes for higher availability?

Having said that, bear in mind that there are limitations to the maximum number of pods per node - which is constrained by the max number or elastic IPs of the instance. There is also some IPs that are reserved by the instance and system pods so the number is a little less than what's prescribed there.


text:
Q: Draw coordinates on edges of a map I plotted a figure using matplotlib:

And now I would like the edges of the figure to display the coordinates, without manually looking them up and using paint like in this figure:

This is my code:
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
# setup Lambert Conformal basemap.
plt.figure(figsize=(20,10))
map = Basemap(width=400000,height=300500,projection='lcc',
        resolution='h',lat_0=52.25,lon_0=4.5)#lat_1=50,lat_2=45
# draw coastlines.

# draw a boundary around the map, fill the background.
# this background will end up being the ocean color, since
# the continents will be drawn on top.
map.drawmapboundary(fill_color='turquoise')
# fill continents, set lake color same as ocean color.
map.fillcontinents(color='white',lake_color='turquoise')
map.drawcountries(linestyle='--')

map.drawmapscale(lon=6.5, lat=51.25, lon0=0, lat0=52, length=50)
lonA =np.loadtxt('AllStranding250Lon.txt',delimiter=',') ##    [4.540377,4.173571,3.041619]
latA =np.loadtxt('AllStranding250Lat.txt',delimiter=',') #    [52.395394,52.035414,51.286338]

AA=np.loadtxt('AllStranding250Numbers.txt',delimiter=',')
n=len(lonA)
m=len(latA)

print('m=', m)
print('n=',n)

SizeA=np.zeros(n)#number counted
q=len(SizeA)
print('q=',q)

x,y = map(lonA[0:7], latA[0:7])
z,a = map(lonA[7:9], latA[7:9])
for i in range (0,n):
    if 250<=AA[i] <1000:
        SizeA[i]=15
    elif 1000 <= AA[i] < 5000:
        SizeA[i]=25
    elif 5000 <= AA[i] < 10000:
        SizeA[i]=45
    elif 10000<= AA[i]<50000:
        SizeA[i]=65
    elif 50000<= AA[i]<100000:
        SizeA[i]=100
    else:
        SizeA[i]=200

map.scatter(x, y, s=SizeA, c='steelblue', marker='o', label = 'Aurelia     aurita',zorder=2, edgecolors='k')
map.scatter(z, a, s=SizeA[7:9], c='coral', marker='v', label = 'Chrysaora     hysoscella', zorder=2)

l2 = plt.scatter([],[], s=15,color='white', edgecolors='k')
l3 = plt.scatter([],[], s=25,color='white',edgecolors='k')
l4 = plt.scatter([],[], s=45,color='white', edgecolors='k')
l5 = plt.scatter([],[], s=65,color='white', edgecolors='k')
l6 = plt.scatter([],[], s=80,color='white', edgecolors='k')
l7 = plt.scatter([],[], s=200,color='white', edgecolors='k')
l8 = plt.scatter([],[], s=80,color='steelblue', edgecolors='k')
l9 = plt.scatter([],[], s=80,color='coral', marker = 'v', edgecolors='None')

labels = [ "250-1000", "1000-5 000", "5 000-10 000","10 000-50 000","50 000-100 000", "100 000<", 'Aurelia aurita','Chrysaora hysoscella']

plt.legend([ l2, l3, l4,l5,l6,l7,l8,l9], labels, frameon=True,
        fontsize=12, handlelength=2, loc = 'upper left', borderpad = 1,
        handletextpad=1,title ="Stranded medusa", scatterpoints =     1)#loc='upper center'

plt.savefig('AllStranding.png')

plt.show()

I tried to use the line:
map.drawmeridians([],labels=[left,right,top,bottom])

But then it says it doesn't know 'right', and I don't want to draw the meridians in the first place, I just want 2 numbers at each corner.
Thanks in advance!

A: Here is a solution, with only relevant code.
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
#import matplotlib.patches as mpatches

plt.figure(figsize=(20,10))
ax = plt.gca()

width, height = 400000, 300500  # for Basemap()
sx, sy = width/20., height/20. # shifts for annotation placement

bmap = Basemap(width=width, height=height, projection='lcc', \
        resolution='i', lat_0=52.25, lon_0=4.5)

# the limits (corner points) of the map
x1, x2, y1, y2 = bmap.xmin, bmap.xmax, bmap.ymin, bmap.ymax  #meters

# corner points (x, y) in meters of the projection
ll = (x1, y1)
ur = (x2, y2)
ul = (x1, y2)
lr = (x2, y1)

# All (lon, lat) of corner points, degrees
LL = bmap(*ll, inverse=True)
UR = bmap(*ur, inverse=True)
UL = bmap(*ul, inverse=True)
LR = bmap(*lr, inverse=True)

bmap.drawmapboundary(fill_color='turquoise')
bmap.drawcoastlines(linewidth=0.7)

# fill continents, set lake color same as ocean color.
bmap.fillcontinents(color='#eceffd', lake_color='turquoise')
bmap.drawcountries(linestyle='--')

# set properties for use with annotation
anno = [{'text': "{:6.3f}".format(LL[1]), 'xy': np.array(ll), 'shift': [-sx, 0], 'va': 'center', 'ha': 'center'}, \
        {'text': "{:6.3f}".format(UR[1]), 'xy': np.array(ur), 'shift': [+sx, 0], 'va': 'center', 'ha': 'center'}, \
        {'text': "{:6.3f}".format(UL[1]), 'xy': np.array(ul), 'shift': [-sx, 0], 'va': 'center', 'ha': 'center'}, \
        {'text': "{:6.3f}".format(LR[1]), 'xy': np.array(lr), 'shift': [+sx, 0], 'va': 'center', 'ha': 'center'}, \
        {'text': "{:6.3f}".format(LL[0]), 'xy': np.array(ll), 'shift': [0, -sy], 'va': 'bottom', 'ha': 'center'}, \
        {'text': "{:6.3f}".format(UR[0]), 'xy': np.array(ur), 'shift': [0, sy], 'va': 'top', 'ha': 'center'}, \
        {'text': "{:6.3f}".format(UL[0]), 'xy': np.array(ul), 'shift': [0, sy], 'va': 'top', 'ha': 'center'}, \
        {'text': "{:6.3f}".format(LR[0]), 'xy': np.array(lr), 'shift': [0, -sy], 'va': 'bottom', 'ha': 'center'}]

deg_sign= u'\N{DEGREE SIGN}'

# plot texts at all 4 corners of map
for ea in anno:
    txt = ax.annotate(ea['text']+deg_sign, xy=ea['xy'], xytext=ea['xy']+ea['shift'], \
                textcoords='data', \
                arrowprops = dict(arrowstyle="-", lw=.5), \
                size=10, ha=ea['ha'], va=ea['va'])

#plt.savefig('AllStranding.png')
plt.show()


text:
Q: sysTick frequency manipulation? I need a high precision interrupt for my STM32F7. The task is to increase a counter at every tick. The frequency of the CPU is up to 216 MHz (from datasheet) which means an tick duration of around 5 ns can be achieved right?
After some internet research I found out that sysTick can be used for this purpose. I should simply configure the SysTick as follows:
/** Configure the Systick interrupt time */
    HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

/**Configure the Systick */
    HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

I'm toggling a GPIO pin inside the SysTick_Handler function to check the frequency of execution and it is 1 ms.
I want to achieve a tick duration of 1 microsecond so I replaced the 1000 (in the code) with 100, then I tried different numbers but nothing seems to affect the 1 ms duration.
Am I missing something here?
Is there a better solution than the sysTick to achieve this goal?
Thanks.

A: You can't (and shouldn't!) increase some variable each clock cycle. Instead, you should use a hardware timer (TIMx) for such a precision measurement.
In general, there are few suitable approaches:

*

*Use a scheduler. Set up a hardware timer to generate an interruption on overflow and configure it to overflow once in 20us–20ms depending on necessary time granularity. In the interruption routine check if you should do_something() in current scheduling cycle and do, if so. It's extremely important to keep the interruption routine short and surely finite (without long software cycles etc.), especially when the timer period is short.

*Use one-shot timers. If you need to execute only one routine or the order is strictly defined, you can use following approach. In the end of your do_something(), configure and start a hardware timer which will launch do_something() again after the necessary amount of time. So in the interruption routine you just launch do_something(), then in the beginning of do_something() you reset the timer, do your job and set up the timer again. This way you can control the delay up to single clock cycle. However, this solution is much more difficult to maintain and expand.

*Combine. You can use a scheduler that spins a one-shot timer to control the execution start time precisely.
Scheduling is heavily researched area of MCU software development. There are lots of articles on it as well as mature real-time operating systems for MCUs capable of this and much more such as FreeRTOS or ChibiOS. If it's commercial project you usually should stick with common tools like FreeRTOS instead of writing your own scheduler. However, of course, it's very educational — and it's fun!


text:
Q: Symfony2, doctrine2, session, best way to paginate search page Let's imagine we have simple data and want to make pagination of it. It's not hard to do, simple _GET var with page number others doctrine with offset will allow us to do it in easy way, BUT How should it look like in search page? Let me explain.
For example we have simple route with /search url. Where we have form for our search. When use input string we user POST method on same page and will get result. Simple enough but if we add pagination here it become a problem with storing "inputed string".
If we store in session on search query it will be solution BUT... it's not. Why? User input search string - get result with pagination (here search string already in session) after that leave the page (or close browser, or left to another page). When he will return data from session will show him 'result of old query'...
So question is, what is the best practice for such situation? I want simple search query + pagination of it but if user left page - clear result.

A: Using POST instead of GET for search query is kinda unusual and not really safe. Since search query operations are read-only you should use GET to access/get the data. POST is used for updating or creating resources.
And how you will go back/forward in the pagination (using browser's buttons)? You always will be getting an alert box. AND you cannot share/bookmark the search query url.
BTW to answer your question, sessions and hidden input fields would be the way to go. You also can use a combination of get and post
When should I use GET or POST method? What's the difference between them?


text:
Q: characteristic function in probability theory Suppose $\mu$ is a probability measure and $f$ is its characteristic function. Suppose $f$ has finite first order derivative at $t=0$, can you conclude that $\mu$ has finite expectation?
I know that if $f$ has a finite derivative of even order $k$ at $t=0$, then $\mu$ has a finite moment of order $k$. But I am not sure whether $\mu$ has finite expectation and how to prove it.
Can anyone help me?


text:
Q: cvs annotate and standard error redirection First, some background. I'm trying to use cvs annotate within a Perl script invoked from a ksh command line to find out who's using bad hex constants in their source code and dole out justice appropriately. I'd like to use stdout for this program strictly for my own structured output, so I can pipe it to a file or to other programs. But, every call to cvs annotate results in a diagnostic message being printed to the console. It takes the form of:
Annotations for <filename>
***********

It's mucking up my stdout! I played around with annotate on the command line, and I figured that these diagnostic messages were coming from stderr, because running this command directly in ksh:
cvs annotate <filename> 1>yay.txt 2>boo.txt

correctly puts the desired annotated output into yay.txt and the diagnostics into boo.txt. However, things get weirder when I try to run this from within a perl script using backticks.
$muhstring = `cvs annotate $filename 2>boo.txt`;

The desired annotated output does appear in $muhstring, but the diagnostics still get printed to the command line, and boo.txt is created as an empty file. There's an admittedly old post on perlmonks.org that says this syntax should work as written. So, what's the deal? Is this a CVS quirk, have I misread the post, or have things changed since 1999? Or is it something else?
Edit: So, it is not, in fact, mucking up stdout. I tried this in ksh:
perl findbadhexowners.pl badhex.txt > out.txt

and the diagnostic messages still printed to the console, but out.txt only contains the annotations. This is fine for my purposes, and I can continue with other code.
That said, it seems like Perl and cvs specifically are interacting a little strangely, especially considering that redirection in ksh works fine and redirection in Perl for other commands like cd works fine - for example, in Perl
`cd nonexistentDir 1>stdout.txt 2>stderr.txt`;

gives the expected output in both stdout.txt and stderr.txt. It's only using cvs annotate from within Perl that produces this problem.


text:
Q: Operator precedence C++ Could someone please explain the operator precedence that takes place in the following C++ statement?
int lower = height[height[l] < height[r] ? l++ : r--];
Assume, height=[0,1,0,2,1,0,1,3,2,1,2,1] and int l = 0, r = height.size()-1;.
As per my understanding, height[l] < height[r]? would be evaluated first, followed by l++ or r-- as the case might be (l++ in this case).  Then the value of height[updated l] should be assigned to lower.  Thus lower should be 1; but the output says it is 0.  How?  What would be the correct order of the evaluation of the statements then?

A: The l++ uses the post-increment operator. The value of l is increased after the value of the expression is evaluated. So, when l is 0, the value of l++ is 0 and not 1, even though the variable l will have the value 1 afterwards.
Using ++l would show a different behaviour.
The following statement in the question is incorrect:

Then the value of height[updated l] should be assigned to lower

The updated value of l is not used as the array index, but the value of the expression l++, which is the value of l before it is increased.

A: l++ is the post increment operator, which means it will be incremented after the operation is complete. Hence the output 0, everything else is correct.

A: Code is equal to:
int lower = height[height[l] < height[r] ? l : r];
(height[l] < height[r]) ? l+=1 : r-=1;


text:
Q: Optimal memory for page loading in hosted environment? In PHP, shared hosting environment, what shall be an optimal memory consumption to load a page. My current PHP script is consuming 3,183,440 bytes of memory. What shall I consider a good memory usage, to entertain say, 10000 users parallely?
Please be detailed, as I am a novice in optimization part.
Thanks in advance

A: 3MB isn't that bad - keep in mind that parts of PHP are shared, depending on which server is used (IIS, ngx, apache etc.) you can specify pools and clusters as well when having to scale up.
But the old adage testing is knowledge goes well here, try load tests on the site, concurrent 10 -> 100 -> 1000 connections and look at the performance metrics, it wil give you more insight on how much memory is required.
For comparison, the site I normally work on has an average of 300+ users concurrently online and the memory usage is just under 600MB, however I run certain processes locally it will easily use up 16MB.


text:
Q: Bootstrap responsive layout is breaking on small screens For normal and high resolution screens it displays fine, but on small resolution screens it breaks. I tried using classes like col-xs-12 but it still did not display properly.

        Lorem ipsum dolor sit amet
        consectetur adipisicing elit, sed
        do eiusmod tempor incididunt ut
        labore et dolore magna aliqua.

        Ut enim ad?
        minim veniam,
quis
        nostrud exercitation ullamco laboris laboris nisi ut aliquip

                ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non

        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

The full code can be viewed on plunkr.

A: You are given fixed height: 600px to the div. So when changing the width, content should automatically adjust to the space and will go down.
You can only do onething, if you want the hieght to be fixed 600px, do meadia query. Using media query reduce font size and padding.
for example:
CSS
@media screen and (max-width: 480px){
  .container{
   padding: 1em !important;
  }
  .col-md-8.col-xs-12.about-staf span{
   font-size: 27px;
  }
}

Note: all the classes above are from your plunkr only.
like this reduce width of button, font size, other paddings etc