Is there a way to link a menu item to the edit page of the last article?

Question: I want to create a menu item linked to the edit page of the last article.
I created a view and added filters to get the last article. I added only the field node path to the view.
But how can I get the value of that path field and put it in the URL of my menu item?
Answer: Yep!
Create a view that loads the single last published article,  style the view to look like your regular node page and then add a link to the view in your menu.
you could get fancier, but this is the least amount of PHP.
Comment: tank you for the answer , the problem is that i want the menu item to be linked to the edit page of the last article and not to the last article node !
Comment: @ProgrammerB your question says something else now, and if you'll edit it, it will become [chameleon](http://meta.stackexchange.com/q/43478/225745) - something people don't like, and something you should avoid.
Comment: @Molot , it's mentioned in the question's body !
Comment: @ProgrammerB Then clarify. And please try to use proper spelling and interpunction, it really helps readers understand what you mean.
Answer: Thank you DeveloperWeeks , i followed your instructions and made the below code , and it's working like a charm  :
<code>  <?php
/**
* @file
* Use this module to get the last NID of a defined Content Type
*/

/**
* Implementation of hook_menu().
*/

function lastnode_menu() {
$items['lastnode'] = array(
'title' => 'Edit ADS',
'page callback' => 'lastnode_edit',
'access callback' => 'user_is_logged_in' ,
'type' => MENU_CALLBACK,
);
return $items;
}

/**
* Page callback.
*/

function lastnode_edit ($content_type = '') {
$nid = db_query('select MAX(nid) from node where type = :type', array(':type' => $content_type))->fetchField();
drupal_goto('node/' . $nid . '/edit');
}
</code>
Answer: I like user5482's answer, and it is a good one.  If you are logged in, and the view is using "rendered entity" instead of "fields", the Edit context link would be accessible from there and you would have your answer in two clicks and no code.
If you truly want one click that goes straight to the edit page, you will need a custom module.  You will need to implement hook_menu in your module, and register a static path.  In that hook you should define the access callback as using the appropriate drupal permission; I think you want to find the edit instead of the generic access_content.
You will also need to define a custom callback function that will have the dynamic query to find the most recent (published?) node from the database, construct the url, and execute a drupal_goto to take the user there.  This way you can have a static address (good for menus) link to a dynamic location (most recent node edit page).
But again, all this custom code work will only save you one click over user5482's answer.  Since I cannot think of a reason you would want anonymous users editing nodes, I am guessing this is a menu item for admins only.  That extra click shouldn't destroy the ux.


Aggregate function within table I'm creating

Question: I have a dataset where I have an ItemID and then quantity sold at each price like this:
ItemID  |  Quantity  |  Price
ABC        10           14.50
ABC        4            14.25
DEF        32           22.41
ABC        24           14.10
GHI        8            8.50
GHI        12           8.60
DEF        2            22.30

Every entry has a unique combination of ItemID and Price.  I would like to add a fourth column that has the total quantity sold for that ItemID.  So it would look like this for the above table:
ItemID  |  Quantity  |  Price  |  TotalQ
ABC        10           14.50     38
ABC        4            14.25     38
DEF        32           22.41     34
ABC        24           14.10     38
GHI        8            8.50      20
GHI        12           8.60      20
DEF        2            22.30     34

I can't seem to do this without performing an aggregate function on an aggregate function, which obviously gives an error.  How would I go about accomplishing this?
I'm using SQL Server 2008.
Comment: How do you know the TotalQ? You could write a function to calculate the TotalQ.
Comment: That sounds like it's exactly what I'm looking for.  I am very new to SQL so I don't really know how to write such a function.
Answer: Please try:
SELECT
    *,
    SUM(Quantity) OVER(PARTITION BY ItemID) TotalQ
FROM
    YourTable

Comment: Got the error:

Msg 8120, Level 16, State 1, Line 24
Column 'server.Quantity' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Comment: @weskpga - You probably need `SUM(SUM([Quantity])) OVER (PARTITION BY [ItemID]) AS TotalQ` if you are using this in the context of another query already grouping by `ItemID,Price`. It would be better to show us the original query rather than just the result.
Answer: Try this code
select a.ItemID,a.Quantity,a.Price,x.Total form table_name a
left outer join
(select sum(Quantity) Total, ItemID from table_name group by ItemID)x
on x.ItemID = a.ItemID

Answer: If you need this just in query you can write something like this:
;WITH CTE_Total AS
(
    SELECT ItemID, SUM(Quantity) as TotalQ
    FROM YourTable
    GROUP BY ItemID
)
SELECT t.*, c.TotalQ
FROM YourTable t
LEFT JOIN CTE_Total c on t.ItemID = c.ItemID

SQLFiddle DEMO
But, if you want to  have automated computed column in your table, first you need to create function that does the calculation:
CREATE FUNCTION dbo.fn_YourTableTotalQ (@ItemID VARCHAR(3))
RETURNS Int
AS
BEGIN
   DECLARE @toRet INT

   SELECT @toRet = COALESCE(SUM(Quantity),0)
   FROM YourTable WHERE ItemID = @ItemID

   RETURN @toRet
END

... and then add your new column as computed using this function:
ALTER TABLE YourTable
ADD TotalQ AS dbo.fn_YourTableTotalQ(ItemID)

SQLFiddle DEMO


Where Eclipse stores working set configuration

Question: Looks my workspace somehow is corrupted and I have created new one with new project checkout to it. But I was using working set in crashed system that is not stored in repository. How I can retrieve this info? Where Eclipse stores it's working set configuration?
Answer: Working set definitions are stored in the workingsets.xml file in the workspace .metadata/.plugins/org.eclipse.ui.workbench directory.


Foreach dentro de While

Question: Captura em um array os valores recebidos via post de checkbox marcados, esses checkbox tem os valores iguais aos nomes dos campos da tabela, preciso fazer uma consulta com while e imprimir os campos referentes a array:
<?php
    $campos = '`'.implode('`, `', $_POST['check']).'`';
    $sql = mysql_query("SELECT id,$campos FROM chamado where status = 1");
    while($busca=mysql_fetch_array($sql)){
?>

        <?php echo $busca['id'];?>
        <?php
            foreach ($quantidade_item as $tags) {
                echo ''.$busca[$tags].'	';
            }
        ?>

<?php
    }
?>

O que acontece é que ao executar o código, se for verificado que apenas um checkbox foi marcado, a listagem aparece normalmente, mas, caso marque mais de um checkbox, a listagem exibe apenas os dados da primeira coluna, as outras colunas me retornam undefined index –
Comment: Não percebí bem o problema. Podes explicar melhor/por outras palavras?
Comment: SIm, faltou informar o problema. O que acontece é que ao executar o código, se for verificado que apenas um checkbox foi marcado, a listagem aparece normalmente, mas, caso marque mais de um checkbox, a listagem exibe apenas os dados da primeira coluna, as outras colunas me retornam undefined index
Comment: Ok, e o que dá `var_dump($_POST['check']);` se colocares na primeira linha desse código que mostras`
Comment: Desculpa a demora, tive problemas com minha hospedagem, bom, ao executar o codigo e informar a linha que disse me retorna: `array(3) { [0]=> string(8) "cpf_cnpj" [1]=> string(13) "data_cadastro" [2]=> string(10) "id_cliente" }` , sendo que no exemplo marquei 3 check
Comment: e se marcares só um checkbox como vem o `var_dump`? coloca o teu HTML também para perceber melhor. Não precisas de `\`` no $campos.
Comment: Apenas um check `array(1) { [0]=> string(8) "cpf_cnpj" }`, ao marcar um check a consulta funciona normalmente, ao passar mais checks da variaveis indefinidas e retorna na table apenas os valorse de uma coluna
Comment: não entendi muito bem o seu problema mas tenho uma dica para você, não utilize mysql_query pois o mesmo está obsoleto, aconselho você utilizar PDO ou MySQLi.
Answer: Se eu percebo bem o que queres precisas mudar esta linha:
foreach ($quantidade_item as $tags) {

Não vejo no teu código de onde vêm essa variável $quantidade_item e semanticamente não me faz muito sentido pois penso que o que queres é iterar os campos que vêm do $_POST com os dados que foste buscar à BD, certo?
Nesse caso sugiro mudares o código para:
foreach ($_POST as $tags) {

mas colocar o $_POST assim não é boa prática (coloquei só para clarificar o exemplo). Outra coisa que podes mudar é tirar ``` nos campos da query pois não precisa.
Código final:
<?php
    $_campos = $_POST['check'];
    $campos = implode(', ', $_campos);
    $sql = mysql_query("SELECT id,$campos FROM chamado where status = 1");
    while($busca=mysql_fetch_array($sql)){
?>

        <?php echo $busca['id'];?>
        <?php
            foreach ($_campos as $tags) {
                echo ''.$busca[$tags].'	';
            }
        ?>

<?php
    }
?>

Comment: Muito bom ségio, conseguimos solucionar o problema, muito obrigado

Foreach dentro de While


MIDI Humanization: Random detune plugin (audio or midi)?

Question: This question seems obvious, but I have not yet found any solution: if I have for example 3 trumpets (which are actually from a same midi instrument), and I want to submit the same passage to the three, but I want each one to have small oscillations time and tuning, as well as any real human execution, which plugin I could use?
I know there is the Frank's midi plugin, but I plan on doing this detuning directly on the audio output.
Currently I make the corrections in the midi manually.
The problem is that "randomly" may create a variation each time Sonar plays the song, and that's a problem, because I could not have a consistent recording at each review, that is, every time I was to generate a final audio file, the trumpets would have a different interpretation, and that's not good.
The correct thing is that the plugin generates a random pattern variation and this pattern should be registered from then on.
In short, it is a way to facilitate the humanization of a midi pass without having to do this manually at all times.
Comment: You know one other way to humanize a MIDI part is to actually play it in and then use a quantization algorithm that allows you to select a strength percentage.
Comment: if you have something that works and you want to have it be constant could you record the audio with the randomness onto an audio track. downside is that to make a change you would need to make the change in the midi and then rerecord the audio.
Answer: There are DAWs that will help you humanize/randomize MIDI timing and velocity. Pro Tools and Logic both offer this feature. In each one, you can select a range of notes, choose a MIDI event edit menu function and there will be a randomize/humanize option that lets you pick from min and max and randomness parameters.
For pitch, it's less straighforward. You don't want to try randomizing pitch in MIDI note data because note numbers are discrete. You can make something slightly out of tune with a note number, you can only shift it to a different in-tune note.
So the way to randomize pitch for humanization is to put a random LFO wave shape on the MIDI pitch wheel CC. You'll want this to be very subtle or it's going to sound like a high school band. You might try with the timing and velocity first, and then if that still sounds too mechanical look at slight pitch wheel randomization for one of the parts.
Note: I think the pitch wheel CC affects the entire MIDI channel (or at least an entire virtual instrument), so you may have to split the parts into different tracks to make sure you don't randomize all the pitches together.
I've done this extensively with several MIDI parts over the years and never used a plugin, but if you are using a DAW that doesn't have these features, you may have to use a plug-in or some other way to randomize the data.
Comment: Thank you. I use Sonar and I will search how to associate a random LFO wave shape on the MIDI pitch wheel CC.
Comment: @RogérioDec Some DAWs have a CC channel drawing tool that lets you draw straight lines or whatever, and there might be a random draw tool. Unfortunately I've never used Sonar.
Answer: I found this:
There is a CAL script you can run in Sonar called HUMANIZE that will add variation to the timing and velocities of you MIDI notes. When you run it, it will ask you for a number between 1 and 100. The lower the number the more variation you'll get.
If you want to add variations to just the velocities, you can run the Process\MIDI Fx\Cakewalk FX Velocity tool and use the Randomize function. Select the Limit function (leave the min and max values at 1 and 127) then click on the Randomize option and then adjust the Amount slider to the amount of randomization you'd like. Here the higher numbers give more variation.
source: http://www.soundsonline-forums.com/showthread.php?t=29325
Comment: @RogérioDec ok, sorry i didn't realize that, i will leave this answer here for others that may find it helpful. good luck.
Comment: Thank you. I use Sonar and I use humanize.cal constantly. However, it does not change the pitch.
Answer: You might try the plugin demo version of Crusher X. I use it with Sonar and I think with a little patient exploration you could tame it into randomly detuning midi notes.
Comment: Thanks, I've installed Crusher X demo. I'm trying but can't find how to create just a random micro tune adjustment... Do you know how?


Why is this print line command executing twice?

Question: I have the code below.
It all works, but annoyingly, the print line command in the while loop runs twice. There is (and I have tested for it), only unique items in the queue, no duplicates.
public void paint(Graphics g) {

    boolean isParent;

    int drawCount = 1;

    int x = 0, y = 0, width = 0, height = 0;
    Color colour;

    while (!qtreeQueue.empty()) {

        drawNode = (QuadTreeNode) qtreeQueue.deque();
        isParent = drawNode.getIsParent();

        if (!isParent) {
            x = drawNode.getRectangle().x;
            y = drawNode.getRectangle().y;
            width = drawNode.getRectangle().width;
            height = drawNode.getRectangle().height;
            colour = getRectangleColour(drawNode);
            System.out.println(drawCount + ". Drawing: x = " + x + "; y = " + y +
                    "; width = " + width + "; height = " + height +
                    "; colour = " + colour.toString());
            minMax(drawNode);
            g.setColor(colour);
            g.fillRect(x, y, width, height);
            drawCount++;
        }
    }
    System.out.println("Minimum level of tree: " + min + "\nMaximum level: " + max);
}

Appreciate the help.
Comment: What class is `qtreeQueue` from? Is it one of your own classes? The only two things that come to mind for me is that either there's a problem with the `empty()` method of it or the `paint` is called twice in quick succession. The latter might be the case if the queue is always filled before a paint.
Comment: Yep I haven't read that paint() is called twice anywhere but I guess it must be.
Comment: Any event triggers a `repaint()`, that one I did know.
Answer: That means the paint method is being called twice, which is perfectly normal. The system can call paint as many times as it wants, so you shouldn't perform any operation that might change the state of your program within that method.
Comment: @AlexW: It *could* still happen -- you shouldn't be mixing your search operations and `paint`. Perform your search, store all the results in some kind of data structure, then inside `paint` simply display these results.
Comment: @AlexW: `paint` is meant *only* to refresh the contents of the screen. You should perform all updates and other operations (`deque`, `println` etc.) in a separate method and call it whenever your actual data has changed. The system can call `paint` any time a portion of the screen needs to be redrawn, for eg. if the window is maximized or moved.
Comment: But if I call a method from paint to do this it would do it twice still? By the way this only happens in depth first search. Breadth first doesn't repeat.


What is your IT-department to staff ratio?

Question: This is a topic that may be rather political but it related to system administration still...how many people do you have supporting your users in your IT department? We have three people supporting something near 1500 systems and around 2400 people and a recent question was raised about why we have long times to get systems replaced, repaired, work orders fulfilled, etc. along with the system admin duties of maintaining the servers (mail, proxy, filters, VOIP, wireless, backup, etc.)
Does anyone have numbers on what the "best practices" average is of support people to employees in an organization?
EDIT:...from some of the answers that are appearing I'm starting to feel depressed...
Comment: Obvious answer is obvious. You're extremely understaffed. I did software consulting for a state DOE and man teachers sure are dumb when it comes to computers and websites. I couldn't imagine being an IT person for them, I had enough dealing with their questions of why stuff breaks when they click all over the place or send files in wrong formats etc.
Comment: You really should probably wiki this question.  There won't really be any one correct answer.
Comment: I don't want to overstate things, but I would characterize that level of staffing as essentially impossible.  I've seen as few as 50 Windows users per support tech.  300 per tech would be extremely difficult.  500 - 800 per tech is way out of line.
Comment: Wow. Agreed with Chris above. We're VERY understaffed and we've got 12 of assorted talents and specialties supporting 70+ servers/network gear and about 900 "users". :)
Comment: " We have three people supporting something near 1500 systems and around 2400 people and a recent question was raised about why we have long times to [...]" Dude, wait... what? Were the person(s) who asked this question able to keep a straight face? Maybe they should do stand-up at a night club. O_o
Comment: Please mark 'Community Wiki' :)
Comment: Push hard for more staff! It should also be trained staff. You should not have to train some entry level sys admin with you work load. If all this fails. Get out and get out now!
Answer: I would say that the ratio is about right when things get done in a reasonable amount of time, where "reasonable" is defined by management. If you're the one managing the IT department there, you get to balance the budget for the department against the users who complain that things aren't getting done fast enough. If not, then someone else has apparently decided that the needs of your users isn't as important as keeping the books in the black.
But you want to know our ratio? I'm the single IT person in a company of 8 people, including 3 part timers. We have 11 servers. Our networking and server hosting is done entirely by a partner company. We're an ISP/VoIP telco with about 5000 users, plus who knows how many server hosting customers.
Answer: There's probably no general answer. It depends on the environment that has to be maintained (Specialized servers? Fat or thin client? Special software that needs extra attention?), and on how much is outsourced (network infrastructure, sw installation, electrical wiring, helpdesk duties ...).
To give some ideas:
In my company, we have 3 IT people for a staff of about twenty, but that's because our IT people also work for our customers.
For purely inhouse IT, I've seen rations of 10 IT for 300 employees. 1:30 or 1:50 seems about right for general desktop and some light server administration (mail server, file server) plus a bit of help-desk work.
At any rate, 3 IT for 1500 users seems far too little, unless you outsource almost everything (or your users fix most problems themselves :-P).
Comment: It's not really IT per Users, it's IT manhours per Computer Use manhours. If you're users only use the computers/network about 1 hour per day, then you can support many more of them. Otherwise I agree about 1:35 to 1:50 is a good ratio. If you have 3 fulltime IT, then you should be supporting about 6000 hours of computer use per week.
Comment: Fat clients, no thin clients, public school system in USA, cisco and some AD maintenance outsourced to consultants. In-house have AD, mail, spam, proxy, file, cafeteria POS, library catalog, administrative office, video surveillance, printer, student records, and backup servers along with some miscellanious (VOIP servers from Cisco, HVAC control system, some department-specific servers) to maintain, along with help desk calls and repairing/replacing/imaging clients and user maintenance and software install/configuration in 7 buildings around the county...
Comment: Provided the information above I would say you are WAY over utilized. We currently are running a 1:35 ratio, in a samll shop that is heavily technical. We run all IT systems from top to bottom. However in a purely tech support type situation I remember running 1:300 ratios. Either way you are well above those ratios.
Answer: 3 admins to 1500 systems? I have some bad news for you. You are not supporting 1500 systems.
Your users are supporting their systems. You are supporting the servers, network infrastructure, and helping them out a bit with their systems.
Comment: Is that intrinsically a bad thing? Assuming 1495 of these systems don't have viruses, and these people happen to be self sufficient, I don't see a problem.
Answer: Our overall IT staff is about 65 people supporting 450 internal users,  12,000 external users, 500 servers & network-based devices (not including printers), and 1000 desktops.
Of the 65:

8 are 100% management (non-technical)
10 are leads who are roughly 2/3 supervisory/proj mgmt and 1/3 technical in their time-split. (technical plan-build & some daily operational support)
15 are application developers and multimedia developers (technical & daily operational)
8 are database programmers and ERP support (technical & daily operational)
5 are business analysts and project coordinators (non-technical, mostly non-operational)
19 remaining are Help Desk, desktop, business app, server, and network admins. (front-line, technical, & daily operational)
Answer: Ratios don't really matter. You need adequate teams in place to handle different sets of tasks that complement each other. I define an adequate team as 3-4 individuals. You also need to establish career paths.
I say ratios don't matter, because you can operate simple environments easily. I worked at a company with a 1,200 agent call center
Example for a mid-sized place:

Desktop team - usually an entry point for staff. 1 senior tech, 3-4 juniors. May include helpdesk and telecom (cell phones, etc) provisioning functions.
Microsoft tech team. Usually handles domains, file servers, print, etc
Network team
Applications team -- these guys support your apps and may be SAs for the app servers

The complexities and things that matter to your company drives the need for more specialization and more staff.
Examples:

If you have a bunch of servers hosting public-facing apps somewhere, you're going to need specialized network people for that purpose.
If you have tons of databases, you need to have specialized DBAs.
If you have primadonna execs or other VIP-types, you need dedicated desktop guys to mind them
You may need to have specialized directory/identity management people at some point
Eventually following vendor best practices doesn't cut it, and you need dedicated info security people

Perfection doesn't exist, so how you approach things depends on how much money you have, the leadership you have in place, etc. Without good leaders, growing the staff will make things worse.
On the other hand, your staff as it is described is inadequate. I cannot imagine how crappy your life is with those kind of demands.
Answer: We have around 2,300 members of staff, of which 1,800 use PC's on a regular basis.  We also support over 400 servers.
We have 50 permenent members of staff in the "Operations" department who support the servers, desktops, data and voice links, databases etc. (of which 9 are managers or team leaders). Most of the major line-of-business application support is within a different department with over 100 staff.
And we're busy. Very busy.
Most of the user and business support stuff gets done on time but we struggle with project work both internal stuff like upgrades and supporting major business projects.
So yes, I'd say you're doing well.
Answer: I have seen 1:25 to 1:50 as the norm in the corporate world.  For smaller companies - it tends towards the 1:25 ratio, and for larger companies towards 1:50.  That includes all internal IT support staff (developers, managers, help desk, etc).  It does NOT include people working on the revenue producing side (developers at software company).
Answer: As a consultant I have seen a broad variety of ratios: Usually 1:40 or better for small and mid-sized companys seems to work out just fine (larger projects and non-IT related work gets done too). In bigger companies (and I consider 1500 systems "bigger") there is usually a smaller ratio because the it staff benefits from standardized hardware and support-procedures. I've seen 1:100 and on a rare occasion 1:200 as ratio but none as radical as your 1:500... It could work with local (1st level) support or students/interns which solve all the small problems - but it's no surprise to me, that you have a very slow reaction time with a 1:500 ratio.
Answer: At my company it's just me and I'm only a software developer with about 30 people total. It's been quite an experience to walk into being the domain admin aside from being a developer.
I walked into a fully setup network and we do alot of 3rd party hosting for software and our website so alot of that brunt work is shouldered by others. We buy our machines rolled from dell so I have very minimal work in setting up new clients.
At some point I really will need to get a network security team consultant to come look over everything because the security side is definitely my biggest weakness.
Answer: I suspect you are understaffed because you're asking and you've got response time issues.  It depends wildly on how you're counting IT people to users.  Are you counting desktop support?  Or just server administrators?  30 to 50 to 1 for all technology staff is pretty normal for what I've seen, but that includes DBAs, Support Desk, Networking, Network Security, Web folks, developers, etc...
Here we have a lot of very diverse servers running a bunch of sort of high maintence applications so we have 7 sysadmins, and 2 dbas, for about 320 servers.  Which is probably a bit high.  On the other hand our response times are great and we are very flexable about what we can provide for response to users.  There are also 20k users, and probably 40 odd client services people to deal with them.
Comment: There are three of us...one of whom is the director, in charge of the department and budget and such...and there are 2400 people using about 1500 computers. Students, mostly. Labs, classroom systems. We are in charge of keeping systems running including the servers and the desktops and user accounts. We step people through help remotely when possible, take phone calls, image systems and switch them out when there's system failures, try piecing parts together to get functional systems when necessary, etc...along with server maintenance and monitoring.
Answer: In terms of "full-time equivalents" :
All staff : 1,446
(split across 5 main offices, plus 30-40 other sites with some sort of regular staff presence.   )
IT Dept   : 46
(includes 4 vacant posts)
Of the 46 IT staff, 27 are what I'd term "general ops", i.e.

support desk
2nd/3rd line support for network/hardware stuff
infrstracture stuff (backups, network maintenance, etc)

The other 19 staff are split between

project management
DBA's / specific application support
business analysts / data warehouse stuff

There's probably another 3 or 4 staff within the business who don't work in IT but who are essentially doing IT work 70%+ of the time. These staff can be viewed as either
a) a sinister "shadow" IT, working to undermine network security and promote bad practice.
b) chumps who deal with a lot of the more tedious support calls in person for a longer grade of pay.
Finally, there's another 3 or 4 consultants who are summoned whenever we've too much money in the budget and our stock of "old rope" is running dangerously low...
Answer: 1:250 but I don't recommend it
Answer: Over here, about 40 employees; 1.5 FTE of those are IT staff.
IT maintains about 40 servers and 50-60 workstations (some employees have more than one workstation .. software development house).
My previous company (also a software development house) had 150-ish employees and 4-ish IT staff which maintained as many workstations and lots of servers.
Answer: We have three for a company of 10 people, but more importantly, about 30 servers.
Comment: Are those dedicated IT personel?
Comment: We have three plus an intern for a company of 110, and I thought we were doing pretty good
Comment: I would say that's a pretty good number, 1 person per 10 servers. That's alot of hardware and software to maintain.
Answer: We have 2 IT-staff, my self and my director for about 50 people. The bulk of the "help-desk" stuff falls to me, which really isn't a big deal handling 50 people is working out well.
Answer: Totally depends on the company and the business requirements. At my workplace we have 3 "Systems" employees out of about 20 staff total. However, we have an HPC cluster of around 80 nodes with all its supporting infrastructure, a second development cluster, and a new extension on the way in to Amazon's EC2. On top of that we have a bunch of application servers to support the software developers and scientists, and all the other standard office stuff.
We also deal with rapidly changing requirements and a pretty high rate of growth for the compute infrastructure, so while the ratio of staff to users is high, there is a lot to do.
Answer: Our IT organization has 8 staff members (not including Director/VP) with 3 more to-be-hired.  We support:

A development organization of 70+
users.
HR/Internal staff of about the
same size.
Two production sites with
~30 systems, network gear, SAN.
A development site with
~80 systems, network gear, SAN.


multi-conditional logic in Java

Question: I have a homework assignment that has been driving me insane, I have tried several different algorithms to solve the problem with no luck.
I made a GUI, the GUI has two text boxes with three buttons below an add, subtract, and clear button. When numbers are entered in the top two boxes, and the add or subtract are pressed the math is performed and the results show up in the result box. The last part of my assignment is to add a check box that when it is checked, and one of the values is over 5000 the result of an add or subtract method call is shown in red in the results box.
I have tried nested 'if' statements but that did not work, my last attempt was to use '&&' to test for two conditions: 'Jcheckbox state changed && num1/num2 >= 5000.'
What can I do differently?
Comment: people are going to want you to post sample code so we can better help instead of making guesses.
Comment: It's hard to imagine what you have already worked on based on what you described, if you show your work people can better help you.
Comment: Sounds like you're having trouble checking the state of a JCheckBox, use the [isSelected()](http://docs.oracle.com/javase/7/docs/api/javax/swing/AbstractButton.html#isSelected%28%29) method: `if(jcheckbox.isSelected() && (num1 >= 5000 || num2 >= 5000))`  Further, do the same calculations and change the text color to red, or whatever component is supposed to be red.
Comment: I don't want anybody to do my homework, which is why I was trying not to post any code or have anybody post code to solve the problem. I just cant wrap my head around the question, and I don't know why because it looks like a simple problem. I will put up the code shortly, not on my school computer.
Comment: It sounds like you're on the right track and that's the logic you should be using. What went wrong? What was the output? I think you are going to have to post code here.
Answer: inside your add/subtract methods:
<code>if the `JCheckBox` is checked
    if num1 or num2 >= 5000
        do the calculation
        put it in the result box
        draw a red border on result box
    else
        draw black border
        do whatever your assignment says
else
    draw black border
    do the calculation
    put it in the result box
</code>
Comment: Thank you, now I see why my if statement did not work. I had put it with JCheckbox, and now I see why I should have put my code up initially. It makes much more sense when looking at the code, I was trying to avoid getting specific help.

multi-conditional logic in Java


java convert object array to int array

Question: how i can do this? i have an object array id like to convert it to int array
Comment: what does the object array contain?
Answer: if Object[] objectArray like objectArray = {2,23,42,3} then
public static Integer[] convert(Object[] objectArray){
  Integer[] intArray = new Integer[objectArray.length];

  for(int i=0; i<objectArray.length; i++){
   intArray[i] = (Integer) objectArray[i];
  }

  return intArray;
 }

if your objectArray is like Object[] objectArray = new Integer[/*length*/];
You can simply cast (Integer []) objectArray;
Comment: +1 good one ! can be converted into int leveraging Autoboxing feature !
Answer: If the content can be casted to Integer, you can cast the array to Integer [] and use its elements as int:
Object [] arr = new Integer[3];
arr[0] = new Integer(1);
arr[1] = new Integer(2);
arr[2] = 3;
Integer [] newa = (Integer []) arr;
for(int i:newa) {
  System.err.print(i+" ");
}

Otherwise you can create a new int [] array with the same length as the original and then set the elements in the newly created arrays to the values given by conversion:
int [] arr = new int[origarr.length];
arr[0] = convertTo_int(origarr[0]);
// convertTo_int implementation depends on the type of origarr elements.

java convert object array to int array


linear regression with Quarter dummy

Question: I am trying to fit a linear regression to the data below
Power<-mutate(Power,Year=format(Date,"%Y"),Quarter=quarters(Date),Month=format(Date,"%m"))
head(Power)
       Date    YY    XX  Year    Quarter
2007-01-01     NA     NA 2007      Q1
2007-01-02     NA     NA 2007      Q1
2007-01-03  55.90  71.40 2007      Q1
2007-01-04  55.25  70.75 2007      Q1

The model  is
lm(YY~XX+as.factor(Quarter,ref="Q1"),data=Power)

This works fine. However, it automatically creates three dummies for 3 quarters. Is there any way to include only one dummy, say Q2 in this model?
Answer: Arguably the most common way to do this is to create a dichotomous variable on the fly with I().
lm(YY ~ XX + I(Quarter=="Q2"), data=Power)

This includes a binary predictor in the model that's 1 when Quarter=="Q2" and 0 otherwise.
Answer: Easiest way would be to create new variable with information you need...
Power$Q2dummy <- 0
Power$Q2dummy[which(Power$Quarter == 'Q2')] <- 1
lm(YY~XX+Q2dummy,data=Power)

However, it is hard to say, because you dont provide your data or even their summary (what is variable Quarter? Factor with 4 states I guess?).
Answer: One possibility could be to use the ifelse(rule, if TRUE, if FALSE) command :
For Example:
Power$Q2dummy <- ifelse(Power$Quarter == "Q2",1,0)
lm(YY~XX+Q2dummy,data=Power)

linear regression with Quarter dummy


What's the difference between drupalSettings and settings parameter in behaviors?

Question: When having the need to pass settings or parameters from PHP to JavaScript, i always used to do so according to a blog post from Acquia - create a dependency to drupalSettings, attach the settings on the PHP side and use the drupalSettings variable on the JS side.
my_module.libraries.yml:
my_lib:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

my_module.module:
function my_module_page_attachments(&$attachments) {
    $attachments['#attached']['drupalSettings']['my_module']['my_property'] = 'abc';
}

Finally my_javascript.js:
(function ($,Drupal,drupalSettings) {
  Drupal.behaviors.test = {
    attach: function(context,settings) {
      console.log(drupalSettings.my_module.my_property); // would output 'abc';
    }
  }
})(jQuery,Drupal,drupalSettings);

However, I came to a sudden realization that the settings variable of my attach function already contains exactly the same variable:
(function ($,Drupal) {
  Drupal.behaviors.test = {
    attach: function(context,settings) {
      console.log(settings.my_module.my_property); // would also output 'abc';
    }
  }
})(jQuery,Drupal);

So why is there even a separate way to load drupalSettings and it's proposed in every guide I found, when in fact we already have a variable containing our settings, so we don't need to mention the global drupalSettings variable?
Thanks for your clarification!
Update 1
I found out in my test behavior that the variable settings is a reference to drupalSettings, so if you modify one of the two, the other also has the direct changes, and they are therefore equal.
Drupal.behaviors.anotherTest = {
  attach: function(context,settings) {
    console.log(settings == drupalSettings); // outputs true
    drupalSettings.testproperty = 'abc';
    console.log(settings == drupalSettings); // still true
    console.log(settings.testproperty); //  outputs 'abc'
    // works also the other way around
    settings.testproperty = 'def';
    console.log(drupalSettings.testproperty); // outputs 'def' now
  }
}

This applies to every call of my behavior. On my rather complex project, the behavior gets called 12 times, and while the context variable changes on every call, settings is always equal to drupalSettings.
Comment: @Clive Could be bad memory on my part, or me misremembering when AJAX settings get merged with the global settings.  However, using the version passed in from the function also has the advantage of being found in the scope directly, rather than chasing in the global scope.  Passing in via a closure helps here, as well as with the accidental reassignments.  Chasing to the global (ie, window.*) scope can be slow, in a relative sense.
Comment: Yeah that's true @mpdonadio. I think you can probably even ignore the performance stuff with this: you're given a variable and told to use it, so that's what you should do. The fact that it's the same object as something else may be relevant, may not, but it's not your concern. Interface not implementation!
Comment: _so we don't need to mention the global drupalSettings variable?_ That would have been my guess too, but given the advice to wrap behaviours in a closure I'm not sure that makes sense - surely `settings` would be passed in through the outer wrapper of that was the concern. My experience is the same as yours BTW, that `settings === drupalSettings`
Answer: The thing to remember is that behaviors can fire both on page load and on AJAX requests.
Upon page load, the global and the parameter passed to the behavior should be identical.
During the course of page interaction, and depending on the AJAX commands, the settings parameter may be different when it fires.
When writing behaviors in Javascript, always use both the jQuery context to scope selectors, and the settings variable that get passed in to be safe and future proof your code even if you aren't using AJAX.
Comment: You can use alternative settings in the AJAX `SettingsCommand` by keeping the default merge=FALSE. You wouldn't find many examples though in core, because normally the settings are collected from the rendered output and added to the response with merge=TRUE.
Comment: So, you're saying that the settings parameter is also reduced to the given context? How can Drupal distinguish when I attach my settings to the page (using `hook_page_attachments`) which behavior context will use the given setting?
Comment: see also my updated answer with further tests...


Issue trying to add Python27 to path through command-line/gitbash

Question: I am trying to add python 2.7 to my currently set path in the command line. I can not get it to add.
My current path looks like this

Environment variable python "C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\DockerDesktop\version-bin;C:\Program Files\Docker\Docker\Resources\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\Tumbleweed\Desktop Validator\;C:\Program Files\Tumbleweed\Desktop Validator\x86;C:\Program Files (x86)\HID Global\ActivClient\;C:\Program Files\HID Global\ActivClient\;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Users\jandali\AppData\Local\Microsoft\WindowsApps;;C:\Python27\Lib" not defined

at then end it said that
Environment varialbe python is not defined.
I tried the following commands
set "%path%;C:\Python27"
and
set "%path%;C:\Python27\Lib"
not sure why it is saying that it is not defined when it is at the end of the paths...
when I run python or python27, it says that command was not recognized
not sure how to fix this.
Comment: If it is bash not cmd, then try using `PATH="$PATH:C:\Python27\"`. You can use `echo $PATH` to see if it was added.
Comment: Are you running your command line as administrator? If not, try to run a windows command line as administrator (right click on command prompt and select Run as Administrator). Then run your command.
Comment: when i run the PATH=... It shows a caret on the side like i have entered the python shell. do I need to do add anything to the command... @solarc
Comment: Ah wait, bash in windows uses a different path format. Try `PATH="$PATH:/c/Python27/"`. It should return you to the regular prompt.
Answer: On standard Windows command line, the error you have is because
set "%path%;C:\Python27"

expands as
set superlongcurrentuser+systempath;C:\python27

and the variable name just created isn't a valid name. You want:
set path="%path%;C:\Python27"

(in windows, paths are separated by semicolons, not colons like on unix/linux)


how to get interface traffic snmp information for routers ( cisco, zte, huawei ...)?

Question: I have cisco, zte, huawei routers..How can i get the traffic information of every interfaces of these routers. I donot have mib file of zte and huawei. So, i want a generic mib file which can monitor every interfaces of these routers
Answer: As Nick R already mentioned, you need IF-MIB... details matter though.
You can correlate all OIDs to an interface name below by snmp walking ifName: 126.96.36.199.188.8.131.52.1.1.1.
High Speed interfaces
For high-speed interfaces (100Mbps or above) you should use 64-bit counters if the device supports them:

ifHCInOctets: 22.214.171.124.126.96.36.199.1.1.6 (64-bit Octets in counter)
ifHCOutOctets: 220.127.116.11.188.8.131.52.1.1.10 (64-bit Octets out counter)
ifHCInUcastPkts:    188.8.131.52.18.104.22.168.1.1.7 (64-bit Packets in counter)
ifHCOutUcastPkts:   22.214.171.124.220.127.116.11.1.1.11 (64-bit Packets out counter)
ifHighSpeed: 22.214.171.124.22.214.171.124.1.1.15 (An estimate of the interface's current bandwidth in units of 1Mbps)

Low Speed interfaces
Lower speed interfaces can get by with 32-bit counters.  If you use 32-bit counters on high-speed interfaces, they can wrap quickly; a 10 Mbps stream of back-to-back, full-size packets causes ifInOctets to wrap in just over 57 minutes. At 100 Mbps, the minimum wrap time is 5.7 minutes, and at 1 Gbps, the minimum is 34 seconds Note 1

ifInOctets: 22.214.171.124.22.214.171.124.1.10 (32-bit Octets in counter)
ifOutOctets: 220.127.116.11.184.108.40.206.1.16 (32-bit Octets out counter)
ifInUcastPkts: 18.104.22.168.22.214.171.124.1.11 (32-bit Packets in counter)
ifOutUcastPkts: 18.104.22.168.220.127.116.11.1.17 (32-bit Packets out counter)
ifSpeed: 18.104.22.168.220.127.116.11.1.5 (Currently negotiated speed of the interface - Max: 4.294 Gbps)

Note 1: Quoted from Cisco's SNMP FAQ
Comment: The link refers to the original IF-MIB, without the ifXTable extensions.  The full description can be found at [rfc2863](http://tools.ietf.org/html/rfc2863).  Cisco has a plain text version of the extended [IF-MIB](ftp://ftp.cisco.com/pub/mibs/v2/IF-MIB.my).
Answer: IF-MIB should be what you are looking for. The OID you want is ifInOctets and ifOutOctets.
Answer: Cacti is the most strait forward way to go.
Download an install it, it will work with a lot of routers and switches straight out of the box. Also, Observium is even easier to get going but less customisable than Cacti; although it does also work with most switches and routers strait out of the box.
Update: Forgot to say these include the MIBs!
Comment: +1 for observium, it's great if you're a service provider


What is the null hypothesis checked by ANOVA?

Question: I know that null hypothesis used by ANOVA is that means in all the groups are the same and, if p-value is small, we reject the null hypothesis which means that we believe that not all the means are the same (that is, there are groups with different means).
However, it is not clear to me if we also assume within the null hypothesis that standard deviation in all the groups is the same. What about higher momenta (like skewness and kurtosis), do we assume them to be equal? Do we assume, within the null hypothesis, that distributions of all the groups are the same? Do we assume that the distributions are normal?
Comment: Assumptions are hypothetical but they are not part of the null hypothesis.
Answer: ANOVA assumes all group distributions under consideration to be normal with the same variance. Consequently, the only way they can differ is in their means.
However, you allude to the fact that the test could pick up on other differences, and if you want to use ANOVA to test something else, it is common in statistics to use a surrogate test. The best example I know is the Wilcoxon Mann-Whitney U test, which only tests mean equality under strict assumptions, but it is a decent test of mean equality (good power, not too many false positives) even when those assumptions are not the case.
You could do a simulation study to see how well ANOVA detects differences in, say, standard deviation when the means are all equal. I would expect such a test to have awful power barely (if at all) above the $\alpha$-level of the test, which would explain why we use ANOVA to detect mean differences, but perhaps someone could write a simulation that surprises me.
Answer: I think, "assume within the null hypothesis" is not a valid statement. We do not assume nothing in null hypothesis. We check if hull hypothesis can be rejected. And to be able to check it, we make some assumptions. These assumptions help us to develop formulas for test statistic and p-value.
So:

if we also assume that standard deviation in all the groups is the same

Yes, we assume this. It means that all the formulas used in testing procedure are valid only if standard deviation in all the groups is the same. If it is not true we should use some other test (Welch ANOVA probably) that do not assumes it.

What about higher momenta (like skewness and kurtosis), do we assume
them to be equal?

No.

Do we assume that the distributions are normal?

Yes. Just like with SDs. It means that all the formulas used in testing procedure are valid only if distributions are normal. If it is not true we should use some other test (Kruskal-Wallis ANOVA probably) that do not assumes it.

Do we assume that distributions of all
the groups are the same?

If we assumed it, we wouldn't need any test. Because, if all distributions are the same, all means are the same too.
In case you meant "Do we assume that distributions of all the groups are from the same family (like all are normals or all are exponentials)?", look at previous paragraph.
Comment: When I say "do we assume this or this in null hypothesis" I actually ask "what is our null hypothesis". From you answer I understood that our null hypothesis is that all the observations come from one normal distribution.
Comment: In other words, in order to accept or reject a (null) hypothesis we need to know what it is (what is our hypothesis) or, in other words, what it assumes.
Comment: Assumptions are statments that we know (or we believe) that are true. Hypothesis is a statment that we wish to validate. Here, assuptions are: distribution is normal with the same SD in each group. Hypothesis is: means are also the same.
Comment: So running this test we say: "OK, we know/believe that normal with the same SD in each group, let's check if means are the same too".
Comment: For me "assumption" and "hypothesis" mean the same. We assume that all the groups have the same normal distribution and then we prove of disprove this assumption. But it is more a "linguistic question" which does not really matter to me.
Comment: I am not sure that we use at some point the model in which each group has the same SD and different mean. I guess that we assume that all the groups have the same normal distribution and then we show that the observed data are very unlikely under this assumption. So, we say that "null hypothesis" is NOT the reality but we do not say what the reality IS.
Comment: You're right: this turned out to be a linguistic question. You may say that for you "assumption" and "hypothesis" mean the same, but they do not. English is nowadays Lingua Franca, but for most people it is not their first language. So, it would be, in my opinion, beneficial to stick to exact definitions of "assumption" and "hypothesis". Otherwise, we can quickly stop understanding each other.
Comment: Just a detail, skewness and kurtosis are fixed in the normal distribution, skewness is always 0 and kurtosis is always 3, so you are implicitly making assumptions about higher moments when choosing the normal distribution.
Answer: The pooled 2-sample t test is equivalent to a
one-way ANOVA with two levels of the factor.
Suppose one level has 10 replications from
$\mathsf{Norm}(\mu_1=1, \sigma_1=10)$ and the other level
has 100 replications from $\mathsf{Norm}(\mu_2=1,\sigma_2=1).$ In the example below,
the pooled t test strongly rejects the null hypothesis
(nominally that $\mu_1=\mu_2)$
with P-value $0.001.$  So the t test must be
'unofficially noticing' the large difference in variances. [Using R.]
set.seed(2021)
x1 = rnorm(10,1,10);  x2 = rnorm(100,1,1)
t.test(x1,x2, var.eq=T)$p.val
[1] 0.0009002001

Here is the same test in ANOVA format, showing
the same P-value as above.
x = c(x1, x2)
g = as.factor(rep(1:2, c(10,100)))
anova(lm(x ~ g))

Analysis of Variance Table

Response: x
           Df Sum Sq Mean Sq F value    Pr(>F)
g           1  98.02  98.018  11.661 0.0009002 ***
Residuals 108 907.84   8.406
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

A brief simulation in R shows that the result
above is not a one-time fluke. The 'power' of the
pooled 2-sample t test, with similar data, is around 50%, (I'm not sure whether @Dave will find it surprising.)
set.seed(1229)
pv = replicate(10^5, t.test(rnorm(10,1,10),
      rnorm(100,1,1), var.eq=T)$p.val)
mean(pv <= .05)
[1] 0.53772   # 'power' of test at 5% sig level

The unbalanced pooled t test is notorious for rejecting with
equal means and unequal variances, when the sample
with the larger variance is much smaller. The Welch
2-sample t test is designed to mitigate this
kind of bad behavior, rejecting at the 5% level about 5%
of the time when means are equal, even when variances are not.
set.seed(1229)
pv = replicate(10^5, t.test(rnorm(10,1,10),
      rnorm(100,1,1))$p.val)
mean(pv <= .05)
[1] 0.0493

The bad behavior continues for unbalanced one-way
ANOVAs, when means are equal and one level has
much larger variance along with small sample size.
One instance with three levels is shown below;
the hull hypothesis is rejected, even though the three population means are equal.
set.seed(2021)
x1 = rnorm(10, 1, 10)
x2 = rnorm(100, 1, 1)
x3 = rnorm(100, 1, 1)
x = c(x1,x2,x3)
g = as.factor(rep(1:3, c(10,100,100)))
anova(lm(x~g))

Analysis of Variance Table

Response: x
           Df  Sum Sq Mean Sq F value    Pr(>F)
g           2   98.15  49.074  10.027 6.975e-05  ***
Residuals 207 1013.08   4.894
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

However, the procedure oneway.test in R does not
require equal variances, using a Welch-like reduced
denominator degrees of freedom to the extent that sample variances are unequal. This test
does not find significant differences among the three means.
oneway.test(x~g)

        One-way analysis of means
        (not assuming equal variances)

data:  x and g
F = 1.9742, num df = 2.000, denom df = 22.981, p-value = 0.1617

Answer: Assumptions are hypothetical but they are not part of the null hypothesis.

When I say "do we assume this or this in null hypothesis" I actually ask "what is our null hypothesis". From you answer I understood that our null hypothesis is that all the observations come from one normal distribution.

If the null hypothesis and also the additional hypotheses/assumptions are true then indeed the observations come from one single normal distribution (an additional assumption is that each observation is independent).
However, that state 'all observations come from one single normal distribution' is not the hypothesis that is being tested with ANOVA.
The null hypothesis refers to the hypothesis that a certain effect is null/absent. The null hypothesis is not about any additional assumptions.
What happens if the assumptions are false
If the additional assumptions of ANOVA, like normal distributed with equal variance, are wrong then the test still works to some extent.

if p-value is small, we reject the null hypothesis which means that we believe that not all the means are the same (that is, there are groups with different means).

The p-value is an indirect measure of the effect that the means are not the same. More directly we measure the F-statistic, the ratio of variance.
The F statistic remains a measure for the difference between the means of groups.  The larger the F-statistic the more different the means of the groups. What the p-value does is provide a statistical interpretation to the observed effect (the magnitude of the F-statistic) in terms of statistical significance.
The only problem with any false assumptions is that this statistical inference is wrong. Based on the assumptions we can compute a sampling distribution for the F statistic (it follows a F distribution if the null hypothesis is correct and a non-central F distribution if the null hypothesis is not correct). That assumption about the sampling distribution would now be wrong and computed p-values will be wrong.
What remains is the situation that the further the actual situation is from the null hypothesis the more likely it is to observe a larger F statistic, and the F statistic remains a measure for the difference of the means.
If the distributions are extremely different from a normal distribution and/or if the variance is not the same among the different populations then one could still estimate a distribution of the F-statistic based on bootstrapping (use the observed values to estimate the sampling distribution of the F-statistic). Or alternatively, the variance of the groups is made more alike by using a transformation of the data.


Should I use Sql.Stmt or string in database query in GO?

Question: Hi in database/sql package I can execute a query in two ways:

First way: using Sql.Stmt
var DeletePermissionStmt *sql.Stmt
DeletePermissionStmt, err = database.Prepare(`DELETE FROM permission WHERE permission_id=$1`)

if err != nil {
     log.Errorf("can't prepare delete permission statement: %s", err.Error())
}

transaction, err := database.Begin()  // assume postgres database is defined previously

if err != nil {
     log.WithFields(logFields).Errorf("can't start transaction: %s", err.Error())

return err
}
 _, err := transaction.Stmt(DeletePermissionStmt).Exec(permission_id)

Second way: using string
var DeletePermissionStmt string
DeletePermissionStmt = `DELETE FROM permission WHERE permission_id=$1`

transaction, err := database.Begin()  // assume postgres database is defined previously

if err != nil {
log.WithFields(logFields).Errorf("can't start transaction: %s", err.Error())

return err
}
 _, err := transaction.Exec(DeletePermissionStmt,permission_id)

The only difference That I know that its is not possible to use sql.Stmt when you are returning something for example Insert Into FOO(f1,f2,f3) Values(v1,v2,v3) returning f_id
Is there any other differences? and when should I use each one?
Comment: Related / possible duplicate of [Go sql - prepared statement scope](http://stackoverflow.com/questions/38390999/go-sql-prepared-statement-scope).
Comment: `INSERT ... RETURNING ...` is supported if you use `tx.QueryRow()`
Answer: Using the Stmt helps you avoid sql injection from the user.
From wikipedia:

Prepared statements are resilient against SQL injection, because
  parameter values, which are transmitted later using a different
  protocol, need not be correctly escaped. If the original statement
  template is not derived from external input, SQL injection cannot
  occur.


Buscar valores no código fonte da página

Question: Tem esse site, que gera uma tabela de mesas reservadas e disponíveis, sem necessidade de login:

Na inspeção, dá para ver o estilo da div (por ex.: class="day closed"):

Mas, no código fonte apresenta isso:

Faça sua Reserva

Reserve mesa(s) para até 4 pessoas por R$ 12 ou até 6 pessoas por R$ 18 e garanta 50% de desconto nas refeições de toda a mesa.

O que eu queria, era usar o file_get_contents com o preg_match_all para pesquisar quando tivesse class="day available, mas acredito que ele não trás o resultado por conta do JS, e assim não tendo como pesquisar.
O problema realmente é esse ?
Que outra forma posso fazer essa consulta no conteúdo da página, usando php?
Comment: Tem como informar o link do site?
Comment: Adicionei no "site" !
Answer: A solução para seu problema é usar o Network Inspector do browser e estudar as chamadas a API.
Por exemplo, na página:
https://www.primeiramesa.com.br/restaurante/container-burguer

Temos a requisição XHR:
https://www.primeiramesa.com.br/api/v1/restaurant/calendar?slug=container-burguer

Que retorna um json com a informação que você quer:
{
"error": false,
"calendar": {
    "breakfast": [
        {
            "date": "Thu, 08 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "QUI",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        },
        {
            "date": "Fri, 09 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "SEX",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        },
        {
            "date": "Sat, 10 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "SAB",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        },
        {
            "date": "Sun, 11 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "DOM",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        },
        {
            "date": "Mon, 12 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "SEG",
            "qtd_tables": "1",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        },
        {
            "date": "Tue, 13 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "TER",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        },
        {
            "date": "Wed, 14 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "QUA",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        }
    ],
    "lunch": [
        {
            "date": "Thu, 08 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "QUI",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        },
        {
            "date": "Fri, 09 Mar 2018 15:00:00 -0300",
            "hour": "15:00",
            "day_week_name": "SEX",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": "10",
            "status": "available"
        },
        {
            "date": "Sat, 10 Mar 2018 15:00:00 -0300",
            "hour": "15:00",
            "day_week_name": "SAB",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": "10",
            "status": "available"
        },
        {
            "date": "Sun, 11 Mar 2018 15:00:00 -0300",
            "hour": "15:00",
            "day_week_name": "DOM",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": "10",
            "status": "available"
        },
        {
            "date": "Mon, 12 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "SEG",
            "qtd_tables": "1",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        },
        {
            "date": "Tue, 13 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "TER",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        },
        {
            "date": "Wed, 14 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "QUA",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        }
    ],
    "dinner": [
        {
            "date": "Thu, 08 Mar 2018 18:00:00 -0300",
            "hour": "18:00",
            "day_week_name": "QUI",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "timeout"
        },
        {
            "date": "Fri, 09 Mar 2018 17:00:00 -0300",
            "hour": "17:00",
            "day_week_name": "SEX",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": "10",
            "status": "available"
        },
        {
            "date": "Sat, 10 Mar 2018 17:00:00 -0300",
            "hour": "17:00",
            "day_week_name": "SAB",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": "10",
            "status": "available"
        },
        {
            "date": "Sun, 11 Mar 2018 17:00:00 -0300",
            "hour": "17:00",
            "day_week_name": "DOM",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": "10",
            "status": "available"
        },
        {
            "date": "Mon, 12 Mar 2018 00:00:00 -0300",
            "hour": "00:00",
            "day_week_name": "SEG",
            "qtd_tables": "1",
            "month_name": "MAR",
            "qtd_available": 0,
            "status": "closed"
        },
        {
            "date": "Tue, 13 Mar 2018 18:00:00 -0300",
            "hour": "18:00",
            "day_week_name": "TER",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": "10",
            "status": "available"
        },
        {
            "date": "Wed, 14 Mar 2018 18:00:00 -0300",
            "hour": "18:00",
            "day_week_name": "QUA",
            "qtd_tables": "10",
            "month_name": "MAR",
            "qtd_available": "10",
            "status": "available"
        }
    ]
}

}
Nesse caso um:
$dados = json_decode(file_get_contents('https://www.primeiramesa.com.br/api/v1/restaurant/calendar?slug=container-burguer'), true);
print_r($dados);

Faz o que você quer.
Comment: Caraca, não conhecia isso ! Olhei aqui e fiz o seguinte: percorri o network e achei o `calendar?slug=container-burguer`, que seria essa API. Só para eu entender se é exatamente isso, você fez isso também ou no código fonte, algo aponta mais diretamente ?
Comment: No código da página não tem nada, só repare que o slug=container-burger é o final da URL da pagina, que fica fácil de extrair com um end(explode('/', 'https://www.primeiramesa.com.br/restaurante/container-burguer'));
Ou seja, você não precisa do código fonte da página do restaurante, só do endereço mesmo.


Sistema de comentário com chave estrangeira "autor_coment"

Question: Tem uma tabela comentarios com os seguintes atributos: id (int not null), comentario (text not null), data_coment (timestamp not null) e autor_coment (int not null).
O autor_coment é uma FK que referencia uma outra tabela do BD (login).
Estou tendo dificuldade para cadastrar o comentário, sendo que:

Preciso verificar se o usuário está logado, senão ele não pode comentar.
Preciso mostrar o nome do autor_coment e não o id
Comment: Em que exatamente tu ta tendo dificuldade? Posta o código do que tu já fez até agora.
Comment: Sql Server ou MySql? Apresenta algum erro? poste o comando de insert que está fazendo
Answer: Esse é o código de cadastro do comentário:
   <?php
include 'admin/conexao/conecta.php';

if(isset($_POST['comentar'])){
            $comentario = trim(strip_tags($_POST['comentario']));

$insert = "INSERT into comentarios (comentario) VALUES (:comentario)";

        try{
            $result = $conexao->prepare($insert);
            $result->bindParam(':comentario', $comentario, PDO::PARAM_STR);
            $result->execute();
            $contar = $result->rowCount();
            if($contar>0){
                echo '';
            }else{
                echo '';
            }
        }catch(PDOException $e){
            echo $e;
        }

?>

<form method="post" action="#">

            Nome:
<input style="width: 200px;height: 40px;" type="text" id="autor_coment" name="autor_coment" placeholder="Digite seu nome">

            Comentário

            <textarea style="width: 500px; height: 150px;" type="text" id="comentario" name="comentario" required></textarea>

        <input class="w3-button w3-black w3-section" style="width:100px; height:40px; background:#333; color:white; border:none;" type="reset" name="cancelar" value="Cancelar"/>
        <input class="w3-button w3-black w3-section" style="width:100px; height:40px; background:#333; color:white; border:none;" type="submit" name="comentar" value="Comentar"/>

</form>

O problema é que eu não faço ideia de como trabalhar com a FK autor_coment no cadastro.


Offset problem in Drupal 7

Question: I want to use the Views module to display the top item from a listing.
I've utilized the "Use Pager" to display that one item. But sometimes I want to display the second item, or third item, or X item. I've found the offset option to skip the first item, but the result I get doesn't seem to match. What I get instead is some random item, and not, say, the second item.
Any suggestions?
Answer: Did you accidentally enable random ordering as well? In a randomly ordered list, the second item will always be random as well.
If this is not the case, please provide more information about the configuration of your view. Two ways of doing this are to make a screen shot of the edit form, and to upload the exported view to http://pastebin.com.
Comment: Thanks. But no, I did not utilize the randomly orderly list. Rather, my sort criteria is Content: Post date with a granularity set to "Second". The other configuration of my view is as follows...
Content: Published (Yes)
Content: Type (= Article)

Offset problem in Drupal 7


How to stop samsung device maintenance to put our app in sleep mode android?

Question: I am developing one application in which there is Background Service, I want my application always run in background.
In Samsung device android 7.0 user can put the application in sleep mode, but I don't want user to do it because there is Background service is running.
Also it is good if I my app is listed in Unmonitered app list instead of direct listed in power saver mode.
When I install whatsapp it does that actually, it listed in Inmonitered app list.
Thanks.
Answer: Here I am suggesting for the only Samsung devices,
You can do it by using  Knox SDK which is used to create the application with custom configuration for Samsung device,
Here also some link which helps you.
Response from Samsung moderator after question like same you
https://seap.samsung.com/forum-topic/applicationpolicyaddpackagetobatteryoptimizationwhitelist-does-not-work-normally
Maybe this all will help you.
Comment: @Jayesh use english


Iterating over folder names in Python

Question: I have two folders, 1 and 2. I want to go to each folder which has the file Test.xlsx. I tried to iterate on file_loc using i in range(1,3) but there's an error. The code works if I mention 1 or 2 on file_loc.
import pandas as pd
import numpy as np

for i in range(1,3):
    file_loc = "C:\\Users\\USER\\OneDrive - Technion\\Research_Technion\\Python_PNM\\Sept12_2022\\i\\Test.xlsx"
    df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols="A,C:AA")
    A=df["N"].to_numpy()
    print([A])
    A = [x for x in A if str(x) != 'nan']
    print(A)
    A = [eval(e) for e in A]
    print(A)

    A=np.array(A)
    print([A])

    A_mean=[]
    for i in range(0,len(A)):
        A_mean.append(np.mean(A[i]))
    print(*A_mean, sep='\n')

The error is
Traceback (most recent call last):

  File "C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept12_2022\Test.py", line 12, in <module>
    df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols="A,C:AA")

  File "C:\Users\USER\anaconda3\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)

  File "C:\Users\USER\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 364, in read_excel
    io = ExcelFile(io, storage_options=storage_options, engine=engine)

  File "C:\Users\USER\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 1191, in __init__
    ext = inspect_excel_format(

  File "C:\Users\USER\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 1070, in inspect_excel_format
    with get_handle(

  File "C:\Users\USER\anaconda3\lib\site-packages\pandas\io\common.py", line 711, in get_handle
    handle = open(handle, ioargs.mode)

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\USER\\OneDrive - Technion\\Research_Technion\\Python_PNM\\Sept12_2022\\i\\Test.xlsx'

Comment: you need a f-string for `file_loc`, so your `i` in the string gets evaluated as number. At the moment it is just a letter in the string
Comment: Does this answer your question? [How do I put a variable's value inside a string (interpolate it into the string)?](https://stackoverflow.com/questions/2960772/how-do-i-put-a-variable-s-value-inside-a-string-interpolate-it-into-the-string)
Comment: Using this link, I tried ```f'{i}'``` but I get the same error. I tried to access the folder names ```1``` and ```2```, both of which has the file with the same name ```Test.xlsx```.
Answer: for i in range(1,3):
    file_loc = f"C:\\Users\\USER\\OneDrive - Technion\\Research_Technion\\Python_PNM\\Sept12_2022\\{i}\\Test.xlsx"
    ...

Make sure you entered correct path

Iterating over folder names in Python


How to sum up all neighbouring nonzero value in the middle of a list in Python

Question: I am beginner in Python. I need to solve an issue with summing up neighboring nonzero value in a list.
Say, I have list called
a = [2, 3, 0, 0, 1, 0, 3, 3, 1, 0, 0].

In a, there will be multiple instances where the elements are nonzero. For example, 2 and 3 are neigbouring so I want to sum them up so I would get 5.
Then, there another neighbouring elements which are 3, 3 and 1. This is where I face problem because i want to sum it up to 7.
But in the code that I attempted on, it still print out 4, which is the sum of a[7] and a[8]. Is there any way I can avoid this?
c =[]
for i in range(1, len(a)):
    if a[i-1] != 0:
        if a[i] != 0:
           tot = a[i] + a[i-1]
           c.append(tot)
           if a[i+1] != 0:
               tot = tot + a[i+1]
               c.append(tot)
    else:
        tot = 0;
        continue

Comment: what is the difference between summing elements and summing non-zero elements? adding 0 to a sum doesn't change it.
Comment: @Tacratis I think the OP is trying to find the different sums of all groups of non-zero values
Comment: I understand now. It appears that others have already answered. Good luck :)
Comment: Every nonzero value in a represent a block of instances. I need to sum up any nonzero value adjacent to each other to observe the length of the instances. Summing all elements would not help my objectives since I need it to be separate. 0 in the list means that there is a break in instances occurance. Hope you get what I mean
Comment: @Tacratis yup. thank you =)
Answer: You can use itertools.groupby and a comprehension:
>>> import itertools
>>> a = [2, 3, 0, 0, 1, 0, 3, 3, 1, 0, 0]
>>> [sum(v) for k, v in itertools.groupby(a, key=lambda x: x != 0) if k != 0]
[5, 1, 7]

Answer: You can also use a simple generator function:
def groups(d):
  _sum = 0
  for i in d:
    if not i:
      if _sum:
        yield _sum
        _sum = 0
    else:
        _sum += i
  if _sum:
    yield _sum

print(list(groups([2, 3, 0, 0, 1, 0, 3, 3, 1, 0, 0])))

Output:
[5, 1, 7]

Answer: As I understand, you want to calculate sub-sums of consecutive non-zero elements.
How about:
#!python3

from typing import List

def solve(arr: List[int]) -> List[int]:
    ret = []
    tmp = []
    for elem in arr+[0]:
        if elem != 0:
            tmp.append(elem)
        else:
            if len(tmp):
                ret.append(sum(tmp))
                tmp = []
    return ret

arr = [2, 3, 0, 0, 1, 0, 3, 3, 1, 0, 0]
assert(solve(arr) == [5, 1, 7])

Answer: The original list 'a' is [2, 3, 0, 0, 1, 0, 3, 3, 1, 0, 0] where the neighboring non-zero elements in list 'a' are highlighted in bold text.
a = [2, 3, 0, 0, 1, 0, 3, 3, 1, 0, 0]
def fun(a):
    tot =[] # sub-list of list a
    val=0
    for i in a:
        if i==0:
            if val!=0:
                tot.append(val)
                val=0
        else:
            val+=i
    return tot

print(fun(a))
# output [5, 1, 7]


Why is my subview not showing on top of the stack?

Question: I am trying to add a camera capture subview on top of my NavigationStack but even though the code runs fine according to debugs the subview is not shown on top so I cannot scan using the camera
The code looks as follows, why would it not show on top of the stack?
- (IBAction)transactionListViewCameraBtn_Pressed:(id)sender {

    if([NWTillHelper isDebug] == 1) {
        NSLog(@"%s entered", __PRETTY_FUNCTION__);
    }

    NSLog(@"jongel1");
    self.capture.delegate = self;
    NSLog(@"jongel2");
    [self applyOrientation];
    NSLog(@"jongel3");
    self.capture = [[ZXCapture alloc] init];
    self.capture.camera = self.capture.back;
    self.capture.focusMode = AVCaptureFocusModeContinuousAutoFocus;
    NSLog(@"jongel4");
    [self.view.layer addSublayer:self.capture.layer];
    NSLog(@"jongel5");
    [self.view bringSubviewToFront:self.scanRectView];
    [self.view bringSubviewToFront:self.decodedLabel];
    NSLog(@"jongel6");
}

Comment: How can you set `delegate` for `self.capture` before initializing `self.capture`? ;)
Comment: BLEH thats what I get for working through the night !!!!! going to bed now works like a charm when you do things in the right order
Comment: Can i add an answer for your question ? ;)
Comment: of course I will accept it right away
Comment: Congratulation and good night ;)
Answer: Seem like you set delegate for self.capture before initializing self.capture. Try to set delegate after you initialize self.capture.
Comment: I think you mean AFTER though not before INIT
Comment: @MattDouhan My mistake, i have updated my answer. Thank you.


Meeting Organizer Changes, Duplicate Attendees, Duplicate Meetings

Question: I have a user who is ending up with a lot of duplicate meetings, duplicate attendees, and/or the meeting organizer changes.  This seems to happen when users outside the company reply to the meeting in someone, or try to reschedule.  The most consistent thing I think is that the meeting organizer changes to the person who replies.
The Exchange Server is 2003, client is Outlook 2007, and the user has a Blackberry and we are running BES.
I am having trouble locking down the problem, currently, any conflict warnings have probably been deleted.  I ran scanpst.exe and that didn't find issues.  The BB for email is set to "Mailbox Wins", I didn't see a similar setting in outlook.
Anyone know of any server side tools I can look at to try to understand the problem, or seen similar problems?
Answer: What version of BES are you using?  I know that the calendaring agent is missing in Exchange 2007 and must be added manually.  Incorrect versions can cause some superfunky behavior (technical term).  The solution there was to make sure that the CDO.dll file included on the BES server is the same version (or newer) than the version on the Exchange server.  Again, this was a situation I ran into with Exchange 2007, but I wouldn't be surprised if it was a similar issue for Exchange 2003.  I also remember seeing warnings in the application event log on the Exchange server (8206 and 8207 if I remember correctly).  I'd take a look in there and see if you don't see errors when the meetings are modified.
Edit:  I referenced a non-existent file earlier.  That may be part of your problem in locating it.  It is CDO.dll, not .sys.  Anyway, please reference this link since it seems to be much more detailed than I can offer.
Use this knowledge base article [KB-02937] from RIM to troubleshoot/verify your setup:
http://www.blackberry.com/btsc/articles/724/KB02937_f.SAL_Public.html
Comment: Where is that sys file located in both cases?
Comment: Go to the Exchsrvr\bin directory to check the version of the CDO.DLL file on your Microsoft Exchange Server.

Use the following document to help you figure out where your CDO.dll on the BES is located.  http://www.blackberry.com/btsc/search.do?cmd=displayKC&docType=kc&externalId=KB04912  It can technically be any location, so you really need to follow these steps.


SQL find rows whose column "tag" contains a tag

Question: I have a table for articles. Its major fields are:
id
article_name
content
tags (its values will be comma seperate example test, abc ...)

Now when I am on a detail page of any article. I want to show related article in my sidebar. For this if any other article uses the same tag as current article. I want to list those articles as related article. This is my query.
Can anyone please help me on this issue?
Answer: select.....
where  find_in_set(current article name,name of column)

try this
Answer: For minimum coding you can use FIND_IN_SET function.
 SELECT FIND_IN_SET('b','a,b,c,d');

But next time consider using an additional table to store each tag in separate record


Python DataType converter

Question: making a random converter, but need to get it to return None and print 'cannot be converted' when it attempts to change string to integer, string to complex etc. but can't use Try: Except: ruling.
import random

def random_converter(x):
    selection = random.randint(1,5)
    if selection == 1:
        return int(x)
    elif selection == 2:
        return float(x)
    elif selection == 3:
        return bool(x)
    elif selection == 4:
        return str(x)
    else:
        return complex(x)

for _ in range(50):
    output = random_converter('007')
    print(output, type(output))

If the datatype can't be converted then it should return None and print 'Cannot be converted' but can't use Try: except:
Comment: Welcome to Stack Overflow! Please take the [tour]. Try-except is the standard way to do this, so why can't you use it? Is this a homework problem? If so read [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822/4518341) under "Asking about homework", and [ask] more generally. Also you haven't actually asked a question. I'm inferring you're asking *how*, but it would help if you made that explicit.
Comment: what is the question?
Answer: A solution is to used isinstance
def random_converter(x):
    selection = random.randint(1,5)
    if selection == 1:
        if isinstance(x, int):
            return int(x)
    elif selection == 2:
        if isinstance(x, float):
            return float(x)
    elif selection == 3:
        if isinstance(x, bool):
            return bool(x)
    elif selection == 4:
        if isinstance(x,str):
            return str(x)
    elif selection == 5:
        if isinstance(x,complex):
            return complex(x)
    print("Can not be converted")
    return None

Comment: Agree. This function is not a conversion, the requested behavior is strange... I wanted to point out that using `isinstance` is a solution to handle types without exceptions.
Comment: This doesn't do any conversion at all... I think OP's actually asking how to handle `ValueError`s without using try-except.

Python DataType converter


Can't get value from dropdownbox to database

Question: I have a webform wherein the admin will add new records to database. The form has 1 dropdownbox drpDepartments and a few textboxes EmployeeID, Fname, Lname, etc. I can add a new record but the option chosen from the dropdownbox isn't changing. It's always the first value. Here are tables tblEmployee and tblDepartment.

Here's my Page_Load() code:
            sConn = new SqlConnection(sStr);
            daEmp = new SqlDataAdapter("SELECT * FROM tblEmployee", sConn);
            daDep = new SqlDataAdapter("SELECT * FROM tblDepartment", sConn);
            dsEmp = new DataSet();
            dsDep = new DataSet();

            daEmp.Fill(dsEmp, "tblEmployee");
            daDep.Fill(dsDep, "tblDepartment");

            dsEmp.Tables["tblEmployee"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployee"].Columns["EmployeeID"] };

            drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
            drpDepartments.DataTextField = "Description";
            drpDepartments.DataValueField = "DeptID";
            drpDepartments.DataBind();

And the btnAdd_Click() code:
       cb = new SqlCommandBuilder(daEmp);

        DataRow dRow = dsEmp.Tables["tblEmployee"].NewRow();
        dRow["EmployeeID"] = txtID.Text;
        dRow["Lname"] = txtLname.Text;
        dRow["Fname"] = txtFname.Text;
        dRow["Mname"] = txtMname.Text;
        dRow["Address"] = txtAddress.Text;
        dRow["Email"] = txtEmail.Text;
        dRow["Phone"] = Convert.ToInt64(txtPhone.Text);
        dRow["Jobtitle"] = txtJobtitle.Text;
        dRow["Salary"] = txtSalary.Text;
        dRow["DeptID"] = drpDepartments.SelectedValue;

        dsEmp.Tables["tblEmployee"].Rows.Add(dRow);
        daEmp.Update(dsEmp, "tblEmployee");
        dsEmp.Tables["tblEmployee"].AcceptChanges();

        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "test", "");
        Refresh();

Answer: The binding of dropdown must be only in !IsPostBack
if(!IsPostBack)
{
 drpDepartments.DataSource = dsDep.Tables["tblDepartment"];// Set DataSource Table First
        drpDepartments.DataTextField = "Department";// Set Column Name of DataTable to set as Text Field
        drpDepartments.DataValueField = "DepartmentID";// Set Column Name of DataTable to set as Value Field
        drpDepartments.DataBind();
}

If you bind the DropDownList in postback event, the dropdown will be re-binded in the the button_click (in the page_load) event and the value set by the user will be lost.
Comment: @user2971155 - You indicated that Subin resolved your issue.  Please be so kind as to choose his answer so he receives credit.  After all that's what we answer guys are here for :)


Add new content to an existing view

Question: As I have stated in my last few questions, I have almost zero knowledge on Drupal. I have just been given access to a website and told to make changes. So please bare with me and excuse my ignorance. View the below link:
http://www.ascoworld.com/about-us/our-people/leadership-team
The section with the photos and names/titles seems to be a "view"? I have found the edit page (see screenshot). All I am trying to do is add more people. How would I do this? I can seem to add more fields but that just adds to the existing people and not new ones. Any help would be greatly appreciated.
Thanks!
EDIT: Updated the link to live site. Apologies.
Answer: According to the View, to add more people into this display you need to adhere to the filter criteria the View is filtering on.
So, it looks like you need to:

Create a new node of Leadership Team
Fill out the fields
Set the 'Role' field to Leadership Team
Set the node to to published

You should now see it show up in the list.
Comment: For more information on Views and Content, you should consider obtaining a drupalize.me account - you will be up to speed in no time. https://drupalize.me/
Comment: Thanks for the quick response, Kevin. Sounds good but – and again, I'm sorry – but how would I do these steps? I am below beginner here! I honestly thought as it already exists, I would just be able to add more. But obviously not. Thanks.
Comment: Go to Content > Add Content in the admin, you should see 'Leadership Team' in the list of content you can create. The fields will be on that content form. After creating it based on my outline, it should appear in that View display.
Comment: Kevin, you are the man! Simple as that. Thank you very much for your help!
Comment: Thanks for the advice, I will look into that. One more question, how do I reorder these? Thanks!
Comment: In the Sort Criteria of that view, it is going by Weight, and then by Management Position. They should also be fields on the content you created. Adjusting that will change the ordering, you might have to edit multiple Leadership Team nodes to get the sort the way you want it.
Answer: The link you gave is a Admin view only.  I can't open it without your login.
But going off of your image here looks like your view settings are set to show the nodes with the role "Leadership Team".
All you have to do is go to the Content tab in administration view, and change existing nodes roles to "Leadership Team" or add new content with role "Leadership Team" this way it will be displayed on this view.
God Bless!
Comment: This View is based off of nodes, not users. So this won't work.
Comment: I think Kevin is right. I don't think that will work for this problem. I updated the link though if you want to have a better look. Thanks for the response.

Add new content to an existing view


Where did the solution go wrong?

Question: I made this post about a maximizing quadratic expression problem.
Here is the problem I made in the original post:

A table is to be constructed by gluing together $68$ cubes of dimension $1\times1\times1$. All four legs and the rectangular top will be formed by the cubes. The four legs must be the same length and must be one cube thick, and the top is one cube thick, as well. What is the maximum possible volume of the space between the table's top and the floor, excluding the space taken up by the table's legs?

This is my final solution:
Let a be the area of the top and c be the length of a leg.
a + 4c = 68
a = 68 − 4c
We let the maximum volume excluding the four legs equal ac - 4c = 256 - (16 2c)^2 after completing the square.
The maximum is 256 when c = 8.
This is the solution of a commenter:
Noting that subtracting 68−4=64, we can see that, if the legs are only 1 cube high, that leaves 8×8×1=64 for the table top. The space under the table (minus the legs) is 64−(4×1×1)=60 so the volume from the table top to the floor is 2∗64−4=124.
If we let the legs be 4×2=8, the table top is 5×12=60, volume: 3∗60−8=172.
If we let the legs be 4×3=12, the top is 68−12=54 volume: 4×54−12=204
If we let the legs be 4×4=16, the top is 68−16=52, volume: 5×52−16=244
If we let the legs be 4×5=20, the top is 68−20=48, volume: 6×48−20=268
If we let the legs be 4×6=24, the top is 68−24=44, volume: 7×44−24=284
If we let the legs be 4×7=28, the top is 68−28=40, volume: 8×40−28=292
If we let the legs be 4×8=32, the top is 68−32=36, volume: 9×36−32=292
If we let the legs be 4×9=36, the top is 68−36=32, volume: 10×32−36=284
If we let the legs be 4×10=40, the top is 68−40=28, volume: 11×28−40=268
It appears 292 is the maximum volume with outer dimensions of 8×5×8 or 9×6×6
The commenter's solution seems to work, but it contradicts my solution, another commenter's solution, and the book's answer. where did they go wrong?
Comment: We know the answer that works for the book (my $192-36=256$ implies that only the area under the table top is sought) so I posted a new answer showing how to find it. BTW, I upvoted your question. Smile. I think we've solved it. I hope you find it correct.
Answer: I posted a $2^{nd}$ answer to your original question and copied it here because I couldn't stand not knowing and tried my hand at find a derivative slope of zero.
Given 68 cubes, the table top is $68-4h$ where $h$ is the height of the legs.
Under the table we have $(h)(68-4h)=68h-4h^2$ and the total volume (sans legs) is $top+under-legs=(68-4h)+(68h-4h^2)-(4h)=68+60h-4h^2$.
For a continuous function, the max volume can be found by where the increasing/decreasing slope of the given function is zero.
The first derivative $\frac{d}{dh}(68+60h-4h^2)=-8h+60\implies 60-8h=0\implies 8h=60$
This tells us that the max leg height is $\frac{60}{8}=7.5$ If fractional heights were allowed the max volume would be $68+60h-4h^2=68+(60\times7.5)-(4\times7.5^2)=68+450-225=293$ but we are are restricted to the nearest integers. Soooo
$$68+60h-4h^2=68+(60\times7)-(4\times49)=68+420-196=292$$
and
$$68+60h-4h^2=68+(60\times8)-(4\times64)=68+480-256=292$$
Comment: The problem is that "table top" is ambiguous. To me, as a native English speaker, I interpret "between the table top" and the floor to mean *below* the bottom of the table top, not including the top at all. You're interpreting the table top to mean its top. That is plausible but not, to my ear, the natural interpretation. Language is sadly not always precise. As someone who taught calculus for over 40 years, I did my best to be precise.
Comment: English is my $1^{st}$ language as well and I have a BS in Math/Physics. I interpret your solution as meaning, "from the table's bottom to the floor". Let the question poster decide.
Comment: No, the bottom of the table top. I would add that if there is *any* "common sense" or "real world" interpretation of the question, it would be to maximize the storage space *under* the table — so we remove the room occupied by the legs and we certainly can't use the space the table top itself occupies. At any rate, I don't see the point of continuing. Enjoy your downvote :P
Comment: @Ted Shifrin The question did not say "the table top", it said "the table's top" introducing the ambiguity the you mentioned but don't seem to understand. A clearer author statement would have been something like "... between the bottom of the table top and the floor". You also did not provide a useful answer; instead you just posted a formula (with the answer included) that subtracts from the book answer $(256)$ with no explanation of how you derived it. True, $256-4(8-8)=256$ but it did not show how values other than $h=8$ would yield less than maximum.  I've  learn from downvotes.
Comment: I'm not learning a thing from you and your arrogance. The OP wanted an explanation of why the two solutions differed. That is what I supplied.
Answer: If we assume that the author of the textbook is language-challenged and meant only the area under the table top minus the legs, we can begin with the area of the table top (and under) as $h(68-4h)-4h=64h-4h^2.$ This function will rise from zero when $h=0$ to a peak and then fall back to zero when $h=16$ (when the top is reduced to $4\times4).$
The first derivative gives us slope and we want to find where the slope is zero (the peak). We can get the derivative of common functions like this by multiplying each term by the power of the designated variable and reducing the power by $1$. (note: in $\frac{d}{dx}, x$ is the designated variable). We want a slope of zero so.
$$\frac{d}{dh}(64h-4h^2)=64-8h\qquad 64-8h=0\implies64=8h\implies 8h=64\implies h=8$$
Plugging $h=8$ into the volume equation we get $$V=64h-4h^2=64\times8-4\times8^2=4\times64=256$$

Where did the solution go wrong?


Adding a line of code to all pages

Question: I have recently taken over the final stages of construction of 3 websites that were built in Drupal 7. I have never used drupal before and have run into a problem. My footer in one of the websites is not visible. This was due to the color style sheet not being pointed to in the page code. I copied the existing code into dreamweaver and resolved the issue, but cannot upload to the server as I cannot find the pages on the server, so i have no file i can replace.
The code looks like this:
@import url("themes/bartik/css/layoutb3ea.css?mry7g9");
@import url("themes/bartik/css/styleb3ea.css?mry7g9");
It needs to look tike this:
@import url("themes/bartik/css/layoutb3ea.css?mry7g9");
@import url("themes/bartik/css/styleb3ea.css?mry7g9");
@import url("sites/default/files/color/bartik-23dc1686/colors.css?m9ub8w");
You can see that the last line of code is missing.  I am used to working in dreamweaver and I am not familiar with the how the file system works in Drupal.
How do I add that line in to all the pages?
Comment: By looking at this, it seems that the site is using the Color module to alter the color on the site. I would just re-save the color settings first to see if that fixes. Files under sites/default/files is something created by Drupal - either an uploaded file, cached versions of CSS/JS, cropped images, etc.
Answer: You should familiarize yourself with Drupal theming. Check out the Theming Guide.
Basically, you want to edit the CSS in the theme that's currently being used on your site.
Answer: @dcmouyard is right. Also you can find YOURTHEMENAME.info and edit it. Find stylesheets[all][] = css/SOMECSS.css and add your stylesheet with path.

Adding a line of code to all pages


How can I make MS Exchange think that a samba PDC is running a version of windows later than Server 2003?

Question: I'm busy migrating my Active Directory to a Linux server (Centos 7) running Sernet's enterprise samba packackes (Version 4.1.14-SerNet-RedHat-9.el7)
The Domain Controller seems to be working well for all authentication, except Exchange.  The Informatino Store starts, then hangs on "Starting".
The event log shows the following warning:
Process STORE.EXE (PID=3100). The domain controller pdc.*.*.*is running
Windows (Unknown Operating System) (Unknown Service Pack).
Exchange Active Directory Provider requires that domain controllers are running
Windows Server 2003 Service Pack 1 or later versions of Windows.
How can I configure Samba to trick Exchange into thinking this server meets its requirements?
P.S.  I'm running Exchange 2010
Comment: I don't believe you can because Exchange relies on a lot of Active Directory things that Sernet won't provide properly. I really advise against this.
Comment: There are some times where "near enough" just isn't good enough. This is one of those times.
Comment: The SAMBA [project status page](https://wiki.samba.org/index.php/Samba/Status) shows Exchange support as being in development, noting it is "very much a work in progress" - although the [page history](https://wiki.samba.org/index.php?title=Samba/Status&action=history) suggests that line hasn't been updated in 2 years.
Answer: Have you tried to "Raise domain functional level"?
By default samba4 look like "Windows server 2003"
Answer: To just fake a Windows Operating System signature, find the computer account of your samba DC. In a properly configured Directory you would find this at OU=Domain Controllers,DC=mydomain,DC=myforest,DC=mytld. Edit the following attributes:

operatingSystem
operatingSystemServicePack
operatingSystemServicePackLevel

You are going to run into further trouble when the Exchange prep tools start probing into what's OS level your infrastructure is really running on.
According to the Active Directory Technical Specification, this information is stored on the nTDSDSA object that represents the Directory Service Agent on each DC, in the Configuration NC.
The attribute in question is msDS-Behavior-Version, and the docs provide a list of possible values and the corresponding OS levels.
I really don't believe this is feasible, but if you want to try, you'll probably have to emulate Windows behavior in a number of other places as well.
The msDS-Behavior-Version attribute is used to store the Forest Functional Level on the forest crossRefContainer (found in CN=Partitions,CN=Configurations,DC=myforest,DC=tld) and the Domain Functional Level on the Domain NC root object of each domain
There are some constraints as to which versions can coexist:

The Domain Functional Level of each domain cannot exceed that of the "oldest" DC in that domain
The Forest Functional Level cannot exceed that of the "oldest" Domain

To get a better understanding of what Exchange is "expecting", you might want to read through this chapter about special objects and behaviors in an Active Directory forest
Answer: Exchange does lots of checks.  One very specific check is looking at the Schema version (i.e.: in the Schema partition).  Out of interest, what's the rationale behind moving to Samba-based DCs?
Comment: Saving a hell of a lot of money ?