text:
Q: Electric potential of spherical water droplet I'm trying to answer the following:

1000 spherical water droplets, each of radius $r$ and each carrying a charge $q$, coalesce to form a single bigger spherical drop. If $v$ is the electric potential of each droplet and $V$ that of bigger drop, then find $\frac{V}{v}$.

It is not mentioned here whether $v$ is potential at a point outside or on the surface of sphere, where should I take the potential?
As water is a good conductor of electricity so water droplet can be regarded as spherical shell.Potential due to spherical shell is * $\frac{kq}{r}$.* where k is constant and q is charge on the shell and r is the distance between the centre of spherical shell and point on which P is  to be calculated and at a point inside or on the surface of shell P is constant and is equal to * $\frac{kq}{r}$.* here r is the radius of shell. So P  depends on the distance between the centre of spherical shell and point on which P is  to be calculated.So in the above problem P on which point should I need to consider.
I am unable to understand what is meant by the potential of water droplet.I know potential at a point due to point charge,system of charge and due to continuous charge distribution.But they are calculated at  point,I mean we calculate potential at point due to different charge distributions.How can we calculate potential of a body!
I want to know what is meant by( " $v$ is the electric potential of each droplet" )this  line of the question.

A: The potential inside a conductive sphere is the same as the one on it's surface.
All you really need is the self capacitance of a sphere, which is 4*pi*e*r.
In other words twice the radius - twice the capacitance.
So if the volume is 1000 times higher what does that mean for the radius?
And if the capacitance of the drop increases by a factor of x while the charge increases by 1000 then what happens to the potential?

A: For any spherical body whether insulating or conducting,  potential at surface and potential outside body have same formula I.e.
$$ V = \frac {kQ}{R} $$
Here $ k $ is coulomb's constant, $ Q $ is total charge ib sphere and $ R $ is radius of sphere.
So the question remains whether you should consider potential at center or at surface.
If you find out the formula for potential at center of an insulated sphere it comes out to be
$$ V = \frac{3kQ}{2R} $$
All the symbols have same meanings as before.
Since in both cases $ V \propto \frac {kQ}{R}$, it will not matter which potential you consider.


text:
Q: Java - how do I check whether a JFrame is closed When a user clicks the red 'X' button of a JFrame, how do I detect whether the JFrame is open or closed? I have a swing timer where the JFrame keeps updating it's label until the user closes down the JFrame.
int delay = 1000;           //milliseconds

final Timer timer = new Timer(delay, null);
timer.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        tempLabel.setVisible(true);
        String tmp = "test";
        tempLabel.setText("Temperature :  " + tmp);
        // timer.stop();
    }
});

timer.start();

A: You have to implement either the WindowStateListener or the WindowListener. If you use the WindowListener it could look like this:
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.Timer;

public class Foo implements WindowListener {

    private Timer timer;

    public static void main(String args[]){
       initTimerComponent();
    }

    private void initTimerComponent() {
      int delay = 1000;           //milliseconds

      timer = new Timer(delay, null);
      timer.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            tempLabel.setVisible(true);
            String tmp = "test";
            tempLabel.setText("Temperature :  " + tmp);
          }
      });

      timer.start();
    }

    @Override
    public void windowOpened(WindowEvent e) { }

    @Override
    public void windowClosing(WindowEvent e) {
       timer.stop();
    }

    @Override
    public void windowClosed(WindowEvent e) { }

    @Override
    public void windowIconified(WindowEvent e) { }

    @Override
    public void windowDeiconified(WindowEvent e) { }

    @Override
    public void windowActivated(WindowEvent e) { }

    @Override
    public void windowDeactivated(WindowEvent e) { }
}

You have to implement them all as WindowListener is an interface and the first concrete class implementing an interface is forced to implement all its abstract methods. But you actually need just one method.
Use this method
public void windowClosing(WindowEvent e) {
   timer.stop();
}

to stop your timer as soon as the window is closing after the user clicked the red X.

A: Answer
addWindowListener(new WindowAdapter() {
        //for closing
        @Override
        public void windowClosing(WindowEvent e) {
            JOptionPane.showMessageDialog(null, "Closing");
        }
        //for closed

        @Override
        public void windowClosed(WindowEvent e) {
        }
    });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Peticiones en quasar framework modo ssr ¿La forma correcta de hacer un api rest con quasar framework modo ssr es en el archivo extension.js? Tengo este código pero cuando lo pruebo me sale not found (es un simple get):
module.exports.extendApp = function ({ app }) {
/*Extend the parts of the express app that youwant to use with development
server too.Example: app.use(), app.get() etc*/
app.get("/aca", function(req, res) {
       res.send("fdfsdfdsff")
    })
}


text:
Q: How to create python logger with record number in the log file I'm trying to create a python logger using the logging module.
How can I create a multiple loggers to multiple files that the first character will be a record number?
using formatter I didn't find how to do that
formatter=logging.Formatter('%(recored_number)s %(asctime)s %(message)s %(name)s')

This is how I wanted the files to be:
First log file:
#1 2019-09-05 08:55:10,000 first logger line for log 1 INFO logger
#2 2019-09-05 08:55:20,000 second logger line for log 1 INFO logger

Second log file:
#1 2019-09-05 08:58:10,000 first logger line for log 2 INFO logger
#2 2019-09-05 08:58:20,000 second logger line for log 2 INFO logger

A: Similar behaviour is achieved in this question
The only difference, is that You have to increment the counter upon processing each log record.
You can add a singleton class RecordCounter for this purpose.
import logging

class RecordCounter:
    _instance = None
    _count = 0

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = object.__new__(cls, *args, **kwargs)
        return cls._instance

    def count(self):
        self._count += 1
        return self._count

class ContextFilter(logging.Filter):
    def filter(self, record):
        record.record_number = RecordCounter().count()
        return True

logging.basicConfig(
    level=logging.DEBUG,
    format='%(record_number)s %(asctime)s %(message)s %(name)s')
logger = logging.getLogger(__name__)
logger.addFilter(ContextFilter())

A: I just found an answer using extra to every log record:
formatter=logging.Formatter('%(recored_number)s %(asctime)s %(message)s %(name)s')

log_1_counter=1
log_2_counter=1
log1.info('first logger line for log 1',extra=
{'record_number':str(log_1_counter)})
log_1_counter+=1

log_1_counter=1
log_2_counter=1
log1.info('first logger line for log 1',extra=
{'record_number':str(log_1_counter)})
log_1_counter+=1
log1.info('second logger line for log 1',extra=
{'record_number':str(log_1_counter)})
log2.info('first logger line for log 2',extra=
{'record_number':str(log_2_counter)})
log_2_counter+=2
log2.info('second logger line for log 2',extra=
{'record_number':str(log_2_counter)})

This is provably not the best solution but it works for me


text:
Q: could not broadcast input array from shape (512,512) into shape (512,512,2) class DataGenerator(Sequence):

    def __getitem__(self, index):

        indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size]

        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        X,y= self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):

        self.indexes = np.arange(len(self.list_IDs))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):

        X = np.empty((self.batch_size, self.dim[0], self.dim[1], self.n_channels))
        y = np.empty((self.batch_size), dtype=int)

        for i, ID in enumerate(list_IDs_temp):
           X[i,] = self.load_dicom_xray(self.image_path[ID])

           y[i] = self.labels[ID]

        return X, keras.utils.to_categorical(y, num_classes=self.n_classes)

    def load_dicom_xray(self, path):
        data = pydicom.read_file(path).pixel_array
        if data.mean() == 0:
            return data
        data = data - np.min(data)
        data = data / np.max(data)
        data = (data * 255).astype(np.uint8)
        return data

training_gen = DataGenerator(index,train_df['Sınıf'],dim=(512,512),n_channels=2,n_classes=10,batch_size=64,shuffle=True,image_path=paths)

Hi, this my code and I'm getting the this error "ValueError: could not broadcast input array from shape (512,512) into shape (512,512,2)". I don't understand why I am getting such an error. I looked on the internet how to fix it, but I couldn't solve it somehow.
Can someone help me here?

/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     65     except Exception as e:  # pylint: disable=broad-except
     66       filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67       raise e.with_traceback(filtered_tb) from None
     68     finally:
     69       del filtered_tb

<ipython-input-13-41198dad25ab> in __data_generation(self, list_IDs_temp)
     39
     40         for i, ID in enumerate(list_IDs_temp):
---> 41            X[i,] = self.load_dicom_xray(self.image_path[ID])

ValueError: could not broadcast input array from shape (512,512) into shape (512,512,2)

A: Pydicom.read_file(path).pixel_array returns an array of size image heigt x image width, it does not include any channels. An array with the same shape is  returned by self.load_dicom_xray. When trying to put this array into array X, which shape includes channels, this obviously gives an error because the shapes don't match.
Therefore, the shape of X should not include the channels, making its definition become the following:
X = np.empty((self.batch_size, self.dim[0], self.dim[1]))


text:
Q: i am getting bean creation exception when i am try to use aspects in bean class when i am try to work with AOP IN application am getting following error can any one help to resolve this issue.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1011)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:957)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:741)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at TestAop.main(TestAop.java:14)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1004)
    ... 12 more
Caused by: java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
    at org.springframework.aop.framework.adapter.DefaultAdvisorAdapterRegistry.<init>(DefaultAdvisorAdapterRegistry.java:49)
    at org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry.<clinit>(GlobalAdvisorAdapterRegistry.java:32)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.<init>(AbstractAutoProxyCreator.java:115)
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.<init>(AbstractAdvisorAutoProxyCreator.java:47)
    at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.<init>(AspectJAwareAdvisorAutoProxyCreator.java:46)
    at org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.<init>(AnnotationAwareAspectJAutoProxyCreator.java:48)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
    ... 14 more
Caused by: java.lang.ClassNotFoundException: org.aopalliance.intercept.MethodInterceptor
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 25 more

Thanks

A: It looks like a very similar problem to this question:
Getting message "The type org.aopalliance.aop.Advice cannot be resolved." in spring java program
Missing AOP Alliance dependency JAR.

A: I was getting same problem resolved by adding jar
com.springsource.org.aopalliance-1.0.0


text:
Q: .Net Core 3.1 HttpClient does not reuse sockets I have the below piece of code which I ran on .Net 4.7.2 and .Net Core but I have got different behavior for each framework
public class Program
{

    private HttpClient Client = new HttpClient();
    public static async Task Main(string[] args)
    {
        Program example = new Program();

        Console.WriteLine("Starting connections");
        int numberofIterations = 10;
        Task<HttpResponseMessage>[] awaitableTasks = new Task<HttpResponseMessage>[numberofIterations];
        for (int i = 0; i < numberofIterations; i++)
        {
            var httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.RequestUri = new Uri("https://example.com");
            httpRequestMessage.Method = new HttpMethod("GET");

            awaitableTasks[i] = example.Client.SendAsync(httpRequestMessage);
            //Console.WriteLine(result.StatusCode);
        }

        Console.WriteLine("Connections done");
        await Task.WhenAll(awaitableTasks);

    }
}

With the .Net Core framework, the network traces shows a separate tcp connection for each request while with the.NEt 4.7.2 framework the sockets get reused.
Network Trace .Net Core

Network Trace .Net 4.7.2

Appreciate your thoughts to understand the differences, to explain this behavior and the best way to overcome this issue.

A: Short Answer, the below modification to the code will force my .net core app to not create more than two sockets and reuse them.
     var socketsHandler = new SocketsHttpHandler
            {
                PooledConnectionLifetime = TimeSpan.FromSeconds(60),
                PooledConnectionIdleTimeout = TimeSpan.FromMinutes(20),
                MaxConnectionsPerServer = 2
            };

     HttpClientHandler handler = new HttpClientHandler() { MaxConnectionsPerServer = 2 };

     var Client = new HttpClient(handler);

Updated Answer

More Details:
The .Net Framework 4.x.x HttpClient implementation is built on top of HttpWebRequest and ServicePoint which can be managed by the ServicePointManager. The ServicePointManager has a default connection limit set to 10 for ASP.NET hosted applications and 2 for all others, and that is why in my above example the 2 sockets were opened and reused as the application were prevented to create more than 2 connections(sockets) per service point.
See the references below for a bit more understanding
https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.defaultconnectionlimit?view=net-6.0#system-net-servicepointmanager-defaultconnectionlimit
https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager?view=net-6.0
https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepoint?view=net-6.0
C# Does Each Instance of HttpClient Get it's Own ServicePoint
In .Net Core, the implementation has been changed multiple times, no longer managed by the ServicePointManager and has no default connection limit. The below article has the full story of the HttpClient Class.
https://www.stevejgordon.co.uk/httpclient-connection-pooling-in-dotnet-core
Thanks to @user700390 and @PanagiotisKanavos and @JeremyLakeman for their help and guidance toward getting the answer to this question.

A: Have you seen this resource:
Using HttpClientFactory without dependency injection

If you are on .NET Core - you should use a single HttpClient directly
and set SocketsHttpHandler.PooledConnectionTimeout here to an
appropriate value.
If you are on .NET Framework - you should use a single HttpClient and
use ServicePoint to configure the similar settings.
The good news for anyone interested in connection management is that
.NET now has reasonable behavior on Linux (as of 2.1 and
SocketsHttpHandler) but it requires configuration.

More detailed information found in https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#alternatives-to-ihttpclientfactory-2

There are alternative ways to solve the preceding problems using a
long-lived SocketsHttpHandler instance.
Create an instance of SocketsHttpHandler when the app starts and use
it for the life of the app. Configure PooledConnectionLifetime to an
appropriate value based on DNS refresh times. Create HttpClient
instances using new HttpClient(handler, disposeHandler: false) as
needed. The preceding approaches solve the resource management
problems that IHttpClientFactory solves in a similar way.
The SocketsHttpHandler shares connections across HttpClient instances.
This sharing prevents socket exhaustion. The SocketsHttpHandler cycles
connections according to PooledConnectionLifetime to avoid stale DNS
problems.

Also possibly relevant (but more focused on DI):
Use IHttpClientFactory to implement resilient HTTP requests
Here are a few relevant excerpts:

The original and well-known HttpClient class can be easily used, but
in some cases, it isn't being properly used by many developers.

Though this class implements IDisposable, declaring and instantiating it
within a using statement is not preferred because when the HttpClient
object gets disposed of, the underlying socket is not immediately
released, which can lead to a socket exhaustion problem. For more
information about this issue, see the blog post You're using
HttpClient wrong and it's destabilizing your software.

....
HttpClient lifetimes

Each time you get an HttpClient object from the IHttpClientFactory, a
new instance is returned. But each HttpClient uses an
HttpMessageHandler that's pooled and reused by the IHttpClientFactory
to reduce resource consumption, as long as the HttpMessageHandler's
lifetime hasn't expired.


text:
Q: Comparing asymptotic order of logarithmic functions If I have two complicated logarithmic functions, say
$\sqrt{\log n}$ and $\log(n(\log n)^3)$, and I have to compare them in terms of their asymptotic order. How do I do that? Do I have to create graphs, or is there another definitive way of doing that?

A: Using elementary properties of the logarithm we find out that
$$\log(n \log^3 n) = \log n + 3\log\log n = O(\log n), $$
whereas $\sqrt{\log n} = o(\log n)$. So $\sqrt{\log n}$ grows more slowly.


text:
Q: Change handler for pytest fixture log_capture Consider an example of test function
from testfixtures import log_capture
import logging

@log_capture(level=logging.ERROR)
def test_function(logs):
    logs.check()

It works fine but how about changing the default handler and loggers?
For changing the loggers I tried passing as an argument names='my_logger' but it throws an error

l = LogCaptureForDecorator(names or None, install=False, **kw)

TypeError: init() got multiple values for keyword argument 'names'


text:
Q: how to post variables to aspx page and push a button with php I just want to fill a form in aspx page via php. is it possible? I tried some Curl codes but didnt work. Thanks for the answers.
$url = 'somepage.aspx';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data['button_name'] = "button_value";
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$output=@curl_exec($ch);
$info = @curl_getinfo($ch);

if(curl_errno($ch)){
  echo 'Curl error: ' . curl_error($ch);
}

curl_close($ch);
echo "output is:'" . $output . "'";
echo "<br>";
echo "info is:";
print_r($info);


text:
Q: My server was used to boot (problem after MDADM raid rebuild) My home-backup server, with 8*2TB disks won't boot anymore. Two disks failed at the same time and i rebuilt the raid 6 array with no problem, but now i can't boot the os. I'm using ubuntu server, 10.10.
I've made screens of the displays to don't copy everything here.
The problem at the boot:
http://img7.imageshack.us/img7/2360/dsc0407nl.jpg
And the Grub config:
http:// img6.imageshack.us/img6/2789/dsc0408ni.jpg
If anyone can try to help, it would be great. It's not a production server, but i would like to have it online. I've tried for the lasts 2 days (just a couple hours a day) but without success.

A: The problem lies with your fstab. When you created the new raid array, it ended up with a new UUID which is what you are using to specify your root filesystem.
It looks like you can get to busybox (the emergency shell), so mount up your root filesystem manually, edit /etc/fstab, and put in the correct UUID (you can get it with blkid /dev/sdX1 or the output from your mdadm output in your screenshot)
Notes:
You will need to remount root as read/write to edit fstab. If you are unfamiliar with the process, its mount -o remount,rw /

A: IT would be a good idea to boot from an Ubuntu liveCD and see if you can mount the partitions on the RADI6 array that way. This way you can then edit your grub and fstab configuration easily (i.e. you don't have to use vi and you can have manual pages or tutorials open :-) )
Also, you need to carefully think about why 2 hard disks failed at once. There could be many more failures already waiting to happen very soon.


text:
Q: Twig accessing variables that need a variable expansion I have the following code in a Twig template:
       {% macro option_display(type) -%}
    {% if server.options_array.options.{{type}}.name is defined %}
        {{server.options_array.options.{{type}}.name}} +${{server.options_array.options.~type~.price}}
    {%else%}
        None
    {% endif %}
{%- endmacro %}

I'm getting this error:

Twig_Error_Syntax: Expected name or number

How should I get it to expand the variable 'type' in that context? I've tried using ~type~ as well (concat).
would be something like $server['options_array']['options'][$type]['name']; in PHP.

A: Just use the bracket notation:
{% macro option_display(type) -%}
    {% if server.options_array.options[type].name is defined %}
        {{ server.options_array.options[type].name }} +${{ server.options_array.options[type].price }}
    {% else %}
        None
    {% endif %}
{%- endmacro %}

You probably want to also check whether server.options_array.options[type] is defined before checking whether server.options_array.options[type].name is defined.
Furthermore, like the documentation of the macro tag says, "as with PHP functions, macros don't have access to the current template variables." So you probably need to pass the server variable to the macro as well.
So here's a more complete example:
{% macro option_display(server, type) -%}
    {% set option = server.options_array.options[type]|default(null) %}
    {% if option.name is defined %}
        {{ option.name }} +${{ option.price }}
    {% else %}
        None
    {% endif %}
{%- endmacro %}

{% from _self import option_display %}

{{ option_display(server, 'foo') }}
{{ option_display(server, 'bar') }}

Notice that I'm using a helper variable option and the default filter. Without the filter, you'd get a Twig_Error_Runtime exception if the server.options_array.options array doesn't have the key you are using. (Whether you get this exception or not depends on the value of the environment option strict_variables.)
See TwigFiddle


text:
Q: How many clopen subsets does the subspace [0,1]∪[3,4] have? Show that the subspace $[0,1]∪[3,4]$ of $\mathbb R$ has at least $4$ clopen subsets. Exactly how many clopen subsets does it have?
Just to clarify, this is the subspace induced by $[0,1]∪[3,4]$ from $\Bbb R$, so the space is just the intersection of all open sets in $\Bbb R$ with $[0,1]∪[3,4].$
Finding $4$ clopen sets is easy. Just form half open intervals with one of the $4$ endpoints, like $[0, 1/2).$ As for how many clopen sets there are, I think the answer is that there are  uncountable many, since the intervals $(0,1)$ and $(3,4)$ have uncountably many elements.

A: Clopen sets are both closed and open.  For example, the empty set and the entire space are always clopen.  Half-open intervals are not necessarily clopen; for example, $[0,1/2)$ is not closed, because it does not contain $1/2$.
One set that is clopen in the subspace topology is $[0,1]$.  Even though it is not open in $\mathbb R$,  it is open in the subspace topology, because it is the intersection of the subspace $[0,1]\cup[3,4]$ and $(-1,2), $ which is open in $\mathbb R$.
I have given you three clopen sets in the subspace topology, and I hope you can find a fourth.

A: $[0,1]$ and $[3,4]$ are connected spaces. So they have no non-trivial clopen subsets. So if $C$ is clopen in $X=[0,1]\cup[3,4]$, then $C \cap [0,1]$ is also clopen in $[0,1]$ and so can only be $\emptyset$ or $[0,1]$, and, likewise, $C \cap [3,4]$ is $\emptyset$ or $[3,4]$. These $2 \times 2$ options give you four options for $C$, and it's easy to check that these are all clopen.


text:
Q: Mysql Stored procedure to create table Plzzz Answer
I want to create a table in a stored procedure
But tabel name is stored in a variable.
Example
 create procedure ABC
(
@tablename. // is a parameter in which table
                                name is stored
)
AS
     BEGIN

Create table @tablename
(
   Colmn one....
   Colmn. two...
    ...............
)

End

but error is shown where
table @tablename
Q ) how can I fix this
I want to set a table name which is stored in a variable @tablename

A: You can't do that this way, You need prepared statements
DROP procedure IF EXISTS `ABC`;

DELIMITER $$

CREATE DEFINER=`root`@`%` PROCEDURE `ABC`(
IN _tablename VARCHAR(50) -- is a parameter in which table
                            --    name is stored
)
BEGIN
SET @sql = CONCAT('
Create table ',_tablename,'
(
   Colmn1 INT,
   Colmn2 INT

);');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
End$$

DELIMITER ;


text:
Q: Using Lambda/Node js how do I make http GET/POST request with username/password and certificates authentication I need to make HTTP Requests on lambda but it include me using some files known as certificates and also username/password. How can i add this.
I have the files
CRT file
aleezah-mtls.pem
KEY file
aleezah-mtls.key
PEM file
ca.pem
A simple get request script that works perfectly is
function getRequest() {
  const url = 'https://reqres.in/api/users';

  return new Promise((resolve, reject) => {
    const req = https.get(url, res => {
      let rawData = '';

      res.on('data', chunk => {
        rawData += chunk;
      });

      res.on('end', () => {
        try {
          resolve(JSON.parse(rawData));
        } catch (err) {
          reject(new Error(err));
        }
      });
    });

    req.on('error', err => {
      reject(new Error(err));
    });
  });
}

How to I make the above function accommodate those certificates and credentials(username/password)
I was able to do this on postman

How do I add these in a script?


text:
Q: Get other record for specific Date I have the following case:
two tables, same structure.
t1 --> oDate datetime, oVal int

t2 --> oDate datetime, oVal int

let say the data are:
t1:
---------------------
oDate         oVal
---------------------
2016-07-30    30
2016-07-31    40
2016-08-01    35
2016-08-02    50

t2:
--------------------
oDate         oVal
---------------------
2016-07-30    56
2016-07-31    34

t2 is empty since '2016-08-01',  both field oDate and oVal.
I want to have the following result:
---------------------------
oDate          oVal1     oVal2
---------------------------
2016-07-30     30        56
2016-07-31     40        34
2016-08-01     35        35
2016-08-02     50        50

because table t2 is empty since '2016-08-01', the the value for oVal2 is copy from oVal1.
How can I do that with SQL Query?
Thank you.

A: Use left join and case as follows:
SELECT T1.oDate, T1.oVal oVal1, CASE WHEN T2.oVal IS NULL THEN T1.oVal ELSE T2.oVal END oVal2
FROM T1
LEFT JOIN T2 ON T1.oDate=T2.oDate

Take a look at demo:
WITH T1 AS
(
    SELECT * FROM (VALUES
    (CONVERT(datetime, '2016-07-30'), 30),
    (CONVERT(datetime, '2016-07-31'), 40),
    (CONVERT(datetime, '2016-08-01'), 35),
    (CONVERT(datetime, '2016-08-02'), 50)) T(oDate, oVal)
), T2 AS
(
    SELECT * FROM (VALUES
    (CONVERT(datetime, '2016-07-30'), 56),
    (CONVERT(datetime, '2016-07-31'), 34)) T(oDate, oVal)
)
SELECT T1.oDate, T1.oVal oVal1, CASE WHEN T2.oVal IS NULL THEN T1.oVal ELSE T2.oVal END oVal2
FROM T1
LEFT JOIN T2 ON T1.oDate=T2.oDate

A: sel
a.odate,a.oval,Coalesce(b.oval,a.oval)
from t1 a
left join
t2 b
on a.odate = b.odate


text:
Q: SQL List that continues on a new column after a set number of rows Im working with a list in SQL, say it gives the result below:

abcde
abcde
abcde
abcde
abcde
abcde
abcde
abcde
abcde
abcde

what I want is the results ilustrated below

abcde  abcde abcde
abcde abcde abcde
abcde abcde abcde
abcde abcde abcde
abcde abcde abcde

that is, each time my list hits a fifth row,I want it to continue on a new column

A: Test data:
declare @t table (v varchar(10))

insert @t values ('abcde')
insert @t values ('abcde')
insert @t values ('abcde')
insert @t values ('abcde')
insert @t values ('abcde')
insert @t values ('abcde')
insert @t values ('abcde')
insert @t values ('abcde')
insert @t values ('abcde')
insert @t values ('abcde')
insert @t values ('abcde')

Expression:
;WITH x AS ( select (row_number() over(order by (select 1)) - 1)%5 [rn], v
FROM @t
)
SELECT REPLACE(STUFF((
SELECT ',' + [v]
FROM x t
WHERE t.rn = x.rn
for xml path(''), type
).value('.', 'varchar(max)'), 1, 1, ''), ',', ' ') [v] FROM x
GROUP BY rn

Output:
abcde abcde abcde
abcde abcde
abcde abcde
abcde abcde
abcde abcde

A: SQL doesn't really give you the tools to do this in an elegant way as it is a data stuart, and this would be considered a formatting problem.  You should address this on your presentation using looping tools and whatnot.
If you absolutely have to do it in SQL, you can use a cursor, though it will still be rather unpleasant and inelegant.


text: Q: Visualforce pages does not trigger session time out. Any thoughts? i have watched this when i leave the visualforce pages in my browser, it does not trigger session time out. But the standard pages does. Is that anything i need to add to my visualforce page or apex code to make this happen? Any thoughts on this?


text:
Q: How do I put two conditions in having in SQL Server? I have to get members that are on five different groups and those groups should have 5 members each

*

*Member (idMember, nameMember)

*Group (idGroup)

*Belongs (idMember, idGroup)

Groups have members, members are in groups, a member can be in as many groups as he wants but a member can't be twice on the same group
I made something like
select idMember, nameMember
from Member m, Group g
where idMember in (select b.idMember
                   from Belongs b)
group by idMember, nameMember
having (select count(*)
        from Belongs b
        where b.idMember = m.idMember)>5
       and
       (select count (*)
        from Belongs b
        where b.idGroup = g.idGroup /*??*/)>5

and there I don't know how to relate belongs with group

A: Approach this type of problem in steps.  The following gets the members that are in five groups:
select b.idMember
from belongs b  -- Note:  `group` is a reserved word so a bad name for a table
group by b.idMember
having count(*) = 5;

The following gets the groups that have five members:
select b.idGroup
from belongs b
group by b.idGroup
having count(*) = 5;

(Interesting symmetry.)
If you want to limit the first query to the groups in the second, then a simple way is to use in:
select b.idMember
from belongs b
where b.groupId in (select g.idGroup
                    from belongs b
                    group by b.idGroup
                    having count(*) = 5
                   )
group by b.idMember
having count(*) = 5;

When you are dealing with complex queries, build them up one step at a time.
Note:  group is a really bad name for a table because it is a reserved word.  And, if you want the table name then use JOIN to join to the members table to get the right name.
EDIT:
You can use join to get columns from member:
select b.idMember, m.name
from belongs b join
     member m
     on b.idMember = m.idMember
where b.groupId in (select g.idGroup
                    from belongs b
                    group by b.idGroup
                    having count(*) = 5
                   )
group by b.idMember, m.name
having count(*) = 5;


text:
Q: C++ CGI nowadays
(source: atmel.com)
Background
I've a 5 years PHP background and in the last month I've been busy finding a way to do web with C++ (even if I know this is childish and stupid, I feel like C++ is the only true programming language and I have this sort of religious faith in it that makes me love it and only it).
My CGI trip
I've come across several blog posts (mostly from 2000-2003), discussions and had some chat discussions here. This is what I've gathered:

*

*PHP is designed for the web while C++ is a generic purpose language.

*PHP is inconsistent and have a lot of hate on the web

*PHP is the most common and supported scripting language out there

*CGI is a pretty old and common technology that was used in the days before PHP (PHP1 was actually a CGI library for C)

*In CGI (vs PHP) we have the problem of the fork-exec execution for each process which kinda slows everything down

*^ this is what FastCGI is there for

*For some common mathematic operations C++ is 200X faster than PHP (because of PHP being an interpreted language)

*Big websites that requires performance doesn't use pure PHP (Facebook use HipHop which is something related to C++ and on Google there are several rumors about it being written in Perl, C++, C or some other language but PHP)

*PHP is faster to learn and to write

*C++ has very bad string manipulation methods

*There are some good (subjective) libraries for C++ CGI like wT (witty).

*Some people just told me to stay away from PHP as far as I could

Real question(s)
Today I have to decide whatever to go with PHP or CGI. And I'm asking you:

*

*Is CGI dead in 2013? (yeah I know it has been asked before)

*Since everybody needs performance and considering that I've time to spend like 1 year to build a solid C++ library for the web and that I don't like easy things, what are the cons in using CGI (or FCGI) nowadays (in comparison to newer techonologies)

*Is there a more efficient way to build websites with C++

*What is the real deal with FastCGI?

*Is FastCGI widely supported?

*Considering a project where I have to build a web tool, web app, iphone app, pc app and mac app all around a single website/server/database, can I actually reuse some code from the C++ website for my applications? (the database interaction for example)?

A: *

*Almost used for only very specific cases

*Don't build one use one: CppCMS*

*Yes, C++ Web Frameworks

*Because it is dead for a long time ago

*It replaces CGI making it VERY efficient

*Yes - all major (and minor) web servers support it

* Full-disclosure: I am the author


text:
Q: HashSet for byte arrays
I need a HashSet for byte arrays in order to check if a given byte array exists in the collection. But it seems like this doesn't work for byte arrays (or perhaps any array).
Here is my test code:
void test()
{
    byte[] b1 = new byte[] { 1, 2, 3 };
    byte[] b2 = new byte[] { 1, 2, 3 };

    HashSet<byte[]> set = new HashSet<byte[]>();
    set.Add(b1);
    set.Add(b2);
    Text = set.Count.ToString();//returns 2 instead of the expected 1.
}

Is there a way to make a HashSet for byte arrays?

A: Construct a HashSet with an IEqualityComparer<byte[]>. You don't want to use an interface here. While byte[] does in fact implement interfaces such as IEnumerable<byte>, IList<byte>, etc., use of them is a bad idea due to the weightiness involved. You don't use the fact that string implements IEnumerable<char> much at all so don't for byte[] either.
public class bytearraycomparer : IEqualityComparer<byte[]> {
    public bool Equals(byte[] a, byte[] b)
    {
        if (a.Length != b.Length) return false;
        for (int i = 0; i < a.Length; i++)
            if (a[i] != b[i]) return false;
        return true;
    }
    public int GetHashCode(byte[] a)
    {
        uint b = 0;
        for (int i = 0; i < a.Length; i++)
            b = ((b << 23) | (b >> 9)) ^ a[i];
        return unchecked((int)b);
    }
}

void test()
{
    byte[] b1 = new byte[] { 1, 2, 3 };
    byte[] b2 = new byte[] { 1, 2, 3 };

    HashSet<byte[]> set = new HashSet<byte[]>(new bytearraycomparer );
    set.Add(b1);
    set.Add(b2);
    Text = set.Count.ToString();
}

https://msdn.microsoft.com/en-us/library/bb359100(v=vs.110).aspx
If you were to use the answers in proposed duplicate question, you would end up with one function call and one array bounds check per byte processed. You don't want that. If expressed in the simplest way like so, the jitter will inline the fetches, and then notice that the bounds checks cannot fail (arrays can't be resized) and omit them. Only one function call for the entire array. Yay.
Lists tend to have only a few elements as compared to a byte array so often the dirt-simple hash function such as foreach (var item in list) hashcode = hashcode * 5 + item.GetHashCode(); if you use that kind of hash function for byte arrays you will have problems. The multiply by a small odd number trick ends up being rather biased too quickly for comfort here. My particular hash function given here is probably not optimal but we have run tests on this family and it performs quite well with three million entries. The multiply-by-odd was getting into trouble too quickly due to possessing numerous collisions that were only two bytes long/different. If you avoid the degenerate numbers this family will have no collisions in two bytes and most of them have no collisions in three bytes.
Considering actual use cases: By far the two most likely things here are byte strings and actual files being checked for sameness. In either case, taking a hash code of the first few bytes is most likely a bad idea. String's hash code uses the whole string, so byte strings should do the same, and most files being duplicated don't have a unique prefix in the first few bytes. For N entries, if you have hash collisions for the square root on N, you might as well have walked the entire array when generating the hash code, neglecting the fact that compares are slower than hashes.


text:
Q: How to make sense of and use error derivatives of backpropagation algorithm I'm following Geoffrey Hinton's Neural Networks Lectures (this one in particular: https://www.youtube.com/watch?v=LOc_y67AzCA), and I'm stumped by the second equation here:

As I understand it, $E = \frac{1}{2} \sum\limits_n (t_n - y_n)^2$ ranges over all neurons in the network, and all neurons above $y_i$ depend on $y_i$. Then shouldn't that mean $\frac{\partial E}{\partial y_i} = \sum\limits_n \frac{\partial E}{\partial z_n} \frac{\partial z_n}{\partial y_i}$ where $n$ ranges over all neurons (above layer $i$)? But the way the second equation in the picture indexes over $j$ makes it look like it's only over the layer $j$ above $y_i$. What about the other neurons in layer $j + 1, j + 2,...$?
UPDATE
Ah I understand now. Thanks to Rabindra for the hint. I think this is how it goes:
At layer $i$, $E$ is considered a function of the $z_j$'s in layer $j$, and the $z_j$'s depend on $y_i$. So by the chain rule we have the second equation:
$$\frac{\partial E}{\partial y_i} = \sum\limits_j \frac{\partial E}{\partial z_j} \frac{\partial z_j}{\partial y_i} = \sum\limits_j w_{ij} \frac{\partial E}{\partial z_j}.$$
But we don't know $\frac{\partial E}{\partial z_j},$ so we use the first equation:
$$\frac{\partial E}{\partial z_j} = \frac{\partial E}{\partial y_j} \frac{d y_j}{d z_j} = y_j (1 - y_j) \frac{\partial E}{\partial y_j}.$$ Here we use the second equation again to go up another layer, and so on. (In practice you'd start from the top and calculate down.)
Along the way down we use the third equation to calculate $\frac{\partial E}{\partial w_{ij}},$ and once we have all of those we use the Delta Rule to calculate the necessary weight changes $\Delta w_{ij} = - \alpha \frac{\partial E}{\partial w_{ij}}.$

A: You are backpropagating the error layer by layer, so before you calculate $\frac{\partial E}{\partial y_i} $, $\frac{\partial E}{\partial y_j}$ must have been calculated. If there is a layer j+1(let's denote as k), then $\frac{\partial E}{\partial y_j} = \sum\limits_k \frac{\partial E}{\partial z_k} \frac{\partial z_k}{\partial y_j}$


text:
Q: SQL Server Manager Studio creates lots of users folder My SQL server setup is bread and butter, but after successfully installed SQL server into my laptop, I notice there are lots of empty folder in the C:\Windows\Users folders. I have a question whether I can move these folder into a specified folder for organisation?
I'm using SQL Server Manager Studio 17


text:
Q: error: expected identifier or '(' before ')' token I have created a function register to register the name from the standard input and put it into a file but it gives me error listed below. please help.
#include<stdio.h>
#include<string.h>
void register(){
    char* reg_names;
    printf("Please enter a username for registration: ");
    scanf("%s", &reg_names);
    printf("\n");
    FILE *fpointer;
    fpointer = fopen("registration.txt", "a+");
    if(fpointer == NULL){
        printf("Error connecting to the database. Check for corruption of the database.");
    }else{
        fprintf(fpointer, "%s\n", name);
        printf("User has been registered as %s", name);
        fclose(fpointer);
    }
}

int main(void){
    int registration;
    char* usr_names;
    char* registered;
    printf("***************** Welcome to The Library Management System ********************\n");
    printf("Enter the value \t1 if you have account or \t2 if you are new and have to register: \t");
    scanf("%d", &registration);
    if(registration == 1){
    printf("test");
    }else{
        register();
    }
    return 0;
}

I am getting
library.c:6:15: error: expected identifier or '(' before ')' token
 void register(){
               ^
library.c: In function 'main':
library.c:32:12: error: expected identifier or '(' before ')' token
   register();

error while running the code. I am a beginner in C trying to get better knowledge of it.

A: register is a keyword in C. You cannot use it as an identifier. Pick a different name for your function.


text:
Q: Quantum energy spectrum of coupled LC harmonic oscillators
*

*For a LC harmonic oscillator, the energy spectrum is evenly spaced by

$$ \Delta E = \hbar \omega \quad \omega = {1\over \sqrt{LC} } $$

*

*For two inductively coupled LC harmonic oscillators with mutual inductance $M$, starting from:

$$\begin{cases}
\quad (i\omega L_1 + {1\over i\omega C_1})I_1 + i\omega M I_2 &= U \\
\quad (i\omega L_2 + {1\over i\omega C_2})I_2 + i\omega M I_1 &= 0
\end{cases} $$

*

*The eigen-energies are (calculated by Mathematica):

$$ \left[
\left[W = \sqrt{\frac{1}{2}} \sqrt{-\frac{L_{1} C_{1} + L_{2} C_{2} - \sqrt{L_{1}^{2} C_{1}^{2} + 4 \, C_{1} M^{2} C_{2} - 2 \, L_{1} C_{1} L_{2} C_{2} + L_{2}^{2} C_{2}^{2}}}{C_{1} M^{2} C_{2} - L_{1} C_{1} L_{2} C_{2}}}
\right],
\left[W = \sqrt{\frac{1}{2}} \sqrt{-\frac{L_{1} C_{1} + L_{2} C_{2} + \sqrt{L_{1}^{2} C_{1}^{2} + 4 \, C_{1} M^{2} C_{2} - 2 \, L_{1} C_{1} L_{2} C_{2} + L_{2}^{2} C_{2}^{2}}}{C_{1} M^{2} C_{2} - L_{1} C_{1} L_{2} C_{2}}}
\right]
\right] $$

*

*In the case where $L_1 = L_2, C_1 = C_2$, the above becomes:

$$ \left[
\left[W = \frac{1}{\sqrt{L_{1} C_{1} + C_{1} M}}\right],
\left[W = \frac{1}{\sqrt{L_{1} C_{1} - C_{1} M}}\right]
\right] $$

*

*The question is: Now that there are two different frequencies (close to each other when $M$ is small), how does the energy spectrum look like?

*I have found this: https://en.wikipedia.org/wiki/Quantum_LC_circuit, but the spectrum is not discussed.

A: When the two (identical) oscillators are decoupled, the energy spectrum is identical to that of a harmonic oscillator albeit each energy level is doubly degenerate. In the case of the coupled oscillator, it can be viewed as this degeneracy being lifted. As the coupling $M$ increases, the splitting is higher.


text:
Q: How do you hyphenate 'luminous' over 2 verse lines, 'lumi-nous' or 'lumin-ous'? Help How do you hyphenate 'luminous' over two verse lines, 'lumi-nous' or 'lumin-ous'? Help.

A: Some dictionaries give hyphenation points in their definitions. Merriam-Webster is one such.

lu·mi·nous

A: In poetry, the sound is even more important than anywhere else.
So the answer to your question depends on how you say it.
If you must hyphenate, for some reason, make the hyphenation represent the sound.

*

*If you end the line with /m/, hyphenate after M

*If you end the line with /n/, hyphenate after N

*In general, hyphenate after the last sound in the line.

I.e, never mind official punctuation rules.
This is poetry, and poetry does what it must.


text:
Q: Async map with multiple insert inside I need to insert inside a MongoDB a list of topics with unique slugs.
This is an example of two topics:
{
  title: "my title"
},
{
  title: "my title"
}

I then need to generate the slugs and insert my topics:
// For each topic perform insert
async.map(topics, function (topic, done) {

    // Generate unique slug
    topic.slug = slug(topic.title).toLowerCase();

    // Look into DB to find topic with same slug
    self._collection.findOne({slug: topic.slug}, function(err, result) {

        // If there is a result then generate an unique slug prepending a shortId to the slug
        if (result) {
            topic.slug = shortId.generate() + "-" + topic.slug;
        }

        // Insert new topic into db
        self._collection.insert(topic, function (err, docs) {
            return done(err, docs[0]);
        });
    });

}, done);

My problem is that being async, the finds are done all together and so they don't find anything because the inserts are performed all together before the finds.
How can I fix this problem without loose the advantage of async operations?

A: All you really seem to need to do is change this to async.mapSeries:
// For each topic perform insert
async.mapSeries(topics, function (topic, done) {

    // Generate unique slug
    topic.slug = slug(topic.title).toLowerCase();

    // Look into DB to find topic with same slug
    self._collection.findOne({slug: topic.slug}, function(err, result) {

        // If there is a result then generate an unique slug prepending a shortId to the slug
        if (result) {
            topic.slug = shortId.generate() + "-" + topic.slug;
        }

        // Insert new topic into db
        self._collection.insert(topic, function (err, docs) {
            return done(err, docs[0]);
        });
    });

}, done);

Acutally, since you are not really altering the array then .eachSeries() is really what you want.
The "series" types in the async library all wait for the current operations or "iteration" in this case to complete, as the callback is then used to signal the end before the other starts.
Of course, these loops make use of events and do not block.


text:
Q: Как отменить (откатить) действие git pull? Подскажите, пожалуйста, решение проблемы:
Есть две ветки: sphere и tags.
Я находился в ветке sphere и случайно сделал git pull origin tags, потом, заметив, что написал неправильно, и не посмотрев, что мердж прошел с конфликтами, сделал git pull origin sphere, и у меня в ветку влились все новые изменения из sphere.
Как мне вернуть код к состоянию до первого pull?

A: git reset --hard
git checkout sphere
git reflog
# Находите хэш коммита, в котором вы находились до первого pull-а.
# Будет что-то вроде "8f05e00 HEAD@{4}: checkout: moving from master to sphere"
# или "4c31200 HEAD@{10}: commit: Awesome feature implemented."
git reset --hard [нужный хэш]

Ну и я бы не рекомендовал использовать "git pull" вообще, потому как эта команда берет на себя слишком много функций и ее поведение неочевидно. Рекомендую разобраться поподробнее, как работает git, и использовать fetch + merge или fetch + rebase. Я лично предпочитаю второе, но это дело вкуса.
A: Если прям на предыдущее состояние:
git reset --hard HEAD@{1}

*

*HEAD@{0} - текущий коммит (рабочий стейт)

*HEAD@{1} - коммит перед текущим коммитом

*HEAD@{N} - N как номер коммита от текущего

--hard сбросит все изменения отслеживаемых файлов! Если исправления всё же нужно сохранить - просто не указывай этот ключ...


text:
Q: Cómo evitar repetir el código estoy modificando un sitio diseñado por otra persona.
Cada ítem del menú está escrito de la siguiente forma

<svg xmlns="http://www.w3.org/2000/svg" height="16" viewBox="0 0 16 16" width="16" class="icon icon-pos-left svg-secondary"><path d="m11 12v-8l-5 4z" fill-rule="evenodd" transform="matrix(-1 0 0 1 17 0)"></path></svg>PAGINA

así repetido por cada ítem del menú.
Quisiera encontrar una forma de mostrar el svg desde un archivo externo, que quede algo asi:

<svg src=...>

Sé que así como lo puse no se puede, pero seguramente hay una alternativa que evite tener que escribir lo mismo 50 veces. Me podrían indicar como? Gracias

A: como estas?
Si entiendo bien tu pregunta, lo que quieres hacer es llamar al svg externamente no ?.
Puedes usar el tag img que ya soporta svg externos.
Por ejemplo:

Entonces en tu ejemplo podes hacer lo siguiente:
Archivo "logo.svg"
<svg xmlns="http://www.w3.org/2000/svg" height="16" viewBox="0 0 16 16" width="16" class="icon icon-pos-left svg-secondary"><path d="m11 12v-8l-5 4z" fill-rule="evenodd" transform="matrix(-1 0 0 1 17 0)"></path></svg>

HTML

    PAGINA

Espero que sea de ayuda. Suerte!

A: En SVG el elemento <use> esta hecho exactamente para algo así.
Primero guardas todos tus iconos en los <defs>de un elemento svg que puedes poner al principio del  o justo antes del cierre, o donde tu quiras. Este elemento svg no es visible así que no estorba en la página.
#root{width:0;height:0;position:absolute;left:-100em}
Importante: los trazados que quieres reutilizar tienen que tener un id, en este caso id="flecha"
En el menú reutilizas, tantas veces como quieras, la flecha de esta manera:
<use xlink:href="#flecha" />
La ventaja de este método es que, si lo necesitas, puedes cambiar el color de los íconos así:
<use xlink:href="#flecha" fill="red" />
o en el css:
.icon{fill:red}
A continuación una demo. Espero que sea lo que necesites:

#root{width:0;height:0;position:absolute;left:-100em}

.icon.icon-pos-left.svg-secondary{fill:red}
<svg id="root" viewBox="0 0 16 16">
<defs>
<path id="flecha" d="m11 12v-8l-5 4z" fill-rule="evenodd" transform="matrix(-1 0 0 1 17 0)"></path>
</defs>
</svg>

  <svg viewBox="0 0 16 16" width="16" class="icon icon-pos-left svg-secondary">
    <use xlink:href="#flecha" />
  </svg>PAGINA


text:
Q: Python Azure function processing blob storage I am trying to make a pipeline using Data Factory In MS Azure of processing data in blob storage and then running a python processing code/algorithm on the data and then sending it to another source.
My question here is, how can I do the same in Azure function apps? Or is there a better way to do it?
Thanks in advance.
Shyam

A: Yes you can do this. I have recently worked on creating a Data Factory (ADF) pipeline that pulls data from blob storage and transfers it to Snowflake. Since it is a good specific example, Snowflake has a number of connectors (including Python) that allow you to link up to it and run queries (which is how you create a stage in order to pull data from Azure). Here is the Snowflake documentation: https://docs.snowflake.net/manuals/user-guide/data-load-azure-create-stage.html.
You can follow the documentation here for creating an Azure Function in Python: https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-first-function-python and then replace whatever code you want to write in order to move your data elsewhere. It should be noted that this currently cannot be done in the portal(though Microsoft mentions that it is something they hope to fix soon). You can do this for any other endpoints that you want to move your data (this is just an example).
In my case, I used an ADF copy activity to pull data from a local file server into blob storage. From there, I created an Azure Function (Python) that connected to Snowflake and just used SnowSQL queries to create a file format, create an azure stage, and copy from the stage into a table (already created). Of course, for Snowflake you can just run all of those queries in a worksheet from the portal, but if you want all of your code stored in ADF (and you use Snowflake), then this is a nice way to do it:

*

*Imports:

import logging
import snowflake.connector
import azure.functions as func
...

*Setup Snowflake connection and execute queries (just insert the code in the "main" function):

con = snowflake.connector.connect(
        user='user',
        password='password',
        account='account'
        )
cs = con.cursor()
try:
    cs.execute("USE WAREHOUSE ...")
    cs.execute("USE DATABASE ...")
    ...
finally:
    cs.close()
con.close()

A: I created a Flask API and called my python code through that. And then put it in Azure as a web app and called the blob.


text:
Q: TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type int32 of argument 'a' - even after casting I get the following error when I try to run the following program
TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type int32 of argument 'a'.
I figured it says that _x is of type int32, but I already cast it using tf.cast
import tensorflow as tf
import numpy as np

x = ([[3, 4, 5], [1, 2, 3], [3, 2, 5]])
y = ([[1, 2, 3, 4, 5, 6, 7, 8], [5, 3, 2, 5, 2, 6, 2, 5], [3, 2, 2, 5, 2, 4, 2, 7]])

tf.cast(x, tf.float32)
tf.cast(y, tf.float32)

train_x = np.asarray([3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167,
    7.042, 10.791, 5.313, 7.997, 5.654, 9.27, 3.1], dtype=float)
train_y = np.asarray([1.7, 2.76, 2.09, 3.19, 1.694, 1.573, 3.366, 2.596, 2.53, 1.221,
    2.827, 3.465, 1.65, 2.904, 2.42, 2.94, 1.3], dtype=float)

learning_rate = 0.01
training_epochs = 100
batch_size = 10

n_hidden_1 = 256  # number of neurons in first hidden layer
n_hidden_2 = 256  # ,,      ...      ,,, second hidden layer
n_input = 50  # Dimension of feature used
n_output = 8  # Number of output neurons

weights = {
    'hidden_1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),  # Randomly initialising weights
    'hidden_2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),  # Randomly initialising weights
    'out': tf.Variable(tf.random_normal([n_hidden_2, n_output]))
}
biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_output]))
}

def mlp(_x, _weights, _biases):  # Feed forward net / Multi layer perceptron
    # Defining layers

    layer_1 = tf.nn.relu(tf.add(tf.matmul(_x, _weights['hidden_1']), _biases['b1']))
    # Choose appropriate activation here
    layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['hidden_2']), _biases['b2']))
    # layer_2 = tf.nn.relu()

    # Linear activation for output
    out_layer = tf.add(tf.matmul(layer_2, _weights['out']), _biases['out'])
    return out_layer

prediction = mlp(x, weights, biases)

A: tf.cast() doesn't do in-place casting. It returns the reference to the cast tensor, which you need to use afterwards; i.e.:
x = tf.cast(x, tf.float32)
y = tf.cast(y, tf.float32)


text:
Q: read csv file from Data folder I use the following to read a csv file into an array from a file in the assets folder
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("Buttons.csv")));

How do i change it so it reads it from the data/data folder

A: Csvreader csvreader = new CSVReader(openFileInput("Buttons.csv"));

By the way: this reads from folder
/data/data/packagename/files


text:
Q: I am getting an error "indexRouter is not defined" I am getting an error "indexRouter is not defined while I am trying to execute the following code. I tried removing the line but again there are other errors. Can anyone tell me why we are using this common variable router for both index.js and user.js?
This is my app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var dishRouter = require('./routes/dishRouter');

const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const Dishes = require('./models/dishes');

const url = 'mongodb://localhost:27017/conFusion';
const connect = mongoose.connect(url,{
  useMongoClient : true
});

connect.then((db) => {
  console.log('Connected correctly to the server');
},(err) => {console.log(err);});

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/index',indexRouter);
app.use('/users',usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

This is my index.js
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

This is my users.js
var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

A: You are using wrong variable.
var index = require('./routes/index');
var users = require('./routes/users');

app.use('/index',indexRouter); // it would be index
app.use('/users',usersRouter); // it would be users

Change from indexRouter to index and userRouter to users.


text:
Q: Is ProtoRPC API the GAE built-in for ajax? Next step: an ajax frontend for a gae/py app.
My app have only basic html version that interacts with the datastore and updates the page everytime. It's ok but now it needs ajax.
I tried some solution: basic javascript, jquery's ajax API and some frameworks.
I think I found everything I was looking for in knockoutjs but this framework interacts with the server throught the json format. This means that i need learn the json library and rewrite all handlers so get and post in json. I can start this task but before I want understood something more about ProtoRPC API.
The docs says that this API is useful also for "Creating structured Ajax backends" and if I understood fine the messages in response is in json format. My questions is:
It's true that ProtoRPC API messages use json?
It will be a problem that all the request/response pass throught ProtoRPC?
Implement a server-side solid ProtoRPC service and use the framework for client-side is a good strategy?

A: ProtoRPC comes with a JSON implementation of its transmission protocol.
You should be able to build your server side logic using ProtoRPC, and issue HTTP request to your API endpoints with messages encoded in JSON, as described on the ProtoRPC overview in the official documentation.
Knockoutjs shouldn't get in the way, since the documentation state that it doesn't force you to use any one particular technique to load or save data

A: I just want to mention a minor point about using ProtoRPC from the client side, since there is not yet a fully developed client there.  The main way to get ProtoRPC to use Json is to just make sure that your request content-type is 'application/json'.  Otherwise, ProtoRPC might try to use the binary protobuf format.
Also, the documentation for ProtoRPC is a wee bit out of date.  The examples show using ProtoRPC with a webapp based request handler.  Instead you should use the newer wsgi based handler, especially if you are working on Python 2.7.
The WSGI handler is built in to ProtoRPC and the source code is here:
http://code.google.com/p/google-protorpc/source/browse/python/protorpc/wsgi/service.py#211
It works very similarly to the webapp handler except it's a little tricker to use it with existing webapp based application.


text:
Q: Sufficient parameters for a probability distribution We know that a Gaussian distribution can be constructed if its first two moments i.e. its mean and covariance are known. Is there any other standard distribution whose construction requires the knowledge of first three or four moments?
I know that given a set of moments, one can construct a probability distribution using the principal of maximum entropy. However, I am looking for any standard distribution having the aforementioned property.

A: The title (original and edited versions) of your question implies you are trying to use data to say from which member
of a particular distribution family the data were sampled. But the use of the word constructed in the question seem to imply you already know some parameter values and have a specific distribution family in mind and are wondering whether they are enough to identify the member of the family.
Finally, your question seems to imply that parameters are always population moments (or estimates are always sample moments?), and they need not be.
I don't think there is any simple rule of the kind you seem to be seeking. So I am going to write a bit about
a few distributions (all univariate, for simplicity). Maybe these examples will answer your real question, and
maybe they will help you formulate it.
Normal: mean $\mu$ and standard deviation $\sigma$ are the parameters, needed to specify a particular member of the family.
Sample mean and sample standard deviation are often used as estimates of these parameters. Both are based on sufficient statistics.
(You can use variance $\sigma^2$ instead of SD.)
Exponential: either mean $\mu$ or $\lambda = 1/\mu$ are
enough to identify which member of the family. The sample mean
estimates $\mu$ and is a sufficient statistic. For this distribution it happens that $\mu = \sigma,$ but the sample SD is not based
on a sufficient statistic.
Beta: there are two shape parameters usually called $\alpha$ and $\beta.$ Both are required to identify a specific member of the
family. Neither is a moment. Sufficient statistics are not moments.
Binomial: parameters are $n$ and $\theta$ (sometimes notation $p$ is used). Usually $n$ is known. The success probability $\theta$ is estimated as $X/n,$ where $X$ is the number of observed successes
and also the sufficient statistic. The population mean is $\mu = n\theta,$ and the population variance is $\sigma^2 = n\theta(1-\theta);$ these are the moments.
Some distribution families require three or even four parameters to
specify the family member. Perhaps look at Wikipedia for Weibull and Pareto (including the 'shifted' and more-advanced expanded families near the ends of the articles.)

A:
Is there any other standard distribution whose construction requires the knowledge of first three or four moments?

This isn't about "any standard distribution" but rather about any standard family of distributions.
You can single out a normal distribution with only the mean if the family of distributions happens to be all normal distributions with one particular number as the variance.
You cannot single out a normal distribution with only the mean and the variance if you're working with a broader class of distributions that includes normal distributions but also some other distributions; for some such families perhaps the mean, variance, and skewness would suffice.
For the uniform distirbution on the interval $[a,b]$ we have
\begin{align}
\text{mean} & = \frac{a+b} 2, \\[10pt]
\text{variance} & = \frac{(a+b)^2}{12}.
\end{align}
Given the mean and variance one can find $a$ and $b$ by a bit of algebra, so this would be such an example. I can image parametrizing this family of distributions by the mean and the range, those being a location parameter and a scale parameter.
The standard Gamma distribution is
$$
\frac 1 {\Gamma(\alpha)} \left( \frac x \beta\right)^{\alpha-1} e^{-x/\beta}\  \frac{dx}\beta\text{ on }(0,\infty).
$$
The parameter $\beta$ is a scale parameter so the variance must be proportional to $\beta^2$ but it also depends on $\alpha$.  We have
\begin{align}
\text{mean} & = \beta\alpha, \\[10pt]
\text{variance} & = \beta^2\alpha.
\end{align}
Given the mean and the variance one can easily find $\alpha$ and $\beta$ and thus single out one distribution.  In particular
$$
\beta = \frac{\text{variance}}{\text{mean}} \text{ and }\alpha = \frac{\text{mean}^2}{\text{variance}}.
$$
(For the family of gamma distributions, all of the cumulants are directly proportional to $\alpha$.)
The family of Pareto distributions is characterized by
$$
\Pr(X>x) = \left(\frac{\kappa}{x}\right)^\alpha \text{ for }x>\kappa.
$$
The two parameters are positive numbers, the "Pareto index" $\alpha$ and the minimum $\kappa$. Here are some exercises:

*

*Show that $\kappa$ is a scale parameter, so that the mean and standard deviation must be proportional to $\kappa$.

*Find the mean and variance as functions of $\kappa$ and $\alpha$.

*For which values of $\alpha$ does the mean exist?

*For which values of $\alpha$ does the variance exist?

*How can one find $\kappa$ and $\alpha$ given the mean and the variance (when those exist)?


text:
Q: Adjustment factor in logistic growth model of facebook-prophet In the paper it emphasizes:
"When the rate k is adjusted, the offset parameter m
must also be adjusted to connect the endpoints of the segments. The correct adjustment
at changepoint j is easily computed as:"
$$\gamma_j = \left(s_j - m - \sum_{l<j}\gamma_l \right)\left(1 - \frac{k + \sum_{l<j} \delta_l}{k + \sum_{l \leq j} \delta_l} \right)$$
My understanding is, adjustment makes sure function is still continuous.
I have 2 questions regarding this model that are not explained in the paper:
How do we come up with the result function is not continuous without the adjustment factor, and how do we compute the adjustment factor?
Link to paper: https://peerj.com/preprints/3190/

A: Asked a friend, for anyone interested here how to come up with adjustment factor


text:
Q: Concatenate javascript files in eclipse? (PureMVC Mootools) I just started to work with the pureMVC tutorials with javascript. In the Objs-Platform, there was some nice ObjsComp.jar, which concatenate all javascript files in my a specific folder into one file.
Now I m working with the Mootools-Platform, which doesn't offer such a script. Any suggesntions or other tools?
Thanks K

A: I use apache ant to do this for my mootools projects, you might find these links helpful to get started.
How do I concatenate JavaScript files into one file?
http://www.julienlecomte.net/blog/2007/09/16/
http://ant.apache.org/
http://ant.apache.org/manual/Tasks/concat.html


text:
Q: How to get first element of list or `None` when list is empty? I can do it like this but there has to be better way:
arr = []
if len(arr) > 0:
    first_or_None = arr[0]
else:
    first_or_None = None

If I just do arr[0] I get IndexError.
Is there something where I can give default argument?

A: I think the example you give is absolutely fine - it is very readable and would not suffer performance issues.
You could use the ternary operator python equivalent, if you really want it to be shorter code:
last_or_none = arr[0] if len(arr) > 0 else None


text:
Q: How do I detect whether or not an input with type=time has any values entered I have a javascript script that's supposed to detect whenever an html form input with type="time" has any value entered.
However, whenever I enter a partial value (for instance, type one number, instead of a full time with AM/PM), it doesn't detect the input as having a value.
In the below example, timeSelector is the input with type="time".
if (timeSelector.value == "") {
    timeSelector.classList.add("empty");
} else {
    timeSelector.classList.remove("empty");
}

Is there any way to detect this type of thing?
To clarify, since apparently I didn't ask my question clearly enough, I need to detect when a time input has something entered, even if that something is an invalid or incomplete input.

A: Well the problem with html5 inputs is they do not give the text in the input if it is not valid. So you can use checkValidity when the user removes focus from the element.

var checkInput = function() {
  var value = this.value
  var isValid = this.checkValidity()
  if (!this.value.length && isValid) {
    console.log('empty');
  } else if (!this.value.length && !isValid) {
    console.log('invalid time entered')
  } else {
    console.log('valid time entered')
  }
}

var input = document.querySelector("input")

input.addEventListener("input", checkInput)
input.addEventListener("blur", checkInput)
<input type="time" />

A: Per the specification on Input Elements with type time ( HTML Spec ) :

The value attribute, if specified and not empty, must have a value that is a valid time string.
If the value of the element is not a valid time string, then set it to the empty string instead.

This means that input and change events don't occur until the entire time field has been filled out. Why? Because nothing really has changed.
You may think that you can circumvent this by using keydown or keyup events, but this is simply not the case.
The value is not changed and is therefore inaccessible until a full string that is capable of being parsed as a time is inside the time input box.
By filling in the below example you can see how the events fire. Notice the lack of value until everything is filled in.

let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });

on("keydown");
on("keyup");
on("change");
on("input");
<input type="time">

The only way to possibly get around the lack of a changing value is to set a default value as below:

let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });

on("change");
<input type="time" value="00:00">

However, with a default value there is a risk that the user will submit a time that isn't something that you'd likely want.
You could write some validation code to take care of this depending on the complexity of your functionality this may be possible.
Overall if this is something you need and the functionality is a bit more complicated than you think you can handle validating yourself, it would be best to either create your own time input interface from other input types, or to use a library or UI kit from a source that has already done the legwork.


text:
Q: java.sql.SQLException: Column Index out of range, 0 < 1. using prepared statement I am using a prepared statement to insert data in a  database. After I have inserted one row normally, the program keeps showing the "column index out of range exception". The number of columns and inserted values equals. The problem might be the cursor not moving to the next line, but in other similar programs this wasn't an issue.
The screenshot of the code is in the link, I cannot post an image.
inserting values using prepared statement


text:
Q: How to update existing documents with Spring Data MongoDB type information after type renames? I am using mongodb with spring and I have some subdocuments that are derived from one base class, mongo uses the '_class' property to find out what is the correct type to convert to, but now I have changed the package name and the collection still has documents with old package name, how can I tell mongo what custom conversions to do ?

A: first of all for next time to decouple your package/class name from _class variable, use: @TypeAlias("name") annotation on your pojo. then _class will have the value "name"
The easiest solution in my opinion is to update your pojo with TypeAlias and update your collection's _class field with it's new value
Read about Type mapping over here: http://docs.spring.io/spring-data/data-mongodb/docs/current/reference/html/#mongo-template.type-mapping


text:
Q: Laravel Convert Word file images to PDF I am tring to convert my word file into pdf

laravel/dompdf

and

phpoffice/phpword

to convert word file into pdf and that is woking fine but it removes all the spaces from the text if word file is not containing any image but in case if word file is containing any media/image it disturb the whole pdf layout and structure this is my code from the controller
\PhpOffice\PhpWord\Settings::setPdfRendererPath($request->file);
    \PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');

    //Load word file
    $Content = \PhpOffice\PhpWord\IOFactory::load($request->file);

    //Save it into PDF
    $PDFWriter = \PhpOffice\PhpWord\IOFactory::createWriter($Content, 'PDF');
    $PDFWriter->save(public_path('uploads/word-to-pdf/'. pathinfo($request->file->getClientOriginalName(), PATHINFO_FILENAME).'.pdf'));

please guide me for this what is the solution for this thanks in advance


text:
Q: How to convert GTFS stop data to a spreadsheet? I'm trying to make a timetable in a spreadsheet by converting the agency's provided GTFS data.
Unfortunately, I have been unable to find any tools for doing this. It seems as though many people use GTFS for maps, not scheduling.
Is there any tool that can make it a spreadsheet, or even HTML?
I looked at BlinkTag's tool but I can't use node-js so it doesn't meet my requirements.


text:
Q: A first countable, countably compact space is sequentially compact Let $(X, \mathcal{T})$ be a space that is both first countable and countably compact (every countable open cover has a finite cover). Show that $X$ is sequentially compact (every sequence has a convergent subsequence.
Related theorems I can use:
(1) X countably compct => X limit point compact
(2) In a first countable space is $x \in cl A \iff \exists (a_n)_n \in A^\mathbb{N}: a_n \to x$
I was able to prove the result if the space is $T_1$, but I don't think we need this hypothesis.

A: Theorem: $X$ is countably compact, then $X$ is strongly limit compact: every countably infinite subset $A$ has an $\omega$-limit point, i.e. a point $x$ such that for every neighbourhood $U$ of $x$ we have $U \cap A$ is infinite.
Proof: suppose not, then every $x \in X$ has a neighbourhood $O_x$ such that $O_x \cap A$ is finite. Now a nice trick: for each finite subset $F$ of $A$ (and there are countably many finite subsets of $A$) define
$$O(F) = \bigcup\{O_x: O_x \cap A = F\}$$
As every $O_x$ is a subset of one of the $O(F)$ (namely that with $F = O_x \cap A$), and the $O_x$ cover $X$, the $O(F)$ form a countable cover for $X$.
Hence there is a finite subcover $O(F_1), \ldots, O(F_N)$ but then there is some $a_0 \in A \setminus \bigcup_{i=1}^N F_i$ (as the $F_i$ are finite subsets of $A$) and this $a_0$ is not covered by any of the $O(F_i)$ for $i \le N$, and this is a contradiction. So $A$ does have an $\omega$-limit point.
BTW the reverse also holds, as you can see here, from which I also borrowed the above argument.
But now the sequential compactness can be proved: let $(x_n)$ be a sequence in $X$. If $A = \{x_n :  n \in \mathbb{N} \}$ is finite, there is a constant (hence convergent) subsequence. So we can assume $A$ is infinite. So $A$ has an $\omega$-limit point $p \in X$, as we saw above.
Let $U_n, n \in \mathbb{N}$ be a countable local base at $p$. Then pick $n_1$ with $x_{n_1} \in U_1 \cap A$. Then having chosen all $x_{n_k} \in (U_1 \cap \ldots U_k) \cap A$, for some $k \ge 1$, where we also have $n_1 < n_2 <\ldots < n_k$, we note that $\cap_{i=1}^{k+1} U_i$ is an open neighbourhood of $p$, so contains infinitely many points of $A$, so in particular we can pick $n_{k+1} > n_k$ such that $x_{n_{k+1}} \in \cap_{i=1}^{k+1} U_i$. Continue this recursion.
It's now standard to check that $x_{n_k} \to p$ is a convergent subsequence of $(x_n)$.
Because I used $\omega$-limit points, there was no need for $T_1$-ness (which you can have with just limit points).

A: Let $(x_n)_{n\in\mathbb N}$ be a sequence of elements of $X$. There are two possibilities:

*

*There is some $x\in X$ such that $x_n=x$ for infinitely many $n$'s. Then it is obvious that $x$ is a limit of a subsequence of the sequence $(x_n)_{n\in\mathbb N}$.

*For every $x\in X$, the equality $x_n=x$ holds for finitely many $n$'s only. In that case, the set $\{x_n\,|\,n\in\mathbb N\}$ is infinite. Since $X$ is limit point compact, there is some $x\in X$ which is a limit of a sequence of elements of $\{x_n\,|\,n\in\mathbb N\}$. Therefore, $x$ is a limit of some subsequence of the sequence $\{x_n\,|\,n\in\mathbb N\}$.


text:
Q: Existence (?) of an analytic $f$ such that $|f(z)|=e^{|z|},~|z|<1.$

Prove or disprove: there is an analytic function $f$ on
    $D=\{z:~|z|<1\}$ such that $|f(z)|=e^{|z|},~z\in D.$

Attempt. I believe that such a function does not exist (besides, a candidate function would be for example $e^z$, but $|e^z|=e^{Rez}\leq e^{|z|}$, although I can not provide  a proof of my claim.
Thanks in advance!

A: If such a $f$ exists, then $f$ non-zero, analytic
$\implies \log f$ analytic
$\implies \log |f| = \Re \log f$ harmonic.
However, $|z|$ isn't harmonic. This means $f$ doesn't exist.

A: As $|f|\geq 1$ on $\mathbb{D}$, we can consider the analytic function $g=\dfrac{1}{f}$ on $\mathbb{D}$. Clearly $g \leq 1$ on $\mathbb{D}$, and $g(0)=1$. By Maximum Modulus Principle, $g$ and therefore $f$ is constant.


text:
Q: Adding a \n newline symbol when using sprintf in PHP I'm trying to export existing data from a MySQL database, into ruby commands I can run with rake db:seed.
Here's my code.
# Generate db:seed data for proveedores.
$proveedores = R::findAll('tbproveedores');
$proveedoresE = R::exportAll($proveedores);

foreach ($proveedoresE as &$p) {

    $line = 'BookSupplier.create(company: "%s", city: "%s", country: "%s", address: "%s", telephone: "%s", contact: "%s", email: "%s", website: "%s"\n';
    $exportedLine = sprintf($line, $p['empresa'], $p['ciudad'], $p['pais'], $p['direccion'], $p['telefono'], $p['personacontacto'], $p['email'], $p['website']);
    var_dump($exportedLine);
    fwrite($seeds, $exportedLine);
    echo "<br />";
}

Notice the \n newline symbol at the end of the $line variable. I read online that that was all that is needed to use a newline.
The output of my code above is (vertabim, a long line):
BookSupplier.create(company: "Pearson", city: "Lima", country: "Peru", address: "Av. Limon", telephone: "4673535421", contact: "Javier", email: "", website: ""\nBookSupplier.create(company: "Project Management Institute - PMI", city: "Pennsylvania", country: "Estados Unidos", address: "Newtown Square, Pennsylvania", telephone: "1", contact: "Limberg Morales", email: "", website: "http://www.pmi.org/"\nBookSupplier.create(company: "UVirtual - Centro de Excelencia", city: "Santa Cruz", country: "Bolivia", address: "Av. Irala 585", telephone: "1", contact: "Limberg Morales", email: "", website: ""\nBookSupplier.create(company: "Ábaco de Rodolfo Depalma", city: "Buenos Aires", country: "Argentina", address: "Viamonte 1336, 4° (C1053 ACB) Buenos Aires", telephone: "5411-43711675", contact: "Limberg Morales", email: "", website: "http://www.abacoeditorial.com.ar/"\nBookSupplier.create(company: "Pablo Lledó - ProjectManagement", city: "Canadá", country: "Estados Unidos", address: "Victoria, BC, Canadá", telephone: "1", contact: "Limberg Morales", email: "", website: ""\n

I'd like each call to be in it's own line, following my newline insertion. Any suggestions on what I'm doing wrong?

A: You need to use double quoted strings, single quoted ones don't expand special character sequences. Check out the manual for more details on PHP strings.

A: The newline symbol \n will only being interpreted when it is enclosed in double quotes: ". Like that:
$line  = '...............';
$line .= "\n";

You should also know about PHP_EOL It is a constant that contains the systems newline delimiter which is different on several operating systems. For example it will be \n on Linux but \r\n on Windows. The most portable code would look like:
$line  = '.....';
$line .= PHP_EOL;

A: The special characters in strings only work when it is enclosed in double quotes ("). See the PHP string documentation for more information.
So either use double quotes, which is a lot of work as you use quite a few double quotes in your string as well. And escape all double quotes inside the string.
Or if you are lazy, concatenate the new line afterwards:
$line = '...';
$line .= "\n";

A: Following on from Josh's answer, you could inject the newline from an interpolated string into printf using %s printf('something%s', "\n") which starts to make more sense in a more complex example - e.g. if the string template is stored in a language variable, or you are doing multiple replacements, or just have to stick with sprintf because your PHB mandates it.
In your case it would be
$line = 'BookSupplier.create(company: "%s", city: "%s", country: "%s", address: "%s", telephone: "%s", contact: "%s", email: "%s", website: "%s"%s';
$exportedLine = sprintf($line, $p['empresa'], $p['ciudad'], $p['pais'], $p['direccion'], $p['telefono'], $p['personacontacto'], $p['email'], $p['website'], "\n");

I've formatted an email header block thus:
$headers = sprintf(
    'From: %1$s%2$sReply-To: %1$s%2$sMIME-Version: 1.0%2$sContent-type: text/html; charset=iso-8859-1%2$s'
    , $EMAIL_FROM, "\r\n");

repeating the use of the \r\n using the 1$ parameter index syntax.
So %2$s becomes the new \r\n, not taking up any extra chars but is harder to read!

A: If you can't (or don't want to) switch to double quotes, you can insert a newline using the ASCII code like so:
> php
<?php printf('line one%cline two', 10);^D
line one
line two
>

The %c lets you insert any ASCII code and 10 is the code for a newline.

A: $line = "BookSupplier.create(company: '%s', city: '%s', country: '%s', address: '%s', telephone: '%s', contact: '%s', email: '%s', website: '%s'\n";

Double quotes are mandatory for \n(or any other whitescpace char like \t) to work.


text:
Q: UPDATE records using REST api I am working on PHP and Salesforce integration and I want to update records using PHP.

I want to update records in Salesforce when clicking on the Button "Follow up".
And also try the below code.
function update_account($id, $followup, $instance_url, $access_token) {
$url = "$instance_url/services/data/v20.0/sobjects/Contact/$id";

$content = json_encode(array("shivendra__FollowUp__c" => $followup));
echo $content;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Authorization: OAuth $access_token",
            "Content-type: application/json"));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 204 ) {
    die("Error: call to URL $url failed with status $status, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
echo "update_contact function";
echo "HTTP status $status updating Contact

";

curl_close($curl);
}

But getting an error:

{"shivendra__FollowUp__c":null}
[{"errorCode":"METHOD_NOT_ALLOWED","message":"HTTP Method 'PATCH' not allowed. Allowed are HEAD,GET,POST"}]
Error: call to URL https://shivendra-dev-ed.my.salesforce.com/services/data/v20.0/sobjects/Contact/ failed with status 405, curl_error , curl_errno 0

A: Try the post method with cURL, similar to this:
curl_setopt($ch, CURLOPT_POST, 1);


text:
Q: Bootstrap column stacking Is is possible to force a bootstrap column to force all columns to make use of the white space above?
Example:
http://jsfiddle.net/tkrhkz0d/

A
A

B

C
C
C
C
C
C

D

E
E

F

G
G

H

I
I

J

I want all whitespace to be filled without knowing the contents of the columns

A: just change background from col-sm-6 to row!
.row {
  background: #DDDDDD;
}

EDIT
in this case use bootstrap row for each couple of cols
jsfiddle-link


text:
Q: Pass long string through exec When I try to pass a short string it passes, and when I try to pass a longer string It doesn't pass.
Here's the code I'm using :
index.php
function bgExec($cmd) {
 if(substr(php_uname(), 0, 7) == "Windows"){
  pclose(popen("start /B ". $cmd, "r"));
 }else {
  exec($cmd . " > /dev/null &");
 }
}

$string = "some long string";

bgExec("php -q process.php $string");

process.php
file_put_contents('file.txt', print_r($argv[1], true));

Is there any solution to pass a longer string ?

A: For long data use pipe, or give only path to the input data.


text:
Q: How i can find out that URL is active or inactive I have One issue i am showing information of web site using web view. Before showing it i want to know is it url link active or not if it is then i will show it in webView otherwise i will show alert message to User. Can anyone help to me. The url is like www.domainname.com:8150/imagename.jpg will it work or not. In this i want to know Will this link active or not.
      Thanks in advance.

A: *

*Check whether your internet connection is alive with well known host. For example you can use the following request:

NSMutableURLRequest req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.google.com"]];
NSHTTPURLResponse urlResponse = nil;
NSError *error = [[[NSError alloc] init] autorelease];
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&urlResponse error:&error];
[req release];

*Then do the same for your url.


text:
Q: Jogar dados para uma box Necessito pegar os dados de um input e passar a uma box!
 Tenho um cod que pega os dados de uma combo para jogar em uma box!
cod:
function move(Origem, Destino)
{
    var opt = document.createElement("option");

    for(i = 0; i < Origem.options.length; i++)
    {
        if (Origem.options[i].selected && Origem.options[i].value != "")
        {
            if(w_seq_qtde[Origem.options[i].value]==0)
                alert("sem periférico no estoque!");
            else
            {
                document.getElementById("cb_MenuDestino").options.add(opt);
                opt.text = Origem.options[i].text;
                opt.value = Origem.options[i].value;
                w_seq_qtde[Origem.options[i].value]--;
            }
        }
    }
}

input:
<input type="text" name="tx_MenuOrigem" value="">

button :
<input type="button" onClick="move(this.form.tx_MenuOrigem,this.form.cb_MenuDestino)" value="+++">

select:
<select multiple size="7" name="cb_MenuDestino" style="width:300"></select>

Nesse caso quando se seleciona o item na combo e aperta em um button para add ele joga na box! Mas quero pegar os dados em um input e jogar dentro da box! Se possivel tem como ser mais ou menos parecido para melhor entendimento?! Obrigado a quem ajudar!

A: function move(input, Destino)
{
 var opt = document.createElement("option");
 var valor = input.value;
 if(valor=="")
 return;

  if(valor==0)
  {
    alert("sem periférico no estoque!");
   return;
  }

  opt.text = valor ;
  opt.value = valor ;
  Destino.options.add(opt);

 }

A: Verificar se o valor já existe
function JaExiste(Destino, valor)
{

for(i = 0; i < Destino.options.length; i++)
    {
        if (Destino.options[i].value == valor)
                   return true;
     }
return false;
}

Adicionar o valor no select
function move(input, Destino)
{
//Obtém o valor digitado
 var valor = input.value;

 //retorna se não houver valor ou se o valor já existir no destino

 if(valor==""|| JaExiste(Destino,valor)) return;

//Mensagem do explo caso o valor seja 0
  if(valor==0)
  {
    alert("sem periférico no estoque!");
   return;
  }
  var opt = document.createElement("option");
  opt.text = valor ;
  opt.value = valor ;
  Destino.options.add(opt);
 }


text:
Q: magento 2 add unique key on multiple columns using installschema Here i am trying to create unique key using installSchema . Array of
column names is defined here on which columns combinedly i want to
apply unique key
$arrayOfColumnsName = array('column1', 'column2');

here defined the addIndex method for creating the unique key
->addIndex(
            $installer->getIdxName(
                $installer->getTable('table_name'),
                $arrayOfColumnsName,
               \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
            ),
            $arrayOfColumnsName,
            ['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
        )

This creates unique key for only first column instead of both columns, needs help for the same

A: Try This :-
->addIndex(
            $installer->getIdxName(
                $installer->getTable('table_name'),
                ['column1','column2'],
               \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
            ),
           ['column1','column2'],
            ['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
        )

A: Change the format of your $arrayOfColumnsName data like this:
$arrayOfColumnsName = ['column1', 'column2']


text:
Q: Ubuntu - PostgreSQL failing with no error message I've installed PostgreSQL 9.0 on Ubuntu 10.04 using this guide.
However, when I try to start the service, I get this back, with no error or message shown.
root@srv1:/etc/init.d# ./postgresql start
* Starting PostgreSQL 9.0 database server
* The     PostgreSQL server failed to start. Please check the log output.
                                                                     [fail]

I don't know where the log file is to see this error. It's definitely not in /var/log/* or /var/log/postgresql

A: The issue was to do with not having write access to the log file for the 'postgres' user.
IMO, the startup script should echo an error to the screen instead of telling you to check the log that it can't even write to.


text:
Q: Installed Ubuntu with Windows 7 I had Windows 7 and installed Ubuntu using the Windows installer. Now when I restart the PC, it directly boots to Ubuntu. What happened to my Windows 7 and how I can make it dual boot?

A: I have installed Ubuntu from a DVD. During installation process I was asked about options to install as only simple system or dual system or other. So make sure what you've selected before installation, it's decisively the right point.

A: At the start of Ubuntu installation, when Preparing to Install window appears, it presents you with following options

*

*Install Ubuntu alongside your other systems (e.g. alongside Windows). You shold have selected this option in your case if you want to create a dual boot system.

*Erase disk and install Ubuntu (Install Ubuntu over your entire hard drive). If you have selected this option by any chance, Ubuntu has formatted and overwritten your Windows partition. You may have to reinstall Windows and then Ubuntu after that to get back to a dual boot system once again.

*Something else (use manual options for installations, like partitioning hard drive and then install).

A: There is a software on ubuntu called Gparted that lets you see what's on your hard drive. To access it, go to Terminal and type
sudo gparted

And enter your root/ubuntu password.
If it says you don't have it, download it with
sudo apt-get install gparted

and then try the first command again. This software can cause loss of data if you use it without knowing it well enough, so read the warnings carefully if you plan on changing something. For now, you don't need to change anything.
Look for a partition with data type "NTFS" or "ntfs" : it's the windows part of your hard drive. The Linux part is generally "ext4" for home use. Two cases :
1) If you have only an "EFI" partition and "ext4" partition, maybe a "swap" one too, and NO "NTFS", congratulations, you've deleted Windows. ^^" If you had anything worthwhile on your disk, I suggest you bring your hard drive to a data recovery center and use your computer as little as possible until then, as it will make data recovery harder. This will remind you to backup your data before any OS manipulations...
Or if you don't care about what was on there and just want your dual-boot : reinstall windows from scratch while erasing everything on your disk in the Windows installer menu (by booting with a Windows CD or Live USB of the Windows distribution of your choice). Then once Windows is installed, pick up your Ubuntu Live USB and this time, pick the "Install Ubuntu alongside Windows" option. From then on, your computer should recognize both.
2) If you do have an NTFS partition, or had to follow part 1) and your windows is still unrecognized, then windows is quite probably still there, it's just not recognized by your Linux-centric computer.
The key to fixing this is a software called GRUB (or GRUB2) that allows your computer to pick an OS when it boots. It's basically a black screen on startup with the choice of "ubuntu", "memtest", "setup", and "windows".
To work, Grub needs a) to be installed, b) information about which OS exists in the machine.
sudo apt-get install grub

will install grub, you might already have it.
sudo update-grub

will have grub check the hard drive for the OSs present. It will then correct the grub boot menu (or have it appear for the first time, if your computer used to boot to Linux automatically).
Normally that should fix your problem. On startup, you should be able to pick between Windows and Ubuntu.


text:
Q: Best way to write InputStream to RandomAccessFile Lets say I have a method
private int writeToFile(RandomAccessFile file, InputStream input) {
    int numberOfBytesWritten;
    //for now I have this :
    int data = in.read();
    while(data != -1) {
            //do something with data...
            numberOfBytesWritten += 1;
            f.write(data);
            data = in.read();
     }

    return numberOfBytesWritten;
}

I guess this is not the best way to write data to RAF. How can I do it better?

A: The canonical way:
byte[] buffer = new byte[8192]; // or more if you like
int count;
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
    numberOfBytesWritten += count;
}
out.close();
in.close();