text:
Q: When does a javascript settimeout or setinterval function stop? Will these functions always stop when user browses away from page, or closes the browser?

A:
Will these functions always stop when user browses away from page, or closes the browser?

Yes, all javascript execution of the page stops, all timers and the browser memory allocated for it is cleared, both for the markup, style sheets and scripts. Whats left is only cookies, local storage and/or etags, but none of these run any code ever, if you have put such in the browser using javascript.

A: Yes, they're stopped in that case.
you can also manually stop them like this:
t=setTimeout("timedCount()",1000);
clearTimeout(t);


text:
Q: How can I avoid "Segmentation fault" error when plotting two Widgets with PyVista? I have created a GUI with PyQt5 where there is an area in which I would like to plot some volumes. I sometime wish to slice the volumes for which I am using PyVista's "add_mesh_clip_plane" widget. It always works just fine the first time, but when I try to plot another volume with the same slicing function in the same QFrame, the program crashes and I get a " Segmentation fault (core dumped)" error,
does anybody know / have any ideas on how I could solve this??
I have created a small example (code to be found below) where a QFrame plots either a brain or Nefertiti's head by means of this slicing widget ad the user's will.
Before plotting each of them, I clear the QFrame of all actors and remove all their properties thanks to "clear()", the situation I would like to avoid would be:
1- click on plot Nefertiti
2- click on either plot Nefertiti or plot brain
3- when clicked within the QFrame area to move the slicing widget, the program crashes
I would like to complete delete the mesh before step 2), so that step 2) works just as step 1)
I have tried deleting the whole QFrame object and creating it again from scratch to no avail
PyQt5 GUI :
---------------------------------
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'double_plot.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtWidgets  # QtGui

class Ui_Test(object):
    def setupUi(self, Test):
        Test.setObjectName("Test")
        Test.resize(642, 574)
        self.widget = QtWidgets.QWidget(Test)
        self.widget.setGeometry(QtCore.QRect(110, 30, 402, 433))
        self.widget.setObjectName("widget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.widget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.vtkFrame = QtWidgets.QFrame(self.widget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.vtkFrame.sizePolicy().
                                     hasHeightForWidth())
        self.vtkFrame.setSizePolicy(sizePolicy)
        self.vtkFrame.setMinimumSize(QtCore.QSize(400, 400))
        self.vtkFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.vtkFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.vtkFrame.setObjectName("vtkFrame")
        self.verticalLayout.addWidget(self.vtkFrame)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.plotNef_button = QtWidgets.QPushButton(self.widget)
        self.plotNef_button.setObjectName("plotNef_button")
        self.horizontalLayout.addWidget(self.plotNef_button)
        self.plotBrain_button = QtWidgets.QPushButton(self.widget)
        self.plotBrain_button.setObjectName("plotBrain_button")
        self.horizontalLayout.addWidget(self.plotBrain_button)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.retranslateUi(Test)
        QtCore.QMetaObject.connectSlotsByName(Test)

    def retranslateUi(self, Test):
        _translate = QtCore.QCoreApplication.translate
        Test.setWindowTitle(_translate("Test", "Test"))
        self.plotNef_button.setText(_translate("Test", "Plot Nefertiti"))
        self.plotBrain_button.setText(_translate("Test", "Plot Brain"))

Main file - executable (python main.py)
-----------------------------------------------
import pyvista as pv
from pyvista import examples

from PyQt5 import QtWidgets

from double_plot import Ui_Test

class MainWindow(QtWidgets.QMainWindow, Ui_Test):
    def __init__(self, *args, **kwargs):
        QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)

        self.mesh = None
        self.vtk_widget = pv.QtInteractor(self.vtkFrame)

        self.plotNef_button.clicked.connect(self.plot_nefertiti)
        self.plotBrain_button.clicked.connect(self.plot_brain)

    def plot_nefertiti(self):
        self.vtk_widget.clear()  # Remove all actors and properties
        self.mesh = examples.download_nefertiti()
        self.vtk_widget.add_mesh_clip_plane(self.mesh)
        self.vtk_widget.update()

    def plot_brain(self):
        self.vtk_widget.clear()  # Remove all actors and properties
        self.mesh = examples.download_brain()
        self.vtk_widget.add_mesh_clip_plane(self.mesh)
        self.vtk_widget.update()

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

As stated above, step 2 makes the program crash, reminder:
1- click on plot Nefertiti
2- click on either plot Nefertiti or plot brain
when clicked within the QFrame area to move the slicing widget, the program crashes (ONLY AFTER STEP 2)

A: For anyone reading this in the future, this edge case can be avoided by calling disable_plane_widget prior to calling add_mesh_plane_widget.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS - how to make dynamic padding of children within a container I am trying to make dynamic padding within a container and are having some trouble with that.
If I for example have this html

and this styling
.sections-container {
  border: 1px solid black;
  width: 90%;
  height: 400px;
  padding: 2.4rem;
}

.section {
  border: 1px solid black;
  width: 100%;
  height: 100px;
  margin-top: 24px;
}

then the padding in the container is hardcoded to be 24px. You can see it at this stackblitz example: https://stackblitz.com/edit/typescript-yw8xyp?file=style.css.
What I am trying to achieve is:

*

*When the container gets larger, then the padding of the container should get bigger to a maks padding of 100px.

*When the container gets smaller, then the padding of the container should get smaller to minimum padding of 10px.

So when the container hit a specific size - then the padding should change dynamically - increase or decrease dependinding on the container size. I am trying to do this only using CSS - if that is even possible :D
Does someone know how to do this? Thanks in advance :)

A: You can achieve adaptive padding, using a variable for the width like this:
https://stackblitz.com/edit/typescript-u26fhc?embed=1&file=style.css
For min and max you need media queries

A: i guess you want padding in all 4 sides.
use display flex
    .sections-container {
      border: 1px solid black;
      width: 80%;
      height: 400px;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      align-items: center;
    }

    .section {
      border: 1px solid black;
      width: 70%;
      height: 100px;
    }

A: Best way is define break points and set paddings accordingly.


text:
Q: Laravel queue job does not load file in I am a bit stuck with loading in a file for Laravel Queue/Job
I am using Laravel queued/async jobs (lets call it job for easy use)
Oke lets start from the beginning, we have our own translation function and we also named it __() just like the default from Laravel, don't ask me why etc. (easy solution is to just rename it, I know) but this is what I have to stick with (unless this is unfixable maybe).
So to declare the function before Laravel does we insert the function just before the autoload in the index.php like this.
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/
require __DIR__.'/../app/Helpers/localization.php'; <-- yes this file
require __DIR__.'/../vendor/autoload.php';

And this works fine for the website and if we execute jobs with SomeJob::dispatchNow() (not async)
But when we want to do a async job like SomeJob::dispatch() the index.php is not called so the file is never required so neither is the function. (or am I wrong?)
I tried it with composer.js autoload
"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "files": [
        "app/Helpers/helpers.php", <-- works fine
        "app/Helpers/Localization.php" <-- it does include tho
    ]
},

now in the file we use the if (! function_exists('__')) but at that point the function is already declared, on the website itself it doesn't work either.
So short saying, require at the index.php only works from the website directly and not from async jobs cause index.php is never called when a queue execute the job.
Using the composer autoload doesn't work for both the website or the job cause the function is already declared by Laravel before we declare it.
So where should I require the file/declare the function so that both the website directly and the async job can use our version of the function.
P.S. I know my english isn't that great, so if anything is unclear or even if I miss any information, please ask me and I try to edit the post to be more clear.

A: You can add your function definition to the start of the bootstrap file of laravel bootstrap/app.php
Or (since i suspect SomeJob::dispatch() to use artisan), you can require your file in index.php and in artisan
#!/usr/bin/env php
<?php

define('LARAVEL_START', microtime(true));

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/app/Helpers/localization.php';
require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';


text:
Q: (Regex Python) удалить конструкции в квадратных скобках в строке Пусть на вход дана строка, в которой есть комментарии автора, записанные в квадратных скобках.
Например, так:
Это отличная строка [по моему мнению]
Или даже так: [Сейчас бы погладить [милого] ёжика] Это прекрасная [ну или не очень] строка
Комментарии автора не нужны конечному пользователю – значит, их можно удалить и получить такие строки:
Это отличная строка
Это прекрасная строка
Реализуйте программу, удаляющую скобки и комментарии внутри них.
С первой строкой я справился, а со второй - не пойму как быть, не могу подобрать паттерн
import re
str1, str2 = 'Это отличная строка [по моему мнению]', \
             '[Сейчас бы погладить [милого] ёжика] Это прекрасная [ну или не очень] строка'

pattern1 = r'\[.+\]'
pattern2 = r''
print(re.sub(pattern1, '', str1))
print(re.sub(pattern2, '', str2))

A: Код работает, если только нет лишних "одиноких" символов "[" или "]"
import re
str1, str2 = 'Это отличная строка [по моему мнению]', \
         '[Сейчас бы погладить [милого] ёжика] Это прекрасная [ну или не очень] строка'
pattern = r'\[[^\[\]]*\]'

print(re.sub(pattern, '', str1))

for i in range(str2.count('[')):
    str2 = re.sub(pattern, '', str2)
print(re.sub(' +', ' ', str2).strip())

Вывод:
>>> Это отличная строка
>>> Это прекрасная строка

A: Нужно удалять все подстроки между скобками до тех пор, пока не останется ни одного совпадения.
Код:
import re

def remove_text_between_brackets(text):
    n = 1
    while n:
        text, n = re.subn(r'\s*\[[^][]*]', '', text)
    return text.strip()

С помощью \s* перед \[[^][]*] находятся (и потом удаляются) все пробельные символы перед подстрокой между скобками.
Тест (см. пример выполнения кода):
texts = ['Это отличная строка [по моему мнению]', '[Сейчас бы погладить [милого] ёжика] Это прекрасная [ну или не очень] строка']
for text in texts:
    print(remove_text_between_brackets(text))

Результат:
Это отличная строка
Это прекрасная строка

A: Для нескольких вложенных скобок в предложении можно воспользоваться просмотром вперед. И если за закрывающей квадратной скобкой следует опять  закрывающая, то продолжаем брать до неё.
import re

str1, str2 = 'Это отличная строка [по моему мнению]', \
             '[Сейчас бы погладить [милого] ёжика] Это прекрасная [ну или не очень] строка'

pattern = r'\[.*?\] *(?![\w\s]*?\])'

print(re.sub(pattern, '', str1))
print(re.sub(pattern, '', str2))

--------------------------
Это отличная строка
Это прекрасная строка

Проверить можно здесь.
\[ соответствует символу [ с индексом 9110 (5B16 или 1338) буквально (с учетом регистра)
. соответствует любому символу (кроме разделителей строк)
*? соответствует предыдущему токену от нуля до неограниченного количества раз, как можно меньше раз, расширяясь по мере необходимости (ленивый)
\] буквально соответствует символу ] с индексом 9310 (5D16 или 1358) (с учетом регистра)
   буквально соответствует символу с индексом 3210 (2016 или 408) (с учетом регистра)
* соответствует предыдущему токену от нуля до неограниченного количества раз, как можно больше раз, возвращая по мере необходимости (жадный)
Отрицательный просмотр вперед (?![\w\s]*?\])
Утверждают, что приведенное ниже регулярное выражение не соответствует
Совпадение с одним символом из списка ниже [\w\s]
*? соответствует предыдущему токену от нуля до неограниченного количества раз, как можно меньше раз, расширяясь по мере необходимости (ленивый)
\w соответствует любому символу слова (эквивалентно [a-zA-Z0-9_])
\s соответствует любому символу пробела (эквивалентен [\r\n\t\f\v ])
\] буквально соответствует символу ] с индексом 9310 (5D16 или 1358) (с учетом регистра)]


text:
Q: Inserir valores em mais de 1 formulário dinamicamente com formsy-react Estou desenvolvendo uma aplicação em ReactJS e atualmente tenho 6 formulários (estou utilizando o formsy-react) que são inseridos de forma dinâmica, preciso inserir informações nos inputs de um determinado form, porém não achei nenhuma forma de fazer isso mesmo lendo a documentação. Alguém sabe como fazer?
 const upForm = () => {
    let result = {};

  for (const item of data) {
        result[`value[${item.id_pl_indicator}]`] = item.value;
    }

    setTimeout(() => {
        formRef.current.updateInputsWithValue({ ...result })
    }, 100);
 }

Mas ele não insere em nenhum form, parece estar 'perdido'.
Alguém sabe como poderia fazer?

A: Se você quer que o <input /> do seu formulário já inicie com um valor específico, você deve utilizar o atributo value.
De acordo com este trecho da documentação do formsy você pode fazer isso de forma semelhante utilizando a props, de mesmo nome, value.
Estes links podem te ajudar componentes controlados e componentes não controlados no React.


text:
Q: How do i write C code without using a goto keyword? I have this code written using a goto keyword:
#include<stdio.h>

    int main()
    {
        int i,j,k;
         for(i=1;i<=3;i++)
         {
         for(j=1;j<=3;j++)
         {
         for(k=1;k<=3;k++)
         {
         [***if(i==2&&j==2&&k==2)

           goto out;][1]
         else
         printf("%d %d %d\n ",i,j,k);***
        }
        }
       }
       out:
       printf("\nOut of the loop");
        return 0;
    }

And I have tried to write it without using goto with help of if statement and switch case. But I couldn't come with perfect logic. Please, someone, help me with this one.
#include<stdio.h>

int main()
{
        int i,j,k;
         for(i=1;i<=3;i++)
         {
         for(j=1;j<=3;j++)
         {
         for(k=1;k<=3;k++)
         {
         if(i>=2&&j>=2&&k>=2)
         break;
         else
         printf("%d %d %d\n ",i,j,k);

        }
        **

**switch(i>=2&&j>=3&&k>=1)
        {
        case 1: break;
        default : break;
     }**

**
     }
        switch(i>=3&&j>=2&&k>=2)
        {
        case 1: break;
        default : break;
     }
     }
     return 0;
    }

A: You can change the control variable inside the loop
for (i = 0; i < 2; i++) {
    for (j = 0; j < 4; j++) {
        for (k = 0; k < 8; k++) {
            if ((i == 2) && (j == 2) && (k == 2)) {
                // change control variables to finish their loop
                k = j = i = 9; break; // exit all loops
            }
            printf("%d, %d, %d\n", i, j, k);
        }
    }
}

A: You can use another variable and use it to "notify" the loops that they should end.
#include<stdio.h>

int main()
{
    int i,j,k;
    int run_me = 1;
    for (i = 1; run_me && i <= 3; i++) {
      for (j = 1; run_me && j <= 3; j++) {
        for (k = 1; run_me && k <= 3; k++) {
          if (i == 2 && j == 2 && k == 2) {
             run_me = 0;
          } else {
             printf("%d %d %d\n ",i,j,k);***
          }
        }
      }
   }
   printf("\nOut of the loop");
   return 0;
}

You can create a function from the loops.
#include<stdio.h>

void function(void)
{
    int i,j,k;
    for (i = 1; i <= 3; i++) {
      for (j = 1; j <= 3; j++) {
        for (k = 1; k <= 3; k++) {
          if (i == 2 && j == 2 && k == 2) {
             return;
          } else {
             printf("%d %d %d\n ",i,j,k);***
          }
        }
      }
   }
}

int main()
{
   function();
   printf("\nOut of the loop");
   return 0;
}


text:
Q: Client side validation not working with ASP.Net MVC Razor and Ajax form I am displaying a partial view inside a JQuery UI dialog.  The partial view contains fields that include Html.ValidationMessageFor entries and the form itself has a Html.ValidationSummary.  I can't seem to get client side validation to work at all.  I am expecting to see error messages if I leave a field empty and tab to another field.  I have been able to see the validation messages if I include this line upon successful loading of the partial view...
$.validator.unobtrusive.parse('#theForm');

but that is only when I submit the ajax form, not before.
jquery to load the partial view in a jquery ui dialog...
$('#theForm').load('/Company/Edit', function (response, status, xhr)
        {
            if (status != "success")
                $('#theForm').html('failed to load details')
            else {
                $.validator.unobtrusive.parse('#theForm');
                $('#theForm').dialog({ title: title, show: 'blind', hide: 'blind', width: '1000px' });
                $('#theForm').dialog('open');
            }
          });

Partial View...
    @model CompanyDetails

    @using (Ajax.BeginForm("Save", "Company", new AjaxOptions() { HttpMethod="Post", OnSuccess="closeForm" }, new {@id = "companyDetailsForm"}))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()
        <fieldset>
            <legend>Company Details Form</legend>

                    @Html.LabelFor(c => c.Name)
                    @Html.TextBoxFor(c => c.Name)
                    @Html.ValidationMessageFor(c => c.Name)

                    <input type="submit" value="Save" />

        </fieldset>
}

Here is the model clas....
public class CompanyDetails
{
    [Required]
    [Display(Name = "Company Name")]
    public string Name { get; set; }
}

And I have this in my web.config...
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ClientValidationEnabled" value="true"/>

I have the following javascript files included..

*

*jquery-ui-1.9.2.js

*jquery.unobstrusive-ajax.js

*jquery.validate.js

*jquery.validate.unobtrusive.js

Can anyone spot what I have done wrong?

A:
but that is only when I submit the ajax form, not before.

That's how unobtrusive javascript validation works. If you leave a field blank and tab out from it, validation won't trigger until you attempt to submit the form.


text:
Q: Which places I could question about TFS, Visual Studio and ALM? We are going to applying VSTS 2010 in our company. This includes Visual Studio, TFS, TFS Build and ALM. It's predictable that we would encounter a wave of new questions about their usage.
But the problem is I don't know which places we could do questioning. StackOverflow is programming base question site and ServerFault is not very active. How do you think about? Which places and their advantages and disadvantages?
afsharm

A: You could ask your questions here, there is already a handful of question on tfs, visual-studio and msbuild.
You could also ask on Team System forum MSDN. (Or both)

A: We are trying to start a Visual Studio ALM community on Stack Exchange that is dedicated to these questions.
If you want to join in you can Commit to the Visual Studio ALM proposal.

A: Whilst you wait for the ALM site to get to beta these sites/blogs might help you:

*

*The WoodwardWeb this is a very useful site for me.

*Brian Harrys TFS blog


text:
Q: how to remove history for last page use PHP?
I want to delete history for the last page that was opened by the user using PHP.

A: If you mean browser history, the answer is simple. It's not possible without using js and additional browser extensions. See related question.


text:
Q: Add Facebook Open Graph in Magento Products I'm trying to show the product image when sharing a product on Facebook.
The issue is that the image isn't added all the times. The first share is without image, the second one works.
    <?
$og = [];
$og['title'] = $this->getTitle();
$og['site_name'] = Mage::app()->getStore()->getName();
$og['description'] = strip_tags($this->getDescription());
$og['url'] = $this->helper('core/url')->getCurrentUrl();

if(Mage::registry('current_product')):
    $product = Mage::registry('current_product');
    $og['title'] = $product->getName();
    $og['type'] = 'product';
    $og['image'] = $this->helper('catalog/image')->init($product, 'image');
    $og['description'] = strip_tags(($product->getShortDescription()));
    $og['price:amount'] = Mage::registry('product')->getFinalPrice();
    $og['price:currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
elseif(Mage::registry('current_category')):
    $og['type'] = 'product.group';
elseif((Mage::getSingleton('cms/page')->getIdentifier() == 'home' &&
    Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms')) :
    $og['type'] = 'website';
else:
    $og['type'] = 'article';
endif;
?>
<? foreach($og as $key => $value): ?>
<meta property="og:<?= $key ?>" content="<?= $value ?>">
<? endforeach; ?>


text:
Q: Ionic how to image from data of array I need to show the image from array. And the array is already in array.
Example like this
{
title:xyz
attachments: [
{
image:'xyz.com'
}]}

im showing like this but image is not showing just title is showing
    <ion-card *ngFor="let x of art">

{{x.title}}

    </ion-card>

but its not showing image Its showing unexpeted image of cross camera

[![enter image description here][2]][2]

A: That [ on the attachments line indicates that its an array of objects.
You need to access [0] like this:
<ion-card *ngFor="let x of art">

{{x.title}}

</ion-card>

I think to be safe you should also put a ? in there but this is just off the top of my head, I haven't double-checked it:
<ion-card *ngFor="let x of art">

{{x.title}}

</ion-card>

Basically, if I got the syntax right then it won't show an error if there are no attachments in that Art item.
It's called the "Angular Safe Navigation Operator" if you want to research it more.


text:
Q: How to send Java mail with error trapping and reports My Windows Java  app needs to send individualized email to multiple recipients. The user must provide host, port, username, password, and of course recipient addresses. I'd like there to be meaningful reports if something goes wrong, e.g., "Failed to connect. Check username & password". If connect fails, no attempt to send should be made. Also, Email addresses should be validated as to format, and skipped if invalid.
I've looked at many examples that have helped me to create the working code below. It's doing a fair job of telling the user what was wrong, e.g., host doesn't exist, username or password wrong, etc. but it's inelegant at best.
I'm aware of SendFailedException and expect that it's what I need, but have yet found an example complete and simple enough to show me how to fit it my needs. Examples I've seen so far are either too simple, or too complex and embedded in large projects. I'm hoping someone can tell me if I'm on the right track at all, or how to improve it.
Here's my code (revised 2019 Sep 2):
public class SimpleMail2 {
private static String host;
private static String port;
private static String username;
private static String password;
private static String from;

private void sendAction(){
    host =  "smtp.gmail.com"; //"nx.dnslinks.com"; //
    port = "587";
    username = "jagman653@gmail.com"; //eds653@concoursbuilder.us";
    password =  "xxxxx";
    from = "usere123@concoursbuilder.us";
    String [] recipients = {"usera123@concoursbuilder.us", // Good
                            "userb123@concoursbuilder-us", // Valid according to RFC 822, but deemed INVALID for typical recipients.
                            "userc123concoursbuilder.us",  // Invalid format... no @
                            "userX123@concoursbuilder.us", // Valid format but no such mailbox at concoursbuilder.us
                            "hurt123@aol-com",  // Invalid format
                            "userc123@concoursbuilder.us"}; // Good

    // Prevalidate all recipient addresses
    ArrayList<String> goodAddrs = new ArrayList<>();
    System.out.println("Prevalidate email addresses.");
    for(String recip : recipients){
        System.out.println("recip: " + recip);
        boolean isOK = validateEmail(recip); //Valid according to RFC 822, but deemed INVALID for typical recipients.
        if(isOK){
            String msg;
            goodAddrs.add(recip);
            msg = "Good email address: " + recip;
            System.out.println(msg);
        } else {
            String msg;
            msg = " Bad email address: " + recip;
            System.out.println(msg);
        }
    }
    String[] goodAddrAry = new String[goodAddrs.size()];
    goodAddrAry = goodAddrs.toArray(goodAddrAry);
    int result = senderToAll(goodAddrAry);
    System.out.println("There were " + result + " successful sends and " + (recipients.length - result) + " failures.\n");
}

private int senderToAll(String [] recipients){
    System.out.println("Starting senderToAll\n\n");
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.user", username);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true"); //TLS
    // Note that an authenticator is incorporated in the session instance.
    Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });

    Transport transport = null;
    int successfulSends = 0;
    try {
        transport = mailSession.getTransport();
    } catch (NoSuchProviderException ex) {
        String msg = ex.getMessage();
        System.out.println(msg  + "\n");
        Logger.getLogger(SimpleMailDialog.class.getName()).log(Level.SEVERE, null, ex);
        return successfulSends;
    }
    try{
        if(!transport.isConnected())
            transport.connect();
    } catch ( javax.mail.MessagingException mex){
       String msg = mex.getMessage();
       String msg2;
       if(msg.contains("Unknown SMTP host") || msg.contains("DNS Error")) {
           msg2 =  "MessagingException while trying to connect: Could not connect. Check eMail host name" ;
           System.out.println(msg2);
       } else if(msg.contains("Could not connect to SMTP host")){
           msg2 =  "MessagingException while trying to connect: Could not connect. Check eMail host name & port" ;
           System.out.println(msg2);
       }
       else if(msg.contains("authentication failed") || msg.contains("535")){
            msg2 =  "MessagingException while trying to connect: Authentication failed. Check user eMail address & password.";
            System.out.println(msg2);
       }  else {
            msg2 =  "MessagingException while trying to connect: " + mex.getMessage();
            System.out.println(msg2);
       }
       return successfulSends; // no sends will be attempted
    }
    for(String recip : recipients){
        MimeMessage message = new MimeMessage(mailSession);
        try {
            message.setContent("This is sent to " + recip + " using SimpleMail", "text/plain");
        } catch (MessagingException ex) {
            String msg2 =  "MessagingException while trying to set content: " + ex.getMessage();
            System.out.println(msg2);
            Logger.getLogger(SimpleMailDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
        boolean result = true;
        try {
            result = senderToSingle(message, transport, recip, from);
        } catch (Exception ex) {
            String msg2 =  "Exception while sending to " + recip + "message: " + ex.getMessage();
            System.out.println(msg2);
            Logger.getLogger(SimpleMailDialog.class.getName()).log(Level.SEVERE, null, ex);
            result = false;
        }
        if(result){
           String msg = "Sent to " + recip;
           System.out.println(msg);
           successfulSends++;
        } else {
           String msg = "NOT Sent to " + recip;
           System.out.println(msg);
        }
   }

    if(transport.isConnected()){
        try {
            transport.close();
        } catch (MessagingException ex) {
           String msg = "Failed to close connection";
           System.out.println(msg);
           Logger.getLogger(SimpleMailDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
   return successfulSends;
}

public static boolean senderToSingle(MimeMessage message, Transport transport, String recip, String from) throws Exception{
    message.setFrom(new InternetAddress(from));
    InternetAddress[] toAddrs = InternetAddress.parse(recip);
    InternetAddress[] replyToAddrs = InternetAddress.parse(from);
message.setRecipient(javax.mail.Message.RecipientType.TO, toAddrs[0]);
    message.setReplyTo(replyToAddrs);
    Address[] toRecips = message.getRecipients(javax.mail.Message.RecipientType.TO);
    String msg2;
    try {
        transport.sendMessage(message, toRecips);
    } catch (MessagingException ex){
        String msg = ex.getMessage();
        if(msg.contains("Invalid Address") || msg.contains("User unknown")){
            msg2 =  "MessagingException: " + recip + " is an invalid address. ";
            System.out.println(msg2);
            return false;
        } else if(msg.contains("Mailbox unavailable") ){
            msg2 =  "MessagingException:  mailbox unavailable while attempting to send . " + recip ;
            System.out.println(msg2);
            return false;
        } else {
            msg2 =  "MessagingException: " +  msg + " for recipient " + recip ;
            System.out.println(msg2);
            return false;
        }
    }
    return true;
}

public boolean validateEmail(String email) {
    boolean isValid = false; // this value never used
    try {
        InternetAddress internetAddress = new InternetAddress(email, true); // strict
        internetAddress.validate(); // this throws AddressException if it doesn't meet RFC822 rules
        // There is a "@" since otherwise it would have thrown AddressException
        //Check to be sure it also has a DOT after the @ ... i.e., the most common form of address
        String[] splitArray = email.split("@");
        if(splitArray[1].contains(".")) isValid = true;
    } catch (AddressException e) {
        System.out.println("AddressException in MyJavaUtils validateEmail(). Bad eMail address: " + email);
        return  false;
    }
    return isValid;
}

public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(SimpleMailDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(SimpleMailDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(SimpleMailDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(SimpleMailDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            SimpleMail2 smt = new SimpleMail2();
            smt.sendAction();
        }
    });
}

}

A: Finally found a more complete example of SendFailedException usage here:
https://javaee.github.io/javamail/#Samples. See Max Spivak's public class transport. For my needs, I had to modify it to do Authentication. Works great, but I'm curious about his including a Thread Sleep after the sendmessage.


text:
Q: Crash interacting with NSUserDefaults and NSArray I have an NSMutableArray in which I am adding objective and storing in user defaults, but while adding it is crashing.
 if ([[NSUserDefaults standardUserDefaults] objectForKey:@"bssidObserverArray"]) {
        bssidObserverArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"bssidObserverArray"];
    }

   if (bssidObserverArray.count > 0) {
        if (![bssidObserverArray containsObject:vendorID]) {
            NSLog(@"bssidObserverArray %@",bssidObserverArray);
            // In this line app is getting crashed
                [bssidObserverArray addObject:vendorID];
                [[NSUserDefaults standardUserDefaults] setObject:bssidObserverArray forKey:@"bssidObserverArray"];

        }
    }else{
        [bssidObserverArray addObject:vendorID];
        [[NSUserDefaults standardUserDefaults] setObject:bssidObserverArray forKey:@"bssidObserverArray"];
    }

Any suggestions would be more helpful.

A: Assuming bssidObserverArray is NSMutable array then come the problem here .
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"bssidObserverArray"]) {
        bssidObserverArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"bssidObserverArray"];
    }

since NSUserdefaults returns immutable. you can do like this
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"bssidObserverArray"]) {
        NSArray *someArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"bssidObserverArray"];
        bssidObserverArray = [someArray mutableCopy];

    }


text:
Q: Unable to start service in Android I made I widget for reading news-items. If I put one widget at my homescreen, everything is fine. But if I put a seconde one at my homescreen and I remove it, the service of the widget stops. So if the widget gets in the update methode, an error occurs.
java.lang.RuntimeException: Unable to start service news.WidgetActivity$UpdateService@405231d8 with Intent { flg=0x10000000 cmp=news/.WidgetActivity$UpdateService bnds=[26,97][79,151] }: java.lang.NullPointerException

A nullpointer is at this line:
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);

Here the code:
public static class UpdateService extends Service {
    @Override
    public void onStart(Intent intent, int startId) {

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);

        remoteViews.setViewVisibility(R.id.WidgetRefresh_btn, View.GONE);
        remoteViews.setViewVisibility(R.id.progressWidget, View.VISIBLE);

        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

        WidgetActivity.Widget.onUpdate(context, appWidgetManager, appWidgetIds);

    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

A: Your context object is probably null. Since you are in a service, which extends Context, you may as well use this.getPackageName() or just getPackageName() instead.


text:
Q: threads for reading and writing java i'm reading data from serial port for average interval say 1 second,and at the same time writing read data to textArea and textfile,problem is i'm not getting correct data at some time,may be because i'm doing all three process in a single program,how to do writing to text area and text file by separate thred?
this is my code:
import java.io.BufferedWriter;
import java.io.File;

import java.io.FileWriter;

import java.io.IOException;
import java.io.InputStream;

import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Iterator;

import java.util.TooManyListenersException;
import java.util.TreeMap;

import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
import javax.swing.JOptionPane;

import com.pressure.constants.Constants;

import com.pressure.online.OnlineStartWindow;

public class SerailReader implements SerialPortEventListener {

    // DECLARES INPUT STREAM TO READ SRIAL PORT
    private InputStream inputStream;
    // DECLARES PORT
    private CommPortIdentifier port;
    private SerialPort serialPort;

    // DATE TO CREATE FILE NAME
    private static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yy");

    private int index = 0;

    private File file;

    private OnlineStartWindow onlineStartwindow;

    private int[] tempIntArray = new int[233];
    private int newData = 0;

    private String outFolder;

    private String filename = "0";

    private FileWriter fileWriter;

    private BufferedWriter buffOut;
    private StringBuffer line;
    private String packetFilename;

    TreeMap<Integer, Float> channelMap = new TreeMap<Integer, Float>();

    ThreadPrintsAndWrites p;

    public FileWriter getFileWriter() {
        return fileWriter;
    }

    public void setFileWriter(FileWriter fileWriter) {
        this.fileWriter = fileWriter;
    }

    public BufferedWriter getBuffOut() {
        return buffOut;
    }

    public void setBuffOut(BufferedWriter buffOut) {
        this.buffOut = buffOut;
    }

    // SETTER GETTER TO OnlineStartwindow OBJECT
    public OnlineStartWindow getOnlineStartwindow() {
        return onlineStartwindow;
    }

    public void setOnlineStartwindow(OnlineStartWindow onlineStartwindow) {
        this.onlineStartwindow = onlineStartwindow;
    }

    // SETTER GETTER TO SERIALPORT
    public SerialPort getSerialPort() {
        return serialPort;
    }

    public void setSerialPort(SerialPort serialPort) {
        this.serialPort = serialPort;
    }

    // ********* connects to serial port ***********//
    public void SerialReadmethod(OnlineStartWindow onlineStartwindow,
            String outFolderPath) throws Exception {

        setOnlineStartwindow(onlineStartwindow);
        outFolder = outFolderPath;
        // SELECTS PORT NAME SELECTED

        port = CommPortIdentifier.getPortIdentifier(getOnlineStartwindow()
                .getComPort());
        System.out.println("port name " + port);

        // CHEAK WETHER SELECTED PORT AVAILABLE OR NOT
        if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {

            if (port.getName().equals(getOnlineStartwindow().getComPort())) {

                JOptionPane.showMessageDialog(null, "Successpully opened port",
                        "Online Dump", JOptionPane.INFORMATION_MESSAGE);

            }

        }

        // OPENS SERAIL PORT
        serialPort = (SerialPort) port.open("SimpleReadApp1111", 1000);

        // OPENS SERIAL PORT INPUT STREAM TO READ DATA
        try {
            inputStream = serialPort.getInputStream();

        } catch (IOException e) {
            System.out.println("IO Exception");
        }

        // ADDS LISTNER TO SERIALPORT
        try {
            serialPort.addEventListener(this);

        } catch (TooManyListenersException e) {
            System.out.println("Tooo many Listener exception");
        }

        // EVENT GENERATED WHEN DATA WILL BE AVAILABELE ON SERIALPORT
        // INPUTSTREAM
        serialPort.notifyOnDataAvailable(true);

        try {

            // SETS SELECTED BAUDRATE

            int BAUDRATE = Integer.parseInt((getOnlineStartwindow()
                    .getBaudRate()).trim());

            // SETS SELECTED DATA BITS

            int DATABITS = Integer.parseInt(getOnlineStartwindow()
                    .getDataBits().trim());
            if (DATABITS == 8) {
                DATABITS = SerialPort.DATABITS_8;
            } else if (DATABITS == 7) {
                DATABITS = SerialPort.DATABITS_7;
            } else if (DATABITS == 6) {
                DATABITS = SerialPort.DATABITS_6;
            } else if (DATABITS == 5) {
                DATABITS = SerialPort.DATABITS_5;
            }

            // SETS SELECTED STOPBITS
            int STOPBITS = 0;

            if (getOnlineStartwindow().getStopBits() == "1") {
                STOPBITS = SerialPort.STOPBITS_1;
            } else if (getOnlineStartwindow().getStopBits() == "1.5") {
                STOPBITS = SerialPort.STOPBITS_1_5;
            } else if (getOnlineStartwindow().getStopBits() == "2") {
                STOPBITS = SerialPort.STOPBITS_2;
            }

            // SETS SELECTED PARITY
            int PARITY = 0;
            if (getOnlineStartwindow().getParity() == "NONE") {
                PARITY = SerialPort.PARITY_NONE;
            } else if (getOnlineStartwindow().getParity() == "EVEN") {
                PARITY = SerialPort.PARITY_EVEN;
            } else if (getOnlineStartwindow().getParity() == "ODD") {
                PARITY = SerialPort.PARITY_ODD;
            }

            // SETS SELECTED FLOW CONTROL
            int FLOWCONTROL = 0;
            if (getOnlineStartwindow().getFlowControl() == "NONE") {
                FLOWCONTROL = SerialPort.FLOWCONTROL_NONE;
            } else if (getOnlineStartwindow().getFlowControl() == "XON/XOFF") {
                FLOWCONTROL = SerialPort.FLOWCONTROL_XONXOFF_IN;
            }

            serialPort
                    .setSerialPortParams(BAUDRATE, DATABITS, STOPBITS, PARITY);

            // no handshaking or other flow control
            serialPort.setFlowControlMode(FLOWCONTROL);

        } catch (UnsupportedCommOperationException e) {
            System.out.println("UnSupported comm operation");
        }

    }

    // *********this method will automaticaly calls when u get data on port and
    // arranges packet from start frame to end frame *************//
    public void serialEvent(SerialPortEvent event) {

//      switch (event.getEventType()) {
//
//      case SerialPortEvent.DATA_AVAILABLE:

        if(event.getEventType()==SerialPortEvent.DATA_AVAILABLE){

                //dataAvailabel = inputStream.available();

                // READING DATA CHARECTER BY CHARECTER

                while (newData != -1) {
                    try {
                        newData = inputStream.read();
                        if (newData == -1) {
                            break;
                        }
                        if (Constants.SF == (char) newData) {
                            index = 0;
                            // System.out.println("start frame");
                        }
                        tempIntArray[index] = newData;

                        if (Constants.EF == (char) newData) {
                            selectToDispalyAndWrite(tempIntArray);
                            // disp(tempIntArray);

                        }
                        index++;

                    } catch (IOException ex) {
                        System.err.println(ex);
                        // return;
                    }
                }
                // ///////////////// completes
        }

    }

    // DISPLYS PACKET TO TEXT AREA AND CREATES .PSI FILE
    public void selectToDispalyAndWrite(int[] readBufferArray) {

        if (getOnlineStartwindow().getDump().isSelected()) {
            packetFilename = Integer.toString(readBufferArray[1])
                    + Integer.toString(readBufferArray[2])
                    + Integer.toString(readBufferArray[3]);

            try {
                if (getOnlineStartwindow().getFileTypeSelection() == "text") {

                    displayAndWriteToTextFile(readBufferArray);

                } else {
                    displayAndWriteToExcelFile(readBufferArray);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            printToTextArea(readBufferArray);
        }
    }

    public void printToTextArea(int[] readBufferArray) {
        int i = 0;
        int portname = 0;
        Float portval = 0.0f;

        int len = 0;
        i = 0;
    writeloop:   while (len != readBufferArray.length) {
            // while ((char) readBufferArray[i] != Constants.EF) {
            if ((char) readBufferArray[i] == Constants.SF) {

                // WRITES DASH LINE TO TEXT AREA
                getOnlineStartwindow()
                        .getTextArea()
                        .append(
                                "\r\n\r\n-----------------------------------------------------------------------\r\n");

                getOnlineStartwindow().getTextArea().append(
                        "Time :" + readBufferArray[i + 4] + " Min "
                                + readBufferArray[i + 5] + " Sec.");
                getOnlineStartwindow()
                        .getTextArea()
                        .append(
                                "\r\n-----------------------------------------------------------------------\r\n");

            }
            if ((char) readBufferArray[i] == Constants.EF) {
                for (Iterator<Integer> iterator = channelMap.keySet()
                        .iterator(); iterator.hasNext();) {

                    int key = iterator.next();
                    Float value = channelMap.get(key);

                    getOnlineStartwindow().getTextArea().append(
                            "Port_" + key + "           " + value + "\r\n");

                }
                channelMap.clear();
                break writeloop;
            }
            i++;
        }

    }

    public void displayAndWriteToTextFile(int[] readBufferArray)
            throws IOException {
        int i = 0;
        int portname = 0;
        Float portval = 0.0f;

        if (!(filename.equalsIgnoreCase(packetFilename))) {
            filename = packetFilename;
            if (buffOut != null && fileWriter != null) {
                drawLine('*');
                buffOut.close();
                fileWriter.close();

            }

            // GET CURRENT DATE
            Date date = new Date();
            file = new File(outFolder + "\\" + SDF.format(date) + "-"
                    + packetFilename + ".txt");

            if (!file.exists()) {
                fileWriter = new FileWriter(file, true);
                buffOut = new BufferedWriter(fileWriter);

                drawLine('*');

                drawLine('*');
            } else {
                fileWriter = new FileWriter(file, true);
                buffOut = new BufferedWriter(fileWriter);
            }

        }

        // LOOP TO DISPLY ALL PORT NAME AND PRESSURE VALUES
        int len = 0;
        i = 0;
        writeloop: while (len != readBufferArray.length) {
            // while ((char) readBufferArray[i] != Constants.EF) {
            if ((char) readBufferArray[i] == Constants.SF) {

                // WRITES DASH LINE TO TEXT AREA
                getOnlineStartwindow()
                        .getTextArea()
                        .append(
                                "\r\n\r\n-----------------------------------------------------------------------\r\n");

                getOnlineStartwindow().getTextArea().append(
                        "Time :" + readBufferArray[i + 4] + " Min "
                                + readBufferArray[i + 5] + " Sec.");
                getOnlineStartwindow()
                        .getTextArea()
                        .append(
                                "\r\n-----------------------------------------------------------------------\r\n");

                drawLine('-');
                buffOut.write("TIME: " + readBufferArray[i + 4] + " Min "
                        + readBufferArray[i + 5] + " Sec." + "\r\n\r\n");

            }
            if ((char) readBufferArray[i] == Constants.ST) {

                portname = readBufferArray[i + 1];
                portval = getFloatValue(i);
                channelMap.put(portname, portval);

            }
            if ((char) readBufferArray[i] == Constants.EF) {
                for (Iterator<Integer> iterator = channelMap.keySet()
                        .iterator(); iterator.hasNext();) {

                    int key = iterator.next();
                    Float value = channelMap.get(key);

                    getOnlineStartwindow().getTextArea().append(
                            "Port_" + key + "           " + value + "\r\n");

                }
                channelMap.clear();
                break writeloop;
            }
            i++;
        }

    }
}

Thanks in advance

A: Here an approach from a design standpoint.

*

*Create a class type for the data. This will be a container (inherit the appropriate queue). And inside of this class as you set and get the data make sure you lock.

*Create a new thread in main to start the serial port and read the messages. Pass the thread one object (your list class object). The serial port will chuck data into this list. This will be sets in the object.

*You main thread (the window) will have a timer that fires and reads the data from queue. You may have to play with the timer some. You don't want it firing too often and eating all your processing time in the main window. However if it is too slow you may not be updating enough and getting messages out of the queue when they are available. This timer should get all of the data out the queue and display it.

The queue and the lock are the important part here. The queue will keep messages in order. The lock will make sure you don't try to write new data to your queue while you are in the middle of reading data.

A: I was under the impression that Java does not support serial port for Windows, it only does it for Solaris or Linux.
your class should implement the Runnable Interface. and create a thread that reads from the serial port in its run method.
The Main thread could do the writing part to the TextArea.
You may need to do some synchronization between the Main Thread and the Runnable so that writing to the TextArea/File only takes place after appropriate data has been read from the port.


text:
Q: How to show image when a specific key is pressed in p5js? I'm new to p5js :)
When users press a certain key between 1-0 on the keyboard, a certain sound plays and random image shows. I tried this...
function keyPressed() {
   if (key === '2') {
        songA.play()
        image(imgB1, random(windowWidth), random(windowHeight), img.width/2, img.height/2);
   }

But p5js only reads "image" in draw function. Then i tried keyisdown in the draw function and tried entering the keyCodes for each number, for instance 1 is 49 I believe, but it didn't work.
  if (keyIsDown(49)) {
     songA.play()
     image(imgB1,random(windowWidth), random(windowHeight), img.width/2, img.height/2);
}}

I'm basically copying https://openprocessing.org/sketch/441971 from openprocessing which is similar to p5js but not really. Help?
Thanks!

A: *

*Make sure your image is being preloaded in the setup() function

*When you display the image, you are referencing "img" instead of imgB1, which means p5js doesn't know what size to display the image at, so I assume it defaults to 0. To fix this, just replace img with imgB1.


text:
Q: Create python nested json from jsons in list I have a list of strings (jsons). pprint.pprint(jsondump) gives:
[
    '{"Parent\'s Name:": "xx", "School Award Won:": "xx", "Rank:": "862"}',
    '{"Parent\'s Name:": "xx", "School Award Won:": "xx", "Rank:": "872"}',
    '{"Parent\'s Name:": "xx", "School Award Won:": "xx", "Rank:": "333"}'
]

I want to covert it to a single json like:
{
    {"Parent\'s Name:": "xx", "School Award Won:": "xx", "Rank:": "862"},
    {"Parent\'s Name:": "xx", "School Award Won:": "xx", "Rank:": "872"},
    {"Parent\'s Name:": "xx", "School Award Won:": "xx", "Rank:": "333"}
}

I know this isn't valid json, can anyone find out how?

A: *

*json.dumps('[' + ','.join(your_list) +']')
Here you create one string, which begins and ends by brackets, like JSON list, and contains all your strings, separated by comma. After creating - dump into python list.

*[json.dumps(el) for el in your_list]
Here you dump every element to python object and transform the result to python list by list comprehensions


text:
Q: webpack-cli failed to load webpack.config.js I'm trying to change the theme of a sylius project to a bootstraptheme and I'm using this tutorial https://docs.sylius.com/en/1.9/book/themes/bootstrap-theme.html to do it but I got an error something missing and didn't work.
I've tried this commands in my Ubuntu 18.4 system:
yarn encore dev
yarn encore production
yarn encore dev-server

This is the result:
yarn run v1.22.5
$ /home/safa/git_environment/MyFirstShop/node_modules/.bin/encore production
Running webpack ...

 WARNING  Webpack Encore requires version ^9.0.1 || ^10.0.0 || ^11.0.0 of sass-loader, but your version (7.3.1) is too old. The related feature will probably *not* work correctly.
 WARNING  Webpack Encore requires version ^9.0.1 || ^10.0.0 || ^11.0.0 of sass-loader, but your version (7.3.1) is too old. The related feature will probably *not* work correctly.
 WARNING  Webpack Encore requires version ^9.0.1 || ^10.0.0 || ^11.0.0 of sass-loader, but your version (7.3.1) is too old. The related feature will probably *not* work correctly.
 WARNING  Webpack Encore requires version ^9.0.1 || ^10.0.0 || ^11.0.0 of sass-loader, but your version (7.3.1) is too old. The related feature will probably *not* work correctly.
[webpack-cli] Failed to load '/home/safa/git_environment/MyFirstShop/webpack.config.js' config
[webpack-cli] ReferenceError: bootstrapTheme is not defined
    at Object.<anonymous> (/home/safa/git_environment/MyFirstShop/webpack.config.js:52:1)
    at Module._compile (/home/safa/git_environment/MyFirstShop/node_modules/v8-compile-cache/v8-compile-cache.js:192:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:849:19)
    at require (/home/safa/git_environment/MyFirstShop/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
    at loadConfig (/home/safa/git_environment/MyFirstShop/node_modules/webpack-cli/lib/webpack-cli.js:1327:31)
    at WebpackCLI.resolveConfig (/home/safa/git_environment/MyFirstShop/node_modules/webpack-cli/lib/webpack-cli.js:1459:44)
    at WebpackCLI.createCompiler (/home/safa/git_environment/MyFirstShop/node_modules/webpack-cli/lib/webpack-cli.js:1837:33)
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

webpack.config.js:
const path = require('path');
const Encore = require('@symfony/webpack-encore');

const syliusBundles = path.resolve(__dirname, 'vendor/sylius/sylius/src/Sylius/Bundle/');
const uiBundleScripts = path.resolve(syliusBundles, 'UiBundle/Resources/private/js/');
const uiBundleResources = path.resolve(syliusBundles, 'UiBundle/Resources/private/');

// Shop config
Encore
  .setOutputPath('public/build/shop/')
  .setPublicPath('/build/shop')
  .addEntry('shop-entry', './assets/shop/entry.js')
  .disableSingleRuntimeChunk()
  .cleanupOutputBeforeBuild()
  .enableSourceMaps(!Encore.isProduction())
  .enableVersioning(Encore.isProduction())
  .enableSassLoader();

const shopConfig = Encore.getWebpackConfig();

shopConfig.resolve.alias['sylius/ui'] = uiBundleScripts;
shopConfig.resolve.alias['sylius/ui-resources'] = uiBundleResources;
shopConfig.resolve.alias['sylius/bundle'] = syliusBundles;
shopConfig.name = 'shop';

Encore.reset();
Encore
  .setOutputPath('public/bootstrap-theme')
  .setPublicPath('/bootstrap-theme')
  .addEntry('app', './themes/BootstrapChildTheme/assets/entry.js')
  .disableSingleRuntimeChunk()
  .cleanupOutputBeforeBuild()
  .enableSassLoader()
  .enableSourceMaps(!Encore.isProduction())
  .enableVersioning(Encore.isProduction());

const bootstrapThemeConfig = Encore.getWebpackConfig();
bootstrapThemeConfig.name = 'bootstrapTheme';

bootstrapTheme.resolve.alias['sylius/ui'] = uiBundleScripts;
bootstrapTheme.resolve.alias['sylius/ui-resources'] = uiBundleResources;
bootstrapTheme.resolve.alias['sylius/bundle'] = syliusBundles;
bootstrapTheme.externals = Object.assign({}, bootstrapTheme.externals, { window: 'window', document: 'document' });
bootstrapTheme.name = 'admin';

module.exports = [shopConfig, bootstrapTheme];

package.json:
{
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.35",
    "@fortawesome/free-brands-svg-icons": "^5.15.3",
    "@fortawesome/free-regular-svg-icons": "^5.15.3",
    "@fortawesome/free-solid-svg-icons": "^5.15.3",
    "axios": "^0.21.1",
    "babel-polyfill": "^6.26.0",
    "bootstrap": "^5.0.1",
    "bootstrap.native": "^3.0.15",
    "chart.js": "^2.9.3",
    "form-serialize": "^0.7.2",
    "glightbox": "^3.0.9",
    "gulp-cli": "^2.3.0",
    "jquery": "^3.5.0",
    "jquery.dirtyforms": "^2.0.0",
    "lightbox2": "^2.9.0",
    "semantic-ui-css": "^2.2.0",
    "slick-carousel": "^1.8.1"
  },
  "devDependencies": {
    "@symfony/webpack-encore": "^1.3.0",
    "babel-core": "^6.26.3",
    "babel-plugin-external-helpers": "^6.22.0",
    "babel-plugin-module-resolver": "^3.1.1",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-register": "^6.26.0",
    "dedent": "^0.7.0",
    "eslint": "^4.19.1",
    "eslint-config-airbnb-base": "^12.1.0",
    "eslint-import-resolver-babel-module": "^4.0.0",
    "eslint-plugin-import": "^2.11.0",
    "fast-async": "^6.3.7",
    "gulp": "^4.0.2",
    "gulp-chug": "^0.5",
    "gulp-concat": "^2.6.0",
    "gulp-debug": "^2.1.2",
    "gulp-if": "^2.0.0",
    "gulp-livereload": "^4.0.1",
    "gulp-order": "^1.1.1",
    "gulp-sass": "^4.0.1",
    "gulp-sourcemaps": "^1.6.0",
    "gulp-uglifycss": "^1.0.5",
    "lodash.throttle": "^4.1.1",
    "merge-stream": "^1.0.0",
    "node-sass": "^6.0.0",
    "rollup": "^0.60.2",
    "rollup-plugin-babel": "^3.0.4",
    "rollup-plugin-commonjs": "^9.1.3",
    "rollup-plugin-inject": "^2.0.0",
    "rollup-plugin-node-resolve": "^3.3.0",
    "rollup-plugin-uglify": "^4.0.0",
    "sass-loader": "^7.0.0",
    "upath": "^1.1.0",
    "webpack-cli": "^4.7.0",
    "yargs": "^17.0.1"
  },
  "scripts": {
    "build": "gulp build",
    "gulp": "gulp build",
    "lint": "yarn lint:js",
    "lint:js": "eslint gulpfile.babel.js",
    "watch": "gulp watch"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Sylius/Sylius.git"
  },
  "author": "Paweł Jędrzejewski",
  "license": "MIT"
}

composer.json:
   {
    "keywords": ["symfony", "sylius", "distribution", "ecommerce", "cart", "shopping"],
    "type": "project",
    "license": "proprietary",
    "homepage": "https://sylius.com",
    "authors": [
        {
            "name": "Paweł Jędrzejewski"
        },
        {
            "name": "Sylius project"
        },
        {
            "name": "Community contributions"
        }
    ],
    "require": {
        "php": "^7.3",
        "bitbag/payu-plugin": "^1.8",
        "friendsofsymfony/oauth-server-bundle": ">2.0.0-alpha.0 ^2.0@dev",
        "sylius/bootstrap-theme": "^0.1.2",
        "sylius/paypal-plugin": "^1.1",
        "sylius/sylius": "~1.9.0",
        "symfony/dotenv": "^4.4 || ^5.2",
        "symfony/flex": "^1.11"
    },
    "require-dev": {
        "behat/behat": "^3.7",
        "behat/mink-selenium2-driver": "^1.4",
        "dmore/behat-chrome-extension": "^1.3",
        "dmore/chrome-mink-driver": "^2.7",
        "friends-of-behat/mink": "^1.8",
        "friends-of-behat/mink-browserkit-driver": "^1.4",
        "friends-of-behat/mink-debug-extension": "^2.0",
        "friends-of-behat/mink-extension": "^2.4",
        "friends-of-behat/page-object-extension": "^0.3",
        "friends-of-behat/suite-settings-extension": "^1.0",
        "friends-of-behat/symfony-extension": "^2.1",
        "friends-of-behat/variadic-extension": "^1.3",
        "lchrusciel/api-test-case": "^5.0",
        "phpspec/phpspec": "^7.0",
        "phpstan/extension-installer": "^1.0",
        "phpstan/phpstan": "0.12.80",
        "phpstan/phpstan-doctrine": "0.12.32",
        "phpstan/phpstan-webmozart-assert": "0.12.12",
        "phpunit/phpunit": "^8.5",
        "stripe/stripe-php": "^6.43",
        "sylius-labs/coding-standard": "^3.2",
        "symfony/browser-kit": "^4.4 || ^5.2",
        "symfony/debug-bundle": "^4.4 || ^5.2",
        "symfony/intl": "^4.4 || ^5.2",
        "symfony/web-profiler-bundle": "^4.4 || ^5.2",
        "symplify/easy-coding-standard": "^8.3"
    },
    "conflict": {
        "symfony/form": "4.4.11|4.4.12"
    },
    "prefer-stable": true,
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        },
        "classmap": ["src/Kernel.php"]
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ],
        "post-create-project-cmd": [
            "@php bin/console sylius:inform-about-gus --ansi",
            "@php bin/console sylius:show-available-plugins --ansi"
        ]
    },
    "config": {
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true
    },
    "extra": {
            "sylius-theme": {
                "title": "Crimson Theme"
            }
        },

        "name": "acme/crimson-theme",
        "authors": [
            {
                "name": "James Potter",
                "email": "prongs@example.com"
            }
        ]

}

A: It's an old question but I had the same problem.
Updating the version of node in production to have the same as local solved my issue.


text:
Q: Position for scaled sprites is always the same - Unity (What Am I doing wrong?) First of all, I'm new to Unity and obviously I'm doing something wrong but I don't know what.
Take a look at the image below. There are three balls. The biggest one is the original size (imported) and the other two are scaled.
I wrote a code and gave these balls a linear force toward right edge of the camera. Camera size is 10 (which is 5 each way). When it reaches the edge it should bounce back to the left camera edge. It works but only the original one is bounced when it reaches the edge (other balls are bounced too at the same time, but they shouldn't because they haven't reached the edge).
All balls have the same position, but two are scaled and are bounced from "the air - check the image").

Code for changing direction is in the Update function. It looks like this:
if (rigidBody.transform.position.x > 5)
        {

            rigidBody.AddForce(new Vector2(-60,0));

        }

I appreciate all help.

A: The issue I see is that your code only checks the position to make the balls rebound. The position is probably measured at the center of the images (check this out!), so you have to take into consideration the width of each ball - actually, from the center, half the width.
To check if the position plus half width of the image has arrived to the limit you can use renderer.bounds.size as in:
if ((transform.position.x + renderer.bounds.size.x/2) > 5)
    {
        //change directions
        //do something else...
    }

Put in another words, the smaller the size of the ball, the more the x position has to grow to get to the limit, and then you make them rebound.
I strongly encourage, however, a different approach to prevent having everything hardcoded. Just suppose you change your camera size, you would have to rewrite everything again!
I would put colliders on both sides of the camera limits, and when your balls collide with them set an OnCollisionEnter function that makes them change directions. That is a little off course from your question, so I'll leave it there.
Good luck!


text:
Q: Dual booting ubuntu 14.04-windows 10 on separate ssd and efi partition I have a laptop with two ssd and one hdd (hdd is for storage,not os) and I have windows 10 installed on one ssd and I want to install ubuntu on other ssd. However I can not disconnect drives during the process as recommended on online guides because m.2 ssd's are under the motherboard and hard to reach.
Now for the background. I previously had one ssd and dual-booted with separate partitions. I deleted ubuntu but could not delete grub. Now that I have another brand new ssd and I fresh installed windows 10 on it and deleted the Windows from other ssd using disk management like I used for ubuntu. Note that I still have grub(I can only exit from grub by typing exit at booting and reach my Windows).
 My partitions look like this:
Disk 0: Old ssd, gonna use for ubuntu.
Disk 1: New ssd, windows installed.
Disk 2: HDD

Partitions:

Now for my questions:

*

*Should I move efi partitions(and maybe recoveries) to the new ssd before installing ubuntu?

*Can I install ubuntu without disconnecting drives during process?

*I guess I am going to install grub again. Could there be any problem if I overwrite current grub?


text:
Q: OS X: How to show all files in chooser dialogs On OS X 10.5 and 10.6 at least, the command to enable all files in Finder only affects Finder Windows -- the "/File /Open" dialogs on applications still show a limited set of files, ignoring nearly all the Unix stuff.
Is there a setting which enables ALL file dialogs of ALL types to show ALL files?  I really am a big boy and promise not to harm them! :)

A: Command - Shift - . when the dialog is open.


text:
Q: How to order an object of type "structure" based on names(c)? I have an object that looks like this:
structure(c(0, 2, 0, 3, 5, 0), .Names = c("6", "1", "3", "4", "2", "5" ))

I need the values of this object  to be in the order indicated by the names, if they would be integers and not characters as they are now. The object should be (2, 5, 0, 3, 0, 0) i don't mind it to be a vector or a matrix with row names but I simply couldn't order this object.
Thanks

A: You have a named vector. Function structure is a convenient way of packing your objects for distribution. Notice that you're missing a comma before .Names.
x <- structure(c(0, 2, 0, 3, 5, 0), .Names = c("6", "1", "3", "4", "2", "5" ))
right.order <- order(as.numeric(names(x)))
x[right.order]

1 2 3 4 5 6
2 5 0 3 0 0


text:
Q: Populating dropdown list with json I am new to jQuery. I am trying to populate dropdown list with json data. In this code I have received data with ajax. It is also shown in the alert in json format but the drop down list is not populated. I am stuck. Please help..
$.ajax({
                url: "http://10.0.2.2/Quizapp/getsubcategory.php",
                type: 'POST',
                data: data,
                beforeSend: function() {

                },
                success: function(data, textStatus, xhr) {
                    alert(data);
                    $.getJSON('data', function(data) {
                        employees = data.items1;
                        $.each(employees, function(index, employee) {
                            $("#subcategory").append("<option value='"+employee.scid+"'>"+employee.Name+"</option>");
                            //alert("1.."+employee.scid);
                        });
                    });
                },
                error: function(xhr, textStatus, errorThrown) {

                    alert(errorThrown);
                }
            });

A: You have two problems:

*

*You want $.parseJSON, not $.getJSON.

*You should not have "data" in quotes.

Your final result should look something like this:
var items = $.parseJSON(data).items1;
for (var i = 0; i < items.length; i++) {
   $("#subcategory").append("<option value='"+items[i].scid+"'>"+items[i].Name+"</option>");
}

Also, you should probably not build HTML strings like that because you then have to worry about quoting. Instead, do this:
$("#subcategory").append($("<option/>").attr("value", items[i].scid).html(items[i].name));


text:
Q: Hybrid Federated Search Results in SharePoint 2013 From SharePoint 2010 I am trying to setup a federated search between our SharePoint 2013 and SharePoint 2010 Farms. I want to show search results from SharePoint 2010 and SharePoint 2013 in my new SharePoint 2013 environment.
Is it possible to show federated search results from older version into later version of SharePoint?
I have seen multiple articles on setting up federated search including Microsoft but they all shows the same SharePoint version i.e online and on-premises.
Method i have tried so far.
1. Building Server to Server trust and publishing SharePoint 2010 Search Service to SharePoint 2013. (Both Web Applications on Classic Mode Authentication however i am unable to use the published service. I get multiple errors while using the published service related to Schema Property error and services Contract Mismatch.)
2. Configuring Remote SharePoint result sources and Query Rules
3. Creating new content source and providing SharePoint 2010 URL in it for crawling. (This method crawled only root site collection)
Any other possible way to achieve the target? Am i looking on the wrong side to do the stuff? Please guide.

A: What i understand, you trying to consume the SharePoint 2010 search in SharePoint 2013 which will not work.
What you have to do.

*

*Create a search service application in 2013 farm, this is your publishing farm

*Build the trust between other 2 farms( 2010 & 2013) farms. both farms will be consuming.

*after completing all steps to establishing trust then you have to make sure that default content access account has read permission on all web apps which you want crawl.

Here is good article to establish trust between farm.https://blogs.technet.microsoft.com/meamcs/2013/09/03/cross-farm-service-applications-integration-between-two-separate-sharepoint-farms/


text:
Q: exact example for JMS Topic in HornetQ I read the hornetQ documentation, confused a lot. Can someone give an exact example to create a JMS topic in hornetQ. I mean the xml configurations in hornetq-jms.xml and hornetq-configuration.xml. assume we have a topic named top and 2 subscribers named: sub1, sub2. what I get is that we should define two queues(one for each subscribers) and bind them to an address which is the topic name actually, but how the subscriber would know they should connect to which one?(They only know the topic name)

A: I think you are confused by the way HornetQ handles topics internaly in contrast to the way the JMS specification describes topics.
Let's start with the JMS specification. Here you have one topic, where n subscribers can listen to the messages, that will be published by a client. In JMS we talk only about the destination in singular, eg. we'll send a message to the topic, or the queue respectively.
HornetQ is a JMS Provider - a server that implements the JMS specification, so Java-clients can connect to it, and use the JMS-API. The JMS Provider might change, but the code should still work when using another JMS provider.
However, HornetQ does not distinguish internally the destinations (topic or queue), since it tries to be a generic messaging middleware. In HornetQ all topics or queues are implemented as "addresses" and "queues". When you use the HornetQ API (CoreAPI) instead of the JMS-API, you have to deal with such things. You should read the Address section in the HornetQ documentation:

In core, there is no concept of a Topic, Topic is a JMS only term.
  Instead, in core, we just deal with addresses and queues.
For example, a JMS topic would be implemented by a single address to
  which many queues are bound. Each queue represents a subscription of
  the topic. A JMS Queue would be implemented as a single address to
  which one queue is bound - that queue represents the JMS queue.

For an example how to use a topic with JMS via HornetQ, I stongly recommend the examples that come with HornetQ itself. After donwloading and extracting the hornetq archive, just go to the examples/jms/topic directory and see the readme.html for a brief overview how to implement and how to execute the example (mvn verify).


text:
Q: Checking Request.IsAjaxRequest always return false inside my asp.net mvc4 I have the following code inside my controller
public ActionResult Index(string searchTerm=null)
        {   System.Threading.Thread.Sleep(5000);
            var accountdefinition = repository.FindAccountDefinition(searchTerm).ToList();
            if (Request.IsAjaxRequest())
            { return PartialView("_CustomerTable",accountdefinition); }
        return View(accountdefinition);
        }

But if I call the above action method using an Ajax.beginform,, then the Request.IsAjaxRequest will return false and the partial view will not be returned
@using (Ajax.BeginForm(
new AjaxOptions{
    HttpMethod= "get",
    InsertionMode=InsertionMode.Replace,
    LoadingElementId = "progress",
    UpdateTargetId="customerTable"}))
    {

Search <input placeholder="Search by name.." name="searchTerm" type="text"> <input class="btn btn-success" type="submit" value="search" />

}

A: I ran across this issue and wasnt sure what black magic the jquery.unobtrusive-ajax.min.js file was doing but it was not working for me.  I was happy when I ran across this post which explains the very simple problem.
The author of the post declared that there is a header that needs to be populated.
X-Requested-With => 'XMLHttpRequest'
For Angular users that find this post I have included a snippet from above post.
var productsApp = angular.module('productsApp', []);

productsApp.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);

A: It seems to me that I did not include the jquery.unobtrusive-ajax.min.js

A: Hi try  this and change your view like this hope it's work for you
 @using (Ajax.BeginForm("Index", "controller", null, new AjaxOptions { HttpMethod = "post", InsertionMode = InsertionMode.Replace, LoadingElementId = "progress", UpdateTargetId = "customerTable" }))
        {

                Search
                <input placeholder="Search by name.." name="searchTerm" type="text">
                <input class="btn btn-success" type="submit" value="search" />

        }


text:
Q: Which context.xml is used First On my Tomcat 6.0.x I have a context.xml file in the conf directory and I also have a context.xml in the META-INF directory of a project deployed from netbeans6.9.1.
The context.xml contains the details of database to be connected...
Which among the two will be used by the application to connect to the database

*

*Context.xml in tomcat/conf

*Context.xml in project/META-INF

A: My understanding is that tomcat/conf/context.xml defines a set of "global", statically-configured contexts. Any WAR deployed with its own context.xml will be configured using that, rather than any of the contexts defined in the global one.


text:
Q: Interpolating data using the package move: How to create a movestack object? I have just started using R  for my masters thesis project, and i am trying to interpolate the sampling rate for my penguin tracking data using the package move. However when trying to create a movestack object i get this error:
Error in validityMethod(as(object, superClass)) :
  There are NA timestamps records

and this warning message
In addition: Warning messages:
1: In showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj = prefer_proj) :
  Discarded ellps WGS 84 in Proj4 definition: +proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs
2: In showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj = prefer_proj) :
  Discarded datum WGS_1984 in Proj4 definition

the code:
alltripsfiltered <- read.csv(file = "C:/Users/Admin/OneDrive - Massey University/Documents/Korora/GPS data for all trips/alltracksfiltered00.csv")

tracks.move<- move(x=alltripsfiltered$Long, y=alltripsfiltered$Lat, time =as.POSIXct(alltripsfiltered$datetime, format="%Y-%m-%d %H:%M:%OS", tz="UTC"), proj=CRS("+init=epsg:3857"), animal=alltripsfiltered$TripID)

and the data:
dput(alltripsfiltered[1:6, ])
structure(list(X = 1:6, Deployment = c(1L, 1L, 1L, 1L, 1L, 1L
), Device = c(2L, 2L, 2L, 2L, 2L, 2L), Box.no. = c("C23", "C23",
"C23", "C23", "C23", "C23"), Bird.no. = c(10825325L, 10825325L,
10825325L, 10825325L, 10825325L, 10825325L), Breeding.Stage = c(1L,
1L, 1L, 1L, 1L, 1L), Long = c(174.78327, 174.78326, 174.78332,
174.78323, 174.78325, 174.78277), Lat = c(-41.09482, -41.09491,
-41.09484, -41.09491, -41.09496, -41.09564), datetime = c("18/09/2020 4:13",
"18/09/2020 4:14", "18/09/2020 4:15", "18/09/2020 4:16", "18/09/2020 4:17",
"18/09/2020 4:18"), TripID = c(1L, 1L, 1L, 1L, 1L, 1L), Trip.no. = c(1L,
1L, 1L, 1L, 1L, 1L), Complete = c(0L, 0L, 0L, 0L, 0L, 0L), optional = c(TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE)), row.names = c(NA, 6L), class = "data.frame")

I am unsure if this is happening because of an issue in R or with my dataset. I intend on running the remainder of the code using the 'movestack' object to then split into separate trips so i can extract the values to use for calculating home range:
tracks.split<- split(tracks.move)
##interpolate the first track
track1interpolated<-interpolateTime(tracks.split$X1, time=as.difftime(1, units="mins"), spaceMethod=c('greatcircle'))
track1interpolated
##continue to do this for all tracks (change to X2, X3….),

A: Your datetime input is not as the same format as you put in the time argument :
tracks.move<- move(x=alltripsfiltered$Long, y=alltripsfiltered$Lat, time =as.POSIXct(alltripsfiltered$datetime, format="%d/%m/%Y %H:%M", tz="UTC"),
                   proj=CRS("+init=epsg:3857"), animal=alltripsfiltered$TripID)


text:
Q: Iphone OpenGL ES Reuse or draw once Texture scene Ok guys, so I am drawing charts in OpenGL for Iphone. And everything is ok, until I use that Texture2D class to draw X axis labels and Y axis labels. The function of drawing labels is executing at each frame which I think is time consuming. In order to solve animation slowing, I have 2 ideas, but I still can't find how could I implement them:
1. Draw the Labels 1 time, but next time just reuse them, reuse the matrix or the textures, if there is any possibility (sorry I am a newbie, I may write some not adequate stuff);
2. When cleaning the buffer (glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)) clean just a part of the screen, not the whole Rendering scene, I would also be very happy to know if there is any possibility to clear not the whole screen but the drawn objects (for example in the Column chart, to clear just the columns, not the background and not the Labels, or lengend).
I would appreciate very much your help.

A:     glLoadIdentity();    // Added line

glEnableClientState(GL_VERTEX_ARRAY);

glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

NumberFormatter *lFormater = [[NumberFormatter alloc] init];
int i = 0;
for (NSNumber *lNumber in mColXLabelCoord) {
    NSNumber *lUnformated = [NSNumber numberWithInteger:[[NSString stringWithString:[mColYLabelsArray objectAtIndex:i]] integerValue]];

    NSString *lFormated = [NSString stringWithString:[lFormater stringFromNumber:lUnformated withMask:[[mGraphArray objectAtIndex:0] mGraphMask]]];

    Texture2D* lWord= [[Texture2D alloc] initWithString:lFormated dimensions:CGSizeMake(40, 15) alignment:UITextAlignmentLeft fontName:@"Helvetica" fontSize:13];

    glColor4f(RedFromRGB(0xFFFFFF), GreenFromRGB(0xFFFFFF), BlueFromRGB(0xFFFFFF), 1.0);
    [lWord drawInRect:CGRectMake([lNumber floatValue]+2, 470,40,15) rotation:-90];

    [lWord release];

    i++;
}
[lFormater release];

i = [mColYCoord count]-1;
for (NSNumber *lNumber in mColYCoord) {
    Texture2D* lWord= [[Texture2D alloc] initWithString:[NSString stringWithFormat:((GraphValue*)[mGraphValuesArray objectAtIndex:i]).mGraphValueXLabel,[lNumber floatValue]]
                                             dimensions:CGSizeMake(40, 15)
                                              alignment:UITextAlignmentCenter
                                               fontName:@"Helvetica" fontSize:12];

    if ([mColYCoord count] < kOptimalLabelNumber) {
        glColor4f(RedFromRGB(0xFFFFFF), GreenFromRGB(0xFFFFFF), BlueFromRGB(0xFFFFFF), 1.0);
        [lWord drawInRect:CGRectMake(10, [lNumber floatValue]+15, 40, 15) rotation:-90];
    }else {
        glColor4f(RedFromRGB(0xFFFFFF), GreenFromRGB(0xFFFFFF), BlueFromRGB(0xFFFFFF), 1.0);
        [lWord drawInRect:CGRectMake(2, [lNumber floatValue]+5, 40, 15) rotation:-30];

    }
    [lWord release];
    i--;
}

glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);

glDisableClientState(GL_VERTEX_ARRAY);

A: Things will be much simpler and go far more smoothly if you clear the full render buffer every time. Just pre-render the axes into a single texture and render the texture on each pass.


text:
Q: How to create mysql triggers using migrations in Rails? Is there a way to create mysql triggers using Activerecord migrations  ?  Has anybody worked on it share your experience . Thanks

A: There's no magic method allowing you to create a trigger without writing any SQL.
But you can execute raw sql inside any migration.
def self.up
    execute <<-SQL
        CREATE TRIGGER my_trigger ...
    SQL
end

Then you just need to appropriately write your trigger or update it depending of the migration.
Edit : I've just found rails_on_pg, which provides some helpers to migrations.
It doesn't work with any other database server than PgSQL. But it can be a good lead if you're up to writing some MySQL triggering helper.

A: there's a gem called hairtrigger that makes this a little easier and more portable (mysql/sqlite/postgres). it lets you create triggers in your migrations in a db-agnostic way, or even better you can declare them in your models and then run rake db:generate_trigger_migration to do it for you.

A: Thought it might help someone...
If we put custom SQL it may not work on development environment, if we are using SQLite3 and our migrate command would fail on sqlite:
rake db:migrate

I found it more useful to create trigger sql in a separate file under db/scripts and execute them in mysql cli. That way I could re-run them as per the need when the trigger changes.


text:
Q: About the solvability of non-analytical equations with new "helper" functions VtC reviewers: please drop a comment, what "context or other details" are missing.
I am thinking on to solve such equations like $e^x+cx+d=0$. These are generally not analytical, which essentially means that we can't do with them anything. There is no closed formula what could express the result.
However, it is not the first case as we faced similar problems. The ancient greeks had a quite similar problem about the irrationals. But we don't have a finite expression of, for example, $\sin22^\circ$, too.
The solution was that new functions were invented, their details, identities were discovered. For example, we still don't have a closed expression for $\sin 22^\circ$, but trigonometry is high school math today, and most practical trigonometric problems can be easily solved.
For example, what if we define a function
$\kappa(c)$ on the way, that $\kappa(c) := x|e^x+cx=0$ ?
I suspect, this $\kappa(c)$ would have identities, it would have Taylor-series, and using these we could get the solution for not only the equations like $e^x+cx=0$, but for a far more wider class of equations?
Do such functions exist? More specifically, what is the case for the named problem ("roots" of $e^x+cx+d$)?

A: For the specific question...  Solution $x$ of $e^x+cx+d=0$ is
$$
x = -\frac{d}{c}-W\left(\frac{\exp(-d/c)}{c}\right)
$$
where $W$ is the Lambert W function.


text:
Q: Vertical space between caption and main text I am trying to adjust the vertical space between my captions and the main body of text below it. It is likely to be packages interfering with each other, but I am not sure which.
Herbert suggested including these commands into my preamble, and I have removed the caption package completely as it seems to be superseded by the floatrow package included with chemstyle.
 \captionsetup{
      justification=centering,
      singlelinecheck=false,
      font=small,labelfont=bf,labelsep=space}
    \floatsetup{captionskip=6pt}
    \renewcommand\FBbskip{20pt}

But it seems as though \FBbskip is only having an effect on the first image float. I have updatd the MWE below so that this is clear, using \FBbskip at 20pt so you can clearly see the difference in vertical space between the two schemes.
Also. I am still unclear what these settings do:
\captionsetup{skip=5cm}
\addtolength\belowcaptionskip{20.0cm}
\addtolength\abovecaptionskip{20.0cm}

Commenting them out doesn't seem to have an effect, and setting them to extreme values doesn't seem to do anything either? Should I just remove them?
MWE using Herbert's solution, hopefully you can see the difference in vertical space surrounding the two schemes?
 \documentclass[11 pt]{report}

\usepackage[T1]{fontenc}
\usepackage{bera}
\usepackage[scaled]{berasans}
\usepackage[scaled]{beramono}
\usepackage{textcomp}

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage[left=1in, right=1in, top=.75in, bottom=.5in, includeheadfoot,   headheight=13.6pt]{geometry}
\usepackage{setspace}

\usepackage{achemso}

\usepackage{graphicx}
\usepackage{times,mathptmx}
\usepackage[version=3]{mhchem}

\usepackage[runs=2]{auto-pst-pdf}
\usepackage{chemstyle}
\usepackage{chemnum}
\usepackage{chngcntr}

\usepackage{titlesec}
\usepackage{sectsty}
\usepackage{balance}
\usepackage{lastpage}
\usepackage[toc, page, header]{appendix}
\usepackage{fancyhdr}
\usepackage[plain]{fancyref}

 \captionsetup{
  justification=centering,
  singlelinecheck=false,
  font=small,labelfont=bf,labelsep=space}
\floatsetup{captionskip=6pt}
\renewcommand\FBbskip{20pt}

\linespread{1.8} %1.5 line spacing

\parindent=0pt
\parskip=8pt

\renewcommand{\captionfont}{\sffamily}{\small}
\renewcommand{\captionlabelfont}{\bf}
\renewcommand\thescheme{\arabic{scheme}}
\counterwithout{scheme}{chapter}
\renewcommand\thefigure{\arabic{figure}}
\counterwithout{figure}{chapter}

\begin{document}
\captionsetup{skip=5cm}
\addtolength\belowcaptionskip{20.0cm}
\addtolength\abovecaptionskip{20.0cm}
\onehalfspace

\chapter[Introduction]{Introduction}
\chaptermark{Introduction}
\label{ch:introduction} % label for referring to chapter in other parts of the thesis
\section[Importance]{Importance}\label{C1:Intro}

Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text     Text Text Text

\begin{scheme}[ht]
\centering
\includegraphics[scale=0.2]{cat}
\caption{}
\label{scheme}
\end{scheme}

Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text     Text Text Text Text Text
Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text     Text Text Text

\begin{scheme}[ht]
\centering
\includegraphics[scale=0.2]{dog}
\caption{}
\label{scheme}
\end{scheme}

Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text     Text Text Text Text Text

 \end{document}

A: Package chemscheme loads itself package floatrow which controls the space above/below the caption with own settings:
\floatsetup{captionskip=10pt}%% space between figure and caption
\renewcommand\FBaskip{20pt}% space before float
\renewcommand\FBbskip{20pt}% space after float

You are looking for the latter.
However, in your example the font setting is a bit weird. You load several font packages which overwrites each preceding one. Here an example with a correct font setting for bera:
\documentclass[11pt]{report}
\usepackage[T1]{fontenc}
\usepackage{bera}
\usepackage[scaled]{berasans}
\usepackage[scaled]{beramono}
\usepackage{textcomp}

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage[left=1in, right=1in, top=1in, bottom=1in, includeheadfoot,    headheight=13.6pt]{geometry}
\usepackage{setspace}

\usepackage{graphicx}

\usepackage{chemstyle}
\usepackage{chemnum}
\usepackage{chngcntr}

\captionsetup{
  justification=centering,
  singlelinecheck=false,
  font=small,labelfont=bf,labelsep=space}
\floatsetup{captionskip=1cm}
\renewcommand\FBbskip{20pt}

\parindent=0pt
\parskip=8pt

\renewcommand\thescheme{\arabic{scheme}}
\counterwithout{scheme}{chapter}
\renewcommand\thefigure{\arabic{figure}}
\counterwithout{figure}{chapter}

\begin{document}
\captionsetup{skip=1cm}
\addtolength\belowcaptionskip{2cm}
\addtolength\abovecaptionskip{2cm}

\onehalfspace
\chapter[Introduction]{Introduction}
\chaptermark{Introduction}
\label{ch:introduction} % label for referring to chapter in other parts of the thesis
\section[Importance]{Importance}\label{C1:Intro}

Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text     Text Text Text

\begin{scheme}
\centering
\includegraphics[scale=0.2]{cat}
\caption{foo bar baz}
\label{scheme}
\end{scheme}

How I adjust the space between this text and the caption above??Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text  Text Text Text Text

\end{document}


text:
Q: @Pattern annotation used as a part of bean validation in spring mvc, is repeatedly throwing the same error I used @pattern annotation to validate the input for studentName. If I submit the invalid input once, its showing the error message as expected. But if I reload the page and submit the valid input, its showing the same error message again. Is there a way to clear the previous binding errors
I have tried restarting the server
Student bean class :
import javax.validation.constraints.Pattern;
public class Student {
@Pattern(regexp = "^[0-9]*")
private String studentName;

public String getStudentName() {
    return studentName;
}

public void setStudentName(String studentName) {
    this.studentName = studentName;
}

}
Controller class :
@RequestMapping(value = "/submitAdmissionForm.html", method = RequestMethod.POST)
    public ModelAndView submitAdmissionForm(@Valid @ModelAttribute("student1") Student student, BindingResult result) {
        if (result.hasErrors()) {
            ModelAndView model = new ModelAndView("AdmissionForm");
            return model;
        }
        ModelAndView model2 = new ModelAndView("AdmissionSuccess");
        return model2;
    }

studentMessages.properties :
Pattern.student1.studentName = custom error message.
spring-dispatcher-servlet :
<bean id = "messageSource" class = "org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name = "basename" value = "/WEB-INF/studentMessages"/>
    </bean>


text:
Q: Illegal invocation error in XPages mobile app I have an XPages mobile application using the single page application design pattern. When I open the application using my iPhone 6 none of the links work.
When I open the application on my desktop chrome browser by first setting the user agent then opening the URL I see an "illegal invocation" JavaScript error whenever I click on a link.
If I open the application on my desktop chrome browser by first opening the URL then setting the user agent I no longer receive the "illegal invocation" error and the links work but the theme is black (background) and white (text).
My xsp properties are:
xsp.ajax.renderwholetree=false
xsp.error.page.default=true
xsp.library.depends=com.ibm.xsp.extlib.library
xsp.persistence.mode=fileex
xsp.resources.aggregate=false
xsp.user.timezone=true
xsp.html.doctype=html
xsp.theme.mobile.pagePrefix=m_
xsp.client.resources.uncompressed=true
xsp.application.forcefullrefresh=true

The illegal invocation error is being reported at: (anonymous function)    @   dojo.js:14753 which is this line: var firstChangeTouch = event.changedTouches[0];
More info:
I am running Domino 9.0.1 with version 901v00_14.201 of the extension library.
I enabled the Web Inspector in mobile Safari and connected my iPhone to a mac. When I do this I get two errors when I touch a link:
First Error: Depreciated attempt to access property 'changedTouches' on a non-TouchEvent object. dojo.js on line 14753 which is: var firstChangeTouch = event.changedTouches[0];
Second Error: TypeError: Attempted to assign to readonly property. dojo.js on line 14756 which is: event[i] = firstChangeTouch[i];

A: This issue was fixed in Domino 9.0.1 Fix Pack 2 Interim Fix 1. I only had FP2 on my Development server.
The cause of the issue was iOS 8 made some changes to touch events causing Dojo to break. See http://www-01.ibm.com/support/docview.wss?uid=swg21686751


text:
Q: Android: starting activity landscape wrong orientation I'm facing a strange problem: i have an activity wich launches another activity when orientation changes to landscape. the problem is that the new activity comes in the reverse position when i turn my device clockwise.
Some screenshots to understand...
FirstActivity (runs in portrait mode):

When i turn the device counterclockwise my second activity is launched and it all works great:

If i turn my device in portrait orientation the first activity gets called and it's all ok: i can go on turning it again and again and it always works.
The problem is that when i turn my device clockwise i get this:

Here' the code:
first activity (glanceActivity):
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_glance_landscape);

    setOrientationChangeListener();
}

private void setOrientationChangeListener() {

    mOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL){

        long changeStart = 0;

        @Override
        public void onOrientationChanged(int arg0) {

            if (arg0 > 80 && arg0 < 280) {
                if(changeStart == 0) {
                    changeStart = System.currentTimeMillis();
                }
                else if ((System.currentTimeMillis() - changeStart) > 1500) {
                    launchLandscapeActivity();
                    changeStart = 0;
                }
            }
            else {
                changeStart = 0;
            }
        }
    };

    if (mOrientationEventListener.canDetectOrientation()){
        mOrientationEventListener.enable();
    }
    else{
        finish();
    }
}

private void launchLandscapeActivity() {
    mOrientationEventListener.disable();
    Intent intent = new Intent(GlanceActivity.this, GlanceLandscapeActivity.class);
    startActivity(intent);
    finish();
}

And here's my second activity (GlanceLandscapeActivity):
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_glance_landscape);

    setOrientationChangeListener();
}

private void setOrientationChangeListener() {

    mOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL){

       long changeStart = 0;

       @Override
       public void onOrientationChanged(int arg0) {

        if ((arg0 <= 360 && arg0 > 280) || (arg0 >= 0 && arg0 < 80)) {
            if(changeStart == 0) {
                changeStart = System.currentTimeMillis();
            }
            else if ((System.currentTimeMillis() - changeStart) > 1500) {
                launchPortraitActivity();
                changeStart = 0;
            }
        }
        else {
            changeStart = 0;
        }
    }
};

if (mOrientationEventListener.canDetectOrientation()){
    mOrientationEventListener.enable();
}
else{
    finish();
}
}

private void launchPortraitActivity() {
    mOrientationEventListener.disable();
    Intent intent = new Intent(GlanceLandscapeActivity.this, GlanceActivity.class);
    startActivity(intent);
    finish();
}

EDIT: I forgot to add the declaration in the manifest.xml :
<activity
      android:name=".GlanceActivity"
      android:configChanges="orientation|keyboardHidden|screenSize"
      android:screenOrientation="portrait"
      android:label="@string/title_activity_glance"
      android:theme="@style/sectionsTheme" >
</activity>
<activity
      android:name=".GlanceLandscapeActivity"
      android:label="@string/title_activity_glance_landscape"
      android:configChanges="orientation|keyboardHidden|screenSize"
      android:screenOrientation="landscape"
      android:theme="@android:style/Theme.Holo.Light.NoActionBar" >
</activity>