text:
Q: Are LEDs in modern streetlights usually pulsed? If so, roughly what frequency? I can think of some reasons why modern LED streetlights would likely be pulsed;

*

*Efficient voltage conversion starting from line voltage would likely include an AC or switching step higher than 60 Hz.

*Highest efficiency operation of LEDs often occurs at a current greater than can be sustained continuously due to heating issues.

*Conversion back to steady DC (edit: at line frequency 50/60Hz) would require additional components that could fail, and would have no benefit that would offset the reduced efficiency operation.

There is a short section in Wikipedia about pulsed LED operation but it just introduces the concept without addressing how widespread pulsed operation is in the field.
As long as the frequency were sufficiently high that there were no chance of flicker perception, it seems to me that LED streetlights would be pulsed - or at least the blue LEDs used to excite the phosphor. The phosphor could have a long enough half-life to make most of the spectrum of the resulting emitted light steady even if the LEDs were pulsed.
Because some white light LEDs rely much more on LED's primary blue light than others, I'm going to ask my question primarily about the LEDs themselves, rather than the emitted light.
Are LEDs in modern streetlights usually pulsed? If so, roughly what frequency? 100 Hz, 1 kHz, 10 kHz? While there could be substantial variation in some regions, I'd expect in regions where cities are implementing widespread conversion from gas (mercury, sodium) to LED, there must be some commonalities or general trends/convergence in design.

A: LEDs used for street lighting usually employ a DC/DC converter of some kind, with tight current control at its output. So, providing a steady current isn't reducing efficiency nor does it add unnecessary components which could fail, nor does it reduce the lifetime of the LEDs.
It's the simplest and most efficient way to drive a high-power LED array. Steady current, provided from a "pulsed" source.

A: You're making a wrong assumption that the efficacy goes up with higher power level. The opposite is true, to any meaningful power levels the efficacy decreases whenever you increase the current.
PWM is used because it's very easy to implement. If you set your current to the maximum you want to use, you can have linear brightness control by just adjusting the duty cycle. Adjusting current has nonlinear response requiring calibration table if absolute accuracy is important (it often is not).

As you can see from this 1W white led Lumen vs current curve, doubling the current does not double the light output. Whether this is important depends on your application. If you're dealing with a >1kW advertising backlight, the electricity bill easily exceeds the up front cost of the display module. There are also thermal considerations, with better efficacy you have less waste heat on your system.

To make things worse is that efficacy drops even more with higher junction temperature. This graph shows ambient temperature but essentially junction temperature works in similar fashion. They're just being difficult about it. Now PWM will average the heat output but still, worse efficacy requires higher average current which means higher junction temperature..
One downside of a PWM is that the load is nasty from SMPS point of view, you're effectively imposing constant radical transients to the poor thing. At the very least you need a large output capacitor to buffer the voltage dips and peaks at edges.
A problem with constant current driving is that it's more complicated, especially if you want adjustable output current. There are further complications with local dimming applications as Vf varies with output power level so your current regulator has to dissipate the difference.
Edit added bit about junction temperature.

A: To summarize: They wouldn't do it because it's not efficient, wouldn't keep the lights in safe spec, and is not viable as a way to control a large group of lights (owing to the distance and lack of versatility).
In street lighting, the name of the game is efficiency.
LEDs are inherently a difficult customer, since at their high-efficiency ranges, they are too non-linear** and most be driven by a constant-current power supply.
Operative word: "constant".
Since they already must drive it with a constant-current supply, if they also wanted to do PWM, that would add unnecessary complexity. And there's a much better way to dim LEDs using the constant-current supply already present.  Here, look at this datasheet on Page 11. Forward voltage vs forward current.  Note this graph is very distorted, for normalized, look at my endnotes.

If you're driving the LED at 3000ma and want to dim it, cut current to 1000ma, and voila. Of course it doesn't quite drop by 2/3, look at "flux vs current", same page.

At 1/3 the current, luminous flux drops from 235% to 95% of spec.  It's much more efficient at the lower current.  Voltage drops too, which nibbles a bit of the efficiency difference, but not by a whole lot.
Would someone deliberately use more emitters to improve efficiency? Absolutely.  Many commercial and industrial customers are looking at total life-cycle cost, and emitters are a small part of that.  If $100 more emitters saves $300 in electricity over the life of the fixture, it may be a smart move.  I had a guy who specced three LEDs at redline max 1400ma. It gave the needed light. However heat was the key issue.  I respecced using the datasheet "normal" current of 350ma and seven emitters.  Got the same light at half the heat.
Now that I've positively shown lower power is more efficient for LEDs, you can see where PWMing them is not efficient.  Running 3000ma at 33% PWM is worse than running 1000ma continuous.
Why would anyone PWM then?
In a perfect world, all dimming would be via something like the 0-10 volt signal widely used commercially, and each LED module would use the "adjust the output of the constant-current supply for perfect dimming" method.  However.. that does not work everywhere. Fact is... PWM is an efficient way to propagate a dimming signal.
Consider the lowly "LED strip".  A narrow strip of PCB, every 50mm (2") it has a CUT line, three LEDs and a resistor.  Or for an RGB strip, three RGB LEDs and three resistors. And with RGB, of course, they want to dim each channel individually. How do we get three dimming signals down to hundreds of little segments?  Cost makes it impossible to put adjustable-output constant-current power supplies on every 50mm segment. The only workable dimming method is PWM.
It gets better.  PWM is both the power and the signal.  If the PWM controller can only drive 3 amps, and you want to run seven 6A strips, you can use an amplifier: it receives the controller's output as a signal and uses it to gate its high-current outputs, tapping out PWM in lock-step.  The versatility is hard to beat.
And this works for any of a huge variety of LED lighting (whose purpose is notably, not efficiency.)  Nobody really cares about the lumens per watt here:
 src
Why not street lights, then?
It's not entirely unreasonable to dim LED street lights.  They could ease on at dusk, burn in excess of legal requirements to 11pm, then roll back in the haunting hours when hardly anyone is out.  But they wouldn't use PWM.  The signal won't propagate well over an installation the size of a town.
An LED street light takes high voltage (240-277V or even 480V which they tap off the nearest power line without metering, that means that PWMing the power line is right out)***. Internally, a street light has a sensible number of large emitters - ideal for series connection to a high voltage constant-current supply. This would be best dimmed by current adjustment.  They would either use radio - or if they were hardwiring an expensive signal wire, they would use it for a lot more stuff than dimming.  They might work with the power company to power-line-encode a data signal similar to how power companies can remotely shut off smart meters.  Adding $20 a unit for the transceiver is not a "deal breaker" on a $1000 street light.

** Incandescents are linear once lit, so sending 120V to them will reliably produce 60W.  Discharge lighting (fluorescent, neon, low/high pressure sodium, mercury vapor and metal halide) is totally non-linear: once struck, they are a dead short and must be current-limited by a ballast/driver.  In the case of LEDs, their voltage-current curve is quite steep, You remember the Voltage vs Current chart from This data sheet page 11.  Look again: The scale is distorted, and volts don't start at zero.  If corrected, the graph would look like this:

That's what you call non-linear. Remember, this line moves a little depending on temperature, age, binning, etc. and when the line is that steep, a little is a lot.  Send 3.05V and who knows what'll happen! The manufacturer only guarantees what'll happen if you send 2500ma. Every other chart in the datasheet is based on current, for that reason.
*** The power company and the city agree how much power a normal street light draws, and the power company simply multiplies by the number of lights, and bills them.

A: In general, there are two methods of dimming LEDs, PWM dimming and Amplitude dimming. What you refer to as DC dimming is amplitude dimming.
In professional lighting applications, PWM is no longer used for dimming , mainly due to health concerns over the generated flicker. With street lighting, another issue is the stroboscopic effect. You will find today that virtually all professional LED drivers including street lights use amplitude dimming. You can read more about flicker and dimming here.
Update: In response to some of the comments, I would like to extend my answer.
By professional lighting applications, I am referring to constant current dimmable >20W LED drivers such as these, not cheap and nasty halogen or bulb replacements or computer backlight applications.
There are two causes of flicker, one is caused by the mains ripple propagating to the output. Cheap single-stage LED drivers such as those used in bulb replacements suffer from this phenomenon.
The second type of flicker is caused by PWM dimming. This may be perceptable or imperceptable. The IEEE PAR1789 is a recommendation of how high the PWM frequency needs to be for it to be considered imperceptable. That said, you will find in industry that high-quality LED drivers for professional applications almost exclusively use amplitude dimming (DC dimming).


text:
Q: With a UNCHECKED checkbox, how to filter out NSFW tagged divs to be hidden at all times but when checked ON, to follow the visibility rules? This question is based on this Question/Answer:
Filter accurately with BOTH checkboxes AND dropdown menus at the same time
Hi!
(NOTE, the simplified question and code is in the codepen or the snippet below, here I'm just explaining the context.)
Image of the simplified question, for which I actually need the answer:

My reference image PHP gallery is progressing nicely: https://manu.mymaterial.org (Watch out, it includes NSFW material, Fine Art painting by Andrew Loomis, in the front page ATM.)
And that brings me to this question.
How can I have that "Display NSFW material" to NOT show ANY of the images that have the NSFW tag in them when the "Display NSFW material" checkbox is UNCHECKED, no matter what other filtering options I do?
I have a feeling that it is a simple if-statement in Javascript, but I'm uncertain where to put it exactly and if it breaks other things.
At the moment the NSFW checkbox displays ONLY the NSFW material (yellow box) and nothing else. This is not desired.
So, in other words, I have tags for all of the material to be shown in various ways - but now the NSFW tag should HIDE stuff when included into a div. Or in my case, it's just an image file that gets processed by PHP and into a div: Andrew_Loomis; Traditional_Characters_Realistic_Color_NSFW.jpg
Codepen project:
https://codepen.io/manujarvinen/pen/wvdzeQv
Thank you all, this is a fine place.
Image of my project thing:

var $filterCheckboxes = $('input[type="checkbox"]');
       var $filtermenues = $('.grid1');

       var filterFunc = function () {

           var selectedFilters = [];
           $filtermenues.find(":selected").each(function () {

               var v = this.value;
               if (selectedFilters.indexOf(v) === -1 && v)
                   selectedFilters.push(v);
           });

           $('.animal' && '.filterDiv')
               .hide()
               .filter(
                   function (_, a) {
                       var itemCat = $(a).data('category').split(' ');
                       if (itemCat.indexOf("showAll") > -1)
                           return;
                       return selectedFilters.every(
                           function (c) {
                               return itemCat.indexOf(c) > -1;
                           })
                   })
               .show();
           $filterCheckboxes.filter(':checked').each(function () {
               var v = this.value;
               if (selectedFilters.indexOf(v) === -1)
                   selectedFilters.push(v);
           });

           $('.animal' && '.filterDiv')
               .hide()
               .filter(
                   function (_, a) {
                       var itemCat = $(a).data('category').split(' ');
                       return selectedFilters.every(
                           function (c) {
                               return itemCat.indexOf(c) > -1;
                           })
                   })
               .show();

       }

       $filterCheckboxes.on('change', filterFunc);

       $('select').on('change', filterFunc);
body {
width: 100%;
text-align: center;
background-color: black;
color: white;
font-family: sans-serif;
}
.grid {
width: 300px;
margin: 50px auto;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
.grid1 {
width: 300px;
margin: 50px auto;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
.filterDiv {
width: 100px;
height: 100px;
padding-top: 20px;
color: black;
font-weight: bold;
}

          <select>
              <option value="">--</option>
              <option value="violet">violet</option>
          </select>
          <select>
              <option value="">--</option>
              <option value="blue">blue</option>
          </select>
          <select>
              <option value="">--</option>
              <option value="yellow">yellow</option>
          </select>

      VIOLET
      <input type="checkbox" value="violet" />

      BLUE
      <input type="checkbox" value="blue" />

      YELLOW
      <input type="checkbox" value="yellow" />

Tags:
violet
blue

Tags:
violet
red
MVP

Tags:
yellow
NSFW
MVP

  Most Valuable Players (MVP)
  <input type="checkbox" value="MVP" />

  Display NSFW material also
  <input type="checkbox" value="NSFW" />

    What I need:

By default, NSFW material checkbox is OFF and YELLOW shouldn't be seen at all in ANY situation.

When NSFW material checkbox is checked, ALSO YELLOW should be seen, but follow rest of the rules.

A: The code is overly complex, and hard to follow. For one, this bit
        var v = this.value;
        if (selectedFilters.indexOf(v) === -1 && v)
            selectedFilters.push(v);

merely serves to avoid duplicates in the array. This means that it is more like a set, which is a data structure that avoids duplicates by itself. If you do selectedFilters = new Set(), then that entire block can be replaced by selectedFilters.add(this.value);
Queries "is this category contained in the selected filters" can then also be reduced from selectedFilters.indexOf(cat) === -1 to selectedFilters.has(cat). That way the code already starts to match much more the desired behaviour.
Furthermore, the single-letter variables should also be abolished, and be replaced by explanatory names. The code should also have more comments to explain what's going on.
Then there is the confusion of being able to select filters from both the menu and the checkboxes. I'm not sure how this should work, so I've just changed the code such that it groups them all together: a filter is active when it's either selected by the checkbox or the menu.
Finally there is the problem that the "NSFW allowed" is not really the same as filtering of the other categories. Because of that, I just created a separate variable for it, and removed it from the filter. And finally finally I added an extra call to filterFunc() so that things start out filtered (instead of waiting for the first change to the filter checkboxes/menus). This is the end result.
EDIT: Updated for the "MVP only" checkbox.
EDIT 2: Don't let the "MVP" checkbox show everything with the MVP tag.
EDIT 3: Flipped the condition to show items; they need all the tags now. The old code is left commented-out, so that anyone can revert this switch for themselves if they want.
var $filterCheckboxes = $('input[type="checkbox"]');
var $filtermenus = $('.grid1');

// Return the intersection of setA and setB.
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
function intersection(setA, setB) {
    let _intersection = new Set()
    for (let elem of setB) {
        if (setA.has(elem)) {
            _intersection.add(elem)
        }
    }
    return _intersection
}
function isSuperset(set, subset) {
    for (let elem of subset) {
        if (!set.has(elem)) {
            return false
        }
    }
    return true
}

function filterFunc() {
    var selectedFilters = new Set();

    // Gather tags from the menus.
    $filtermenus.find(":selected").each(function () {
        if (this.value)
            selectedFilters.add(this.value);
    });
    // Gather tags from the checkboxes.
    $filterCheckboxes.filter(':checked').each(function () {
        if (this.value)
            selectedFilters.add(this.value);
    });
    console.log("selected filters:", [...selectedFilters]);

    let mayShowNSFW = selectedFilters.has("NSFW");
    selectedFilters.delete("NSFW");

    let mustShowMVPOnly = selectedFilters.has("MVP");
    selectedFilters.delete("MVP");

    $('.filterDiv')
        .hide()
        .filter(
            // Returns 'true' to show items, 'false' to hide them.
            function (_, element) {
                let itemCats = new Set($(element).data('category').split(' '));

                // If the item has tag 'showAll', always show it.
                if (itemCats.has("showAll"))
                    return true;

                // If item is NSFW but that's not in the filters, hide the item
                // regardless of other tags.
                if (itemCats.has("NSFW") && !mayShowNSFW)
                    return false;

                if (mustShowMVPOnly && !itemCats.has("MVP"))
                    return false;

                // If there are no filters at all, just show everything.
                if (selectedFilters.size == 0)
                    return true;

                // If this item has all the tags, show it:
                return isSuperset(itemCats, selectedFilters);

                // If this item has any of the tags, show it:
                // return intersection(selectedFilters, itemCats).size > 0;
            })
        .show();
}

$filterCheckboxes.on('change', filterFunc);
$('select').on('change', filterFunc);
filterFunc();

A: You can add this in your css stylesheet

.nsfw{
    visibility: hidden;
}

And this should be in the head tag of your html page

Your nsfw box should be something like this

Tags:
yellow

NSFW
MVP

Here is the checkbox

        Display NSFW material also
            <input type="checkbox" value="NSFW" id="nsfw" />

A: You can give a class to all nsfw images and then set their visibility to hidden in css. and when checkbox is checked you can set nsfw images visibility to hidden.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Равномерное распределение данных по таблицам Попалось мне тестовое задание

Имеется 2 таблицы следующего содержания:
Таблица А:
Референс договора на кредитную карту REP_REF (тип поля текстовый)
Бранч (код отделения) договора ECA_BRNM (тип поля текстовый)
Логин сотрудника, за которым закреплен договор LDAP_EXPERT (тип поля текстовый)

Таблица Б:
Логин сотрудника LDAP_LOGIN (тип поля текстовый)
Бранч (код отделения) сотрудника ECA_BRNM (тип поля текстовый)
Код бизнеса сотрудника BUS_BUS (тип поля числовой)
Код должности сотрудника POSIT_POS (тип поля текстовый)

Задача:
Отобрать все договора, которые закреплены за сотрудником, работающем на бранче, который не совпадает с бранчем договора или если указанного сотрудника нет в таблице Б. Найти в таблице Б сотрудника который работает на бранче договора.
------- в котором есть одно из  условий
4)      если на бранче найдено несколько сотрудников указанных выше бизнесов, то распределить договора равномерно между ними
Пробую использовать
COUNT(DISTINCT LDAP_EXPERT) AS exp_cnt  FROM A
into #EXP_COUNT
IF  (#EXP_COUNT.exp_cnt ) > 1
NTILE(2) OVER(PARTITION BY  REP_REF ORDER BY LDAP_EXPERT) gr
FROM BUS_BUS ORDER BY  *********??.

но мне кажется, что это полная муть. Как правильно использовать для этого  условия эту функцию ?
или можно  обойтись простыми вещами
по логике, должно  работать так
нужно посчитать кол-во договоров и кол-во сотрудников, между к-ыми их нужно распределить
далее, пронумеровать договора подряд (от 1 и до кол-ва сотрудников)
и пронумеровать сотрудников
далее к таблице с договорами сджойнить таблицу с сотрудниками по условию, что номер у договора совпадает с номером у сотрудника
помогите составить запрос

A: Я не понял как пользоваться NTILE, точнее как правильно передать ему нужное количество, полученное в том же запросе. И решил взять записи с одинаковыми остатками от деления порядкового номера записи в разрезе договоров и в разрезе сотрудников на количество сотрудников. Так же из вопроса не ясно какое поле является первичным ключем в таблице договоров, написал ID, замените на нужные в выборке поля.
select id,LDAP_LOGIN
  from
  (
   select A.id,B.LDAP_LOGIN,
          row_number() over(partition by A.id order by B.LDAP_LOGIN) rn,
          row_number() over(partition by B.LDAP_LOGIN order by A.id) rn2,
          count(distinct B.LDAP_LOGIN) over() cnt
     from A, B
    where A.ECA_BRNM=B.ECA_BRNM
      and not exists(select 1 from B as B1
                      where B1.LDAP_LOGIN=A.LDAP_LOGIN
                        and B1.ECA_BRNM=A.ECA_BRNM
                    )
  )
where mod(rn2,cnt)=mod(rn,cnt)

not exists в запросе, что бы взять те договора, для которых назначены неверные сотрудники. Что сказано у вас в начале задачи, но вы это опускаете в итоговой формулировке как бы вы это сделали.
Что в вопросе означает "указанных выше бизнесов" совершенно не ясно, потому как выше ничего подобного не сказано. Если надо добавите необходимые дополнительные условия.
P.S. запрос писался для Oracle, все используемые функции есть в Sybase. Может потребоваться написать что то внутри пустого over() который для Oracle означает окно размером во всю выборку.


text:
Q: Bootstrap dropdown menu content covered by content below: https://www.dropbox.com/s/aqr0444isul1rky/Screenshot%202014-09-23%2022.06.49.png?dl=0
Above is an image of the about us dropdown in the header.  When I click it, the below content is currently taking priority over the dropdown menu content.
This should not be the case but it is.  Below is a picture of what it looks like when I click it:
https://www.dropbox.com/s/5ud446l7hpz7veg/Screenshot%202014-09-23%2022.08.15.png?dl=0
As you can see it's white and the content below is covering it from showing.  There is a little white space but it's not taking up what it should.
I've searched around SO/Google and most answers say to add a higher z-index.  I have tried this and it did NOT work.
This is the current CSS for the header (non-bootstrap but it works) and it shows the content properly:
#nav > li > ul {
position: absolute;
border: 5px solid #008553;
border-width: 5px 0px 6px;
padding: 27px 26px 30px 26px;
left: -9999em;
top: 35px;
width: 908px;
background: #f1f7f4;
z-index: 500;
-webkit-box-shadow: 0px 3px 3px 0px rgba(30, 30, 30, 0.3);
-moz-box-shadow: 0px 3px 3px 0px rgba(30, 30, 30, 0.3);
box-shadow: 0px 3px 3px 0px rgba(30, 30, 30, 0.3);
}

What can be the solution to this?  There is other CSS from a wordpress website -- how can I tell the dropdown menu to be given priority to take up this space?

A: try this
.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu {
      position: absolute;
      border: 5px solid #008553;
      border-width: 5px 0px 6px;
      padding: 27px 26px 30px 26px;
      left: -9999em;
      top: 35px;
      width: 908px;
      background: #f1f7f4;
      z-index: 500;
      -webkit-box-shadow: 0px 3px 3px 0px rgba(30, 30, 30, 0.3);
      -moz-box-shadow: 0px 3px 3px 0px rgba(30, 30, 30, 0.3);
      box-shadow: 0px 3px 3px 0px rgba(30, 30, 30, 0.3);
}


text:
Q: how to use the edmx and functions created by it for calling stored procs? I have the edmx in the DAL and it has automatically created functions and complex types for all the stored procs. I am able to call the stored procs using the entity object.
Now in the Business Logic Layer I am creating an object for DAL in a class level.
i.e
public class ProjectBO   //Business object
    {
       ProjectEntities Entities = new ProjectEntities();

       public IEnumerable<usp_Project_Team_GetTeam_Result> usp_Project_Team_GetTeam(string strAssociateId)
       {
           return Entities.usp_Project_Team_GetTeam(strAssociateId);
       }
}

I call this function from handlers. So my question is since i have created the object for entity in class level, will the connection be opened as soon the object is created and it will remain open throughout??
are there any equivalent command like connection.close() to close the connection when it is not needed to open it?! or will the edmx open and close the connection as soon as the data is fetched from the db ???

A: Your Entities variable is within the scope of an instance of ProjectBO. So when your garbage collector runs, your DB connection will be cleaned up. Not ideal.
A better option is to explicitly give it a narrower scope:
public IEnumerable<usp_Project_Team_GetTeam_Result> usp_Project_Team_GetTeam(string strAssociateId)
{
   using (ProjectEntities Entities = new ProjectEntities())
   {
       return Entities.usp_Project_Team_GetTeam(strAssociateId);
   }
}

This way your connection will be opened and closed exactly where you would expect.


text:
Q: How to check if user is logged in and redirect them to the right screen using Jetpack Navigation what is the best way to save user logged in state, check if they logged in or not and redirect them to the right screen. I'm not using firebase Auth in this current project please any help would be appreciated!

A: the page where we created the user
val prefences = activity?.getSharedPreferences("control", Context.MODE_PRIVATE)
val editor = prefences?.edit()
editor?.putString("usercontrol",value) // After creating the user you give value 1
editor?.apply()

on the login page
val shared = getSharedPreferences("kontrol", MODE_PRIVATE)
        val control = shared.getLong("date", 0)

I suggest you look at the SharedPreferences structure


text:
Q: How to generate "x" jQuery scripts with a for loop? This might sound very strange and probably it is, so forgive me if I'm committing a bad mistake.
I have an unspecified number of <input type='text'>, generated at runtime and identified with a progress number id like id='data1', id='data2'...I would like to have a jQuery script on every input. I thought to generate x scripts for x inputs but it doesn't work.
How could I do this?

function addPreparations (nos, pietanze) {
  var numeroTotale = nos.value;
  var box = document.getElementById("box_righe");
  generateScripts(numeroTotale);
  if (numeroTotale == '') {
    box.innerHTML = '';
  }
  else {
    var righe = "
";
    righe += "Pietanza	U. di Misura	Quantità	Cuoco	Data di Preparazione	";
    for (i = 1; i <= numeroTotale; i++) {
      righe = righe + "
<select name='pietanza"+i+"' class='form-control' onchange='showMU(this.value, \"p\", "+i+");'>";
      righe = righe + "<option value=''>Selezionare la pietanza "+i+"</option>";
      for (j=0; j<pietanze.length; j++) {
        righe = righe + "<option value='"+pietanze[j]+"'>"+pietanze[j]+"</option>";
      }
      righe = righe + "</select>	";
      righe = righe + "
- - -
	";
      righe = righe + "<input type='number' placeholder='Inserire la quantità' name='quantita"+i+"' class='form-control'/>	";
      righe = righe + "<input type='text' placeholder='Inserire il cuoco' name='cuoco"+i+"' class='form-control'/>	";
      righe = righe + "<input type='text' placeholder='GGMMAAAA' id='data"+i+"' class='form-control' name='data"+i+"' />
";
    }
    righe = righe + "
";

    righe = righe + "<input type='submit' name='storageConfirm' value='Conferma' class='btn btn-success'/>&nbsp&nbsp";
    righe = righe + "<input type='reset' value='Reimposta' class='btn btn-danger'/>";

    box.innerHTML = righe;
  }
}

function generateScripts (total) {
  for (i=1; i<=total; i++) {
    $(document).ready(function() {
      $("body").on('keydown', '#data'+i, function(e) {
        if ((e.keyCode == 8) || (e.keyCode >= 96 && e.keyCode <= 105) || (e.keyCode >= 48 && e.keyCode <= 57)) {
          return;
        }
        else {
          alert("Solo numeri!");
          e.preventDefault();
        }
      });
    });
  }
}

A: Use attribute selector [] with the start with ^ selector ([id^="data"]), your code should be :
$(document).ready(function() {
    $("body").on('keydown', '[id^="data"]', function(e) {
        //Your logic HERE
    });
});

Or you could give all your inputs a common class and use it as selector like :
$(document).ready(function() {
    $("body").on('keydown', '.common_class', function(e) {
        //Your logic HERE
    });
});

NOTE : It's better to use the input event when you track the user input, like :
$(document).ready(function() {
    $("body").on('input', '[id^="data"]', function(e) {
        //Your logic HERE
    });
});

Hope this helps.

A: You do not need the loop here.  What you want to do is add a class to each of these elements.  Something like inputdata; make sure this same class is on all of the inputs.
Then you can just do:
$(document).ready(function(){
    $('body').on('click', '.inputdata', function(e){
    });
});


text:
Q: hide span with validator asp.net Is it possible to completely hide css validator ? Despite its not visible as a text, there is visible space for it. In html there is simply a span with visibility hidden but it takes space:
Situation after adding requiredFieldValidator is shown below:
http://imageshack.us/g/571/desirez.png/
Thank You very much for help.

A: Try setting the display property of the validator to dynamic. By default, it's set to static, which will render space for it on the page. If you set it it to dynamic, I'm quite certain it uses display:none to hide it completely.


text:
Q: When in physics we assume a quantity is constant over an interval dt, why/how is this justified? Unsure about whether I should have posted it here or on the physics stackexchange, but since this feels to me more like a question about calculus, I have posted it here.
An example would be when we're finding the work done by a varying force $F(x)$ over some interval $[x_1,x_2]$. We assume that the force is constant over $\Delta x$ as we take the limit $\Delta x \to 0$. What I want to know is, what exactly is the mathematical assumption we're making here? I.e what quantity's limit is approaching zero or some quantity, as we take $\Delta x\to 0$. I want to know this so I know how to verify if this assumption is valid.

A: The way the calculation works is a bit more subtle. Let's say the interval $[a,b]$ is given, and you want to calculate the work done by the force $F(x)$ as $x$ changes from $a$ to $b$.
We now do subdivide the interval $[a,b]$ into parts, which are usually equal (but sometimes inequal). This is done by placing additional points $a=x_0<x_1<x_2<\cdots<x_n=b$. For example, set $x_i=a+\frac{b-a}{n}i$.
What we do next is not exactly keeping $F(x)$ constant on the intervals $[x_i,x_{i+1}]$ - this is sort of a simplification of what we really do.
Instead, on each of those intervals we take the maximum and the minimum force: the actual work done on $[x_i,x_{i+1}]$ by real $F(x)$ must be between $(x_{i+1}-x_i)\min_{x_i\le x\le x_{i+1}}F(x)$ and $(x_{i+1}-x_i)\max_{x_i\le x\le x_{i+1}}F(x)$. (For pedants: we are really taking the supremum and infimum, not maximum and minimum, but I will use the symbols $\max$, $\min$ throughout.)
Now we sum those across $i=0,1,2,\ldots,n-1$ to get something we call lower Darboux sum and upper Darboux sum:
$$\sum_{i=0}^{n-1}(x_{i+1}-x_i)\min_{x_i\le x\le x_{i+1}}F(x)$$
$$\sum_{i=0}^{n-1}(x_{i+1}-x_i)\max_{x_i\le x\le x_{i+1}}F(x)$$
Now, if we can prove that those two sums converge to the same number as the division of $[a,b]$ grows finer and finer, then it is natural to call that number the work done by $F(x)$ on $x\in[a,b]$. Or, in maths, we call that the Riemann integral of $F(x)$ on interval $[a,b]$ and denote it:
$$\int_a^b F(x)dx$$
More precisely, if the upper and lower Darboux sums exist for every subdivision of $[a,b]$ and converge to the same value as the maximum size of the intervals in the subdivision tends to $0$, then we call the function $F$ Riemann-integrable, and we call the common limit of the two sums the Riemann integral of $F(x)$ over $[a,b]$. Otherwise, we say that $F$ is not Riemann-integrable.

Side note: If a function $F$ is Riemann-integrable on $[a,b]$, this automatically means that the method of keeping $F(x)$ constant on the intervals $[x_1,x_{i+1}]$ also works! Namely, as long as you pick $F(x)$ on each interval equal to some value of it on that interval (e.g. keep it equal to $F(x_i)$ or to $F(x_{i+1})$ or even to $\frac{1}{2}(F(x_i)+F(x_{i+1})$) - the sum you're getting is between the lower and the upper Darboux sums. That means that, having both the upper and lower Darboux sums converge to $\int_a^b F(x)dx$, your sum (squeeze theorem!) converges to the same value!

Back to the integration: why does it work in physics so well that you don't ever get to ask the question about Riemann integrability? I believe this mostly comes from the fact that (unlike some very hairy functions that we study in maths), in physics most functions are assumed to be well-behaved: normally continuous, often more than that (smooth - i.e. differentiable, often infinitely many times). So a theorem comes handy:
Theorem: Every continuous real function $F$ on $[a,b]$ is Riemann-integrable.
Proof (sketch): I won't go down to show the full proof here, but there is a bunch of prerequisites:

*

*Every continuous real function $F$ on a closed interval is bounded.

*

*This means, for every subdivision $a=x_0<x_1<x_2\cdots<x_n=b$ of $[a,b]$ both the lower and upper Darboux sum make sense.

*Every continuous real function $F$ on a closed interval is uniformly continuous.

*

*This is a condition often stronger than "just" being continuous, and it means that, if you pick a small $\epsilon>0$, you can always find the size $\delta>0$ of a small interval so that, whenever $|x-y|<\delta$ you have $F(x)-F(y)<\epsilon$. In other words, the values of $F$ come close "enough" to each other across the whole interval as the points on which you calculate $F$ come close "enough".

Because of the above uniform continuity, all of $\max_{x_i\le x\le x_{i+1}}F(x)$ and $\min_{x_i\le x\le x_{i+1}}F(x)$ are also smaller (or equal) than $\epsilon$ if we set $|x_i{+1}-x_i|<\delta$, so one can see that the upper and lower Darboux sums differ by at most $\epsilon(b-a)$. You see that you can now make that difference arbitrarily small by choosing $\epsilon$ arbitrarily small and then choosing the subdivision to be as fine as the corresponding $\delta$ (or finer).$\,\blacksquare$
This theorem is then extended in different directions:

*

*If a bounded function has finitely many discontinuities, it can still be proven to be Riemann-integrable.

*If a function is not bounded on $[a,b)$ but is Riemann-integrable on all $[a,c]$ with $a<c<b$, we may still try to define $\int_a^b F(x)dx:=\lim_{c\to b-}\int_a^c F(x)dx$ (if the limit exists) and we call that value an improper integral of $F$ on $[a,b)$. $b$ could be taken to be a finite real number or $+\infty$.

*There is a different definition of something called Lebesgue integral, which is a generalization of the previous two, although in fact it is more than "just" a generalization and covers many more pathological cases.

Anyways - the bottom line is that, as long as your force $F(x)$ is continuous (or has finitely many discontinuities), it is Riemann-integrable, and so your method works, and it produces the value of the Riemann integral $\int_a^b F(x)dx$, which (as we concluded above) is the only sensible number to call the "work done by this function".
Further reading:

*

*Riemann integral (original definition)

*Riemann-Darboux integral (an equivalent definition which is explored in this answer)

*Improper integral

*Lebesgue integral

*Continuous functions are bounded (a question here, on MSE)

*Uniform continuity

*How to prove that continuous functions are Riemann-integrable (another MSE question)

A: Let me first rephrase the question to make sure I understand it right. You have a function $F(x)$, and you are trying to find out what conditions are required on $F$ to assume that $F$ is constant over an infinitesimal interval.
Basically, you need to ensure that your function does not vary highly in suitable small intervals and that any change in $F$ that happened in $\Delta x$ should limit to $0$, as $\Delta x \to 0$. You would like to avoid $F$ from being functions such as, say, Dirichlet function.
Short answer : Yeah, as you have noted in a comment, continuity of $F$ seems to be a sufficient condition for this.

Slightly longer answer: Note that trying to make sense of this process of dividing up the domain into very small intervals, assuming $F$ is constant on that interval, and adding all the $F \Delta x$ up to form an approximation of what the integral (in this case, the Work) should be; such that it becomes a better and better approximation as $\Delta x \to 0$, is exactly what Riemann integration, and constructing Riemann integrals, are all about.
So the class of functions you are looking for is probably the class of Riemann integrable functions. But then, all the continuous functions on $\Bbb R$ are Riemann integrable, and thus checking for continuity is a sufficient condition for you in this case.

A: You need to separate motivations from definitions (or theorems). This is I think unfortunately not clearly distinguished in introductory Physics explanations. We often gain our intuition and motivations when things are constant/piecewise constant, and then we use that insight to formulate a general definition/theorem.
For example, since middle/high school, we introduce the concept of work done (by a given force on a given object) to be the product of the force with the distant moved in the direction of the force. This idea makes a lot
sense when we look at "simple" everyday idealizations, e.g moving a ball from the ground to the top of a shelf etc. But, once you have this idea for constant forces, you can easily generalize the intuition to piecewise constant forces. Finally, once we have enough of an idea, we formulate a rigorous definition:

Definition.
Let $U\subset\Bbb{R}^n$ be an open set, $\mathbf{F}:U\to\Bbb{R}^n$ a continuous vector field, and $\gamma:[a,b]\to U$ a (piecewise) $C^1$ path. We define the work done by $\mathbf{F}$ along the path $\gamma$, $W_{\mathbf{F},\gamma}$, to be the line integral
\begin{align}
W_{\mathbf{F},\gamma}&:=\int_{\gamma}\mathbf{F}\cdot d\mathbf{l}:=\int_a^b\mathbf{F}(\gamma(t))\cdot\gamma'(t),dt.
\end{align}

If you only wish to focus on the one-dimensional case, this reduces to $\int_{x_1}^{x_2}F(x)\,dx$ (where the path starts at $x_1$ and ends at $x_2$).
So, this integral formula is just a definition! We as humans are allowed to make whatever definitions we like (as long as it doesn't cause logical contradictions with the theory we have already developed). So, there is no longer any question of why we're allowed to "assume forces are constant over $\Delta x$, and then take $\Delta x\to 0$". A definition is a definition. However, you can ask why it is a good definition, and here some of the reasons are:

*

*It is a pretty general definition for work done by a force field, and as a result applies to a wide range of scenarios, and also due to the generality, it "unifies" many previously separate ideas. For instance, the definition makes no reference to any specific type of force field, i.e the definition applies equally well to gravitational fields, electricmagnetic fields, to frictional forces acting on a curved inclined ramp etc.

*One can easily see that in the case of constant/piecewise-constant forces and piecewise-linear paths, this definition reproduces what we already expect. So, it conforms to our intuition.

*A slightly more difficult-to-motivate reason is because the mathematical quantity $\int_{\gamma}\mathbf{F}\cdot \,d\mathbf{l}$ appears all over physics, so giving this quantity a name is convenient. Part of the reason this quantity appears all over is because Newton's second law is given in ODE format: $\sum_i\mathbf{F}_i=m\mathbf{a}$ (now you can of course question why it is valid to describe nature using a second order ODE, but this is just an approximation… though a very good one for most everyday (and even slightly beyond) purposes. So in this sense, the definition is also physically reasonable). This is a vector quantity, so not necessarily easy to deal with, so one of the things we like to do is consider specific scalar quantities, and it has proven (by experience) to be useful to consider various integrated quantities (work done, kinetic energy, potential energy etc etc, and to consider relationships between them).

Above, I described the situation for the motiviation/definition of work done. We can make exactly the same argument for other things, like mass of a rigid body, center of mass, moment of inertia and so on. These are usually given by various integral formulae, whereby the motivation for these integral formulae comes by considering the case of constant/piecewise-constant/pointlike things. For mass/mass density specifically, you may find some of the remarks here What does it mean to integrate with respect to mass? helpful (but be warned, that answer was intentionally written at a higher level of math sophistication).

A: This, to me, looks similar to the analogy used to explain that the Riemann integral is a "good approximation" of the area underneath a function: if you take $\Delta x\to 0$ you are taking such a small interval that the function changes value so little that considering it constant is a good approximation: thus you can approximate the area underneath a function with the sum of many little rectangulars.
Note that I chose the analogy with the integral because the work done by a changing force is actually the integral of the force function, over the time interval that you're interested in.
For visual intuition, see https://commons.wikimedia.org/wiki/File:Somme-superiori.png#/media/File:Somme-superiori.png

A: Riemann integration has 'upper sums' and 'lower sums'.  They get introduced in university mathematics.
Divide the interval $[x_1,x_2]$ into $n$ intervals, so $\Delta x=(x_2-x_1)/n$.
Let $m_i$ be the lowest value of $F(x)$ in the $i$th interval of $\Delta x$.  The sum $L_n = \Sigma m_i\Delta x$ is a lower bound for the true answer.
In the same way, let $M_i$ be the highest value of $F(x)$ in the $i$th interval.  Then $U_n=\Sigma M_i\Delta x$ is an upper bound for the true answer.
If $F(x)$ is always increasing, or if it is always decreasing, then $$|U_n-L_n|\le
\left(\max(F(x))-\min(F(x))\right)\Delta x$$
So, as $\Delta x\to0$, the upper bounds and lower bounds approach the same value.
If $F(x)$ increases and decreases a finite number of times, the difference between the upper bounds and the lower bounds still approaches zero.  The integral is the only number left between all the lower bounds and all the upper bounds.


text:
Q: Xcode 4 : Re-signing the xcode archive for release My client wants to submit the project by himself so he asked me to get the xcode xcarchive of the project and send him to sign it and upload it.
He gave me his development certificate, I installed it and sign the target with its provision profile.
The build configuration that I'm using for signing is a copy of "Release".
Now when he tries to resign the archive and submit it, iTunes throw an error Invalid Binary and the culprit is the Signature
Its says :

Invalid Signature - Make sure you have signed your application with a
  distribution certificate, not an ad hoc certificate or a development
  certificate. Verify that the code signing settings in Xcode are
  correct at the target level (which override any values at the project
  level). Additionally, make sure the bundle you are uploading was built
  using a Release target in Xcode, not a Simulator target. If you are
  certain your code signing settings are correct, choose "Clean All" in
  Xcode, delete the "build" directory in the Finder, and rebuild your
  release target. Once you have corrected these issues, go to the app's
  version details page (found in the Manage Your Applications module of
  iTunes Connect) and click Ready to Submit Binary. Proceed through the
  submission process until the app's status is Waiting for Upload. You
  can then use Application Loader to upload the corrected binary.

Do I need the private key used by my client?
Can someone please point me to the right direction? Can I get any tutorial or video how to resign the archive and submit it to the store.

A: I think you should ask your client to generate a distribution certificate and then sign your project with it.


text:
Q: Regular tilings of n-simplex Consider a regular n-simplex (the n-dimensional generalisation of a triangle/tetrahedron).
A triangle will tile the plane in a triangular pattern.
In 4, 8 and 24 dimensions. Can we tile the volume with n-simplices?
And will the vertices of those simplices give the lattices $F_4$, $E_8$ and Leech lattice in turn?
i.e. will a 5-cell tile 4D space where the vertices form the lattice $F_4$. If not what shape does?
(These are the sphere packing solutions in those dimensions). But are they also tiling of n-simplices?
Edit: I just read that in fact a 24-cell can tessellate 4D space in a $F_4$ arrangement

A: The angle of an equilateral triangle is a sixth of $2\pi$, so we can fit
six of them round a point. Thus it is unsurprising that one can tile the
plane with equilateral triangles.
The dihedral angle of the regular tetrahedron is $\cos^{-1}(1/3)$. That
is not a rational multiple of $2\pi$, so one cannot fit them round an edge.
Thus a space packing of regular tetrahedra is impossible.
In $n\ge4$ dimensions, the same problem happens. The dihedral angle
of the regular $n$-simplex is $\cos^{-1}(1/n)$, not a rational multiple
of $2\pi$, and again a tiling with regular simplices is impossible.

A: The point symmetry of $F_4$ is "o3o4o3o" (typewriter friendly notation of Dynkin symbol).
Polytopes representing that symmetry can be obtained by extending either nodes into true (non-zero) edges, e.g. the 24-cell with Coxeter-Dynkin symbol "x3o4o3o".
That point symmetry is extendable into a euclidean space symmetry "o3o4o3o3o". A hyper-honeycomb representing that symmetry then is be obtained quite similarily, e.g. the already mentioned packing of 24-cells with symbol "x3o4o3o3o".
Just as the cells of the 24-cell are octahedra, as can be given symbolically by "x3o4o .", so the cells of that tetracomb (4D hyper-honeycomb) are indeed 24-cells, as can be seen symbolically "x3o4o3o .". And just as the vertex figure of the 24-cell is the cube, as symbolically is obtained accordingly by ". x4o3o", so alike the vertex figure of that tetracomb is deduced from ". x4o3o3o" as the tesseract. The tesseract is known to show up 8 cubical cells, therefore you'd get accordingly eight 24-cells per vertex in that tetracomb.
Alternatively you also could have considered the tetracomb "o3o4o3o3x" of the same euclidean space group instead. The cells here are ". o4o3o3x", also known as 16-cells. The vertex figure of that tetracomb would have been "o3o4o3x .", i.e. the 24-cell. As it is known that the 24-cell has 24 cells, accordingly this tetracomb will show up twenty-four 16-cells per vertex. - Infact, those too regular tetracombs are dual to each other.
Quite similarily the point group of $E_8$ is "o3o3o3o3o3o3o *e3o" (where the "*e" part is just the typewriter friendly inline representation of the tridental Dynkin symbol: the link adjoined to "*e" is meant to revisit the e-th so far already mentioned node). Polytopes representing that symmetry can be obtained by extending either nodes into true (non-zero) edges, e.g. the 8D Gosset polytopes $4_{21}$ with Coxeter-Dynkin symbol "x3o3o3o3o3o3o *e3o", $2_{41}$ with symbol "o3o3o3o3o3o3x *e3o" or $1_{42}" with symbol "o3o3o3o3o3o3o *e3x".
This point group further can be extended similarily into the euclidean space group "o3o3o3o3o3o3o3o *f3o". Thus the according octacombs (8D hyper-honeycomb) would be either $5_{21}$ or "x3o3o3o3o3o3o3o *f3o", $2_{51}$ or "o3o3o3o3o3o3o3x *f3o", resp. $1_{52}$ or "o3o3o3o3o3o3o3o *f3x".
The cells of $5_{21}$ then are both, "x3o3o3o3o3o3o3o *f ." (or 8D simplices), 17280 per vertex, and "x3o3o3o3o3o3o . *f3o" (or 8D cross-polytopes), 2160 per vertex.
The cells of $2_{51}$ are both, ". o3o3o3o3o3o3x *f3o" (Gosset polytopes $2_{41}$), 16 per vertex, and "o3o3o3o3o3o3o3x *f ." (or 8D simplices), 128 per vertex.
And finally the cells of $1_{52}$ then are both, ". o3o3o3o3o3o3o *f3x" (Gosset polytopes $1_{42}$), 9 per vertex, and "o3o3o3o3o3o3o . *f3x" (or 8D hemi-hypercubes), 9 per vertex as well.
Obviously all 3 of those octacombs therefore no longer are regular, as this would require just a single cell type at least.
(24D finally is beyond my grasp. I never managed to wrap  my mind around that Leech lattice.)
But for sure, in any dimension you would also have the hypercube "x4o3...3o", which allows to fill the according all-space regularily, as is shown by the hyper-honeycomb "x4o3...3o4o".
OTOH, the general $n$D simplex is encoded by the Coxeter-Dynkin symbol "x3o3...3o", i.e. it belongs to the point group $A_n$ or "o3o3...3o". And that group can indeed be continued into the euclidean space group "o3o3...3o3o3*a" (closed loop Dynkin symbol). Thus there surely are according hyper-honeycombs, obtained by extending either nodes into true (non-zero) edges, e.g. "x3o3...3o3o3*a". Sadly that one (and any other choice alike) will not be regular. This is simply because the cells here would be multiple again. Infact those are "x . o3...3o3o3*a" (simplex), "x3o . o3o3...3o3o3*a" (rectified simplex), "x3o3o . o3...3o3o3*a" (birectified simplex), ..., "x3o3...3o . o3*a" (rectified simplex again), "x3o3...3o3o . *a" (simplex again).
For instance the $A_2$ group "o3o" is being extended into "o3o3o3*a", giving rise to the tiling "x3o3o*a", which shows up the tiles "x3o . *a" (triangle) and "x . o3*a" (triangle again). Thus this one is regular.
But already $A_3$ would give rise to the extended (euclidean) space group "o3o3o3o*a". For that would provide the honeycomb "x3o3o3o$*$a", and that one would have for cells the types "x3o3o . *a" (tetrahedron), "x3o . o3*a" (octahedron), and "x . o3o3*a" (tetrahedron again).
--- rk


text:
Q: Couldn't install textract in google colab I couldn't install textract in google colab, error message showing as below.
some people suggest to use sudo apt-get install libasound2-dev but how to do sudo... in google colab?
=== error message ==========================================================

Failed building wheel for pocketsphinx   Running setup.py clean for
  pocketsphinx Failed to build pocketsphinx Installing collected
  packages: pocketsphinx   Running setup.py install for pocketsphinx ...
  error
      Complete output from command /usr/bin/python3 -u -c "import setuptools,
  tokenize;file='/tmp/pip-install-03c_ysbm/pocketsphinx/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n',
  '\n');f.close();exec(compile(code, file, 'exec'))" install
  --record /tmp/pip-record-6n9ewg9i/install-record.txt --single-version-externally-managed --compile:
      running install
      running build_ext
      building 'sphinxbase._sphinxbase' extension
      swigging deps/sphinxbase/swig/sphinxbase.i to deps/sphinxbase/swig/sphinxbase_wrap.c
      swig -python -modern -threads -Ideps/sphinxbase/include -Ideps/sphinxbase/include/sphinxbase -Ideps/sphinxbase/include/android -Ideps/sphinxbase/swig -outdir sphinxbase -o deps/sphinxbase/swig/sphinxbase_wrap.c
  deps/sphinxbase/swig/sphinxbase.i
      unable to execute 'swig': No such file or directory
      error: command 'swig' failed with exit status 1

===========================================================================
Thank you,
Ling

A: Nope you can't use sudo because you don't get root access for colab.
The problem is that you don't just need libasound2-dev but a whole host of packages. Check debian requirements in https://textract.readthedocs.io/en/stable/installation.html
Also in order to build sphinx (a requirement for textract) you need libpulse-dev. So here is the updated command list.
!apt-get install python-dev libxml2-dev libxslt1-dev antiword unrtf poppler-utils \
     pstotext tesseract-ocr \
     flac ffmpeg lame libmad0 libsox-fmt-mp3 sox libjpeg-dev swig libasound2-dev libpulse-dev
!pip install git+https://github.com/deanmalmgren/textract

A: In google colab  Bash commands run by prefixing the command with '!'.
Example:
!apt update
!apt-get install libasound2-dev


text:
Q: How to set serial port NMEA source to QtPositioning in PySide6 I have a GPS device running on COM7. and I can read NMEA data from serial port.
It seems that QtPositioning support NMEA source . but I can't find any document about setting NMEA source to it.
I wrote some code to trying my best:
import PySide6.QtPositioning
import PySide6.QtCore
import PySide6.QtSerialPort

print('createSource')
obj = PySide6.QtCore.QObject()

source = PySide6.QtPositioning.QGeoPositionInfoSource.createDefaultSource(obj)
print(source.availableSources())

print('try Nmea Source')
qpNmea = PySide6.QtPositioning.QNmeaPositionInfoSource( PySide6.QtPositioning.QNmeaPositionInfoSource.RealTimeMode)

print(qpNmea.availableSources())

print('try Serial Port')
# new com9 QIODevice
com7 = PySide6.QtSerialPort.QSerialPort("com7" )
com7.setBaudRate(PySide6.QtSerialPort.QSerialPort.Baud9600)
com7.setDataBits(PySide6.QtSerialPort.QSerialPort.Data8)
com7.setParity(PySide6.QtSerialPort.QSerialPort.NoParity)
com7.setStopBits(PySide6.QtSerialPort.QSerialPort.OneStop)
com7.setFlowControl(PySide6.QtSerialPort.QSerialPort.NoFlowControl)
com7.open(PySide6.QtSerialPort.QSerialPort.ReadWrite)

com7.open(PySide6.QtSerialPort.QSerialPort.ReadOnly)

print(com7.readLine())

print('setDevice')
qpNmea.setDevice(com7)
qpNmea.startUpdates()
print(qpNmea.device())

print('others')

print(PySide6.QtPositioning.QGeoSatelliteInfoSource.availableSources())
print(PySide6.QtPositioning.QGeoPositionInfoSource.availableSources())
print(PySide6.QtPositioning.QNmeaPositionInfoSource.availableSources())

print ('end')

OUTPUT:
createSource
['winrt', 'nmea']
try Nmea Source
['winrt', 'nmea']
try Serial Port
b''
setDevice
<PySide6.QtSerialPort.QSerialPort(0x28928ad9680) at 0x000002892956F800>
others
[]
['winrt', 'nmea']
['winrt', 'nmea']
end


text:
Q: Getting super class with JPA Hibernate The following snippet is retrieving a Player object instance from the database. How can I make it retrieve only the User instance and then use another query to retrieve a Player instance?
Query q = em.createQuery("SELECT u FROM User u WHERE email = :email", User.class);
User u = (User) q.setParameter("email", email).getSingleResult();

Inherance type is Joined.
Thank you,
Hibernate 4.3.5.Final
EDIT:
I could find a question that matches this and already flagged my question as duplicate. Thank you!


text:
Q: Which files should I include when I wish to deploy a library with my project using node.js? I used npm to install most of my dependent libraries. Now I would like to add these libraries to my working directory so that another computer can directly run it w/o manually downloading and installing these files.
I have seen many projects on github do this.
How should this be done? And which files should I include? Most of my libraries are in /usr/local/lib/node/

A: Create a package.json file that states what your dependencies are then use npm link to install from that package file.
example package file :
{
    "name": "Inventory-System",
    "description": "Manage Inventory web app",
    "version": "0.0.1",
    "author": "Raynos",
    "dependencies": {
        "now": "0.5.3",
        "backbone": "0.3.2",
        "cradle": "0.5.5",
        "supervisor": "0.1.2",
        "less": "1.0.41",
        "ejs": "0.4.1"
    }
}

This allows you to declaratively define your dependancies then installing your library because as simple as npm link.
You can also go further and publish your own library through npm then just call npm install myLibrary on another computer.

A: All you need to run a stand-alone node.js application is your application code and the node binary executable--typically found under /usr/local/bin--as it already contains all of the "native" modules. (See below for a list.) If your application requires other libraries than these, you'd need to provide them as part of your application.
If you choose to deploy your application to a server using npm, the method outlined below by @Raynos will work nicely.
On the other hand if you choose to deploy your application to a server via git or as an archive, you'll need to provide all of the libraries required by your application as well as their dependencies.
One way to do this is to install/copy all required libraries under the 'node-modules' directory in your application's home directory.
As of Node@0.4.7, the native modules include: assert, buffer, child_process, console, constants, crypto, dgram, dns, events, freelist, fs, http, https, module, net, os, path, querystring, readline, repl, stream, string_decoder, sys, timers, tls, tty, url, util and vm.
See http://nodejs.org/docs/v0.4.7/api/modules.html for further information.


text:
Q: Do better job + V-ing Does the sentence: "I can do a better job working with them!" mean "I can do a better job if i work with them" or "I can work with them better (than someone else)"?
Are there any other general structure similar with this sentence?

A: There is apparently no problem in distinguishing at least three possible meanings as made specific through context. However, I find no supporting evidence.

*

*1/ choosing them to work with, 2/ as someone working with them, 3/ working with them rather than leaving everything up to them
(The apostrophe gives sentence stress)

*

*The people in group A have a better control than those in group B. So I am interested in people in group A, I can do a (')better job working with (')them! (either possibility of sentence stress seems meaningful)

*This teacher is not counselling his pupils well; I wouldn't have them do all these exercises; I can do a 'better job working with them!

*Having the task done by a subcontractor and giving up all initiative to their crew is not the best way to obtain good results: I can do a better job 'working with them!


text:
Q: SLComposeViewController doesn't handle tap on Cancel I'm using SLComposeViewController to share data to Facebook. I need to know if user tap Post or Cancel button, but in block
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
            if (result == SLComposeViewControllerResultDone) {
                NSLog(@"Done");
            } else {
                NSLog(@"Cancelled");
            }

            [controller dismissViewControllerAnimated:YES completion:Nil];
        };

I'm getting Done in both cases, after tapping Cancel and after tapping Post. Have anyone some ideas what is wrong?
UPDATE
This bug is being discussed here. Thanks to Amudi


text:
Q: How to reconstruct an image object from a list? I have been attempting to break an image (.png) into a list, edit the list, and then save the edited image as a file.
After editing the image, and restoring it into an array, mpl.imshow(image) correctly displays the new image, however attempting to save it as a file results in a blank image.
I believe that the flaw lies in the line marked  # <-- Estimated point of failure, but I have researched the command and can find no solution to the problem. I have examined the reconstructed array using print(), and nothing seems unusual.
Any ideas on how I could correctly save my edited image in file form would be greatly appreciated.
Thank you for your help,
Lochlann F.
import numpy as np
import matplotlib.pyplot as mpl
from PIL import Image

# Desconstruct the image into an editable list
img = Image.open('mini.png')
my_dot_array = np.asarray(img)
my_dot_list = my_dot_array.tolist()
my_dot_list[0][0] = [30, 220, 90, 255] # <-- Attemp a small edit to a pixel in the image

# Reconstuct the image into a saved .png file
my_dot_array = np.asarray(my_dot_list)
img = Image.fromarray(my_dot_array, mode='RGBA') # <-- Estimated point of failure
img = img.save('updated_mini.png')

# Display the resulting image
mpl.imshow(my_dot_array)
mpl.show()

#print(my_dot_array)

A: I think you are one line out. The line above needs a second parameter dtype=np.uint8:
my_dot_array = np.asarray(my_dot_list, dtype=np.uint8)


text:
Q: Manga where the main character is summoned twice and gets two different classes I am looking for a manga where the main character gets summoned to another world with some people and gets the class 'god', which lets him be able to do anything. Then he gets summoned again along with some people by the demon lord and get a class 'demon lord' or something, which gives him the power to manipulate reality.

A: Summoned to a parallel fantasy world many times
It might be "めっちゃ召喚された件" (in romaji "Metcha Shoukan Sareta Ken THE COMIC"), translated as "Summoned to a parallel fantasy world many times".
First volume cover

Synopsis

Guy's whole class gets summoned to another world, except he's the only who one was transferred to a different one. Just when he gets used to his new life, he gets summoned to another world again, and again.


text:
Q: Can't set CALayer frame I am trying to set the frame of my CALayer in this code below
CGRect VFrame;
VFrame = CGRectMake(self.viewNo2.frame.origin.x, self.viewNo2.frame.origin.y, self.viewNo2.frame.size.width, self.viewNo2.frame.size.height);

self.customLayer = [CALayer layer];
self.customLayer.frame = VFrame;
self.customLayer.contentsGravity = kCAGravityResizeAspectFill;
[self.view.layer addSublayer:self.customLayer];

For some reason the layer goes somewhere around this frame but not as the frame I am trying to declare.
Does anyone know what is the problem?

A: //try this,simply assign frame to viewNo2 frame
self.viewNo2.frame.size.width, self.viewNo2.frame.size.height);
self.customLayer = [CALayer layer];
self.customLayer.frame = viewNo2.frame;
self.customLayer.contentsGravity = kCAGravityResizeAspectFill;
[self.view.layer addSublayer:self.customLayer];


text:
Q: How to Show and Log a Perl Scripts Output in Real Time when Invoked from PowerShell I am writing a PowerShell script that has to invoke a legacy Perl Script and display the output of this long running Perl script in real time to PowerShell as I would normally view in a Windows command prompt or interactive Putty SSH session.  My requirement is to write the output of the Perl script to a log file in real time and display the results to the PowerShell in real time.
My problem is that once the Perl script finishes running, all of the results are then returned to PowerShell or my log files.
Here is a simplified sample of my PowerShell code.
#Test.ps1
$env:Path = "C:\Dev\perl583\bin;" + $env:Path
$WORKING_PATH="C:\Dev\scripts"
perl $WORKING_PATH\LegacyScript.pl *>> C:\Dev\results\realtime_output.txt
exit $LASTEXITCODE

Here is a sample Perl Script that simulates a long running operation invoked by the PowerShell script:
#LegacyScript.pl
for( $a = 1; $a < 6; $a = $a + 1 ){
  print "New value of a: $a\n";
  sleep(10)
}

A: After a day of researching I think I found the answer to my own question courtesy of PerlMonks.org . It is perl in the way it buffers the output (line vs. block). Once I set "$| = 1;" in my Perl script, I got the expected results from both the PowerShell itself and PowerShell's file redirection. Here is the site for those that may run into this problem integrating legacy scripts as in my case.
http://www.perlmonks.org/?node_id=305801
"By setting $| as Anonymous Monk indicated, you force the output to be flushed after each write."  - Direct Quote from this Website that solved my problem.


text:
Q: Error while using two modals: [$injector:unpr] Unknown provider: $modalInstanceProvider <- $modalInstance I really find it very hard to solve the above error.
I have two modals in my project. One of the modal is working fine and the other modal is not so. I have injected $modal as a dependency in the controller where I have created my first modal and I have injected $modalInstance as a dependency in the modalController and it works fine for me. I tried to create one more modal with the same steps and I have encountered unknown provider $modalInstance error.
Any answers will be appreciated.
Here is my code for first modal.
Controller:
angular.module('menu').controller('HeaderNavbarController', ['$scope', '$modal', '$log',
function($scope, $modal, $log) {
 $scope.signin = function() {
        console.log('in signin');
        var modalnstance = $modal.open({

            templateUrl: '/modules/users/client/views/authentication/signin.client.view.html',
            controller: 'AuthenticationController',
            size: 'lg',
            resolve: {
                items: function() {
                    return $scope.items;
                }
            }
        });
        modalnstance.result.then(function(selectedItem) {
            $scope.selected = selectedItem;
            console.log('$scope.selected', $scope.selected);
        }, function() {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };}]);

View:

SIGN IN

ModalController: AuthenticationController
    angular.module('users').controller('AuthenticationController', ['$scope', '$modalInstance',
        function($scope, $modalInstance) {
        $scope.cancel=function(){
            $modalInstance.close();
          }
}
]);

Template for Modal: signin.client.view

<button ng-click="cancel()">cancel</button>

Code for Second Modal
controller
angular.module('menu').controller('ScripsController', ['$scope', '$modal', '$log',
    function($scope, $modal, $log) {
     $scope.focusInput = function() {
            console.log('in signin');
            var modalnstance = $modal.open({

                templateUrl: '/modules/menu/client/views/search.popup.html',
                controller: 'SearchController',
                size: 'lg',
                resolve: {
                    items: function() {
                        return $scope.items;
                    }
                }
            });
            modalnstance.result.then(function(selectedItem) {
                $scope.selected = selectedItem;
                console.log('$scope.selected', $scope.selected);
            }, function() {
                $log.info('Modal dismissed at: ' + new Date());
            });
        };}]);

Modal view(HTML): search.popup.html

<button ng-click="closeSearch()">cancel</button>

ModalController: SearchController
angular.module('menu').controller('SearchController', ['$scope', '$modalInstance',
    function($scope, $modalInstance) {
      $scope.closeSearch=function(){
         $modalInstance.close();
}

}
}]);

I am getting unknown injector $modalInstance in the SearchController.
Thanks in advance.

A: Most likely this means you have recently upgraded ui-bootstrap from a version before 0.14 to one after 0.14.
https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes#modal
Modal

*

*Change: $modal for $uibModal.

*Change: $modalInstance for $uibModalInstance.

*Change: modal-transclude for uib-modal-transclude


text: Q: Visual Studio displaying errors even if projects is closed or rebuild? I add MySql.dll to my project and I replace all classes of Sql server to Mysql. In source code I dont' have any errors but my project is not building. lots of time I close the solution and I open again but didn't work.


text:
Q: protecting kml access to google only I have a large amount of data (thousands of polygons) that I want to share with people through my site. I want them to be able to view the polygons, and due to the large amount of data, I am not worried about them stealing this data through the displayed google map. However, since the kml file must be accessible to google, a proficient coder could discover the url of the kml files and simply download the entire file. Is there any way to restrict access to these kml files only to google so no outside people can get to them. I have tried .htaccess, but I can't figure out how to restrict access to everyone but google. Any ideas?

A: You could provide as a WMS layer in which case the end users will only have a picture of your data. And with 1000s of polygons it will be faster to download too.
Otherwise I don't think there is any way to display the KML on Google with out allowing general access to your data.

A: not a great solution but you could monitor the IP addresses used by Google calling back to your KML and then setup a frontend proxy to only allow those addresses access. Obviously, this list would need to be dynamic and constantly tended to but over time, you might find the block of IPs Google uses for KML Layer callbacks is fairly stable. It would also be great list to post back to this group :)
YMMV, cheers
brian

A: allow access to 66.249.82.* and deny rest others for your kml file using any front end proxy servers or apache/nginx anything you use to serve kml files.

A: i check the $_SERVER["HTTP_USER_AGENT"] variable for google.
and if is correct i generate the kml from php.
$agent = "Kml-Google";
$google = strpos($_SERVER["HTTP_USER_AGENT"], $agent);
($google !== FALSE) or die;
header('Content-Type: application/vnd.google-earth.kml+xml kml');
header('Content-Disposition: attachment; filename="otras.kml"');
?>
<?xml version="1.0" encoding="UTF-8"?>
<kml xml ...

A: KML can be partially protected served from a httpaccess passworded directory could be parsed using a third party KML parser.(such as EGeoXml or GeoXml)


text:
Q: How to parallelize this loop? I'm running into a wall with the borrow checker, I think because it can't tell things are no longer used by the worker after it is joined by the main thread. I've reduced my problem to the simplest possible example of the same pattern that I could. I'm trying to avoid unnecessary allocations and copies, especially of b.
fn sequential_fn() -> Vec<i32>
{
    let mut a = vec![1,2,3,4]; //two mutable arrays
    let mut b = vec![0;4];

    for repetitions in 0..100
    {
        for i in 0..4
        {
            b[i] ^= a[i]; //example heavy operation - a isnt modified but b is
        }
        b.sort();       //heavy operation over, b is sorted
        for e in a.iter_mut() //a is modified by main thread before repeating process
            { *e += 1;}
    }
    return b; //return b
}

The sequential version above compiles and works fine. This is how I've attempted to parallelize the heavy operation to split up the workload:
fn parallel_fn() -> Vec<i32>
{
    let mut a = vec![1,2,3,4];
    let mut b = vec![0;4];
    let (mut b1 , mut b2) = b.split_at_mut(2); //split b into slices for each worker (err1)

    for repetitions in 0..100
    {
        //only 1 worker for example purposes
        let worker = std::thread::spawn(||  //(err2)
        {
            for i in 2..4
            {
                b2[i-2] ^= a[i] //mutably borrow b2, immutably borrow a
            }
        });
        for i in 0..2
        {
            b1[i] ^= a[i]; // mutably borrow b1, immutably borrow a
        }
        worker.join(); //workers finish
        b.sort(); //borrow b as mutable in main thread only (err3)
        for e in a.iter_mut() //borrow a as mutable in main thread only (err4)
            { *e += 1;}
    }
    return b;
}

The errors I'm getting are:
error[E0597]: `b` does not live long enough
  --> src/lib.rs:5:29
   |
5  |     let (mut b1 , mut b2) = b.split_at_mut(2); //split b into slices for each worker (err1)
   |                             ^^^^^^^^^^^^^^^^^
   |                             |
   |                             borrowed value does not live long enough
   |                             argument requires that `b` is borrowed for `'static`
...
27 | }
   | - `b` dropped here while still borrowed

error[E0499]: cannot borrow `*b2` as mutable more than once at a time
  --> src/lib.rs:10:41
   |
10 |           let worker = std::thread::spawn(||  //(err2)
   |                        -                  ^^ `*b2` was mutably borrowed here in the previous iteration of the loop
   |  ______________________|
   | |
11 | |         {
12 | |             for i in 2..4
13 | |             {
14 | |                 b2[i-2] ^= a[i] //mutably borrow b2, immutably borrow a
   | |                 -- borrows occur due to use of `*b2` in closure
15 | |             }
16 | |         });
   | |__________- argument requires that `*b2` is borrowed for `'static`

error[E0373]: closure may outlive the current function, but it borrows `a`, which is owned by the current function
  --> src/lib.rs:10:41
   |
10 |         let worker = std::thread::spawn(||  //(err2)
   |                                         ^^ may outlive borrowed value `a`
...
14 |                 b2[i-2] ^= a[i] //mutably borrow b2, immutably borrow a
   |                            - `a` is borrowed here
   |
note: function requires argument type to outlive `'static`
  --> src/lib.rs:10:22
   |
10 |           let worker = std::thread::spawn(||  //(err2)
   |  ______________________^
11 | |         {
12 | |             for i in 2..4
13 | |             {
14 | |                 b2[i-2] ^= a[i] //mutably borrow b2, immutably borrow a
15 | |             }
16 | |         });
   | |__________^
help: to force the closure to take ownership of `a` (and any other referenced variables), use the `move` keyword
   |
10 |         let worker = std::thread::spawn(move ||  //(err2)
   |                                         ++++

error[E0499]: cannot borrow `b` as mutable more than once at a time
  --> src/lib.rs:22:9
   |
5  |     let (mut b1 , mut b2) = b.split_at_mut(2); //split b into slices for each worker (err1)
   |                             ----------------- first mutable borrow occurs here
...
19 |             b1[i] ^= a[i]; // mutably borrow b1, immutably borrow a
   |             ----- first borrow later used here
...
22 |         b.sort(); //borrow b as mutable in main thread only (err3)
   |         ^^^^^^^^ second mutable borrow occurs here

error[E0502]: cannot borrow `a` as mutable because it is also borrowed as immutable
  --> src/lib.rs:23:18
   |
10 |           let worker = std::thread::spawn(||  //(err2)
   |                        -                  -- immutable borrow occurs here
   |  ______________________|
   | |
11 | |         {
12 | |             for i in 2..4
13 | |             {
14 | |                 b2[i-2] ^= a[i] //mutably borrow b2, immutably borrow a
   | |                            - first borrow occurs due to use of `a` in closure
15 | |             }
16 | |         });
   | |__________- argument requires that `a` is borrowed for `'static`
...
23 |           for e in a.iter_mut() //borrow a as mutable in main thread only (err4)
   |                    ^^^^^^^^^^^^ mutable borrow occurs here

error[E0505]: cannot move out of `b` because it is borrowed
  --> src/lib.rs:26:12
   |
5  |     let (mut b1 , mut b2) = b.split_at_mut(2); //split b into slices for each worker (err1)
   |                             -----------------
   |                             |
   |                             borrow of `b` occurs here
   |                             argument requires that `b` is borrowed for `'static`
...
26 |     return b;
   |            ^ move out of `b` occurs here

Playground

A: You've made a bunch of assumptions in your code which rust borrow checker can't ensure in compile type:

*

*When parallel_fn finishes, a and b are removed. You are calling .join() which ensures the spawned thread should finish by that time, but it is a runtime check, rust can't check it in compile time.
That is why you can't pass reference to spawn, so you need arc

*You are calling .join() which ensures no read operation over a happens when you modify it, but compiler can't check this.

*You mutate parts of the same vector in different threads, which is not safe unless you take extra care, so you need a little bit of unsafe code. Alternative would be split the vector into 2 vectors (not slices) and join them, but it is extra copying.

I've ended up with something like this:
use std::sync::{Mutex, Arc, RwLock};

#[derive(Debug)]
struct VectorHolder {
    vec: Vec<i32>,
    slice1_ptr: Mutex<*mut [i32]>,
    slice2_ptr: Mutex<*mut [i32]>,
}

impl VectorHolder {

    pub fn new(mut vec: Vec<i32>) -> Self {
        let (slice1 , slice2) = vec.split_at_mut(2);
        let slice1_ptr = slice1 as *mut _;
        let slice2_ptr = slice2 as *mut _;
        Self {
            vec,
            slice1_ptr: Mutex::new(slice1_ptr),
            slice2_ptr: Mutex::new(slice2_ptr),
        }
    }

    /// Below operations are "safe" as no one else can access parts of Vec until
    /// VectorHolder is consumed.
    /// It is also safe we can't call op1 from 2 threads due to the mutex.
    /// Mutex could optionally be removed if you are sure you never call op1 and op2 concurrently.
    /// In this case we are sure about that as we have .join
    pub fn op1(&self, a: &[i32]) {
        let mut guard = self.slice2_ptr.lock().unwrap();
        let b2 = unsafe { &mut **guard };
        for i in 2..4 {
            b2[i-2] ^= a[i] //mutably borrow b2, immutably borrow a
        }
    }

    pub fn op2(&self, a: &[i32]) {
        let mut guard = self.slice1_ptr.lock().unwrap();
        let b1 = unsafe { &mut **guard };
        for i in 0..2 {
            b1[i] ^= a[i]; // mutably borrow b1, immutably borrow a
        }
    }

    pub fn consume(self) -> Vec<i32> {
        self.vec
    }
}

unsafe impl Send for VectorHolder { }
unsafe impl Sync for VectorHolder { }

pub fn operations_on_b(b: Vec<i32>, a: Arc<RwLock<Vec<i32>>>) -> Vec<i32> {
    let holder = Arc::new(VectorHolder::new(b));

    //only 1 worker for example purposes
    let holder_clone = holder.clone();
    let a_clone = a.clone();
    let worker = std::thread::spawn(move || {
        holder_clone.op1(a_clone.read().unwrap().as_slice());
    });
    holder.op2(a.read().unwrap().as_slice());
    worker.join().unwrap(); //workers finish

    let mut modified_b = Arc::try_unwrap(holder).unwrap().consume();

    modified_b.sort();
    modified_b
}

fn parallel_fn() -> Vec<i32>
{
    let a = Arc::new(RwLock::new(vec![1,2,3,4]));
    let mut b = vec![0;4];

    for _repetitions in 0..100
    {
        b = operations_on_b(b, a.clone());

        for e in a.write().unwrap().iter_mut() //borrow a as mutable in main thread only (err4)
        { *e += 1;}
    }
    return b;
}

fn main() {
    println!("{:?}", parallel_fn());
}


text:
Q: Passing self as parameter I am fairly new at Objective C and may be confused since I am used to C++.  I am making an iphone game and what I want to do is have a class all enemies and heros "register" and "unregister" to.  I want to pass each individual instance of an enemy and hero to this singleton class and then add the object to a NSMutableArray and be able to call functions and change variables within each specific instance (by using a for-loop based on their registerIDs).  I am getting an error it expects a type (in damagedistributer.h") when I am trying to pass the pointer of an enemy object and looking online at forums no one seems to be answering this question. How could I make this work?  I don't want a copy of the object that is on the stack so when I change variables I don't lose those changes.  Thanks in advance. Here is some code:
DamageDistributer.h
@interface DamageDistributer : NSObject {

    GLuint enemyRegisterID;
    GLuint heroRegisterID;

    NSMutableArray *enemies;
    NSMutableArray *heros;
}

- (void)RegisterHero:(Player*)playerHero; //PROBLEM HERE
- (void)RegisterEnemy:(AbstractEnemy*)enemyUnit; //PROBLEM HERE
- (void)Unregister:(GLuint)registerID type:(GLuint)typeOfEntity;

+ (DamageDistributer*)sharedDamageDistributer;

DamageDistributer.m
- (void)RegisterHero:(Player *)playerHero {

    [heros addObject:playerHero];
    playerHero.damageDistID = heroRegisterID;
    heroRegisterID++;
}

- (void)RegisterEnemy:(AbstractEnemy *)enemyUnit {

    [enemies addObject:enemyUnit];
    enemyUnit.damageDistID = enemyRegisterID;
    enemyRegisterID++;
}

- (void)Unregister:(GLuint)registerID type:(GLuint)typeOfEntity {

    if (typeOfEntity == hero) {
        [heros removeObjectAtIndex:registerID];
    }
    else {
        [enemies removeObjectAtIndex:registerID];
    }
}

And then this is the call from the Enemy Class
sharedDamageDistributer = [DamageDistributer sharedDamageDistributer];
[sharedDamageDistributer RegisterEnemy:self];

So what am I doing wrong?
Edited:
Oh wow overlooked that... Thanks guys I was thinking it was more than that. One more question. Will the mutable array shift the indexes once an object is removed from the array so i will have to go decrement all the objects (registerIDs) after the one being removed? Or no it keeps the indexes where they are and it fills in the blanks? Or keeps adding to the end not shifting anything? Thanks again.

A: Looks like the header doesn't know about Player and AbstractEnemy. You can either import those 2 headers, or just add @class (forward declaration) which tells the compiler there's a class for that name. Then of course you import those headers within the implementation of DamageDistributer
    @class Player;
    @class AbstractEnemy;
    @interface DamageDistributer : NSObject {

        GLuint enemyRegisterID;
        GLuint heroRegisterID;

        NSMutableArray *enemies;
        NSMutableArray *heros;
    }

    - (void)RegisterHero:(Player*)playerHero; //PROBLEM HERE
    - (void)RegisterEnemy:(AbstractEnemy*)enemyUnit; //PROBLEM HERE
    - (void)Unregister:(GLuint)registerID type:(GLuint)typeOfEntity;

    + (DamageDistributer*)sharedDamageDistributer;

A: I think that it's not recognizing your custom classes in the header.  Add declarations to your .h file, such as:
@class Player;
@class AbstractEnemy;

A: In objective-C everything (with the exception of basic c types like int, strict, etc.) is on the heap. All objects are on the heap and use reference counting (like smart pointers) for memory management.
Your error looks unrelated to this though, and it could be you're just failing to #import "Player.h"


text:
Q: How does Webix implement hidden text controls to enforce rules There is a hidden text control in the project requirement. The text is assigned by the result of the file upload, but the hidden control does not seem to be monitored by the Rule rule.
The sample is as follows
App.form={
    elements:[
        ....
        ,{"cols": [
                {id: "file_code", name: "file_code", view: "text", invalidMessage:"please upload file", hidden: true},
                {id: "file_code_btn", view: "button", label: "select file", "width": 100, "inputHeight": 20},
            ]}
    ],
    rules:{
        "name": webix.rules.isNotEmpty
        ,"file_code": webix.rules.isNotEmpty
    }

When I change the hidden property to false, I can realize the non-null check in the front end, but it cannot be realized after the hidden property.
I would appreciate it if you could tell me how to solve it.

A: By default hidden and disabled fields are ignored during data validation.
Though, you can add an extra parameter to the validate call to include them
form.validate({ hidden: true })

https://docs.webix.com/desktop__data_validation.html#validationofhiddenanddisabledfieldsinform


text:
Q: Pandas selecting with unaligned indexes I have 2 series.
The first one contains a list of numbers with an index counting 0..8.
A = pd.Series([2,3,4,6,5,4,7,6,5], name=['A'], index=[0,1,2,3,4,5,6,7,8])

The second one only contains True values, but the index of the series is a subset of the first one.
B = pd.Series([1, 1, 1, 1, 1], name=['B'], index=[0,2,4,7,8], dtype=bool)

I'd like to use B as boolean vector to get the A-values for the corresponding indexes, like:
A[B]

[...]
IndexingError: Unalignable boolean Series key provided

Unfortunately this raises an error.
Do I need to align them first?

A: Does
A[B.index.values]

work for your version of pandas? (I see we have different versions because now the Series name has to be hashable, so your code gave me an error)


text:
Q: How to ask until the user get specific reply in C#         {
            bool stayInLoop = true;

            while(stayInLoop)
            {
                Console.WriteLine("Enter Yor Number");
                var PlusA = Console.ReadLine();
                Console.WriteLine("Enter Yor Number");
                var PlusB = Console.ReadLine();
                if(PlusA == ';')
                {
                    stayInLoop = false;
                    break;
                }
                else if(PlusB == ';')
                {
                    stayInLoop = false;
                    break;
                }
                else
                {
                    Console.WriteLine("Answer =");
                    Console.WriteLine(PlusA + PlusB);
                }
            }
        }

I want to make a plus calculator, I want to let the user type more then 2 numbers, keep asking for PlusC, PlusD, until they type the symbol ; .
For example the user numbers in PlusA PlusB PlusC and in PlusD, he/she type ; so it should print PlusA + PlusB + PlusC
If he type a number in PlusD, it should ask for PlusE, until he/she type ;, it should sum up all the number before
And I want to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own, how to do that? (I know I am not saying it clearly, coz i can't find better words)

A: You want to add numbers until the user enters ;. You should use loops for that. Here's the complete solution that uses a for loop:
  switch(exp)
  {
    case "+":
    {
      var sum = 0;
      for(;;)
      {
         Console.WriteLine("Enter Yor Number");
         var line = Console.ReadLine();
         if (line == ";") break;
         sum += Convert.ToInt32(line);
      }
      Console.WriteLine(sum);
      break;
    }
  }

Here we repeat the part inside the loop over and over, accumulating entered numbers into sum variable until the user enters ; - that's when we end the loop with break.

A: Use a while loop:
switch(exp)
{
      case "+":
           int sum = 0;
           string input = "";
           do
           {
               Console.WriteLine("Enter your number:");
               input = Console.ReadLine();
               if (input != ";")
                  sum += int.Parse(input);

           } while (input != ";");

           Console.WriteLine("Answer =" + sum);
           break;
}

A: You are having problems because you should iterate the code until your exit/end condition is met using the while statement.
switch(exp)
{
    case "+":
       int mySum = 0;
       string userInput = "";
       while(userInput != ";")
       {
           Console.WriteLine("Enter number to add (';' to end the sum):");
           userInput = Console.ReadLine();
           if (userInput != ";")
           {
              // Would be interesting checking if entered really is an integer, for example Int32.TyParse()
              mySum = mySum + Convert.ToInt32(userInput);
           }
       }
       Console.WriteLine("Answer =" + mySum.ToString());
       break;
}

A: Thankyou for your reply, but is there any way to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own
            bool stayInLoop = true;

            while(stayInLoop)
            Console.WriteLine("Enter Yor Number");
            var PlusA = Console.ReadLine();
            Console.WriteLine("Enter Yor Number");
            var PlusB = Console.ReadLine();
            if(PlusA == ';')
            {
                stayInLoop = false;
                break;
            }
            else if(PlusB == ';')
            {
                stayInLoop = false;
                break;
            }
            else
            {
                Console.WriteLine("Answer =");
                Console.WriteLine(PlusA + PlusB);
            }
        }

and when I run this, it run out 'error CS0019' and 'error CS0139'

A: What you're looking for is a while() loop.
example:
bool stayInLoop = true;

while(stayInLoop) // basically means (stayInLoop == true)
{
  var text = Console.ReadLine();
  if(text == ';')
  {
   stayInLoop = false;
   break; // break will stop the loop, but you can also change the variable to false to break the loop.
  }
}


text:
Q: C++11: Parameter Pack Expansion Counter I'd like to increment a counter for each parameter during parameter pack expansion.
Here is some pseudo code of what I want to achieve:
    template<class ... Args>
    void doSomething(Args ... _args)
    {
        std::size_t counter = 0;
        bar(doSomethingWithOneArg(_args, counter++)...);
    }

The problem with this code is, that while the order of the Argsis preserved, the order in which the function parameters are evaluated is not defined, i.e. on clang the order in which the counter expressions are evaluated is the same as the order of Args while in gcc it is reversed. What is a portable, standard way of achieving this?
Thanks!

A: You could add a helper function:
template <typename ...Args>
void doSomething(Args &&... args)
{
    doSomethingImpl(std::make_index_sequence<sizeof...(Args)>(),
                    std::forward<Args>(args)...);
}

template <typename ...Args, std::size_t ...N>
void doSomethingImpl(std::index_sequence<N...>, Args &&... args)
{
    bar(oneCommand(std::forward<Args>(args), N)...);
}

A: If you want the order of evaluation to be in line with the order of the arguments for doSomething you can expand the arguments into an initializer:
template <typename ...Args, std::size_t ...N>
void doSomethingImpl(std::index_sequence<N...>,
  std::tuple<Args...> && args)
{
  using std::get;
  int t_[] = { 0, (static_cast<void>(oneCommand(
    get<N>(std::forward<decltype(args)>(args)), N)), 0)... };
  static_cast<void>(t_); // "use" t_ to silence warnings
}

template <typename ...Args>
void doSomething(Args &&... args)
{
  doSomethingImpl(std::make_index_sequence<sizeof...(Args)>(),
    std::forward_as_tuple(std::forward<Args>(args)...));
}

A: You might utilize list-initializatio in conjunction with a comma operator to sequence the function calls:
template<class T>
void doSomethingWithOneArg(const T&, std::size_t counter)
{
    std::cout << counter << ": " << typeid(T).name() << '\n';
}

template<class ... Args>
void doSomething(Args ... args)
{
    std::size_t counter = 0;
    std::initializer_list<int>{ ( doSomethingWithOneArg(args, counter++), 0) ... };
}

int main() {
    doSomething(char(0), int(0), long(0));
}

8.5.4 List-initialization (N4296)

4
  Within the initializer-list of a braced-init-list, the
  initializer-clauses, including any that result from pack expansions
  (14.5.3), are evaluated in the order in which they appear. That is,
  every value computation and side effect associated with a given
  initializer-clause is sequenced before every value computation and
  side effect associated with any initializer-clause that follows it in
  the comma-separated list of the initializer-list.


text:
Q: Simple way to hide and show element with svelte I want to have a simple with way to hide and show an element with a button on svelte, how can I do it? Also is it simpler to do it in vanilla JS?

A: Svelte has the {#if} directive for that, which can be tied to local state, which in turn can be changed via a button's on:click.
Whether it is easier in vanilla JS depends on many things, including the overall complexity. In the long run, things tend to be easier with Svelte.
I would recommend doing the tutorial...

A: this code worked for me, it is a modified version of an example provided by Svelte which can be found here

<button on:click={toggleVissible}>
    Hide
</button>

{#if visible}

        This text will hide.

{/if}

A: Vanilla
Here is one way to do it in vanilla JS.
You can directly place this inside an .astro component:
<button>Toggle</button>

Content

Svelte
And here is one example doing it in svelte:

<button on:click={() => (toggle = !toggle)}> Toggle </button>

{#if toggle}

Content

{/if}

Make sure to import it with a client: directive to get the JS actually shipped to the client in astro:
---
import Svelte from "./svelte.svelte";
---

<Svelte client:load />

Which one to choose?
I would recommend going with svelte, since it's so more readable, and you also have a better scalability, when you plan to add more features in the future.


text:
Q: Building a GUI in Netbeans, which should I use? I am building a GUI in Netbeans - it is for a simple little application - a converter program.  Basically, user types whatever it is they want to convert into a text field, selects the conversion from a number of radio buttons (say lbs to kg) and then clicks "Convert".
The thing is, I want the "Convert" button and the radio buttons to behave like this:

*

*Radio buttons and "Convert" button are disabled when program loads.

*Radio buttons and "Convert" button will become enabled if user types a number (and only a number) into the text field.

*If used deletes what they have typed, everything will be disabled again until they type in another number.

I have managed to set the Radio buttons and "Convert" button up so they are disabled, by unchecking the "enabled" box in the properties for each component.  I have also been able to use a simple if statement and the keyTyped event to enable/disable as follows:
private void txtUsrInputKeyTyped(java.awt.event.KeyEvent evt)
{
    if (!txtUsrInput.getText().equals(""))
    {
        btnCalculate.setEnabled(true);
    }
    else
    {
        btnCalculate.setEnabled(false);
    }
}

I want to extend my code so that if the user accidentally types a letter or symbol into the text field (don't ask me why they'd do that, when they know they must only type a number) then the program will either ignore what they typed, or display an error.  The exception to this is, of course, typing a period (.) because they might want to indicate a decimal number.
Any thoughts on how I might do this?  Hope what I wrote makes sense!

A:  Your GUI
If you do not already know swing, then learn it. Knowing how all of the components work is always a huge advantage for any developer, and if anything goes wrong, you know exactly how to fix it (or at least have a much better chance). Take a look at this stuff, for some help on getting started.
 Checking for a decimal
This looks like a job for regular expressions. What you can do is specify a number [0-9], and a period, \.. Then ensure that either a number or a decimal is typed a certain amount of times. The important thing to note here though, is that the user can only type one decimal, which winds up being:
([0-9]+(\.[0-9]+))

This will allow values like 9, 0.9, 1.9302. It will not allow values like .901. If you wish to allow that, simple swap the first + for a *.:
([0-9]*(\.[0-9]+))

 Using it
Because a text box contains a string, you can compare it with your regex. Simply:
if(textBox1.getText().matches("([0-9]+(\.[0-9]+))")) {
    // Run some code in here.
}

A: Well, if GUI is simple, DO NOT use GUI Builder, but code from scratch. Following harder path, you will learn about layouts, actionlisteners and so on ...


text:
Q: Integration of Cubepoints/Achievements Is there some plugin or some way to integarate any of the following :

*

*Cubepoints

*Achievements

with either of the following :

*

*Favorite (default in bp)

*Vote it Up

*Emo Votes

A: I'm the author of the Achievements for BuddyPress plugin, and it's lucky I saw your question. I don't often read this site. I can't talk for Cubepoints, but with Achievements, it is easy to extend support to other plugins.
For developer documentation, see http://achievementsapp.com/developer/add-support-for-a-plugin-non-custom-post-type/. If either of those vote plugins are super popular and well-written, I'll add support to the core of Achievements.
Favourites (activity stream favourites, yes?) should work with Achievements. I'll put it on the to-do and check support for hte next release.