text:
Q: Selenium bug: Message: invalid argument: 'url' must be a string I have some simple selenium scraping code that returns all the search results, but when I run the for loop, it displays an error: Message: invalid argument: 'url' must be a string
(Session info: chrome=93.0.4577.82)
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chrome_path = r'C:\Windows\chromedriver.exe'
driver = webdriver.Chrome(chrome_path)
driver.get("https://www.youtube.com/results?search_query=python+course")
user_data = driver.find_elements_by_xpath('//*[@id="video-title"]')
links = []
for i in user_data:
    links.append(i.get_attribute('href'))
print(links)

wait = WebDriverWait(driver, 10)
for x in links:
    driver.get(x)
    v_id = x.strip('https://www.youtube.com/watch?v=')
    #//*[@id="video-title"]/yt-formatted-string
    v_title = wait.until(EC.presence_of_element_located(
                           (By.CSS_SELECTOR,"h1.title yt-formatted-string"))).text

I would like to ask for some help. How to avoid this error?
Thanks.

A: You are trying to get the "user_data"
user_data = driver.find_elements_by_xpath('//*[@id="video-title"]')

immediately after opening the YouTube url
driver.get("https://www.youtube.com/results?search_query=python+course")

This causes "user_data" to be an empty list.
This is why when you trying to iterate over "links" with
for x in links:

to iterate over single "x" value of "NoneType" object, not a string.
To fix this you should add a wait/ delay between
driver.get("https://www.youtube.com/results?search_query=python+course")

and
user_data = driver.find_elements_by_xpath('//*[@id="video-title"]')

The simplest way to do that is to add a delay there, like this:
driver.get("https://www.youtube.com/results?search_query=python+course")
time.sleep(8)
user_data = driver.find_elements_by_xpath('//*[@id="video-title"]')

However the recommended approach is to use explicit wait implemented by expected conditions, like this:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chrome_path = r'C:\Windows\chromedriver.exe'
driver = webdriver.Chrome(chrome_path)
wait = WebDriverWait(driver, 20)
driver.get("https://www.youtube.com/results?search_query=python+course")
wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id="video-title"]")))
#adding some more pause to make all the videos loaded
time.sleep(0.5)
user_data = driver.find_elements_by_xpath('//*[@id="video-title"]')
links = []
for i in user_data:
    links.append(i.get_attribute('href'))
print(links)

for x in links:
    driver.get(x)
    v_id = x.strip('https://www.youtube.com/watch?v=')
    #//*[@id="video-title"]/yt-formatted-string
    v_title = wait.until(EC.visibility_of_element_located(
                           (By.CSS_SELECTOR,"h1.title yt-formatted-string"))).text

Also, you should use visibility_of_element_located instead of presence_of_element_located since presence_of_element_located waits only for element initial presence, element state while it's content like texts etc. may still not be ready.


text:
Q: Communication between computers through external networks I'm trying to build an application with my Raspberry Pi 3B that get some data from connected sensors. Once I got the data, I'd like to send them to a fix computer that is on an external network via a script in Python and the socket library. Here is my code:
On server side (the external computer):
import socket

ip = (([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")]
or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]])
+ ["no IP found"])[0]
print("IP ordinateur local: {}".format(ip))

port = 9999
print("Port d'entrée des données sur l'ordinateur local: {}".format(port))

address = ("",port)

serveur = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serveur.bind(address)

serveur.listen(5)
print("En attente de nouvelles connexions")

client, infosClient = serveur.accept()

print("Nouvelle connexion client établie")
print("Infos client: IP = {}, port = {}".format(infosClient[0],infosClient[1]))

msg = "Serveur: connexion acceptee"
client.send(msg.encode())

flag = False
try:
    while True:
        if flag == False:
            msgRecu = client.recv(1024)
            print("Message reçu: {}".format(msgRecu.decode()))
            msg = input("Entrez une réponse à envoyer \n")
            client.send(msg.encode())
            print("Réponse envoyée")
            print("En attente de la commande d'arrêt")
            flag = True
except KeyboardInterrupt:
    msg = "Le serveur a enclenché la commande d'arret Ctrl+C"
    client.send(msg.encode())
finally:
    print("Fermeture de la connexion")
    client.close()
    serveur.close()

On client side (the RPi):
import socket

ipLocal = (([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")]
or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]])
+ ["no IP found"])[0]

client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

ipServeur = input("Entrez l'adresse IP du serveur \n")
portServeur = input("Entrez le port du serveur \n")

try:
    client.connect((ipServeur,int(portServeur)))
except KeyboardInterrupt:
    del client

print("Connexion établie")

msgRecu = client.recv(1024)
print(msgRecu.decode())

msg = input("Entrez un message à envoyer \n")

client.send(msg.encode())
print("Message envoyé")

answer = client.recv(1024)

print("Réponse serveur: {}".format(answer.decode()))

print("Fermeture de la connexion")
client.close()

Unfortunately when I enter the IP address that the server script gives me via the first command (ip = ...), the client script tells me I'm connected but the server one is still waiting for a connection.
I think it could possibly come from the fact that the ip address I get from the command is a local one, but I don't know how to get the external, especially since the network of the server is well protected.
A friend told me to use a VPN but I don't know much things about how it works, any idea ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP/MySQLi - Sort, then undo sort? I get the information of my database into a table on my website. I sort my table when I click the link below, but I'd like to undo the sorting by clicking the same link again.
How do I do that? I researched rsort & unsset but I just can't get the solution.
For example I have a table with the tableheader "firstname" which contains all the names of course. When I click "firstnames", it sorts the firstnames.
$sqli = "SELECT * FROM data_base"

 if ($_GET['sort'] == 'firstname')
  {
      $sqli .= " ORDER BY firstname ASC";
  }

 Firstname

A: Depending on what was clicked, the links have to be different:
  if ($_GET['sort'] == 'firstname')
  {
      $sqli .= " ORDER BY firstname ASC";
  }
  else if ($_GET['sort'] == 'lastname ')
  {
      $sqli .= " ORDER BY lastname ASC";
  }

 if ($_GET['sort'] == 'firstname'){
     echo 'Firstname';
 }
 else {
     echo 'Firstname';
 }

 if ($_GET['sort'] == 'lastname'){
     echo 'Lastname';
 }
 else {
     echo 'Lastname';
 }

A: Pass your parameter according to you previously clicked your link
$sqli = "SELECT * FROM data_base";
$fname="firstname";
$lname="lastname";
 if ($_GET['sort'] == 'firstname')
  {
      $sqli .= " ORDER BY firstname ASC";
      $fname="";
  }
  else if ($_GET['sort'] == 'lastname')
  {
      $sqli .= " ORDER BY lastname ASC";
      $lname="";
  }

 echo "Firstname";
 echo "Lastname";

A: I recommend a new approach:
Add an ID column to your table and use it as primary key, this can be your default sort.
It's better a sort ordenation at database level instead of php level (ex: array).
Link1: Default sort
Link2: Sort by FirstName
Link3: Sort by LastName
Also, you can play with ASC and DESC in same link to sort ASCending or DEScending.

A: session_start();

$sqli = "SELECT * FROM data_base"

if ($_GET['sort'] == 'firstname'){
      if(!isset($_SESSION['first']))//checks if there is a no session
      {
         $sqli .= " ORDER BY firstname ASC";//sorting
         $first='1';
         $_SESSION['first']=$first;//start a session
      }

      if(isset($_SESSION['first']))//checks if their is a session
      {
          $sqli .= "";        //no sorting
          unset($_SESSION['first']); destroys the session so next time it will sort the results
      }
}

else if ($_GET['sort'] == 'lastname ')
{
    if(!isset($_SESSION['first']))     //checks if there is a no session
    {
        $sqli .= " ORDER BY lastname ASC";  //sorting
        $first='1';
        $_SESSION['last']=$last;  //start a session
    }
    if(isset($_SESSION['last']))     //checks if their is a session
    {
        $sqli .= "";        //no sorting
        unset($_SESSION['last']);
    }
}

 Firstname
 Lastname

You can do it with sessions just add session_start();
at the top just after


text:
Q: Scope of XML languages defined by DTD vs XSD Does the following propositions hold:
For every DTD there is an XSD that defines exactly the same language, and for every XSD there is a DTD that defines exactly the same language. Or put another way: The collection of languages defined by any DTD is exactly the the collection of languages defined by any XSD?
Expanding on the question a little: An XML document is basically a large string. A language is a collection of strings. For example, the (infinite) set of all MathML documents is a language, and so is the set of all RSS documents and so on. MathML (RSS, ...) is also a proper subset of the (infinite) set of all XML documents. You can use DTD or XSD to define such a subset of XML.
Now, every DTD defines exactly one language. But if you think of all possible DTDs, you get a set of languages. My question is, is this set exactly the same as the one you get from all possible XSDs? If so, then DTD and XSD are equivalent in the sense that the scope of XML languages defined by either is equal.
Why is this question important? If both DTD and XSD are equivalent then it is possible to write a program that takes a DTD as input and gives you an equivalent XSD, and another program that does the opposite. I know there are quite a few programs out there that claim to do exactly this, but I'm in doubt whether or not that's actually possible.

A: An interesting question; well asked!
The answer is "no", in both directions.
Here is a DTD which has no equivalent in XSD:
<!ELEMENT e (#PCDATA | e)* >
<!ENTITY egbdf "Every good boy deserves favor.">

The set of character sequences accepted by this DTD includes both <e/> and <e>&egbdf;</e>, but not <e>&beadgcf;</e>.
Since XSD validation operates on an information set in which entities have all already been expanded, no XSD schema can distinguish the third case from the second.
A second area where DTDs can express constraints not expressible in XSD involves NOTATION types.  I won't give an example; the details are too complicated for me to remember them correctly without looking them up, and not interesting enough to make me want to do so.
A third area:  DTDs treat namespace attributes (aka namespace declarations) and general attributes in the same way; a DTD can therefore constrain the appearance of namespace declarations in documents.  An XSD schema cannot.  The same applies to attributes in the xsi namespace.
If we ignore all of those issues, and formulate the question with respect only to character sequences containing no references to named entities other than the pre-defined entities lt, gt, etc., then the answer changes:  for every DTD not involving NOTATION declarations, there is an XSD schema that accepts precisely the same set of documents after entity expansion and with 'same' defined in a way that ignores namespace attributes and attributes in the xsi namespace.
In the other direction, the areas of difference include these:

*

*XSD is namespace aware:  the following XSD schema accepts any instance of element e in the specified target namespace, regardless of what prefix is bound to that namespace in the document instance.
<xs:schema xmlns:xs="..." targetNamespace="http://example.com/nss/24397">
  <xs:element name="e" type="xs:string"/>
</xs:schema>

No DTD can successfully accept all and only the e elements in the given namespace.

*XSD has a richer set of datatypes and can use datatypes to constrain elements as well as attributes.  The following XSD schema has no equivalent DTD:
<xs:schema xmlns:xs="...">
  <xs:element name="e" type="xs:integer"/>
</xs:schema>

This schema accepts the document <e>42</e> but not the document <e>42d Street</e>.  No DTD can make that distinction, because DTDs have no mechanism for constraining #PCDATA content.  The closest DTD would be <!ELEMENT e (#PCDATA)>, which accepts both sample documents.

*XSD's xsi:type attribute allows in-document modifications of content models.  The XSD schema described by the following schema document has no equivalent DTD:
<xs:schema xmlns:xs="...">
  <xs:complexType name="e">
    <xs:sequence>
      <xs:element ref="e" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="e2">
    <xs:sequence>
      <xs:element ref="e" minOccurs="2" maxOccurs="2"/>
    </xs:sequence>
  </xs:complexType>

  <xs:element name="e" type="e"/>
</xs:schema>

This schema accepts the document <e xmlns:xsi="..." xsi:type="e2"><e/><e/></e> and rejects the document <e xmlns:xsi="..." xsi:type="e2"><e/><e/><e/></e>.  DTDs have no mechanism for making content models depend on an attribute value given in the document instance.

*XSD wildcards allow the inclusion of arbitrary well-formed XML among the children of specified elements; the closest one can come to that with a DTD is to use an element declaration of the form <!ELEMENT e ANY>, which is not the same because it requires declarations for all the elements which in fact appear.

*XSD 1.1 provides assertions and conditional type assignment, which have no analogues in DTDs.
There are probably other ways in which the expressive power of XSD exceeds that of DTDs, but I think the point has been illustrated adequately.
I think a fair summary would be:  XSD can express everything DTDs can express, with the exception of entity declarations and special cases like namespace declarations and xsi:* attributes, because XSD was designed to be able to do so.  So the loss of information when translating a DTD to an XSD schema document is relatively modest, well understood, and mostly involves things most vocabulary designers regard as DTD artefacts not of substantive interest.
XSD can express more than DTDs can, again because XSD was designed to do so. In the general case, translation from XSD to DTD necessarily involves loss of information (the set of documents accepted may need to be larger, or smaller, or to be an overlapping set).  Different choices can be made about how to manage the loss of information, which gives the question "How does one best translate an XSD into DTD form?" a certain theoretical interest.  (Very few people, however, seem to find it an interesting question in practice.)
All of this focuses, as did your question, on documents as character sequences, on languages as document sets, and on schema languages as generators of languages in that sense.  Issues of maintainability and information present in the schema that does not turn into differences in the extension of document sets (e.g. the treatment of class hierarchies in the document model) is left out of account.

A: Without qualifiers, the answer is no.
You have to define what is it you call a "language". In my mind, these you refer to are languages meant to define document schemata. A schemata defines constraints on the document structure and content. The constraints expressible by XSD are far more powerful than DTD. So no, they wouldn't be the same.
A comparison of DTD vs. XSD might help you understand why not.


text:
Q: Make rows of a Google spreadsheet editable in a Google form I'm looking for a way to edit a large Google spreadsheet collectively via a form for each row in the spreadsheet. (I don't want to simply give access to the spreadsheet to everyone because some fields have multiple lines and are a bit hard to edit directly inside of the spreadsheet.)
I've managed to create pre-filled forms for each row with Is it possible to 'prefill' a google form using data from a google spreadsheet? and How to prefill Google form checkboxes?. (and I then can create a view as an Awesome-table with a button for each row which opens the pre-filled form corresponding to the row).
But the responses do not update the existing rows but add a new row (at row 2 strangely enough, protecting the headers, but messing up the Awesome-table that needs filter information in row 2).
How can I make a pre-filled form that writes at a specific row of a sheet? If possible the same row that the pre-fill was created from. Maybe with some script that is triggered by the submission of the form and which replaces the standard recording? Or is there a completely other way to edit Google spreadsheets by means of forms?

Update:
This was much harder than expected and I finally got back to it. Here is what I ended up hacking together:
A spreadsheet document document with three sheets:

*

*main: The main data

*temp: only used for the automatically added entries after submission

*links: keeping the editing links and response ids corresponding to each line of the main sheet

Then

*

*A function that can be triggered from the menus: creates a prefilled answer per line of main, submits, and puts the url and id in the links sheet. These links are distributed to different people who are asked to update the prefilled information of their row by means of the form.

*A onFormSubmit function attached to the form that

*

*searches for the line with the right response id in links

*updates the corresponding line in main
So the temp sheet is not used at all, all entries are handled manually. What I haven't managed to do is to allow a manual change in the main table and to resubmit the data under the same id. (I don't want to make a completely new response because the links are already distributed.)

A: The pre-filled URL allways will create a new form response. Instead you should use the URL returned by getEditResponseUrl(). For details see this other question
How do I edit the response of a form submission in Google Forms/Sheets?


text:
Q: Is it ok to create a generic viewmodel? A while back I had posted this question about the use of ViewModels.
I have another question related to the same topic -
Is it ok to create a generic viewmodel? By generic, I mean a viewmodel that can be shared among different views. (some views may use one subset of the fields of the viewmodel while another may use another subset). Or should each viewmodel be tailor made for one specific view?

A: Well the short answer is Yes and the long answer is Yes.
Paging for instance if configured via your ViewModels is a good reason to generalize your ViewModel for those pages.  That's only one example but i'm sure there's gonna be more....

A: Why not use the ViewBag?
This is what it's meant to be used for, in my experience.


text:
Q: validate hour field with yup I have field hour declared in material-ui TextField. I want to add Yup validation to control the format for the value typed which should respect this format: 02:30
How can I control it with Yup?

A: You can use regex to achieve your goal.
I made in this way:
const schema = yup.object({
  hour: yup
    .string()
    .length(5)
    .matches(/(\d){2}:(\d){2}/, 'Hour must have this pattern "00:00"'),
});


text:
Q: backbone.js: understanding browser event handling and view removing I'm fiddling with a view and related model that look like that:
App.Views.Addresses         = App.Views.Addresses || {};
App.Views.Addresses.Address = Backbone.View.extend({

  events: {
    "click button#foo"             : "clear"
  },

  initialize: function(model){
                this.address = model.model;
                this.address.view = this;
                _.extend(this, Backbone.Events);
                this.render();
              },

  render:     function(){
                ... rendering stuff
              },

  clear:      function(){
                this.address.clear();
              }
});

and
var Address = Backbone.Model.extend({

  url:   function() {
           ... url stuff
         },

  clear: function(){
           this.destroy();
           this.view.remove();
         }
});

I'm facing two problems here. The first one:
I have a button with id="foo" in my source and would like the view to catch the 'click' event of this very button and fire the 'clear' event. Problem: This does not work.
Anyway calling 'clear' on my model by hand cleanly removes the data on the server but does not remove the view itself. Thats the second problem. Hopefully someone more experienced can enlighten me.
Thx in advance
Felix

A: First problem:

*

*Your button must be inside the element rendered by the view.

*

*backbone scope events to inner elements only

*You must render your view within this.el element

*

*backbone use that element for delegation

Second problem:

*

*Use events to destroy your view

*

*You should not store the view in the model. This is kind of a "no no" in MVC. Your model already emits a "remove" event when deleted. Your view should listen to it and behave accordingly.

*You must remove your view element from the DOM yourself

*

*This is not handled by backbone.

Other general comments:

*

*Views already are extending Backbone.Events

*Use this.model instead of this.address


text:
Q: Angular: How go to have multiple PWA app under same domain I am facing a big problem since last one week.
I am working with Angular app which have one feature like create Business Card with url dedicated. Example is given below.
mysite.com (main site)
mysite.com/card1 (card1)
mysite.com/card2 (card2)
So how to have pwa for each of this card seperately.

*

*I don't think this would require code i did

*I know this can be achieved by having multiple service workers.

Above 2 points i know. Please help me with this. I had searched a lot about this but I didn't find anything specific for Angular.


text:
Q: How to display number of sunday's between the dates on the ReactJS application I'm trying build app on ReactJS to display number of Sundays between the dates when click on submit button. I've take start date and end date as input date and button in side a form. I'm unable to get an idea how to incorporate in submitHandler and display. Below is my code
 import React from 'react'
    import {useState} from 'react'

    const Calculate = () => {
      const [inputDate,setInputDate] = useState({
        sdate:'',
        edate:'',
      });

      const onChangeHandler = (e)=>{
          let name =e.target.name
          let value = e.target.value

        const Calculate = () => {
          const [inputDate,setInputDate] = useState({
            sdate:'',
            edate:'',
          });

          const onChangeHandler = (e)=>{
              let name =e.target.name
              let value = e.target.value
              setInputDate({...inputDate,[name]:value})
          }
          const submitHandler=(e)=>{
            e.preventDefault();

          }

          return (

              <form action="">

                    Start Date
                    <input type="date" name="sdate"  onChange={onChangeHandler}/>

                    End Date
                    <input type="date" name="edate" onChange={onChangeHandler}/>

                  <button>Submit</button>

              </form>

          )
        }

        export default Calculate

          setInputDate({...inputDate,[name]:value})
      }
      const submitHandler=(e)=>{
        e.preventDefault();

      }

      return (

          <form action="">

                Start Date
                <input type="date" name="sdate"  onChange={onChangeHandler}/>

                End Date
                <input type="date" name="edate" onChange={onChangeHandler}/>

              <button>Submit</button>

          </form>

      )
    }

    export default Calculate

Looking for help here. Thank you


text:
Q: Bootstrap columns with stacked images: need to have same column height I have a Bootstrap section with stacked images and the issue is that I want the second and third columns to always have the same height as the first column. I can't seem to find a solution for the second and third column because they keep fluctuating in height as I change to different view sizes. It would be ideal to have them always align to the bottom and top.

.gallery {
 min-height: 980px;
}

.gallery .row{
 display: -webkit-box;
 display: -webkit-flex;
 display: -ms-flexbox;
 display: flex;
}

Here is the Bootply: http://www.bootply.com/mb2Ez6G7r8

A: Hi Paul you can resolve in that way, i see that you use boostrap you dont need the property flex in your css.

 and your css
.gallery {
min-height: 980px !important;}

dont forget add bootrap in your html
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

i explain why you dont need flex, Boostrap make your thml responsive with class .row and you can fill this with 12 columns that is why you have col-sm-(Number) in your case 5+4+3=12 if you want you can read more in this link grid systemn

A: .column-sm-4{
   display: flex;
   flex-direction: row;
}

If height is an issue you should probably use background-image with css instead of  element.
Hope this will solve the issue.


text:
Q: magento url rewrite prevent -1 or -2 I have a category created which contains url key as - "sofa" and url generated is "sofa.html". URL rewrites system record generated as follows :
ID Path : category/5
Request path : sofa.html
Target Path : catalog/category/view/id/5

Now I want to run one of the custom module over that url(sofa.html) so I deleted system url rewrites and added custom url rewrites from the backend as follows :
ID path : alternate-sofa
Request path : sofa.html
Target path : alternate-sofa

So when I run sofa.html from the browser, I got the expected page from the custom module and it resolves the issue removing custom rewrites after reindexing, though after reindexing new system record added as follows :
ID path : category/5
Request path : sofa-1.html
Target path : catalog/category/view/id/5

Now, I am having issue as follows : On the page, I am listing out categories on left side which contains category url as "sofa-1.html" which is displaying my category layout instead of custom module. How to overcome this issue? I don't want to create sofa-1.html, sofa-2.html, onwards.
Edit :
I refereed http://jc-designs.net/blog/2012/09/magento-adding-cms-pages-to-the-main-navigation/ and http://www.magentocommerce.com/knowledge-base/entry/adding-page-links-in-the-navigation-bar but when I set 301(permenant), url changed from "sofa.html" to "alternate-sofa" which is not expected url in the browser.

A: You cant simply prevent this, as there are cases, where it could make sense, like when you have products whith the same url key.
Additionally this is caused by a bug in magento, which has severel possible bugfixes, some of them described in Magento core_url_rewrite table excessively large

A: You need to change the settings in admin under System -> Configuration -> Catalogue -> Catalogue -> Search Engine Optimisation -> Category URL Suffix - This should be ".html", you just need to change it to BLANK. Once done then delete all the entries from core_url_rewrite table for all the categories using the following query -:

DELETE FROM core_url_rewrite WHERE product_id IS NULL AND LENGTH(category_id)>0
N.B - Please take DB back up prior to run any update/insert/delete queries on production server

Hope it helps
Cheers
S

A: The way I handled -1 or -2 in the url's is making sure all index processes are done or set on manual index. Then in the URL Rewrite manager I search for all requested paths with -1 and remove them. Reindex catalog URL Rewrites and they should be resolved.


text:
Q: docker registry v2, where do buffered or pushed images get stored I have setup a local docker registry v2 and images have been pushed and pulled frequently with various tags.

*

*Where do the pushed images get stored (pushed from the docker client) ? Do they get store within the registry container or on the host OS ?

*How to be purge the pushed/buffered images from the registry for free disk space ?

A:
By default, your registry data is persisted as a docker volume on the
  host filesystem.

https://docs.docker.com/registry/deploying/#storage
If you don't mount the volume, you can locate where it is persisted using docker inspect
https://docs.docker.com/userguide/dockervolumes/#locating-a-volume


text:
Q: How can I use virtual member functions in multi-file programs? So I just figured out that it was much simpler to just use multiple files to separate classes from each other and keep things nice and tidy, instead of dealing with 10 000 line programs inside the one file. Unfortunately this has caused some issues with the virtual member functions I was using in the computer program I was "partitioning".
My working directory looks like this:
main.cpp (the main function and other ambiguous stuff)
foo.h (declaration an object, including prototype of virtual function "baz")
foo.cpp (implementation of the above object object, including implementation of virtual function "baz")
bar.h (declaration of an object that inherits from foo (includes "foo.h"))
bar.cpp (implementation of the bar object, including a redefinition of the "baz" object)

The only issue I am having is an error when I implement the baz objct in foo.cpp. the error is "E0239: invalid specifier outside a class declaration".
I can't figure out why I can't implement the baz function outside the object (in the .cpp file). It seems to want me to declare it and implement it in foo.h, which kinda counteracts the idea of separating the source in the first place.
I get the feeling I'm doing something very wrong, but I don't know what it is. Any ideas?


text:
Q: True/False- Does the limit exist? True or False: Suppose that $f$ is bounded. Suppose that $f$ is not continuous at $x$=$a$. Then $\lim_{x\to\ a} f(x)$ exists but is not equal to $f(a)$.
I want to say false because all we know is that it is bounded and not continuous at one point and not all bounded sequences have limits.

A: False : consider $"\lim\limits_{x\to0^+}\sin(\frac{1}{x})",$ with $f(0)$ equals what you want.


text:
Q: check for a specific delimiter per line - bash I want to write a script in bash that handles a file with lines that has 5 columns and i expect the delimiters to be one single space (" ").
everything other than that should lead to an error, even more than 1 space.
for instance, that line is legal: first last 1234124 complex no
while this
first  last 1234124 complex no

or
first_last  1234124 complex no

should lead to an error.
I've tried some commands but everything i tried handled one space and more than one  - the same way.
Waiting to be shared by your knowledge. Thanks.

A: If you use a regular expression to set the field separator in awk to a single space (and nothing else), you can use the below to report problematic lines
awk -F'[ ]' 'NF != 5' file.txt

A: You can use grep -qP with this regex:
grep -qP '^(\S+\s){4}\S+$'

Testing:
> s='first last 1234124 complex no'
> grep -qP '^(\S+\s){4}\S+$' <<< "$s" && echo "valid" || echo "invalid"
valid

> s='first   last 1234124 complex no'
> grep -qP '^(\S+\s){4}\S+$' <<< "$s" && echo "valid" || echo "invalid"
invalid


text:
Q: Activity used in 2 different ways, only allow one instance of each I have QueueActivity that can be accessed on its own, and also a SearchActivity that can launch a QueueActivity intent with search results.  I want to make it so that one of each of these two types of QueueActivity can be launched but no more than one of each.  How can I go about doing this?
I tried using ActivityManager to see what instances are already running but I can only get Tasks, not individual Activities.  I tried using Intent.FLAG_REORDER_TO_FRONT but of course that will only allow one total QueueActivity, not two.

A: If you only want to have one instance of your Activity than you just have to set the launchMode to singleInstance in your manifest:
<activity
    android:name=".ui.activities.SomeActivity"
    android:launchMode="singleInstance"
    android:theme="@style/SomeTheme" />


text:
Q: Moving Azure credentials to Docker I have a Docker volume from ${USERPROFILE}/.azure to /root/.azure:rw. In my Dockerfile, I'm installing az-cli and then using DefaultAzureCredentials class in .NET (https://learn.microsoft.com/en-us/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet) to load the credentials.
It worked fine until a month ago, I had to az login on my machine and then it worked fine in Docker. However, about a month ago, when az-cli switched from ADAL to MSAL, it throws an exception saying I'm not logged in.
My guess is that az-cli stores the tokens somewhere else now, other than the .azure directory, or something else, I'm not sure. Anyone has any idea?

A: Earlier, Azure CLI save ADAL tokens and service principal entries to ~/.azure/accessToken.json
Later when Azure CLI use MSAL, it no longer generate accessTokens.json file.
Any existing workflow depending on accessTokens.json no longer works
So instead of DefaultAzureCredentials class, you can use AzureCliCredential class
AzureCliCredential class uses subprocess to call az account get-access-token to get an access token for the current logged-in account
Reference: MSAL-based Azure CLI | Microsoft Docs

A: For now you can use a pre-2.30 az-cli version both on your host system and inside your container. Instructions are here to install a specific version: https://learn.microsoft.com/en-us/cli/azure/install-azure-cli


text:
Q: Behaviour DataInputStream into mapping I had problems to save a file into disk.
The path to save, in environment, it's a mapping (the disk is in another server).
A - When I try to save a DataInputStream with a loop, reading "byte per byte", takes a lot of time (~12 min / MB).
B- Now, I read a passing an byte[8192]. This solve the problem.
I know that B is faster than A but, when I run the same code, trying to save into my local disk, there is no difference, both take same time.
Why the mapping takes a lot of time?
Read a byte[8192] at a time can cause problems?
Tks!


text:
Q: Meaning of inertial frames in quantum mechanics In quantum mechanics where it is difficult to speak about the precise position and momentum of a particle for a macroscopic observer, does it still make sense to speak of inertial frames or even rest frames?

A: I am not an expert on this topic but I would try to give a naively sensible answer.

*

*At least for a limited class of systems who admit a large action classical-limit, there is a sense in which we can give meaning to the concept of inertial frames in quantum mechanics using the insight from Ehrenfest theorem that the equations of motion for expectation values of Hermitian observables are isomorphic to classical equations of motion for the corresponding canonical quantities.

*

*Namely, inertial frames are those in which free particles evolve according to such laws that produce $\frac{d}{dt}{\langle p\rangle}=0$.

*As to the definition of rest-frame, the only meaningful definition ought to be that the frame in which the system is in a momentum-eigenstate with the eigenvalue $0$ is the rest-frame of the said system.

*

*However, as one can imagine, it is not guaranteed that one can always find a rest-frame for a given system because a given system need not be in its momentum-eigenstate (in fact, it is guaranteed for most systems that this would never happen because the momentum-eigenstates for most systems are non-normalizable and thus, physically unrealizable).

I admit that this discussion does not address the question of what physical configuration would realize an inertial observer in the way one imagines such a system in relativity (i.e., an imagined grid of clocks and rulers).

A: Here is another way to look at it. Let us assume a quantum system $\mathcal O$ whose pure state is denoted by the ray $[\Psi]$. The fundamental assumption of implementing any symmetry (and in particular the Galilean symmetry) in Quantum Mechanics is that there are two macroscopic observers $O$ and $\bar{O}$, so that each of them has its own version of $[\Psi]$. They define what is known as Galilean/inertial reference frames which should be familiar from Galilean/special relativity. This is the starting point of any symmetry (typically known as the Weyl-Wigner approach to Quantum Physics = "Gruppenpest") analysis of Quantum Mechanics. Replace Galilean with Lorentzian and you have the fundamentals of Relativistic Quantum Field Theory, chapter 2 of the 1st volume of Weinberg's QFT text.
The thing about these macroscopic observers is that their kinematics is well known and the "Heisenberg uncertainty" does not really apply to them. Why? Well, let us say that there is a small uncertainty in the position and momentum of the observers and that $\delta x \cdot \delta p \approx \hbar $. But for Galilean/Lorenzian frames we have a macroscopic speed $v$ which connects $O$ and $\bar{O}$ and then $\delta v =\frac{\delta p}{M_{\text{OBSERVER}}}$. The observer's mass can be taken arbitrarily high so that $\delta v$ is literally $0$. This argument is also used by Fonda and Ghirardi in their famous text.
So it always makes sense to have $[\Psi] ({x_{O},v_{O},t})$ and $[\Psi] ({x_{\bar{O}},v_{\bar{O}},t})$ and $x_{O} = x_{\bar{O}} + v_{O\rightarrow \bar{O}} t$, for example.


text:
Q: Replacing string with variable with Groovy and SED command I am trying to replace an entire description string contained in an XML file. I would like to replace that string with a variable. I am using a SED command within a Groovy script.
I have the following code. I am expecting the string "foo" to replace the description text but it doesn't.
Instead the following line causes the XML to change to:
Description="sDescription"
What am I doing wrong?
def sDescription = "foo"
def sedCommand = 'sed -i \'s/Description="[^"]*"/Description="'$sDescription'"/g\'  package.appxmanifest' as String

A: In Groovy variable/expression substitution inside of strings (interpolation) only works with certain types of string literal syntax. Single quote syntax ('content') is not one of them. However, if you replace the outer single quotes with double quotes ("content") then you should get the interpolation effect you are looking for:
def sDescription = "foo"
def sedCommand = "sed -i 's/Description=\"[^\"]*\"/Description=\"$sDescription\"/g\'  package.appxmanifest" as String

This should give you the string that contains the command you wish to run. Please note how I changed the special character escaping (\) within the string to reflect the change in string delimiters.
Aside: As noted by @tim_yates, Why would you want to invoke a separate ad hoc process to do this substitution when Groovy contains excellent XML manipulation facilities built into the language?


text:
Q: GraphQL : OverLoaded function error when adding a computed field I am trying to add a computed field to my graphql table "user" in schema "abc" using the hasura API but receiving the following error :
**Saving computed field failed**
in table "abc.user": in computed field "allaccounts": function "abc.get_accounts"
is overloaded. Overloaded functions are not supported

The function is added correctly :
  CREATE OR REPLACE FUNCTION abc.get_accounts(id bigint)
    RETURNS VARCHAR immutable AS $$
DECLARE
    value VARCHAR;
BEGIN
    SELECT array_to_string(ARRAY_AGG( name ORDER BY name ASC )::varchar[], ',', '')
           into value
    FROM abc.account
             INNER JOIN abc.user_account ON (account.id=user_account.account_id)
    where user_account.user_id = id group by user_id;
    return value;
END;
$$ LANGUAGE plpgsql;

id field is present in user table.
I am able to select the function "get_accounts" from the dropdown but getting an error on adding computed field. Any guidance is appreciated. Thank you.

A: Your function is overloaded. That is, you have (at least) another function in the database that uses the same name and another list of arguments.
You typically need to identify the conflicting function, and drop it (unless you have a good reason not to). You can exhibit the "homonyms" with the following query, that generates drop function statements which you can directly use:
select format('drop %s %s;', case when proisagg then 'aggregate' else 'function' end, oid::regprocedure) as stmt
from pg_catalog.pg_proc
where proname = 'get_accounts'

Credits go to Erwin Brandstetter in this SO answer, that goes into more details on how to solve the problem.

A: Adding STABLE worked for me :
CREATE OR REPLACE FUNCTION abc.all_accounts(user_row abc.user)
  RETURNS VARCHAR AS $$
DECLARE
  value VARCHAR;
BEGIN
  SELECT array_to_string(ARRAY_AGG( name ORDER BY name ASC )::varchar[], ',', '')
      into value
               FROM abc.account
                      INNER JOIN abc.user_account ON (account.id=user_account.account_id)
                   where abc.user_account.user_id = user_row.id
               group by user_id;
  return value;
END;
$$ LANGUAGE plpgsql STABLE;


text:
Q: Get IP address of a server machine There was a robbery at my place and the lads took my NAS. Couple of weeks later I discover my NAS is online again. I access it through a dynamic DNS address that does not give back an IP address with nslookup (Gives back the Synology pool of servers - but cannot http directy to this IP address). It is probably nated behind the returned server. The question is if there were anyway to get around this.

A: Not sure if I understand your question right, the dynamic DNS entry should (as long as your NAS is able to update it) always point to the public IP where your NAS is behind... otherwise it wouldn't be working. If it's at an ISP or larger datacenter and unclear who is really behind this public IP you might want to involve police so they can take the necessary measures.


text:
Q: Can i Save an image on let defaults = NSUserDefaults.standardUserDefaults() on swift? i want to take a picture an save it on NSUserDefaults an then show taht image on other view its that posible ?

A: Yes, it is possible, but you shouldn't do it. Save an image to the file system, not to the user defaults. It is data, not a preference. And it is relatively huge.


text:
Q: Installing krb5 package on Windows I'm installing simplesamlphp and php composer.phar install is throwing an exception due to a lack of ext-krb5 PHP extension.
I didn't find 'krb5' in php.ini; I found the extension here: https://pecl.php.net/package/krb5
I've downloaded the tgz file; how do I activate it?


text:
Q: Private Network broken in Vagrant with Docker I create a Virtualbox vm via Vagrant by using the default Docker Vagrantfile. Building the vm with vagrant up works as expected and provides a running box to work with.
I then needed the ability to forward ports and added the following to the Vagrantfile:
Vagrant::VERSION >= "1.1.0" and Vagrant.configure("2") do |config|
  config.vm.network :forwarded_port, :host => 5432, :guest => 5432 # postgres
  # ... more port forwardings
end

This works, but i then realized that i need port forwarding in both directions. I tried to create a private network for this matter instead of forwarding each port. The following addition to the config should have done the trick:
Vagrant::VERSION >= "1.1.0" and Vagrant.configure("2") do |config|
  config.vm.network :private_network, ip: "172.17.0.2"
end

But, this triggers an error while creating the vm:
> vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for machine to boot. This may take a few minutes...
The guest machine entered an invalid state while waiting for it
to boot. Valid states are 'starting, running'. The machine is in the
'poweroff' state. Please verify everything is configured
properly and try again.

If the provider you're using has a GUI that comes with it,
it is often helpful to open that and watch the machine, since the
GUI often has more helpful error messages than Vagrant can retrieve.
For example, if you're using VirtualBox, run `vagrant up` while the
VirtualBox GUI is open.

Any idea how to debug and resolve this?
Host OS: Arch Linux
VM OS: Ubuntu (see Vagrantfile linked above)

A: From the Arch Linux Wiki:

To ensure full functionality of bridged networking, ensure that the
  vboxnetadp, vboxnetflt and vboxpci kernel modules are loaded too and
  that the net-tools package is installed.

Kernel modules
The issue is that the kernel modules for creating private networks in a virtual machine need to be loaded seperately:
sudo modprobe -a vboxnetadp vboxnetflt

To make this change permanent after each reboot, put the following lines in /etc/modules-load.d/virtualbox.conf:
vboxdrv
vboxnetadp
vboxnetflt

Packages
net-tools needs to be installed:
sudo pacman -S net-tools

You also need the virtualbox-host-modules package in order to bring private networks to life:
sudo pacman -S virtualbox-host-modules


text:
Q: R: duplicates elimination in a matrix, keeping track of multiplicities I have a basic problem with R.
I have produced the matrix
M
     [,1] [,2]
[1,] "a"  "1"
[2,] "b"  "2"
[3,] "a"  "3"
[4,] "c"  "1"

I would like to obtain the 3X2 matrix
     [,1] [,2] [,3]
[1,] "a"  "1"  "3"
[2,] "b"  "2"  NA
[3,] "c"  "1"  NA

obtained by eliminating duplicates in M[,1] and writing in N[i,2], N[i,3] the values in M[,2] corresponding to the same element in M[,1], for all i's. The "NA"'s in N[,3] correspond to the singletons in M[,1].
I know how to eliminate duplicates from a vector in R: my problem is to keep track of the elements in M[,2] and write them in the resulting matrix N. I tried with for cycles but they do not work so well in my "real world" case, where the matrices are much bigger.
Any suggestions?
I thank you very much.

A: You can use dcast in the reshape2 package after turning your matrix to a data.frame. To reverse the process you can use melt.
df = data.frame(c("a","b","a","c"),c(1:3,1))
colnames(df) = c("factor","obs")
require(reshape2)
df2=dcast(df, factor ~ obs)

now df2 is:
 factor  1  2  3
1      a  1 NA  3
2      b NA  2 NA
3      c  1 NA NA

To me it makes more sense to keep it like this. But if you need it in your format:
res = t(apply(df2,1,function(x) {  newLine = as.vector(x[which(!is.na(x))],mode="any"); newLine=c(newLine,rep(NA, ncol(df2)-length(newLine) )) }))
res = res[,-ncol(res)]

     [,1] [,2] [,3]
[1,] "a"  " 1" " 3"
[2,] "b"  " 2" NA
[3,] "c"  " 1" NA


text:
Q: Preparing a function to repeatedly use in a generator runner I'm using a nodejs telnet implementation which uses an event to provide notification each time data is received from a telnet client, which can be subscribed as follows:
client.on('data', [callback]);

I'm also using a generator runner (generator-runner on npm) to execute workflows.
The problem I'm having is that yielding values in this way requires something more like a promise: a single delegate passed on to process a single value. How would I go about writing a function which could be placed in the generator yield statements, and could be repeated every time I want to yield more input?
I've tried using Baconjs for this, but I don't think there's a way to block waiting for a single value on a stream, at least I can't find such a method.
I'm open to any advice. My only real requirement is that I be able to place my workflows in a flat block of code without chaining promises.
Here's the code I've got mocked up, which simply doesn't work:
var requirejs = require('requirejs');
requirejs(['telnet', 'baconjs', 'colourise', 'lodash', 'generator-runner'], function(Telnet, Bacon, Colourise, _, Async) {
    var configureClient = client => {
        client.do.transmit_binary();
    };

    Telnet.createServer(client => {
        var session = {
            connectedAt: Date.now(),
            user: { }
        },
        write = _.compose(_.bind(client.write, client), Colourise.encode),
        readStream = Bacon.fromBinder(function (sink) {
            client.on('data', function (data) {
                sink({ client : client, data : data, session : session });
            })}),
        read = () => readStream.take(1).toPromise();

        configureClient(client);
        write("%xxWelcome!\r\n")

        Async(function*(){
            write("Username: ");
            var user = yield read();
            console.write("Username entered: " + user);

            write("Password: ");
            var password = yield read();
            console.write("Password entered: " + password);
        });
    }).listen(8100);
});

A: I've gotten this working by using 'fromEvent' in Baconjs and using 'firstToPromise'. I was getting exceptions thrown from 'fromBinding', so I don't know what was up there, but it slowed down my progress a lot.
Below is the simplified and working code. Requires ES6 (I used node flags --harmony and --harmony_generators.)
On a side note, I'm hugely excited about the implications of this technique!
var requirejs = require('requirejs');
requirejs(['telnet', 'baconjs', 'generator-runner', 'lodash'],
    function(Telnet, Bacon, Async, _) {
        var configureClient = client => {
            client.do.transmit_binary();
        };

        Telnet.createServer(client => {
            var write = _.bind(client.write, client),
                readStream = Bacon.fromEvent(client, 'data'),
                readAsync = () => readStream.firstToPromise();

            configureClient(client);
            write("Welcome!\r\n")

            Async(function*(){
                write("Username: ");
                var user = yield readAsync();
                console.log("Username entered: " + user);

                write("Password: ");
                var password = yield readAsync();
                console.log("Password entered: " + password);
            });
        }).listen(8100);
    }
);


text:
Q: Exact phrase search using lucene without increasing number of fields For a phrase search, we want to bring up results only if there's an exact match (without ignoring stopwords). If it's a non-phrase search, we are fine displaying results even if the root form of the word matches etc.
We currently pass our data through standardTokenizer, StopFilter, PorterStemFilter and LowerCaseFilter. Due to this when user wants to search for "password management", search brings up results containing "password manager".
If I remove StemFilter, then I will not be able to match for the root form of the word for non-phrase queries. I was thinking if I should index the same data as part of two fields in document.
I have asked same question at Different indexing and search strategies on same field without doubling index size?. However folks at office are not happy about indexing the same data as part of two fields. (we currently have around 20 text fields in lucene document). Is there any way to support both the cases I listed above using TokenFilters?
Say, for a StopFilter, make changes so that it emits both the input token and ? (for ignored word) with same position increments. Similarly for StemFilter, it emits both the input token and stemmed token with same position increments. Basically input and output tokens (even ignored ones) have same positions.
Is it safe to go ahead with this approach? Has anyone else faced the requirements listed here? Are there any Filters readily available which do something similar to what I mentioned in my approach?
Thanks

A: I don't understand what you mean by "input and output tokens." Are you storing the data twice - once as stemmed and once non-stemmed?
If you aren't storing it twice, I don't think your method will work. Suppose the stored word is jumping and they search for jumped. Your query parser can emit jump and jumped but it still won't match jumping unless you have a value stored as jump.
And if you're going to store the value once as stemmed and once as non-stemmed, then why not just store it in two fields? Then you won't have to deal with weird tokenizer changes.


text:
Q: A game on sets of reals A 2 player game on $\mathcal{P}(\mathbb{R})$: Players take turns playing uncountable sets of reals.  Each play must be a subset of the previously played set. Player 1 wins if the intersection of all the sets is nonempty. Otherwise player 2 wins.
Assuming AC, player 2 has a winning strategy. On can prove in ZF that 2 wins the analogous game on any well-ordered set.
What might happen without AC?  I heard a false argument that 1 wins assuming the perfect set property, so be careful.

A: This is a great question!   I've now managed to eliminate the use of countable choice.
Theorem. Without using any choice principle, it follows that player I can have no winning strategy in the game.
Proof: Working in ZF only, suppose toward contradiction that player I has a winning strategy $\tau$. Look at the set $A$ played by player I on the first move, using strategy $\tau$. Note that $A$ is uncountable, but it can have no uncountable well-orderable subset, since in this case player II could play that subset and move to the well-orderable case, which according to what you have said would put player II in a winning position and therefore contradict that $\tau$ is winning for player I.
Let us now argue that there is a choice function on the uncountable subsets of $A$. To see this, fix any uncountable $B\subset A$ and let us have player II respond with $B$ on player II's first move, with player I continuing subsequently to play according to $\tau$. At each subsequent stage $n$, let us have player II follow the (losing) strategy, where when confronted with a set $E\subset A$, he will find the first rational interval $I$ (in some canonical enumeration) of width $\frac 1n$ such that $E\cap I$ is uncountable, and then play $E\cap I$.
We could deduce that such an interval $I$ exists if we had countable choice, since otherwise $E$ would be a countable union of countable sets. But I claim that we do not need to assume any choice principle in order to make this conclusion. If the set $E$, which was played by player I according to the strategy $\tau$, is the countable union of countable sets $\bigcup_n E_n$, then this is now a winning position for player II, since every uncountable subset of $E$ must contain points from infinitely many $E_n$, and so player II can always subsequently play on his $k^{th}$ step so as to remove the sets $E_i$ for $i\leq k$ from play (a countable removal). Since $\tau$ is winning for player I, however, it must be that the set $E$ is not a countable union of countable sets and so such a rational interval $I$ exists.
Continuing with the main line of argument, what we have is that player II is playing in a prescribed manner (without using any AC), but ensuring that the diameters of the sets in the play of the game go to $0$. Since $\tau$ is winning, the final intersection set will therefore be a singleton subset of $B$, and thus we have provided a means to choose an element from any such $B$.
Using this choice function, we can now choose elements from uncountable subsets of $A$. It follows that we can define an injection of $\omega_1$ into $A$: we first choose a point $a_0\in A$, and then choose a point from $A-\{a_0\}$ and so on. At each stage $\beta$, we choose a point in $A-\{a_\alpha\mid\alpha\lt\beta\}$, which is an uncountable subset of $A$. The set of $a_\alpha$ is an uncountable well-orderable subset of $A$, which contradicts our assumption that there was no such subset. So player I cannot have such a winning strategy after all. QED
This theorem does not seem to imply that player II must have a winning strategy, however, since perhaps the game is undetermined.
Following the link in Andres's comment, we see that Asaf Karagila had had essentially the same argument over at math.SE. And the trick to eliminate the use of countable AC uses the same idea as in Andres's answer over at math.SE.


text:
Q: Index and import HTML not working in Google Sheets I am trying to extract the certain value of a Single row of html table in 5th Row and third column from the below mentioned link
https://www.xe.com/currencytables/?from=USD&date=2020-02-07
the formula that I have used as mentioned below:
=index(IMPORTHTML("https://www.xe.com/currencytables/?from=USD&date=2020-02-07","table",0),5,3)
The formula doesnt extract the value in the cell instead it displays in the popup of google sheets.
I am looking to extract single value in 5th Row and third column . I tried using index and importxml but could not get any value.
Please help with the requiste formula to get the desired result .
Thanks

A: The formula seems to work fine for me.


text:
Q: UIView animation with CGAffineTransformMakeScale changes size instantly with decimal number - (void)startAnimation {
//reverse - shrinking from full size
    if (_reversed == YES) {
        //self.transform = CGAffineTransformMakeScale(1.0, 1.0);
        [UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^{
            self.transform = CGAffineTransformMakeScale(0.1, 0.1); //this line does it instantly
            self.alpha = 0;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    } else {
//non reverse - expanding from middle
        self.transform = CGAffineTransformMakeScale(0.001, 0.001);
        [UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^{
            self.transform = CGAffineTransformMakeScale(1.0, 1.0);
            self.alpha = 0;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }
}

The non reverse piece of code does work fine as I expect, however when I do the _reversed == YES bit, the transformation inside the animation block happens instantly. If I comment that line of code, then the view stays the right size, but if i uncomment it then it shrinks instantly but the alpha still does the fade animation. Why does this happen?
Edit: I figured out what happened but I don't know how to fix it. The view does do the animation, only the size of the view changes instantly but it still 'slides' into the centre as if it is shrinking (what you see is just a small rectangle sliding to the middle as if it's the top left corner of the object). If I scale the view to 2 first, then scale down to 1 the animation works fine, its only when going from 1 to a decimal number that it doesn't work. Also I used draw rect to create an object with core graphics and the transform problem affects that, but not the actual frame if a set background colour.

A: I was running into a similar issue, where the position of the view would suddenly jump before animating in a change of transform with CGAffineTransformMakeScale. I noticed that the size of the "jump" seemed to be proportional to the scaling that would occur later in the animation.
I could fix this problem by finding that in a viewWillLayoutSubviews() override, I was setting the frame of the view being animated. As a rule, don't set the frames of views that will have a non-identity transform. So in the viewWillLayoutSubviews() override, I set the view's bounds and layer.position instead and now the animation is smooth as silk.


text:
Q: WKWebView Open _Bank Target Links in Safari I am very new so bear with me. I had an youtube video embed in a WKWebView playing fine on macOS in Objective-C. At first, none of the standard youtube links on the video (channel, recommended videos, etc) would load. I think this was because youtube uses _blank target links. The following code fixed it so any video links will now open in the WKWebView.
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    NSLog(@"createWebViewWithConfiguration %@ %@", navigationAction, windowFeatures);
    if (!navigationAction.targetFrame.isMainFrame) {
        [(WKWebView *)_webView loadRequest:navigationAction.request];
    }
    return nil;
}

However, I would like these links to open in the macOS browser, and not WKWebview. Lot's of swift examples on iOS, but can't seem to get links to open from WKWebView in safari.
I have tried:
if (!navigationAction.targetFrame.isMainFrame) {
     [[NSApplication sharedApplication] openURL:[navigationAction.request URL]];
}

But doesn't work on macOS

A: This is what eventually worked for me. Seems to open any url (including javascript type popovers used in YouTube) in Safari instead of opening them in WKWebView (or not opening them at all).
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    NSLog(@"createWebViewWithConfiguration %@ %@", navigationAction, windowFeatures);
    if (!navigationAction.targetFrame.isMainFrame) {
       [[NSWorkspace sharedWorkspace] openURL:[navigationAction.request URL]];
    }
    return nil;
}

A: Not 100% sure but I've seen this circulated online for opening URLs on Mac. Give it a try.
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://stackoverflow.com"]];


text:
Q: Babel installation - src doesnt exist quick question.
Found similar cases but they dont worked for me.
Following this guide https://babeljs.io/docs/setup/#installation I´m trying to install Babel Cli.
but running babel from a command in package.json configured like
"scripts": {
    "build": "babel src -d lib"
},

throwing an error
> babel src -d lib

src doesn't exist
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! my-package@1.0.0 build: `babel src -d lib`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the my-package@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely
additional logging output above.

npm ERR! A complete log of this run can be found in:

when running the command npm run build
I´ve already installed babel-preset-env and configured a .babelrc
npm version 6.1.0
Do you know where src doesn't exist comes from ?
Thanks!

A: src is the folder that contains the files you want to transform. Either create it and move your files there or update the command to use the folder that contains your files.
More info: https://babeljs.io/docs/usage/cli/#compile-directories


text:
Q: Understanding ARC in iOS I have this block of code I have written to test ARC. I set the string s2 as weak and assign it the value of s1. Then, I set s1 to nil. I was assuming that since this background block is executed at a later time, s2 will already be dealloced by then. But, when I run this code, the NSLog still prints the value of s2 as "123". Can someone please explain to me why that happens?
- (void)testARC {
    NSString *s1 = [NSString stringWithFormat:@"123"];
    __weak NSString *s2 = s1;
    s1 = nil;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        // what will NSLog print?
        NSLog(@"s2 = %@", s2);
    });
}

A: Two considerations:

*

*You're creating an autorelease object which isn't released until the pool is drained. If you create a non-autorelease object (or use your own autorelease pool), you won't see that behavior, e.g.:
NSString *s1 = [[NSString alloc] initWithFormat:@"123"];
__weak NSString *s2 = s1;
s1 = nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    // what will NSLog print?
    NSLog(@"s2 = %@", s2);
});

*You always should be wary of evaluating memory behavior using NSString. In this case, I don't think it matters, but in other cases NSString will do all sorts of optimizations and caching that can affect the behavior. I'd suggest testing this with NSObject or an NSObject subclass.


text:
Q: Rename and upload file I am using this code (Got from w3schools), i want to add random number to every image name before upload like:
<?php $randomnum =  rand(470000,900000); ?>
How can i do so?
if($_FILES["image"]){
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
$error =  "Sorry, file already exists. Rename the file and try again.";
$uploadOk = 0;
}
if ($_FILES["image"]["size"] > 500000) {
$error =  "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$error =  "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
} else {
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
    $image = basename($_FILES["image"]["name"]);
} else {
    $error = "Sorry, there was an error uploading your file.";
}
}
}

A: I have used this in my project.
$name = round(microtime(true)) . substr(md5(rand()), 0, 4) . '.' . end($temp);
$newfilename = 'files/uploads/' . $name;
move_uploaded_file($_FILES["image"]["tmp_name"], $newfilename);


text:
Q: dynamically divs creation on the basis of table records I have a page in which i have to display a list of job boards. I have a table named as job_board in which i all the record of 10 to 12 may be more job boards is saved. I want to display a page in which there will be a div as container and inside that div i want to display these job boards, each in a separate div(side by side). At the moment i am trying this loop:
  foreach($this->test as $value)
{
            $variable=null;

             echo $variable .='

';
              $variable .=$value["job_board_id"] . '
';
              $variable .=$value["name"] . '
';
              $variable .=$value["description"] . '
';
              $variable .=$value["price"]. '
';
              $variable .= $value["enabled"]. '
';

              echo $variable;
}

The columns in my table are id,name,description,price,url)
I want to display it in the small divs which are inside the main div "container"

A: if you wish to print each line in one div with span you can try with this
 echo $variable .='

';
              $variable .= '
'.$value["job_board_id"] . '';
              $variable .= ''.$value["name"] . '';
              $variable .= ''.$value["description"] . '';
              $variable .= ''.$value["price"]. '';
              $variable .= ''.$value["enabled"]. '
';

              echo $variable;

And for second loop after print $variable please assign with blank like $variable = '';
Also try to make more attractive with css.
let me know if i can help you further.

A: If you want show divs side by side, please try float. The code may goes like this:
foreach($this->test as $value)
{
          $variable=null;
          $variable .='
';
          $variable .=$value["job_board_id"] . '
';
          $variable .=$value["name"] . '
';
          $variable .=$value["description"] . '
';
          $variable .=$value["price"]. '
';
          $variable .= $value["enabled"]. '
';
          $variable .='
';
          echo $variable;
}

And, the class 'cell' will be defined in your CSS file like below:


text:
Q: Use regex as input file path in Logstash I would like to parse a directory of logs files with logstash.
When the logs are formatted like this :
server-20140604.log
server-20140603.log
server-20140602.log

There is no problem, I am using globs like this :
input {
 file {
   path=>["D:/*.log"]
 }
}

But my logs are formatted like this :
server.log
server.log.1
server.log.2
client.log
client.log.1
client.log.2

So I would like to know how to tell to logstash to parse in the folder all the files starting with "server" expression in their names. I really need to do it like that, because I have other files in the folder (i.e client logs) that I don't want to parse but also cannot remove from the folder.

A: With this configuration I can only parse all the log files start with prefix server.
input {
        file {
                path => ["D:/server*"]
        }
}

output {
    stdout {
                codec => rubydebug
        }
}

I think the possible problem you have meet is the start_position config. It means that where does logstash start to read the logs. Please refer to here. Remember this option only modifies first contact situations where a file is new and not seen before. If a file has already been seen before, this option has no effect.
When you stop logstash, logstash will save a .sincedb* in your home directory. Next time you start it, logstash will start read the file according to .sindb*. If you do not input new logs to server.log, logstash will never parse the old logs.
What you can try to do is delete all the .sincedb before you start logstash and add start_posistion to your config. In your comment you have say if you overwrite the server.log logstash can parse the file from beginning, it is because logstash detect it as a new file and the .sincedb* do not save any information about this file. So logstash will parse it! You can try to find out your .sincedb and try to delete it.


text:
Q: Making a follow button, Ajax not talking to php I'm trying to make a user follow button using AJAX, but for some reason my AJAX isn't talking to my jk_user_follow function and setting the wp_set_object_terms.
PHP
function register_user_taxonomy(){
    register_taxonomy( 'follow' , 'user' , $args );
}
add_action( 'init', 'register_user_taxonomy' );

/**
* (1) Enqueue scripts for follow system
*/
function follow_scripts() {
    wp_enqueue_script( 'jk_follow_user', get_template_directory_uri().'/js/follow.js',                     array('jquery'), '1.0', 1 );
    wp_localize_script( 'jk_follow_user', 'ajax_var', array(
        'url'   => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce( 'ajax-nonce' )
    ) );
}
add_action( 'init', 'follow_scripts' );

/**
* (2) follow the user
*/
add_action( 'wp_ajax_jk-user-follow', 'jk_user_follow' );
function jk_user_follow() {

    $nonce = $_POST['nonce'];
    if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
        die ( 'Nope!' );

    if ( isset( $_POST['jk_user_follow'] ) ) {

        $author_id = get_the_author_meta( 'nickname' ); // get authors name

        if ( is_user_logged_in() ) { // user is logged in
            $user_id = get_current_user_id(); // current user
            wp_set_object_terms( $user_id, $author_id, 'follow', true ); // Follow the author
            echo "ok";
        } else {
            echo "login";
        }

    }
    exit;
}

Front-End Button
function getAuthorFollowLink( $author_id ) {
    $author     = get_the_author_meta( 'nickname' );
    $user_ID    = get_current_user_id();
    $termId     = get_term_by( 'slug', $author, 'follow' ); // get the term id from author
    $termId     = $termId->term_id;
    $followers  = get_objects_in_term( $termId, 'follow' ); // count followers in author term
    $count      = count( $followers );

    if ( is_object_in_term( $user_ID, 'follow', $author ) ) {
        $class = esc_attr( ' following' );
        $title = esc_attr( 'Unfollow' );
        $heart = 'Following';
    } else {
        $class = esc_attr( '' );
        $title = esc_attr( 'Like' );
        $heart = 'Follow';
    }

    $output = ''.$heart.' '.$count.'';
    return $output;
}

JQuery Update
$(function(){
$('.jk-user-follow').on('click', function(e){
e.preventDefault();
$('.jk-user-follow').fadeOut(300);
$post = jQuery(this);
author = $post.data('author');
$.ajax({
  type: "post",
  url: ajax_var.url,
  data : "action=jk-user-follow&nonce="+ajax_var.nonce+"&jk_user_follow=&author"+author,
  success: function(response) {
    // You can put any code here to run if the response is successful.

    // This will allow you to see the response
    console.log(response);
  }
 });
});


text:
Q: PowerShell edit line in config file and save I'm trying to edit 2 specific lines and then save, I'm having issues with the Set-Content it would overwrite everything besides the last changed line
CODE
$configPath = "C:\config.ini"

foreach($line in Get-Content $configPath) {
    if($line -like "option1" -or $line -like "option2"){
        $line -replace ("OldValue", "NewValue") | Set-Content -Path $configPath
    }
}

A: To make changes to content of a file it is generally handled by

*

*getting the full contents of the file into a collection

*modifying the collection

*overwriting the file with the modified collection

    $configPath = "C:\config.ini"

    # capture both modified and unchanged lines in $newContent variable
    $newContent = foreach($line in Get-Content $configPath) {
        if($line -match "option(1|2)"){
            # modify the line
            $line -replace "OldValue", "NewValue"
        }
        else {
            # leave the line unmodified
            $line
        }
    }

    $newContent | Set-Content -Path $configPath

Switch is nice to use for these tasks
$configPath = "C:\config.ini"

$newContent = switch -regex -File $configPath {
    # if option1 or option2 found on line do replace and output to variable
    'option(1|2)' { $_ -replace "OldValue", "NewValue" }
    # Otherwise output line untouched
    Default { $_ }
}

$newContent | Set-Content -Path $configPath

Lastly, as Theo mentioned in comments, for ini files it might be better to use one of the existing ini modules available

A: The problem is that you are trying to do this on the fly.
Like you are opening the file, at the same time reading its content, and during that, you are trying to write it.
So the main idea, that you will get its content to a variable first.
Then the content is located inside a variable, and the file is already closed, and you can interact with its content as you do.
$configPath = "C:\config.ini"
$content = Get-Content $configPath

$newContent = $content -replace $line, "NewValue"
$newContent | Set-Content -Path $configPath


text:
Q: Unable to upload javascript file to joomla 3 I have recently started working with joomla.
While using Direct php plugin, which allows to execute php code from the article itself, I needed to invoke custom javascript.
But, in order to invoke custom javascript, I have to upload the javascript file to joomla, which I am unable to do.

Everytime, i try, i am getting the following error This file type is not supported.

I have tried adding js , JS to Legal Extensions (File Types), but it doesn't seem to work.
Attached is the screenshot of Joomla Media Manager Settings

*

*Joomla Version :- Joomla! 3.5.0-beta6-dev Beta

*Joomla Platform Version :- Joomla Platform 13.1.0 Stable

*Php :- 5.4

*Db :- postgresql

Any leads will be appreciated.

A: what is the editor you are using for joomla (JCE editor allows you to use and run JavaScript right out of the box.

A: Yes you can add an external Javascript file Joomla. You can also add it to an article. But first you must upload the external Javascript file. in order to do this you must first go to extensions and select templates. To the left you will see another menu that says Styles and templates,  select templates. then selected template you're working with. On the top you will see a menu item that will says new file, click on it a pop-up window will appear choose upload file  then choose the Js folder. Once you are sure that everything is correct you can click the "upload button". You can now click close because you are done with it.
Then fallow this link to add external file to article
Joomla 3.x: How to add or Link to a external javascript file


text:
Q: Sanitize apex and user input I'm trying to sanitize user input in PHP for saving data in a query. The problem are special chars like ' or ".
I tried with htmlspecialchars(), addslashes() and mysql_real_escape_string() but they aren't working. What's the best and fast way to do it?

A: You can use APEX_ESCAPE package to "sanitize" your data. Try the below
select apex_escape.html_whitelist('
Hello
') from dual;


text:
Q: Как правильно прописать nth-child? Привет всем, хочу cдвинуть текст немного ниже в 3 и 4 с помощью nth-child, что бы не прописывать класс, чего то не получается, просветите.

.how_pay {
  .item {
    text-align: center;
    position: relative;
    display: block;
    margin: 10px 0;
    a {
      position: absolute;
      display: block;
      width: 120px;
      bottom: 50px;
      left: 50px;
      font-size: rem-calc(15);
      color: $t-gray;
      font-weight: bolder;
      line-height: 1.1;
      transition: all .25s ease;
      &:hover {
        color: #008932;}
      }
   }
  .item {
    &:nth-child(3) a, &:nth-child(4) a {
        bottom: 40px;
    }
}
}

A: Правильно его вообще не прописывать и не пихать absolute'ы куда не следует.

section {
  text-align: center;
  counter-reset: i;
}

a {
  display: inline-block;
  vertical-align: middle;
  width: 115px;
  height: 115px;
  border-radius: 50%;
  border: 1px solid;
}

a:before {
  counter-increment: i;
  content: counter(i);
  display: block;
  font-size: 3em;
}

  Выбрать квартиру
  Выбрать способ оплаты
  Заключить договор и оплатить
  Мы готовим все документы
  Вы владелец квартиры

A: .how_pay {
    .item {
        text-align: center;
        position: relative;
        display: block;
        margin: 10px 0;
        a {
            position: absolute;
            display: block;
            width: 120px;
            bottom: 50px;
            left: 50px;
            font-size: rem-calc(15);
            color: $t-gray;
            font-weight: bolder;
            line-height: 1.1;
            transition: all .25s ease;
            &:nth-of-type(3),
            &:nth-of-type(4) {
                bottom: 40px;
            }
            &:hover {
                color: #008932;
            }
        }
    }
}

и миксин на rem вот такой красивее будет:
@mixin x-rem($property, $values) {
    $base-font-size: 16px;
    $px-values: ();
    $rem-values: ();
    @each $value in $values {
        @if $value==0 or $value==0px {
            $px-values: join($px-values, 0);
            $rem-values: join($rem-values, 0);
        }
        @else if type-of($value)==number and not unitless($value) and (unit($value)==px) {
            $new-rem-value: $value / $base-font-size;
            $px-values: join($px-values, round($value));
            $rem-values: join($rem-values, #{$new-rem-value}rem);
        }
        @else {
            $px-values: join($px-values, round($value * $base-font-size));
            $rem-values: join($rem-values, #{$value}rem);
        }
    }
    #{$property}: $px-values;
    #{$property}: $rem-values;
}

A: А вот и вариант с вертикальным центрированием.

section {
  text-align: center;
  counter-reset: i;
}

a {
  display: inline-block;
  vertical-align: middle;
  width: 115px;
  height: 115px;
  border-radius: 50%;
  border: 1px solid;
  overflow: hidden;
}

a:before {
  counter-increment: i;
  content: counter(i);
  display: block;
  font-size: 3em;
}

div {
  height: 56px;
  background: antiquewhite;
  padding-bottom: 4px;
}

div:before, span {
  display: inline-block;
  vertical-align: middle;
}

div:before {
  content: "";
  height: 100%;
}

Выбрать квартиру

Выбрать способ оплаты

Заключить договор и оплатить

Мы готовим все документы

Вы владелец квартиры

Или так:

section {
  text-align: center;
  counter-reset: i;
}

a {
  display: inline-block;
  vertical-align: middle;
  width: 115px;
  height: 115px;
  border-radius: 50%;
  border: 1px solid;
  overflow: hidden;
  background: linear-gradient(to bottom, white 0, white 45%, antiquewhite 45%, antiquewhite 100%);
}

a:before {
  counter-increment: i;
  content: counter(i);
  display: block;
  font-size: 3em;
}

a:after, span {
  display: inline-block;
  vertical-align: middle;
}

a:after {
  content: "";
  height: 56px;
}

  Выбрать квартиру
  Выбрать способ оплаты
  Заключить договор и оплатить
  Мы готовим все документы
  Вы владелец квартиры


text:
Q: How to send html in document.write() in ajax function? I've recently started using Ajax and javascript.
This is my ajax function:
   var saveForm = function () {
var form = $(this);
$.ajax({
  url: form.attr("action"),
  data: form.serialize(),
  type: form.attr("method"),
  dataType: 'json',
  success: function (data) {
    if (data.form_is_valid) {

      w=window.open();
      w.document.write($("#book-table tbody").html(data.html_book_list));
      w.print();
      w.close();

      $("#book-table tbody").html(data.html_book_list);

      $("#modal-book").modal("hide");

    }
    else {
      $("#modal-book .modal-content").html(data.html_form);
    }
  }
});
return false;
};

In the output it only displays [object Object] and no html is getting passed.
How can I pass correct html to the document.write() and how can I access the "data" to perform modification?

A: $('#element').html() returns a string of the content that exists at the target.
$('#element').html('some html') returns the HTML object that has the new code added to it.

$('#output').html( $('#test').html() );

// returns a string of the HTML inside
console.log( $('#test3').html() );
// returns the object being targeted
console.log( $('#test2').html('some html') );

Test content 123

Test Content 456

Test Content 789


text:
Q: Return name of current foreground app in Pythonista IOS Iphone Background: I am creating automation of my phone that only allows apps to be run based on certain criteria. This automation is for the purpose of preventing bad habits like constant social media use. E.G. my automation would block accessing Instagram multiple times within a 30 minute time period. It would initially allow Instagram at 10:00 pm then if I try to open Instagram from 10:00 pm to 10:29 pm it would immediately close the app thus preventing me from using Instagram too much.
Code and comments: the ios automation setup
However with the automation in shortcuts on the iPhone, I can only know what app is open if I create individual automation for EVERY SINGLE APP on my phone and hardcode a name. This is extremely impractical especially since I want to share this automation and code with friends that also want to cut back on phone usage. list of apps that trigger this automation when opened.
The code to be run after the automation is triggered (any app is opened). Calls a Pythonista script that retrieves the name of the most recently opened app E.G. Instagram and pastes it to the clipboard. The shortcuts code then retrieves the name from the clipboard and pastes it to a shortcut that determines whether the app is allowed to be used at this time.
the code:
1st part of ios shortcuts code to be run on automation trigger
2nd part of ios shortcuts code
My question is how can I return the name of the most recently opened app within a Pythonista script. I am open to answers that incorporate different languages like Swift or javascript but I have no experience with those and I don't know how to incorporate them into my automation like I can call Pythonista scripts within ios shortcuts.


text:
Q: Office JS API for OneNote - Missing APIs? Office JS API for OneNote... Love it, but I am missing some critical things. Can someone comment?
I got a paragraph, type is RichText. But, I could not find in the API the style of the rich text. In my case, I want to know if it is a Header 1,2,3... or Quote, etc.
Same-page linking: In OneNote desktop I can right click any text and copy link to that specific paragraph. Clicking that link later will take me directly to that paragraph. However, I did not find an API that can navigate directly to a paragraph, the only one I could find navigates to a page: navigateToPage(page: Page)    and navigateToPageWithClientUrl(url: string)
If that even possible? Also, I noticed these links don't work at all in the web version of OneNote, but that's a different story I guess.
I am building (a free!) TOC add-in, you can put at the top of your page and will potentially show all headers with links to the header in the page. However, the lack of the above capabilities make it impossible for such a simple add-in to work (or, at least I thought it is a very basic and simple one...)
Any help will be greatly appreciated!!! Like I said, if I get these 2 issues resolved - the add-in will be available for free.
https://dev.office.com/reference/add-ins/onenote/paragraph?product=onenote

A: Sounds like a cool add-in!
You can use the getHtml method on richText to get the style. There is an example in this answer.
OneNote Add in: Getting HTML content
As for creating links to a specific paragraph, OneNote add ins do not expose the capability of doing that. You can add a request in our uservoice. The only supported capability is to navigate to a page.
https://onenote.uservoice.com/forums/245490-onenote-developer-apis
As for links that work in OneNote online, the "webUrl" property in a page will contain a link that works in OneNote online.
https://github.com/OfficeDev/office-js-docs/blob/master/reference/onenote/page.md

A: Thanks for feedback. We will update the documentations.
There is currently no way to scroll to any region in the page.


text:
Q: iOS Auto Renewable Subscriptions veirfyReceipt returns different receipts base64 than device I'm trying to implement Auto Renewable Subscriptions. My app can be used across different devices (Android, Web) so I needed to implement the Status Polling technique in order to acknowledge my server when App Store manages to renew an expired subscription.
The receipt is being verified on my server as elaborated here.
On each transaction made on the device, I update the user's entry on the database for the last_receipt_base64 field during the receipt verification process.
On each status polling, I want to update the last_receipt_base64 and expired_date fields, so I take the last_receipt_base64 and send it to apple's /verifyReceipt route. But each time it puts a different receipt (base64) under the 'latest_receipt' key. Even more, the length of the returned (from /verifyReceipt) receipt base 64 is strangely much shorter than the receipt sent from the device (35,000 chars receipt from device, 6000 chars receipt returned from /verifyReceipt). Why is that?
I want to update the entries on my database on each status pole if there's a change but the data keeps changing! Also the extreme length differences between the receipts from the device and /verifyReceipt makes me worried that the receipt might be rejected someday, If a user won't login the iOS app for long time.
Anyway I'm a bit confused, and the docs aren't very good... Some guidelines will be helpful.

A: Gal Shahar!
We are also using Apple server notifications for updating subscription status in our subscriptions managing platform.
Receipt in status poll notifications is not the one that you are looking for. You should store receipts that are sent directly from device.
You should rely only on original_transaction_id and find your customer by this id.
And by the way, there is no need to update your base64 receipt as it will always give you the latest transactions.
I could recommend you reading this article from our blog: https://blog.apphud.com/subscriptions-notifications/
Let us know, if you need help. Thanks!


text:
Q: SQL : oracle 11g, Split the result set into 2 subset and display side by side I did unpivot that transformed columns to rows. http://sqlfiddle.com/#!4/fc489/6
now I would like to display to student information side by side something like
AVGGPA      1                    1
COURSEAVG   101.5                101.5
STUDENTNAME Jilly Doe            John Doe

Any hints??

A: If you really only have two subsets to worry about, a simple way to build on what you have so far is:
SELECT labeln,
  MAX(CASE WHEN rn = 1 THEN value1 END) AS col1,
  MAX(CASE WHEN rn = 2 THEN value1 END) AS col2
FROM (
  SELECT * FROM (
    SELECT to_char(avg(g1.grade)) AS avgGPa,
      to_char(avg(s1.course)) AS courseAVG,
      s1.student_name AS studentName,
      ROW_NUMBER() OVER (PARTITION BY NULL ORDER BY s1.student_name) AS RN
    FROM student s1
    JOIN grade g1 ON s1.student_name = g1.student_name
    GROUP BY s1.student_name
  )
  UNPIVOT (value1 FOR labeln IN (avggpa, courseavg, studentname))
)
GROUP BY labeln
ORDER BY labeln;

SQL Fiddle
It's basically a manual pivot; adding a row_number() to your original query, and then using that to decide which column the corresponding values go in, with max() to collapse the blanks. You can easily add more columns by duplicating the max(case(...)) bit and just changing the rn check. But you have to know how many columns you need to end up with; or overestimate and have some blanks at the end.
In theory you could use an actual pivot() but you don't know the values in advance, so you don't have values to use in the for clause. You could maybe use an XML approach, but that's maybe overkill; depending on what your real-world usage for this would be.


text:
Q: Can I pass value of forward declared enum? When passing forward declared struct or a class, one has to pass it to a function through a reference or a pointer.
But, what can be done with a forward declared enum? Does it also have to be passed through a reference or a pointer? Or, can it be passed with a value?
Next example compiles fine using g++ 4.6.1 :
#include <iostream>

enum class E;

void foo( const E e );

enum class E
{
  V1,
  V2
};

void foo( const E e )
{
  switch ( e )
  {
    case E::V1 :
      std::cout << "V1"<<std::endl;
      break;
    case E::V2 :
      std::cout << "V2"<<std::endl;
      break;
    default:
      ;
  }
}

int main()
{
  foo( E::V1);
  foo( E::V2);
}

To build :
g++ gy.cpp -Wall -Wextra -pedantic -std=c++0x -O3

Is the above standard compliant, or is it using an extension?

A: A declared enum, even if you don't specify the enumerators (what the standard calls an opaque-enum-declaration) is a complete type, so it can be used everywhere.
For completeness, here's a quote from paragraph 3 of §7.2:

An opaque-enum-declaration is either a redeclaration of an enumeration
  in the current scope or a declaration of a new enumeration. [Note: An
  enumeration declared by an opaque-enum-declaration has fixed
  underlying type and is a complete type. The list of enumerators can be
  provided in a later redeclaration with an enum-specifier. —end note ]

And the grammar for opaque-enum-declaration, from paragraph one of the same §7.2:

opaque-enum-declaration:

enum-key attribute-specifier-seqopt identifier enum-baseopt;


text:
Q: Can we make a rocket with acceleration 17-40 $g$? I have read that humans can survive 17g for several minutes, and 40g for a few fractions of a second. There has been much talk about a 1g rocket and its relativistic capabilities, but even with that a trip to Alpha Centauri would still take more than a year.
What if the rocket slowly accelerates up to 17g for a few minutes, and then 40g for only a few nanoseconds, and then the rate of acceleration stalls to more bearable levels, before ramping back up, over and over again. The human crew would never stay at higher g-forces long enough to kill them, but the ship would gain speed much faster, and more relativist effects would be experienced, making the trip shorter for the crew.

A: A rocket ride from hell.

What if the rocket slowly accelerates up to 17g for a few minutes

Ouch.  I mean that would be very high for a few minutes.  I suspect it would cause blackouts at best and death or serious injury at worst.  Fighter piolts sustain much lower gees for only very short periods at a time.  And they are exhausting.
To illustrate this try to think about the differece between carrying your normal personal weight and then what would happen your body if I dump 16 more people on top of you as well.  How long would you survive that ?

and then 40g for only a few nanoseconds

In a nanosecond your speed will barely change at all.  It's utterly pointless.  Any period of time for which this actually achieves anything would be death for the crew.

and then the rate of acceleration stalls to more bearable levels, before ramping back up, over and over again.

So essentially you want an extremely violent roller-coaster that can kill for the entire trip.
Not for me thanks.  I suspect volunteers will be in very short supply.

A: It is in principle doable if you are not carrying along the fuel. The only viable option I am aware that would be consistent with known laws of physics are huge laser sails pushed from even bigger orbital laser arrays, capturing and converting TeraWatts of solar energy into coherent Gaussian beams (which have the smallest beam divergence of all coherent wavefronts)


text:
Q: How to get listoffigures as a horizontal list? Is there a way to have \listoffigures displayed as a horizontal list of figure number, caption and page number divided by |?

Fig. 1: Caption of Figure 1 | 2; Fig. 2: Caption of Figure 2 | 4; Fig. 3: Caption of Figure 3 | 82; Fig. 4: Caption of Figure 4 | 282

And is there also a way to suppress the page numbers? e.g.

Fig. 1: Caption of Figure 1; Fig. 2: Caption of Figure 2 Fig. 3: Caption of Figure 3; Fig. 4: Caption of Figure 4

As MWE I provide
\documentclass{scrbook}
\usepackage{graphicx}
\usepackage{caption}
\makeatletter
\AtBeginDocument{
\renewcommand*\l@figure{\@dottedtocline{1}{2.4cm}{.5cm}}
\renewcommand{\@dotsep}{10000}
}
\makeatother
\renewcommand{\thefigure}{\bfseries\arabic{figure}}

\begin{document}

    \captionof{figure}{example-image-a}
    \captionof{figure}{example-image-b}
    \captionof{figure}{example-image-c}

\listoffigures
\end{document}

A: You only need a custom version of \numberline:
\def\numberline#1#2{%
  \lofsep\space{\let\bfseries\relax Fig. #1: #2}
}

\lofsep will be the vertical line and \let\bfseries\relax because by default \bfseries gets written into the .lof file. At last you need to say \let\l@figure\@firstoftwo, so the page number simply is forgotten.

Complete Code
\documentclass{scrbook}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{etoolbox}

\makeatletter
\let\l@figure\@firstoftwo
\let\ltx@numberline\numberline
\preto\listoffigures{
  \def\numberline#1#2{%
    \lofsep\space{\let\bfseries\relax Fig. #1: #2}
  }
  \def\lofsep{\def\lofsep{\(\mid\)}}
}
\appto\listoffigures{\let\numberline\ltx@numberline}
\makeatother

\renewcommand*\thefigure{\bfseries\arabic{figure}}

\begin{document}
\captionof{figure}{example-image-a}
\captionof{figure}{example-image-b}
\captionof{figure}{example-image-c}
\listoffigures
\end{document}