text:
Q: How to use QScopedPointer I have an example that use
QApplication app(argc,argv);
QStandardItemModel* model = new QStandardItemModel(r,c,&app);

But in my program I have
QScopedPointer<QApplication> app(createApplication(argc, argv));
QStandardItemModel* model = new QStandardItemModel(r,c,&app); //ERROR: no matching function

How to use this QScopedPointer without error?

A: Use app.data().  Though it is very unusual to create the QApplication on the heap...

A: QScopedPointer<QApplication> app(createApplication(argc, argv));
QStandardItemModel* model = new QStandardItemModel(r,c,app.data());

A: hope to be useful
#include <QScopedPointer>
class  target
{
 public:
 int var;
};
class logic
{
 public:
 QScopedPointer<target> variable;
 target* variable2;
};
int main()
{
 logic LogicClass;
 LogicClass.variable.reset(new target);
 LogicClass.variable->var=10;
 cout<<LogicClass.variable->var<<endl;

LogicClass.variable2 = new target;
LogicClass.variable2->var = 20;
cout<<LogicClass.variable2->var<<endl;
delete LogicClass.variable2;
return 0;
}


text:
Q: Symfony 3 form assigns error to the FormType instead of the actual field I created a form in Symfony with this setup:
#\src\AppBundle\Entity\Order.php

class Order
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string $orderID
     *
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */
    protected $orderID;

    /**
     * @var string $email
     *
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     * @Assert\Email()
     */
    protected $email;

    ...

In my form type:
# \src\AppBundle\Form\OrderType.php

class OrderType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('order_id', TextType::class, [
                    'label' => 'index.order_id',
                    'attr' => array(
                        'placeholder' => 'index.order_id.placeholder'
                    )
                ])
                ->add('email', EmailType::class, [
                    'label' => 'index.email',
                    'attr' => array(
                        'placeholder' => 'index.email.placeholder'
                    )
                ]);
        }

        ...

So if I submit the form with empty fields, Symfony detects both errors but the order ID error is assigned to the Class instead of the actual field.
Any ideas?

Update
I renamed protected $orderID; to protected $orderid; and the problem is fixed! So why this happened? Is there any reserved names when it comes to the use of ID in the property name?

A: I think you should have this because that's what you specified in buildForm:
/**
  * @var string $order_id
  *
  * @ORM\Column(type="string")
  * @Assert\NotBlank()
  */
protected $order_id;

Can you try it?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tensorflow: get all tensors beginning with "Add" Right now I am doing the following to access tensors in my graph
graph = tf.get_default_graph()
add_0 = graph.get_tensor_by_name("Add:0")
add_1 = graph.get_tensor_by_name("Add_1:0")
add_2 = graph.get_tensor_by_name("Add_2:0")

When the graph is short, this approach is ok. But for longer graphs it gets really boring.
Is there a way to collect all tensors beginning with Add in a clean way? Something like:
add = []
for Add in graph.get_tensors_by_name():
    add.append(Add)

(I know this pseudocode is really wrong)
Such that I get add = [add_0, add_1, add_2, ... ]
Later I want to use it to do that: sess.run(add, feed_dict={input: data})

A: You can get all tensors with sess.graph.get_operations() and then use startswith() to pick the ones you need. Tested code:
import tensorflow as tf

a = tf.constant( [ 1.0 ] )
b = tf.constant( [ 2.0 ] )
c = tf.add( a, b )
d = tf.add( c, b )

with tf.Session() as sess:

    tensors = sum( [ operation.outputs
                             for operation in sess.graph.get_operations()
                             if operation.name.startswith( "Add") ],
                   [] )
    print( tensors )
    print( sess.run( tensors ) )

Outputs:

tf.Tensor 'Add:0' shape=(1,) dtype=float32, tf.Tensor 'Add_1:0' shape=(1,) dtype=float32
  [array([3.], dtype=float32), array([5.], dtype=float32)]


text:
Q: ZFS for offline backups I'm thinking of using ZFS to backups files to single drives that are going to be kept mostly offline.  Does anyone know if the FreeBSD ZFS implementation still uses memory if a dedupped pool is exported?

A: Technically yes, practically no.
A minor amount of RAM will be used to keep track of the status of the pool, it is not removed from the kernel's data structure unless the drives are all removed. All ZFS file systems are unmounted however, so none of the file system caching (ARC/etc) is used.


text:
Q: Failed to run EfficientNet model to trained 4 class I'm going to train my model with 4 classes with images.
Here's my pre-trained code look like
conv_base = EfficientNetB0(weights="imagenet", include_top=False,
                                               input_shape=(224, 224, 3))

I trained my mode with code like this:
eff_history = model.fit(
                        train_generator,
                        validation_data=validation_generator,
                        steps_per_epoch=486 // 20,
                        epochs=10)

But there's problem occured like below:

Any help guys?

A: You have three labels for each sample, but the last layer of your model outputs 2 classes thus the number of the logits you get is 2 rather than 3. You need to change your model to have a 3 dimensional output.


text:
Q: make customer login page 3 column layout in magento I am new in magento. I want to make customer login page 3 column layout, which is 1 column by default. I got code from somewhere to make it 3 column layout.
<customer_account_login>
  <reference name="root">
     <action method="setTemplate">
           <template>page/3columns.phtml</template>
     </action>
  </reference>
</customer_account_login>

But I don't know where I have to write this code to make customer login page 3 column layout.

A: <customer_account_login translate="label">
    Customer Account Login Form

    <reference name="left">
        <block type="catalog/product_compare_sidebar" name="catalog.compare.sidebar" template="catalog/product/compare/sidebar.phtml"/>
    </reference>
    <reference name="right">
        <block type="catalog/product_compare_sidebar" name="catalog.compare.sidebar" template="catalog/product/compare/sidebar.phtml"/>
    </reference>
    <reference name="root">
        <action method="setTemplate"><template>page/3columns.phtml</template></action>
    </reference>
    <reference name="content">
        <block type="customer/form_login" name="customer_form_login" template="customer/form/login.phtml" />
    </reference>
</customer_account_login>

A: Go to app\design\frontend\rwd\default\layout\customer.xml Open customer.xml file
There you will have code for customer login page like this
<customer_account_login translate="label">
        Customer Account Login Form

        <remove name="right"/>
        <remove name="left"/>

        <reference name="root">
            <action method="setTemplate"><template>page/1column.phtml</template></action>
        </reference>
        <reference name="content">
            <block type="customer/form_login" name="customer_form_login" template="customer/form/login.phtml" />
        </reference>
</customer_account_login>

Here in this line <action method="setTemplate"><template>page/1column.phtml</template></action> change page/1column.phtml to page/3columns.phtml
But for that you should have 3columns.phtml file in  app\design\frontend\rwd\default\template\page\  here. If you don't have create 3columns.phtml there and put this code in it.
<!DOCTYPE html>

 <html lang="<?php echo $this->getLang(); ?>" id="top" class="no-js">

<?php echo $this->getChildHtml('head') ?>

<body<?php echo $this->getBodyClass()?' class="'.$this->getBodyClass().'"':'' ?>>
<?php echo $this->getChildHtml('after_body_start') ?>

    <?php echo $this->getChildHtml('global_notices') ?>

        <?php echo $this->getChildHtml('header') ?>

                <?php echo $this->getChildHtml('breadcrumbs') ?>

                    <?php // This left_first block will display above the main content on smaller viewports ?>
                    <?php if ($_leftContent = $this->getChildHtml('left_first')): ?>

<?php echo $_leftContent;   ?>

                    <?php endif; ?>

                        <?php echo $this->getChildHtml('global_messages') ?>
                        <?php echo $this->getChildHtml('content') ?>

<?php echo $this->getChildHtml('left') ?>

<?php echo $this->getChildHtml('right') ?>

        <?php echo $this->getChildHtml('footer_before') ?>
        <?php echo $this->getChildHtml('footer') ?>
        <?php echo $this->getChildHtml('global_cookie_notice') ?>
        <?php echo $this->getChildHtml('before_body_end') ?>

<?php echo $this->getAbsoluteFooter() ?>

And if you are using other theme then please go to your theme folder insted of rwd


text:
Q: Prove that : $\int_{a}^{b} (\varphi (t)-\lambda_{\varphi}\theta(t))\,dt =0$ Prove that :
$$\int_{a}^{b} (\varphi (t)-\lambda_{\varphi}\theta(t))\,dt =0$$
Where :
$$\theta , \varphi \in D(]a,b[)
:\text{functions test} $$
Such that :
$$\lambda_{\varphi}=\displaystyle\int_{a}^{b} \varphi (t)dt$$
And :
$$\displaystyle\int_{a}^{b} \theta (t)  dt=1$$

*

*also prove that $$\exists\psi\in D(]a,b[) , \varphi =\psi '+\lambda_{\varphi}\theta $$
My try :

$$\displaystyle\int_{a}^{b} (\varphi (t)-\lambda_{\varphi}\theta(t))dt =\displaystyle\int_{a}^{b} \varphi (t)-\displaystyle\int_{a}^{b}\displaystyle\int_{a}^{b} \varphi (t)\theta (t) dtdt$$
From here how I can complete ?
Can you assist

Thanks!


text:
Q: css изменение высоты картинки вместе с родительским контейнером Задача: размещаю некий блок с высотой к примеру 90vh, внутри него помещаю изображение, которое по высоте будет меньше родителя. Когда браузер по высоте уменьшается до порога <= высоты картинки - картинка также должна адаптивно пропорционально уменьшаться вместе с родительским блоком. Я уменьшаю размер браузера по высоте больше нежели высота изображения - изображение все равно распирает блок (появляется вертикальная прокрутка в браузере). Возможно ли это сделать средствами CSS?

.peng {
  width: 376px;
  height: 90vh;
  position: absolute;
  right: 0;
}

.peng img {
  width: 100%;
  height: auto;
}

A: нашел решение
.peng
{
width: 376px;
height: 90vh;
position: absolute;
right: 0;
border: green 1px solid;
}

.peng img
{
width: auto;
max-width: 376px;
height: auto;
max-height: 100%;
display: block;
}

A: В CSS можно воспользоваться методом object-fit.
Имеет 94% поддержку в браузерах и не работает в IE

.peng {
  width: 376px;
  height: 90vh;
}

.peng img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background-color: red;
}

.peng.cover img {
  object-fit: cover;
}


text:
Q: Symfony - Event not being dispatched This is the first time ever I am working with creating custom event dispatcher and subscriber so I am trying to wrap my head around it and I cant seem to find out why my custom event is not being dispatched.
I am following the documentation and in my case I need to dispatch an event as soon as someone registers on the site.
so inside my registerAction() I am trying to dispatch an event like this
$dispatcher = new EventDispatcher();
$event = new RegistrationEvent($user);
$dispatcher->dispatch(RegistrationEvent::NAME, $event);

This is my RegistrationEvent class
namespace AppBundle\Event;
use AppBundle\Entity\User;
use Symfony\Component\EventDispatcher\Event;

class RegistrationEvent extends Event
{
    const NAME = 'registration.complete';

    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function getUser(){
        return $this->user;
    }

}

This is my RegistrationSubscriber class
namespace AppBundle\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RegistrationSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::RESPONSE => array(
                array('onKernelResponsePre', 10),
                array('onKernelResponsePost', -10),
            ),
            RegistrationEvent::NAME => 'onRegistration'
        );

    }
    public function onKernelResponsePre(FilterResponseEvent $event)
    {
        // ...
    }

    public function onKernelResponsePost(FilterResponseEvent $event)
    {
        // ...
    }
    public function onRegistration(RegistrationEvent $event){

        var_dump($event);
        die;

    }

}

After doing this, I was hoping that the registration process would stop at the function onRegistration but that did not happen, I then looked at the Events tab of the profiler and I do not see my Event listed their either.
What am I missing here? A push in right direction will really be appreciated.
Update:
I thought i need to register a service for the custom event so I added the following code inside services.yml
app.successfull_registration_subscriber:
    class: AppBundle\Event\RegistrationSubscriber
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        - { name: kernel.event_subscriber}

Inside the Event tab of profiler I do see my custom event being listed but it still does not dispatch.

A: By creating your own EventDispatcher instance you dispatch an event that can never be listened to by other listeners (they are not attached to this dispatcher instance). You need to use the event_dispatcher service to notify all listeners you have tagged with the kernel.event_listener and kernel.event_subscriber tags:
// ...

class RegistrationController extends Controller
{
    public function registerAction()
    {
        // ...

        $this->get('event_dispatcher')->dispatch(RegistrationEvent::NAME, new RegistrationEvent($user););
    }
}

A: Duplicate of dispatcher doesn't dispatch my event symfony
With auto-wiring, it is now better to inject the EventDispatcherInterface
<?php
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
//...

class DefaultController extends Controller
{
    public function display(Request $request, EventDispatcherInterface $dispatcher)
    {
        //Define your event
        $event = new YourEvent($request);
        $dispatcher->dispatch(YourEvent::EVENT_TO_DISPATCH, $event);
    }
}


text:
Q: How to get the location and index of an Icon in a ".lnk" shortcut with SHGetFileInfo in C++ I am using C++ (VS 2012) on Win7x64 and am trying to get the location and index of an icon using SHGetFileInfo with SHGFI_ICONLOCATION like this:
SHFILEINFO info;
memset(&info, 0, sizeof(info));
DWORD_PTR result = SHGetFileInfo(_T("C:\\Users\\Admin\\Desktop\\test.lnk"), 0, &info, sizeof(SHFILEINFO),  SHGFI_ICONLOCATION);

I get a 1 as result and after inspecting info.szDisplayName I see this:
0x0022CDE0  00 00 3a 00 5c 00 50 00 72 00 6f 00  ..:.\.P.r.o.
0x0022CDEC  67 00 72 00 61 00 6d 00 20 00 46 00  g.r.a.m. .F.
0x0022CDF8  69 00 6c 00 65 00 73 00 20 00 28 00  i.l.e.s. .(.
0x0022CE04  78 00 38 00 36 00 29 00 5c 00 54 00  x.8.6.).\.T.
0x0022CE10  65 00 73 00 74 00 5c 00 54 00 65 00  e.s.t.\.T.e.
0x0022CE1C  73 00 74 00 2e 00 65 00 78 00 65 00  s.t...e.x.e.
0x0022CE28  00 00 00 00 00 00 00 00 00 00 00 00  ............
0x0022CE34  00 00 00 00 00 00 00 00 00 00 00 00  ............

What I find strange is that although the string info.szDisplayName appears empty due to the 00 00 at the start, the call to SHGetFileInfo seems to have filled in the entire path correctly and then replaced the drive letter in it with a 00 00 making it an "empty" string.
What I also have noticed is that when I choose a different icon from a different executable it appears to work alright. But when I then create a shortcut to that different executable and use the icon from it that worked before it again returns this "empty" string.
It seems to work sort of crisscross with the locations of the executable and the icon, but with the icon being from the same executable it always seems to exhibit this strange behaviour. The only exception to this is the index of the icon.
It does not matter if an executable has only one or many icons, but when I use an icon with an index greater than 0, it does fill in the location correctly and the index as well, even though the location of the executable and the icon in the shortcut is the same.
Why is SHGetFileInfo filling in icon.szDisplayName as an "empty" string when in the shortcut the location of the icon is the same as the executable and the index is 0?


text:
Q: How to call c# function with out parameter in c++/CLI I very new to C++.
I have a C# dll which I want to call it in c++ project.
The function in C# I would declare it like this:
   public int ShowStringReturn(out string str)
    {
        str = "Message from c#";
        return 0;
    }

Then, I call it in my C++ project :
__declspec(dllexport)
    int ShowStringCSharpReturn (std::string &strOut)
    {
        try
        {
            String^ str;
            IngWrapper::Ingressus_Instance->xIMUobject->ShowStringReturn(str);

            using System::Runtime::InteropServices::Marshal;
            const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(str)).ToPointer( );
            strOut = chars;

            return 0;
        }
        catch (Exception^ ex)
        {
            MessageBox::Show(ex->Message,"Error",MessageBoxButtons::OK,MessageBoxIcon::Error);
            return -1;
        }
    }

I can compile it, but when I call the activex dll in my windows form application, i get an error "External component has thrown an exception"
How should I declare and call my function?


text:
Q: unable to disable FlatButton I have Buttons that use the Widget.AppCompat.Button.Borderless style with a custom color selector that changes the textColor according to the enabled state.
It generally works, but when the Button is initially disabled (in XML or in code), it won't. The Button will look clickable and is clickable. As soon as i add a small delay of just 100 Milliseconds, it works.
clickable on the other hand, works without any delays.
I've tried calling invalidate() and requestLayout() on the Button without success.
Anyone experienced anything like this?

A: Fooled myself! The presenter checks for an active connection and enabled the Button.
That also explains the 100ms workaround.
Gotta hate the feeling of wasting hours to your own stupidity.


text:
Q: Offline Gretty Plugin I have a project that runs on gretty and needs to be built without access to the internet.  I have included all the gretty jars locally and am getting the following error:
Caused by: java.lang.NoClassDefFoundError: org/akhikhl/gretty/Externalized
  at org.akhikhl.gretty.GrettyPlugin$_apply_closure62.doCall(GrettyPlugin.groovy:772)
  at org.gradle.api.internal.ClosureBackedAction.execute(ClosureBackedAction.java:70)
  at org.gradle.util.ConfigureUtil.configureTarget(ConfigureUtil.java:160)
  at org.gradle.util.ConfigureUtil.configure(ConfigureUtil.java:106)
  at org.gradle.util.ConfigureUtil$1.execute(ConfigureUtil.java:123)
  at org.gradle.api.internal.plugins.ExtensionsStorage$ExtensionHolder.configure(ExtensionsStorage.java:145)
  at org.gradle.api.internal.plugins.ExtensionsStorage.configureExtension(ExtensionsStorage.java:69)
  at org.gradle.api.internal.plugins.DefaultConvention$ExtensionsDynamicObject.invokeMethod(DefaultConvention.java:215)

What other files are required in order to be able to run gretty offline?  The only way I can get the project running is by letting gradle access the files thru jcenter.

A: Use gradle appRun --offline
Reference Gretty issues


text:
Q: Invalid assignment left-hand side. (line 1, file "Code") the following is my code
my task is to make a post to wordpress from google script for that
while i am try the following code i got an error of Invalid assignment left-hand side. (line 1, file "Code")
please any one can help me in this
 function programmatically_create_post(){

    // Initialize the page ID to -1. This indicates no action has been taken.
    $post_id = (-1);

    // Setup the author, slug, and title for the post
    $author_id = 1;
    $slug = 'example-post';
    $title = 'My Example Post';

    // If the page doesn't already exist, then create it
    if( null == get_page_by_title( $title ) ) {

        // Set the post ID so that we know the post was created successfully
        $post_id = wp_insert_post(
            array(
                'comment_status'    =   'closed',
                'ping_status'       =   'closed',
                'post_author'       =   $author_id,
                'post_name'         =   $slug,
                'post_title'        =   $title,
                'post_status'       =   'publish',
                'post_type'         =   'post'
            )
        );

    // Otherwise, we'll stop
    } else {

            // Arbitrarily use -2 to indicate that the page with the title already exists
            $post_id == (-2);

    } // end if

} // end programmatically_create_post
add_filter( "after_setup_theme", + "programmatically_create_post" );
$post_id = programmatically_create_post()
if( -1 == $post_id || -2 == $post_id ) {
   // The post wasn't created or the page already exists
} // end if


text:
Q: RabbitMQ stuck in pending state when deploy on Kubernetes I currently trying to deploy simple RabbitMQ cluster for my project.
So far, I found this two example that suit my needed.
https://www.linkedin.com/pulse/deploying-rabbitmq-cluster-kubernetes-part-1-darshana-dinushal/
https://github.com/marcel-dempers/docker-development-youtube-series/blob/master/messaging/rabbitmq/kubernetes/rabbit-statefulset.yaml
And since official website, articles and tutorial videos about RabbitMQ on Kubernetes are pointing to large production deployment. I only get this 2 example to follow.
And when I try it RabbitMQ pod is stuck on pending state while other pods are running fine. I currently use YAML files from the first example.
kubectl describe pod rabbitmq-0
Name:           rabbitmq-0
Namespace:      default
Priority:       0
Node:           <none>
Labels:         app=rabbitmq
                controller-revision-hash=rabbitmq-84b847b5d5
                statefulset.kubernetes.io/pod-name=rabbitmq-0
Annotations:    <none>
Status:         Pending
IP:
IPs:            <none>
Controlled By:  StatefulSet/rabbitmq
Init Containers:
  config:
    Image:      busybox
    Port:       <none>
    Host Port:  <none>
    Command:
      /bin/sh
      -c
      cp /tmp/config/rabbitmq.conf /config/rabbitmq.conf && ls -l /config/ && cp /tmp/config/enabled_plugins /etc/rabbitmq/enabled_plugins
    Environment:  <none>
    Mounts:
      /config/ from config-file (rw)
      /etc/rabbitmq/ from plugins-file (rw)
      /tmp/config/ from config (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-ffj67 (ro)
Containers:
  rabbitmq:
    Image:       rabbitmq:3.8-management
    Ports:       4369/TCP, 5672/TCP
    Host Ports:  0/TCP, 0/TCP
    Environment:
      RABBIT_POD_NAME:         rabbitmq-0 (v1:metadata.name)
      RABBIT_POD_NAMESPACE:    default (v1:metadata.namespace)
      RABBITMQ_NODENAME:       rabbit@$(RABBIT_POD_NAME).rabbitmq.$(RABBIT_POD_NAMESPACE).svc.cluster.local
      RABBITMQ_USE_LONGNAME:   true
      RABBITMQ_CONFIG_FILE:    /config/rabbitmq
      RABBITMQ_ERLANG_COOKIE:  <set to the key 'RABBITMQ_ERLANG_COOKIE' in secret 'rabbit-secret'>  Optional: false
      K8S_HOSTNAME_SUFFIX:     .rabbitmq.$(RABBIT_POD_NAMESPACE).svc.cluster.local
    Mounts:
      /config/ from config-file (rw)
      /etc/rabbitmq/ from plugins-file (rw)
      /var/lib/rabbitmq from data (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-ffj67 (ro)
Conditions:
  Type           Status
  PodScheduled   False
Volumes:
  data:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  data-rabbitmq-0
    ReadOnly:   false
  config-file:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
  plugins-file:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
  config:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      rabbitmq-config
    Optional:  false
  kube-api-access-ffj67:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type     Reason            Age                   From               Message
  ----     ------            ----                  ----               -------
  Warning  FailedScheduling  2m25s (x39 over 89m)  default-scheduler  0/1 nodes are available: 1 pod has unbound immediate PersistentVolumeClaims. preemption: 0/1 nodes are available: 1 Preemption is not helpful for scheduling.

A: Since I had tested deploying RabbitMQ via docker-compose and it worked before.
I discovered a tool called Kompose and I use it to convert my rabbitmq docker-compose file to k8s yaml files.
And it works!.
Yaml files that generate from Kompose.
service file
apiVersion: v1
kind: Service
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.26.0 (40646f47)
  labels:
    io.kompose.service: rabbitmq3
  name: rabbitmq3
spec:
  type: LoadBalancer
  ports:
    - name: amqp
      port: 5672
      targetPort: 5672
    - name: discovery
      port: 15672
      targetPort: 15672
  selector:
    io.kompose.service: rabbitmq3

deployment file
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.26.0 (40646f47)
  labels:
    io.kompose.service: rabbitmq3
  name: rabbitmq3
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: rabbitmq3
  strategy: { }
  template:
    metadata:
      annotations:
        kompose.cmd: kompose convert
        kompose.version: 1.26.0 (40646f47)
      labels:
        io.kompose.service: rabbitmq3
    spec:
      containers:
        - env:
            - name: RABBITMQ_DEFAULT_PASS
              value: rabbitpassword
            - name: RABBITMQ_DEFAULT_USER
              value: rabbituser
          image: rabbitmq:management-alpine
          name: rabbitmq
          ports:
            - containerPort: 15672
              name: discovery
            - containerPort: 5672
              name: amqp
          resources: { }
      restartPolicy: Always


text:
Q: longtable: hline doesn't display on the first page table head and \hline do not display on the first page, as shown the red line below.

Here is the source code.
\documentclass[twoside,12pt]{article}
\usepackage{longtable}

\begin{document}

\begin{longtable}{|c|c|r|r|r|r|r|r|r|l|}
    \caption{The throughput improvements achieved by network coding in Toulouse}
    \label{table:throughput improvement 2}
    \endfirsthead
    \hline
    line1   &   line2   &   $t_1$       &   $t_{12}$    &   $t_2$       &   $r$(\%)&    $D$(GB)&    $D_{nc}(GB)$&$G_t$(\%)&Station\\    % table head
    \hline
    \endhead % all the lines above this will be repeated on every page
    \hline
    \endfoot %  to appear at the bottom of each page
    10  &   2       &   0:22:00 &   9:46:00 &   2:00:00 &   80.49   &   159.18  &   302.25  &   89.88   &   Cours Dillon    \\
    10  &   109 &   1:19:00 &   8:55:00 &   1:40:00 &   74.93   &   188.48  &   319.09  &   69.3    &   Malepère    \\
    % more data is here
\end{longtable}

\end{document}

If I remove \endfirsthead, it raised the following error.

A: You should add content of the head also to the firsthead:
\documentclass[twoside,12pt]{article}
\usepackage{longtable}

\begin{document}
    \begin{longtable}{|c|c|r|r|r|r|r|r|r|l|}
    \caption{The throughput improvements achieved by network coding in Toulouse}
    \label{table:throughput improvement 2}\\ %<-- added
\hline%<-- added
line1 & line2 & $t_1$ & $t_{12}$ & $t_2$  & $r$(\%) & $D$(GB) & $D_{nc}(GB)$ & $G_t$(\%) & Station\\  %<-- added
\hline%<-- added
    \endfirsthead
    \hline
    line1   &   line2   &   $t_1$       &   $t_{12}$    &   $t_2$       &   $r$(\%)&    $D$(GB)&    $D_{nc}(GB)$&$G_t$(\%)&Station\\    % table head
    \hline
    \endhead % all the lines above this will be repeated on every page
    \hline
    \endfoot %  to appear at the bottom of each page
    10  &   2       &   0:22:00 &   9:46:00 &   2:00:00 &   80.49   &   159.18  &   302.25  &   89.88   &   Cours Dillon    \\
    10  &   109 &   1:19:00 &   8:55:00 &   1:40:00 &   74.93   &   188.48  &   319.09  &   69.3    &   Malepère    \\
% more data is here
    \end{longtable}
\end{document}

Note: The code, as it is, will not repeat caption on the new page.

A: Put \\\hline before \endfirsthead:
\documentclass[twoside,12pt]{article}
\usepackage{longtable}

\begin{document}

\begin{longtable}{|c|c|r|r|r|r|r|r|r|l|}
    \caption{The throughput improvements achieved by network coding in Toulouse}
    \label{table:throughput improvement 2}
    \\\hline
    \endfirsthead
    \hline
    line1   &   line2   &   $t_1$       &   $t_{12}$    &   $t_2$       &   $r$(\%)&    $D$(GB)&    $D_{nc}(GB)$&$G_t$(\%)&Station\\    % table head
    \hline
    \endhead % all the lines above this will be repeated on every page
    \hline
    \endfoot %  to appear at the bottom of each page
    10  &   2       &   0:22:00 &   9:46:00 &   2:00:00 &   80.49   &   159.18  &   302.25  &   89.88   &   Cours Dillon    \\
    10  &   109 &   1:19:00 &   8:55:00 &   1:40:00 &   74.93   &   188.48  &   319.09  &   69.3    &   Malepère    \\
    % more data is here
\end{longtable}

\end{document}


text:
Q: Expand box in all directions I have the following structure:

My goal is when the user mouseover the boxes, they should expand and go over the others without breaking the UI. So basically the box should expand 20px in every directive, while every other element stays on the same place. Note that I dont know the exact size of the boxes, because they're responsible.
I'm positioning the boxes like this:
#holder {
    width: 250px;
    background-color: #FFCCCC;
    overflow: hidden;
    padding: 15px;
}

.box {
    width: 45%;
    height: 50px;
    border: 1px grey solid;
    float: left;
    margin-bottom: 15px;
}

.box:nth-child(odd) {
    float: right;
}

With the HTML below:

And I'm handling the events using jQuery.
$(document).ready(function(){
$(".box").mouseenter(function(){
      var _this = $(this);
      var newWidth = parseInt(_this.css("width")) + 40,
          newHeight = parseInt(_this.css("height")) + 40;

    _this.
        css("z-index", 99).
        animate({
            width: newWidth + "px",
            height: newHeight + "px",
            marginTop: "-20px",
            marginLeft: "-20px"
        }, 1000);
});

 $(".box").mouseleave(function(){
      var _this = $(this);
      var newWidth = parseInt(_this.css("width")) - 40,
          newHeight = parseInt(_this.css("height")) - 40;

    _this.
    css("z-index", 1).
    animate({
        width: newWidth + "px",
        height: newHeight + "px",
        marginTop: "0px",
        marginLeft: "0px"
    }, 1000);
});
});

And here is the fiddle: http://jsfiddle.net/3T89h/

A: Easiest way I can think of is absolute positioning (although there is probably is a much neater way).
You'd need to apply
position:absolute;

to each box, give it a fixed height/width (percentages wouldn't really work) and position it manually, for example
http://jsfiddle.net/3T89h/1/
Edit:
If your boxes need to be responsive, have undetermined heights & widths, then it's still possible to do this with a similar method.
You can use your original boxes as a container, with
position:relative;

and then within them keep your actual content which'll be absolutely positioned, here's an example:
http://jsfiddle.net/3T89h/2/
So essentially you now have boxes acting as a responsive wrapper, which contain an inner box with the desired effect, that matches the wrapper's dimensions. The design can then be changed dramatically, but the javascript effect you wanted will not be altered, eg: http://jsfiddle.net/3T89h/3/


text:
Q: SOAP service crash with empty field in request Our SOAP web service provider insist on removing empty field tags from the request because it breaks the service. Is that right practice?
See below example of request. StockID is empty tag. Should it break the SOAP service?
I would like to know best practice around empty tags in request

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
  <m:GetStockPrice>
    <m:StockName>IBM</m:StockName>
    <m:StockID/>
  </m:GetStockPrice>
</soap:Body>

</soap:Envelope>

A: This Depends on how the rest of the system is programmed. There are 3 ways of sending StockID:

*

*Empty tag

*Tag removed

*Tag With nil="true"

What is probably happening for the first item above is that the program is deserializing the tag as an empty string, and then crashing since there is no Stock id = "".
In the 2 last items above it would deserialize as NULL and then not try and find a Stock id = NULL.


text:
Q: Access the containing object in a constructor function I want to access the parent object when calling a function contained inside that object as a constructor. See this example:
var users = {
    // The count of users
    count: 0,

    // Naturally _this is undefined
    _this: this,

    // Constructor function
    CreateUser: function (name, email) {
        this.name = name;
        this.email = email;

        // Is this the only way to access the containing object?
        users.count++;
    },

    getCount: function () {
        return this.count;
    },
};

If I try to invoke the CreateUser function as a constructor, then this will be a reference to the blank object that the new operator created. See this:
var user = new users.CreateUser('Rick', 'rick@example.com')

How can I access the users containing object in this case without explicitly referring to it?

A: Pass it as an explicit parameter.
var users = {
    count: 0,
    _this: this,

    // Constructor function
    CreateUser: function (name, email, parent) {
        this.name = name;
        this.email = email;

        // Is this the only way to access the containing object?
        parent.count++;
    },

    getCount: function () {
        return this.count;
    },
};

var user = new users.CreateUser('Rick', 'rick@example.com', users);

A: It looks like what you are looking for is a static property, which are still to come in JS.
It is an experimental feature though.
Currently:

Static (class-side) data properties and prototype data properties must be defined outside of the ClassBody declaration:

Rectangle.staticWidth = 20;
Rectangle.prototype.prototypeWidth = 25;

Since what you do here is somehow similar to Joshua Bloch's idea of a static factory method or factory method pattern in general, it makes sense to move new keyword up to CreateUser method of users object.
By doing so you can use closure to save the reference to users object, implement nested constructor function and invoke it with new keyword.
Working example:

var users = {
    count: 0,

    CreateUser: function (name, email) {
        var self = this;
        const createUser = function(name, email) {
              this.name = name;
              this.email = email;
              self.count++;

        }
        return new createUser(name, email)
    },

    getCount: function () {
        return this.count;
    },
};
var user = users.CreateUser('Rick', 'rick@example.com')
console.log(user)
console.log(users.getCount())
users.CreateUser('Morty', 'morty@example.com')
users.CreateUser('Jerry', 'apples@example.com')
console.log(users.getCount())


text:
Q: how to parse nested XML in iphone sdk I want to parse following XML, but i'm confused how to parse it because I have multiple nesting in a single record. Can any one give me  a suggestion for this?
<daily_record>
    <date>2011-04-17</date>
    <gold>
        <team_image>http://hockeypicks.com/ConfiMeter/nhl_images/vancouver.bmp</team_image>
        <percentage>56%</percentage>
        <status>WIN</status>
    </gold>

    <silver>
        <team_image>http://hockeypicks.com/ConfiMeter/nhl_images/detroit.bmp</team_image>
        <percentage>66%</percentage>
        <status>LOST</status>
    </silver>

    <bronze>
        <team_image>http://hockeypicks.com/ConfiMeter/nhl_images/nashville.bmp</team_image>
        <percentage>66%</percentage>
        <status>LOST</status>
    </bronze>
    <avg_conf>56.22%</avg_conf>
</daily_record>

A: NSData *data=[NSData dataWithContentsOfURL:myUrl.mURL];
NSString *string=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
DDXMLDocument *doc=[[[DDXMLDocument alloc] initWithXMLString:string options:0 error:nil] autorelease];
NSArray *docs=[doc nodesForXPath:@"//item" error:nil];
NSLog(@"Doc Count%i",[docs count]);

for (DDXMLElement *documents in docs)
{}

then in this for loop u can do something like this:
DDXMLNode *childNode=[documents childAtIndex:k];
DDXMLElement *childElement=(DDXMLElement *)childNode;
book.title=[childElement stringValue] ;
book.podLink=[[childElement attributeForName:@"url"] stringValue];//For Attributes


text:
Q: Bonferroni correction in generalised linear model I am running a generalised linear model in R. I have a single response variable and a maximum of 4 possible explanatory variables. I am adding each explanatory variable to the model sequentially, based on whether the coefficient is statistically significant.
If the coefficient for an explanatory variable is statistically significant at 0.05, the explanatory variable remains in the model.  If the coefficient for an explanatory variable is NOT statistically significant at 0.05, the explanatory variable is removed from the model.
I am wondering if instead of using 0.05, I should be using a Bonferroni corrected P value? Should I use a threshold of 0.05/4 = 0.0125?


text:
Q: What are solid NMaven or build servers for .NET alternatives? Maven had a long history and is well supported in the Java world. NMaven has received a less successful start and has never become as popular in the C#/.NET world as its larger cousin was in the Java world. The project seems close to dead(ish), but maybe I'm wrong.
Are there alternatives that, preferably using NAnt, are commonly used in favor of NMaven and have similar properties as Maven? What I'm looking for is a good open source automatic build server for .NET, if any exists. Or should I continue using NMaven?

A: MAven is more a repository manager than a CI/Build setup.
If you're looking for continuous integration servers, here are the ones I know of:

*

*CruiseControl.Net (http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET) Good enough, free, but can be a resource hog and configuration is sometimes maddening.

*Hudson ( http://hudson-ci.org/ )  has some pretty good .Net specific tasks. As a open source/free automatic build setup I tend to favor it over CruiseControl.Net. It needs Java to run, but it runs fine on Windows. The web dashboard is nice (albeit with that strange fetish for blue instead of green) and project configuration is a breeze (compared to CCNet...)

*TeamCity (JetBrains) (http://www.jetbrains.com/teamcity/) is really good, offers a lot of interesting features (private remote builds before committing, distributed build agents, etc.) and nice VS.Net integration. You have to pay for a license but it's free for small teams.

All of these support the most popular SCM (CVS, SVN) Hudson and TeamCity support Mercurial and Git.
I'd go for Hudson or TeamCity.

A: We use CruiseControl.NET (with a little NAnt thrown in).  It is open source (Apache/BSD), solid, popular, and under active development.
It's designed for Continuous Integration, but builds can easily be manually triggered if you prefer.
Configuration is via an XML file.

A: For continuous integration and creating builds TeamCity is nice and free for smaller operations (up to 3 build agents). It's powerful, supports NAnt and friends (e.g. MSBuild) out of the box, and it's best feature is ease of use and configuration. Even upgrades are painless.
The rub is that it isn't completely free, and if you need more features (e.g. more than 3 build agents) it costs.
Also, you ask about a Maven replacement - it won't handle dependencies like Maven does.

A: You might want to look at our Parabuild. It is not open source but it is free for small teams, support included.

A: You might like to look at NPanday, which is being actively worked on. It will work with any build server that Maven does.

A: NMaven is abandoned and NPanday is its continuation.


text:
Q: How do I replace [number] to {number - 1} using Regex in C#? I have string values like A, something happened [1], something else [2], whatever [3] and want to replace it to A, something happened {0}, something else {1}, whatever {2}.
So, basically replace [ with { and ] with } if there is a number between and then decrement the number between by one. Is this possible with Regex somehow?
So far I got this:
var text = "A, something happened [1], something else [2], whatever [3]";
var result = Regex.Replace(text, @"\[(\d+)\]", @"{$1}");
Console.Write(result);

However, this gives me A, something happened {1}, something else {2}, whatever {3}.
Is there an option to decrement the numbers by one?

A: You may decrement the number in a match evaluator:
var text = "A, something happened [1], something else [2], whatever [3]";
var result = Regex.Replace(text, @"\[(\d+)\]", m => $"{{{int.Parse(m.Groups[1].Value)-1}}}");
Console.Write(result); // => A, something happened {0}, something else {1}, whatever {2}

See the C# demo
In case the number cannot be cast to int use int.TryParse:
var result = Regex.Replace(text, @"\[(\d+)\]", m =>
    int.TryParse(m.Groups[1].Value, out var number) ? $"{{{number - 1}}}" : m.Value);

For C# prior to C#7:
var result = Regex.Replace(text, @"\[(\d+)\]", m => {
         int number;
         if (int.TryParse(m.Groups[1].Value, out number))
         {
            return $"{{{number-1}}}";
         }
         else
         {
            return m.Value;
         }
    });


text:
Q: Gaussian-Gaussian model Can we rewrite N Gaussian measurements ~iid, in one measurement with a Gaussian distribution?
However, a book talking about these really confused me.

Suppose we have data from multiple related group. For example $x_{ij}$ can be the test score for student i in school j, for $j = 1:D$ and $i = 1:N_j$. We want to estimate the mean score for each school $\theta_j $and we assume that $\theta_j$ come from a common distribution $N(\mu,r^2)$
The join distribtuion has the form:
$$p(\theta,X |\mu,r,\sigma) = \prod_{j=1}^D N(\theta_j|\mu,r^2) \prod_{i=1}^{N_j} N(x_{ij} | \theta_j,\sigma^2)$$
Once we have estimated $(\mu,r)$, we can compute the posteriors over the $\theta_j$'s. To do that, it simplifies matters to rewrite the joint distribution in the follow form, exploiting the fact that $N_j$ Gaussian measurements with values $x_{ij}$ and variance $\sigma^2$ are equivalent to one measurement of value $y_j := (1/N_j)\sum_{j=1}^{N_j} x_{ij}$ with variance $\sigma_j^2 := \sigma^2/N_j$
This yields
$$p(\theta,X |\hat \mu,\hat r,\sigma) = \prod_{j=1}^D N(\theta_j|\hat\mu,\hat r^2) N(y_j | \theta_j,\sigma_j^2)$$

But a particular event A in which $X_{1j}= x_{1j},..., X_{nj} = x_{nj}$ is a subset of event B = {y:$y_j := (1/N_j)\sum_{j=1}^{N_j} x_{ij}$}
Can someone explain?

A: The real question here is why we can substitute the whole data with sufficient statistics in finding the posterior probability.
This is best to summarized in an equation

$p(\theta|t(x1,...,xn)) = (p(t|\theta)*p(\theta))/p(t)$

In regard of the getting the posteria, we can map to a statistic t= T(x1,...,xn) upon getting the observation(x1,...,xn) and because it simplified the calcuation of the likelihood $p(t(x)|\theta)$, we should focus the pdf of the statistic instead of the whole data


text:
Q: generalized linear model with constraint from known observation? Suppose one has a generalized linear model with binomial error and link $g$ of the form
$$
g(\pi_j) = β_0 + β_1 x_j  \qquad  j = 1,2,···
$$
where $x$ is the explanatory variable. Suppose that we also know that
$$
g(\pi_0) = β_0 + β_1 x_0
$$
for a single pair of known values $\{\pi_0, x_0\}$.
Would anyone know how I can fit this model?

A: You can solve the constraint equation and use an offset to fit the resulting model.  That is,
$$
\begin{split}
g(\pi_0) & = \beta_0 + \beta_1 x_0 \\
\beta_0 & = g(\pi_0) - \beta_1 x_0
\end{split}
$$
Substituting into your regression equation:
$$
\begin{split}
g(\pi_j) & = g(\pi_0) - \beta_1 x_0 + \beta_1 x_j \\
         & = g(\pi_0) + \beta_1 (x_j - x_0)
\end{split}
$$
So you need to fix the intercept at $g(\pi_0)$ and use $x-x_0$ as your predictor variable.
In R, you would do this as:
glm(p ~ -1 + I(x-x0) + offset(plogis(p0)),
     family=binomial, data = ...)

The -1 suppresses estimation of the intercept, plogis() is the logit function [the default link, or $g()$, for the binomial]. I used p instead of pi for the response because pi is a built-in variable in R: might still work, but v. confusing ...


text:
Q: Create a new column in data frame based on the range found in another column and a common column I'm trying to create a new column in a data frame based on values from another data frame.
df1 is,
Name    Depth
A   100
A   120
B   200

df2 is,
Name    Start_Depth End_Depth   Zone
A   50  150 Zone1
A   150 200 Zone2
B   50  120 Zone3
B   120 300 Zone4

I want to add Zone column in df1, based on two conditions,

*

*"Name" should match in both data frames

*df1.Depth should be between Start_Depth and End_Depth in df2 for same "Name"

Output df1,
Name    Depth   Zone
A   100 Zone1
A   120 Zone1
B   200 Zone4

A: Use df.merge with df.query:
In [120]: r = df1.merge(df2).query('End_Depth >= Depth > Start_Depth')[['Name', 'Depth', 'Zone']]

In [121]: r
Out[121]:
  Name  Depth   Zone
0    A    100  Zone1
2    A    120  Zone1
5    B    200  Zone4

OR use Series.between:
In [114]: x = df1.merge(df2)
In [124]: r = x[x.Depth.between(x.Start_Depth, x.End_Depth)][['Name', 'Depth', 'Zone']]

In [125]: r
Out[125]:
  Name  Depth   Zone
0    A    100  Zone1
2    A    120  Zone1
5    B    200  Zone4


text:
Q: Limit of a function $p_n$ when $n \rightarrow +\infty$ We have the following function : $$p_n = \frac{n}{(2n+1)^2} \frac{1}{\sum_{d=1}^n \dfrac{1}{(2n+d)^2} }$$
And we would like to know the limit of $p_n$ when $n \rightarrow +\infty$.
I don't know at all how to do it... I just know that $\dfrac{n}{(2n+1)^2} \rightarrow_{n \rightarrow +\infty} 0$. But how to study the second member ?

A: Write $\ p_n$ as :$$\ p_n = (\frac{n^2}{(2n+1)^2})(\frac{1}{\frac{1}{n}\sum_{d=1}^n\frac{1}{(\frac{d}{n}+2)^2}})$$Now , You can use "limit of a sum" for second part and limit of first can be calculated by dividing numerator - denominator by $\ n^2$.. Final limit will be product of limits of both parts.

A: at a first step you must calculate the sum $$ \sum_{d=1}^n\frac{1}{(2n+d)^2}$$

A: Put first
$$v_n=\sum_{d=1}^n \frac{1}{(2n+d)^2}=\frac{1}{4n}u_n$$
with $$u_n=\frac{1}{n}\sum_{d=1}^n\frac{1}{(1+\frac{d}{2n})^2}$$
The sum $u_n$ is a Riemann sum, so $u_n$ is convergent to $L=\displaystyle \int_0^1 f(t)dt$, with $f(t)=\frac{1}{(1+t/2)^2}$.
Now your expression is $\frac{4n^2}{(2n+1)^2u_n}$, so it is easy to see that the limit is $\displaystyle \frac{1}{L}$. It remain to compute $L$.


text:
Q: repeat the play of the music certain x number of time using android media player In my application user selects the count like 1, 21, 51, 101, 108,like when he selected using buttons or radio button, the media player has to be repeated at number of time. If he selects 21, media player should repeat the playing of the music by 21 times. In my code, if I use while loop inside the for loop its blocking the UI, not allowing to stop or pause the play, if I did not use the while loop it plays only once. Please I need to solve it any one will be appreciated thanks in advance. Below I am posting my entire code
public class MainActivity extends Activity implements OnClickListener{
    private MediaPlayer mp;
    int count;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        findViewById(R.id.button_1).setOnClickListener(this);
        findViewById(R.id.button_2).setOnClickListener(this);
        findViewById(R.id.button_3).setOnClickListener(this);
        findViewById(R.id.button_4).setOnClickListener(this);
        findViewById(R.id.button_5).setOnClickListener(this);
        findViewById(R.id.pause).setOnClickListener(this);
        findViewById(R.id.stop).setOnClickListener(this);

    }

    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.button_1:
            if (mp!=null) {
                mp.release();
            }

            player(3);

            break;
        case R.id.button_2:
            if (mp!=null) {
                mp.release();
            }
            player(21);

            break;
        case R.id.button_3:
            if (mp!=null) {
                mp.release();
            }
            player(51);

            break;
        case R.id.button_4:
            if (mp!=null) {
                mp.release();
            }
            player(108);

            break;
        case R.id.button_5:
            if (mp!=null) {
                mp.release();
            }

            break;
        case R.id.pause:

                mp.pause();

            break;
        case R.id.stop:

                mp.stop();

            break;

        }

    }

    private void player(int count) {
        // TODO Auto-generated method stub
        mp = MediaPlayer.create(this, R.raw.a);

         for (int i=1; i<=count ; i++){
             mp.start();
             while(mp.isPlaying());
     }
        // mp.release();

 }
    @Override
    protected void onDestroy() {
        if(null!=mp){
            mp.release();
        }
        super.onDestroy();
    }

}

A: you can achieve this by setting a yourCount integer that has the numbers you are going to repeat your sound and than simply do this
    int count = 0;
    mp.setOnCompletionListener(new OnCompletionListener()

        @Override
        public void onCompletion(MediaPlayer mp) {
            if (count < yourCount) {
                mp.start();
                count++;
            }
        }
    });
    mp.start();

A: try this, Hope it helps
mp.setOnCompletionListener(new OnCompletionListener(){
    @Override
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub
        // Count here and restart if required.
    }});


text:
Q: Save TimeZone with Date in mongodb I have java.util.Date field in my document class.
E:g:
@Document(collection = "testdoc")
public class TestDoc {
    @Id
    String id;
    Date startDate;
}

Even if I set the Date with UTC and IST, it always save in my collection as below,
 "startDate" : ISODate("2015-08-21T18:30:00.000Z")

How can I save the time zone also in mongo collection? What does Z stand in this case?

A: Do the conversion before storing and save as UTC always. Then reconvert it in the timezone you want before displaying.
If you desperately want to store the timezone with the offset you may have to deal with it as a separate string in db, but it cannot go with date field for MongoDB.
As currently MongoDB doesn't allow saving of timezone.
Below is the open JIRA issue or the same.
https://jira.mongodb.org/browse/SERVER-6310

A: Dates in MongoDB are stored in UTC. There isn't timestamp with a timezone data type like in some relational databases. Applications that need to access and modify timestamps, based on local time, should store the timezone offset together with the date and offset dates on an application level.
In the MongoDB shell, this could be done using the following format with JavaScript:
let now = new Date();
db.page_views.save({date: now,
                    offset: now.getTimezoneOffset()});

Then you need to apply the saved offset to reconstruct the original local time, as in the following example:
let record = db.page_views.findOne();
let localNow = new Date( record.date.getTime() - ( record.offset * 60000 ) );

A: The 'Z' signifies that the time is stored in UTC. Mongo internally converts all local representations of time in UTC before storing. However, one suggestion would be to store the time along with the timezone which is received from your application. You can later reconstruct the local time from the UTC time and the timezone in your application logic.
Please go through this link. They have given an example on how to model local time data using JavaScript.
https://docs.mongodb.com/v3.2/tutorial/model-time-data/

A: I guess here you'll find a good guideline how to handle timestamps in different scenarios for different data language independent.
As it's recommendet in the document, ALWAYS use UTC to save the data, even it is local timezone. If necessary, save the time zone in a seperate field ( JSON or xml) and follw the format guideline ISO 8601. ( like you did but there are many possible representations)
As far as I know, correct me if i'm wrong, JSOn does not deal with specific date formats but JS does. Microsoft docs recommends the followind format bases on ECMA YYYY-MM-DDTHH:mm:ss.sssZ this
The Z in the Timestamp shows that it's UTC format with zero offset +00:00
if nothing else is added.
If you want to use the "Z" notation, you have to add or substract the offset within the timestamp instead of writing the zero-offset and add the offset at the end.
I recommend you to follw the w3c guideline because it covers different scenatios for different time saving usecases.
Hope this helps


text:
Q: permutation or combination using shell scripting An number is added to a file on daily basis. Like 1000, 2000, 2560, 5356, etc. till last day of the month, say upto 30/31 numbers. I want to write a shell script with which when I pass a random number like 5560, this 5560 can be combination of any 2 or 3 or 4 or 5 numbers whose sum is equal to 5560. These numbers can be of any permutation or combination. All those numbers should get printed whose sum is equal to the passed random number 5560.
Possible solution I can think of:

*

*Loop thru the file and store all the values in an array.

*use brace to make combinations of array elements

*?

A: Addition is commutative. So the sum of a specific combination is the same as the sum of any permutation of the same numbers.
That should save some time. I believe the number of combinations of 31 numbers {2,3,4,5} at a time is only 206,336, whereas the number of permutations {2,3,4,5} at a time is 21,172,380.
Combinations lend themselves well to recursive solutions, but your runtime in shell is likely to be annoying, if not prohibitive. Would you consider an awk solution?
Are all the numbers in the file unique? If (3 + 3) = 6, then there are two (identical) combinations because the 3s can be reordered.


text:
Q: is this possible to hook on messages that child process is sending to windows console? As of now I tried SetWindowsHookEx, but it seems that it isn't able to catch messages from console window.
Code illustrating this :
#include <iostream>
#define _WIN32_WINNT 0x501
#include <windows.h>

using namespace std;

HHOOK hHook = 0;

LRESULT CALLBACK Callback(int code,WPARAM wParam,LPARAM lParam) {
  cout << "tick: " << GetTickCount() << ", code: " << code << ", wParam: "
    << wParam << ", lParam: " << lParam << endl;
  return CallNextHookEx(hHook,code,wParam,lParam);
}

int main() {

  int idHook[14] = { WH_CALLWNDPROC, WH_CALLWNDPROCRET, WH_CBT, WH_DEBUG,
    WH_FOREGROUNDIDLE, WH_GETMESSAGE, WH_JOURNALPLAYBACK, WH_JOURNALRECORD,
    WH_KEYBOARD, WH_KEYBOARD_LL, WH_MOUSE, WH_MOUSE_LL, WH_SHELL,
    WH_SYSMSGFILTER };

  for (int i=0 ; i<=14 ; i++) {
    hHook = SetWindowsHookEx( idHook[i] , (HOOKPROC)Callback,
      NULL, GetCurrentThreadId());
  }

  system("dir");
  //here appeared nothing insead `dir` output, but why ?
  system("pause");
  MessageBox(NULL, "Now creating window ...", "... and messages appear.", 0);
}

Another way that I looked at is api of the console itself, specifically the ReadConsoleInput() function. But it is not working through callback so it is only useable for catching key or mouse events. Example code here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms685035%28v=vs.85%29.aspx
But what I need is to take hold of console calls that are issued by process that was created through system or CreateProcess. By calls I mean for example to catch every printf() issued by child process before it gets to the console that my process owns.
Any chance is that possible ?

A: Try output redirection. Create two pipe objects (one for stdout and another for stderr) using CreatePipe API, and pass them in hStdOutput and hStdError members of STARTUPINFO when invoking CreateProcess. Anything the child process outputs will not be displayed, but will go through these pipes; you can then filter the data as appropriate and output it yourself.


text:
Q: In flutter how to use GetX to get and set first frame in video player? I am using video_player with GetX. And as you can see in official example, to get and set first frame of video as thumbnail, you have to use empty setState.
@override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(
        'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4')
      ..initialize().then((_) {
        // Ensure the first frame is shown after the video is initialized,
        // even before the play button has been pressed.
        setState(() {});
      });
  }

Now I am not able to understand even that how to figure out below code using GetX. (i.e. how do I get first frame using GetX and set it on video player as thumbnail.)

// Ensure the first frame is shown after the video is initialized,
// even before the play button has been pressed.
setState(() {});

Any help is much appreciated.
Edit: I am using GetX hence I do not want to use stateful widget. So how can i achieve the same example using GetX, especially what this part is doing - setState(() {});

A: actually the comment is pretty clear

Ensure the first frame is shown after the video is initialized,
even before the play button has been pressed.

the purpose of the empty setState executed after video initialize is to rebuild ui once. so first frame of your video shown in the ui.


text:
Q: How to subtract date and time in Pandas? I have data from Pandas which was the contents of a CSV file:
Date                Inbound     Outbound
17/10/2019 12:35    5.49E+02    3.95E+03
17/10/2019 12:40    2.06E+02    3.17E+03
17/10/2019 12:45    2.06E+02    3.17E+03
17/10/2019 12:50    2.06E+02    3.17E+03
17/10/2019 12:55    2.06E+02    3.17E+03
17/10/2019 13:00    2.06E+02    3.17E+03
....

I aim to convert the column Date from timestamps to time periods in units of minutes, which should result in something like the following:
    Date        Inbound     Outbound
    0           5.49E+02    3.95E+03
    5           2.06E+02    3.17E+03
    10          2.06E+02    3.17E+03
    15          2.06E+02    3.17E+03
    20          2.06E+02    3.17E+03
    25          2.06E+02    3.17E+03

A: You can use subtract the first timestampe to calculate the difference, then get total_seconds() and convert to minutes:
df['Date'] = pd.to_datetime(df['Date'])

df['Date'] = (df.Date.sub(df.Date.iloc[0])
   .dt.total_seconds().div(60).astype(int)
)

Output:
   Date  Inbound  Outbound
0     0    549.0    3950.0
1     5    206.0    3170.0
2    10    206.0    3170.0
3    15    206.0    3170.0
4    20    206.0    3170.0
5    25    206.0    3170.0

A: import pandas as pd

data = [
"17/10/2019 12:35",
"17/10/2019 12:40",
"17/10/2019 12:45",
"17/10/2019 12:50",
"17/10/2019 12:55",
"17/10/2019 13:00",
    ]

columns = ["Date"]

df = pd.DataFrame(data, columns = columns)
# Because the values came in frm a CSV, they are not datetime objects.
# Convert the column to datetime ojects
df['Date'] = pd.to_datetime(df['Date'])
subtractdate = df["Date"].iloc[0]
df["Diff"] = df["Date"].apply(lambda x: x - subtractdate)
print(df)

EDIT:
To get the minutes, do the following...
df["Diff"] = df["Date"].apply(lambda x: (x - subtractdate).seconds/60)

(x - subtractdate) returns a timedelta object. It doesn't have a "minutes" option, but does have a seconds. This will return in a float format (I.e. 5.0, 10.0)
To get it as a string, do the following:
df["Diff"] = df["Date"].apply(lambda x: str( (x - subtractdate).seconds/60  ) )

And to get it as an int:
df["Diff"] = df["Date"].apply(lambda x: int( (x - subtractdate).seconds/60  ) )

The int will be the "5, 10, 15" format.


text:
Q: kernel module programming - how to remove all the data in text file in the user space I know it's not worth doing but I have to. I want to delete information from a specific text file that called file1.text after i read from this file , How can i do that in my module. Many thanks to all the helpers.

    static int checkDOS(char *name)
    {

       //get the path to this file
       char path[2000];
       strncat(path,"/home/daniel/count/should/",1000);
       strncat(path,name,1000);
       struct file * file_dos;

       //Open this file
       file_dos=filp_open(path,O_RDONLY,0);
       char count[1];//save the first character of file

       //check if the file is exists
       if(IS_ERR(file_dos) == 0)
       {

          file_read(file_dos,0,count,1);//Read this file
          if(count[0]=='0')
          {
            return 0;
          }

          char count2[200];//Stores the number listed in the file
          filp_close(file_dos,NULL);//close the this text file
          file_sync(file_dos);

         //Takes the character stored in the count variable converts
          // it to a number and then subtracts one from it, then

          file_dos=filp_open(path,O_WRONLY, 0);
          long count_dos;
          kstrtol(count,0,&count_dos);
          count_dos=count_dos-1;

          //converts it to a string, then writes in a file
          sprintf(count2, "%d", count_dos);
          file_write(file_dos,1,count2,1);
          filp_close(file_dos,NULL);
          return 1;

       }
       return 0;

     }


text:
Q: My PC isn't updating from 1803 to 1903 I cannot seem to update, and using the Windows 10 Update Assistant reports that Windows is installed in an unsupported directory, and it cannot proceed to update without clearing all of my data (PC specs are below).
I tried clearing the Windows update cache, and it redownloaded through Windows update, and it rebooted, and got to 18% and then rebooted, and then got to the boot screen and said Updating your system, and at 5% it said FATAL ERROR and an error code. This happens every once in a while now, when it attempts to update.
I tried all troubleshooters, everything, even using an MSU file to update, and using the installation media to update, but nothing worked.
I use UltraUXThemePatcher for my UX theme, as I use a custom dark theme, and I have some registry tweaks like no lock screen, dark Alt Tab backgrounds. I use Listary for search. I have a registry tweak to set default program files folders to my D: drive.
I am on Windows 10 1803, 1809 refuses to install, and I don't have a dedicated DVD/ROM drive.
I will be happy to respond in this forum.
Specs:

*

*CPU: Intel Core i7 7740x

*Mobo: Asus TUF Mark 2

*GPU: Nvidia GeForce GTX 1060 3GB (ASUS Geforce GTX 1060 3GB)

*RAM: 16GB 4x4 Corsair Vengeance LPX

*SSD: 240GB M.2 SSD - it isn't well-known. I got it from Amazon & it seemed legit, it was 6GbPS

*HDD: 2TB Seagate Baracuda

*PSU: Corsair SF Series Modular SF600 ATX Power Supply (600 watts) (80 plus platinum)

*Cooler: DeepCool CAPTAIN 240 EX White AIO (used on a 2066 socket)

*Case: NZXT S340VR Elite

A: I was kind of waiting for this question.
While the Bluetooth adaptor is one thing that does this, the windows update process checks for certain things then fails if they are not there. This is stored in registry (boo!) and the tool that reads it was a little hard to find.
MS has a tool for advanced users called SetupDiag that looks through the logs and tells you precisely why newer versions of windows isn't running a feature update. In my case it was backup software (macrium) that had changed a registry entry (related to volume shadow copies)  and didn't reset it once uninstalled . It also tells you what to do.
Unlike the update troubleshooter, it dosen't run through a series of useless steps - it tells you what's wrong, and expects you to fix it. Which is much better.

A: I am pretty new here, didn't realise I could just answer my own question, I have already solved it so here is my solution:

So, here is what I did: First, I set my Program Files DIR to C: from D: and booted into Windows PE. Then, I went into CMD and used DISM to image the C: drive, as a failsafe. Then, I applied the image with DISM, but to a folder called Windows.TEMP and that was the fresh install, then I modified the registry of it, followed by adding a boot entry. I then booted to it and skipped OOBE, and booted back into WinPE. I then copied everything from the old Windows folder that I knew was not related to Windows itself, and moved the new install. It worked out, I patched UXTheme and it was upgraded!

Anyway, if you have the same issue and the solution that I did doesn't work for you, tag me in a new post and I might be able to help.


text:
Q: save images as zip on a custom folder in php im trying to save my images on a zip file, my code works fine but saves all images inside the folder /wp-content/uploads/2016/03/... and i want to have my own  "images" folder on the zip with all the content on it...  i tried the other solutions posted on stackoverflow but i cant get it to work
my code :
<?php
//This script is developed by www.webinfopedia.com
//For more examples in php visit www.webinfopedia.com
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
    $zip = new ZipArchive();
    //create the file and throw the error if unsuccessful
    if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
        exit("cannot open <$archive_file_name>\n");
    }
    //add each files of $file_name array to archive
    foreach($file_names as $files)
    {
        $zip->addFile($file_path.$files,$files);
        //echo $file_path.$files,$files."<br />";
    }
    $zip->close();
    //then send the headers to foce download the zip file
    header("Content-type: application/zip");
    header("Content-Disposition: attachment; filename=$archive_file_name");
    header("Pragma: no-cache");
    header("Expires: 0");
    readfile("$archive_file_name");
    exit;
}

//------------------------------------------------------------------------------------------------------
//If you are passing the file names to thae array directly use the following method
$file_names = array('../wp-content/uploads/2016/03/IMG_8121-900x1200.jpg','../wp-content/uploads/2016/03/IMG_8124-900x1200.jpg','../wp-content/uploads/2016/03/IMG_8106-900x1200.jpg');

//------------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------

//Archive name
$archive_file_name=$name.'DEMOphpCreateZipTodownloadMultipleFiles.zip';
//Download Files path
$file_path=$_SERVER['DOCUMENT_ROOT'].'/images/';

//cal the function
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
?>

A: Simply change:
$zip->addFile($file_path.$files,$files);

into:
$zip->addFile($file_path.$files, 'pictures' . DIRECTORY_SEPARATOR . pathinfo($files)['basename']);

Second parameter for addFile method is how file will look like inside archive so you can define new path and filename.

A: If i got it right, you want folder 'images' inside zip archive.
try something like this:
public function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
    $zip = new \ZipArchive();
    //create the file and throw the error if unsuccessful
    if ($zip->open($archive_file_name, ZipArchive::CREATE )!==TRUE) {
        exit("cannot open <$archive_file_name>\n");
    }
    $zip->addEmptyDir("images");
    //add each files of $file_name array to archive
    foreach($file_names as $files)
    {
        $zip->addFile($file_path.$files, "images".DIRECTORY_SEPARATOR.$files);
    }
    $zip->close();
    ...
}

it ads empty folder into your zip a then specifies file path within zip when adding in foreach loop


text:
Q: Detect in Javascript/jQuery if mobile browser is not open or active *I have searched online and on SO
I have a mobile site made in jQuery Mobile. If the user has navigated away from the mobile browser on their phone, (to another app), which would hide the mobile browser (but the mobile browser would still be running on their phone), I need a way in Javascript or jQuery to know when the user opens their mobile browser again.
I have packaged the mobile site as an app using PhoneGap and I currently achieve this by using the onResume() function.

A: You can detect when the tab or window is closed via the onunload and onbeforeunload events. These will trigger if the tab is closed, the back button is hit or an exit link is clicked.
There's a proposal to allow webapps to detect if they're in the foreground or not, the visibilitychange event, http://www.w3.org/TR/2013/REC-page-visibility-20131029/#sec-visibilitychange-event
It's partially supported, mainly by newer browsers, so depending on your needs it may work for you. http://caniuse.com/#feat=pagevisibility


text:
Q: Is there a way to add a delay to your weapon following the camera? In the game apex legends there is a slight delay to the weapon following the camera when you turn. I was wondering if there is an easy way to replicate this in unity?

A:
Yes it's possible, it's called weapon sway.
private float swayAmountX = 5;
private float swayAmountY = 2;
private float smooth = 8;

private void Update(){
    float mouseX = Input.GetAxisRaw("MouseX") * swayAmountX;
    float mouseY = Input.GetAxisRaw("MouseY") * swayAmountY;

    Quaternion rotationX = Quaternion.AngleAxis(-mouseY, Vector3.right);
    Quaternion rotationY = Quaternion.AngleAxis(mouseX, Vector3.up);

    Quaternion targetRot = rotationX * rotationY;

    transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRotation, smooth * Time.deltaTime);
}

Put this in a script inside the parent of your weapon and you should be good. If you already have rotation on your character i think you can easily see how it's done and adapt it to your needs. This script stay pretty basic but you can enhance it to your liking :)
Hope it helped you ! Have a nice day !


text:
Q: An error occured.......unmet dependecies.........run package manager There's a red circle with minus sign at the top left corner on my ubuntu 14.04 desktop, when clicked it says:

An error occurred, please run Package Manager from the right-click menu or apt-get in a terminal to see what is wrong.

The error message was:
Error: Opening the cache(E:Encountered a section with no package:header, E: Problem with MergeList/var/lib/apt/lists/dl.google.com_linux_chrome_deb_dists_stable_main_i18n_Transaltion-en, E:The package lists or status file could not be opened or parsed.)'. This usually means that your installed packages have unmet dependencies.

Please help me solve this problem.

A: You need to first remove the problematic Merge List and then re-create it. Open your terminal and run the following codes:
sudo rm /var/lib/apt/lists/* -vf
sudo apt-get clean
sudo apt-get update
sudo apt-get upgrade


text:
Q: Is it possible to export Datadog Aurora dashboard as cloud formation? I'm using this built-in dashboard for monitoring Aurora and was wondering how can I have as code, as cloud formation stack precisely.
I'm aware of those three repos which do backup and monitoring of changing of the dashboard in the API and then commit back to GitHub, but I only want to export it once.

A: I was able to do that by using this api call: https://docs.datadoghq.com/api/?lang=python#get-a-screenboard
and then get it as a son file, which can be passed to cloud formation later.


text:
Q: Opamp noise: When is a resistor in the signal path? I am confused as to when a resistor is considered to be in the signal path and when its not when it comes to opamp noise calculations. For instance, take the following circuit:

simulate this circuit – Schematic created using CircuitLab
a very similar circuit is published in Douglas Self's book, he mentions that the only resistor in the signal path (on the non-inverting input) is the 100ohm resistor R3, so R1 and R2 do not contribute to the noise. It was my understanding that a resistor can be modeled like an ideal or noise-less resistor in series with a noise generator, so what I would think is that for instance, if I replace R1 with a noise generator given by \$\sqrt{4KTBR} \$ with R1 in series, then that noise generator should be amplified by the noise gain of the opamp. Why is R1 and R2 not in the signal path then?
The author also mentions the following circuit which is a simple inverting amplifier with a resistor on the non-inverting input to compensate for bias currents.

simulate this circuit
In this case the author mentions that resitor R3 causes noise, so I dont get it, in both circuits there is a resistor connected to the non-inverting input, yet in the first circuit it does not produce noise but it does produce noise in the second circuit, so how do I know when a resistor produces noise (in the signal path) and when not? it doesnt seem very intuitive.
Edit: I simulated the first circuit and ran a noise analysis, what I found is that if R3 is small valued, then varying the value of R1 or R2 does not affect the noise output and the noise depends only on R3 (plus the feedback resistors and opamp noise, etc.. Im just focusing on the non-inverting input), however if R3 is not small, then the value of R1 or R2 does affect the noise output, however, I believe this is because of the voltage divider effect is attenuating the noise of the first resistor R3, not because R1 or R2 are contributing to the total noise output, so yeah, to add to the confusion, it would seem that only R3 is in the signal path of the non-inverting input and R1 and R2 contribute no thermal noise to the output, I dont understand this. Doing a simpler simulation, just connecting a resistor to the non-inverting input in parallel with a voltage source shows that the EIN of the resistor is 0, effectively contributing no noise to the output.
I also simulated the second circuit and in fact R3 (of the 2nd circuit) does affect the noise output if I vary its value. So my observations are: shunt resistors in the non-inverting input when using as non inverting amplifier do not contribute to noise, whilst a resistor in the non-inverting input when using as an inverting amplifier does contribute to noise.

A: All resistors contribute to noise. Looking at the circuit more carefully I notice two things.

*

*The noise sources of R1 and R2 encounter a very large divider providing about 60dB of attenuation to their noise.

*Those noise sources encounter a very strong low-pass filter further dropping their noise spectrum.

But that has nothing to do with "being in the signal path", if R3 was larger and the capacitors smaller, then their noise contribution would dominate, while keeping the same topology and frequency response.
"Being in the signal path" is at best some sort of mnemonic device that leads you to the right design choices (I.e., make R3 small), but it is not a circuit analysis tool.
When a resistor is "in the signal path" it really means that both it and the signal are equally affected, and there is nothing you can do in the design to reduce that noise that will not also affect the signal. So you should make that noise contribution as small as possible, or try to avoid it altogether.
I have designed low-noise circuits in which some of the major noise contributors are the current source transistors biasing the transistor at the tail of differential pairs (on the opposite corner of the IC). There really can't be something further away from the "signal path" than that.

A: In the 1st circuit, since C1 is high enough, we can assume it as a short:

simulate this circuit – Schematic created using CircuitLab
You can model a resistor with either;

*

*a noise-less resistor with a noise generator voltage source in series,

*or a noise-less resistor with a noise generator current source in parallel.

So, if we replace R2 and R1 with the 2nd model, we'll see that total noise generator current source, n1 + n2, will see a heavy low-pass filter (C2 = 100nF & R2||R1 = 69k, yielding fC = 23Hz):

simulate this circuit
Thus the noise will most likely be filtered (Please remember that a parallel RC filter works only if driven by current source).
In the second circuit, if you replace the resistor with noise model then you'll see that there's no filtering. Probably that's why the noise totally reflects to the output.


text:
Q: How to combine two regular expressions in JavaScript validation

function checkpara(obj) {

  var paragraph = obj.value;
  var para = /\d{4}/;
  if (paragraph.match(para)) {

    document.getElementById("para_error").innerHTML = " You can't use numbers in description";
    document.getElementById("para_error").className = "errmsgshow";
  } else {
    document.getElementById("para_error").className = "errmsghide";
  }

}
.wrapper {
  width: 100%;
  height: 100%;
}

.w_50 {
  width: 400px;
  margin-top: 50px;
  margin-left: 50px;
}

.errmsghide {
  display: none;
}

.errmsgshow {
  display: block;
  color: red;
}
<DOCTYPE! html>

        <textarea id="para" name="desc" rows="20" cols="66" onblur="checkpara(this)"></textarea>

I have used JavaScript to validate the paragraph. The paragraph should not contain more than 4 sequences of numbers (i.e 1234).
I want in this format.
4 sequence number space 4 sequence number.
Then it should show error message.
How can I combine the two regular expressions?

A: Do you need this: /\d{4}( \d{4})?/
Or for n sequences: /\d{4}( \d{4})*/


text:
Q: Scoping bug using locals() and an import within a function I have code that looks something like this:
def outer(*args):
    import os

    def inner():
        def fget(self):
            print(os)

        def fset(self, arg):
            print(os)

        return locals()

    return property(**inner())

outer()

But when ran, I get:

TypeError: 'os' is an invalid keyword argument for property()

Which means that os is within the local scope of inner.  Why is that?
If I replace import os with a simple variable declaration, the variable isn't within the scope of inner, so no error is thrown:
def outer(*args):

    os = 'foo'

    def inner():
        def fget(self):
            print(os)

        def fset(self, arg):
            print(os)

        return locals()

    return property(**inner())

outer()

Or, if I move import os to the global scope of the module, no error is thrown:
import os

def outer(*args):

    def inner():
        def fget(self):
            print(os)

        def fset(self, arg):
            print(os)

        return locals()

    return property(**inner())

outer()

What is the explanation for this?


text:
Q: Printing an array in a while loop I am trying to print my array using a method call once while the user inputs y or Y. I do not know how to get the array to only print once.
I've researched and tried tweaking my own code but I am lost.
public class Lab10p1 {
public static final int ROW = 5;
public static final int COL = 6;
public static final int MIN = 0;
public static final int MAX = 100;

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
    Scanner scan=new Scanner(System.in);
    System.out.println("Do you want to start Y/N?");
    char c =scan.next().charAt(0);

    while(c=='y'||c=='Y')
    {
        int[][] a = new int[ROW][COL];
        randArray(a, ROW, COL, MIN, MAX);
    }
}

public static void randArray(int[][] matrix, int row, int col, int low, int up)
{
    Random rand = new Random();
    for (int r = 0; r < row; r++)
    {
        for (int c = 0; c < col; c++)
        {
            int are=matrix[r][c] = rand.nextInt(up - low + 1) + low;
            System.out.print(" "+are);
        }
        System.out.println();
    }
}

the expected output is
Do you want to continue(Y/N): y
The array elements are:
12 31 12 21 45 23
32 12 67 54 35 67
34 54 33 34 53 34
23 34 43 23 45 78
23 54 89 76 54 34
The actual results are an infinite loop of printing 6x5 arrays

A: You should use if instead of while. If the user enters Y or y, the loop will never finish because c is never set to anything else but Y or y inside the loop and therefore the loop condition is always true.
If you want to ask the user again after each printed array, you have to include the question into the loop, but in this case I would prefer a do while loop.

A: Once you print the array. prompt user to input character again so if he/she inputs Y again the print array again like:
while(c=='y'||c=='Y')
{
    int[][] a = new int[ROW][COL];
    randArray(a, ROW, COL, MIN, MAX);
    System.out.println("Do you want to start Again Y/N?");
    c = scan.next().charAt(0);
}

Or if you want your program to run only once then replace while with if.

A: That is happening because you input the value of 'c' only once and keep iterating it, now it goes into infinite loop because the value of 'c' doesn't change at all.
char c =scan.next().charAt(0);
int[][] a;
while(c=='y'||c=='Y')
{

a = new int[ROW][COL];
randArray(a, ROW, COL, MIN, MAX);
c =scan.next().charAt(0);
}

Also, you don't have to redeclare the 2D array each time.

Also, you can use a do-while loop which is more suitable for such cases.

A: two ways
 if(c=='y'||c=='Y')
{
    int[][] a = new int[ROW][COL];
    randArray(a, ROW, COL, MIN, MAX);
}

or
 while(c=='y'||c=='Y')
{
    int[][] a = new int[ROW][COL];
    randArray(a, ROW, COL, MIN, MAX);
    break;
}


text:
Q: return ((char *)&s[i]); What & means in this statement? I'm new to these wanderings, sorry if it's a stupid question. but can they enlighten me what what's doing there?
char    *ft_strchr(char *s, int c)
{
    int i;

    i = 0;
    if (!s)
        return (0);
    if (c == '\0')
        return ((char *)&s[ft_strlen(s)]);  // THIS LINE
    while (s[i] != '\0')
    {
        if (s[i] == (char) c)
            return ((char *)&s[i]); // THIS LINE
        i++;
    }
    return (0);

}

I know this is being performed a cast to that variable but I had not yet come apart with this & there in the middle. and to test this function if I take it out of there... it crash.
Someone help me please???
the function is working properly it finds the first occurrence of c in the string and returns the pointer with its position. I just wanted to understand this application better.

A: Here & is the pointer-to operator.
With e.g. &s[0] you get a pointer to the first element of the array s (which is the same as plain s). To get a pointer to the character at index i it's &s[i].

To explain more you have to remember that strings in C are really arrays of characters, terminated with the null-terminator character '\0'.
Such strings are usually represented by pointers to the first character of the string.
For example:
char hello[] = "Hello world";  // An array of 12 characters, including terminator

When you use hello it decays to a pointer to the first element, i.e. &hello[0]. When you print it:
printf("%s", hello);  // Same as printf("%s", &hello[0])

It will print the whole string: Hello world.
But you can use a pointer to anywhere in the array as the "first" character of the string, to get only a small part of it. For example &hello[6] is a pointer to the 'w' character in the array, basically the start of the second word in the above array. Using that when printing:
printf("%s", &hello[6]);

it will print world.

On a different note, in the code you show, the (char *) cast is not needed.
And please be aware of cargo cult programming, which is a rather bad thing.

A: Regarding why the code is written in this manner/how the function works:
It's a requirement at least from standard C strchr that the null terminator is considered part of the string. Therefore if the user of the function requests the function to search for the null terminator, it must be handled as a special case.
Basically you have 4 possible, different outcomes:

*

*(normal use) if (s[i] == (char) c) return ((char *)&s[i]);
The character was found, return a pointer to the found character position. The cast from int to char is per the requirement of standard C strchr - it behaves like that as well. (And thereby allows to pass stuff like EOF.)

*(normal use) return (0); }
The character was not found, return NULL.

*(special case) if (!s) return (0);
The user passed a null pointer to the function, return NULL. This isn't required by standard C strchr. Since the caller might be perfectly aware they are passing a valid pointer to the function, error checks like this just add extra bloat/branches for nothing. The recommended practice is to place them on the caller side. Naively written library functions are often cluttered with null pointer checks like this.

*(special case) if (c == '\0') return ((char *)&s[ft_strlen(s)]);
The user for some reason decided to search for the null terminator. It will always be found at index strlen(s) in the array, so therefore strlen is used for indexing and then a pointer to that location of the null terminator is returned.
Also note the subtle distinction between the caller passing something explicitly zero ('\0') and the caller passing an int which upon conversion to char becomes zero. In the latter case, the function will return NULL (not found). That's why there's no cast to char at if (c == '\0').

Some notes regarding coding style:

*

*Casting from char* to char* is nonsense.

*Parenthesis at return (0); is pointless.

*For loops are great for readability: for(size_t i=0; s[i] != '\0'; i++).

So it would seem that the function could be rewritten as:
char* ft_strchr (char *s, int c)
{
  if(c == '\0')
    return &s[strlen(s)];

  for(size_t i=0; s[i] != '\0'; i++)
  {
    if(s[i] == (char)c)
    {
      return &s[i];
    }
  }
  return NULL;
}


text:
Q: tsort: -: input contains an odd number of tokens coreutils manual says

tsort reads its input as pairs of strings, separated by blanks,
  indicating a partial ordering. The output is a total ordering that
  corresponds to the given partial ordering. For example
tsort <<EOF
a b c
d
e f
b c d e
EOF

will produce the output
a
b
c
d
e
f

What does "tsort reads its input as pairs of strings" mean, and what requirements does that put on the input?
In the example, does the first line a b c mean nothing itself, but a and b are paired, and so are c and d?
Why does this not work?
$ tsort <<EOF
> a b c
> b c d e
> EOF
tsort: -: input contains an odd number of tokens

A: tsort does a topological sorting of a directed graph.  It gets the graph as pairs of nodes. These constitute a partial ordering of the graph and tsort gives you a total ordering as the result (there may be more than one total ordering of the graph though, see the documentation for the -f and -h options on BSD systems (not available on GNU systems AFAIK)).
Example of a real graph (these are the OpenBSD packages required to build the shells/bash package on an OpenBSD system):
$ make -C /usr/ports/shells/bash build-dir-depends
shells/bash devel/ccache
shells/bash devel/gettext
devel/gettext devel/ccache
devel/gettext archivers/xz
archivers/xz devel/ccache
devel/gettext converters/libiconv
converters/libiconv devel/ccache
devel/gettext converters/libiconv

A pair, A B, in this list means "A is connected to B" (in that order, since it's a directed graph), and in the particular case shown here it means "A depends on B" (converters/libiconv needs to be built before devel/gettext because the latter depends on the former).
tsort takes the the partial ordering of pairs of nodes and returns a list of nodes in a total ordering compatible with that partial ordering:
$ make -C /usr/ports/shells/bash build-dir-depends | tsort -r
devel/ccache
archivers/xz
converters/libiconv
devel/gettext
shells/bash

Here, I've instructed tsort to reverse the resulting ordering (not possible on GNU systems as -r is not an option to GNU tsort), which gives me the order in which the system needs to build the packages while at the same time honouring the dependencies between them (ending up with building the final shells/bash package).
If tsort gets an input line
a b c d

then this is the same as
a b
c d

and as
a b c
d

That is, it always reads the nodes of the graph in pairs, no matter whether these are separated by spaces or newlines.  The issue with your data,
a b c
b c d e

is that it can't be read as a list of pairs as it contains an odd number of nodes.

A: Yes, tsort reads its inputs in pairs separated by any whitespace, including newlines.
So the example from the tsort documentation:
tsort <<EOF
a b c
d
e f
b c d e
EOF

Defines the following pairs of orderings:

*

*a < b

*c < d

*e < f

*b < c

*d < e

And putting these all together, you get to a ordering of a < b < c < d < e < f, which in this case is a total ordering.
A reading of the source code confirms that, tsort uses readtoken() from gnulib with a set of delimiters comprised by space, tab and newline, in other words, any whitespace.
(My initial interpretation of that tsort example, to answer your other question, was that a line with b c d e created three implicit pairs, b < c, c < d and d < e, but that's really not the case, all whitespace is interpreted the same, including newlines, and a single pair is read at a time.)


text:
Q: Density of a set of functions in Schwartz space I have a difficulty doing the following problem:
Let $S(\mathbb{R}^n)$ be the Schwartz space. I need to determine whether the following set of functions $A$:
$$A= \{f\in S(\mathbb{R}^n): \text{supp}(\hat{f}) \text{ is compact and } 0\not\in \text{supp}(\hat{f})\}$$
is dense in $L^p(\mathbb{R}^n)$, where $\hat{f}$ is the Fourier transform of $f$.
I think that the above space is dense in $L^p$ when $p\in (1,\infty)$, but not when $p=1$ or $\infty$, but I don't know how to prove it. Any help is appreciated.

A: I will denote the vector space of Schwartz functions with compactly supported Fourier transforms not containing the origin by $\mathcal{S}_{0}(\mathbb{R}^{n})$.
$\mathcal{S}_{0}(\mathbb{R}^{n})$ is obviously not dense in $L^{\infty}(\mathbb{R}^{n})$ since $\mathcal{S}(\mathbb{R}^{n})$ is not dense in $L^{\infty}(\mathbb{R}^{n})$. Decay at $\infty$ means that $\left\|1-f\right\|_{L^{\infty}}\geq\epsilon$, for any given $f\in\mathcal{S}(\mathbb{R}^{n})$ and $0<\epsilon<1$. $\mathcal{S}_{0}(\mathbb{R}^{n})$ is also not dense in $L^{1}(\mathbb{R}^{n})$, since every $f\in S_{0}$ has mean zero.
However, $\mathcal{S}_{0}$ is dense in $L^{p}(\mathbb{R}^{n})$, for $1< p<\infty$. We will use Littlewood-Paley theory to show this.

Given a Schwartz function $\phi$, we denote the $k^{th}$ Littlewood-Paley projection associated to $\phi$, where $k\in\mathbb{Z}$, by
$$\widehat{\Delta_{k}^{\phi}f}=\widehat{\phi}(\cdot/2^{k})\widehat{f},\quad f\in\mathcal{S}'(\mathbb{R}^{n})$$
If there is no ambiguity, I may omit the $\phi$ and just write $\Delta_{k}$.

Lemma 1. Let $\eta$ be a Schwartz function such that $\widehat{\eta}$ is compactly supported away from the origin. Then for $1<p<\infty$,
  $$\left\|\sum_{j\in\mathbb{Z}}\Delta_{j}^{\eta}f\right\|_{L^{p}}\lesssim_{\eta,p}\left\|f\right\|_{L^{p}},\qquad f\in\mathcal{S}(\mathbb{R}^{n})$$

For a proof, see this post of mine.

Lemma 2. Let $\eta$ and $\zeta$ be Schwartz functions as above. Then for any $j,k\in\mathbb{Z}$,
  $$\sup_{j,k}\left|\Delta_{j}^{\eta}\Delta_{k}^{\zeta}f\right|\lesssim_{\eta,\zeta}\mathcal{M}(\mathcal{M}(f)) \quad \text{a.e.}$$
  where $\mathcal{M}$ denotes the Hardy-Littlewood maximal operator.

Proof. Observe first that by the invariance properties of the Fourier transform,
$$\Delta_{j}^{\eta}\Delta_{k}^{\zeta}f=2^{jn}\eta(2^{j}\cdot)\ast 2^{kn}\zeta(2^{k}\cdot)\ast f$$
Since $\eta$ and $\zeta$ have $L^{1}$ radially decreasing majorants, being Schwartz functions, it follows (see Stein, Singular Integrals and Differentiability Properties of Functions, Theorem 2, pg. 63) ) that
$$\sup_{k} \left|2^{kn}\zeta(2^{k}\cdot)\ast f\right|\lesssim_{\zeta} \mathcal{M}(f) \quad\text{a.e.}$$
and by the same argument,
$$\sup_{j}\left|2^{jn}\eta(2^{j}\cdot)\ast\mathcal{M}(f)\right|\lesssim_{\eta}\mathcal{M}(\mathcal{M}(f))\quad\text{a.e.}$$
$\Box$

Proposition 3. Let $\eta$ be as in the statement of the preceding lemma. Then the operator
  $$f\mapsto \sup_{N\in\mathbb{Z}}\left|\sum_{j<N}\Delta_{j}^{\eta}(f)\right|$$
  is bounded on $L^{p}(\mathbb{R}^{n})$, for $1<p<\infty$.

Proof. Fix $\eta$ and let $\phi$ be as in the statement of the lemma below. I leave it to you to check (it's not hard) that there is a constant $c_{0}>0$, which depends on $\eta$ and $\phi$, such that
$$\left|j-k\right|>c_{0}\Rightarrow\Delta_{j}^{\phi}\Delta_{k}^{\eta}=0$$
So we may write
$$\sum_{k\leq N}\Delta_{k}^{\eta}=\sum_{j\leq N+c_{0}}\Delta_{j}^{\phi}\left(\sum_{k\leq N}\Delta_{k}^{\eta}\right)=\sum_{j\leq N+c_{0}}\Delta_{j}^{\phi}\left(\sum_{k\in\mathbb{Z}}\Delta_{k}^{\eta}\right)-\sum_{j\leq N+c_{0}}\Delta_{j}^{\phi}\left(\sum_{k>N}\Delta_{k}^{\eta}\right)$$
Observe that the second term is a finite sum, for any $N$, with $\lesssim c_{0}^{2}$ terms. So by the preceding lemma,
$$\sup_{j,k}\left|\sum_{j\leq N+c_{0}}\Delta_{j}^{\phi}\left(\sum_{k>N}\Delta_{k}^{\eta}\right)\right|\lesssim_{\phi,\eta}c_{0}^{2}\mathcal{M}(\mathcal{M}(f))\quad\text{a.e.}$$
For the first term, we need the following little lemma. We can define a Schwartz function $\psi$ by
$$\widehat{\psi}(\xi)=1-\sum_{j\geq 1}\widehat{\phi}(2^{-j}\cdot)$$
Observe that $\widehat{\psi}$ is compactly supported in the ball $\left|\xi\right|\leq 2$ and $\equiv 1$ on the ball $\left|\xi\right|\leq 1$. Moreover,
$$\widehat{\psi}(\xi)=\sum_{j\leq 0}\widehat{\phi}(2^{-j}\xi), \forall\xi\neq 0$$
and therefore
$$2^{Nn}\psi(2^{N}\cdot)\ast g=\sum_{j\leq N}\Delta_{j}^{\phi}g,\quad\forall g\in\mathcal{S}(\mathbb{R}^{n})$$
By density and continuity of the convolution, this equality holds for all tempered distributions, in particular $L^{p}$ functions. Since $\psi$ has an $L^{1}$ radially decreasing majorant, the same argument as above yields
$$\sup_{N}\left|\sum_{j\leq N+c_{0}}\Delta_{j}^{\phi}\left(\sum_{k\in\mathbb{Z}}\Delta_{k}^{\eta}f\right)\right|=\sup_{M}\left|\sum_{j\leq M}2^{nM}\psi(2^{M}\cdot)\ast\left(\sum_{k\in\mathbb{Z}}\Delta_{k}^{\eta}f\right)\right|\lesssim_{\phi}\mathcal{M}\left(\sum_{k\in\mathbb{Z}}\Delta_{k}^{\eta}f\right)$$
Since $f\in L^{p}$, $\sum_{k}\Delta_{k}^{\eta}f\in L^{p}$, and the $\mathcal{M}$ is bounded $L^{p}\rightarrow L^{p}$, when $1<p\leq\infty$, we conclude that
\begin{align*}
\left\|\sup_{N}\left|\sum_{k\leq N}\Delta_{k}^{\eta}f\right|\right\|_{L^{p}}&\lesssim_{\phi,\eta}\left\|\mathcal{M}(\mathcal{M}(f))\right\|_{L^{p}}+\left\|\mathcal{M}\left(\sum_{k\in\mathbb{Z}}\Delta_{k}^{\eta}f\right)\right\|_{L^{p}}\\
&\lesssim_{n,p}\left\|f\right\|_{L^{p}}+\left\|\sum_{k}\Delta_{k}^{\eta}f\right\|_{L^{p}}\\
&\lesssim_{\eta,p}\left\|f\right\|_{L^{p}},
\end{align*}
where we use the first lemma to obtain the ultimate inequality.
$\Box$

Lemma 4. Let $\phi\in\mathcal{S}(\mathbb{R}^{n})$ be such that $\text{supp}(\widehat{\phi})\subset\left\{1/2\leq\left|\xi\right|\leq 2\right\}$ and
  $$\sum_{j\in\mathbb{Z}}\widehat{\phi}(\xi/2^{j})=1,\qquad\forall \xi\neq 0$$
  Then for any $f\in\mathcal{S}(\mathbb{R}^{n})$,
  $$\left\|f-\sum_{\left|j\right|\leq N}\Delta_{j}f\right\|_{L^{\infty}}\rightarrow 0, \quad N\rightarrow\infty$$

Proof. By Hausdorff-Young, it suffices to show that
$$\left\|\widehat{f}-\sum_{\left|j\right|\leq N}\widehat{\Delta_{j}f}\right\|_{L^{1}}\rightarrow 0, \quad N\rightarrow\infty$$
But this is trivial, as
\begin{align*}
\widehat{f}(\xi)\left(1-\sum_{\left|j\right|\leq N}\widehat{\phi}(2^{-j}\xi)\right)\rightarrow 0, \quad N\rightarrow \infty
\end{align*}
a.e., and the conclusion follows by dominated convergence.$\Box$
Observe that for any $N\in\mathbb{N}$,
$$\sum_{\left|j\right|\leq N}\Delta_{j}=\sum_{j\leq N}\Delta_{j}-\sum_{j<-N}\Delta_{j}$$
and therefore for any $f\in L^{p}$,
$$\left|\sum_{\left|j\right|\leq N}\Delta_{j}f\right|\leq 2\sup_{N\in\mathbb{Z}}\left|\sum_{j\leq N}\Delta_{j}f\right|$$
which is in $L^{p}$, if $1<p<\infty$. Since the partial sums converge to $f$ uniformly, dominated convergence implies that
$$\left\|f-\sum_{\left|j\right|\leq N}\Delta_{j}f\right\|_{L^{p}}\rightarrow 0,\quad N\rightarrow\infty$$
If $f\in\mathcal{S}(\mathbb{R}^{n})$, then for any $N$, $\sum_{\left|j\right|\leq N}\Delta_{j}f$ is a Schwartz function whose Fourier transform is compactly supported away from the origin. Since Schwartz functions are dense in $L^{p}$, we conclude that $\mathcal{S}_{0}(\mathbb{R}^{n})$ is dense in $L^{p}$, if $1<p<\infty$.


text:
Q: Vue3 failing to build project because can't resolve module I'm using animeJS in my Vue3 project. I'm currently importing it only within the component I'm using it, and it functions fine over local host. However, in the import statement, I do get the warning:
Could not find a declaration file for module 'animejs/lib/anime.es.js'. 'path/to/node_modules/animejs/lib/anime.es.js' implicitly has an 'any' type.
And when I try to run npm run build, I get the following error:
error  in ./src/components/HeroSection.vue?vue&type=script&lang=js

Module not found: Error: Can't resolve 'animejs/lib/anime.es.js' in 'path/to/src/components'

How can I get Vue to recognize the import? Because animeJS is working fine over local host, I was expecting npm run build to compile properly.