text:
Q: Why am I unable to scrape values from a Hidden tooltip of a Highchart using selenium python? I've particularly asked a couple of questions on the same topic before asking it one final time.
To begin with, I am scraping values from https://www.similarweb.com/website/zalando.de/#overview
I am trying to scrape the contents from a graph. Take a look at this highchart graph.

I want to scrape value like its value as : 27,100,000. from the hidden tooltip. At present I am able to scrape the Months as [Nov '20,....Apr '21], However, I am unable to scrape its values.
Here's my complete code:
def website_monitoring():
    websites = ['https://www.similarweb.com/website/zalando.de/#overview']

    options = webdriver.ChromeOptions()
    options.add_argument('start-maximized')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option("useAutomationExtension", False)

    browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)
    for crawler in websites:
        browser.get(crawler)
        wait = WebDriverWait(browser, 10)

        website_names = browser.find_element_by_xpath('/html/body/div[1]/main/div/div/section[1]/div[1]/div/div[1]/a').get_attribute("href")
        total_visits = browser.find_element_by_xpath('/html/body/div[1]/main/div/div/div[2]/div[2]/div/div[3]/div/div/div/div[2]/div/span[2]/span[1]').text

        tooltip = wait.until(EC.presence_of_element_located((By.XPATH, "//*[local-name() = 'svg']/*[local-name()='g'][8]/*[local-name()='text']")))
        ActionChains(browser).move_to_element(tooltip).perform()
        month_value = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//*[local-name() = 'svg']/*[local-name()='g' and @class='highcharts-tooltip']/*[local-name()='text']")))
        values = [elem.text for elem in month_value]
        print('VALUES-->', values)
        months = browser.find_elements(By.XPATH, "//*[local-name() = 'svg']/*[local-name()='g'][6]/*/*")
        for date in months:
            print(date.text)

        # printing all scraped data
        print('Website Names:', website_names)
        print('Total visits:', total_visits)

if __name__ == "__main__":
    website_monitoring()

The output that I presently get:
VALUES--> ['']
Nov '20
Dec '20
Jan '21
Feb '21
Mar '21
Apr '21

The output that I want:
VALUES--> ['27,100,000', .....]
Nov '20
Dec '20
Jan '21
Feb '21
Mar '21
Apr '21

I am stuck on this issue since 2 days and nothing sofar has worked upon trying. Please, Please help!
EDIT: I also tried a method to check if a csv file exists upon inspecting the page and then going to the networks tab as Highcharts graph usually store a csv file but I Guess the site has blocked it. Is this possible by using a json or lxml?

A: I have a solution that works. I took the time to identify a way to hover over each of the points, print the data, and move to the next.  This could be way cleaner, but it works.  Here's my python file:
from selenium import webdriver
import chromedriver_autoinstaller
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

def website_monitoring():
    chromedriver_autoinstaller.install()

    websites = ['https://www.similarweb.com/website/zalando.de/#overview']

    options = webdriver.ChromeOptions()
    options.add_argument('start-maximized')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option("useAutomationExtension", False)

    browser = webdriver.Chrome(options=options)

    def stringToPrint():
        return browser.find_element_by_css_selector('g.highcharts-tooltip > text > tspan:nth-child(1)').text + ': ' + browser.find_element_by_css_selector('tspan:nth-child(3)').text

    for crawler in websites:
        browser.get(crawler)
        wait = WebDriverWait(browser, 10)

        website_names = browser.find_element_by_xpath('/html/body/div[1]/main/div/div/section[1]/div[1]/div/div[1]/a').get_attribute("href")
        total_visits = browser.find_element_by_xpath('/html/body/div[1]/main/div/div/div[2]/div[2]/div/div[3]/div/div/div/div[2]/div/span[2]/span[1]').text

        highchartElement = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'g:nth-child(8) > path:nth-child(3)')))

        ActionChains(browser).move_to_element(highchartElement).move_by_offset(-300,0).perform()
        print(stringToPrint())
        ActionChains(browser).move_by_offset(120,-10).perform()
        print(stringToPrint())
        ActionChains(browser).move_by_offset(120,0).perform()
        print(stringToPrint())
        ActionChains(browser).move_by_offset(120,-10).perform()
        print(stringToPrint())
        ActionChains(browser).move_by_offset(120,10).perform()
        print(stringToPrint())
        ActionChains(browser).move_by_offset(120,0).perform()
        print(stringToPrint())

        # printing all scraped data
        print('Website Names:', website_names)
        print('Total visits:', total_visits)

if __name__ == "__main__":
    website_monitoring()

And here's the console output:
November, 2020: 29,900,000
December, 2020: 27,100,000
January, 2020: 26,900,000
February, 2021: 22,600,000
March, 2021: 24,700,000
April, 2021: 26,200,000
Website Names: http://zalando.de/
Total visits: 19.94M


text:
Q: Print disk space with df, with headers, but only one particular row I have the following df -h output:
Filesystem      Size  Used Avail Use% Mounted on
dev             7,8G     0  7,8G   0% /dev
run             7,8G  1,8M  7,8G   1% /run
/dev/nvme0n1p5   93G   40G   49G  45% /
tmpfs           7,8G  157M  7,7G   2% /dev/shm
tmpfs           7,8G   48M  7,8G   1% /tmp
/dev/nvme0n1p4  204G  173G   31G  86% /run/media/test/drive
/dev/nvme0n1p1   96M   33M   64M  35% /boot/efi
tmpfs           1,6G   68K  1,6G   1% /run/user/1000

I want to print only the root partition (/dev/nvme0n1p5) with headers - i.e. Size, Used Space, Available Space, etc.

A: You can ask df to only show the free space on a given device:
$ df -h /dev/nvme0n1p5
Filesystem      Size  Used Avail Use% Mounted on
/dev/nvme0n1p5   93G   40G   49G  45% /

redpajama_set_name: RedPajamaStackExchange


text:
Q: Emacs-like keybindings globally I'm trying to emulate behaviour I get from KeyRemap4MacBook on Mac OS X. It lets me remap control-m to Enter, for instance, globally.
Is this possible with X/GNOME? Seems like xmodmap is not suitable for remapping key combinations. I tried xbindkeys to bind control-m to xdotool key Return, but it emits control-return. I tried xdotool keyup control; xdotool key Return; xdotool keydown control but it stills behaves unpredictably.
Any ideas? Kernel level hacks?

A: I strugled myself with similar question and discovered autokey which is just great:
sudo add-apt-repository ppa:cdekter/ppa
sudo apt-get update
sudo apt-get install autokey-gtk

Just put <enter> as the phrase and set the shortcut to control-m. Works perfectly for me.


text:
Q: Добавление классов при нахождении в ссылках определенных фраз Есть задача из разных ссылок сделать форматирование чтоб можно было с помощью css сделать так чтоб они были по порядку пример
движок формирует такого вида блок

и на каждой странице динамически меняется их положение
но слова kuzov , dvizhok и тд всегда фигурируют возможно ли как прогонять этот список постоянно и по фразам в ссылке присваивать класс например:

и так далее
Я не совсем разбираюсь в javascript
Пытался по образцу но не получается именно фразу найти
window.onload = function() {
const template = ( link, title ) => `<li class="link-list-item"><a href="${ link }">${ title }</a></li>`;

let messages = document.body.querySelectorAll( '.Tooltip' );

let html = Array.from( messages ).reduce( (result, element) => {
  let text = element.innerText;
  let titles = text.match( /dvizhok/g );

  if( titles ){
    let link = element.querySelector('.Tooltip').href;

    return result += template( link, titles[1] ) + '\n';
  }

  return result;
}, "" );

let linkList = document.body.querySelector('.link-list');
linkList.innerHTML = html;}

но это скорей всего не в ту степь потому что нужно оставлять на месте просто добавлять класс , и еще не понимаю как с кешированием это все сделать чтоб человек не видел что это происходит пока страница грузится

A:

Array.from(document.querySelectorAll('#target a')).forEach(a => {
  if(a.href.includes('threads/')){
    a.classList.add(a.href.match(/[a-z]+-[a-z]+-([a-z]+)/i)[1]);
  }
});

A: Можно использовать в CSS селекторы по аттрибутам вместо классов.

a[href*=engine] {
  color: green;
}
Engine Link

Или использовать их же, для поиска нужных ссылок:

var keywords = ['dvizhok', 'kuzov', 'tuning', 'zvik', 'electrika'];
keywords.forEach(word => {
  document.querySelectorAll('a[href*='+word+']')
    .forEach(el => el.classList.add(word));
})
.kuzov{color: red;}
.tuning{color: green;}
.zvik{color: yellow;}
.electrika{color: black;}

1

2

3

4


text:
Q: When to choose webservices? I'd like to give external access to a web application. Several applications on many clients will use this service extensively (hopefully), which will always lead to CRUD functions on a database.
Is a webservice always the first choice? Is there any rule of thumb when to choose webservices, sockets, etc?

A: It really depends on who your clients are, what kind of performance are you looking at, how well your clients know the technologies.
Sockets etc might give you a good performance speed but development time might increase for both, you and your clients.
SOAP web services established a standard quite some time back but now people are using REST web services more because of its simplicity and less overhead.
I am heavily impressed by the RESTful webservices offered by twilio
I am sure that Twilio is receiving hundreds of thousands of calls a day and they are performing just well.
Have a look at the following articles for more understanding about them
http://www.ibm.com/developerworks/webservices/library/ws-restful/
http://grails.org/doc/1.0.x/guide/13.%20Web%20Services.html

A: The big benefit of web services is the ease of use and the predefined interface, but they are "slower" compared to low level socket communication, because for example the XML Requests/Respnses of a SOAP-Service needs to be created/interpreded.
So I would say if you open the service to "outsider" use web services unless speed is really the biggest concern.
Also because web services are mostly accessable through port 80 you have much less problems with proxy/firewalls than with a socket on a random other port.
If you are having a high work load cahcing is also very important because it can speed up the system dramaticaly.

A: I would choose a web services (SOAP or REST) whenever I can. It's easier to scale a web service than a home brew socket implementation and it takes less time to build a webservice.
Sockets is usually the preferred choice if you need two-way communication (I know that WCF has callbacks).

A: Webservice makes it a generic way for different type of clients and applications to exchange data also it is dependent on your architecure and infrastructure.
Socket programming is bit complex and some time may create problem in data exchange. It entirely depends on your fuctionaly requirements and architecure which should you use.
if your clients will consume this data from browsers of application then webservice is better choice.


text:
Q: Jest error: TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received null I've a weird problem with Jest v29.0.3, React v18.2.0 and Node v16.12.0 on Windows Machine v.10 Enterprise OSbuild 19042.2130 when I run jest I get this error:
node:internal/validators:119
    throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received null
    at new NodeError (node:internal/errors:371:5)
    at validateString (node:internal/validators:119:11)
    at Module.require (node:internal/modules/cjs/loader:998:3)
    at require (node:internal/modules/cjs/helpers:102:18)
    at execMethod (C:<project>\.yarn\cache\jest-worker-npm-29.2.1-f152a67b79-10365612fa.zip\node_modules\jest-worker\build\workers\processChild.js:110:16)
    at process.messageListener (C:<project>\.yarn\cache\jest-worker-npm-29.2.1-f152a67b79-10365612fa.zip\node_modules\jest-worker\build\workers\processChild.js:44:7)
    at process.emit (node:events:390:28)
    at process.emit (C:<project>\.pnp.cjs:41990:25)
    at emit (node:internal/child_process:917:12)
    at processTicksAndRejections (node:internal/process/task_queues:84:21) {
  code: 'ERR_INVALID_ARG_TYPE'
}```


text:
Q: Spatial Downscaling of global temperature in R? I am interested in spatial downscaling of global temperature to grid cell.
What I have is a vector of future annual global temperature values which I would like to downscale to (hopefully) 0.5°.
Is this possible in R?
year  Temperature
2016  0.8630774
2017  0.8924077
2018  0.9221504
2019  0.9522887
2020  0.982807
2021  1.013691

I have read about the gstat, spataEco, and gdalUtils packages for statistical downscaling using regressions.
Could someone guide/provide me with an example of downscaling the global data to a finer scale using covariates such as altitude, slope, aspect etc?


text:
Q: What stabilizes the Higgs field components against rotation? As known, the Higgs field has a 4-th grad "Mexican hat" potential, described by the formula $\nu = -\mu\phi^*\phi+\lambda(\phi^*\phi)^2$:

Where $\phi$ are the 4-vector of the components of the Higgs field and $\mu$ and  $\lambda$ are constant real values.
It means, rotating the Higgs field components doesn't require energy. Thus, its components should be easily rotable on a 4-Sphere with the radius of its current length.
Despite that, the experimental evidence shows that the Higgs field seems very stable in the whole Universe. Why it doesn't rotate even from the slightest quantum fluctuations?
Maybe the space-derivate of the Higgs field has some (probably not really negligible :-) ) energy density?

A: The Higgs potential in this two dimensional perspective
$$
V(\phi) = -\mu|\phi|^2 + \lambda|\phi|^4
$$
has derivatives
$$
\frac{dV(\phi)}{d\phi} = -\mu\phi^* + 2\lambda|\phi|^2\phi^*.
$$
That is zero for $\phi = 0$ and $|\phi|^2 = \mu/2\lambda$. This tells us the magnitude of the field, but the field is complex. There is then a degenerate set of values the field may assume
$$
\phi = \frac{\mu}{2\lambda}e^{i\phi}.
$$
This is the circle at the bottom of the Mexican hat potential. The field is in fact a pair of doublets so this two dimensional picture is expanded to four dimensions
There is this degenerate vacuum of the low energy Higgs field. This is a boson condensate that couples to the electroweak field. The fact there is this degenerate Higgs field configuration is in fact what makes the Higgs mechanism work.

A: My layman answer, after a lot of digging, is this.
The total energy density of the Higgs field is described by this formula:
$H(\phi )={\frac {1}{2}}\left|{\dot {\phi }}\right|^{2}+\left|\nabla \phi \right|^{2}+V(\left|\phi \right|)$
The second term is the sum of the squares of the gradient of the components of the Higgs field. It means, if the Higgs field changes in space, it has an energy density. And nature wants an energy minimum.


text:
Q: I can't composer install magento/extension-b2b Thank you for browsing.
I use "magento-ce-2.4.0-2020-07-24-11-08-21".
And I want to use magento/extension-b2b.
But, I got this error message.
  [InvalidArgumentException]
  Could not find a matching version of package magento/extension-b2b. Check the package spelling, your version constr
  aint and that the package is available in a stability which matches your minimum-stability (stable).

I read https://devdocs.magento.com/guides/v2.3/install-gde/prereq/connect-auth.html .
I made file "C:/Users/USER_NAME/AppData/Roaming/Composer/auth.json".
{
   "http-basic": {
      "repo.magento.com": {
         "username": "MY_PUBLIC_KEY",
         "password": "MY_PRIVATE_KEY"
      }
   }
}

Why I can't use magento/extension-b2b??

A: You can't use the extension because you haven't supplied all the arguments.
Based on https://devdocs.magento.com/guides/v2.3/comp-mgr/module-man/compman-checklist.html
and the details of the question you supplied, the reason you receive this exception is because you have failed to complete either of the listed..

*

*Prerequisites for the package

*the Module Manager checklist

*both of these lists of steps are documented in the link you supplied.
As you mentioned in the comments to your question you are required by the vendor to setup a server, as many of the prerequisite activities involve running operating system commands (CLi)
You can then either start the component manager, or upgrade the system.
This appears to be what the package is to be used for.


text:
Q: Setstate going haywire when dispatch is triggered I'm practicing building something similar to reddit using Reactjs and Firestore. However, when I click the upvote button, and trigger the dispatch to increate the score of the post, the post re-renders and component's state's id property becomes undefined.
A screenshot of my console log where id magically becomes undefined :(

class PostCard extends Component {

  state = {
    id: this.props.post.id,
    score: this.props.post.score,
    upVoted: false
  }

  upVoteClicked = () => {
    console.log(this.state);
    if (!this.state.upVoted) {
      this.props.upVote(this.state);  // without this dispatch function, it works perfectly
      const currentScore = this.state.score;
      const newScore = currentScore + 1;
      this.setState({
        score: newScore,
        upVoted: true
      });
    } else {
      const currentScore = this.state.score;
      const newScore = currentScore - 1;
      this.setState({
        score: newScore,
        upVoted: false
      });
    }
  }

render() {
    console.log(this.state)
    const { title, content, imgUrl} = this.props.post;

    return(

                  arrow_drop_up

{this.props.post.score}

                {title}

{content}

    );

  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    upVote: (postDetails) => dispatch(upVote(postDetails))
  }
}

export default connect(null, mapDispatchToProps)(PostCard);

the component above is called by this parent component:
class Dashboard extends Component {

  render() {
    const { posts, auth } = this.props;
    //post cards returned here
    const list = posts && posts.map(post => {
      return(
        <PostCard key={post.id} post={post}/>
      );
    })

    if(!isLoaded(auth)) {
      var rightBar =
Loading

    } else {
      if (!auth.uid) {
        rightBar = <AuthCard/>
      } else {
        rightBar = <SignedInCard userName={auth.email}/>
      }
    }

    return(

            {list}

            {rightBar}

    );

  }

}

const mapStateToProps = (state) => {
  return {
    auth: state.firebase.auth,
    posts: state.firestore.ordered.posts
  }
}

export default compose(
  connect(mapStateToProps),
  firestoreConnect([
    { collection: 'posts', orderBy: ['score', 'desc']}
  ])
)(Dashboard);

the imported upVote action is as follow:
export const upVote = (postDetails) => {
  return (dispatch, getState) => {
    const newScore = postDetails.score + 1;
    firebase.firestore().collection('posts').doc(postDetails.id).update({
      score: newScore,
    }).then(() => {
      dispatch({type: 'UPVOTE_SUCCESS'})
    }).catch((err) => {
      dispatch({type: 'UPVOTE_ERROR', error:err})
    })
  }
}

and its reducer is as follow:
const postReducer = (state = initState, action) => {
  switch (action.type) {
    case 'UPVOTE_SUCCESS':
      console.log('Upvote Success!')
      return state;
    case 'UPVOTE_ERROR':
      console.log('Upvote Error', action.error)
      return state;
    default:
      return state;
  }
}

My questions:

*

*I heard it is not right to set properties of your state to prop's value, but has this issue got to do with that? If so, how should i restructure it?

*Is it possible to not re-render the component when I trigger the dispatch function, but still be able to update the score in the post component?


text:
Q: update View when model data changed(not database) I want test a solution  : capture image data from local camera , and display !
This is my controller:
public class DevController : Controller
{
    public byte[] Pixels = null;
    Bitmap _bmp = new Bitmap(480, 272, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
    Graphics _g = null;
    System.Timers.Timer _timer = new System.Timers.Timer(1000);

    public ActionResult Index()
    {
        if (_g == null)
            _g = Graphics.FromImage(_bmp);

        _g.Clear(Color.Black);
        _g.FillRectangle(Brushes.Blue, 2, 2, 65, 31);
        _g.DrawString("hello ", new Font("Arial", 15f), Brushes.Yellow, new PointF(5f, 5f));

        MemoryStream ms = new MemoryStream();
        _bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

        Pixels = ms.ToArray();

        _timer.AutoReset = true;
        _timer.Enabled = true;
        _timer.Elapsed += _timer_Elapsed;
        return View(this);
    }
}

use Timer to update model data:
void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    if (_g == null)
    {
        _g = Graphics.FromImage(_bmp);
    }

    _g.Clear(Color.Black);
    _g.FillRectangle(Brushes.Red, 2, 2, 65, 31);
    _g.DrawString(string.Format("hello :{0}", id++), new Font("Arial", 15f), Brushes.Yellow, new PointF(5f, 5f));

    MemoryStream ms = new MemoryStream();
    _bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
    Pixels = ms.ToArray();
}

View Code
<img src="data:image/bmp;base64,@System.Convert.ToBase64String(Model.Pixels)" id="u_image" />

The question is :
how can the View been changed automatically when the Pixels changed in the time?


text:
Q: Ajax / Jquery refresh page after variables are passed Okay so am using Ajax to send a JS variable from index.php to page2.php . Once it is set to page2.php, the database is edited while the user has been on index.php the entire time. However, I need the index.php to reload or refresh once page2.php has finished updating the database in the background. To give you a better clue, I will include some of my code.
On Index.PHP is :
Update

and
function dbchange(obj) {
    var id = $(obj).attr('id');
    $.ajax({
        type: "POST",
        url: 'page2.php',
        data: "NewID=" + id,
    });
}

So basically when they click the button that says "Update" it sends the ID of the button the page2.php and page2.php from there updates the changes the database using that info. However, the URL the user is on is:

http://website.com/index.php#

and the database has not updated for them and they have to see the annoying hash symbol in the URL. I have googled how to refresh the page in JS, and found things that either do not work or do work , but result in the variables not being sent to the PHP file. I just need it so that after it is sent to the php file, and preferably after the php file is finished, the index.php page refreshes and without the # at the end.

A: e.preventDefault() is the answer but if I may suggest:
Get rid of that inline function and add the event handler with jQuery.
$(function () {
  $('.dbchange').click (function (e) {
    e.preventDefault();
    var id = this.id;
    $.ajax({
      type: "POST",
      url: 'page2.php',
      data: {NewID: id},
      success: function(data) {
        window.location.reload();
      }
    });
  });
});

A: Remove # then replace with javascript:void(0):
Update

JS:
function dbchange(obj) {
    var id = $(obj).attr('id');
    $.ajax({
        type: "POST",
        url: 'page2.php',
        data: "NewID=" + id,
        success: function() {
            window.location.reload();
        }
    });
}


text:
Q: retrieve custom exception message in calling method Intentionally i set email as null in DAO method.it goes to Exception block in persist method in DAO class where i put custom error message "Failed to add Employee" in Custom exception class;
How to catch that error message in controller.In Controller Exception block if i use e.getMessage() am getting whole message but i want only custom error message.
Calling method(controller)

try {
    employeeDao.persist(employees);
}
catch (SpringUtilException ex) {
    System.out.println("..at line 87......."+ex.getErrorMessage());
}
catch (Exception e) {
    System.err.println("Exception returned message: " + e.getMessage());
}

Called method(DAO)

public void persist(Employees employee) throws SpringUtilException {
    try {
        employee.setEmail(null);
        em.persist(employee);
    }
    catch (EntityExistsException e) {
        throw new SpringUtilException(e, "Employee Duplicate");
    }
    catch (Exception ex) {
        System.out.println("at line 31 in DAO..");
        throw new SpringUtilException("Failed to add Employee");
    }
}

A: em.persist() just makes a transient entity persistent. It doesn't issue any insert statement.
The insert statement, which causes the exception you get, is issued at flush time. And the flush is done (in this case) at the end of the transaction, when the DAO method has already returned.
Don't rely on database constraints to validate your objects. Validate them explicitely, and don't even call persist() if the entity is invalid. The database constraints are a last resort check.


text:
Q: How To get LastActivity from ejbbered server using smack library? I am sending below request for getting the LastActivity(Last seen status) of the below user from ejabbered server using smack library in android.
try {
    Packet pk = new Packet() {

        @Override
        public String toXML() {
            // TODO Auto-generated method stub
            return "<iq from='" + Utils.createJabberUserIdByUserId(me.getUserId()) + "'" + " id='last1' "
                    + " to='" + Utils.createJabberUserIdByUserId(friendId) + "' " + " type='get'> "
                    + "<query xmlns='jabber:iq:last'/>" + "</iq>";
        }
    };
    ConnectionManager.getInstance().getXmppConnection().sendPacket(pk);
} catch (Exception e) {
    // TODO: handle exception
}

Result I got from the server is:
 <iq from="272@jabber.com">
     id="last1"
     to="274@jabber.com/64faf3314bee33c4"
     type="result"
 </iq>

But the result should be like this:
<iq from='272@jabber.com'
    id='last1'
    to='274@jabber.com/64faf3314bee33c4'
    type='result'>
  <query xmlns='jabber:iq:last' seconds='903'/>
</iq>

What am I doing wrong? please help.

A: It is usually a sign that there is no provider for the query/jabber:iq:last extension, if you don't get that child XML of an IQ in Smack. You will have to register a Provider with the Provider Manager.
BTW I recommend using the offical aSmack version, where this would been done automatically for your.

A: You can use Smack's methods to get the last time-stamp of a user, base on last activity.
Try this:
LastActivityManager lastactivity =
LastActivityManager.getInstanceFor(MyXMPPconnection);
LastActivity result = lastactivity.getLastActivity(JID); // user jid
Log.d("Last seen",result.lastActivity");

Which prints a long number in log-cat. You can convert it to Year,Month,Day,Hour and so on.
You can get the exact time-stamp with:
long current-millis = System.currentTimeMillis() - result.lastactivity;


text:
Q: I want fill an empty SharePoint-Online List using .csv file with help of JavaScript What I want to achieve is that I have a SharePoint-Online list by the name DemoList which has 5 columns.
Instead of filling the fields by clicking 'Quick Edit' I have an Excel Sheet which has the data that needs to be filled in the SP-Online List.
Now I want to import the data from Excel sheet to SPList such that even in future if I have updated the values of existing data in the Excel or Or new data is added to the list I should be to update the existing sp list instead of creating a new ist

A: Without more info I can only say this:

*

*Ask your data provider to send the data as JSON.
Otherwise:

*Your data should reside in an actual database and be imported from such a database.

*Since your question is tagged as
'SharePoint-online' I would recommend that you take a close look at  PowerApps.
Look, you are getting this data from either an internal or an external source.
If it's internal, you need to talk to your data provider about better, more sophisticated options.  If your export is coming from an external vendor or department, you may be stuck with it.

A: I would say if this is your one time requirement, just import the excel into the empty list.
And if this is your recurring requirement, create a PowerShell script to read the csv and read item one by one then insert each row in the SharePoint list.
To make this to happen automatically, configure this PS script in Windows task scheduler.
Below is the sample PowerShell script how to read CSV and create item in SharePoint online list :
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#next pass the credentials and connect to web
$siteURL = "https://hubto.sharepoint.com/sites/learnhub"
$Listname="sitecollections"
$userName = "User.onmicrosoft.com"
$PlainPassword = "Password"
$ImportFile ="D: \Powershell\LearnPowershell\Test.csv"
$password = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force

# set SharePoint Online credentials
$SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)

#Creating client context object
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$clientContext.credentials = $SPOCredentials $web = $clientContext.Web
$clientContext.load($web)

#Get the List
$List = $clientContext.Web.Lists.GetByTitle($Listname)
$clientContext.Load($List)
$clientContext.executeQuery()

$csv = Import-CSV $ImportFile foreach($row in $csv) {
    #Creat single list Items
    $ListItenCreationInformation =New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
    $NewListItem = $List.AddItem($ListItenCreationInformation)
    $NewListItem["Sourcesite"] = $row.Sourcesite
    $NewListItem["TargetSite"] = $row.TargetSite
    $NewListItem["WaveId"] = $row.WaveId
    $NewListItem["Status"] = $row.Status
    $NewListItem.Update()
    $ClientContext.ExecuteQuery()
}
Write-Host "Items Added to List Sucessfully"

Reference URL:
Steps to add items from CSV file to SharePoint Online List using PowerShell in CSOM
As an alternate, using the below Power Automate (Microsoft Flow) also can do same thing:
Read CSV file and create/update list items with logic

A: You could use the script Reading CSV file with Javascript and HTML5 File API
processDataAsObj will check the first row as header.
<!DOCTYPE html>

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

        CSV File:

    <input type="file" id="csvFileInput" onchange="handleFiles(this.files)"
           accept=".csv">


text:
Q: PropertyNotFoundException: Could not find a getter for lastMoveDate in class com.hib.objects.GameBoard I've named the class variable with camel casing.This is the class, which seems to be the culprit.
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.sql.Date;

public class GameBoard
{
    @Temporal(TemporalType.DATE)
    private Date lastMoveDate;

    /**
     * @return the lastMoveDate
     */
    public Date getLastMoveDate() {
        return lastMoveDate;
    }

    /**
     * @param lastMoveDate the lastMoveDate to set
     */
    public void setLastMoveDate(Date lastMoveDate) {
        this.lastMoveDate = lastMoveDate;
    }

}

The class has several other variables such as playerOneFk, playerTwoFk and gameLobbyFk (hibernate is able to track each setter-getter on these variables, but is throwing exceptions with the last_move_date column).
I've also tried the method names setlastMoveDate and getlastMoveDate (with no luck..), The properties.. for lastMoveDate
<property name="lastMoveDate" type="date" column="last_move_date" />

And the caught exception
SEVERE: Servlet.service() for servlet [authapi] in context with path [/TTTserver] threw exception [Servlet execution threw an exception] with root cause
org.hibernate.PropertyNotFoundException: Could not find a getter for lastMoveDate in class com.hib.objects.GameBoard
    at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:282)
    at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:275)
    at org.hibernate.mapping.Property.getGetter(Property.java:272)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:247)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:125)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:55)
    at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:56)
    at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:295)
    at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:434)
    at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:109)
    at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:55)
    at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:226)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1294)
    at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
    at com.hib.objects.HibernateUtil.<clinit>(HibernateUtil.java:24)
    at nz.ac.massey.cs.capstone.auth.authapi.processRequest(authapi.java:42)
    at nz.ac.massey.cs.capstone.auth.authapi.doGet(authapi.java:74)

A: In Hibernate, the property type "date" maps to a java.sql.Date.
If you are using a java.util.Date, you will want your property type to be "timestamp".
Using "date" as you are now will cause it to look for a getter/setter that operates on a java.sql.Date, and it won't be able to find it.
See Hibernate basic type reference (6.1.1.12 and 6.1.1.14).
Edit: Addressing some naming convention concerns:
Hibernate obeys standard bean naming conventions:

*

*Field: someField

*Property: someField (same as field name)

*Getter: getSomeField() or isSomeField() (if it is a boolean)

*Setter: setSomeField()

A: <property name="LastMoveDate" type="date" column="last_move_date" />
should work...


text:
Q: Custom STL compatible iterator for iterating over columns of a 2D array class I'm trying to define a custom STL compatible iterator for iterating over the columns of a 2D array class.  The final piece that I'm stuck on is defining the iterator difference operator:
difference_type operator-(const self_type& rhs) const noexcept

For example:
Data is stored in row major order as such (values represent the iterator difference from begin() to end() row major):
0  1  2
3  4  5
6  7  8

And I would like to access it like (values represent the iterator difference from begin() to end() now column major):
0  3  6
1  4  7
2  5  8

What I have so far only works for ~half of the elements, so obviously not correct:
difference_type operator-(const self_type& rhs) const noexcept
{
    const auto idx = ptr_ - rhs.ptr_;
    const auto row = idx / numCols_;
    const auto col = idx % numCols_;
    return row + col * numRows_;
}

For elements 0 and 7 of the row based I get:
idx = 6 - 4 = 7
row = 2 / 3 = 2
col = 2 % 3 = 1
diff = 2 + 1 * 3 = 5

which is correct.
For elements 6 and 4 of the row based I get:
idx = 6 - 4 = 2
row = 2 / 3 = 0
col = 2 % 3 = 2
diff = 0 + 2 * 3 = 6

When the correct answer should be 2.

A: Seems that you need to remap ptr_ and rhs.ptr_ to their sequence numbers (in the order you want to go through) and subtract the values:
difference_type operator-(const self_type& rhs) const noexcept
{
    const auto row1 = ptr_ / numCols_;
    const auto col1 = ptr_ % numCols_;
    const auto seq1 = col1 * numCols_ + row1;
    const auto row2 = rhs.ptr_ / numCols_;
    const auto col2 = rhs.ptr_ % numCols_;
    const auto seq2 = col2 * numCols_ + row2;
    return seq2 - seq1;
}


text:
Q: Querying multiple tables with the same column name I have multiple tables with an account number and a dollar amount.
Table Name: July Accounts
|   Account Number | Amount |
|------------------|--------|
| 1111111111111111 | $99.00 |

Table Name: August Accounts
|   Account Number | Amount |
|------------------|--------|
| 2222222222222222 | $89.00 |

I want my results to display as:
|   Account Number |   July | August |
|------------------|--------|--------|
| 1111111111111111 | $99.00 |    -   |
| 2222222222222222 |    -   | $89.00 |

So far everything I've tried causes something along the lines of:
|   Account Number |   July | August |
|------------------|--------|--------|
| 1111111111111111 | $99.00 | $89.00 |
| 1111111111111111 | $99.00 | $99.00 |
| 1111111111111111 | $89.00 | $89.00 |
| 1111111111111111 | $89.00 | $99.00 |
| 2222222222222222 | $99.00 | $89.00 |
| 2222222222222222 | $99.00 | $99.00 |
| 2222222222222222 | $89.00 | $89.00 |
| 2222222222222222 | $89.00 | $99.00 |

Any suggestions?

A: You just need to use UNION:
SELECT Account_Number, Amount as July, null as August
FROM July_Accounts

UNION

SELECT Account_Number, null, Amount
FROM August_Accounts


text:
Q: Many-to-Many update controller in Entity Framework 6 and Web API I can't get an Update controller in Web API to update both the object called and the referenced objects during the same call.
I have two classes:
public class Foo
{
    public int Id { get; set; }
    [Required]
    [MaxLength(250)]
    public string Title { get; set; }
    ...
    public virtual ICollection<Bar> Bars { get; set; }
}

public class Bar
{
     public int Id { get; set }
     public string Name { get; set; }
     ...
     public virtual ICollection<Foo> Foos { get; set; }
}

and a controller
public class BarController : ApiController
{
    private DbContext db = new DbContext();

    [HttpGet]
    public IQueryable<Bar> getBar(int id)
    {
         Bar bar = await db.Bars.FindAsync(id);
         if(bar == null)
         {
             return NotFound();
         }
         return OK(bar);
    }

    [ResponseType(typeof(Bar))]
    public async Task<IHttpActionResult> PostBar(Bar bar)
    {
        if (!ModelState.IsValid)
        {
             return BadRequest(ModelState);
        }

        db.Bar.Add(bar);
        foreach(var foo in bar.Foos)
        {
            db.Foos.Attach(foo);
        }
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = bar.Id }, bar);
    }

    [ResponseType(typeof(void))]
    public async Task(IHttpActionResult) PutBar(int id, Bar bar)
    {
        if (!ModelState.IsValid)
        {
             return BadRequest(ModelState);
        }

        if (id != ticket.Id)
        {
            return BadRequest();
        }

        db.Entry(bar).State = EntityState.Modified;

        await db.SaveChangesAsync();

        return StatusCode(HttpStatusCode.NoContent);
    }
    ...
}

Entity Framework creates a linking table correctly called FooBar (in this example), with the foreign Key relationships to Foo and Bar respectively.
A 'get' call resolves the reference, and returns an array of 'foos' with the rest of the bar object.
A 'post' call also resolves correctly, although without the foreach section, it would create new foo objects before linking.
However, a 'put' call only updates the Bar object, but does not update the linking to the Foo objects.
Updating the put controller to:
    [ResponseType(typeof(void))]
    public async Task<IHttpActionResult> PutBar(int id, Bar bar)
    {
        ...

        Bar _bar = db.Bars.Find(id);
        List<Foo> addedFoos = bar.Foos.Except(_bar.Foos,
            new KeyEqualityComparer<Bar, int>(x => x.Id)).ToList();
        List<Foo> removedFoos = _bar.Foos.Except(bar.Foos,
            new KeyEqualityComparer<Bar, int>(x => x.Id)).ToList();

        removedFoos.ForEach(c => _bar.Foos.Remove(c));
        addedFoos.ForEach(c =>
        {
            if (db.Entry(c).State == EntityState.Detached)
            {
                db.Foos.Attach(c);
            }
            _bar.Foos.Add(c);
        });

        await db.SaveChangesAsync();

        return StatusCode(HttpStatusCode.NoContent);
    }

would allow the update controller to update the Bar's Foo collection, but not the rest of Bar.
Unfortunately, attempting to use both calls would always throw an 'Attaching Entity of type' error, as each bar item loaded a foo item into the context, and visa versa.
Trying something akin to:
db.Entry(_bar).CurrentValues.SetValues(bar);
db.Entry(_bar).Collection(b => b.Foos).Load();
db.Entry(_bar).Collection(b => b.Foos).CurrentValue = bar.Foos;

caused an exponentially growing number of copies of both foo and bar on every update.
Is there any way around this? It strikes me odd that Entity Framework would produce the correct database structure, but make it impossible to work on.

A: Attempt this and let me know if you have issues
Bar _bar = db.Bars.Find(id);
var removed =_bar.Foos.Except(bar.Foos);
var added = bar.Foos.Except(_bar.Foos);

var toRemoveTracked =_bar.Foos.Where(foo => removed.Any(r => r.FooId == foo.FooId))
                              .ToList();

added.ToList().ForEach(_bar.Foos.Add);
toRemoveTracked.ForEach((fooo) => {_bar.Foos.Remove(fooo);});

await db.SaveChangesAsync();

Also remove lazy loading from your ICollection<Foo> property, (done by removing the virtual keyword that precedes ICollection)


text:
Q: jQuery scroll from element to element to element and factor in page scroll I am trying to make a fixed navigation that lets you scroll between elements on a page and keeps count of where you are on the page. I have seen a couple examples, to which I modified slightly, but haven't been able to get any to work properly. My latest attempt works fine with when you toggle between the previous/next buttons to get from section to section, but I want to take into account where the user is on the page. For example, if I click on the next button two times, the count is set to 2, and it takes me to the second section on the page. Then if I click the previous button once, the count is set to 1, and it takes me the first section on the page. Now if I scroll down towards the middle of the page (using the browser scrollbar), and hit the next button, the count is set to 3 and it takes me to the second section on page. I want it so that it takes me to the next visible section on the page. I need a way to detect what section the user is currently on and factor that in to my logic so that someone can seamlessly navigate through the page using either their scrollbar or this fixed navigation. How can I achieve this?
JS Fiddle: http://jsfiddle.net/picitelli/fCLKm/
JS
function scrollTo(el) {

    $('html,body').animate({
      scrollTop: $(el).offset().top
    }, 500);

}

var scroller = $('.scroller'),
    scrollNext = scroller.find('.next'),
    scrollPrev = scroller.find('.prev'),
    count = 0,
    sectionCounter = $('.section').length;

scrollNext.on("click", function() {

    if (count < sectionCounter && count !== sectionCounter) {
        count++;
        scrollTo('.section:eq(' + count + ')');
    } else {
        // do nothing
    }

    console.log(count);

});

scrollPrev.on("click", function() {

    if (count > 0) {
        count--;
        scrollTo('.section:eq(' + count + ')');
    } else {
        // do nothing
    }

    console.log(count);
});

HTML

    Previous
    Next

Lorem ipsum some content...

A

B

C

D

E

F

G

H

I

J

K

CSS
.content {
    padding: 20px;
}
.section {
    background: #f2f2f2;
    height: 400px;
    padding: 20px;
}
.section:nth-child(even) {
    background: #ccc;
}
.scroller {
    position: fixed;
    right: 20px;
    top: 20px;
}
.scroller span {
    background: #fff;
    color: #666;
    cursor: pointer;
    display: block;
    font-size: 14px;
    padding: 5px;
    text-align: center;
    width: 50px;
}
.scroller span:hover {
    color: #000;
}
.scroller span.prev {
    margin-bottom: 2px;
 }

Any feedback/direction would be greatly appreciated.

A: I think instead of keeping a count,  just scroll to the nearest section closest to the window top position when scrolling down or up, when no section is in perfect position to the window top position.  And if it is, just scroll to the section one above or below the one you are on.  Take a look at this How to find the closest element to the current position with jQuery

A: Ok, I think I figured it out.
JS Fiddle: http://jsfiddle.net/picitelli/Tfbb3/
New JS
function scrollTo(el) {

  $('html,body').animate({
    scrollTop: $(el).offset().top
  }, 500);

}

var scroller = $('.scroller'),
    scrollPrev = scroller.find('.prev'),
    scrollNext = scroller.find('.next'),
    section = $('.section'),
    position = -1;

// add data count to each section
section.each(function(index) {

    $(this).attr('data-count', index);

});

// next click through scrolling
scrollNext.on('click', function() {

    if (position
 0) {

      position--;

      scrollTo(section[position]);

    }

});

// page scroll position detection
$(window).scroll(function() {

    var currentPosition = $(this).scrollTop();

    section.each(function() {

        var top = $(this).offset().top,
            bottom = top + $(this).height();

        if(currentPosition >= top && currentPosition <= bottom) {

            var sectionCount = $(this).attr('data-count');

            position = sectionCount;

        }

     });

});


text:
Q: How to get the list of constant terms of linear equations? A system of linear equations:
$\left\{\begin{aligned} x_{1}+3 x_{2}+x_{3} &=2 \\ 3 x_{1}+4 x_{2}+2 x_{3} &=9 \\-x_{1}-5 x_{2}+4 x_{3} &=10 \\ 2 x_{1}+7 x_{2}+x_{3} &=1 \end{aligned}\right.$
I know how to get its coefficient matrix.
Clear["Global`*"];
eqns = {\!\(TraditionalForm\`
\*SubscriptBox[\(x\), \(1\)] + 3
\*SubscriptBox[\(x\), \(2\)] +
\*SubscriptBox[\(x\), \(3\)]\[AlignmentMarker] ==
      2\), \!\(TraditionalForm\`3
\*SubscriptBox[\(x\), \(1\)] + 4
\*SubscriptBox[\(x\), \(2\)] + 2
\*SubscriptBox[\(x\), \(3\)]\[AlignmentMarker] ==
      9\), \!\(TraditionalForm\`\(\[Minus]
\*SubscriptBox[\(x\), \(1\)]\) \[Minus] 5
\*SubscriptBox[\(x\), \(2\)] + 4
\*SubscriptBox[\(x\), \(3\)]\[AlignmentMarker] ==
      10\), \!\(TraditionalForm\`2
\*SubscriptBox[\(x\), \(1\)] + 7
\*SubscriptBox[\(x\), \(2\)] +
\*SubscriptBox[\(x\), \(3\)]\[AlignmentMarker] == 1\)};
c = CoefficientArrays[eqns, Variables@eqns];
mc = MatrixForm@c[[2]]

$\left(\begin{array}{ccc}1 & 3 & 1 \\ 3 & 4 & 2 \\ -1 & -5 & 4 \\ 2 & 7 & 1\end{array}\right)$

How to get the list of constant terms of these linear equations, i.e {2,9,10,1}?

A: Try this:
Part[-Normal[CoefficientArrays[eqns]], 1]
(*{2, 9, 10, 1}*)

The system coefficients:
Part[Normal[CoefficientArrays[eqns]], 2]
(*{{1, 3, 1}, {3, 4, 2}, {-1, -5, 4}, {2, 7, 1}}*)


text:
Q: Riesz-Markov-Kakutani theorem with absolutely continuous measure? Suppose that $X$ is a locally-compact Hausdorff space and also $(X,\mathcal F, P)$ is a probability space. Let $\psi$ be any positive, linear functional on the space $C_c(X)$ of continuously compactly supported functions $f$ on $X$.
The Riesz-Markov-Kakutani Theorem implies that there exists a unique regular Borel measure $\mu$ such that for all $f \in C_c(X)$,
$$
\psi(f) = \int f(x) d\mu.
$$
Are there conditions that guarantee $\mu \ll P$, so that---by the Radon-Nikodyn theorem---we can write
$$
\psi(f) = \int f(x) \frac{d\mu}{dP} dP \quad ?
$$


text:
Q: Parsley.js Customer Validator Pass Variable to message window.Parsley.addValidator('passwordValidChars', {
    requirementType: ['integer', 'integer'],
    validateString: function(value, min, max) {
        var invalidChars = [];
        for (var i = 0; i < value.length; i++) {
            if(value.charCodeAt(i) < min || value.charCodeAt(i) > max) {
                invalidChars.push(value.charAt(i));
            }
        }
        return (invalidChars.length === 0)
    },
    messages: {
        en: 'These characters are not allowed %s'
    }
});

I have this custom validator which validates the password entered between specific char codes e.g [33, 126].
If the user entered any invalid characters I collect them to an array invalidChars and then I want to pass the invalidChars array to the error message but how can I do that? The only values I can pass to the message are the min and max.

A: There's no super easy way, but you can return a dynamic error message. It's not well documented, but instead of returning false return $.Deferred().reject('your dynamic error message').


text:
Q: ReferenceError: require is not defined in ES module scope, you can use import instead Here I have mentioned the Files I have used. I have tried in both ways, by adding and removing of "type" : "module"  tag in package.json file.
App.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('app.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

import { hello } from './sell.js';
hello();

app.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>React JS </title>

JavaScript Tutorial

sell.js
export let hello = () => {
    console.log("heyy shreya suman");
}

A: Look, there are 2 ways to import somthing

*

*var http = require('http');

*import http from "http"
But you cant use import and require() at the same time, it does not work. You either use require() or import And, your package.json module type or file extension must match the type of import you are using


text: Q: ASP.NET Core send nested list from razor view page to controller action is null? I am trying to send a sub list called OrderItems EditOrderViewModel from a razor view page view page to controller action Post Action method but I always get null for the OrderItem Edit action post method sub list and this picture shows the inspected form fields. any help? note that I am using JQuery Ajax to send the data using form .serialize() method and this is the data that it sends.


text:
Q: Why variable is blank when using nested environments with tikz and figure I have the following document setup:
\documentclass[a4paper]{article}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{tikz}

\begin{document}
\newenvironment{foo}{
  \newcommand\bara{}
  \newcommand\barb[1]{
    \renewcommand\bara{##1}
    \typeout{FIRST}
    \typeout{##1}{\bara}
  }

  \newenvironment{baz}{
    \begin{figure}[!h]
    \centering
    \begin{tikzpicture}{scale=1}
  }{
    \typeout{SECOND}
    \typeout{\bara}
    \end{tikzpicture}
    \typeout{\bara}
    \caption{\bara}
    \end{figure}
  }
}{}

\begin{foo}
  \begin{baz}
    \bara{abc}
  \end{baz}
\end{foo}

\end{document}

It logs:
SECOND
[blank]

The last line is blank, and the FIRST stuff is missing. (And the caption is blank in the PDF).
I am new to latex and am not sure how to go about debugging this beyond putting the \typeout statements in the document.
Wondering why it doesn't log:
FIRST
abc
SECOND
abc
abc

A: The test code should be
\begin{foo}
  \begin{baz}
    \barb{abc}
  \end{baz}
\end{foo}

because it's \barb that sets the value of \bara.
Where's the problem? The baz environment opens a tikzpicture environment which forms a group; the \barb{abc} declaration is issued inside this tikzpicture so it's no longer available when the environment ends.
Depending on your needs, this could be solved by setting \bara globally; it's also possible to smuggle values one level up, with some lower level programming, if needed.
The level of generality of the question doesn't allow for suggesting a choice.

A: This MWE
\documentclass{article}
\makeatletter
\newenvironment{foo}%
{%
%
  \newcommand\@bar{}%
  \renewcommand\bar[1]{%
    \renewcommand\@bar{##1}%
    \typeout{FIRST}%
    \typeout{##1}{\@bar}%
  }%
%
  \newenvironment{baz}%
  {%
  }%
  {%
    \typeout{SECOND}%
    \typeout{\@bar}%
  }%
}%
{}%
\makeatother

\begin{document}
\begin{foo}
  \begin{baz}
    \bar{abc}
  \end{baz}
\end{foo}
\end{document}

Seems to produce the correct output/log
% latex tmp.tex
[snip]
FIRST
abc
SECOND
abc
[snip]
Output written on tmp.pdf (1 page, 11670 bytes).
Transcript written on tmp.log.


text:
Q: How do I know what code is blocking my rn main process, and how do I find the reason for switching pages to become stuck? I am a beginner to write react native app on android platform.
I found that my program is very stuck, and it takes a long time to even switch the screen.
I want to find what code is causing my rn app to be so stuck.
What tools can be used to troubleshoot the cause of the freeze, and what measures can be used to improve the user experience of rn?


text:
Q: Determine a cause of privilege elevation in Windows 7 I've stuck with some problem in my Visual Studio instance. I've used it for a while with the low-priveleged user account without any problem. But today I found that I can't start it without administrative account. I don't know what was happened but it seems that it is incurred by some plugin I've installed recently.
So I need to find what the part of the Visual Studio startup process requires the privilege elevation or at least what the privilege cause the UAC to be invoked.
I don't want to use VS with admin account.
System info:
Windows 7 Ultimate, Visual Studio 2010 SP1. VS is used with C++ only and didn't demand rights evaluation before.


text:
Q: Margin while printing html page I am using a separate style-sheet for printing.
Is it possible to set right and left margins in the style-sheet which set the print margin? (i.e. margin on paper)

A: I'd personally suggest using a different unit of measurement than px. I don't think that pixels have much relevance in terms of print; ideally you'd use:

*

*point (pt)

*centimetre (cm)

I'm sure there are others, and one excellent article about print-css can be found here: Going to Print, by Eric Meyer.

A: Firstly said, I try to force all my users to use Chrome when printing because other browsers create different layouts.
An answer from this question recommends:
@page {
  size: 210mm 297mm;
  /* Chrome sets own margins, we change these printer settings */
  margin: 27mm 16mm 27mm 16mm;
}

However, I ended up using this CSS for all my pages to be printed:
@media print
{
    @page {
      size: A4; /* DIN A4 standard, Europe */
      margin:0;
    }
    html, body {
        width: 210mm;
        /* height: 297mm; */
        height: 282mm;
        font-size: 11px;
        background: #FFF;
        overflow:visible;
    }
    body {
        padding-top:15mm;
    }
}

Special case: Long Tables
When I needed to print a table over several pages, the margin:0 with the @page was leading to bleeding edges:

I could solve this thanks to this answer with:
table { page-break-inside:auto }
tr    { page-break-inside:avoid; page-break-after:auto }
thead { display:table-header-group; }
tfoot { display:table-footer-group; }

Plus setting the top-bottom-margins for @page:
@page {
    size: auto;
    margin: 20mm 0 10mm 0;
}
body {
    margin:0;
    padding:0;
}

Result:

I would rather prefer a solution that is concise and works with all browser. For now, I hope the information above can help some developers with similar issues.

A: You should use cm or mm as unit when you specify for printing. Using pixels will cause the browser to translate it to something similar to what it looks like on screen. Using cm or mm will ensure consistent size on the paper.
body
{
  margin: 25mm 25mm 25mm 25mm;
}

For font sizes, use pt for the print media.
Note that setting the margin on the body in css style will not adjust the margin in the printer driver that defines the printable area of the printer, or margin controlled by the browser (may be adjustable in print preview on some browsers)... It will just set margin on the document inside the printable area.
You should also be aware that IE7++ automatically adjusts the size to best fit, and causes everything to be wrong even if you use cm or mm. To override this behaviour, the user must select 'Print preview' and then set the print size to 100% (default is Shrink To Fit).
A better option for full control on printed margins is to use the @page directive to set the paper margin, which will affect the margin on paper outside the html body element, which is normally controlled by the browser. See http://www.w3.org/TR/1998/REC-CSS2-19980512/page.html.
This currently works in all major browsers except Safari.
 In Internet explorer, the margin is actually set to this value in the settings for this printing, and if you do Preview you will get this as default, but the user can change it in the preview.
@page
{
    size: auto;   /* auto is the initial value */

    /* this affects the margin in the printer settings */
    margin: 25mm 25mm 25mm 25mm;
}

body
{
    /* this affects the margin on the content before sending to printer */
    margin: 0px;
}

Related answer:
Disabling browser print options (headers, footers, margins) from page?

A: Updated, Simple Solution
@media print {
   body {
       display: table;
       table-layout: fixed;
       padding-top: 2.5cm;
       padding-bottom: 2.5cm;
       height: auto;
   }
}

Old Solution
Create section with each page, and use the below code to adjust margins, height and width.
If you are printing A4 size.
Then user
Size : 8.27in and 11.69 inches
@page Section1 {
    size: 8.27in 11.69in;
    margin: .5in .5in .5in .5in;
    mso-header-margin: .5in;
    mso-footer-margin: .5in;
    mso-paper-source: 0;
}

div.Section1 {
    page: Section1;
}

then create a div with all your content in it.
<div class="Section1">
    type your content here...
</div>

A: I also recommend pt versus cm or mm as it's more precise.
Also, I cannot get @page to work in Chrome (version 30.0.1599.69 m) It ignores anything I put for the margins, large or small. But, you can get it to work with body margins on the document, weird.

A: You can also try this one, for using top negative margin
@media print {
 @page {
   /* size: 210mm 297mm;  */
   margin: -110mm 16mm 27mm 16mm;
 }

}

A: If you know the target paper size, you can place your content in a DIV with that specific size and add a margin to that DIV to simulate the print margin.
Unfortunately, I don't believe you have extra control over the print functionality apart from just show the print dialog box.


text:
Q: What happens to the momentum when 2 black holes collide and no matter is present? Imagine 2 non-spinning black holes with identical mass collides with each other at the same speed in the absence of other matter, I think the gravitational waves can only carry a little of the momentum but how about the rest which cannot be imparted to falling matter since it is initially vacuum? Normally when 2 objects collides, the momentum is distributed according to Newton 3rd law and heat as well but on the case of black hole no heat is produced and gravitational wave cannot carry the balance momentum also black hole don't knock back each other.

A: If two black holes with the same mass collide head on at the same speed, the total momentum is zero. What you may be asking is not momentum, but the kinetic energy of the black holes moving toward each other. After the collision, the mass of the resulting larger black hole will consist of the masses of two original black holes plus their kinetic energy minus the energy emitted in gravitational waves ($c=1$).
In a simpler example, if a small relativistic particle with a relatively large kinetic energy hits a black hole, the mass of the black hole is increased by the total energy of the particle or  the sum of its mass and kinetic energy (neglecting gravitational waves).


text:
Q: ¿Cómo encontrar los valores en que se diferencian dos series de dos DataFrame en python? Quiero realizar en python el siguiente proceso que en RStudio es muy sencillo con la función setdiff()
library(tidyverse)

# 1| data.frame sobre población
pop <- structure(list(country = c("Afghanistan", "Angola", "Albania",
                                  "Andorra", "United Arab Emirates",
                                  'Canada', 'United States'),
                      `2021` = c("40.8M", "35M", "2.87M", "77.5k", "10.1M", "30.2M", "50.6M"),
                      `2022` = c("41.7M", "36.1M", "2.86M", "77.6k", "10.2M", "30.6M","51.7M")),
                 row.names = c(NA, -7L), class = c("tbl_df", "tbl", "data.frame"))

# data.frame sobre ingresos
inc <- structure(list(country = c("Afghanistan", "Angola", "Albania",
                                  "Andorra", "United Arab Emirates"),
                      `2021` = c("1990", "5980", "14.7k", "56.5k", "65.2k"),
                      `2022` = c("2040", "6000", "15.1k", "56.9k", "66.3k")),
                 row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))

setdiff(pop$country, inc$country)

El resultado de la función setdiff(), arroja: "Canada" "United States"
¿Cómo puedo realizar este mismo proceso pero en python?

A: No está muy claro por qué hablas de dataframes, pues en el fondo lo que buscas es encontrar la diferencia entre dos listas (o series de valores).
Así que de momento olvidémonos de dataframes, puesto que además el código que muestras ni siquiera es Python y por tanto no se puede saber qué estructura tendrían esos dataframes tuyos si usaras pandas.
Vamos a suponer que de algún modo consigues tener en un par de listas los países cuya diferencia quieres obtener:
paises_pop = ["Afghanistan", "Angola", "Albania", "Andorra", "United Arab Emirates", 'Canada', 'United States']
paises_inc = ["Afghanistan", "Angola", "Albania", "Andorra", "United Arab Emirates"]

En este caso encontrar la diferencia entre ambas listas es muy simple si las conviertes en conjuntos (set()). Puedes hacer la diferencia entre conjuntos, o bien la operación XOR (que es la diferencia entre la unión de los conjuntos menos su intersección):
>>> set(paises_pop) ^ set(paises_inc)
{'Canada', 'United States'}

En este caso la diferencia (set(paises_pop) - set(paises_inc)) te daría el mismo resultado, pero creo que XOR es más genérico pues la diferencia sólo te daría los países que estuvieran en el primer conjunto y no en el segundo, pero no te daría los que estuvieran en el segundo y no en el primero, mientras que XOR te da todos los que están en un conjunto pero no en el otro.
Aunque esta respuesta se ejemplifica sobre un par de listas, en realidad funciona sobre cualquier tipo de iterable, por lo que son válidas también series Pandas. Por ejemplo, si se tuvieran dos dataframes df1 y df2 y se quisieran comparar sus columnas "country":
>>> set(df1.country) ^ set(df2.country)


text:
Q: How is it that both my if and else statements are executing? This code is working just fine - but both my if and else statements are executing, which I've never seen before and cannot understand:
function submit(total_lines) {

  total_lines   = total_lines;
  completed_lines         = 0;

  /* create one line at a time... */
  for (i=0;i<total_lines;i++) {

    color      = $('#color_' + i).val();
    qty        = $('#qty_' + i).val();

    console.log("starting line " + completed_lines);

    if ( color && qty ) {
      $.ajax({
        type: 'POST',
        url: '/submit_line.php',
        data: { color:color, qty:qty },
        success:function(data){
          console.log("Line " + completed_lines + " was successfull");
          completed_lines++;
        }
      }); //close ajax
    } else {
       console.log("Line " + completed_lines + " was not successfull. color = " + color + " and qty = " + qty);
       toastr.error("Color and quantity are both required fields.");
    }
  }

  setTimeout(function(){
    toastr.success("All done! ...");
    $('#add_something_footer').html('

CLOSE

');
  }, 5000);

}

For each iteration of i, The submit_line.php is executing, as it should, but I'm also getting the toastr.error line in my else statement executing.  How is this possible - color and qty both exist, so the primary part of the if statement is executing.. I don't believe my syntax is bad anywhere, (otherwise nothing would execute...).  I'm confused...
Edit
Updated the OP to reference console.log statements.
Here's my console.log
Object {type: "info", iconClass: "toast-info", message: "Submitting quotes...", optionsOverride: undefined, title: undefined}
5VM7093:699 starting line 0
VM7093:712 Line 0 was not successfull. color = undefined and quantity = undefined
toastr_qt.js:227 Object {type: "error", iconClass: "toast-error", message: "Color and quantity are both required fields", optionsOverride: undefined, title: undefined}
VM7093:699 starting line 0
VM7093:712 Line 0 was not successfull. color = undefined and quantity = undefined
toastr_qt.js:227 Object {type: "error", iconClass: "toast-error", message: "Color and quantity are both required fields", optionsOverride: undefined, title: undefined}
VM7093:699 starting line 0
VM7093:712 Line 0 was not successfull. color = undefined and quantity = undefined
toastr_qt.js:227 Object {type: "error", iconClass: "toast-error", message: "Color and quantity are both required fields", optionsOverride: undefined, title: undefined}
VM7093:699 starting line 0
VM7093:712 Line 0 was not successfull. color = undefined and quantity = undefined
toastr_qt.js:227 Object {type: "error", iconClass: "toast-error", message: "Color and quantity are both required fields.", optionsOverride: undefined, title: undefined}
VM7093:699 starting line 0
VM7093:712 Line 0 was not successfull. color = undefined and quantity = undefined
toastr_qt.js:227 Object {type: "error", iconClass: "toast-error", message: "Color and quantity are both required fields.", optionsOverride: undefined, title: undefined}
VM7093:708 Line 1 was successfull
VM7093:708 Line 2 was successfull
VM7093:708 Line 3 was successfull
VM7093:708 Line 4 was successfull
toastr_qt.js:227 Object {type: "success", iconClass: "toast-success", message: "All done!", optionsOverride: undefined, title: undefined}

The fact that in my console - all lines are going through the else statement FIRST, as the variables are undefined, then passing again through the regular if statement because they ARE defined is the thing that is confusing me.  How can the variable be undefined if I define it directly above the ajax line?


text:
Q: Custom UI painting problem I have a JInternalFrame that I am applying a custom UI to. The UI paints the component, but when I add a JPanel to the JInternalFrame it doesn't show up. I think the UI is paining over the whole component, but how do I paint the UI THEN paint the components?
But if anyone has a better way of doing this, please let me know! Thanks!
public class ClassInternalFrame extends JInternalFrame {
    public static Color currentColor;
    public static final Color CLASS_TYPE = new Color(148, 227, 251);

    public ClassInternalFrame(String title, Color classType) {
        super(title, true, true, false, true);
        currentColor = classType;
        super.setUI(new ClassFrameUI());

        Container pane = super.getContentPane();
        pane.setLayout(new BorderLayout());

        JPanel titlePanel = new JPanel();
        titlePanel.setPreferredSize(new Dimension(0, 20));
        pane.add(titlePanel, BorderLayout.NORTH);

        titlePanel.setBorder(new MatteBorder(1, 1, 1, 1, Color.yellow));
    }

}

class ClassFrameUI extends InternalFrameUI {
    private final static ClassFrameUI frmUI = new ClassFrameUI();

    public static ComponentUI createUI(JComponent c) {
        return frmUI;
    }

    @Override
    public void paint(Graphics g, JComponent c)
    {
        Graphics2D g2d = (Graphics2D) g;

        g2d.setColor(Color.LIGHT_GRAY);
        g2d.fillRect(0, 0, c.getWidth(), c.getHeight());

        g2d.setColor(ClassInternalFrame.currentColor);
        g2d.fillRect(0, 0, c.getWidth(), 20);

        g2d.setColor(Color.DARK_GRAY);
        g2d.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 1, 0 }, 0));
        g2d.drawRect(0, 0, c.getWidth()-1, c.getHeight()-1);
        g2d.drawLine(0, 20, c.getWidth(), 20);

    }
}

A: The problem is not that you're painting over anything, but that InternalFrameUI does absolutely nothing (if it did, you would also need to call super.paint(g, c);). Normally, painting of the components is done by a subclass such as BasicInternalFrameUI. It looks like you're trying to paint a custom title bar, a task that BasicInternalFrameUI delegates to BasicInternalFrameTitleBar.


text:
Q: Cannot Auto Generate Sequence with postgreSQL My Entity class:
@Entity
@Table(name = "songs", schema = "dbo")
public class Song {
    @Id
    // Try 1
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "songs_song_id_seq")
    // Try 2
    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "songs_song_id_seq")
    // Try 3
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "songs_song_id_seq")
    // Just so you know, when using one try, the other 2 were commented out :D

    @Column(name = "song_id")
    private Integer songId;

    // MRE
}

My Database: (PostgreSQL 10)
My sequence generator

My POSTMAN POST Request:
{
    "songName": "Song1",
    "songDuration": "500"
}

Table:
My Table
Sequence DDL: nextval('dbo.songs_song_id_seq'::regclass) (This came with the data type BigSerial)
Error I keep getting: The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!

I am all out of options. Please tell me what I've done wrong.
PS: First day with Spring Boot and PostgreSQL.

A: Maybe you have a little incorrect code anywhere.
For viewing return values of nextval function, so execute this query
select * from nextval('public.table_id_seq'::regclass)

3-5 times, you will view returned values. Values are modified in the same execution time.
If you want to use this function on inserting process manually, then use this sample query:
INSERT INTO table1 (id, "date", amount) VALUES(nextval('public.table_id_seq'::regclass), '2021-02-06', 30);

I tested all theses queries, worked 100%


text:
Q: In IE8, glitches during jQuery slider transition Would someome do a quick check on IE 8 and go to my site and verify that what I'm seeing is correct? I've been coding a new stylesheet for IE8 and it works fine, except all of the sudden I am now getting some pixelation glitch in the top left thumbnail of my homepage slider. This wasn't there a moment ago and I haven't changed anything, so I want to make sure it's a bug on my computer and not in IE 8.
http://fdoandsons.com/beta/index.html
What I see:
Top left thumbnail on the above link flashes black squares when the slider is transitioning. You can view in a standards compliant browser and see what it's supposed to look like.


text:
Q: Define one notify block for several tasks in Ansible Is it possible to define one notify block for several tasks?
In next code snippet notify: restart tomcat defined 3 times, but I want to define it only one time and "apply" to list of tasks
- name : template context.xml
  template:
    src: context.xml.j2
    dest: /usr/share/tomcat/conf/context.xml
    group: tomcat
    mode: 0664
  notify: restart tomcat

- name : copy server.xml
  copy:
    src: server.xml
    dest: /etc/tomcat/server.xml
    group: tomcat
    mode: 0664
  notify: restart tomcat

- name : copy atomikos-integration-extension
  copy:
    src: atomikos-integration-extension-3.7.1-20120529.jar
    dest: /usr/share/tomcat/ext-libs/
    group: tomcat
    mode: 0664
  notify: restart tomcat

A: As of Ansible v2.11 (https://github.com/ansible/ansible/blame/stable-2.11/changelogs/CHANGELOG-v2.11.rst#L599)
It is now possible to set notify on a block, and import_tasks https://github.com/ansible/ansible/pull/73572/commits/899f39800cb74e0e38010aba30087672819b2097
So, wrap your tasks with a block and set notify on the block!

A: No, you cannot.
Notify sets a trigger to run the specified handler based on the status of the task. There is no "status for a block of tasks" in Ansible hence you cannot define notify for a block.
Besides, it wouldn't change anything functionally, only influence the visual appeal (and I would claim by obscuring things rather than simplifying). The handler is run only once regardless of how many tasks triggered it.

A: Like already mentioned above it is now possible to use notify on a block.
Just make sure not to forget your handler.
- block:
  - name : template context.xml
    template:
      src: context.xml.j2
      dest: /usr/share/tomcat/conf/context.xml
      group: tomcat
      mode: 0664
  - name : copy server.xml
    copy:
      src: server.xml
      dest: /etc/tomcat/server.xml
      group: tomcat
      mode: 0664
  - name : copy atomikos-integration-extension
    copy:
      src: atomikos-integration-extension-3.7.1-20120529.jar
      dest: /usr/share/tomcat/ext-libs/
      group: tomcat
      mode: 0664
  notify: restart tomcat

A: A small workaround if you want to specifically want one handler for three tasks.

In your main role

- include: role2.yml

In role 2

- name : template context.xml
  template:
    src: context.xml.j2
    dest: /usr/share/tomcat/conf/context.xml
    group: tomcat
    mode: 0664

- name : copy server.xml
  copy:
    src: server.xml
    dest: /etc/tomcat/server.xml
    group: tomcat
    mode: 0664

- name : copy atomikos-integration-extension
  copy:
    src: atomikos-integration-extension-3.7.1-20120529.jar
    dest: /usr/share/tomcat/ext-libs/
    group: tomcat
    mode: 0664

- name: running handler for above tasks
  debug: msg='running handler for all three'
  notify: restart tomcat


text:
Q: Set value to a datepicker without clicking 'Done' button I'm using the Webix time picker and have no idea how to force it to set the value without clicking the "Done" button (I don't want to display it at all). Is there a way to do this through the DOM or through the plain JS?
For example, a time picker (a datepicker with type:"time")
var time = webix.ui({
    view:"datepicker",
    align: "right",
    label: 'Select Date',
    labelWidth:100, width:350,
    type:"time", stringResult:true
});

http://webix.com/snippet/232a2e2c

A: I modified your code a little. Now you can select a date hitting the Enter key:
var time = webix.ui({
   view:"datepicker",
   align: "right",
   label: 'Select Date',
   labelWidth:100, width:350,
   type:"time", stringResult:true
});

document.addEventListener("keydown", keyDownTextField, false);

function keyDownTextField(e) {
  var keyCode = e.keyCode;
  if(keyCode==13) {
     var done = document.getElementsByClassName('webix_cal_done');
     if(done.length > 0){
        done[0].click();
     }
  }
}

Working fiddle: http://webix.com/snippet/91f4cecc

A: Based on your code, I would look at using datepicker() directly instead of using ui. its part of the jquery UI set. I have linked directly to the datepicker site.
var time = webix.datepicker();

And on the jquery page there is a list of time picker plugins that may also help fill the void
Timepicker plugins

A: I've created a similar solution for my project using DOM. Works good enough for me, but actually, it's a temporary hack (unless I can find something better). Check it out:
time.getPopup().attachEvent("onhide", function(){
  var timeArr = document.getElementsByClassName("webix_cal_block webix_selected");
  if (timeArr.length == 2){
    var hour = timeArr[0].getAttribute("data-value");
    var min = timeArr[1].getAttribute("data-value");
    time.setValue(hour+" "+min);
  }
});

http://webix.com/snippet/ff554921

A: all done in one script:
var time = webix.ui({
    view:"datepicker",
    align: "right",
    label: 'Select Date',
    labelWidth:100, width:350,
    type:"time", stringResult:true
}).attachEvent("onBlur", function(){
    document.getElementsByClassName('webix_cal_done')[0].click();
});

thanks @Hackerman http://webix.com/snippet/1613c3d2


text:
Q: How to resize OpenStreetMap tiles I implement offline map application by route-me and OpenStreetMap.
I used tile from zoom level 11-16.
But when I convert to .sqlite it very large file size.
that is my first problem.
and second is on map zoom level 16 is very small (text and road detail on map). have any solution for resize tiles on level 16 or any thing is should do.

A: If you just need help generating tiles, go to maptiler.org and give it a try.
(If you need help implementing tiles, a few more details in the question might help.)
(Hat tip:
Convert a single large image overlay to tiles for Google Maps)


text:
Q: Assign tab content in WPF to a page I am trying to add dynamic tabs to my application. Right now if I click a button, it will open a new page. What I want is to open this page in a new tab. But when I set up the tab content to a page , the code complains. I wanna do something like this
private void bttnGoToClientsOnClick(object sender, RoutedEventArgs e)
{
    var content = new TextBlock();
    TabItem tab = new TabItem();
    tab.Header = "Search Page";
    SearchPage sp = new SearchPage();
    tab.Content = sp;
    tabControl.Items.Add(tab);
    this.NavigationService.Navigate(sp);
}

is there any way I can convert my page to usercontrol or cast it as user control
Thank you!

A:
But when I set up the tab content to a page , the code complains.

It wouldn't hurt if you were more specific here :)
What is SearchPage class? It doesn't seem to be the part of the WPF framework. I googled it up on the
http://www.intersoftpt.com/ website. Is that it?
TabItem.Content needs to be of ContentControl type, which SearchPage - apparently - is not. I'm sure you need to embed this SearchPage object in some control presenter, such as a panel, before you can assign it to TabItem.Content.

Update:
Try this, then:
TabItem tab = new TabItem();
tab.Header = "Search Page";
SearchPage sp = new SearchPage();
this.NavigationService.Navigate(sp);
// ----------------------------------------------------
var frame = new Frame(); // !
frame.Navigate(sp);  // !
tab.Content = frame; // !
// ----------------------------------------------------
tabControl.Items.Add(tab);

While I believe this should work, I haven't tested it. Please let me know if it doesn't do the trick.

A: You can always create your own UserControls, directly in the XAML definition (even if they are partial pages or windows).
In this example I assume that your SearchClass is defined in the [YourProject].Model namespace (where [YourProject] is the name of your project)
<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:search="clr-namespace:[YourProject].Model">
    <search:SearchClass>
        <!--<Grid>
            ...ANYTHING YOU WANT HERE ! ...
        </Grid>-->
    </search:SearchClass>
</UserControl>

Now you can create an instance of the UserControl, even in XAML or in code-behind (remember only to declare the namespaces correctly!):
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:ctrls="clr-namespace:WpfApplication1"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <UserControl1 />
    </Grid>
</Window>

...and this my code-behind...
UserControl1 myControl = new UserControl1();


text:
Q: ASP.NET Unauthorized in Postman using IIS Express, but works in Chrome I am trying to test an ASP.NET Web Api locally using IIS Express. When I use Chrome and hit the url (localhost:5000/api/test, for example) the json displays fine, but when using Postman I keep getting unauthorized 401.2 when hitting the same url. The api controller has Anonymous access on the route.
On the error message, one of the likely causes is:
Integrated authentication is enabled and the request was sent through a proxy that changed the authentication headers before they reach the Web server.
Is Postman somehow changing the headers?

A: Looks like it's your proxy.
I haven't found the proxy setting in postman. So I deleted postman for Win and installed postman for Chrome. Possibly Postman gets the environment from Chrome.
Anyway the resolution is to use Postman for Chrome instead of Postman for Win.

A: [2019 Update]
Got the same issue, I couldn't debug an ASP Core 2.1 API using Postman when running on the local machine using IIS Express. I kept on having "Could not get any response" despite it was working fine on a browser.
Following troubleshooting steps explained here PostmanLabs Github, I noticed into Postman console that this was coming from a certificate issue.
Disabling SSL Verification from Postman Settings > General allowed the request to pass through.

A: I have a localhost WebAPI site up with IIS Express (HTTPS).  Postman started to respond as expected to GETs and POSTs after I changed (in Postman)
File --> Settings --> Proxy

*

*to: "Use the system proxy"

*and turning on: "Respect HTTP_PROXY ...".

I had earlier set up a custom proxy that wasn't working with HTTPS.


text:
Q: Create class objects with a dictionary as argument In the next example, I have created a class Sample which accepts a dictionary of keyword arguments, like:
import numpy as np

class Sample:
    def __init__(self, **kwargs):
        self.A = kwargs['A']
        self.B = kwargs['B']
        self.C = kwargs['C']
        self.D = kwargs['D']
        self.E = kwargs['E']
        self.F = kwargs['F']
        self.G = kwargs['G']

and a function to create a list of class objects like:
def createSampleList (As, Bs, Cs, **kwargs):
    sampleList = []
    for A in As:
        for B in Bs:
            for C in Cs:
                addedkwargs = {'A': A, 'B': B, 'C': C}
                kwargs = dict(kwargs,**addedkwargs)
                sampleList.append (Sample (**kwargs))
    return sampleList

So far this function works fine if I give it a list of positional arguments like in the definition, so that
As = np.linspace (0, 3, 3)
Bs = np.linspace (0, 3, 4)
Cs = np.linspace (0, 3, 6)
D = 3
E = 5
F = 8
G = 9

sampleList = createSampleList (
                As, Bs, Cs, **{
                'D' : D,
                'E' : E,
                'F' : F,
                'G' : G,
            })

works as expected. For instace:
print(len(sampleList))
>>> 72

Now, what I would like is to be able to call the function createSampleList with a dictionary of variable length of keyword arguments. Say:
sampleList = createSampleList2 (
                {'A': As, 'B': Bs, 'C': Cs, 'D' : D }, **{
                    'E' : E,
                    'F' : F,
                    'G' : G,
            })

I have tried something like
def createSampleList2 (arrayDict, **kwargs):
    sampleList = []
    addedkwargs = dict()
    for key in arrayDict.keys():
        for value in arrayDict[key]:
            addedkwargs[key]= value
    kwargs = dict(kwargs,**addedkwargs)
    sampleList.append (Sample (**kwargs))
    return sampleList

but of course, this doesn't work. Any suggestions?

A: If I understand correctly what you want is to create a product of given lists. If so, you can use Python's goods from itertools. Code below uses itertools.product to generate all possible combinations of lists' values. To make things simpler, non-iterable (e.g. simple numbers) are replaced by one-item-long lists:
from itertools import product

def createSampleList2(array_dict, **kwargs):
    sample_list = []
    keys = []
    values = []
    for k, v in array_dict.items():
        keys.append(k)
        try:
            iter(v)
            values.append(v)
        except TypeError:
            values.append([v])

    for value_set in product(*values):
        kw = dict(zip(keys, value_set))
        kw.update(kwargs)
        sample_list.append(Sample(**kw))
    return sample_list

This function will accept any combination of values and lists in array_dict. So all below are equivalent:
createSampleList2({"A": [1, 2], "B": [3, 4], "C": [5, 6]}, D=7, E=8, F=9, G=10)
createSampleList2({"A": [1, 2], "B": [3, 4], "C": [5, 6], "D": 7, "E": 8, "F": 9, "G": 10})


text:
Q: Adding to Values of a Dictionary With simpler dictionaries like this Dictionary<key,value> I know I can add an item to the dictionary like this:
if(!myDic.ContainKeys(key))
  myDic[key] = value;

But how about a more complex dictionary like this:
Dictionary myDic<string, List<MyClass>>

where each key might have a list of values of my class? How do we add to that?

A: The same way:
myDic[key] = new List<MyClass()>();

If the list is already there and you want to add to it:
myDic[key].Add(new MyClass());

A: Here is a code snippet that I use for this:
// This is the list to which you would ultimately add your value
List<MyClass> theList;
// Check if the list is already there
if (!myDict.TryGetValue(key, out theList)) {
    // No, the list is not there. Create a new list...
    theList = new List<MyCLass>();
    // ...and add it to the dictionary
    myDict.Add(key, theList);
}
// theList is not null regardless of the path we take.
// Add the value to the list.
theList.Add(newValue);

This is the most "economical" approach, because it does not perform multiple searches on the dictionary.

A: You can use TryGetValue method:
List<MyClass> list;

if (myDic.TryGetValue(key, out list))
  list.Add(value); // <- Add value into existing list
else
  myDic.Add(key, new List<MyClass>() {value}); // <- Add new list with one value

A: If the value to add is an item for the list, you can do:
if(!myDic.Keys.Contains(key)) {
    myDic[key] = new List<MyClass>();
}
myDic[key].Add(value);


text:
Q: Regex pattern search starts with 2 letters OR 2 numbers I'm writing a javascript function to detect a correct entry into the database before sending it.  The variable must start with either 2 digits OR 2 letters followed by 2 more letters then 3 digits.  I can make each regex work independently but I want to do this in one statement. I've tried /^[A-Z]{2}|^[0-9]{2}[A-Z]{2}\d{3}$/ with no luck.
 var valL = /^[A-Z]{2}[A-Z]{2}\d{3}$/;letter
    var valj = /^[0-9]{2}[A-Z]{2}\d{2}$/;digits

A: You just need to group your alternation.
/^([A-Z]{2}|[0-9]{2})[A-Z]{2}\d{3}$/

otherwise you match only the left or the right side of the alternation.

A: Following regex should work:
/^(?:[A-Z]{2}|\d{2})[A-Z]{2}\d{3}$/i


text:
Q: Lifting of automorphism of rational surface to that on abelian variety The paper I am referencing is "Normal Subgroups of the Cremona Group." https://arxiv.org/abs/1007.0895. In theorem 5.14, at the bottom of page 52, the author stated for the abelian surface $Y= \mathbb{C}/\mathbb{Z}[i] \times \mathbb{C}/\mathbb{Z}[i]$, we consider the quotient $X= Y/ \Gamma$ where $\Gamma$ is the group of order 4 generated by the map $(x,y)\mapsto (ix, iy)$ on $Y$. Moreover one can show that $X$ is rational.
In general the group of automorphism of $X$ cannot be lifted to that on $Y$ since there are more automorphisms on a rational surface than on an abelian one. However, the paper stated that in this case we can do so since the fundamental group $\Lambda$ of $X\backslash \text{Sing}(X)$ is the group $\mathbb{Z}/4\mathbb{Z} \ltimes (\mathbb{Z}[i]\times \mathbb{Z}[i])$. They further say that $\mathbb{Z}[i]\times \mathbb{Z}[i]$ is invariant under all automorphism of $\Lambda$ and used this to conclude that we can lift an aut on $X$ to that of $Y$.
How did they arrive at this conclusion? Would be grateful if anyone can help to explain what that paragraph meant.


text:
Q: Angular 5 Cannot read property 'subscribe' of undefined when am trying to subscribe which is not a type of Service Method I have a method like,
validatingUpdateBtn: boolean;

Validating(): Observable<boolean> {

    //Do some function

    if (this.validatingUpdateBtn) {
         return Observable.of(true).map(res => res);
    }
    else {
         return Observable.of(false).map(res => res);
    }
}

Now as show in the below method, am subscribing to above method.
handleSelection(){
    this.Validating().subscribe(
          (res) => {
            if (res) {
              //Do some work
            }else{
              //Do some work
            }
          }
        )
}

but am getting Cannot read property 'subscribe' of undefined when am trying to subscribe Validating() method.
Am not getting whats going wrong?

A: As we found out with @Chandan Y S, the problem was that current if statement was inside of another conditional structure, in this case switch statement, and in some particular scenario execution didn't even come to that if-else statement which was returning observables, and that is why function didn't return anything.

A: validatingUpdateBtn: boolean;
ValidatingFunction = () => {

    //Do some function

    if (this.validatingUpdateBtn) {
         return Observable.of(true).map(res => res);
    }
    else {
         return Observable.of(false).map(res => res);
    }
}

Validating = ValidatingFunction.asObservable();

Try this maybe it's work

A: You have nothing to map therefore remove map operator after of. Use of operator from rxjs/observable/of as below.
import { Observable, of } from 'rxjs';

  Validating(): Observable<any> {

    let res = this.validatingUpdateBtn ?  of(true) : of(false);
    return res;
  }

handleSelection(): void{

  this.Validating().subscribe( res => {
    if (res) {
      console.log(res);
    } else {
      console.log(res);
    }
  });
}

StackBlitz


text:
Q: data and salt required : hashSync i'm trying to hash the password inside the ueserRouter with hashSync to create a signup
the error: data and salt are required
if someone can help how can i declare data and salt in this function
the code below:
const userRouter = express.Router();
userRouter.post('/signup',expressAsyncHandler(async (req, res) => {
const newUSer = new User({
  name: req.body.name,
  email: req.body.email,
  password: bcrypt.hashSync(req.body.password)
});
const user = await newUSer.save();
res.send({
  _id: user._id,
  name: user.name,
  email: user.email,
  isAdmin: user.isAdmin,
  token: generateToken(user),
});

})
);

A: The problem that i was defining password as a number in userSchema so I changed it to string.
Then I made this change in userRouter:
password: bcrypt.hashSync(req.body.password, 10);

Instead of:
password: bcrypt.hashSync(req.body.password)

A: Error message:

data and salt are required

Fix by passing num salt rounds (or generated salt):
hashSync(req.body.password, 10)

Source: npm


text:
Q: HTML5 on iPhone Safari - data stored by localStorage does not always persist. Why? I write a simple iPhone web app using HTML5's localStorage.
Tests on a 2G device show that data stored using localStorage does not persist after the Safari process is killed although the opened Safari windows are remembered.
The data is also lost in a case where I am on a different site on a different Safari window, then I change the window to where the web app in subject is shown. When Safari loads the page it automatically refreshes the page. Then the data is lost.
This is a simple test code:
<html>
<head>
    <meta name="viewport" content="height=device-height, width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
</head>
<body>
<script>
    alert("1:" + localStorage.getItem("test"));
    localStorage.setItem("test", "123");
    alert("2:" + localStorage.getItem("test"));
</script>
</body>

As far as I understand the data should persist!
Can anyone shed some light on this behavior? What should I do to get the persistence to work?
Thanks!
Tom.

A: According to Apple (https://developer.apple.com/library/archive/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Name-ValueStorage/Name-ValueStorage.html#//apple_ref/doc/uid/TP40007256-CH6-SW3), localStorage support was added in Safari 4.0.
According to Wikipedia (https://en.wikipedia.org/wiki/Safari_version_history), Safari 4.0 was added in iPhone OS 3.0.
2G iPhones did not come with OS 3.0 or later pre-installed. Your iPhone OS version is most likely too old.

A: I think there is a bug with local storage in iPhone Safari. I  have a similar problem as you:
http://groups.google.com/group/phonegap/browse_thread/thread/746868e928aaba5c

A: I tried your code on my iPhone 3G and Safari on Windows and it works.  Maybe you are running an older version of Safari on your iPhone?


text:
Q: Testing backbone-relational with jasmine UPDATED:
I have a simple Backbone-relational model:
@App.M.Product = Backbone.RelationalModel.extend
    defaults: {}
    url: App.D.dataURL
    relations: [
        {
            type: Backbone.HasMany
            key: 'templates'
            relatedModel: 'App.M.Template'
            collectionType: 'App.C.Templates'
            reverseRelation:
                key: 'product'
        }
        {
            type: Backbone.HasMany
            key: 'pages'
            relatedModel: 'App.M.Page'
            collectionType: 'App.C.Pages'
            reverseRelation:
                key: 'product'
        }
        {
            type: Backbone.HasMany
            key: 'uploaded_images'
            relatedModel: 'App.M.UploadedImage'
            collectionType: 'App.C.UploadedImages'
            reverseRelation:
                key: 'product'
        }
    ]
    initialize: ->
        if @get('minimumNumberOfPages') < 1
            @set 'minimumNumberOfPages', 1
    fixPages: ->
        col = @get 'pages'
        col.each (page) ->
            page.collection = col

and an even simplier test suite:
"use strict"

describe 'Product', ->
    pr = null
    beforeEach ->
        pr = new App.M.Product
    it 'should be defined', ->
        expect(pr).toBeDefined()

However, the model fails to initialize (taken from testem's terminal output):
TypeError: Cannot read property 'prototype' of undefined
    at Backbone.HasMany.Backbone.Relation.extend.initialize (http://localhost:7357/app/bower_components/backbone-relational/backbone-relational.js:835:78)
    at Backbone.Relation (http://localhost:7357/app/bower_components/backbone-relational/backbone-relational.js:537:9)
    at new child (http://localhost:7357/app/bower_components/backbone/backbone-min.js:1:25220)
    at _.extend.initializeRelation (http://localhost:7357/app/bower_components/backbone-relational/backbone-relational.js:137:5)
    at null.<anonymous> (http://localhost:7357/app/bower_components/backbone-relational/backbone-relational.js:1176:31)
    at Array.forEach (native)
    at Function.w.each.w.forEach (http://localhost:7357/app/bower_components/underscore/underscore-min.js:1:599)
    at Backbone.RelationalModel.Backbone.Model.extend.initializeRelations (http://localhost:7357/app/bower_components/backbone-relational/backbone-relational.js:1175:6)
    at Backbone.RelationalModel.Backbone.Model.extend.set (http://localhost:7357/app/bower_components/backbone-relational/backbone-relational.js:1373:11)
    at Backbone.Model (http://localhost:7357/app/bower_components/backbone/backbone-min.js:1:3929)

Why is that? The app is wokring correctly, the tests are not.

A: So the error is ReferenceError: product is not defined. This cause you defined it in the before function and in the test, so both are not the same and in the test its undefined. You have to define it in your describe block :
"use strict"
describe 'Product', ->
    product = null
beforeEach ->
    product = new App.M.Product

it 'should be defined', ->
    expect(product).toBeDefined()

For the other error TypeError: Cannot read property 'prototype' of undefined, it seems you have missed to add the collections mention under collectionType. So the plugin is looking for App.C.Pages in the global namespace and and try to get the prototype of the object. But as the error says its not defined


text:
Q: Publishing error "can't find file..." when the file exists in the path specified I'm trying to publish out to Azure and I'm suddenly receiving an error

Copying file bin\de\Microsoft.Data.Edm.resources.dll to obj\Release\Package\PackageTmp\bin\de\Microsoft.Data.Edm.resources.dll failed. Could not find file 'bin\de\Microsoft.Data.Edm.resources.dll'.

The file is definitely in the path.  I've deleted everything from bin and obj to force a complete rebuild but nothings seems to work.  Ideas?

A: I have the same exact error but unable to figure out why. Cleaning and rebuild doesn't help anything too.
Following this
link, I exclude both bin and obj in my solution, tried to publish again and it work like a charm.
Hope this helps


text:
Q: Google Script getActiveRange I have a spreadsheet with two sheets inside named "Sheet1" and "Sheet2". I have a script, running on click the menu item:
function foo(){

var oSheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"),
oSheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
Logger.log(oSheet1.getActiveRange().getValues());
Logger.log(oSheet2.getActiveRange().getValues());

} // foo

I select in browser in Sheet1 the first range, and then click on Sheet2, and select the second range, different on the first. I click the menu item, start foo(). Logger view same result for oSheet1 and oSheet2. Why? And how I can to get selected range on unactive sheets?
Here is the table with full access https://docs.google.com/spreadsheets/d/1lfQl9H1PW2lKL-4YJir7uxl-ZMnDR6Zn1_FndG07WGY/edit#gid=1264703349

A: I guess I was wrong.  It looked like it was working but it was taking the active range in whatever sheet was sitting on top when the function runs. I tried it by avoiding to use active range like below and it does work. I put the Sheet1 and Sheet2 in there with all the asterisks so I could see the beginning of each data set to insure that they were the correct data. But even though there are selected ranges in each of the sheets the function repeats the selected data on the upper sheet (whichever one is active) and it doesn't report any errors.
function foo(){

var oSheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getDataRange();
var oSheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getDataRange();
Logger.log('**************************Sheet1**********************' + oSheet1.getValues());
Logger.log('********************Sheet2**************************' + oSheet2.getValues());

} // foo