text:
Q: How to get data from checked checkboxes? I am trying to get data of the particular checkbox that I click and make that data go away if I uncheck it but clicking All I want all the data of the table to be displayed.
I don't want to use JQuery and want to use JavaScript. I tried doing as the code below but could not achieve the result I was expecting.

function myFunction() {
  var checkBox = document.getElementsByClassName("All")[0];
  var text = document.getElementsByClassName("text")[0];
  if (checkBox.checked == true) {
    text.style.display = "block";
  } else {
    text.style.display = "none";
  }
}

function firstFunction() {
  var checkBox = document.getElementsByClassName("select-one")[0];
  var text = document.getElementsByClassName("text-one")[0];
  if (checkBox.checked == true) {
    text.style.display = "block";
  } else {
    text.style.display = "none";
  }
}

function secondFunction() {
  var checkBox = document.getElementsByClassName("select-two")[0];
  var text = document.getElementsByClassName("text-two")[0];
  if (checkBox.checked == true) {
    text.style.display = "block";
  } else {
    text.style.display = "none";
  }
}
<input type="checkbox" class="All" onclick="myFunction()">All
<input type="checkbox" class="select-one" onclick="firstFunction()">Select 1
<input type="checkbox" class="select-two" onclick="secondFunction()">Select 2

    Checkbox is CHECKED!

    Checkbox is CHECKED 1!

    Checkbox is CHECKED 2!

I expect my output to display all of the values when clicked All and only particular values when a particular checkbox is clicked.

A: I've touched up the JavaScript and HTML a tiny bit as below:
The main difference is having first, second and third variables in a global scope.
Plus, moving the class="text" into the first TD.
Also, initailize(); which grabs the three HTML elements sort of thing.
JavaScript:
var  first = ''
,    second = ''
,    third = '';

function initialize () {

    first = document.getElementsByClassName('text')[0];
    second = document.getElementsByClassName('text-one')[0];
    third = document.getElementsByClassName('text-two')[0];
}

function myFunction() {
    var checkBox = document.getElementsByClassName("All")[0];
    if (checkBox.checked == true) {
        first.style.display = "block";
        second.style.display = "block";
        third.style.display = "block";
    } else {
        first.style.display = "none";
        second.style.display = "none";
        third.style.display = "none";
    }
}

function firstFunction() {
  var checkBox = document.getElementsByClassName("select-one")[0];
  if (checkBox.checked == true) {
    second.style.display = "block";
  } else {
    second.style.display = "none";
  }
}

function secondFunction() {
  var checkBox = document.getElementsByClassName("select-two")[0];
  if (checkBox.checked == true) {
    third.style.display = "block";
  } else {
    third.style.display = "none";
  }
}

And the HTML:

    <input type="checkbox" class="All" onclick="myFunction()">All
    <input type="checkbox" class="select-one" onclick="firstFunction()">Select 1
    <input type="checkbox" class="select-two" onclick="secondFunction()">Select 2

        Checkbox is CHECKED!

        Checkbox is CHECKED 1!

        Checkbox is CHECKED 2!

Hope this helps,
Kind regards,

A: Just to specifically point out what was your issue:
Your
 has a display: none style that is not updated from firstFunciton() or secondFunction(). So, even though you make the  visible, the parent (
) is still hidden, so the child rows or cells of the table will not show.
There are more elegant solutions, but to keep the code closest to what you have, you could update your HTML table to this:

    Checkbox is CHECKED!

    Checkbox is CHECKED 1!

    Checkbox is CHECKED 2!

And your Javsacript function myFunction() to this:
function myFunction() {
  var checkBox = document.getElementsByClassName("All")[0];
  var text = document.getElementsByClassName("text")[0];
  var first = document.getElementsByClassName("text-one")[0];
  var second = document.getElementsByClassName("text-two")[0];
  if (checkBox.checked == true) {
    text.style.display = "block";
    first.style.display = "block";
    second.style.display = "block";
  } else {
    text.style.display = "none";
    first.style.display = "none";
    second.style.display = "none";
  }
}

A: You can try the following way:

function myFunction(chk) {
  var all = document.querySelectorAll('.text tr td');
  if(chk.classList.value.includes('All')){
    if(chk.checked){
      all.forEach(function(td){
        td.style.display = "block";
      });
    }
    else{
      all.forEach(function(td){
        td.style.display = "none";
      });
    }
  }
  if(chk.classList.value.includes('select-one')){
    document.querySelector('.All').checked = false;
    all.forEach(function(td){
      td.style.display = "none";
    });
    if(chk.checked){
      document.querySelector('.text-one').style.display = "block";
    }
    if(document.querySelector('.select-two').checked){
      document.querySelector('.text-two').style.display = "block";
    }
  }
  if(chk.classList.value.includes('select-two')){
    document.querySelector('.All').checked = false;
    all.forEach(function(td){
      td.style.display = "none";
    });
    if(chk.checked){
      document.querySelector('.text-two').style.display = "block";
    }
    if(document.querySelector('.select-one').checked){
      document.querySelector('.text-one').style.display = "block";
    }
  }

}
<input type="checkbox" class="All" onclick="myFunction(this)">All
<input type="checkbox" class="select-one" onclick="myFunction(this)">Select 1
<input type="checkbox" class="select-two" onclick="myFunction(this)">Select 2

    Checkbox is CHECKED!

    Checkbox is CHECKED 1!

    Checkbox is CHECKED 2!

A: You can achieve this using pure javascript like this
var classname = document.getElementsByClassName("All");
var myFunction = function() {
var at = this.getAttribute("id");
if(at == 'selectAll' ) {
var checkedele = classname[0].checked;
var closestTr = classname[0].closest("td").closest("tr");
    closestTr.getElementsByClassName('togg')[0].style.display=checkedele?'block':'none';
  for (var i = 1; i < classname.length; i++) {
            classname[i].checked = checkedele;
           var closestTr = classname[i].closest("td").closest("tr");
           closestTr.getElementsByClassName('togg')[0].style.display= checkedele?'block':'none';
  }
} else {
var checkedele = this.checked;
var closestTr = this.closest("td").closest("tr");
         closestTr.getElementsByClassName('togg')[0].style.display= checkedele?'block':'none';
}

var checkedCount = 0
for (var i = 1; i < classname.length; i++) {
if(classname[i].checked){
 checkedCount++;
 }
}

if(!checkedCount) {
classname[0].checked = false
var closestTr = classname[0].closest("td").closest("tr");
    closestTr.getElementsByClassName('togg')[0].style.display='none';
}
};

 for (var i = 0; i < classname.length; i++) {
   classname[i].onclick = myFunction;
 }

html code

<input type="checkbox" class="All" id="selectAll">All
Checkbox is CHECKED!

   <input type="checkbox" class="select-one All">Select 1
   Checkbox is CHECKED 1!

   <input type="checkbox" class="select-two All">Select 2
   Checkbox is CHECKED 2!

fiddle link
http://jsfiddle.net/gfz1vyr2/1/
you can optimise this code...

A: check below code if works as per your requirement:

function myFunction(t) {

 var text = document.getElementsByClassName("text-all")[0];
      if(t.checked)
      {
       text.style.display = "block";
        var checkboxes = document.getElementsByName("chk");
        for(var i=0, n=checkboxes.length;i<n;i++) {
       checkboxes[i].checked = true;
          CheckFunction(checkboxes[i]);
     }
      }
      else
      {
       text.style.display = "none";
        var checkboxes = document.getElementsByName("chk");
        for(var i=0, n=checkboxes.length;i<n;i++) {
       if(checkboxes[i].checked)
           { checkboxes[i].checked = false;
            CheckFunction(checkboxes[i]);
             }
     }
      }
}

function CheckFunction(chk)
{
 if(chk.id == "chk-one")
  {
    var text = document.getElementsByClassName("text-one")[0];
    if (chk.checked == true) {
      text.style.display = "block";
    } else {
      unchkAll(text);
    }
  }
  else
  {
   var text = document.getElementsByClassName("text-two")[0];
    if (chk.checked == true) {
      text.style.display = "block";
    } else {
      unchkAll(text);
    }
  }
}

function unchkAll(text)
{
text.style.display = "none";
      var chkall = document.getElementById("chk-all");
      if(chkall.checked)
      {
       chkall.checked = false;
       myFunction(chkall);
      }
}
<input type="checkbox" name="chkbox" id="chk-all" class="All" onclick="myFunction(this)">All
<input type="checkbox" id="chk-one" name="chk" class="select-one" onclick="CheckFunction(this)">Select 1
<input type="checkbox" id="chk-two" name="chk" class="select-two" onclick="CheckFunction(this)">Select 2

    Checkbox is CHECKED!

    Checkbox is CHECKED 1!

    Checkbox is CHECKED 2!

Hope this helps.


text:
Q: Two of the same commands give different result (output as utf8) I have a .bat file that contains two commands:

SQLCMD -S . -d "databaseName" -E -i "path_to_query1.sql" -y0 -s "|" -f o:65001 > outputPath1.json

SQLCMD -S . -d "databaseName" -E -i "path_to_query2.sql" -y0 -s "|" -f o:65001 > outputPath2.json

The argument -f o:65001 is to output it to utf8 format, but only the second line outputs the query in an utf8 format.
Why is this? Why does it seem that the argument "-f o:65001" only works for the second command?
I checked it by switching the order and then again only the second command outputs the query in utf8 format.
Thanks for any tips on this.
EDIT
The solution for my specific problem was to put "chcp 65001" before the SQLCMD's. You then also don't need the argument -f 0:65001

redpajama_set_name: RedPajamaStackExchange


text:
Q: Label on UIButton of type UIButtonTypeCustom is not displaying I want to add a borderless UIButton to my view. Using the interface builder, I do this by dragging a Round Rect Button from the object library. Then, on the attributes inspector, change the Type to Custom and leave the title to "Button." Everything is okay with the interface builder. But, this is not the case with the programmatic approach. Programmatically, this is how I do it:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(x, y, width, height)];
[button setTitle:@"Button" forState:UIControlStateNormal];

When I run the app, the button is not displayed. Maybe I'm missing something here but when I change the type to UIButtonTypeRoundRect the button is displayed. But, again, I want the button to be borderless.
Anyway, I can always use the interface builder. However, I want to understand why the programmatic approach doesn't work. So, does anyone know what the problem is?

A: UIButtonTypeCustom is really, actually a custom button type. There are no meaningful values setup for it by default. If you want to display it, you have to set its background color and/or its title color to a non-transparent one:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(x, y, width, height)];
[button setTitle:@"Button" forState:UIControlStateNormal];
// Set visible values
[button setBackgroundColor:[UIColor greenColor]];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[someSuperview addSubview:button];

A: Here i have used your code the Thing you missing is that
 [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

A: Hi I was in the same situation.
I do not know why somewhere in my code there was
button.translatesAutoresizingMaskIntoConstraints = NO;

Once I've deleted that line I was able to set my button frame without any issues.
Hope this helps


text:
Q: What's the difference between the five masses: inertial mass, gravitational mass, rest mass, invariant mass and relativistic mass? I have learned in my physics classes about five different types of masses and I am confused about the differences between them.
What's the difference between the five masses:

*

*inertial mass,

*gravitational mass,

*rest mass,

*invariant mass,

*relativistic mass?

A: A body's inertial mass is the mass measured by its resistance to changes in motion. Its gravitational mass is the mass measured by its attraction by gravitational force. Its rest mass is the mass when it's at rest with respect to an observer, and is then equivalent to its inertial mass.

A: Astonishingly (for this site) poor performance of experts. They simply restated some historical knowledges of Newton's age and threw some modern formulas over it, without considering misconceptions of former or latter.
Here is my answer (not in original order):
1. invariant mass
A scalar quantity, an intrinsic property of a body (preserved by Poincaré transformations, and with some clauses, in General Relativity). Is constant for subatomic particles (each species has its value of mass), as well as for atoms (and similar objects) on a specified energy level. Does not have a conservation law. Is not strictly constant for large bodies; for example, increases with heat.
2. rest mass
The same as invariant mass if it is positive. For particles with zero invariant mass, strictly speaking, rest mass is undefined (although both terms might be synonymous in colloquial speech). A separate term is motivated by the fact that massive bodies, and only them, have their rest frames (may be also called CoM frames).
3. relativistic mass
A historical misconception; in short, the same as energy in Special Relativity. See  Why is there a controversy on whether mass increases with speed? for details.
4. inertial mass
The "m" thing in Newtonian mechanic; thought to be a conserved scalar quantity. For low speeds approximately equals to the rest mass, but generally an obsolete concept since relativistic dynamics. Depending on context, is superseded in relativity either with the rest mass or (along momentum vectors) with 4-momenta. One can't consistently define inertial mass of a photon, for example.
5. gravitational mass
Supposed gravitational charge (for Newton's gravity law or some another theory). GR's equivalence principle suggests that it does not differ from energy and momentum (it means there is no scalar charge in gravitation!) and isn't recognized as a separate concept in GR. But alternative theories of gravitation are possible, in principle.

A: Let us define the inertial mass, gravitational mass and rest mass of a particle.
Inertial mass:
To every particle in nature we can associate a real number with it so that the value of the number gives the measure of inertia (the amount of resistance of the particle to accelerate for a definite force applied on it) of the particle.
Using Newton's laws of motion,
$$m_i = \frac{F}{a}$$
Gravitational mass:
(This is defined using Newton's law of universal gravitation i.e. the gravitational force between any two particle a definite distance apart is proportional the product of the gravitational masses of the two particles.) To every particle in nature we can associate a real number with it so that the value of the number gives the measure of the response of the particle to the gravitational force.
$$F = \frac{Gm_{G1}m_{G2}}{R^2}$$
All experiments carried out till date have shown that $m_G = m_i$
This is the reason why the acceleration due to gravity is independent of the inertial or gravitational mass of the particle.
$$m_ia = \frac{Gm_{G1}m_{G2}}{R^2}$$
If $m_{G1} = m_i$ then $$a = \frac{Gm_{G2}}{R^2}$$
That is acceleration due to gravity of the particle is independent of its inertial or gravitational mass.
Rest mass:
This is simply called the mass and is defined as the inertial mass of a particle as measured by an observer, with respect to whom, the particle is at rest.
There was an obsolete term called relativistic mass which is the inertial mass as measured by an  observer, with respect to whom, the particle is at motion. The relation between the rest mass and the relativistic mass is given as
$$m = \frac{m_0}{\sqrt{1-v^2/c^2}}$$
where $v$ is the speed of the particle and $c$ is the speed of light, $m$ is the relativistic mass and $m_0$ is the rest mass.

A: Inertial mass is the mass that appears in Newton's Second Law $$F=ma$$ Gravitational mass is what appears in Newton's Law of Gravity $$F=\frac{GMm}{r^2}$$ Einstein's Equivalence Principle requires that inertial mass and gravitational mass are equal so that all masses react the same way to a given gravitational field ($m$ cancels in the above two equations to give the same acceleration). This equality has been established to great precision in many experiments.
Rest mass is a somewhat obsolete term for what is referred to more commonly today as the invariant mass, proper mass or simply just mass in relativistic physics. Given the 4-momentum $p^\mu$ of a particle, a scalar invariant can be obtained from it which is the square of its mass. $$p^\mu p_\mu=m^2$$
Since it is an invariant, it holds true in any reference frame. However, in the frame in which the particle is at rest, $m$ equals the total energy of the particle (in units of $c=1$), hence the old name of "rest mass".
Newton's second law takes a different form when relativity is taken into account, so it's not helpful to compare rest mass and inertial mass, except of course in the rest frame of the particle. The important conceptual difference in relativity however is that inertia, defined as the resistance to motion, depends on the velocity of the particle so that the higher the velocity, the harder it is to accelerate it. You can read more about that in the Wikipedia article or a nice textbook on Special Relativity.


text:
Q: How to use CREATE/DROP table inside IF I am migrating data from a series of old data tables to new tables. In this process I came upon some issues.
I need to create a table, copy some data from old table to new one then drop old table. To achieve this, I need to write a script that does not show errors even if you run it on a migrated database, meaning even if the old tables are not there I should not see errors and simply skip the process.
Following is what I came up with up to now:
IF NOT EXISTS(SELECT * FROM sys.objects WHERE Object_ID = Object_ID('Old_Table'))
    GOTO Migrated_Before

  -- Drop OldTable Indexes, PK's and FK's;
  -- CREATE newTable ....;
  -- Add Indexes, PK's, Fk's;
  -- INSERT INTO NewTable(someFields) FROM OldTable.Fields, OtherTable.Fields ...;
  -- DROP OldTable;

Migrated_Before:

Here is the issue, Drop and Create need GO to commit changes before continue to next stage otherwise, next command will fail, however putting GO between GOTO and Label will make label undefined for GOTO.
How can I force each process to run before continue to next one without writing IF multiple times?
Solution: I leave the solution here as reference for others.
I added begin transaction before every statement that need to happen before proceeding to next statement, for example, create table or drop FK's. and also replaced goto and label with begin end (my first solution)

A: Try using begin transaction, commit instead of go

A: Try putting the CREATE, DROP and following 3 commands in a separate stored procedure and call that procedure after GOTO. This SP will contan the required GO statement. This may keep the scope of Label as it is.

A: I can run this code below without any "GO"
if object_id('abc') is not null
    drop table abc
create table abc (asdf varchar(10))

if object_id('abc') is not null
    drop table abc
create table abc (asdf varchar(10))

if object_id('abc') is not null
    drop table abc
create table abc (asdf varchar(10))

Also, you can just check for object_id() of null instead of querying the sys.objects table.


text:
Q: Why can't I boot into Ubuntu installed alongside Windows 8? Once I reboot it after the installation, it brings me to a screen to choose Windows 8 or Ubuntu. When I click Ubuntu it brings me to a screen with this options:

*

*Reinstall windows

*Change the language or

*Repair

And then it brings me back to the GRUB, and then if I pick Ubuntu it does it again.

A: Pre install windows 8 comes with UEFI secure boot enabled
(UEFI which substitutes what we have known as the BIOS)
which prevent unrecognized source to boot or Linux
But latest version of Ubuntu have support for the UEFI boot see (you doesn't mention which Ubuntu version you are using) https://help.ubuntu.com/community/UEFI
So there is no problem in dual boot Ubuntu with windows 8
for your convenient (solve your problem ) you can off the UEFI secure boot in some easy step they are
1 ) while holding shift key click on restart option (from power)
2 ) windows will show you option then select Troubleshoot
3 ) select advanced options
4 ) select UEFI frameware settings then disable it after restart
Here is the video
Then you are able to boot ubuntu and even old version of the Linux which couldn't install before in windows 8 .
in dual boot if you don't get the windows 8 listed in grub menu then
type following command in terminal while mounting drive which have windows installed

sudo update-grub2


text:
Q: Merge two dateframes I'm relatively new to R and I'm trying to create some graphs from air quality data. I was able to follow the tutorials and achieve what I want, there is just one thing that does not work for me.
I have a CSV with one column Date, one Time and some other columns with data. I was able to use the selectbydate method to extract certain period. Now what I need to do is combine two or more periods together into one dataset.
So far I have:
library(writexl)
library(openair)

dataSet <- import(file = "dataCSV.csv", file.type = "csv", sep = ";", header.at = 1, data.at = 2, date = "Date", date.format = "%d.%m.%Y", time = "Time", time.format = "%H:%M",quote = "\"")
x <- selectByDate(dataSet, start = "31/8/2018", end = "31/8/2018", hour = 21:23)

I then use "x" for the analysis and it works fine.
However when I try this:
x <- selectByDate(dataSet, start = "31/8/2018", end = "31/8/2018", hour = 21:23)
y <- selectByDate(dataSet, start = "1/9/2018", end = "1/9/2018", hour = 0)
z <- merge(x,y)

And I then try to pass "z" as the dataset later, I get
Error in matrix(unlist(value, recursive = FALSE, use.names = FALSE), nrow = nr,  :

length of 'dimnames' [2] not equal to array extent

Thanks in advance for any help.


text:
Q: How to get selected checkbox value and id from the multi select in MUI I am using MUI select component with multi-select. The multi-select rendering uses the below JSON array. Is there any way we can get both the selected item id and value?
Here is the code sandbox URL :https://codesandbox.io/s/cranky-currying-ce8djy?file=/src/App.js
JSON Array: const menuItems = [
  { id: "8271e42a-8982-44b8-9745-3271e0cf9d12", value: "Item 1" },
  { id: "c0f3e462-02f8-4d8d-ae05-6965b7902a80", value: "Item 2" },
  { id: "c0f3dfyh-02f8-4d8d-ae05-6965b7dw3456", value: "Item 3" }
];

 export default function App() {
  const [selected, setSelected] = useState([]);

  const handleChange = (event) => {
    const {
      target: { value }
    } = event;
    setSelected(typeof value === "string" ? value.split(",") : value);
    console.log(selected);
  };

  const ITEM_HEIGHT = 48;
  const ITEM_PADDING_TOP = 8;

  const lteProps = {
    PaperProps: {
      style: {
        maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
        width: 250
      }
    }
  };
  return (
    <div className="App">
      <FormControl fullWidth={true}>
        <Select
          multiple
          value={selected}
          onChange={handleChange}
          renderValue={(selected) => selected.join(", ")}
          MenuProps={lteProps}
        >
          {menuItems.map((item) => (
            <MenuItem key={item.id} value={item.value}>
              <Checkbox checked={selected.indexOf(item.value) > -1} />
              <ListItemText primary={item.value} />
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}

Appreciate any help.

A: I worked before on MUI.
You need to add one more parameter to the handleChange function to access ID. But it is currently returning ID with .$. So you have to filter these two chars.
  const handleChange = (event,obj) => {
    const {
      target: { value }
    } = event;
    setSelected(typeof value === "string" ? value.split(",") : value);
    // on selecting first option, will return
    // .$8271e42a-8982-44b8-9745-3271e0cf9d12
    console.log(obj.key);
  };


text:
Q: Does setting a Random objects' seed to a random value make the generator more random? I have this code that simulates 10 coin tosses:
public void FlipCoinTenTimes() {
    Random randomNumberGenerator = new Random();

    // Generate 10 random numbers
    for (int i = 0; i < 10; i++) {
        randomNumberGenerator.setSeed(randomNumberGenerator.nextLong());
        System.out.println(randomNumberGenerator.nextInt(2) == 0 ? "Heads" : "Tails");
    }
}

Does the setting of the seed to a random long make this method any more random? I.e., more 50/50 than if I were to remove the setSeed() line?

A: No, settings the seed like this will not make it 'more random'. The default constructor will use a random seed.
The Random class uses a linear congruential generator to generate a pseudo random series of bits. The state of the random class is contained in something called the seed. When the class is asked for a random number the seed is updated.
It should not affect the distribution to manually reset the distribution of random numbers. If you need a better distribution that is also harder to predict you can use SecureRandom.


text:
Q: How to integrate Rational Functional Tester(RFT) and Jenkins? As part of our continuous integration and testing,we could like to execute a set of RFT automated tests after each build and unit test is complete. If anyone has done this before,please provide the instructions for the same.
Thanks!

A: Some Web resources on the topic:

*

*Someone actually tried the same:
https://www.ibm.com/developerworks/community/forums/html/topic?id=cda9f004-65bd-4594-b987-cfca4174ba9b

*How to set up head less UI testing (you need to somehow get the OS
support for UI testing):
http://rapaul.com/2011/06/05/zero-to-headless-browser-tests-jenkins/

*How to run RFT from Command line: http://www.linkedin.com/groups/is-it-possible-create-integration-3768419.S.219369876
This should give you a start. Your goal is to set up a system where you can run the tests as a real user (from an OS point of view) and not as a service.


text:
Q: How to prove that infimum of this set is $0$
How do I prove that the infimum of the set $A=\{x+\frac{1}{n}:x\in(0,1),n\in\mathbb{Z^+}\}$ is $0$?

Clearly $0$ is a lower bound of A since $1/n$ is greater than $0$ for all $n$. How do I show that any real number $K>0$ is not also a lower bound, hence making $0$ the infimum?
Thanks!

A: Use the fact that $\frac K2+\frac1n\lt K$ if $n$ is large enough.

A: It remains to show that for a given $\epsilon>0$ there are $x\in(0,1)$ and $n\in\mathbb{Z^+}$ such that
$$ x+\frac{1}{n}<\epsilon.$$
Note that the above inequality is implied by $x<\frac{\epsilon}{2}$ and $\frac{1}{n}<\frac{\epsilon}{2}$. Can you take it from here?


text:
Q: pyenchant for other languages I know this was a topic before but unfortunately, nothing is working when it comes to the old solutions. So I need to figure out how to use pyenchant for german.
If I use enchant.list_languages() it just shows me all kinds of English languages.
Edit: I'm using windows

A: Here the answer using python 3.10 and windows 11.
Download both .aff and .dic files from:
https://github.com/LibreOffice/dictionaries
Then copy the files to the folder C:\Users\your_username\AppData\Local\Programs\Python\Python310\Lib\site-packages\enchant\data\mingw64\share\enchant\hunspell
If you're using other Linux, Mac, or your Windows configuration is different, type pip show pyenchant in terminal to see where pyenchant is installed, then navigate to subfolder enchant\data\mingw64\share\enchant\hunspell to find the dictionaries folder.


text:
Q: Are there any issues with this network setup I have setup my house from which I run 3 business, host servers etc. I setup lots of outlets for wired network 20 years ago. I later added Wifi.
I do not know enough about networking to spot potential issues, and I sometimes have weird networking issue like VOIP devices disconnecting, printer not accessible etc. I want to know, if there is something fundamentally wrong with my design that could cause issues.
Some specific questions:

*

*is it OK that there are two switches? Especially that LAN cable connecting the switches is rather long (~ 60 feet).

*is it OK that the 2nd floor wifi access points is connected to the 2nd switch and not directly to the modem/router?

*can there be an issue with a computer from 2nd floor, connecting to computer on wifi network in the basement? Thus having to go through 2 switches?
3.1) is it possible, in such a case, that the connection from 2nd floor will somehow not know how to be routed to computer in basement?

*I am only getting 2MB/s transfer rate for any device on the WIFI network, but ~10BM/s on  devices connected via LAN cable (switches are 10/100 mbps). I would expect my wifi performance to be better, but I know it could be normal. However, is there anything in my network architecture that could be the cause of this?

Any help would be much appreciated!

A: Fundamentally, the setup looks fine.
Length of cables are not an issue (even total length).
Make sure devices are connected LAN to LAN and that the DCHP server you show is the only DHCP server - that is, do not let any other device be a DHCP server.
Make sure everything is on one subnet.  This certainly facilitates network printing.
Make sure devices and printers have static IP addresses to prevent getting lost in case of a power failure or network restart.
That way all devices will be able to see all other devices (assuming you want this at the device level).
Any device (server) facing the Internet (web server) will have to be set up and secured separately. The above in my post is for the internal business requirements.
I come pretty close to doing this. Modem, Router in basement, main computer (wired) on main floor, printer on main floor, Ubqiquiti AP and wireless laptops in upstairs office.
Phone roam throughout the home.


text:
Q: Google Analytics Code Returns 'Undefined Function" Error whatever I do, I keep getting an "Uncaught TypeError: undefined is not a function" error for the click tracking Google Analytics code.
The page is: http://www.purevisionmethod.com/eye-exercises/
Please, why is this happening...?
<script>
$('#clicked-headerbar').on('click', function() {
  ga('send', 'event', 'website-banner', 'clicked-ad', 'headerbar', '0');
});
$('#clicked-cta-bottom').click( function() {
  ga('send', 'event', 'website-banner', 'clicked-ad', 'cta-bottom', '0');
});
$('#clicked-sidebar-image-ad-1').click( function() {
  ga('send', 'event', 'website-banner', 'clicked-ad', 'sidebar-ad-1', '0');
});
$('#clicked-sidebar-image-ad-2').click( function() {
  ga('send', 'event', 'website-banner', 'clicked-ad', 'sidebar-ad-2', '0');
});
$('#clicked-sidebar-image-ad-3').click( function() {
  ga('send', 'event', 'website-banner', 'clicked-ad', 'sidebar-ad-3', '0');
});
</script>

Thanks for your help!!

A: The error isn't related to Google Analytics.
The error is because you're including the jQuery library after this code which uses jQuery. Move this code below your jQuery include, or move your jQuery include to be before this code, and it'll work.

A: First register your tracking id on Google Analytics. Then Google will provide you a block of code which will include some javascript code with your registered tracking id. Put that code into your webpage and then write above code below of Google Analytics code.

A: I actually identified this as the offending line:
$('#clicked-headerbar').on('click', function() {
  ga('send', 'event', 'website-banner', 'clicked-ad', 'headerbar', '0');
});

change the .on() to .click() as below:
$('#clicked-headerbar').click( function() {
  ga('send', 'event', 'website-banner', 'clicked-ad', 'headerbar', '0');
});

Not sure why this is happening, however your page is loading two versions of jQuery.


text:
Q: How Do I Override the Standard Controller's Save Action in My Controller Extension? I am trying to build a controller extension for the Opportunity standard controller.
According to documentation and stackexchange I ought to be able to override the Save() action in the controller extension. I have a VF page that is embedded in the standard Opportunity layout and a save() method in the controller extension, but the save() method in my controller extension never gets called.
What am I doing wrong?
The VF page - embedded in the standard Opportunity layout:
<apex:page standardController="Opportunity" extensions="TestExtension" showHeader="false" >
</apex:page>

The controller extension class - I get the constructor debug message, but not the one from save():
public without sharing class TestExtension {

    ApexPages.StandardController stdController = null;

    public TestExtension(ApexPages.StandardController stdController) {
        this.stdController = stdController;
        System.debug('==== TestExtension: TestExtension() ====');
    }
    public PageReference save() {
        System.debug('==== TestExtension: save() ====');
        // do some stuff
        Pagereference ref = stdController.save();
        // some more stuff
        // give control back to standard controller
        return ref;
    }
}

A: The examples you are referencing only apply if your controller extension is managing the entire page. You cannot change the standard save behavior for an object by embedding a Visualforce page in its layout; page embedding is not a "hook" into the save process.
Your only direct solution is overriding the entire action with a Visualforce page or Lightning (Aura) component, which requires you to reimplement the page layout. It's an expensive, clumsy, inflexible solution that I usually recommend against.
In most cases, a better solution is to rethink your overall objective such that you can achieve it with some combination of

*

*Quick Actions, for streamlining create operations with prepopulated fields.

*Screen Flows, for interactive wizard-style UIs.

*Apex triggers or record-save flows, for non-UI automation.


text:
Q: How to retrieve date from database using java I need to retrieve the date and time from a database. My code correctly retrieves the date and time but when I use toString() it adds a ".0" to the end of the time. How can I avoid this?
IE: date on database is 2013-03-05 11:05:25
When I retrieve it and try to convert it to a String it becomes 2013-03-05 11:05:25.0
 r.getTimestamp("mydate").toString();

A: Don't think about the value on the database as being a string value at all. Think of it being a point in time. (I'm assuming it really is a TIMESTAMP field or something similar.)
If you want to format it in a particular way, do so - but 2013-03-05 11:05:25 is the same point in time as 2013-03-05 11:05:25.0... it's just using a different string representation.

A: Use SimpleDateFormat to display the date in any fashion you want
String output = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(r.getTimestamp("mydate"));

This should display it how you are after.
EDIT:
You have said your method is not returning the object as a timestamp or date, you need to put it into a date format first to use SimpleDateFormat:
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String in = r.getTimestamp("mydate"));
Date d = sdf.parse(in);

A: If you want to actually remove the ".0" you could just do this. Where "s" is the string object with the extra 2 characters.
s = s.substring(0, s.length() - 2);


text:
Q: The two projections in an $ C^*$ algebra Let $A$ be a $C^∗$-algebra, $a \in  A$ and let $p,q \in A$ be orthogonal projections (i.e. selfadjoint idempotents with $pq = 0$). Suppose that a is positive and $pap = 0$. Show that $paq = 0$
Could you check my solution of following problem ( i am stressed a little due to the operator $q$)?
My solution: so, there is the positive element $b$ that $bb=a$. Therefore $pap=pbbp=pb(bp)^*=0$, then using the $ C^*$ property we can conclude $pb=0$

A: The only thing I can see that is wrong when you claim $pbbp=pb(bp)^*$.  What you should write is $pbbp=pb(pb)^*$.  (It's not actually wrong, because you actually prove that $pb=0=0^*=bp$, but, you know, deduction.)
And as far as my proof-writing style is concerned (and to make this more than a two-line answer), you should write
$$pap=pbbp=pb(pb)^*=0$$
as
$$0=pap=pbbp=pb(bp)^*,$$
so that it's logically consistent.

A: Your argument is the standard way to deal with this, with the minor exception mentioned by Aweygan.
The probable reason the problem is formulated this way is, that if you write $a$ as a $2\times 2$ matrix with respect to $p$, you are showing that if $a_{11}=0$ then $a_{12}=a_{21}=0$.


text:
Q: Evaluate $\oint_C\frac{dz}{z-2}$ around the square with vertices $3 \pm 3i, -3 \pm 3i$. I'm having a tough time figuring out $\gamma(t)$ in $\oint_C f(z) dz = \int_a^b f(\gamma(t)) \gamma '(t) dt$. I think I have to split this into four parts, the four separate lines, but from there I'm trying to get things to cancel out so that I could arrive at the answer $2\pi i$. Clearly, we have to consider $3+3i \to -3+3i \to -3 - 3i \to 3-3i$, but I can't seem to find a good starting point.

A: Cauchy's integral formula (and the homotopy invariance of the contour integral) tells you that for holomorphic $f$, $$\oint_C \frac{f(z)}{z-2} = 2\pi i f(2).$$ Apply this to the constant function $f = 1$.

A: We have four curves:
$C_1=x-3\cdot i$ for $-3 \leq x \leq 3$
$C_2=3+y\cdot i$ for $-3 \leq y \leq 3$
$C_3=x+3\cdot i$ for $-3 \leq x \leq 3$
$C_4=-3+y\cdot i$ for $-3 \leq y \leq 3$
Then we just have $\int_C f(z)\,dz=\int_{C_1}f(z)\,dz+\int_{C_2}f(z)\,dz+\int_{C_3}f(z)\,dz+\int_{C_4}f(z)\,dz$.
I can add more to clarify.

A: Just apply the Cauchy Integral formula. And you will get $2\pi(i)f(2)$ = $2\pi(i)$, since $f(z)=1$ and $2$ is an interior point of your contour.
This link should clarify: http://en.wikipedia.org/wiki/Cauchy%27s_integral_formula
By using the Cauchy integral theorem, one can show that the integral over C (or the closed rectifiable curve) is equal to the same integral taken over an arbitrarily small circle around a. Since f(z) is continuous, we can choose a circle small enough on which f(z) is arbitrarily close to f(a). On the other hand, the integral,


text:
Q: create wordpress plugin with zend framework 2 I want to develop a membership plugin under wordpress and for this I want to use zend framework 2.
Does anyone managed to create a wordpress plugin using zend framework 2?
I'm new to zf and I do not know how and where to start from.
I tried to start from zend skeleton application but got stuck at add_menu_pages and displaying a simple dashboard.
Can anyone give me some ideas or links.
Thanks!
Updated!
I managed to get this working! I just needed to use a PhpRenderer. For those who need a little more help here is how I did:
I created a class that manages all admin area. On class init I called a method that created menu pages( in this method simply add_menu_pages() and instead of callback_function I called a new method, manage_pages, that, wel... manages pages, but you can do it as you desire) and then I initiated the view, like this:
  $this->view = new PhpRenderer();
  $this->map = new Resolver\TemplateMapResolver(array(
        'template_name' => 'template_path',
        'template2_name'=> 'template2_path')); //this is for handling view templates a little easier
  $this->resolver = new Resolver\TemplateMapResolver($this->map);
  $this->view->setResolver($this->resolver);
  $this->model    = new ViewModel();

Further, in manage_pages method, for each page I have, I added its own template and variables I needed
 $this->model->setTemplate('template_name');
 $this->model->setVariable('variable_name', value);

As for displaying template, you just have to write this piece of code:
 echo $this->view->render($this->model);

In the template files you can access variables using $this->variable_name
Also you can insert another template using $this->partial( 'template2_name', assoc_arrray_of_variables_to_be_passed_to_template ).
And this is it! If you have any questions, please let me know!

A: There is a wordpress plugin you can use, search "wopzen2" or "wordpress and zend framework 2 integration" on Google, with this solution, you can use the following code inside the php wordpress code:

    global $wpzf2plugin;
    $render=$wpzf2plugin->render('/application/index/contactform');
    echo $render;

This code calls the contactform action, if you are familiar with zendframework I think you are going to understand it.
This plugin is dedicated to developers.
You can get a free version of the plugin via support center.
I hope this answer can be helpful for you
reference link:
Example codes


text:
Q: htaccess unwanted redirect to a page non in folder I have created an htaccess
I have these htaccess redirect rules for redirect some pages as first level and other as in folder pages. The problem is that with these rules are created some second level pages (from first level pages name):
RewriteRule ^([A-Za-z0-9-]+)$  content.php?name=$1 [L]
for first level pages: and I get correct url
mywebsite/mypage1
mywebsite/mypage2
mywebsite/mypage3
and
RewriteRule ^sector/([A-Za-z0-9-]+)$  category/index.php?name=$1 [L]
for in folder pages: and I also get correct url
mywebsite/sector/mysectorpageA
mywebsite/sector/mysectorpageB
mywebsite/sector/mysectorpageC
My problem is that are also created unwanted url first level page name:
mywebsite/sector/mypage1
mywebsite/sector/mypage2
mywebsite/sector/mypage3
Thanks in advance for any help


text:
Q: JavaFX MediaPlayer: plays half as many times it should when setStopTime is used When setStopTime is used on my MediaPlayer, the media plays about half as many times as is specified by setCycleCount.
So if I use player.setCycleCount(10), the sound plays only about 5 times instead of 10.
Why is the player acting this way, and how do I make it play the intended number of times?
I did more tests and it seems that after playing once, currentCount is increased by 2 instead of 1, and OnEndOfMedia is triggered twice too.
The problem seems to be limited to some of the medias. Examples:
https://ia601701.us.archive.org/21/items/Laser_201304/laser.mp3 (about 1.8 seconds long)
https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3 (about 27 seconds long)
The problem disappear if I stop using setStopTime.
Here is a complete example of the problem. Notice how the sound is not played 10 times, and how on most cycles the text is printed twice to the console.
package main;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        Media media = new Media("https://ia601701.us.archive.org/21/items/Laser_201304/laser.mp3");
        MediaPlayer player = new MediaPlayer(media);

        // Add to scene
        Group root = new Group(new MediaView(player));
        Scene scene = new Scene(root, 500, 200);

        // Show the stage
        primaryStage.setTitle("Media Player");
        primaryStage.setScene(scene);
        primaryStage.show();

        player.setCycleCount(10); // should run 10 times, but runs 5-8 times
        player.setStopTime(new Duration(1800)); // removing this fixes the issue

        long start = System.currentTimeMillis();
        player.setOnEndOfMedia(
                new Runnable() {
                    @Override
                    public void run() {
                        float sec = (System.currentTimeMillis() - start) / 1000F;
                        System.out.println("Current Count: " + player.getCurrentCount() + " Seconds: " + sec);
                    }
                });
        player.play();
    }
    public static void main(String[] args) {
        launch(args);
    }
}

Example of output:
Current Count: 1 Seconds: 3.456
Current Count: 2 Seconds: 3.465
Current Count: 3 Seconds: 5.334
Current Count: 4 Seconds: 7.177
Current Count: 5 Seconds: 7.185
Current Count: 6 Seconds: 9.056
Current Count: 7 Seconds: 10.896
Current Count: 8 Seconds: 10.906
Current Count: 9 Seconds: 12.776
Current Count: 10 Seconds: 12.798

Notice how OnEndOfMedia is often triggered in quick succession, for example 1-2, 4-5, 7-8, and 9-10 (in this case the media played 6 times).
I tried with JavaFX 10, 11 and 13 and I get the same issue.
EDIT: I've noticed that for problematic medias, getCurrentTime() always return the maximum duration of the media.


text:
Q: Match on multiple columns using array I'm working on a project where my original dataframe is:
      A     B    C   label
0     1     2    2    Nan
1     2     4    5    7
2     3     6    5    Nan
3     4     8    7    Nan
4     5    10    3    8
5     6    12    4    8

But, I have an array with new labels for certain points (for that I only used columns A and B) in the original dataframe. Something like this:
X_labeled = [[2, 4], [3,6]]
y_labeled = [5,9]

My goal is to add the new labels to the original dataframe. I know that the combination of A and B unique is. What is the fastest way to assign the new label to the correct row?
This is my try:
y_labeled = np.array(y).astype('float64')

    current_position = 0
    for point in X_labeled:
        row = df.loc[(df['A'] == point[0]) & (df['B'] == point[1])]
        df.at[row.index, 'label'] = y_labeled[current_position]
        current_position += 1

Wanted output (rows with index 1 and 2 are changed):
       A     B    C   label
0     1     2    2    Nan
1     2     4    5    5
2     3     6    5    9
3     4     8    7    Nan
4     5    10    3    8
5     6    12    4    8

For small datasets may this be okay with I'm currently using it for datasets with more than 25000 labels. Is there a way that is faster?
Also, in some cases I used all columns expect the column 'label'. That dataframe exists out of 64 columns so my method can not be used here. Has someone an idea to improve this?
Thanks in advance

A: Best solution is to make your arrays into a dataframe and use df.update():
new = pd.DataFrame(X_labeled, columns=['A', 'B'])
new['label'] = y_labeled
new = new.set_index(['A', 'B'])
df = df.set_index(['A', 'B'])
df.update(new)
df = df.reset_index()

A: Here's a numpy based approach aimed at performance. To vectorize this we want a way to check membership of the rows in X_labeled in columns A and B. So what we can do, is view these two columns as 1D arrays (based on this answer) and then we can use np.in1d to index the dataframe and assign the values in y_labeled:
import numpy as np

X_labeled = [[2, 4], [3,6]]
y_labeled = [5,9]

a = df.values[:,:2].astype(int) #indexing on A and B

def view_as_1d(a):
    a = np.ascontiguousarray(a)
    return a.view(np.dtype((np.void, a.dtype.itemsize * a.shape[-1])))

ix = np.in1d(view_as_1d(a), view_as_1d(X_labeled))
df.loc[ix, 'label'] = y_labeled

print(df)

   A   B  C label
0  1   2  2   Nan
1  2   4  5     5
2  3   6  5     9
3  4   8  7   Nan
4  5  10  3     8
5  6  12  4     8


text:
Q: Spring Data JPA : How save data into database using save() of jpaRepository I created one spring Application.  I am trying to save data into database using save method of JPA Repository. i am getting Error null value in column "id" violates not-null constraint
HomeController
@RestController
public class HomeController
{
    @Autowired
    public userRepository repository;

     @RequestMapping(value="/save2",method=RequestMethod.POST )
     public String save1(@ModelAttribute user us)
     {

         repository.save(us);

       return "sucessfull";

     }
}

user
@Entity
@Table(name="user", schema="new")
public class user implements Serializable
{

private static final long serialVersionUID = -2956665320311624925L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer id;

@Column(name="uname")
public String uname;

@Column(name="pass")
public String pass;

Table Script

Through Postman I am trying to Insert following data

I am getting this error
org.postgresql.util.PSQLException: ERROR: null value in column "id" violates not-null constraint

Can Any one tell me what i am doing wrong in above code

A: I see couple of issues here.
First, replace your @ModelAttribute with @RequestBody since you're sending a JSON request, it is wise to use the latter. (Read up here and here). In your case, the values from request is not passed to repository save method including Id value. That's the reason you're getting not null constraint error.
Second, since you're using GenerationType.IDENTITY strategy, you should use serial or bigserial type to let Postgres to generate your primary key.
Read up nicely written answers on IDENTITY strategy here

A: You defined id as an Integer field in your model class. Try to pass the value in the json as an Integer, not as a String.
{
    "id": 1,
    "uname": "abc",
    "upass": "abc"
}


text:
Q: build json object in javascript to post to php I have a group of radio buttons in a form, I need to pass the values of the selected radion buttons to a php script. So I need to build a json object to post.
I tried with this code, but I'm not sure. Please could anyone help me.
result = [];
for (i=0; i<document.getElementsByTagName('input').length; i++) {
    if (document.getElementsByTagName('input').item(i).checked) {
        s = document.getElementsByTagName('input').item(i).name;
        r = document.getElementsByTagName('input').item(i).value;
        result.push({id:s, va:r});
}

A: If the name values are unique, just build a string like so:
var result = '', inputs = document.getElementsByTagName('input');

for ( var i = inputs.length; i--; ) {
    if ( inputs[i].checked ) {
        result+= ( inputs[i].name + '=' + inputs[i].value + '&' );
    }
}

Live demo: http://jsfiddle.net/TTvkb/
Then just send the string in your ajax request.

A: Using jquery, the following is another way to do it:
var postData = {}, inputs = document.getElementsByTagName('input');

for ( var i = inputs.length; i--; ) {
    if ( inputs[i].checked ) {
        postData[inputs[i].name] = inputs[i].value;
    }
}

$.post('/post.php', postData, function(retData){
  // handle response
});


text:
Q: Запрос sql с применением индексов Дана таблица подразделений с древовидной связью Id <- Parent_Id.
S
ET NOCOUNT ON
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [Departs]
(
  [Id]        Int           NOT NULL IDENTITY(1,1),
  [Parent_Id] Int               NULL REFERENCES [Departs] ([Id]),
  [Name]      NVarChar(100) NOT NULL,
  PRIMARY KEY CLUSTERED([Id])
)
GO

DECLARE
  @WithOutDepart_Id Int = ...

-- Выдать все подразделения, кроме подразделения @WithOutDepart_Id и кроме всех его детей и внуков
...
SELECT D.*
FROM [Departs] D
...

Дан параметр – идентификатор некоторого подразделения. Надо выдать все подразделения, исключив из выборки указанное в параметре, а также исключив всех его детей и внуков.
Может стоит добавить индексы?

A: Может вам просто сделать выборку всех id у кого родитель не тот которого стоит исключить.
Если у вас у родителя только один уровень потомков, вам подойдёт простой запрос.
   SELECT
      id
    FROM
      [Departs]
    where parent_id != @WithOutDepart_Id
      CONNECT BY Prior id = parent_id
      start with id = :id


text:
Q: LWJGL Applet Conversion Walkthrough needed I have tried converting my LWJGL game to an applet but It can't load images, when I delete the code for the images it throws a null pointer exception, so Could SOmeone give me a walkthrough on how to Convert this code to an applet:
package com.kgt.platform.name;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import kuusisto.tinysound.Sound;
import kuusisto.tinysound.Music;
import kuusisto.tinysound.TinySound;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
import static org.lwjgl.opengl.GL11.*;

public class Game {

public static Player player;
public static Enemy enemy;
public static ExitButton exitbutton;
public static MenuButton menubutton;
public static ArrayList<Coin> coinlist;
public static ArrayList<Bullet> bulletlist;
public static ArrayList<Bullet2> bulletlist2;
public static ArrayList<Platform> platformlist;
public static ArrayList<OneWayPlatform> onewayplatformlist;
public static int score;
public static boolean p1on;
public static boolean p2on;
static State state = State.GAME;
public int curlvl = 1;
private static Texture logo;
private static Texture pause;

public enum State {
    PAUSE, GAME, MAIN_MENU, INTRO;
}

public static void init() {
    try {
        // load texture from PNG file
        logo = TextureLoader.getTexture("PNG",       ResourceLoader.getResourceAsStream("res/logo.png"));
        System.out.println("Texture 'logo' Loaded. Format: PNG");

        pause = TextureLoader.getTexture("PNG",     ResourceLoader.getResourceAsStream("res/paused.png"));
        System.out.println("Texture 'pause' Loaded. Format: PNG");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public static void logo() {
    Color.white.bind();
    logo.bind(); // or GL11.glBind(texture.getTextureID());

    GL11.glBegin(GL11.GL_QUADS);
        GL11.glTexCoord2f(0,0);
        GL11.glVertex2f(192,468);
        GL11.glTexCoord2f(1,0);
        GL11.glVertex2f(192+logo.getTextureWidth(),468);
        GL11.glTexCoord2f(1,1);
        GL11.glVertex2f(192+logo.getTextureWidth(),468-    logo.getTextureHeight());
        GL11.glTexCoord2f(0,1);
        GL11.glVertex2f(192,468-logo.getTextureHeight());
    GL11.glEnd();
}

public static void pause() {
    Color.white.bind();
    pause.bind(); // or GL11.glBind(texture.getTextureID());

    GL11.glBegin(GL11.GL_QUADS);
        GL11.glTexCoord2f(0,0);
        GL11.glVertex2f(256,440);
        GL11.glTexCoord2f(1,0);
        GL11.glVertex2f(256+pause.getTextureWidth(),440);
        GL11.glTexCoord2f(1,1);
        GL11.glVertex2f(256+pause.getTextureWidth(),440-    pause.getTextureHeight());
        GL11.glTexCoord2f(0,1);
        GL11.glVertex2f(256,440-pause.getTextureHeight());
    GL11.glEnd();
}

public static void main(String[] args) throws Exception
{
    System.setProperty("org.lwjgl.librarypath", new  File("natives").getAbsolutePath());
    System.out.println("Native Path: " + System.getProperty("org.lwjgl.librarypath"));
    Display.setDisplayMode(new DisplayMode(640, 480));
    Display.create();
    init();

    score = 0;

    player = new Player();

    exitbutton = new ExitButton(320, 61);
    menubutton = new MenuButton(320, 95);

    enemy = new Enemy();
    coinlist = new ArrayList<Coin>(0);
    bulletlist = new ArrayList<Bullet>(0);
    bulletlist2 = new ArrayList<Bullet2>(0);
    platformlist = new ArrayList<Platform>(0);
    onewayplatformlist = new ArrayList<OneWayPlatform>(0);
    Level1();

    while(!Display.isCloseRequested())
    {
        setCamera();
        drawBackground1();
        for(Coin c: coinlist) c.draw();
        for(Bullet b: bulletlist) b.draw();
        for(Bullet2 b: bulletlist2) b.draw();
        for(Platform b: platformlist) b.draw();
        for(OneWayPlatform b: onewayplatformlist) b.draw();
        enemy.draw();
        player.draw();

        states();
        stateinput();
        exitbutton.draw();
        menubutton.draw();
        Display.update();
        Display.sync(60);
    }

    Display.destroy();
}

public static void stopsound(){
    TinySound.shutdown();
}

public static void states(){
    switch (state) {
    case INTRO:
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
        glColor3f(1.0f, 0.0f, 0.0f);
        glRectf(0, 0, 640, 480);
        break;
    case GAME:
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
        break;
    case MAIN_MENU:
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
        glColor3f(0.0f, 0.0f, 1.0f);
        glRectf(0, 0, 640, 480);
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, logo.getTextureID());
        logo();
        break;
    case PAUSE:
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
        glEnable(GL_COLOR_ARRAY);
        glBegin(GL_QUADS);

        glColor4d(0.5f, 0.5f, 0.5, 0.7);

        glVertex2d(224, 40);
        glVertex2d(416, 40);

        glColor4d(0.7f, 0.7f, 0.7, 0.7);
        glVertex2d(416, 440);
        glVertex2d(224, 440);

        glEnd();
        glDisable(GL_COLOR_ARRAY);

        glColor3f(0f, 0f, 0f);
        glRectf(224, 40, 226, 440);
        glRectf(416, 40, 414, 440);
        glRectf(224, 40, 416, 42);
        glRectf(224, 438, 416, 440);
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, pause.getTextureID());
        pause();

        break;
    }
}

public static void stateinput(){

    while (Keyboard.next()) {
        if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
            if(state == State.GAME)
                state = State.PAUSE;
            else if(state == State.PAUSE)
                state = State.GAME;
        }
    }

}
public static void jumpsound(){

    TinySound.init();
    Sound jump = TinySound.loadSound("/sound/Jump6.wav");
    jump.play();

}

public static void shootsound(){

    TinySound.init();
    Sound shoot = TinySound.loadSound("/sound/Shoot1.wav");
    shoot.play();
}

public static void selectsound(){
    TinySound.init();
    Sound select = TinySound.loadSound("/sound/select.wav");
    select.play();
}

public static void hurtsound(){
    TinySound.init();
    Sound hurt = TinySound.loadSound("/sound/Hurt1.wav");
    hurt.play();
}

public static void music(int track){

    TinySound.init();
    Music ocean = TinySound.loadMusic("/music/ocean.wav");
    Music menu1 = TinySound.loadMusic("/music/menu1.wav");

    if(track == 1){
    ocean.play(true);
    }
    else if (track == 0){
        menu1.play(true);
    }
}

public static void setCamera(){
    GL11.glEnable(GL11.GL_TEXTURE_2D);
    GL11.glEnable(GL_COLOR_ARRAY);
    GL11.glShadeModel(GL11.GL_SMOOTH);
    GL11.glDisable(GL11.GL_DEPTH_TEST);
    GL11.glDisable(GL11.GL_LIGHTING);

    GL11.glEnable( GL11.GL_TEXTURE );
    GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    GL11.glClearDepth(1);

    GL11.glEnable(GL11.GL_BLEND);
    GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);

    GL11.glViewport(0,0,640,480);
    GL11.glMatrixMode(GL11.GL_MODELVIEW);

    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity();
    GL11.glOrtho(0, 640, 0, 480, 1, -1);
    GL11.glMatrixMode(GL11.GL_MODELVIEW);
}

public static void Level1(){
    Game.platformlist.add(new Platform(16, 120));
    Game.platformlist.add(new Platform(48, 120));
    Game.platformlist.add(new Platform(624, 120));
    Game.platformlist.add(new Platform(592, 120));
    Game.onewayplatformlist.add(new OneWayPlatform(128, 200));
    Game.onewayplatformlist.add(new OneWayPlatform(160, 200));
    music(1);
}

public static void drawBackground1(){
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
    glBegin(GL_QUADS);

    glColor3d(0.4, 0.5, 0.7);
    glVertex2d(640, 480);
    glVertex2d(0, 480);

    glColor3d(0.7, 0.8, 0.9);
    glVertex2d(0, 0);
    glVertex2d(640, 0);
    glEnd();

    glBegin(GL_QUADS);

    glColor3d(0.3, 0.2, 0.1);
    glVertex2d(0, 0);
    glVertex2d(640, 0);

    glColor3d(0.5, 0.2, 0.1);
    glVertex2d(640, 32);
    glVertex2d(0, 32);
    glEnd();

    glBegin(GL_QUADS);

    glColor3d(0.5, 0.2, 0.1);
    glVertex2d(0, 32);
    glVertex2d(640, 32);

    glColor3d(0.2, 0.5, 0.1);
    glVertex2d(640, 47);
    glVertex2d(0, 47);

    glColor3d(1, 1, 1);

    glEnd();
}
}


text:
Q: AdMob Ads not showing but test ads show (iOS) It's been more than a month since I've created the ad units, however I've only been using the test ads when I ran on XCode. Recently, I've changed the test ads to real ads and submitted it to the App Store. When I downloaded the app, the real ads weren't showing. I'm planning to give it a couple hours as I heard that may be the case, however it seems like the app isn't requesting any real ads (shown from the admob app overview). However my app was able to successfully request the test ads.
Update: I've also heard that I needed to update my payment info, so I have done that. How should I be able to check whether my app is requesting ads properly now?

A: *

*Ask the Admob support,

*Sometimes there is a several hours lag before real ads start to show, after you publish your app,

*Double check that all of your app/banner IDs, GoogleService-Info.plist, etc. are configured right.


text:
Q: NullPointerException On EntitytDamageByEntity Event Bukkit I am trying to make a player not able to be damaged if they have right clicked a nether star. Then they will be not able to take damaged for as long as the int damagetime. Here is my code:
public class MineSurvival extends JavaPlugin implements Listener{

private HashMap<String, Long> lastUsage = new HashMap<String, Long>();
private HashMap<String, Integer> daysMap = new HashMap<>();
private HashMap<String, Long> damage = new HashMap<>();
private HashMap<String, Boolean> killable = new HashMap<>();
private final int cdtime = 10;
private final int damagetime = 10;
@Override
public void onEnable(){
getServer().getPluginManager().registerEvents(this, this);
getConfig();
for(String str:getConfig().getKeys(true)) {
int p = getConfig().getInt(str);
daysMap.put(str, p);
}
saveConfig();
}

@Override
public void onDisable(){
for(Entry<String, Integer> pointstostore: daysMap.entrySet()) {
getConfig().set(pointstostore.getKey(), pointstostore.getValue());
}
saveConfig();
}

public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
    final Player player = (Player) sender;
    Integer days = this.daysMap.get(player.getName());
    PermissionUser user = PermissionsEx.getUser(player);
if(commandLabel.equalsIgnoreCase("days")){
    if(player.hasPermission("minesurvival.days") || player.hasPermission("minesurvival.hcdays")){
    long lastUsed = 0;
    if(lastUsage.containsKey(player.getName())){
        lastUsed = lastUsage.get(player.getName());
    }

    long cdmillis = System.currentTimeMillis() + (cdtime * 1000);;

    if(System.currentTimeMillis()-lastUsed>=cdmillis){
        if(daysMap.containsKey(player.getName())){
            days++;
            this.daysMap.put(player.getName(), days);
            player.sendMessage(ChatColor.RED + "You have stayed alive for " + ChatColor.BLUE + days + ChatColor.RED + " days!");
            getServer().dispatchCommand(getServer().getConsoleSender(), "pex user " + player.getName() + " prefix &c[&b" + days + "&c]");
        lastUsage.put(player.getName(), System.currentTimeMillis());

        }
        else if(daysMap.containsKey(player.getName())){
            if(days==10 || days==99){
            days++;
            this.daysMap.put(player.getName(), days);
            Bukkit.broadcastMessage(ChatColor.GREEN +(player.getDisplayName() + ChatColor.RED + "Has survived" + ChatColor.BLUE + days + ChatColor.RED + "!"));
            lastUsage.put(player.getName(), System.currentTimeMillis());
        }
        }
        else if(!daysMap.containsKey(player.getName())){
            daysMap.put(player.getName(), 0);
        }
    }
    else{
        int timeLeft = (int) (cdtime-((System.currentTimeMillis()-lastUsed)/1000));
        player.sendMessage(ChatColor.RED + "It hasn't been a day yet " + ChatColor.GREEN + timeLeft + ChatColor.RED + " seconds left");
        return true;
    }

}
    else if(!player.hasPermission("minesurvival.days")){
        player.sendMessage(ChatColor.RED + "No permission");
    }
}
if(commandLabel.equalsIgnoreCase("hardcore")){
    if(!player.hasPermission("minesurvival.normal")){
        user.addPermission("minesurvival.hardcore");
    player.sendMessage(ChatColor.RED + "You are now playing hardcore");
}
    else if(player.hasPermission("minesurvival.normal")){
        player.sendMessage(ChatColor.RED + "You cannot switch from normal to hardcore!");
    }
}
if(commandLabel.equalsIgnoreCase("normal")){
    if(!player.hasPermission("minesurvival.hardcore")){
        user.addPermission("minesurvival.normal");
    player.sendMessage(ChatColor.RED + "You are now playing normal");
    }
    else if(player.hasPermission("minesurvival.hardcore")){
        player.sendMessage(ChatColor.RED + "You cannot switch from hardcore to normal!");
    }
}
if(commandLabel.equalsIgnoreCase("timeleft")){
    if(damage.containsKey(player.getName())){
            damage.put(player.getName(), System.currentTimeMillis());

            }
        }
return false;

}
@EventHandler
public void onPlayerDeathEvent(PlayerDeathEvent event){
    Player player = (Player) event.getEntity();
    PermissionUser user = PermissionsEx.getUser(player);
    if(player instanceof Player){
        Integer daysdeath = this.daysMap.get(player.getName());
        if(player.hasPermission("minesurvival.normal")){
            Integer death = (int) Math.round((daysdeath-((daysdeath*20)/100)));
            this.daysMap.put(player.getName(), death);
            user.removePermission("minesurvival.normal");
            player.sendMessage(ChatColor.RED + "Because you were playing normal, your days have been reset to " + ChatColor.GREEN + death);
        }
        else if(player.hasPermission("minesurvival.hardcore")){
            Integer hcdeath = (int) Math.round((daysdeath-((daysdeath*80)/100)));
            this.daysMap.put(player.getName(), hcdeath);
            user.removePermission("minesurvival.hardcore");
            player.sendMessage(ChatColor.RED + "Because you were playing hardcore, your days have been reset to " + ChatColor.GREEN + hcdeath);
        }
        else{
            return;
        }
    }
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
    ItemStack is = event.getItem();
    Player player = event.getPlayer();
    long dmgmillis = System.currentTimeMillis() + (damagetime * 1000);
    long DamageUsed = 0;
    if (is.getType() == Material.NETHER_STAR) {
        player.sendMessage("4");
        damage.put(player.getName(), (long) 1);
        player.getInventory().remove(Material.NETHER_STAR);
        player.sendMessage(ChatColor.GREEN + "You have activated your 10 second powerup!");
        DamageUsed = damage.get(player.getName());
        if(System.currentTimeMillis()-DamageUsed>=dmgmillis){
            player.sendMessage("3");
            killable.put(player.getName(), true);
        }
}
    else{
        return;
    }
}
@EventHandler
public void onPlayerDamage(EntityDamageByEntityEvent event){
    Entity damagedE = event.getEntity();
    Entity damagerE = event.getDamager();
    if(!(damagedE instanceof Player)) return;
    if(!(damagerE instanceof Player)) return;

    Player damaged = (Player) event.getEntity();
    if(damaged instanceof Player){
        damaged.sendMessage("2");
    if(killable.get(damaged.getName())){
        damaged.sendMessage("1");
        event.setCancelled(true);
    }
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event){
    Player player = event.getPlayer();
    killable.put(player.getName(), false);
}
}

Here is the error that I get:
And here is the error:
http://hastebin.com/ujawequtik.avrasm

A: The problem is on line 172 in your code:
at com.minetendo.minesurvival.MineSurvival.onPlayerDamage(MineSurvival.java:172)

which seems like it's this line in your code:
if(killable.get(damaged.getName())){

This is because your killable HashMap does not contain the name of the damaged player. To fix this, you should check if killable.contains(damaged.getName())
So, your event should look something like this:
@EventHandler
public void onPlayerDamage(EntityDamageByEntityEvent event){
  Entity damagedE = event.getEntity();
  Entity damagerE = event.getDamager();
  if(!(damagedE instanceof Player)) return;
  if(!(damagerE instanceof Player)) return;

  Player damaged = (Player) event.getEntity();
  if(damaged instanceof Player){
    damaged.sendMessage("2");
    if(killable.contains(damaged.getName())){//check if killable contains the damaged player's name
      if(killable.get(damaged.getName())){
        damaged.sendMessage("1");
        event.setCancelled(true);
      }
    }
  }
}

A: On line 181 you should check for a null pointer:
if(killable.get(damaged.getName()) != null)

See e.g. this question for details why your version results in an exception.


text:
Q: Reading excel file using jQuery/JavaScript/AJAX Until now I was using epplus for excel file reading writing - standalone application.
Bt I've moved to web version, is it possible to read excel file or say 'to manipulate excel file jQuery/JavaScript/AJAX.

A: Yes, you can do this in similar fashion.

*

*Upload an excel File

*Read the uploaded file and return the data and bind a grid.

*Allow the user to modifiy the data

*Post the data back (or use ajax to post the data)

*Write the new data in a new excel File and Download it.

You can use the same EPPlus library or NPOI library to read/write.
Also you can use Excel DataReader to read the excel file.


text:
Q: selected value in p:selectOneMenu was lost Good day!
I'm using JSF 2.1 Primefaces 4.0 Glassfish 3.2.1
In my Form.xhtml, I have this code.
<h:form id="modDlgFormc">

          <h:panelGrid id="criteriapGrid" columns="1">
             <h:panelGrid id="critLabelId" columns="2">

                          <f:selectItem itemLabel="Select Field Name"
                            itemValue="" />
                                <f:selectItems value="#{Fame.fieldNameMap}" />

            <f:selectItem itemLabel="Select Operand" itemValue="" />
                 <f:selectItems value="#{Fame.operandMap}" />

                        </h:panelGrid>

             <h:panelGrid id="valueId" columns="2">
                  <c:if test="#{Fame.showValue == 'txt'}">
                       <h:outputLabel for="inputVal" value="Value : " style="font-weight: bolder"/>

                                <c:if test="#{Fame.operator == 'Is Between'}">
                                    <h:outputText value=""/>

                                </c:if>
                            </c:if>

                            <c:if test="#{Fame.showValue == 'cal'}">
                                <h:outputLabel for="fromDateId" value="From : " style="font-weight: bolder"/>

                                <c:if test="#{Fame.operator == 'Is Between'}">
                                    <h:outputLabel for="toDateId" value="To : " style="font-weight: bolder"/>

                                </c:if>
                            </c:if>

                            <c:if test="#{Fame.showValue == 'upload'}">
                                <h:outputText value=""/>

                            </c:if>
                        </h:panelGrid>

                        <h:panelGrid id="critBtnId" columns="4">

                        </h:panelGrid>

                    </h:panelGrid>

                        <h:panelGrid id="critDTable" columns="1">

                                    #{criteria.wsheetName}

                                    #{criteria.fieldName}

                                    #{criteria.operator}

                                    #{criteria.value}

                        </h:panelGrid>

            </h:form>

My Main code
@ManagedBean(name = "Fame")
@SessionScoped

private FameCriteriaDAOImpl fameCriteriaDAOImpl = new FameCriteriaDAOImpl();
private ArrayList<FameCriteriaBean> createdCriteria = new ArrayList();

public void saveCriteria() {
        fameCriteriaDAOImpl = new FameCriteriaDAOImpl();
        try {
            if (this.validate() == true) {
                //String wsheetId = fameManagementDP.getWsheetId(group_Id, workbookName);
                FameCriteriaBean bean = new FameCriteriaBean();
                bean.setWsheetId(this.worksheetId);
                bean.setFieldName(this.fieldName);
                bean.setOperator(this.operator);
                bean.setValue(this.value);

                String actionStr = "inserted";
                fameCriteriaDAOImpl.save(bean);
            }

        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
            error(converter.getConvertedError(sqlEx.getMessage()));
        } finally {
            this.initialize();
            this.initializeCreatedCriteria();
            this.resetCriteria();
        }
    }

My Bean code.
public class FameCriteriaBean {

private String wsheetName = "";
private String wsheetId = "";
private String fieldName = "";
private String operator = "";
private String value = "";

public FameCriteriaBean(){

}

/**
 * @return the fieldName
 */
public String getFieldName() {
    return fieldName;
}

/**
 * @param fieldName the fieldName to set
 */
public void setFieldName(String fieldName) {
    this.fieldName = fieldName;
}

/**
 * @return the operator
 */
public String getOperator() {
    return operator;
}

/**
 * @param operator the operator to set
 */
public void setOperator(String operator) {
    this.operator = operator;
}

/**
 * @return the value
 */
public String getValue() {
    return value;
}

/**
 * @param value the value to set
 */
public void setValue(String value) {
    this.value = value;
}

/**
 * @return the wsheetId
 */
public String getWsheetId() {
    return wsheetId;
}

/**
 * @param wsheetId the wsheetId to set
 */
public void setWsheetId(String wsheetId) {
    this.wsheetId = wsheetId;
}

/**
 * @return the wsheetName
 */
public String getWsheetName() {
    return wsheetName;
}

/**
 * @param wsheetName the wsheetName to set
 */
public void setWsheetName(String wsheetName) {
    this.wsheetName = wsheetName;
}

}

Below is the scenario.

*

*I choose a fieldName then the lists of operand was loaded. This is correct.

*I click the button ADD, then a p:message appear that there is no operand selected. This is correct.

*I had noticed that the fieldname value that I was selected when error appears was gone.
My question is how not to refresh the value of fieldNameId so that I can use it after an error is displayed in p:message.
I'm using SessionScoped for my java class because I'm using p:wizard in Form.xhtml.
Please help me to solve this.
Thank you and More Power!  :)

A: What I did is this.
Please see updated Main class
@ManagedBean(name = "Fame")
@SessionScoped

private FameCriteriaDAOImpl fameCriteriaDAOImpl = new FameCriteriaDAOImpl();
private ArrayList<FameCriteriaBean> createdCriteria = new ArrayList();

public void saveCriteria() {
        fameCriteriaDAOImpl = new FameCriteriaDAOImpl();
        if (!this.validate()) {
          return;
         }
               try {

                FameCriteriaBean bean = new FameCriteriaBean();
                bean.setWsheetId(this.worksheetId);
                bean.setFieldName(this.fieldName);
                bean.setOperator(this.operator);
                bean.setValue(this.value);

                String actionStr = "inserted";
                fameCriteriaDAOImpl.save(bean);

        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
            error(converter.getConvertedError(sqlEx.getMessage()));
        } finally {
            this.initialize();
            this.initializeCreatedCriteria();
            this.resetCriteria();
        }
    }


text:
Q: How to call android application from web browser I want to call android application on clicking of button on some website from mobile.
Suppose I am opening one url on android browser and I want to call my application on clicking on button provided by that site. How to do that??
Suppose we are using browser other than Chrome then is it allowing??

A: If you link to your application as "myapp://foo/bar", can't you use some sort of intent filter  to start your application.
I mean, if you press a youtube link in the browser it asks if you want to complete the action with the YouTube app or the browser.
I have seen similar examples regarding Google Maps links (which would open in either browser, google maps(?) or GeoBeagle).

A: Please take a look at the WebViewDemo. Javascript code in the web page can call into your Activity. As well as the other way around.

A: You cannot... if the site is being browsed in the default browser (Chrome).
If you already have an application that embeds the WebView, then you can do some bit of handling of - mouse clicks, window alerts, navigation etc. Otherwise, not!


text:
Q: Can't connect to Time Capsule in recovery mode (Big Sur) I made a big mistake and updated some Python packages with Homebrew on my 2015 MacBook Pro, MacOS 11.0.1. The updates caused many issues with my preferred IDE, PyCharm. Of course, I made a backup on my Time Capsule prior to updating with Homebrew. So, after being frustrated and getting nowhere with PyCharm, I decided to restore from my backup. I entered into recovery mode by holding CMD + R while restarting. When I went to restore from backup, I could not connect to my Time Capsule. The prompt stated, "There was a problem connecting to the server." Any ideas on how to get the MacBook to connect to the Time Capsule?

A: After over an hour on the phone with Apple, it was suggested I try to use Migration Assistant to restore from backup. That worked for me.
EDIT: While it did work, there was a major issue: While trying to run Python/Jupyter in PyCharm, I repeatedly get malware warnings that have to be manually suppressed, individually. I mean, every file associated with a Python package in the virtual environment seems to be identified as possible malware. I called Apple about the issue, but no one knew how to globally suppress the malware warnings. There are way too many files to manually suppress them all.
I found an alternative, create a new project in PyCharm, copy in Python/Jupyer files (not packages, but files I created), then add the packages needed to run everything.

A: I unfortunately have no real solution but as I recently also installed Big Sur on a MacBook Pro Late 2013 and wanted to revert back to Catalina. I got the exact same error message "There was a problem connecting to the server." when trying to connect to the Time Capsule through recovery (CMD+R mode) - (also shown by me as NAOpensession failed for afp:// ... - Error 22) in the log window when seeing extra details.
I later made a copy of the sparsebundle (from the Time Capsule) to an external hdd and could make it further through the recovery screens. (I didn't finalize the steps as I later read Big Sur may brick 2013 MacBook and didn't want to take any more risks - but it looks like I could have made the complete recovery through the hdd with the same backup copied from the TM). This may be a potential temporary alternative
I also did further testing my on wife's laptop (still on Catalina) and she received the same error (There was a problem connecting to the server...).
I suspect the bug may not be new to Big Sur.
I also made a hard factory reset of the Time Capsule and made two new backups that are working and are verified perfectly on Big Sur itself, but once in recovery mode it fails to connect to it.
Regards

A: "NAOpensession failed for afp:// ... - Error 22" is also the case for Big Sur 11.1.
I needed to go down to the shipped os for this machine (10.10) and then back to catalina again to gain access to the backup. From catalina I could sucessfully recover the Timecapsule Backup.
My recommendation is to have a big usb3 thumbdrive at hand and format it as startup drive, that can spare a bit of this trouble. https://support.apple.com/de-de/HT201372
Sadly one can not choose which specific version of Mac OS the internet recovery loads, only the one from hardware production time and the last installed, which is Big Sur when you have the problem.
The Problem itself is unrelated to Python or Homebrew, i needed a backup after the Mac Server app forgot it´s settings.


text:
Q: with jquery hide div when mouseout HTML

Menu-1

Menu-2

Menu-3

Menu-4

    Click1
    Click2
    Click3
    Click4

CSS
.wrapper {
    position:relative;
}
.menu {
    width:500px;
    height:300px;
    background-color:#f00;
    position:absolute;
    top:50px;
    display:none;
}

JQUERY
$('.wrapper').children('a').on('click',function(){
  $('.wrapper').children('div').hide().eq($(this).index()-4).fadeIn(400);
});

JSfiddle
When click any a tag in wrapper div, show related div. But I can't hide div when mouseout on the div. How can I do it?

A: Try this
$('.menu').on('mouseout',function(){
$(this).hide();
});

DEMO


text:
Q: OGM/ORM for OrientDB I am looking for a OGM for OrientDb - something that will allow me to persist my domain model (POJO) as vertices and edges declaratively (using annotations perhaps). I stumbled upon Ferma which seems to have the annotations support but I can't find many examples to go on. Specifically, how do I create/initialise a Ferma FramedGraph from an OrientGraphFactory?
This lack of enough samples/documentation also makes me doubt the support for Ferma. I am new to graph databases. Am I on the right track? Are OGM/ORM not the right way to go for graph databases or am I just looking at the wrong OGM? Coming from the RDBM world I am looking for a stack like: OrientDb -> TinkerPop3 Frames -> anOGM where anOGM is an actively maintained fast(preferably compile time code generation) OGM/ORM with wide community support. Something like neo4j-ogm.
Yes, JPA has spoiled me!!.

A: Currently, the most active OGM for TinkerPop 3.x that I know of for Java is the recently announced gremlin-ogm. You also have the option of building a Gremlin DSL which has a similar goal of mapping the domain of the graph to the query language. You can read more about that here in this blog post as well.


text:
Q: Problem with statsmodels ARIMA out-of-sample forecast I am developing an ARIMA model to forecast oil exports. Please see the code below.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.stattools import adfuller
import stats_can

# Get and preprocess data
df = stats_can.sc.vectors_to_df("v1001826820", periods=200)
df.rename(columns={"v1001826820": "oil_exports"}, inplace=True)
df.index.rename('date', inplace=True)
df["log_oil_exports"] = df.apply(np.log)

# Plot logarithm of oil exports
df.log_oil_exports.plot.line()

# Run ADF test on levels
adfuller(df.log_oil_exports, regression='ct', autolag='AIC')

# Plot first difference of log oil exports
df.log_oil_exports.diff().dropna().plot.line()

# Run ADF test on first difference
adfuller(df.log_oil_exports.diff().dropna(), regression='nc', autolag='AIC')

# Fit ARIMA(1,1,2) model
oil_export_model = ARIMA(endog=df.log_oil_exports, order=(1, 1, 2), trend='t')
oil_export_model_fit = oil_export_model.fit()
oil_export_model_fit.summary()

# Print last 5 observations from the training data
df.log_oil_exports.tail()

# Print last 5 fitted values
oil_export_model_fit.predict()[-5:]

# Make an out-of-sample forecast
oil_export_model_fit.forecast()

The last five observations from the training dataset are:
2021-04-01    8.902456
2021-05-01    8.896834
2021-06-01    9.132130
2021-07-01    9.101674
2021-08-01    9.182167
Name: log_oil_exports, dtype: float64

The last 5 fitted values are:
2021-04-01    8.957241
2021-05-01    8.890469
2021-06-01    8.925859
2021-07-01    9.113322
2021-08-01    9.098928
Freq: MS, dtype: float64

The first out-of-sample prediction is
2021-09-01    7.708736
Freq: MS, dtype: float64

To say the truth, I cannot understand how the first out-of-sample prediction is 7.7087 when the preceding five observed and fitted values are all close to 9. Am I missing something obvious here? I would appreciate any help/suggestions.


text:
Q: add field to woocommerce product page I have a question.
I'm new with wordpress and especially with woocommerce.
Its a website I am doing for a friend of mine and now I am just into doing the best of it.
I wanna add an input (date) on the product page so that the customer can select an amount of products date and then proceed to cart.
On cart, there's a table with product bought so I want to display the "input date" there.
and when he purchase it will be updated in to order's DB.
Is there a way to achieve it ?


text:
Q: React Native Date Range import React, {useState} from "react";
import { StyleSheet, View, Text } from "react-native";
import { globalStyles } from "../styles/global";
import {Calendar, CalendarList, Agenda} from 'react-native-calendars';
import {LocaleConfig} from 'react-native-calendars';
import  moment  from  "moment";
import DateRangePicker from "react-native-daterange-picker";

export default function About(){
    const [endDate, setendDate] = useState(null)
    const [startDate, setstartDate] = useState(null)
    const [displayedDate, setdisplayedDate] = useState(moment())

    state = {
        endDate: null,
        startDate: null,
        displayedDate: moment()
    };

    const handleSubmit = (props) => {

        console.log(props);
        setendDate(props.endDate);
        setstartDate(props.startDate);
        setdisplayedDate(props.displayedDate);
        // console.log(props.startDate);
        // console.log(props.displayedDate);
    }

    return(
        <View style={globalStyles.container}>

        <DateRangePicker
          onChange={ handleSubmit }
          endDate={endDate}
          startDate={startDate}
          displayedDate={displayedDate}
          range>
          <Text>Click me!</Text>
          </DateRangePicker>

        </View>
    )
}

1.not able to select date range.
2. undefined is not an object (evaluating displayedDate.format)
3. Using function component but most of the solutions are available with class component

A: You can call handleSubmit as follows
onChang={() => handleSubmit()}
And props param is needless in function prototype
const handleSubmit = (props) => {}
Because props is already declared and you don't need to set it as parameter.
If you want to use it as parameter then you should change like this
onChange={() => handleSubmit(props)}
Hope this helps you.

A: You can change your  handleSubmit() function like this
const handleSubmit = (props) => {
  if (props.startDate != undefined) {
    setStartDate(props.startDate);
  }

  if (props.displayedDate != undefined) {
    setDisplayedDate(props.displayedDate);
  }

  if (props.endDate != undefined) {
    setEndDate(props.endDate);
  }
 }

Source: issues#15


text:
Q: segmentation fault with strtok #include<stdio.h>
#include<string.h>
int main(){
        char path[] = "/fs/lost+found";
        char* temp;
        temp =  strtok(path,"lost+found");
        while(temp != NULL){
                printf("\n %s \n",temp);
                temp = strtok(path,"lost+found");
        }
        return 0;
}

I wanted to extract the string lost+found. The above program goes into an infinite loop and prints the "/" that is before the delimiter "lost+found"
[root@rs]# ./a.out
Segmentation fault

A: You committed two mistakes (as you can easily discover from here).

*

*strtok() takes as second argument a delimiter. In your case this delimiter is not lost+found but reasonably /.

*inside the while block first parameter of the strtok function has to be NULL to make the function continue scanning where a previous successful call to the function ended.
Finally, you have to use strcmp() to discover if processed token is the string you're looking for.
So:
 ...
while (temp != NULL) {
    if (strcmp("lost+found", temp) == 0)
        printf ("%s\n", temp); // found

    temp = strtok (NULL, "/");
  }
 ... // not found

A: from man 3 strtok:

char *strtok(char *str, const char *delim);
  The strtok() function parses a string into a sequence of tokens. On
  the first  call to strtok() the string to be parsed should be
  specified in str. In each subsequent call that should parse the same
  string, str should be NULL.

Fix:
#include<stdio.h>
#include<string.h>

int main(){
    char path[] = "/fs/lost+found";
    char* temp;
    temp =  strtok(path,"/");
                     // ^^^  different delimiter
    do {
        printf("%s\n", temp);
        temp = strtok(NULL, "/");
                   // ^^^^ each subsequent call to strtok with NULL as 1st argument
    } while (temp != NULL);
    return 0;
}

It will print out the "fs" and "lost+found" tokens. You can add some checking whether temp has currently the value you're looking for and then you can store in other variable.

A: The delim argument specifies a set of characters that delimit the tokens in the parsed string.
The 2nd argument that you have provided for strtok provides set of delimiters for tokenizing the given string, not for extracting a particular string
Use strstr
temp = strstr(path,"lost+found");

This returns a pointer to the substring you are searching for

A: You cannot change a string literal, and strtok() will modify the string it's working on.


text:
Q: Windows Search - List Indexed Locations by Number of Items? Beyond looking them up manually, is there any way to get the number of files in each folder that Windows search is indexing? I've noticed that the searching in Windows 7 is a tad slower that I would like it to be. I've tried to limit the search locations to the bare essentials but it still says it has over 30k files indexed, so I'm guessing there's still some low-hanging fruit that I can get rid of.

A: Gonna answer my own question. A way to do this is to get esedbviewer, open the index file, export the contents to CSV, and then get the count of items for each location by opening the CSV in Excel and creating a pivot table.


text:
Q: selenium webdriver run time error on eclips Exception in thread "main" java.lang.IllegalStateException: The driver executable does not exist: E:\chromedriver.exe
    at com.google.common.base.Preconditions.checkState(Preconditions.java:199)
    at org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:121)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:116)
    at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
    at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:296)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:120)
    at MyPackage1.MyClass1.main(MyClass1.java:10)

A: Download and install Google Chrome (if you don't have this browser installed).
Download Chromedriver executable and extract it.
Set system property in your code (before you use ChromeDriver):
System.setProperty("webdriver.chrome.driver", "path to the ChromeDriver file");

A: Either you've added wrong path for your chrome driver executable or you don't have any. Download it from here and run the code with below snippets for path to executable.
System.setProperty("webdriver.chrome.driver", "path to the executable driver file");


text:
Q: Can I use iPadian as an iPad emulator for website development? I'm not sure if it's accurate or not.
For iPhone/iPad, I don't want to buy one and I don't feel like switching to Mac either. iPhone/iPad emulator is a big problem for me.

A: Wildly old thread, but having the same issue myself.
I'm trying Ipadian but not really liking the results.
Probably better, I would recommend getting virtualbox and installing MacOSX, then open the contents of XCODE directory and there is an iOS emulator. That should work very well/accurate.
Also there is browserstack, but that costs money.


text:
Q: Installshield LE for VS2015 Professional after installing VS2015 Community I have installed Visual Studio 2015 Professional after having worked with Visual Studio 2015 Community for a few months.
The problem is that I cannot create a new Installshield Limited Edition project. I thought the issue was that I had both versions installed at the same time, but after removing VS Community, the issue still remains.
As you see in the screenshot below, the project type is located under a 1033 branch, which doesn't seem right to me. Creating a project only redirects me to the default HTML page, which tells me how to register and create a project.
I have uninstalled both versions and installed a fresh copy of VS2015 Professional from scratch. I didn't do any manual removal of certain files or caches, so maybe this could have something to do with it?
Anyone has experience with this? Perhaps any solution?


text:
Q: Copy elements in a doubly linked list to a singly linked list I have a custom doubly linked list and I want to use an enhanced for loop to print elements in O(n) time. So I copied all the elements to a singly linked list but that takes O(n*2) time. Is there a more efficient way to copy elements?

A: You don't need to make a copy to print elements. Iteration of a linked list (doubly-linked or not) should be O(n):
List myList = createMyDoublyLinkedList();
for (Object item : myList) {
    System.out.prointln(item);
}

To better understand your question you would need to post the code you have.


text:
Q: Как увеличить шрифт во всем документе Open-Office? Есть документ Open-Office, в котором слишком мелкий шрифт. Надо его увеличить пропорционально для всего документа (то есть для текста, для заголовков и т.д.). Например, сам текст сейчас размера 5, а надо, чтобы стал размера 7. Заголовки сейчас размера 7, а надо, чтобы стали размера 9. И так далее. Но если выделить весь текст через ctrl+A, то поле кегля становится недоступно. Однако, если выделить отдельный абзац, то поле кегля становится доступно и размер текста можно увеличить.
Как в документе Open-Office увеличить пропорционально для всего документа увеличить текст? Не делать же все это вручную, по отдельным абзацам.

A: По абзацам точно не стоит, но вы можете настроить стили, насколько я помню. Стили заголовков, текста и так далее. Посмотрите какими стилями набраны заголовки и сам текст - и поменяйте кегль в стиле на тот который Вас устраивает.

A: А если стили не настроены, то выделить всё, а затем Формат->Текст->Увеличить кегль, или же Ctrl+].
Проверено для LibreOffice-5.4.