text:
Q: Independency and estimation of user stories that rely on shared predecessor Lest's say I have user stories about using product catalog in shop:

*

*As an administrator I can add/modify/delete catalog items (one or more user story, doesn't matter here)

*As a customer I can search product catalog

*As a customer I  can view product details

Each of this stories rely on predecessor: design and create database to store product information.
I can express db creation as:

*

*another story: As a shop owner I want to store information about products I sell

*Task to be done in story which will be firstly chosen to do

In first case I create story dependency, in second I wondering where estimate this additional task. Let's say it adds additional two story points. To which story should add this points? All (and re-estimate remaining stories in the future), none? I think that second option also can hinder estimation - I have to remember to add this story points to  dependent stories and then possibly remove it.
How to deal with such situations?

A: Setting up the database has no customer value by itself, so preferably it is not a story of its own. The database implementation should be part of the first story that needs it. Or ideally, the database is implemented in phases: with Every story you implement the part that is needed to make that story work.
(That doesn't mean you can't do the design in advance. You probably should)
In general: Dependencies between user stories are very common. The team will estimate a certain story in the assumption that some other story is already done. (Best to take note of these kind of prerequisites). This happens all the time. If the planning changes, and the prerequisites of a story no longer apply, then the team should get the opportunity to re-estimate.

A: The correct solution is number 2.
Agile estimation is by design much less precise than waterfall:

*

*stories are "reminders to have a conversation" and they are incomplete and negotiable by definition

*the only purpose of estimating stories is to determine, more or less, what can be accomplished in an iteration, if you are using iterations

*estimates are basically useless in agile methodologies like Kanban, as long as the stories are small enough.

*there is no point estimating when a set of stories is precisely going to be done: stories will change, so detailed estimates must be avoided for long term goals.

In particular, creating the database is a task, an implementation detail, in the first story you are going to play. Tasks will be estimated (if you so choose) in hours, not in points, and they are estimated during the sprint and not during sprint planning.
Points measure the complexity of a story - not the amount of work, or even less the time it takes - and in my experience they are best seen as a "prize" that the team wins when they complete the story. Adding a database table does not really increase the overall complexity. Adding a database table is a detail which appears because of the specific point in time the story is played.
Asking "where do the 2 points go?" is meaningless. There are no "2 points" to go anywhere. The story is still the same whether you need to create the table or not, and it's perfectly normal and unavoidable not to know which all the tasks that need to be executed in order to complete the story are.
When I estimate, I don't know when a story will be played and what bit of the database will be in place when I play it, so there's no way out of this lack of precision. Again, let me stress that this is normal and unavoidable.
To be more specific, you say:

*

*As an administrator I can add/modify/delete catalog items (one or more user story, doesn't matter here)

*As a customer I can search product catalog

*As a customer I can view product details

  Each of this stories rely on predecessor: design and create database to store product information.

But this is not true in general. You don't need a database at all. You could use, say, a service. You could install an open source component that takes care of it. You could decide to use a document database which doesn't require table creation. You could use a pre-packaged search service, etc. etc.
What you are doing is conflating the implementation details with the stories. Stories are not requirements. They must be more high-level than that! A customer will benefit from searching the product catalog, and the team should be expected to provide the simplest solution that satisfies the story (and the definition of done that you've set), which may or may not include a product database.

A: I've run into this problem a number of times and never found a perfect solution.
But I have found that the least imperfect solution is to have a separate story. The difficulty is in how to word it. You need to do this in conjunction with the user, so that they know this story doesn't produce anything visible, but it does allow you, the programmer, to provide other useful stories for them.
"As a shop owner I want to store information about products I sell" doesn't really convey that point very well. It implies that the end user will be able to store those details.
If your stakeholders are good at understanding that developers are also stakeholders in the product, you can put it to them that a story such as "As a programmer, I want to store and retrieve information about products that my customer sells, so that I can complete tasks #132, #133, #134."
When a user sees this in the current iteration but not tasks 132, 133 or 134, they're going to know that this isn't something you can demonstrate to them at the end of the iteration, but they will be satisfied that, next iteration, they'll be able to get those tasks done, cheaply. This is usually enough.
You should, as a matter of course, demonstrate such tasks to each other, at the end of an iteration, as you are the primary stakeholders for the task.
As a bonus, this mentality leads nicely onto conversations about technical debt stories like "As a programmer, I need an improved API for the XYZ services, so that I can develop against them more rapidly."
Note that I've added a "so that" clause to each of my story examples. This is a good practice for stories, even when they're more clear-cut than the example we're discussing. The business value of a task is at least as important as what the user needs to be able to do to gain that value. This becomes exponentially true as the number of stakeholders grows.

A: I would avoid using story dependencies, it leads to a slippery slope.  As has been said before, how do you know you need a database.  Perhaps flat file or something similar could work for your situation.
Creating the database upfront/early is not really a good option as that will severely limit your options for the code.
I would move forward by using Mocks, XML or some other light weight data input mechanism for the development.  Then as the overall design for the code begins to evolve, you can use the Mocks/XML as the basis for your database design.  The mocks are not throw away, as they can be used later for automated validation of code changes.  Does the creation of the database even need to be work done in an iteration?  Is it possible to review the Mock structure with someone who could create the database based on the mocks and provide it at an agreed upon point in the future?
Story-wise, you may want to think about breaking down "As a customer I can search product catalog" even further?  How do they search the product catalog, by Product ID, Description, Color, Size, Price?  As written, I would say the story has a high probability of taking more than a single iteration to complete.
Finally I would suggest reading some of Scott Ambler's material at [http://www.ambysoft.com/scottAmbler.html][1]
[1]: http://www.ambysoft.com/scottAmbler.html  Scott has done a lot of work regarding databases and how they relate to agile.
Cheers!


text:
Q: Repository pattern in SLIM 3 Hi I am looking to handle slim repository pattern  in the common pattern
like:
productRepositoryInterface
productRepository
product
ProducCOntroller

How do I build that using dependency injection of SLIM
I have routing and it goes to the controller called  ProductController
then in the controller, I want to get in the constructor the ProductRepo interface
my dependencies
$container['productController'] = function($c , ProductRepositoryInterface $productRepo) use ($app) {

    return new ProductController($c ,$productRepo);
};

$container['productsRepository'] = function($c) use ($app) {
    return new ProductRepository( $c->db );
};

but I Got in the controller constructor the following error:
 Catchable fatal error: Argument 2 passed to ProductController::__construct() must be an instance of ProductRepositoryInterface, none given

Product controller:
function __construct($c,ProductRepositoryInterface $repo)
{
    $this->c = $c;
    // grab instance from container
    $this->repository = $repo;
}

A: By default slim passes only the container object to the constructor. Now you have two options.
First option: Grab the repo from the container.
Example pseudo code:
Register the container entry:
use App\Service\Product\ProductRepositoryInterface;
use App\Service\Product\ProductRepository;

$container[ProductRepositoryInterface::class] = function (Container $container) {
    $db = $container->get('db');
    return new ProductRepository($db);
};

Create a controller:
namespace App\Controller;

use Slim\Container;
use App\Service\Product\ProductRepositoryInterface;

class ProductController
{
    /**
     * @var ProductRepositoryInterface
     */
    private $productRepo;

    public function __construct(Container $container)
    {
        // grab instance from container
        $this->productRepo = $container->get(ProductRepositoryInterface::class);
    }

}

Second option: Clean dependency injection. Create a container entry for the controller and pass all dependencies directly.
use Slim\Container;
use App\Service\Product\ProductRepositoryInterface;
use App\Controller\ProductController;
use App\Service\Product\ProductRepository;

$container[ProductRepositoryInterface::class] = function (Container $container) {
    $db = $container->get('db');
    return new App\Service\Product\ProductRepository($db);
};

$container[ProductController::class] = function(Container $container)
{
    $productRepo = $container->get(ProductRepositoryInterface::class);
    return new ProductController($productRepo);
};

The controller
namespace App\Controller;

use Slim\Container;
use App\Service\Product\ProductRepositoryInterface;

class ProductController
{
    /**
     * @var ProductRepositoryInterface
     */
    private $productRepo;

    public function __construct(ProductRepositoryInterface $productRepo)
    {
        $this->productRepo = $productRepo;
    }

}

A: As @Daniel O. mention Slim does not support clear Dependence Injection (specifically the Inversion Of Control principle).  So with Slim you can only  inject dependencies through the Service Locator pattern (which is an anti-pattern based on Mark Seemannn.).
So you have two solutions:

*

*Create a Poor Man's DI. (It's the second solution @Daniel. O provide)

*Use the Slim-Bridge. This package just adapt PHP-DI container
into Slim so make the auto-wiring for you.

What you have to bear in mind is that Dependency Injection and DI-container are two different concepts.

*

*Slim uses the Service-Locator pattern (Daniel O. first solution)

*Daniel O. second solution is a Poor Man's Di

*Slim-bridge is a clear Dependency  Injection Container

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hospital healthcare clinic system I have been trying to find an open source or paid system for hospitals, clinics and in general for a healthcare.
do you know any please?
most of that I find is not supported or bad or not working
I want to integrate it with my call center.
thanks

A: Maybe you are interested on GNUHealth.
Have a look at their home page and project page:

*

*http://health.gnu.org/

*http://savannah.gnu.org/projects/health/


text:
Q: append divs with result ajax I´m traying to do each in response ajax and create divs with this data.
My array it´s:
(3) [Array(15), Array(1), {…}]
0: Array(15)
0: {id: 135, id_oferta: 8, id_articulo: 176, articulos: Array(1)}
1: {id: 136, id_oferta: 8, id_articulo: 169, articulos: Array(1)}
2: {id: 137, id_oferta: 8, id_articulo: 40, articulos: Array(1)}
3: {id: 138, id_oferta: 8, id_articulo: 225, articulos: Array(1)}
4: {id: 139, id_oferta: 8, id_articulo: 450, articulos: Array(1)}
5: {id: 140, id_oferta: 8, id_articulo: 124, articulos: Array(1)}
6: {id: 141, id_oferta: 8, id_articulo: 120, articulos: Array(1)}
7: {id: 142, id_oferta: 8, id_articulo: 125, articulos: Array(1)}
8: {id: 143, id_oferta: 8, id_articulo: 124, articulos: Array(1)}
9: {id: 144, id_oferta: 8, id_articulo: 122, articulos: Array(1)}
10: {id: 145, id_oferta: 8, id_articulo: 119, articulos: Array(1)}
11: {id: 146, id_oferta: 8, id_articulo: 126, articulos: Array(1)}
12: {id: 147, id_oferta: 8, id_articulo: 0, articulos: Array(0)}
13: {id: 148, id_oferta: 8, id_articulo: 121, articulos: Array(1)}
14: {id: 149, id_oferta: 8, id_articulo: 859, articulos: Array(1)}
length: 15
[[Prototype]]: Array(0)
1: Array(1)
0: {id: 8, categoria: 'C', valor: '0.50', nombre: 'ARTICULO C + SECUNDARIO  + OBRA B', descripcion: '', …}
length: 1
[[Prototype]]: Array(0)
2:
firstItems: [{…}]
secondItems: [{…}]
thirdFamily: [{…}]
[[Prototype]]: Object
length: 3
[[Prototype]]: Array(0)

i need access to 2 index and i´m doing this to access to this object array:
if(idOffer == 8){
                        $.each(response[2].firstItems, function(index, value){
                            $(".div-bag").append(`

${value.nombre}

                            `);
                            $(".container-offer").append(`

                                            <input type="checkbox" value="${value.articulos[index].id}">

                                            ${value.articulos[index].codigo}

                                            ${value.articulos[index].nombre}

                                            ${value.articulos[index].precio} €

                                            <input type="number" class="form-control" value="1">

                            `)
                        });

and this create this div:

but in this array i have secondItems array and thirdItems and i need create same div with items from other arrays but mi result it´s that all content it´s duplicated:

i need to do:
block 1:
item
item
item
block 2
item
item
item
block 3
item
item
item
etc
Thanks for read and help


text:
Q: How do I prove $|\left \langle x,y \right \rangle|=\left \| x \right \|\cdot \left \| y \right \|\Leftrightarrow y=cx,c\in F$ Proving $\Leftarrow$ is easy enough, it's just a matter of plugging it right in. For $\Rightarrow$, I tried changing the right side to $\left (\left \langle x,x \right \rangle \cdot\left \langle y,y \right \rangle  \right )^{\frac{1}{2}}$, and then having $|\left \langle x,y \right \rangle|=\left \langle x,\left \langle y,y \right \rangle x \right \rangle^{\frac{1}{2}}$, but that looks off to me, and I don't know where to proceed even if it's right.

A: Define $z:=x-\frac{\left\langle y,\,x \right\rangle}{\left\langle x,\,x \right\rangle}y$. Rearrange $\left\langle z,\,z \right\rangle \geq 0$, with equality iff $z = 0$, to $\left|\left\langle x,\,y \right\rangle\right|^2 \leq \left\langle x,\,x \right\rangle \left\langle y,\,y \right\rangle$. This inherits the above equality condition, which implies $x,\,y$ are parallel (if we regard the zero vector as parallel to all vectors). Strictly speaking, we can violate $y = cx$ with $x=0\neq y$, in which case we have $x = cy$ instead with $c = 0$.

A: Note: the correct statement you should prove is $$|\left \langle x,y \right \rangle|=\left \| x \right \|\cdot \left \| y \right \|\Leftrightarrow x,y\text{ are not linearly independent}$$
(there is a distinction of cases to be made for $x=0$, for instance)

A classic approach: Consider the polynomial (in $\lambda$)
$$
P(\lambda) = \lVert x+\lambda y\rVert^2 = \langle x+\lambda y, x+\lambda y\rangle
= \lVert x\rVert^2 + 2\lambda \langle x,y\rangle + \lambda^2 \lVert y\rVert^2.
$$
It is a non-negative quadratic polynomial, so its determinant $\Delta = 4\langle x,y\rangle^2 - 4\lVert x\rVert^2\lVert y\rVert^2$ keeps a constant (non-positive) sign. This gives you Cauchy-Schwarz inequality.
Now, if you have equality above, the polynomial has determinant equal to zero (not strictly negative), so it must have a root... consider this root: it is a value $\lambda^\ast$ such that $0=P(\lambda^\ast) = \lVert x+\lambda^\ast y\rVert^2$.

A: Let $S=\mathrm{span}\{x\}$ and $P$ the orthogonal projection onto $S$. Then $Py=cx$ for some $c\in F$.
Thus
$\begin{multline}\|Py\|^2=|\langle Py,Py\rangle|=|\langle Py,y\rangle|\\=|\langle cx,y\rangle|=|c\langle x,y\rangle|=|c|\|x\|\|y\|=\|cx\|\|y\|=\|Py\|\|y\|...(*)\end{multline}$
If $Py=0$, done. if $Py\neq 0$ , then by $(*)$ we have $\|Py\|=\|y\|$. Now, by Pythagoras
$$\|y-Py\|^2+\|Py\|^2=\|y\|^2=\|Py\|^2$$
Thus, $\|y-Py\|=0$, or $Py=y$. But $Py=cx$ and done.


text:
Q: Как получить ответ от Google Maps API на русском? юзаю Google Maps Geocoding API, если делать get запрос, то локации приходят транслитом на латинеце.
$request_params = array('latlng' => $item->end_location->lat . ',' .$item->end_location->lng);
$get_params = http_build_query($request_params);
$res = json_decode(file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?'.$get_params));

Если же посылать запрос прям через браузер
https://maps.googleapis.com/maps/api/geocode/json?latlng=55.6858518,52.4851357

то всё нормально и приходит ответ локаций на русском

A: Нужно было мне подробнее читать документацию.. Добавляем в параметры
'language'=>'ru'

И наблюдаем ответ на предпочитаемом языке


text:
Q: Change background color when radio is clicked I'm trying to change the background color of a block when a radio button , which is inner the block, is clicked.
I did this but I don't understand why it dont work.
Here is the code:

$(document).ready(function() {
    $('#rad').click(function() {
        $('#label').addClass('radio-active');
    });
});
.radio-active {
    background-color: black;
    color: white;
}

      <input id="rad" type="radio" name="rad" >
      £25

Thx

A: Put this css code:
.radio-active {
    background-color: black;
    color: white;
}

with in style tag like:

A: I guess you were missing the

    <input id="rad" type="radio" name="rad" >
    £25

    <input id="rad2" type="radio" name="rad2" >
    £35

image uploaded


text:
Q: how to detect if browser is firefox with php?
Possible Duplicate:
Any php code to detect the browser with version and operating system?
how to detect internet explorer and firefox using PHP?

I need to add specific html to non firefox browsers, therefore I need to first detect if user is using firefox or not, i have to do this using php. Something along these line?
<!--[if Firefox]>
Mozilla only HTML here!
<![endif]-->

Any one? Thanks

A: php's inbuilt function get_browser  is your answer. or try using $_SERVER['HTTP_USER_AGENT'] or simply use this script http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php/

A: Use this snippet of code to retrieve the kind of browser:
if (isset($_SERVER['HTTP_USER_AGENT'])) {
    $agent = $_SERVER['HTTP_USER_AGENT'];
}

Then, compare against the user agent string.
For example, to detect "Firefox" you could do:
if (strlen(strstr($agent, 'Firefox')) > 0) {
    $browser = 'firefox';
}

A: Use the get_browser function:
http://php.net/manual/en/function.get-browser.php

A: You can use the User-Agent header in the request. Either you do a regex check on it to find Firefox specific patterns or you can use a library like WURFL that has a better chance of identifying the browser.
See this answer for an example on how to do it.

A: Use $_SERVER['HTTP_USER_AGENT'] to get user browser.

A: look in $_SERVER['HTTP_USER_AGENT']
e.g.: Mozilla/5.0 (Windows NT 5.1; rv:13.0a1) Gecko/20120206 Firefox/13.0a1


text:
Q: RegEx captures file extension when I only want the base name I'm using the following RegEx in a Mod-Rewrite command, but don't want the $1 variable to capture include the .html extension.
RewriteRule ^photo-search\/([^/]+)(/|\.html|)$ http://www.artminds.com/cgi-bin/ImageFolio4/imageFolio.cgi\?search=$1&bool\=all [H=cgi-script]

This command works exactly as intended for the following URL's
http://www.artminds.com/photo-search/outdoors  is rewritten to capture "outdoors" and properly sends just the word "outdoors" to the variable n my rewrite code.
http://www.artminds.com/photo-search/outdoors/ also captures just the word "outdoors" and inserts it without the trailing slash in my rewrite code.
But if someone enters /photo-search/outdoors.html the file extension .html gets included in the rewrite code, which triggers a soft 404, because outdoors.html is being passed through to the cgi script, and of course it doesn't find a keyword that ends with .html.
I've tried various options, but my error logs either show File Not Found or it merely passes through only "photo-search" and not the portion that follows "photo-search".
Thanks in advance.
Art Minds
Pasadena, CA

A: One fix is to make the [^/]+ part non-greedy, so that it will prefer to match as little as possible as long as the regex as a whole still matches. That way, it won't include the .html (since the .html can be matched by a later part of the regex). To do this, use +? instead of +:
RewriteRule ^photo-search\/([^/]+?)(/|\.html|)$ http://www.artminds.com/cgi-bin/ImageFolio4/imageFolio.cgi\?search=$1&bool\=all [H=cgi-script]

However, I'm wondering whether you really want this rule to be applied at all to a URL that ends in (say) .jpg? If not, then a better fix is probably to include . in the list of characters that the [^/]+ part isn't allowed to match:
RewriteRule ^photo-search\/([^/.]+)(/|\.html|)$ http://www.artminds.com/cgi-bin/ImageFolio4/imageFolio.cgi\?search=$1&bool\=all [H=cgi-script]

A: Try
 RewriteRule ^photo-search\/([^/\.]+)(/|\.html|)$
 http://www.artminds.com/cgi-bin/ImageFolio4/imageFolio.cgi\?search=$1&bool\=all
 [H=cgi-script]

Your $1 parameter matches the first group (between ()) but since the regex for that group says any character except / it also grabs the .html. By telling it to not accept .'s it will only take the string without the extension.


text:
Q: Quantum Field Theory, questions about fields and their vacuum state Are the fields in their empty state a single indivisible and static entity? I would also like to know if the gravitational field also has a vacuum state and if the other fields are permanently linked to it.
Regards

A: *

*yes, but in quantum theory the word 'static' here means that there is no evolution over time (except a global phase), it does not mean that a sequence of observations will all yield the same result

*yes; 'indivisible' in the sense that it is continuous and you can't separate one part from another so as to leave a hole where there is no quantum field

*yes, but it depends on how gravity is to be modeled and this is an open research problem

*yes, anything with energy or pressure or stress interacts with the gravitational field, so that means everything interacts with the gravitational field


text:
Q: Entity Framework - Update or Add I want to loop through a series of incoming records, check my database to see if they already exist and add or update them as appropriate. Im having little success.
    var listOfClientAccounts = model.MTAccounts.ToList(); // single DB query
    // for each of the users MTManager
    foreach (var user in users)
    {
        var clientInDb = listOfClientAccounts
                             .SingleOrDefault(c => c.Login == user.Login); // runs in memory
        var processedUser = ProcessUserRecord(user);
        //Check if the Account Login is already in the database
        if (clientInDb != null)
        {
            processedUser.MTAccountId = clientInDb.MTAccountId;
            var entry = model.Entry(processedUser);
                            model.Entry(processedUser).CurrentValues.SetValues(processedUser);
            entry.State = EntityState.Modified;
            Console.WriteLine(x + " : UPDATE : " + processedUser.Login + "(" + clientInDb.MTAccountId + ")");
        }
        else
        {
            //  Client does not exist add now
            model.MTAccounts.Add(processedUser);
            Console.WriteLine(x + " : ADD :" + processedUser.Login);

        }
    }

 model.SaveChanges();

 public MTAccount ProcessUserRecord(UserRecord user)
        {
            MTAccount DALUser = new MTAccount
            {
                BrokerServerId = 1,
                Login = user.Login,
                Group = user.Group
            };
            return DALUser;
        }

The crucial thing is that I want to keep the saveChanges call till the end of the loop as there may be hundreds of records to call, and I dont want to make hundreds of db calls.
there error is as follow:

Member 'CurrentValues' cannot be called for the entity of type
  'MTAccount' because the entity does not exist in the context. To add
  an entity to the context call the Add or Attach method of
  DbSet.

A: Ok, I worked it out,
in the original code I had:
var entry = model.Entry(processedUser);
model.Entry(processedUser).CurrentValues.SetValues(processedUser);

which was trying to update the values of the processedUser
What I should have said was this:
model.Entry(clientInDb).CurrentValues.SetValues(processedUser);

which applied the changes to the original client from database
thanks for the comments.


text:
Q: How to represent a datatable in R as a heatmap I have the following data :
library(data.table)
DT <- data.table(
  Pays = c("Austria", "Belgium", "Brazil", "Bulgaria",
           "Canada", "China", "Croatia", "Cyprus", "Czechia", "Denmark"),
  `Nouveaux cas` = c("212.2", "136.0", "143.5", "258.7", "122.8",
                      "0.0", "615.0", "299.0", "327.7", "314.5"),
  `Nouveaux décès` = c("53.8", "35.4", "14.9", "89.7", "14.2", "0.0", "79.0", "14.4", "47.3", "6.9"),
  `Évolution du nombre de cas` = c("-21.5%", "2.8%", "5.6%", "-5.2%", "4.1%", "-0.9%", "5.5%", "34.3%", "36.7%", "73.8%"),
  `Évolution du nombre de décès` = c("-20.1%", "-20.4%", "10.5%", "-8.5%", "24.1%", "NaN%", "2.9%", "63.6%", "-5.4%", "3.6%"))

> DT
        Pays Nouveaux cas Nouveaux décès Évolution du nombre de cas Évolution du nombre de décès
 1:  Austria        212.2           53.8                     -21.5%                       -20.1%
 2:  Belgium        136.0           35.4                       2.8%                       -20.4%
 3:   Brazil        143.5           14.9                       5.6%                        10.5%
 4: Bulgaria        258.7           89.7                      -5.2%                        -8.5%
 5:   Canada        122.8           14.2                       4.1%                        24.1%
 6:    China          0.0            0.0                      -0.9%                         NaN%
 7:  Croatia        615.0           79.0                       5.5%                         2.9%
 8:   Cyprus        299.0           14.4                      34.3%                        63.6%
 9:  Czechia        327.7           47.3                      36.7%                        -5.4%
10:  Denmark        314.5            6.9                      73.8%                         3.6%

I wonder the best way to get an object, to be inserted in a word file, that would be this table with one heatmap per column. I can export this table in Excel and use conditional formating to get the desired output :

Now I am unsure what is the best way to do that in R. My quick searches yielded me :

*

*Some heatmaps in ggplot2, e.g. here but it seems mainly two dimensional, and not to account for a lot of other options such as renaming columns and so on

*Various packages to do tables, e.g. here, but then I am a bit lost in all the choices. I explored a bit the gtoption a few weeks ago, but I do not recall there being this option, in addition to lacking a possibility to output vectorialized table (which would be ideal but not necessary)

A: Here's an approach with gt.
gt::data_color will only really work for numeric data if it is actually numeric, so I converted the percent columns in your data back to numeric. I used readr::parse_number because it works so easily, but you could do it manually if you want.
scales::col_numeric makes it easy to define the color scales. Change the domain = argument to modify the range.
library(gt)
library(scales)
library(readr)
DT <- DT[,lapply(.SD,readr::parse_number),by = Pays]
DT %>%
  gt() %>%
  data_color(columns = 2:3,
             colors = col_numeric(palette = c("white","red"),
                                  domain = c(0,650))) %>%
  data_color(columns = 4:5,
             colors = col_numeric(palette = c("green","yellow","red"),
                                  domain = c(-30,80))) %>%
  fmt_percent(columns = 4:5, scale_values = FALSE, decimals = 1)


text:
Q: How to use JavaScript onclick Functions with Array Index Values I am currently using an onclick function in JavaScript to display information stored in an array depending on which element a user selects on. I then need another onclick function that allows me to do the same thing (display content based on selection) but based on an array index value that was selected. The first method works well because the user selection is based off an ID. I haven't been successful with the second method because I haven't figured out how to display content based off the selection of an array index value. Using JavaScript is strongly preferred for this project.
After choosing a major (the element labeled biology) the user would then select on one of the Job Titles, say "Genetic Counselor" stored in bioArray[1] [2], and the innerHTML of bioArray [4] and bioArray[5] would then display salary information unique to that Job Title. The information that I would be displaying would be stored in a separate array for each job title - ex: geneticCounselor []
My thoughts were by using nested arrays I may find a method that allows me to display content once selected that is based on the index value. So far, I have seen methods discussing event bubbling and "this" but do not believe these methods satisfy my requirements.
See JS Bin Demo: http://jsbin.com/dolucowuwu/edit?html,css,js,output
CSS:
<!DOCTYPE html>

<meta charset="utf-8">
<title>JS Bin</title>

HTML:

Biology

Select a major from above

JavaScript:
var H4 = document.getElementsByClassName("selected"), act;

[].forEach.call(H4, function(el){
    el.addEventListener("click", function(){
       if(act) act.classList.remove("active");
       return (this.classList.toggle("active"), act=this);
    });
});

var bioArray = [
    "Biology",
    ['Common Job Titles: Biological/Lab Technician',' Medical and Health Services Manager',' Genetic Counselor'],
    "Skills in Demand: Relevant Certifications and Degree Programs Required",
    "Major Salary Range: $35,000 to $120,000 +",
    "Occupation Salary Range: Select a Job Title",
    "Average Salary: Select a Job Title"

];

    document.getElementById("bio").onclick=function() {
    document.getElementById("majorRep").innerHTML = bioArray[0];
    document.getElementById("jobs").innerHTML = bioArray[1];
    document.getElementById("skills").innerHTML = bioArray[2];
    document.getElementById("salaryRange").innerHTML = bioArray[3];
    document.getElementById("salaryRangeOC").innerHTML = bioArray[4];
    document.getElementById("salaryAvg").innerHTML = bioArray[5];
}

var geneticCounselor = [
    "Occupation Salary Range: $45,000 to $90,000",
    "Average Salary: $57,000"
];

A: I've altered most of your data and web site to create a more maintainable example:

*

*I choose to use a library called jquery, which can helps you a lot when manipulating dom elements and bind events.

*Analyze your data, remove reusable words to html, and make the data structure more meaningful.

*Add some class to control/listen to the target events more easily.

And below is what it become:

// Reform of datastructure.
var MainCategory = {
  'Biology': {
    'jobs': [' Biological/Lab Technician,', ' Medical and Health Services Manager,', ' Genetic Counselor'],
    'skills': 'Relevant Certifications and Degree Programs Required, Analysis, ANOVA, Attention to Detail, Analytical, Biological Data Collection, Data Entry, DNA Isolation/Sequencing',
    'salaryRange': '$335,000 to $120,000 +',
    'salary': '$35,000 to $120,000 +'
  },

  'Cartography': {
    'jobs': [' City Planner,', ' Natural Resource Manager,', ' Environmental Planner,', ' GIS Analyst,', ' GIS Specialist,', ' Cartographer'],
    'skills': 'Relevant Certifications and Degree Programs Required, ArcGIS Mapping Suite, Python Programming, Photogrammetry, Attention to Detail, Visual Basic/.NET',
    'salaryRange': '$40,000 to $115,000 +',
    'salary': '$35,000 to $120,000 +'
  }
};

var Jobs = {
  ' Biological/Lab Technician,': {
    'Salary': '$95,000 to $110,000',
    'AverageSalary': '$87,000'
  },
  ' Medical and Health Services Manager,': {
    'Salary': '$75,000 to $90,000',
    'AverageSalary': '$57,000'
  },
  ' Genetic Counselor': {
    'Salary': '$45,000 to $90,000',
    'AverageSalary': '$57,000'
  },
  ' City Planner,': {
    'Salary': '$775,000 to $90,000',
    'AverageSalary': '$57,000'
  }

};

// Get main element blocks
var mainSelect = $('#mainSelect');
var cart = $('#cart');
var details = $('#details');

// Put in main category info.
$.each(MainCategory, function(key) {
  var option = $('
');
  option.text(key).data('category', key).appendTo(mainSelect);
})

// Define event handler
var showDetail = function(category) {
  var categoryData = MainCategory[category];

  // Do nothing if no detail info.
  if (typeof categoryData === 'undefined') {
    details.toggle(false);
    return;
  }
  details.toggle(true);
  // Put info to each detail element
  $.each(categoryData, function(key, value) {
    var info = details.find('#' + key);
    if (key === 'jobs') {
      // Create a selectable job list.
      info.children().remove();
      $.each(value, function(id, job) {
        var jobOption = $('');
        jobOption.addClass('job').data('job', job).text(job).appendTo(info);
      });
    } else {
      info.find('span').text(value);
    }

  });

  // Set default display text for those job related info.
  details.find('.job-related span').text('Select a Job Title');
};
//
var showJobDetail = function(job) {
  var jobInfo = Jobs[job],
    jobSalary, jobAverageSalary;
  if (typeof jobInfo === 'undefined') {
    details.find('.job-related span').text('Select a Job Title');
  } else {
    jobSalary = jobInfo.Salary ? jobInfo.Salary : 'Lack of info.';
    jobAverageSalary = jobInfo.AverageSalary ? jobInfo.AverageSalary : 'Lack of info.'
    details.find('#jobSalary span').text(jobSalary);
    details.find('#jobAverageSalary span').text(jobAverageSalary);
  }
}

// Setup events.
mainSelect.on('click', 'h4', function() {
  $(this).siblings('.active').removeClass('active');
  $(this).addClass('active');
  var category = $(this).data('category');
  showDetail(category);
});
// Bind events to job list.
details.on('click', 'span.job', function() {
  var job = $(this).data('job');
  showJobDetail(job);
});
h4 {
  border: 1px solid black;
  border-radius: 8px;
  padding: 10px 2px 10px 2px;
  margin: 20px 20px 0px 20px;
  background-color: #F0F0F0;
  border-color: #F8F8F8;
  color: #505050;
  cursor: pointer;
}
.active {
  background-color: #99E6FF;
}
p {
  font-size: 1.3em;
}
.fontIncrease {
  font-size: 1.2em;
  margin-bottom: 10px;
}
.pointerClass:hover {
  cursor: pointer;
}

    Related Job Titles:

    Skills in Demand:

    Major Salary Range:

    Occupation Salary Range:

    Average Salary:

If you have question about the code, feel free to ask!

A: You question could be better explained, but I think I've got your point. There are many ways to achieve what you want, and I see no reason why you wouldn't get any closer than what you've got (apart from being lazy =P ).
Anyway, let me try to help you.
You could be working with objects. They would make your life easier. So let's build an object for the jobs:
var jobs = {
    'geneticCounselor': {
        'jobName': 'Genetic Counselor',
        'occupationSalaryRange': '$45,000 to $90,000',
        'averageSalary': '$57,000'
    },
    'biologicalLabTechnician': {
        'jobName': 'Biological/Lab Technician',
        'occupationSalaryRange': '$00,000 to $00,000',
        'averageSalary': '$00,000'
    },
    //...Keep adding jobs
};

Now you have control over the information you want to handle. If you don't know JS objects, I suggest you reading this article. Now let's create our HTML accordingly to our objects:
document.getElementById("bio").addEventListener('click', function() {
  //Access each job in our object
  for (var key in jobs) {
    //get the job object reference
    var job = jobs[key];

    //Create a HTML element do display the information
    var p = document.createElement('p');

    //Creates a reference to keep track on our 'jobs' object
    p.setAttribute('data-job', key);

    //Set the text of the element
    p.textContent = job.jobName;

    //Add function to each job
    p.addEventListener('click', function() {
     //Retrieve the obj reference in the HTML element
     var dataJob = this.getAttribute('data-job');

     //Use the HTML element reference to get the OBJ reference, where the info is stored
     var job = jobs[dataJob];

     //Set the job info into the

     document.getElementById('salaryRange').textContent = job.occupationSalaryRange;

     //Set the job info into the

     document.getElementById('salaryAvg').textContent = job.averageSalary;
    });

    //Put the element on the page
    document.getElementById('jobs').appendChild(p);
}

So my full JS is:
var H4 = document.getElementsByClassName("selected"), act;

[].forEach.call(H4, function(el){
    el.addEventListener("click", function(){
       if(act) act.classList.remove("active");
       return (this.classList.toggle("active"), act=this);
    });
});

var jobs = {
    'geneticCounselor': {
        'jobName': 'Genetic Counselor',
        'occupationSalaryRange': '$45,000 to $90,000',
        'averageSalary': '$57,000'
    },
    'biologicalLabTechnician': {
        'jobName': 'Biological/Lab Technician',
        'occupationSalaryRange': '$00,000 to $00,000',
        'averageSalary': '$00,000'
    }
};

document.getElementById("bio").addEventListener('click', function() {
  //Access each job in our object
  for (var key in jobs) {
    //get the job object reference
    var job = jobs[key];

    //Create a HTML element do display the information
    var p = document.createElement('p');

    //Creates a reference to keep track on our 'jobs' object
    p.setAttribute('data-job', key);

    //Set the text of the element
    p.textContent = job.jobName;

    //Add function to each job
    p.addEventListener('click', function() {
     //Retrieve the obj reference in the HTML element
     var dataJob = this.getAttribute('data-job');

     //Use the HTML element reference to get the OBJ reference, where the info is stored
     var job = jobs[dataJob];

    //Set the job info into the

    document.getElementById('salaryRange').textContent = job.occupationSalaryRange;

    //Set the job info into the

    document.getElementById('salaryAvg').textContent = job.averageSalary;
    });

    //Put the element on the page
    document.getElementById('jobs').appendChild(p);
}
});

Be aware that there are other ways (and better ones) to achieve these type of results. You should read some stuff about HTML / DOM manipulation with JS to have a better knowledge.

A:

// Reform of datastructure.
var MainCategory = {
  'Biology': {
    'jobs': [' Biological/Lab Technician,', ' Medical and Health Services Manager,', ' Genetic Counselor'],
    'skills': 'Relevant Certifications and Degree Programs Required, Analysis, ANOVA, Attention to Detail, Analytical, Biological Data Collection, Data Entry, DNA Isolation/Sequencing',
    'salaryRange': '$335,000 to $120,000 +',
    'salary': '$35,000 to $120,000 +'
  },

  'Cartography': {
    'jobs': [' City Planner,', ' Natural Resource Manager,', ' Environmental Planner,', ' GIS Analyst,', ' GIS Specialist,', ' Cartographer'],
    'skills': 'Relevant Certifications and Degree Programs Required, ArcGIS Mapping Suite, Python Programming, Photogrammetry, Attention to Detail, Visual Basic/.NET',
    'salaryRange': '$40,000 to $115,000 +',
    'salary': '$35,000 to $120,000 +'
  }
};

var Jobs = {
  ' Biological/Lab Technician,': {
    'Salary': '$95,000 to $110,000',
    'AverageSalary': '$87,000'
  },
  ' Medical and Health Services Manager,': {
    'Salary': '$75,000 to $90,000',
    'AverageSalary': '$57,000'
  },
  ' Genetic Counselor': {
    'Salary': '$45,000 to $90,000',
    'AverageSalary': '$57,000'
  },
  ' City Planner,': {
    'Salary': '$775,000 to $90,000',
    'AverageSalary': '$57,000'
  }

};

// Get main element blocks
var mainSelect = $('#mainSelect');
var cart = $('#cart');
var details = $('#details');

// Put in main category info.
$.each(MainCategory, function(key) {
  var option = $('
');
  option.text(key).data('category', key).appendTo(mainSelect);
})

// Define event handler
var showDetail = function(category) {
  var categoryData = MainCategory[category];

  // Do nothing if no detail info.
  if (typeof categoryData === 'undefined') {
    details.toggle(false);
    return;
  }
  details.toggle(true);
  // Put info to each detail element
  $.each(categoryData, function(key, value) {
    var info = details.find('#' + key);
    if (key === 'jobs') {
      // Create a selectable job list.
      info.children().remove();
      $.each(value, function(id, job) {
        var jobOption = $('');
        jobOption.addClass('job').data('job', job).text(job).appendTo(info);
      });
    } else {
      info.find('span').text(value);
    }

  });

  // Set default display text for those job related info.
  details.find('.job-related span').text('Select a Job Title');
};
//
var showJobDetail = function(job) {
  var jobInfo = Jobs[job],
    jobSalary, jobAverageSalary;
  if (typeof jobInfo === 'undefined') {
    details.find('.job-related span').text('Select a Job Title');
  } else {
    jobSalary = jobInfo.Salary ? jobInfo.Salary : 'Lack of info.';
    jobAverageSalary = jobInfo.AverageSalary ? jobInfo.AverageSalary : 'Lack of info.'
    details.find('#jobSalary span').text(jobSalary);
    details.find('#jobAverageSalary span').text(jobAverageSalary);
  }
}

// Setup events.
mainSelect.on('click', 'h4', function() {
  $(this).siblings('.active').removeClass('active');
  $(this).addClass('active');
  var category = $(this).data('category');
  showDetail(category);
});
// Bind events to job list.
details.on('click', 'span.job', function() {
  var job = $(this).data('job');
  showJobDetail(job);
});
h4 {
  border: 1px solid black;
  border-radius: 8px;
  padding: 10px 2px 10px 2px;
  margin: 20px 20px 0px 20px;
  background-color: #F0F0F0;
  border-color: #F8F8F8;
  color: #505050;
  cursor: pointer;
}
.active {
  background-color: #99E6FF;
}
p {
  font-size: 1.3em;
}
.fontIncrease {
  font-size: 1.2em;
  margin-bottom: 10px;
}
.pointerClass:hover {
  cursor: pointer;
}

    Related Job Titles:

    Skills in Demand:

    Major Salary Range:

    Occupation Salary Range:

    Average Salary:


text:
Q: Break Data out of one column into multiple columns I have a table full of attendance data for students, we are migrating to another student info system and the way they want the flat files to be is one row for each student for each day with all 7 periods listed out. Right now our data is stored as one record per day per period (see attached schema) What would be the best way to format this data to match what I have listed above. I'm also attaching a screenshot of how they want it (each row is a column).
Added screen shot of data.

A: take a look at PIVOT and UNPIVOT.
Here is an example

A: Ok so pivot was not what I needed. I ended up talking to a colleuge about my problem and he told me to use subqueries. So this is how I solved it!
select distinct student_id,school_year,school_number,absent_date,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='H') as daily_code,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='1') as per_1,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='2') as per_2,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='3') as per_3,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='4') as per_4,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='5') as per_5,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='6') as per_6,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='7') as per_7

FROM attend_student_detail a

Order By Absent_Date, Student_ID


text:
Q: how to check (read) crul CURLOPT field of handle? 1) Is there any method to check if CURLOPT field of a curl handle is set and if so then what its value?
Reason - I'm writing a class that should recognize if CURLOPT_POST is set. If not then dedicated method will add to url query in GET syntax to perform GET request.
2) Second reason is to read for debug all CURL parameter fields of handle that curl_exec had a problem to execute and returned an error
3) confirmation of successfully changed CURLOPT field of handle, assuming it is possible to change a field that was set before (is it?)

A: For 1), this answer should help you
For 2) you'd better use curl_error to get cURL errors
For 3), curl_setopt will overwrite previously defined options. It returns true on success and false otherwise.


text:
Q: Remove the window title color for XamRibbonWindow I have a wpf window using XamRibbonWindow class, from an old code base.
I don't know why its black color will cover the minimize, maximize, and close buttons. I am not sure if this is caused by XamRibbonWindow either.
Those buttons still works, just hidden behind the title color.

Also, if I press maximize button twice, the black color will be gone.

Anyone has similar experience and knows how to fix it?
The mainwindow.xaml is like:
<igRibbon:XamRibbonWindow x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Geomagic.Shared.UI.WPF.IFGuiService"
xmlns:igRibbon="http://infragistics.com/Ribbon"
>

<Window.Resources>
    <local:StringData x:Key="Theme" Ref="Theme"/>
</Window.Resources>

<igRibbon:RibbonWindowContentHost x:Name="_contentHost" Background="{DynamicResource ContentHostBackground}">

    <igRibbon:RibbonWindowContentHost.Ribbon>
        <igRibbon:XamRibbon/>
    </igRibbon:RibbonWindowContentHost.Ribbon>

    <local:DockManagerWindow x:Name="_dockManager"/>

</igRibbon:RibbonWindowContentHost>


text:
Q: Android - How to hide menu option for current fragment I have an ActionBar activity with a FrameLayout and a menu. when the user clicks the menu item I replace the fragment with the relevant new fragment. However, I cannot see an obvious way to remove the menu item for the selected fragment.
public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            StudyFragment startFragment = new StudyFragment();
            startFragment.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add
                                      (R.id.container, startFragment).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id) {
        case R.id.action_study:
            replaceFragment((Fragment)new StudyFragment());
            break;
        case R.id.action_list:
            replaceFragment((Fragment)new ListFragment());
            break;
        // etc
        }
        return super.onOptionsItemSelected(item);
    }

    private void replaceFragment(Fragment f) {
        FragmentTransaction transaction =
                                getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container, f);
        transaction.addToBackStack(null);

        transaction.commit();
      }

The Google documentation on changing menus says to disable the menu in onPrepareOptionsMenu - but how will I know which item has been selected?
--Solution Implemented--
Using Muhammed Refaat's solution below I added two new members to the class:
private Menu activityMenu;
private MenuItem curMenuItem;

Set them in onCreateOptionsMenu
activityMenu = menu;
curMenuItem = activityMenu.findItem(R.id.action_study);
curMenuItem.setVisible(false);

And changed them on onOptionsItemSelected
curMenuItem.setVisible(true);
curMenuItem = activityMenu.findItem(id);
curMenuItem.setVisible(false);

A: First get the item you want to remove :
MenuItem item = menu.findItem(R.id.your_action);

then set  it's Visibility false :
item.setVisible(false);

and if the problem is in getting the menu (as it's not in the fragment), you can easily get a context from the activity that contains the menu and get the menu by it.

A: Inside your fragment you will have to use setHasOptionsMenu(true); in order to access options menu from within your fragment.
Code (inside your second fragment where you wanna hide the item):
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  // TODO your code to hide item here
  super.onCreateOptionsMenu(menu, inflater);
}

Similarly, for your fragment where you want to show that MenuItem you can do the similar thing.

A: In the fragment where you want to hide the Item
@Override
public void onPrepareOptionsMenu(Menu menu) {
    MenuItem item=menu.findItem(R.id.action_search);
    item.setVisible(false);

and in onCreate() of your fragment
 setHasOptionsMenu(true);

A: Adding to Muhammed's answer above.  Once the item has been set as invisible, you may need to also disable the item. Note Google's comment: "Even if a menu item is not visible, it may still be invoked via its shortcut (to completely disable an item, set it to invisible and disabled)" under setVisible() in the MenuItem documentation.
Thus:

*

*item.setVisible(false);

*item.setEnabled (false);

A: Add below codes into your fragment
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    MenuItem item = menu.findItem(R.id.save);
    item.setVisible(false);
}

A: // create Boolean variable in the main activity
private var menuvisibile:  Boolean = true

// while navigating fragments set the menuvisibile value and use it
// variable as part of the return statement
invalidateOptionsMenu()
menuvisibile = false

override fun onCreateOptionsMenu(menu: Menu?): Boolean
    {
        val menuInflater  = menuInflater
        menuInflater.inflate(R.menu.notification,menu)
        return menuvisibile
    }

working well for me.


text:
Q: Simple database on Java I've got a task to make a simple database on a topic "basketball team" with functionality such as: deleting by ID, inserting new data, modification of information, printing all data from a file. All information should be written in a file.
I've already created createTeam() method that makes a kind of template of my default data that writes in a file.
Basically, after that, I've got trouble in deleteByID() method with deleting exact data that I need, so I'm asking you for a help
My code:
import java.io.*;

public class ChicagoBulls {

    static class Player{

        private int Id;
        private int Age;
        private String Name;
        private String Surname;
        private int Height;
        private int Salary;
        private String KPI;
        private String Shoes;
        private  int Goals;

        Player(int id, int age, String name, String surname, int height,
               int salary, String kpi, String shoes, int goals) {
            Goals = goals;
            Id = id;
            Age = age;
            Name = name;
            Surname = surname;
            Height = height;
            Salary = salary;
            KPI = kpi;
            Shoes = shoes;

        }

        public String getShoes() {
            return Shoes;
        }

        public void setShoes(String shoes) {
            Shoes = shoes;
        }

        public int getSalary() {
            return Salary;
        }

        public void setSalary(int salary) {
            Salary = salary;
        }

        public String getKPI() {
            return KPI;
        }

        public void setKPI(String KPI) {
            this.KPI = KPI;
        }

        public int getHeight() {
            return Height;
        }

        public void setHeight(int height) {
            Height = height;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getSurname() {
            return Surname;
        }

        public void setSurname(String surname) {
            Surname = surname;
        }

        public int getAge() {
            return Age;
        }

        public void setAge(int age) {
            Age = age;
        }

        public int getId() {
            return Id;
        }

        public void setId(int id) {
            Id = id;
        }
        public int getGoals() {
            return Goals;
        }

        public void setGoals(int goals) {
            Goals = goals;
        }

    }

    public void createTeam(int quantity) throws Exception {
        File newFile = new File("NewFile.txt");
        FileWriter newFileReader = new FileWriter(newFile);
        BufferedWriter bufferedWriter = new BufferedWriter(newFileReader);

        bufferedWriter.write("|ID|\t"
                + "|     AGE      |\t"
                + "|     NAME     |\t"
                + "|    SURNAME   |\t"
                + "|     HEIGHT   |\t"
                + "|    SALARY    |\t"
                + "|     KPI      |\t"
                + "|    SHOES     |\t"
                + "|    Goals     |\t\n");
        int counter = quantity;
        for (int i = 0; i <= quantity; i++) {

            Player defaultPlayer = new Player(i, 19, "DefName", "DefSurname", 180, 6000, "Good", "Nike", 0);

            if (defaultPlayer.getId()<=9) {
                bufferedWriter.write("|0" + defaultPlayer.getId() + "|\t");
                bufferedWriter.write("|" + defaultPlayer.getAge() + "              |\t");

                bufferedWriter.write("|" + defaultPlayer.getName() + "      |\t");
                bufferedWriter.write("|" + defaultPlayer.getSurname() + "      |\t");
                bufferedWriter.write("|" + defaultPlayer.getHeight() + "                |\t");
                bufferedWriter.write("|" + defaultPlayer.getSalary() + "              |\t");
                bufferedWriter.write( "|" + defaultPlayer.getKPI() + "         |\t");
                bufferedWriter.write( "|" + defaultPlayer.getShoes() + "             |\t");
                bufferedWriter.write( "|" + defaultPlayer.getGoals() + "                |\t");

            }else{
                bufferedWriter.write("|" + defaultPlayer.getId() + "|\t");
                bufferedWriter.write("|" + defaultPlayer.getAge() + "              |\t");

                bufferedWriter.write("|" + defaultPlayer.getName() + "      |\t");
                bufferedWriter.write("|" + defaultPlayer.getSurname() + "      |\t");
                bufferedWriter.write("|" + defaultPlayer.getHeight() + "                |\t");
                bufferedWriter.write("|" + defaultPlayer.getSalary() + "              |\t");
                bufferedWriter.write( "|" + defaultPlayer.getKPI() + "         |\t");
                bufferedWriter.write( "|" + defaultPlayer.getShoes() + "             |\t");
                bufferedWriter.write( "|" + defaultPlayer.getGoals() + "                |\t");

            }

           bufferedWriter.newLine();

        }
        bufferedWriter.close();
        newFileReader.close();

    }
    public void deleteByID(int id) throws Exception {

        FileReader file = new FileReader("NewFile.txt");
        BufferedReader bufferedReader = new BufferedReader(file);
        String idLine = bufferedReader.readLine();
        int idIndex = idLine.indexOf(id);
        int nextIdIndex = idLine.indexOf(id + 1);

    }
}

Main
public class Main {

    public static void main(String[] args) throws Exception {
        ChicagoBulls team = new ChicagoBulls();
        team.createTeam(30);

    }
}

Thank you in advance.

A: I think the logic behind your execution is a bit too complicated to be understood without further explanations on your part. From what i gathered on your needs, i would suggest creating multiple constructors for the Player class - one requiring no input and returning a "Default" player with default characteristics, the other one with the ability to specify goals, shoes, etc.
After that, each of your teams can be represented as a Set<> of players. This would make iterating for each of the elements (players) easier, as well as provide a natural way of removing players from the team. You can read more about the implementation of this structure in the Java documentation here.


text:
Q: Blogdown doesnt render properly on netlify (theme tranquilpeak) The tranquilpeak website doesnt render properly on netlify even though it looks fine locally. screen shots are below.
My repo is located  here.  Any help would be greatly appreciated.
It took me multiple trials and errors to get my site to work fine locally.  The previous attempts  lead to the same result as you can see on the netlify picture.
Successful local attempt:
a) create an empty folder
b) setwd(folder)
c) new_site(theme = "kakawait/hugo-tranquilpeak-theme")
d) create a project in the existing folder
e) init a git repository in this folder
Previous attemps:
- creating a generic project, then using new_site(theme = "kakawait/hugo-tranquilpeak-theme")
- creating a new "website using blogdown" project, asking for the "kakawait/hugo-tranquilpeak-theme" theme.
Screenshots
serve_site:

netlify:

A: Your issue comes from your asset paths being built to look for them at your base url path set in config.toml, which happens to be your old server.
During development on Netlify, Hugo works well for me by changing my baseURL.
config.toml
# baseURL = "https://www.simoncoulombe.com/"
baseURL = "/"

Then you can always change it back once you have the domain pointing to Netlify.
Note: add your public folder to your .gitignore when hosting on Netlify. public will get built by your build command.


text:
Q: Python: Pip command is not recognized Here is a screenshot I took.

When I try to use pip in command prompt I get the following error message:
pip is not recognized as an internal or external command, operable program or batch file.
I already checked this thread: How do I install pip on Windows?
All I could find there was I had to add "C:\PythonX\Scripts" to my classpath, where X stands for python version.
As you can see on my screenshot I already have this path. I already tried restarting the computer but that didn't work, o.O. The screenshot also shows my C:\Python27\Scripts folder.
Does anyone know what I am doing wrong?

A: Go to C:\Python27\Scripts
Now select the url bar and replace whole content with cmd
This way you directly reach to the directory where pip is available in command prompt
Now type  pip install Django==1.8.5
it will download and install Djanog

A: I had the same exact problem, but typing your command in the "Scripts" folder fixed it!
In other words:

*

*Open command prompt (right click windows start menu and click on "Command Prompt (Admin)"

*Use "cd" command to change directory to where python is installed, but go to your scripts folder (for me, this is cd C:\Program Files\PythonXX\Scripts where the XX is the version number of Python)

*Once in "Scripts" folder, type pip install cython and press enter

A: what I did is for example in the command prompt or cmd in windows:
py -m pip install pygame

A: There is a space before the last path entry, right after the previous semicolon, that is causing the problem.

A: It started working for me when I added ; in PATHEXT  after .PY

A: 1) browse here - C:\Python27\Scripts
2) open the cmd window/terminal (shift+'right click')
3) type pip install django

A: 1) open cmd as an administrator
2) enter: cd c:\python27\scripts (go to python and shift right click on folder. Than copy to path)
3) press enter
4) pip install

A: *

*Add "your python path"\Scripts to PATH variable. See How to set path variable

*Don't forget to restart the command prompt.
Now pip will work in any path.

A: Go to your Python Script Path, copy the path, go to CMD and type cd "paste the path you copied".
type pip --version
You will see the version of pip your system is running.

A: *

*Check if you have python installed properly.

*next install pip using
a) Download get-pip.py to a folder on your computer.
b) Open a command prompt and navigate to the folder containing get-pip.py.
c) Run the following command:
python get-pip.py

Pip is now installed!

*Copy the path of executable file in environment variable. It is the Script folder path where python is installed. like
C:Programs\Python\Python35-32\Scripts OR
C:\Users(username)\AppData\Local\Programs**\Python\Python35-32\Scripts**

*Restart your command prompt and its done


text:
Q: Should we conduct post-hoc tests when there is a significant interaction but no significant main effects? I have data showing outcomes of some treatment on different people grouped by sex and age (grouped into: infant, child, adult). I need to investigate if there is any difference in outcome among age groups or between sexes.
I used:
model <- aov(data$outcome ~ data$sex*data$age)
summary(model)

and found that neither sex nor age were significant on their own, but the interaction term was significant.
I read about the Tukey test so I tried:
TukeyHSD(model)

and found that none of the differences were significant. Was this the right thing to do? Should my conclusion be that there is no significant difference or is there more I should do?

A: I think your conclusion should be that there is a significant interaction but that this is not significant after accounting for multiple testing.
But your emphasis should be on the size of the interaction and what it means rather than whether p = 0.04 or 0.07 or whatever. I would calculate the predicted level of the outcome for men and women of different ages (say, the 3 quartiles of age) and see if the differences were of substantive import.
Of course, there could also be nonlinear effects, so I would plot the data in various ways. E.g. you could plot age on the x axis, outcome on the y axis and color the dots blue for males and red for females, then look and see what is going on. You could add loess lines for males and females and see if a) Those lines are roughly parallel and b) If they are roughly straight.


text:
Q: Keeping output from ModelBuilder in projected coordinate system of input? My model input is a point feature class with groups of points which need to be sorted according to their unit_id and then a Minimum_Bounding_Geometry tool run to generate a polygon for each unit_id which is then saved in a Feature Dataset.
This all works in the model attached except my input point layer is a projected UTM coordinate system. However the output polygons are not projected. The reason this matters is that I want to use the auto-generated shape_Area attribute value but for that value to be a sqm area, I believe I need it to be in a projected coordinate system.

A: You say your output polygons are going into a Feature Dataset.
As per the documentation:

When creating a new feature dataset, you must define its spatial
  reference. This includes its coordinate system—either geographic or a
  specific projection—as well as coordinate units and tolerances for
  x,y; z-; and m-values. All feature classes in the same feature dataset
  must share a common coordinate system, and x,y coordinates of their
  features should fall within a common spatial extent.

Try setting the coordinate system in your Feature Dataset to a projected coordinate system.


text:
Q: How to add Order By in Complex SQL queries when grabbing records using ASP I have a rather complex SQL statement that has multiple joins and I need to be able to add an order by in the end.
<%
Set rsProdInfo = Server.CreateObject ("ADODB.Recordset")

"
SELECT Company_Main.Company_Name,
       Company_Main.Company_Website,
       Practice_Areas.Practice_Area_ID,
       Practice_Areas.Practice_Area
FROM Practice_Areas
INNER JOIN ((Locations
             INNER JOIN (Company_Main
                         INNER JOIN Company_Location_CK ON Company_Main.Company_ID = Company_Location_CK.Company_ID) ON Locations.Location_ID = Company_Location_CK.Location_ID)
            INNER JOIN Company_Practice_CK ON Company_Main.Company_ID = Company_Practice_CK.Company_ID) ON Practice_Areas.Practice_Area_ID = Company_Practice_CK.Practice_Area_ID
WHERE Practice_Areas_CK.Practice_Area_ID=
" & intPractice_Area_ID

rsProdInfo.Open prodSQL, Conn
%>

I need to add an ORDER BY Company_main.Company_name after the WHERE statement but all I get is errors when I do this. Is there any way to get around this problem or is there another way to sort the data?
I tried adding this:
WHERE Practie_Areas_CK.Practice_Area_ID Order BY Company_main.Company_name =" & intPractice_Area_ID

The error I am getting is:

Microsoft Access Database Engine error '80040e07' Data type mismatch in criteria expression.
  /product.asp, line 45

A: Your whole syntax is just wrong. Proper SQL syntax in your case would be:
"WHERE Practie_Areas_CK.Practice_Area_ID=" & intPractice_Area_ID & " Order BY Company_main.Company_name"

I strongly recommend you to visit some basic SQL tutorials.

A: Have you tried running it without the ORDER BY?
If you are still getting the error, something else might be wrong.


text:
Q: Memory error when appending to list in Python I have a list of 8000 website urls. I would like to scrape the text off of the websites and save everything as a csv file. To do this i wanted to save each text-page in a list. This is my code so far which is producing and "MemoryError".
import os
from splinter import *
import csv
import re
from inscriptis import get_text
from selenium.common.exceptions import WebDriverException

executable_path = {'executable_path' :'./phantomjs'}
browser = Browser('phantomjs', **executable_path)
links = []

with open('./Hair_Salons.csv') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')
    for row in spamreader:
        for r in row:
            links.append(r)

for l in links:
    if 'yelp' in l:
        links.remove(l)

df = []

for k in links:
    temp = []
    temp2 = []
    browser.visit(k)

    if len(browser.find_link_by_partial_text('About'))>0:
        about = browser.find_link_by_partial_text('About')
        print(about['href'])
        try:
            browser.visit(about['href'])
            temp.append(get_text(browser.html)) # <----- This is where the error is occuring
        except WebDriverException:
            pass
    else:
        browser.visit(k)
        temp.append(get_text(browser.html))
    for s in temp:
        ss = re.sub(r'[^\w]', ' ', s)
        temp2.append(ss)

    temp2 = ' '.join(temp2)
    print(temp2.strip())

    df.append(temp2.strip())

with open('Hair_Salons text', 'w') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(df)

How can i avoid getting a memory error?

A: If you can't hold all your data in memory, then don't.
At a high level, your code has this structure
for k in links:
    temp = []
    temp2 = []
    browser.visit(k)

    # do stuff that fills in temp

    for s in temp:
        ss = re.sub(r'[^\w]', ' ', s)
        temp2.append(ss)

    temp2 = ' '.join(temp2)
    print(temp2.strip())

    df.append(temp2.strip())

with open('Hair_Salons text', 'w') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(df)

So, you put lots of stuff into a data frame, then write it - you don't use it in the loop. Instead of the df.append(temp2.strip()) write to the file there.
Make you you either open the file once, outside the loop (perhaps more sensible) or open for appending (using 'a' instead of 'w').


text:
Q: What are the actual precise rules for how log4j reads config setting names? I found our log4j config was inconsistently using uppercase or lowercase letters for starting options. When I tried to make them consistent, I found that sometimes it wouldn't let me use the case I wanted to use.
So of course I went to the documentation, which says:

... any setter method in FooBarAppender corresponds to a configurable
  option. For example, in RollingFileAppender the setMaxBackupIndex(int
  maxBackups) method corresponds to the maxBackupIndex option. The first
  letter of the option can be upper case, i.e. MaxBackupIndex and
  maxBackupIndex are equivalent but not MAXBACKUPIndex nor
  mAXBackupIndex.

But sometimes this paragraph is a lie. For example, this is OK:
log4j.appender.MY_LOG.layout=org.apache.log4j.EnhancedPatternLayout

But this is not OK:
log4j.appender.MY_LOG.Layout=org.apache.log4j.EnhancedPatternLayout

My question is, what is the complete list of specific situations for which this paragraph in their docs is a lie, or alternatively, how can I figure out which style I have to use without reading the log4j source code?


text:
Q: pyinstaller: ModuleNotFoundError: No module named 'cv2' I am trying to create a simple software (with pyinstaller) that activates the computer camera, but I am stuck with the error ModuleNotFoundError: No module named 'cv2'. But when I run the same code using command prompt it runs perfectly as I would want.
import cv2
import tkinter as tk

def openCamera():
    video = cv2.VideoCapture(0)
    while True:
        _, frame = video.read()
        cv2.imshow("Camera display", frame)
        if cv2.waitKey(1) & 0xff == ord('q'):
            break
    video.release()
    cv2.destroyWindow("Camera display")

main_window = tk.Tk()#.title("My PC Camera")
activate_camera = tk.Button(text="Activate camera",command=openCamera).pack()
close = tk.Button(text="Close",command=main_window.quit).pack()
main_window.mainloop()

I used the following command to create an executable, which ran successfully.
$ pyinstaller --onefile test_camera.py

But, when I try to run the executable file generated it prints the following message to the console:
Traceback (most recent call last):
  File "test_camera.py", line 1, in <module>
ModuleNotFoundError: No module named 'cv2'
[8876] Failed to execute script test_camera

Error Message
I think I have opencv-python well installed according to the code below
>>> import cv2
>>> cv2.__version__
'4.3.0'
>>>

screenshot

What could I be missing?

A: I hate to be that guy, but you've installed cv2 correct?
IIRC there's a couple different "opencvs" you can download, I believe the correct one is:
pip install opencv-python

My second thought is that you could be in a virtual environment that doesn't have OpenCV2. Considering tkinter is a part of the standard library, the only non-standard library here is OpenCV2.

A: Wow! I needed to upgrade my pyinstaller just.
I run this code
pip install --upgrade pyinstaller

And now I get what I wanted though the size of the software is not it!

A: pyinstaller 4.7 and pyinstaller-hooks-contrib 2021.4 do not support opencv.
pyinstaller 4.5.1 and pyinstaller-hooks-contrib 2021.3 should be used.
pip uninstall pyinstaller
pip install pyinstaller==4.5.1

pip uninstall pyinstaller-hooks-contrib
pip install -U pyinstaller-hooks-contrib==2021.3

A: I found I was confusing the environments in which I was running.


text:
Q: Slow array operations I'm a quite new MatLab programmer, so this might be an easy one.. :)
I'm trying to generate a script, that will be able to read any number of XYZ-files, in any order, into a array, and arrange them in the array according to the X and Y coordinates given in the file..
My attempt is to use Load to get the files into a array, and after that, read through the array and, as explained, use the X and Y coordinate as the locations in a new array..
I've tried presetting the array size, and also I'm subtracting a value from both X and Y to minimize the size of the array (fullArray)
%# Script for extraction of XYZ-data from DSM/DTM xyz files

%# Define folders and filter
DSMfolder='/share/CFDwork/site/OFSites/MABH/DSM/*.xyz';
DTMfolder='/share/CFDwork/site/OFSites/MABH/DTM/*.xyz';

%# Define minimumvalues, to reduce arrays.. Please leave some slack, for the
%#  reduction-algorithm..
borderX=100000;
borderY=210000;

%% Expected array-size
expSizeX=20000;
expSizeY=20000;

%# Program starts.. Please do not edit below this line!
files=ls(DSMfolder);

clear fullArray
fullArray=zeros(expSizeX,expSizeY);

minX=999999999;
minY=999999999;
maxX=0;
maxY=0;

disp('Reading DSM files');
[thisFile,remaining]=strtok(files);
while (~isempty(thisFile))
    disp(['Reading: ' thisFile]);
    clear fromFile;
    fromFile=load(thisFile);
    for k=1:size(fromFile,1)
        tic
        fullArray(fromFile(k,1)-borderX,fromFile(k,2)-borderY)=fromFile(k,3);
        disp([k size(fromFile,1)]);
        if (fromFile(k,1)<minX)
            minX=fromFile(k,1);
        end
        if (fromFile(k,2)<minY)
            minY=fromFile(k,2);
        end
        if (fromFile(k,1)>maxX)
            maxX=fromFile(k,1);
        end
        if (fromFile(k,2)>maxY)
            maxY=fromFile(k,2);
        end
        toc
    end
    [thisFile,remaining]=strtok(remaining);
end

As can be seen, I've added a tic-toc, and the time was 3.36secs for one operation!
Any suggestion on, why this is so slow, and how to improve the speed.. I need to order 2x6,000,000 lines, and I can't be bothered to wait 466 days.. :D
Best regards
Mark

A: Have you considered using a sparse matrix?
A sparse matrix in matlab is defined by a list of values and their location in the matrix -
incidentally this matches your input file perfectly.
While this representation is generally meant for matrices which are truly sparse, (i.e. most of their values are zeros), it appears that in your case it would be much faster to load the matrix using the sparse function even if it is not truly sparse.
Since your data is organised in such a way (location of every data point) my guess is it is sparse anyway.
The function to create a sparse matrix takes the location as columns so instead of a for loop your code will look something like this (this segment replaces the whole for loop):
minX = min(fromFile(:,1);
maxX = max(fromFile(:,1);
minY = min(fromFile(:,2);
minY = max(fromFile(:,2);
S = sparse(fromFile(:,1) - borderX, fromFile(:,2) - borderY, fromFile(:,3));

Note that the other change I've made is calculating minimum / maximum values directly from the matrix - this is much faster than going over a for loop, as operating on vectors and matrices unleashes the true power of matlab :)
You can perform all sorts of operations on the sparse matrix, but if you want to convert it to a regular matrix you can use the matlab full function.
More information here and there.


text:
Q: Unable to get property 'pingInterval' of undefiened null reference I submit a form to take objects from database.
I need to add varbinary(MAX) type (image) column inside json string, and send it via WebMethod to Ajax to display in the page, with the rest of the properties of the object. So in the class its string type instead of byte[] type.
In the encoding part I receive Javascript runtime Error:

Unable to get property 'pingInterval' of undefiened null reference.

 <form id="form1" runat="server">
   Arrival:
   <input type="text" id="txtArrival" />
        departure:
   <input type="text" id="txtDeparture" />
   Nob:
     <input type="text" id="txtNob" />
     <input type="button" id="btnSubmit" value="Get Rooms" />
 </form>

Class:
public int ID { get; set; }
public string RoomType { get; set; }
public string RoomNumber { get; set; }
public string RoomTitle { get; set; }
public decimal Price { get; set; }
public string ServiceName { get; set; }
public string Photo { get; set; }

Ajax:
$(document).ready(function () {
    $(function () {
        $("#btnSubmit").click(function () {
            var arrival = $("#txtArrival").val();
            var departure = $("#txtDeparture").val();
            var nob = $("#txtNob").val();

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "WebForm2.aspx/GetRooms",
                data: "{'arrival':'" + arrival + "','departure':'" + departure + "','nob':'" + nob + "'}",
                dataType: "json",
                success: function (data) {
                    alert(data.d);

                },
                error: function (result) {
                    alert("Error!");
                }
            });
        });
    });
});

WebMethod:
[WebMethod]
        public static string GetRooms(string arrival, string departure, string nob)
        {
            string val = "";
            DateTime d1 = Convert.ToDateTime(arrival);
            DateTime d2 = Convert.ToDateTime(departure);
           int noib=Convert.ToInt32(nob);
            var jSerialize = new JavaScriptSerializer();
            List<Room> lst = new List<Room>();
            using (SqlConnection con = new SqlConnection("Server=.;Database=ResDB;Trusted_Connection=True;"))
            {
                using (SqlCommand cmd = new SqlCommand("roomsAvailable", con))
                {
                    cmd.Parameters.AddWithValue("@arr", d1);
                    cmd.Parameters.AddWithValue("@dep", d2);
                    cmd.Parameters.AddWithValue("@nob", noib);
                    cmd.CommandType = CommandType.StoredProcedure;
                    con.Open();
                    SqlDataReader sr = cmd.ExecuteReader(); ;
                    while (sr.Read())
                    {
                        Room r = new Room();
                        r.ID = Convert.ToInt32(sr["ID"]);
                        //objects..
                        if (sr["Photo"] != System.DBNull.Value)
                        {
                            byte[] p = (byte[])sr["Photo"];
                            r.Photo = Convert.ToBase64String(p);// error here
                        }

                        lst.Add(r);
                        val = jSerialize.Serialize(lst);
                    }
                    con.Close();
                }
            }
            return val;
        }

Error is in this statement in WebMethod:
 r.Photo = Convert.ToBase64String(p);

A: After changing JQuery hosted file to newer version,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

Error disappeared!


text:
Q: How can I copy a text from a sfml window? I've got this sfml window that displays a text and now I want to make it markable so that you can copy the text.
Any ideas how to do that?

A: If you just want to copy everything then just use
sf::Clipboard::setString(your_string_here);

If you want more features, here are some I implemented when I programmed a Code Editor in SFML.
I stored two indexes, the first is where the selection begins, and the second is where the section ends.
So in the string Hello World!, if you wanted to select World you would set the begin index to 6, and the end index to 10 or 11 (depending on whether you include the final character or not).
I render this using an sf::RectangleShape, since my editor supported multiple line selection boxes the code is more complicated, but for your example you would want to get the position of each character. I used my own text renderer, but SFML's sf::Text::findCharacterPos() should be able to help with that.

Next the copy part, this is just
sf::Clipboard::setString(getSelected());

where getSelected() is
return std::string::substr(selection_begin, selection_end - selection_begin);

If you want pasting as well then it is also simple:
eraseSelected();
insertStringAtCursor(sf::Clipboard::getString());

Which are both simple string operations as well (std::string::erase and reset the selection indexes, and std::string::insert).
Finally, to let the user change what is selected, either holding shift and pressing the arrow keys or clicking and dragging are both common ways, the former being easier than the latter.
For the former, check if shift is held and then if left or right is pressed update the indexes.
For the latter, you will need to handle mouse events and dragging. When dragging begins, set one of the indexes, whilst the mouse is moving and is dragging set the other index.


text:
Q: This message is flooding my syslog, how to find where it comes from? When I run dmesg this comes up every second or so:
[22661.447946] [UFW BLOCK] IN=eth0 OUT= MAC=ee:54:32:37:94:5f:f0:4b:3a:4f:80:30:08:00 SRC=35.162.106.154 DST=104.248.41.4 LEN=40 TOS=0x00 PREC=0x00 TTL=37 ID=52549 DF PROTO=TCP SPT=25 DPT=50616 WINDOW=0 RES=0x00 RST URGP=0

How can I trace what is causing this message?

A: The existing answer is correct in its technical analysis of the firewall log entry, but it's missing one point that makes the conclusion incorrect.  The packet

*

*Is a RST (reset) packet

*from SRC=35.162.106.154

*to your host at DST=104.248.41.4

*via TCP

*from his port SPT=25

*to your port DPT=50616

*and has been BLOCKed by UFW.

Port 25 (the source port) is commonly used for email.  Port 50616 is in the ephemeral port range, meaning there's no consistent user for this port.  A TCP "reset" packet can be sent in response to a number of unexpected situations, such as data arriving after a connection has been closed, or data being sent without first establishing a connection.
35.162.106.154 reverse-resolves to cxr.mx.a.cloudfilter.net, a domain used by the CloudMark email filtering service.
Your computer, or someone pretending to be your computer, is sending data to one of CloudMark's servers.  The data is arriving unexpectedly, and the server is responding with a RST to ask the sending computer to stop.  Given that the firewall is dropping the RST rather than passing it through to some application, the data that's causing the RST to be sent isn't coming from your computer.  Instead, you're probably seeing backscatter from a denial-of-service attack, where the attacker is sending out floods of packets with forged "from" addresses in an attempt to knock CloudMark's mail servers offline (perhaps to make spamming more effective).

A: The messages stems from UFW, the "uncomplicated firewall" and it tells you that someone

*

*from SRC=35.162.106.154

*tried to connect to your host at DST=104.248.41.4

*via TCP

*from their port SPT=25

*to your port DPT=50616

*and that UFW has successfully BLOCKed that attempt.

According to this site
the source address 35.162.106.154 is some Amazon machine (probably an AWS).
According to this site
the port 50616 may be used for Xsan Filesystem Access.
So it's an attempt from IP=35.162.106.154 to access your files. Quite normal
and nothing to be really worried about because that's what firewalls are for:
rejecting such attempts.


text:
Q: heroku router - - at=error code=H13 desc="Connection closed without response" method=GET path=/favicon.ico I received this error on heroku using Rack and Sinatra:
heroku router - - at=error code=H13 desc="Connection closed without response" method=GET path=/favicon.ico

I fixed it by adding this line to my config.ru and adding a favicon.ico
map "/favicon.ico" do
    run Rack::File.new("./images/favicon.ico")
end

Is this solution acceptable, or is there a better way to handle this? It seemed a bit odd to me that this is treated as an error H13 "connection closed without response". I wouldn't have thought a favicon.ico would always be needed.


text:
Q: Submenu toggles, top level link does not work I'm having an issue with my mobile menu and submenu.
On mobile view, when clicking the top-level link, my sub-menu toggles open to show the sub-links but now the sub-links do not work and the top level link does not work (it does not go to its URL).
Unfortunately, I cannot manually overwrite the HTML menu structure so I tried adding a caret link (using JQuery) to make the submenu appear when clicking a caret. But, it did not work. Maybe, I could append or prepend a button link (with JQuery) to the left side of the top level menu item (li) to make that a button or caret which toggles the submenu while still allowing the top level link to go to its URL. I hope that explains it all well. I appreciate any help. Thank you.
/HTML/
<#nav id="nav">

Visit

Visit Sublink One

Visit Sublink Two

Visit Sublink Three

Events

Events Sublink One

Events Sublink Two

Events Sublink Three

/JQuery/
//Add caret to top level mobile menu item
  $(document).ready(function () {
    if ($(window).width() < 960) {
  $('#nav li>:not(ul)').addClass('open-submenu');
    }
 });

/* This is used to show the sub-nav on mobile */
$(function(){
   $('.open-submenu').on('click', function(e){
       if(Modernizr.mq('screen and (max-width:767px)')) {
        e.preventDefault();
        $(this).next($('.sub-menu')).slideToggle();
       }
   })

});

A: If I understand correctly
$(function() {

    var isNotMobile = $(window).width() > 786;

    $('.menu-item').each(function() {

        var item = $(this);
        var button = $('.open-submenu', item);
        var subMenu = $('.sub-menu', item);

        button.on('click', function(event) {
            if (isNotMobile) return true;
            event.preventDefault();
            subMenu.slideToogle();
            return false;
        });

    });
});

A: I solved my submenu issue with lots of trial and error. The solution was quite simple, but it's been a while since I coded JQuery. I hope this helps someone else with a similar code issue:
/** HTML **/

Top Level Link

Submenu

Submenu

Submenu

Top Level Link

Submenu

Submenu

Submenu

/** JQuery **/
//Add button to all top level links that have a submenu
  $(document).ready(function () {
   if ($(window).width() < 960) {
  $('.sub-menu').before($('<button class="submenu-button"></button>'));

  $('.sub-menu').hide();

  $('.submenu-button').click(function () {
    $(this).next('.sub-menu').slideToggle();
   });
  }
});

/** CSS **/
.submenu-button {
   width: 60px;
   height: 54px;
   background-color: transparent;
   border: 0;
   text-align: center;
   position: absolute;
   right: 0;
   z-index: 9999;
   font-weight: 700;
}

.submenu-button:after {
    color: #fff;
    content: ' ▾';
    display: flex;
    justify-content: center;
  }

}


text: Q: Localization of multiplicity in algebraic geometry first a disclaimer: I am not an expert in alg. geometry so please don't shoot. Suppose X is a closed  subscheme (not nec. reduced, and $dim >0$) of a smooth (projective if you want) variety Y. Suppose (for simplicity) that X is pure dimensional and Z is an irreducible component of X. The multiplicity of Y along X at Z, denoted $(e_XY)_Z$ can be computed either via the Hilbert-Samuel polynomial or Segre classes of the normal cone (Fulton Example 4.3.4). This seems to be a global description of the multiplicity. My question is whether one can localize and compute this quantity at a generic point of Z? A related question: the fibers of the normal cone $C_XY$ are generically isomorphic  along Z? Any (newer) reference for a more indepth study of $C_XY$?


text:
Q: Extract Data From Second Line of Output I have a table that contains message_content. It looks like this:
message_content | WFUS54 ABNT 080344\r\r
                | TORLCH\r\r
                | TXC245-361-080415-\r

How would I extract only the 2nd line of that output(TORLCH)? I've tried to shorten the output to a certain number of characters but that ultimately doesn't provide what I want. I've also tried removing carriage returns and new lines. I am outputting my results to a CSV I could manipulate with Python, but was wondering if there's a way to do it in the query first.
Based on other examples, it seems like I could use a regular expression to maybe do this? Not sure where to start with learning that though.

A: you can split the line into an array, then take the second element:
(string_to_array(message_content, e'\r\r'))[2]

Online example: https://rextester.com/MDYLXB40812


text:
Q: Stop printing the output of Counter() after a given number of lines Trying to write a program that prints the n most common items in a list depending on how many the user wants to see, and prints more if the last items have the same frequency.
This is what i have written:
num = int(input("Enter Number"))
i = 0
wordsInList = [word1, word2, word2, word3, word1]
catagory = Counter(list)
catagory.keys()
for key, value in catagory.items(): #set the frequency to value and word to key
    if i <= num or lastValue == value: #(Issue with code)If the required number of values have been printed, stop printing
        print('{:<5d}{:<15s}'.format(value, key))
        lastValue = value
        i =+ 1

The problem with this is that as soon as that print statement is run, it prints all lines of the count().

A: You could make use of the built-in function most_common for the Counter class (reference):
num = int(input("Enter Number"))
list = [word1, word2, word2, word3, word1]
counts = Counter(list)

most_common = counts.most_common(num)

# additional requirement by OP
# of having more results if last items have same frequency

most_common_values = [elt[1] for elt in most_common]

ret = []
for k, v in most_common.items(): # python 3.5+
    if v in most_common_values:
        ret.append((k,v))

print(ret)


text:
Q: How to assign drivers and passengers to cars using google script Hello I have about 120 employees working on two shifts and living in 4 cities to which they drive with company cars(9 people van, so driver + 8 passengers, the cars do not always have to be full).
I have prepared a sheet with two tabs. On the first I have:

*

*Name of the empleyee in column A

*City they live in in column B

*Whether they have drivers' license(yes/no) in column C

*Whether they are on vacation(yes/no) in column D

And on another tab I have created a table with a car registration plate(B1) and direction it drives to in cell B2.
I am trying to create a script that will(on button press, one button per car) push the data into D2:D10 based on if:
People are living in the same city AND they are not on vacation AND at least one of them has drivers' license.
I am not sure whether I even have the right idea for that script(or what to use to push the data) because the only script I have ever written was to archive a sheet and clear cells in the original one.
I would like to get some guidance on:

*

*What I am doing is correct

*How to take the data that will pass the if conditions and put it into the table

Here is a link to a copy of the sheet
function updateCar1() {
let ss = SpreadsheetApp.getActiveSpreadsheet();
let range = ss.getRange("A2:D61");
let town = ss.getCell("cars!B2");

for(range){
if(ss.getCell("cars!B2")==town && ss.getRange("D2:D61")=="No" && ss.getRange("C2:C61")=="Yes"){

}
}
}

A: Your idea is correct, the remaining issue is how to loop through a range
For this

*

*first you need to get the values of the range, since you cannot loop through a range without it

*then you need to loop through the rows of the 2D value range

*for each row, you can access the values in the respective columns by their indices starting with 0 for the first column (in your case A)

Sample:
function updateCar1() {
  let ss = SpreadsheetApp.getActiveSpreadsheet();
  let range = ss.getRange("A2:D61");
  let values = range.getValues();
  let town = ss.getRange("cars!B2").getValue();

  for(var i = 0; i < values.length; i++){
    if(values[i][1] == town && values[i][3] =="No" && values[i][2] =="Yes"){
      //do something
    }
  }
}


text:
Q: onCreate() is not overridden when extending Fragment I have this code:
public class CrimeListFragment extends Fragment {
    private RecyclerView mCrimeRecyclerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_crime_list, container, false);

        mCrimeRecyclerView = (RecyclerView) view
                .findViewById(R.id.crime_recycler_view);
        mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        return view;
    }
}

I know that when creating fragment, you separately implement onCreate() and onCreateView(). However, onCreate() is obviously missing here.
Why is that?

A:
you separately call onCreate() and onCreateView()

No, you don't call either. The Fragment lifecycle calls them.

onCreate is not needed to be implemented on a simple Fragment class, only Activity classes
As for the title of your question - it should be called if you add that Fragment to an Activity.

A: Both onCreate() and onCreateView() can be overridden by you.

*

*onCreate() is more optional and you can use to instantiate some variables (but you hardly need to override it).

*onCreateView() is mandatory since you must inflate the view that you want and return it (like return view;).
In the docs:

onCreate()
  The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
  onCreateView()
  The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.

You can also check the Fragment Life Cycle.
As you can see in picture below, in case of returning from back stack, only onCreateView() is called again... So, you can use onCreate() to run some code that can be executed only once (when Fragment is created... like configure some array or something like that)...
Then, you leave onCreateView() just to refresh/inflate the Views before displaying it to the user.
But again: onCreate() is not usually overriden and there's no problem with that... Is always up to you...
: