text:
Q: DispatcherTimer ticking not working when started in ThreadPool.QueueUserWorkItem() method I've created a TimerManager class for my WPF application.
This class handles the start and stop the dispatcher timer.
Here is the class:
public static class TimerManager
{
    static DispatcherTimer disTimer;
    static Model m = Model.GetInstance();
    static TimerManager()
    {
        disTimer = new DispatcherTimer();
        disTimer.Tick += disTimer_tick;
        disTimer.Interval = new TimeSpan(0, 0, 1);
    }

    public static void StartTimer()
    {
        disTimer.Start();

    }

    public static void StopTimer()
    {
        disTimer.Stop();
    }

    private static void disTimer_tick(object sender, EventArgs e)
    {
        m.Tick++;
    }
}

And I've created a Model class that represents the ticking in the UI.
(Binding in MainWindow.xaml -> xy textbox text field "{Binding Tick}").
class Model : INotifyPropertyChanged
{
    private Model()
    {

    }

    static Model instance;
    public static Model GetInstance()
    {
        if (instance == null)
        {
            instance = new Model();
        }
        return instance;
    }

    int tick;

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnNotifyPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, e);
        }
    }

    public int Tick
    {
        get
        {
            return tick;
        }

        set
        {
            tick = value;
            OnNotifyPropertyChanged();
        }
    }
}

And here is the MainWindow class:
Model m;
public MainWindow()
{
    InitializeComponent();
    m = Model.GetInstance();
    this.DataContext = m;
}

private void startButton_Click(object sender, RoutedEventArgs e)
{
    ThreadPool.QueueUserWorkItem(o =>
    {
        TimerManager.StartTimer();
    });
    //TimerManager.StartTimer();
}

private void stopButton_Click(object sender, RoutedEventArgs e)
{
    TimerManager.StopTimer();
}

When I click the start button I use the ThreadPool.QueueUserWorkItem() method. In that method, I start the timer but the timer tick is not run at every one second.
When I don't use ThreadPool this works. But this solution is not good for me; ThreadPool is important for me because I use an HTTP web server (in local).
My question is: why is the ticking not working if I use ThreadPool?

A: The DispatcherTimer object has thread affinity. That is, it is tied to a specific thread. In particular, it is designed specifically to raise its Tick event in the thread in which it was created, using the Dispatcher for that thread.
Your ThreadManager class's static constructor will be called when the type is first used. In your non-working example, this occurs in the queued work item method, causing the static constructor to be executed in the thread pool thread used to execute that work item method. This in turn causes the DispatcherTimer object you create to be owned by that thread, and to have its Tick event raised in that thread by the Dispatcher for that thread.
Except, thread pool threads don't have Dispatchers. So there's no Dispatcher there to raise the Tick event for the DispatcherTimer object. Even if there was, without a call to Application.Run() to have the dispatcher loop executed, the Dispatcher wouldn't actually get to dispatch anything, including the Tick event.
What you need is to make sure that when you create the DispatcherTimer object, the code that creates that object is executed in the dispatcher thread, which is your main UI thread.
There are a couple of ways to do that. IMHO, the best way is to make your ThreadManager class not a static class and to create an instance of it in your MainWindow constructor. For example:
class TimerManager
{
    DispatcherTimer disTimer;
    Model m = Model.GetInstance();

    public TimerManager()
    {
        disTimer = new DispatcherTimer();
        disTimer.Tick += disTimer_tick;
        disTimer.Interval = new TimeSpan(0, 0, 1);
    }

    public void StartTimer()
    {
        disTimer.Start();
    }

    public void StopTimer()
    {
        disTimer.Stop();
    }

    private void disTimer_tick(object sender, EventArgs e)
    {
        m.Tick++;
    }
}

and:
public partial class MainWindow : Window
{
    TimerManager _timerManager = new TimerManager();

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = Model.GetInstance();
    }

    private void startButton_Click(object sender, RoutedEventArgs e)
    {
        ThreadPool.QueueUserWorkItem(o =>
        {
            _timerManager.StartTimer();
        });
    }

    private void stopButton_Click(object sender, RoutedEventArgs e)
    {
        _timerManager.StopTimer();
    }
}

Since you know your MainWindow object has to be created in the dispatcher thread, and you know that non-static field initialization happens at the same time the constructor is called, in that same dispatcher thread, the above ensures that your TimerManager object is created in the dispatcher thread.
This gives you complete control over the lifetime of the TimerManager object, particularly when it's created but of course also when it can be discarded. Given the nature of the DispatcherTimer object itself, it's my opinion that this is better than maintaining a statically-held instance.
This approach also gives you the option of having a manager object for each dispatcher thread (in rare cases, a program might have more than one…you should try very hard to avoid getting into that situation, but it can be useful for types to at least be compatible with such a situation).
That said, if you really want to keep the static implementation, you can do that by providing a method that can be called explicitly when you want to initialize the class, so you can make sure that the initialization happens in the right thread:
static class TimerManager
{
    static DispatcherTimer disTimer;
    static Model m = Model.GetInstance();

    public static void Initialize()
    {
        disTimer = new DispatcherTimer();
        disTimer.Tick += disTimer_tick;
        disTimer.Interval = new TimeSpan(0, 0, 1);
    }

    public static void StartTimer()
    {
        disTimer.Start();
    }

    public static void StopTimer()
    {
        disTimer.Stop();
    }

    private static void disTimer_tick(object sender, EventArgs e)
    {
        m.Tick++;
    }
}

Then in your MainWindow class:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = Model.GetInstance();
        StaticTimerManager.Initialize();
    }

    private void startButton_Click(object sender, RoutedEventArgs e)
    {
        ThreadPool.QueueUserWorkItem(o =>
        {
            StaticTimerManager.StartTimer();
        });
    }

    private void stopButton_Click(object sender, RoutedEventArgs e)
    {
        StaticTimerManager.StopTimer();
    }
}

All you need to do here is make sure you call the Initialize() method from the main UI thread where you actually have a running dispatcher, before you attempt to call either of the other two static methods in the class.
This approach could also be made to work with multiple threads (i.e. if you have more than one dispatcher thread), but it would be trickier, especially if you want to be able to call the StartTimer() method from a different thread that actually owns the timer object. I'd recommend against the static class approach if you really did wind up in that situation.


text:
Q: preg_match to Javascript function $value = 077283331111333;
if( ! preg_match(/^[0-9]{1,20}+$/, $value))
{
    echo $value . " is not a number that has between 1,20 digits";
}

I'm trying to turn this Php conditional statement into a Javascript one.
This is what I have, currently not working.
var value = 077283331111333;
var regex = '/^[0-9]{1,20}+$/';
var match = regex.test(value);
if ( ! match) {
    console.log(value + 'is not a number that has between 1,20 digits');
}

And this is the error I'm getting.
Object /^[1,0]{1}+$//^[0-9]{1,20}+$/ has no method 'test'
Any ideas? Additionally this within a node.js environment.

A: That method is undefined because that's not a regex but a string.
You need to drop the quotes in order to create a RegExp object in javascript:
var regex = /^[1,0]{1}+$//^[0-9]{1,20}+$/;

Anyway I don't think that's a valid regex (because of the double slashes) you might wanna check for typos there...
A regex to check for a number between 1 and 20 digits is just:
var regex = /^\d{1,20}$/

A: try to remove single quotes from your regex
var value = 077283331111333;
var regex = /^[1,0]{1}+$//^[0-9]{1,20}+$/;
var match = regex.test(value);
if ( ! match) {
    console.log(value + 'is not a number that has between 1,20 digits');
}

A: try remove the quotes from regex variable.

A: if ( /regex/.match( value ) ) {
  //do stuff
}

A: That's one odd regexp... why don't you use
/^\d{1,20}$/.test(value)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to open a new window in YII framework 2.0 I want to click on a link inside Grid View, which should open a new window in a new tab.
I don't want CHtml::Link answers, since it is YII 1.1, I am using YII 2.0.
THE BELOW CODE IS INSIDE GRID VIEW.
['attribute'=>'EMPLOYEEID',
'label'=>'EMPLOYEEID',
'value'=> Html::a('E_ID', '?r=tb-run-engine/index', ['title' => 'Go']),
                ],

I didnt get any value for EMPLOYEEID instead am getting [notset] as value in Grid view.and am not getting hyperlink also.Am new to yii 2.0 can any one help me to figure out this problem??

A: To open link in new tab/window you have to set attribute target="_blank" for this link:
some text

So in Yii2 with Html helper in view file you can write:
<?= Html::a("some text","some_url",['target'=>'_blank']) ?>

And in yii2 grid you can show raw column:
[
  'attribute'=>'name', //your model attribute
  'format'=>'raw',
  'value'=>function ($model, $index, $widget){
     return Html::a(
           $model->name,                     //link text
           ['page/update','id'=>$model->id], //link url to some route
           [                                 // link options
             'title'=>'Go!',
             'target'=>'_blank'
           ]
     );
  }
],

A: add this to your Html:a options ['target' => '_blank', 'data-pjax' => 0] or turn off pjax in grid

A: here is my grid view:
<?= GridView::widget([
                'dataProvider' => TbRunEngineSearch::$dataprovider_static,
                'filterModel' => $searchModel,
                'id'=>'searchgrid',
                'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

                 [
                'attribute'=>'run_id',
                        'label'=>'field level details', //your model attribute
                'format'=>'raw',
                'value'=>function ($model, $index, $widget){
                    return Html::a(
                            $model->run_id,                     //link text
                            ['page/update','id'=>$model->run_id], //link url to some route
                            [                                 // link options
                                    'title'=>'Go!',
                                    'target'=>'_blank'
                            ]
                    );
                }
                ],

                ['attribute'=>'run_id',
                'value'=>'product_name',
                'label'=>'Product Name'],

                ['attribute'=>'run_id',
                'value'=>'module_name',
                'label'=>'Module Name'],

                ['attribute'=>'run_id',
                'value'=>'operation_name',
                'label'=>'Operation Name'],

                ['attribute'=>'initiated_at',
                'value'=>'initiated_at',
                'label'=>'Start Time'],

                ['attribute'=>'finished_at',
                'value'=>'finished_at',
                'label'=>'End time'],

                ['attribute'=>'run_id',
                'value'=>'pass_percent',
                'label'=>'Pass %'],

                ['attribute'=>'run_id',
                'value'=>'fail_percent',
                'label'=>'Fail %'],

                ['attribute'=>'run_id',
                'value'=>'operations_num',
                'label'=>'Operations #'],

                ['attribute'=>'build_num_primary',
                'value'=>'build_num_primary',
                'label'=>'Build # Pri/Sec'],

                'run_status',
                'source',

                ['attribute'=>'env_primary',
                'value'=>'env_primary',
                'label'=>'ENV # Pri/Sec '],

                ['attribute'=>'instance_primary',
                'value'=>'instance_primary',
                'label'=>'INSTANCE # Pri/Sec '],

    ],
                ]);
        ?>


text:
Q: Error on export to PDF with Maatwebsite I want to export to PDF in Laravel 5.5 with maatwebsite/laravel-excel. When I try to export to excel it works. But when I export to PDF I get this error:

Unable to load PDF Rendering library

I've tried to change the entry in composer.json from "dompdf/dompdf": "^0.8.1" to "dompdf/dompdf": "0.6.2" without success.

A: Laravel-excel is deprecated.
You should use snappy https://github.com/barryvdh/laravel-snappy with wkhtmltopdf https://github.com/wkhtmltopdf/wkhtmltopdf


text:
Q: How to restore unity after gnome-shell installation? I Just installed gnome-shell in my 12.04 box and, unity disappears from the login screen.
This is what I've done trying to fix:

*

*#Exec: unity --reset`

*Purge and install: indicator-session

*Set Display full username to true in gsettings
`

A: Try this:
Just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command below.
sudo apt-get install --reinstall ubuntu-desktop

If you have compizConfig Setting Manager installed then try
ccsm

A: If you were using compizconfig-settings-manager and messed up your desktop. Only thing that worked successfully for me, was repair it with the same program..

*

*Ctrl +Alt+T  (To open terminal)

*ccsm (To start program.)

*Repair what you have messed up.

All other stuff what you can find online, such as
sudo apt-get install --reinstall ubuntu-desktop

haven't give any result. It was just waste of time.

A: Just open CCSM, scroll down to Desktop, click on Ubuntu Unity Plugin, make sure Enable Unity Plugin is checked in the box on the left side panel of the CCSM window.

That fixed mine. No reboot required.

A: Re-Installed ubuntu, the name is missing just because I disable guest-account.


text:
Q: ASP.Net C# JavaScript Popup Window Help I've looked all over the place and had very little luck.
try{
FooError();
}
catch (Exception Exc){
ClientScript.RegisterClientScriptBlock(this.GetType(), "errorPop",
@"<script language='javascript'> alert(" + Exc.Message + "); </script>");
return;
}

I keep getting a javascript error saying "Expected a ')'.". I've tried the script with a @ at the start (like it is), without a @ at the start, with and without a semicolon at the end. I've tried
ClientScript.RegisterClientScriptBlock(this.GetType(), "errorPop",
@"<script type=\"text/javascript\"> alert(" + Exc.Message + "); </script>");

I've been able to get this to work with a static value in the alert function
ClientScript.RegisterClientScriptBlock(this.GetType(), "errorPop",
@"<script language='javascript'> alert('Foo'); </script>");

But that's not what I need.
What am I doing wrong here? Is there a better way?
I guess what I mean to ask is how do you use a C# string variable in a JavaScript alert box, if it's even possible.
Thanks.
This is my first question I hope I did it right -.-;

A: Sounds like there may be some characters in your Exc.Message that break the javascript string.  Look at your source to see what's generated, but I'd expect to find something like this:
<script language='javascript'> alert("Error "this" happened"); </script>

Notice how the "this" would break that.  So you'd need to do something like
Exc.Message.Replace("\"", "'");

A: add quotes around the Exc.Message -- like you did with Foo.
    ClientScript.RegisterClientScriptBlock(this.GetType(), "errorPop",
@"<script type=\"text/javascript\"> alert('" + Exc.Message + "'); </script>");

or
 ClientScript.RegisterClientScriptBlock(this.GetType(), "errorPop",
    @"<script type=\"text/javascript\"> alert(\"" + Exc.Message + "\"); </script>");

Because your output would look like this
alert(whatever the message is);


text:
Q: Adding padding for the top axis of plt.matshow() not working I am trying to add padding for the top axis of plt.matshow()
I have tried to use various different method but still, I end up with essentially this result:

Code tried:
pca_10 = PCA(10)  # project from 61 to 10 dimensions
projected_10 = pca_10.fit_transform(df)
print(df.shape)
print(projected_10.shape)

plt.figure(figsize=(20,14))
plt.matshow(pca_10.components_,cmap='viridis')
y_ticks_names = ['1st Comp','2nd Comp','3rd Comp', '4th Comp', '5th Comp', '6th Comp', '7th Comp',
'8th Comp', '9th Comp', '10th Comp']
plt.yticks([0,1,2,3,4,5,6,7,8,9],y_ticks_names,fontsize=10)
plt.colorbar()
plt.xticks(range(len(df.columns)),df.columns,rotation=65,ha='left')
#plt.tight_layout(h_pad=200)
#plt.margins(50,50)
#plt.set_ylim(len(df.columns)-0.5, -0.5)
#plt.subplots_adjust(hspace=0.3,top=0.6)
#plt.ylim(10, 0)
#plt.gcf().subplots_adjust(hspace=0.3,top=0.6)
plt.gcf().tight_layout(rect=[0, 0.03, 1, 0.95])
plt.savefig(r'PCA_10_comps.png')
plt.show()

I tried each commented line to no avail.
Has anyone been able to make the saved image with correct padding at the top?
I have used plt.tight_layout() to good effect on other charts but Matplotlib doesn't like one or both of my axes this time around. Not sure why?:

A: It appears I can answer my own question after some fairly long amount of time digging in the docs etc. and playing around.
Seems that if I move from plt.figure() to fig, ax1 = plt.subplots() then I can use fig.tight_layout() to good success.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
import matplotlib.cm as cm
from sklearn import decomposition
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_blobs

from sklearn.decomposition import PCA

Required imports, followed by new code:
pca_10 = PCA(10)  # project from 61 to 10 dimensions
projected_10 = pca_10.fit_transform(df)
print(df.shape)
print(projected_10.shape)

fig, ax1 = plt.subplots(figsize=(15,4.5))
ax1.matshow(pca_10.components_,cmap='viridis')
y_ticks_names = ['1st Comp','2nd Comp','3rd Comp', '4th Comp', '5th Comp', '6th Comp', '7th Comp', '8th Comp', '9th Comp', '10th Comp']
ax1.set_yticks([0,1,2,3,4,5,6,7,8,9])
ax1.set_yticklabels(y_ticks_names,fontsize=10)
ax1.set_xticks(range(len(df.columns)))
ax1.set_xticklabels(df.columns,rotation=65,ha='left')
fig.colorbar(cm.ScalarMappable(norm=None, cmap='viridis'), ax=ax1)
fig.tight_layout()
plt.savefig(r'PCA_10_comps.png')
plt.show()

Results in the desired output (also as the saved image in the current working directory):

Seems to suggest that for the matshow chart type, the fig, ax1 = plt.subplots() approach might be better?


text:
Q: Tablas con campos dinámicos estaba practicando diseño de base de datos y se me ocurrió hacer lo siguiente:
una base de datos para una aplicación en la que se puedan agregar animales y definir para ellos una serie de etiquetas para catalogarlos (características, disculpen el error ortográfico en la imagen), y también definir una cantidad de animales para determinada combinación de etiquetas(características, en la imagen).
Le estuve dando vueltas en mi cabeza, pero la verdad siento que me falta algo por aprender para ver una solución clara.
Me gustaría que me ayudaran con eso y si me pudieran recomendar material de estudio muchísimo mejor, de antemano mil gracias.

A: podrías aplicar 2 tablas y 1 vista...
Tabla animales:

*

*id

*nombre

Tabla animal

*

*id

*id_animal [FK]

*cuerpo

*tamaño

*tono_color

Vista
SELECT
T1.id,
T1.nombre,
T2.cuerpo,
T2.tamaño,
T2.tono_color,
COUNT(T1.nombre AND T2.cuerpo AND T2.tamaño AND T2.tono_color) AS cantidad
FROM animales AS T1
INNER JOIN animal AS T2
ON T1.id = T2.id_animal
GROUP BY T1.nombre,T2.cuerpo,T2.tamaño,T2.tono_color;


text:
Q: Multiple Datacenters I am finding a lack of information regarding handling multiple datacenters.  What tools and techniques are available for taking advantage of multiple datacenters?  A requirement is that the databases become consistent very quickly.

A: http://dev.mysql.com/doc/refman/5.0/en/mysql-cluster.html


text:
Q: Where is erlang-start on Erlang R17 in Mac OS X I have emacs running on Mac OS X to work on a Erlang project. I have followed the instructions at http://www.erlang.org/doc/apps/tools/erlang_mode_chapter.html to configure "erlang mode" but I can't locate erlang-start. I've completed this on Windows, just can't seem to find the right config for Mac OS X.
Erlang is installed from the R17 package for Mac OS from Erlang Solutions. The files are installed to /usr/local/lib/erlang but I can't find erlang-start.
Any help is greatly appreciated.

A: For Erlang/OTP 17.0 installed to /usr/local you should be able to find erlang-start.el here:
/usr/local/lib/erlang/lib/tools-2.6.14/emacs/erlang-start.el

A: The file erlang-start.el should come with the installation of Erlang. You can try to locate it by issuing the command locate erlang-start.el or search for the file using Finder. (Unfortunately, I don't know the normal installation location.)


text:
Q: CSS multi-column: not all columns filled For an overview of all products I have each product as an list item. The ul I gave the mulit-column attribut and set the column-count to 5. I have 9 products, so there should be 5 items in the first row and 4 in the second - right?
ul.products{
    -moz-column-count: 5;
    -moz-column-gap: 30px;
    -webkit-column-count: 5;
    -webkit-column-gap: 30px;
    column-count: 5;
    column-gap: 30px;
}

The problem is that only 3 columns are filled. In the fourth and fifth are no products/list-items. I made a jsfiddle so you can see this and experiment: http://jsfiddle.net/oliverspies/W8PE9/2/
Why are the list-items arranged like this? What do I have to do to get all columns filled?

A: If you remove display:inline-block on .products li you will have your 5 columns.
See this FIDDLE

A: DEMO
.products{
    height: 400px;
}


text:
Q: Apostrophe on Proper Nouns that end in -s. "Louis's" vs "Louis' ''? Though I see that many have asked the question of whether acronyms that ends with a "s" should be s' or s's, I have puzzled over whether nouns that ends in "s" should end in s's or s'.
Many sources online and in SAT books disagree with each other and I am confused because of all the disagreements.
If given the example:

Louis's scarf
  Louis' scarf

One book stated that it was Louis's while another said that it should be Louis'.
I specifically looked for the answer what College Board's SAT would agree with and I would also like to know warrants to the answer as well.


text:
Q: Customize BeanFactory with SpringJUnit4ClassRunner? The slow autowire by type problem has finally been solved by creating a caching bean factory.
I would really like to be able to use such a CachingByTypeBeanFactory together with SpringJUnit4ClassRunner for running JUnit tests with @Autowired. But it does not seem to be possible to change the Bean Factory on the application context via the ContextLoader.
Is there any other way to do this ?

A: Create your own ContextLoader and attach this annotation to your JUnit class:
@ContextConfiguration(loader=YourLoader.class)

This is my example Loader which instantiates another or custom ApplicationContext which in turn may be initialized with custom BeanFactory (depending of capabilities):
public class XmlWebApplicationContextLoader extends AbstractContextLoader {

    public final ConfigurableApplicationContext loadContext(final String... locations) throws Exception {
        ServletContext servletContext = new MockServletContext("war", new FileSystemResourceLoader());
        GenericWebApplicationContext webContext = new GenericWebApplicationContext();
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext);
        webContext.setServletContext(servletContext);
        new XmlBeanDefinitionReader(webContext).loadBeanDefinitions(locations);
        AnnotationConfigUtils.registerAnnotationConfigProcessors(webContext);
        webContext.refresh();
        webContext.registerShutdownHook();
        return webContext;
    }

    protected String getResourceSuffix() {
        return "";
    }

}
In above case application context (provided by Spring Framework) has constructor:
public GenericWebApplicationContext(DefaultListableBeanFactory beanFactory) {
    super(beanFactory);
}


text:
Q: If a class is loaded multiple times, do its static-members get initialized multiple times? If a class is loaded multiple times, do its static-members get initialized multiple times?
How do I check for that?

A: If there are different classloaders involved, then they will be completely separate classes, with separate static fields etc - and each will be initialized separately.
(The simplest way to diagnose this is just to log when you get initialized, of course...)
static {
    // Log initialization
}

A: The code inside static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class). This mean its invoked when the class loader loads the class to memory. So its per class loader. If you have multiple class loaders each one will have its own copy of the classes so static block will be invoked by each class loaders. To test this you can put a Sysout in a static block an try and load it using a custom class loader. In the below example the static block will be executed twice. One by the system class loader when we run the static main method and then by our custom class loader.
package sample;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Sample {

    static {
        System.out.println("Entered Static Block!!");
    }

    public static void main(String[] args) {
        CustomClassLoader loader = new CustomClassLoader();
        try {
            Class<?> c = loader.findClass("sample.Sample");
            Object o = c.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}

class CustomClassLoader extends ClassLoader {

    private Map<String, Class<?>> classes = new HashMap<String, Class<?>>();

    @Override
    public String toString() {
        return CustomClassLoader.class.getName();
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        if (classes.containsKey(name)) {
            return classes.get(name);
        }

        byte[] classData;

        try {
            classData = loadClassData(name);
        } catch (IOException e) {
            throw new ClassNotFoundException("Class [" + name
                    + "] could not be found", e);
        }

        Class<?> c = defineClass(name, classData, 0, classData.length);
        resolveClass(c);
        classes.put(name, c);

        return c;
    }

    private byte[] loadClassData(String name) throws IOException {
        BufferedInputStream in = new BufferedInputStream(
                ClassLoader.getSystemResourceAsStream(name.replace(".", "/")
                        + ".class"));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int i;

        while ((i = in.read()) != -1) {
            out.write(i);
        }

        in.close();
        byte[] classData = out.toByteArray();
        out.close();

        return classData;
    }
}

A: The following actions do not cause a class to be loaded:

*

*Referring to a static final primitive field that is known at compile time.

*classLoader.getResource(className.replace('.', '/') + ".class")
The following cause a class to be loaded (i.e., the .class file is parsed, and a Class<?> object is created):

*

*Any line of code that refers to the class symbolically e.g. Foo.class

*Class.forName(String, false, ClassLoader)

*ClassLoader.loadClass(String)

*Loading a subclass or array of the class, or initializing a class whose code or method signatures refer to the class.

The following cause a class to be initialized (i.e., the static blocks are executed):

*

*Constructing a new instance

*Calling a static method

*Getting or setting a static field that is not a compile-time constant.

*Class.forName(String, true, ClassLoader) and Class.forName(String)

If you do initialize the class from multiple ClassLoaders, the static blocks are indeed executed multiple times. For example, the following code:
import java.net.URL;
import java.net.URLClassLoader;

public class InitializeClassMultipleTimes {
    static class Foo {
        static {
            System.out.format("  %s initialized by %s%n", Foo.class.getSimpleName(), Foo.class.getClassLoader());
        }
        public static void foo() {}
    }
    private static Class<Foo> loadClass() {
        System.out.println("Loading class.");
        // Load the .class file. This will fail if the class file is gone or has
        // the wrong file format.
        return Foo.class;
    }
    private static void initializeClass(Class<?> innerClass) {
        System.out.println("Initializing class");
        try {
            Class.forName(innerClass.getName(), true, innerClass.getClassLoader());
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException(e);
        }
    }

    public static void main(String... argv) throws ClassNotFoundException {
        Class<Foo> fooClass = loadClass();
        initializeClass(fooClass);

        URLClassLoader myClassLoader = ((URLClassLoader) InitializeClassMultipleTimes.class.getClassLoader());
        URL[] urls = myClassLoader.getURLs();
        for (int i = 0; i < 2; i++) {
            URLClassLoader newClassLoader = new URLClassLoader(urls, null);  // parent=bootstrap
            System.out.format("%nLoading class using another class loader%n", Foo.class.getSimpleName());
            Class<?> fooClassAgain = Class.forName(fooClass.getName(), false, newClassLoader);
            initializeClass(fooClassAgain);
        }
    }
}

produces the following output. Note that you can also run it under strace -f -e file to verify when the .class files are read.
Loading class.
Initializing class
  Foo initialized by sun.misc.Launcher$AppClassLoader@73d16e93

Loading class using another class loader
Initializing class
  Foo initialized by java.net.URLClassLoader@15db9742

Loading class using another class loader
Initializing class
  Foo initialized by java.net.URLClassLoader@7852e922


text:
Q: How can Android Studio recognize devices connected to a remote computer I want to be able to create Android-Apps on my very old laptop. Since it can't run Android Studio I figured I could run it on my home computer and use RDS to access the PC with the laptop.
Now the problem was how to connect my Phone to my laptop and have it recognized by Android Studio on the PC. Since my laptop is in the same network as my PC (VPN) I managed to replicate this solution. I can run adb devices (since I've set the environment variable ANDROID_ADB_SERVER_ADDRESS I don't need the -H-flag) in the terminal and get my phone in the resulting list. However, when I try running the app in Android Studio no device is found.
So I am thinking that Android Studio uses an integrated ADB that ignores environment variables or some commands that don't support remote usage. Does anyone have an idea what I can do to have my Phone recognized by Android Studio and not just by adb on the PC? I don't want to manually load and start my apps every time I debug.


text:
Q: Problemas con el onActivityResult Quiero enviar de una actividad a otra un Json. En la primera actividad, dentro del onClick de un boton tengo lo siguiente:
Intent i = new Intent(PrimeraActivity.this, SegundaActivity.class);
startActivityForResult(i, REQUEST_CODE);

En la segunda activity, uso un metodo para devolver los datos si insertan las credenciales correctas:
public void iniciarActivity() {
    String pass = mPasswordView.getText().toString();
    String pass2 = Objeto.getPassword();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (Objects.equals(pass, pass2)) {
            Toast toast = Toast.makeText(this, "Credenciales Correctos", Toast.LENGTH_LONG);
            toast.show();
            Intent intent = new Intent();
            gson = new Gson();
            String myjson = gson.toJson(objeto);
            Log.i("baliza", "json:" +myjson);
            intent.putExtra("myjson", myjson);
            setResult(RESULT_OK, intent);
            finish();
        } else {
            Toast toast = Toast.makeText(this, "Credenciales inCorrectos", Toast.LENGTH_LONG);
            toast.show();
        }
    }
}

En la primera activity, el metodo onActivityResult:
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.i("baliza", "onActivityResult main");
    Log.i("baliza", "requestCode main: "+requestCode);
    // check if the request code is same as what is passed  here it is 2
    if (requestCode == REQUEST_CODE_LOGIN) {
        if (resultCode == RESULT_OK) {
            if (data.getStringExtra("myjson") != null) {
                Log.i("baliza", "onActivityResult main if");
                gson = new Gson();
                objeto = gson.fromJson(data.getStringExtra("myjson"), ClaseObjeto.class);
            }
        }
    }
}

El problema es que no entra en el onActivityResult. ¿Me gustaria saber porque no pasa por ahi? ¿Y si es la manera mas correcta de hacerlo? Gracias!!!

A: Es importante asegurar se ejecute:
 setResult(RESULT_OK, intent);

de otra forma no se llamara onActivityResult() al regresar a tu Activity.

A: estoy convencido que tu fallo esta aqui
if (requestCode == REQUEST_CODE_LOGIN) {

en el  onActivityResult
ahi debes colocar el REQUEST_CODE que envias en el intent del  startActivityForResult
ya que este requestcode , es un codigo que el programardor envia al onActivityResult para saber que codigo debe ejecutar...cuando hay varios resultados que se envian
ya veras que si pones manualmente aqui .....
startActivityForResult(i, 123);

luego aqui le pones el mismo numero
 if (requestCode ==123) {

deberia funcionar....
Por cierto, esto lo puedes simplificar asi:
if ((requestCode ==123) && (resultCode == RESULT_OK)) {


text:
Q: asp:Menu not formatting correctly when run from server In the Site.Master page that came with VS 2010, there is a menu that is supposed to be displayed horizontally. It looks when I run in debug mode from VS, but when its on the server, the tabs or displayed vertically. Here is the asp code:
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="true" IncludeStyleBlock="false" Orientation="Horizontal">
                <Items>
                    <%--<asp:MenuItem NavigateUrl="~/Home.aspx" Text="Home"/>--%>
                    <asp:MenuItem NavigateUrl="~/Loan.aspx" Text="Loan Device"/>
                    <%--<asp:MenuItem NavigateUrl="~/Return.aspx" Text="Return Device"/>--%>
                    <asp:MenuItem NavigateUrl="~/InternationalSwap.aspx" Text="International Swap" />
                    <%--<asp:MenuItem NavigateUrl="~/InventoryControl.aspx" Text="Inventory Control" />--%>
                    <%--<asp:MenuItem NavigateUrl="~/Reports.aspx" Text="Reports" />--%>
                    <asp:MenuItem NavigateUrl="~/Administration/InventoryControl.aspx" Text="Administration" />
                </Items>
            </asp:Menu>

At the bottom of the page is a little javascript that causes an error in IE,
<script type='text/javascript'>new Sys.WebForms.Menu({ element: 'NavigationMenu', disappearAfter: 500, orientation: 'horizontal', tabIndex: 0, disabled: false });</script>

But when i run it locally from VS, there is no error. Could there be something that is missing from the server that my local machine has?

A: I encountered the same issue while I'm using Routing and I fixed it by changing the URL pattern for the route.
Also if there is no need to use Global.asax in your project try to remove it.


text:
Q: How to expand dx-treeview at new item? I have a CRUD AngularJS application with Categories and Phones. I'm trying to expand dx-treeview to the new added item.

After clicking Save button it redirects to the new item page:

I would like to know how to expand dx-treeview to the new item.

A: In your case, when the new page is loaded just call the expandItem method with the item id param.
$("#tree-view").dxTreeView("instance").expandItem(/* item id */);

See this example.


text:
Q: How to make a svg pic scale vertiacally an horizontally

This is what in may.svg

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
 "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
 width="288.000000pt" height="143.000000pt" viewBox="0 0 288.000000 143.000000"
 preserveAspectRatio="xMidYMid meet">

<g transform="translate(0.000000,143.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<path d="M2021 1404 c-73 -20 -147 -58 -204 -105 l-47 -40 -63 25 c-98 39
-219 56 -399 56 -214 0 -370 -34 -462 -102 -27 -19 -33 -20 -80 -8 -77 18
-285 25 -358 11 -110 -22 -167 -42 -211 -75 -48 -36 -71 -77 -62 -107 10 -31
64 -88 99 -105 31 -14 31 -14 6 3 -55 38 -90 81 -90 109 0 46 66 98 162 130
76 25 96 28 248 28 106 0 181 -4 209 -13 42 -12 46 -11 125 28 100 50 169 69
313 83 85 9 142 8 230 0 113 -11 264 -46 311 -71 20 -11 28 -7 70 28 81 68
150 93 276 99 166 7 268 -23 361 -109 56 -52 75 -93 75 -166 l0 -59 70 -17
c82 -22 182 -83 210 -129 25 -42 25 -88 0 -138 -25 -49 -70 -83 -163 -124
l-73 -32 28 -27 c35 -35 36 -66 2 -107 -55 -64 -195 -110 -338 -110 l-73 0 -7
-38 c-10 -68 -56 -117 -148 -161 -103 -49 -180 -68 -330 -82 -192 -19 -399 10
-543 76 -81 36 -137 82 -155 125 l-13 30 -48 -45 c-106 -99 -248 -140 -453
-132 -191 7 -300 49 -394 151 -48 52 -66 102 -60 168 3 32 2 46 -4 40 -6 -6
-12 -39 -15 -74 -10 -124 53 -211 211 -289 98 -48 155 -59 300 -59 173 0 291
41 408 142 36 31 58 44 58 35 0 -29 87 -112 151 -143 141 -70 238 -88 474 -88
155 0 179 2 270 27 119 33 186 64 243 113 49 42 72 81 72 122 0 29 0 29 77 36
178 16 307 63 351 126 29 44 28 69 -7 117 l-30 41 46 12 c58 17 154 79 182
118 39 56 45 88 26 137 -28 75 -131 146 -250 174 l-50 12 0 72 c0 79 -10 101
-74 170 -95 102 -305 153 -460 111z"/>
<path d="M285 930 c3 -5 8 -10 11 -10 2 0 4 5 4 10 0 6 -5 10 -11 10 -5 0 -7
-4 -4 -10z"/>
<path d="M70 798 c-16 -22 -30 -49 -30 -59 0 -9 21 -44 48 -77 36 -47 50 -58
60 -49 11 9 6 18 -26 46 -68 61 -75 89 -37 145 34 50 22 46 -15 -6z"/>
<path d="M81 558 c-14 -23 -14 -23 8 -4 22 20 25 26 13 26 -4 0 -13 -10 -21
-22z"/>
</g>
</svg>
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="may.css">
  </head>
<body>

  <svg width="1000" height="1000">
<g class=flex >

<image href="may.svg" width="100" height="700"></image>

</g>

</svg>

</body>
</html>

I have an svg pic, i want to scale it vertically and horizontally like this
enter image description here
to this
enter image description here
i tried viewbox but it only scaled horizontally
this is my html if it`d help

  <svg width="1000" height="1000">
<g class=flex >
<image href="may.svg" width="100" height="700"></image>
</g>
</svg>
</body>

If i change the height and width in my svg image, it only change picture`s width and height with its ratio. How can I display my svg image with my own width and height ratio
What method should i use. Thanks

A: Use a SVG fragment identifier e.g.
<image href="may.svg#svgView(viewBox(0,0,200,200))" width="100" height="700"></image>

Use whatever numbers are appropriate.


text:
Q: Multi-Dimensional ArrayList initialized with values I'm new to coding.  My teacher recently introduced arrays and arraylists.  I have a multi-dimensional array like this:
private String[][] pods = {{"pod1", ""}, {"pod2", ""}, {"pod3", ""}, {"pod4", ""}};

I'd like to switch this to an arraylist, as I need to edit the information in there.
How would I do this, but with a multi-dimensional ArrayList?  I'd like to initialize it with the above information.
I've tried this:
private ArrayList<ArrayList<String>> pods = new ArrayList();

Whenever I put stuff between the parenthesis, I get an invalid operator error.
By the way, just in case anyone was wondering - this is NOT a class assignment. This is something I'm trying on my own.
Thanks.

A: Firstly, your approach is half-correct.
You can have an ArrayList of ArrayLists for a double-dimensional array.
However...
You're initializing your List as a raw type. From Java 7, you can just change your assignment to a diamond-type for inference:
List<List<String>> pods = new ArrayList<>();

In earlier versions:
List<List<String>> pods = new ArrayList<List<String>>();

You also need to populate your lists.
For that, you'll need some iteration.
Here's a complete Java 7 example (using List as "code to an interface" guideline suggests).
String[][] info = {{"pod1", ""}, {"pod2", ""}, {"pod3", ""}, {"pod4", ""}};
List<List<String>> pods = new ArrayList<>();
for (String[] level1: info) {
    List<String> list = Arrays.asList(level1);
    // use this instead if you intend to modify the inner lists
    // List<String> list = new ArrayList<>(Arrays.asList(level1));
    pods.add(list);
}
System.out.println(pods);

Output
[[pod1, ], [pod2, ], [pod3, ], [pod4, ]]

And now, some Java 8 mojo:
String[][] info = {{"pod1", ""}, {"pod2", ""}, {"pod3", ""}, {"pod4", ""}};
List<List<String>> pods =
    Arrays.stream(info)
        .map((a) -> Arrays.asList(a))
        // use this instead if you intend to modify the inner lists
        // .map((a) -> Arrays.stream(a).collect(Collectors.toList()))
        .collect(Collectors.toList());
System.out.println(pods);

(same) output
[[pod1, ], [pod2, ], [pod3, ], [pod4, ]]

A: If you absolutely want a one liner like when you use arrays you can use this "one liner" (you will also need import static java.util.Arrays.asList;):
List<List<String>> pods = new ArrayList<>(asList(
    new ArrayList<>(asList("pod1", "")),
    new ArrayList<>(asList("pod2", "")),
    new ArrayList<>(asList("pod3", "")),
    new ArrayList<>(asList("pod4", ""))
));

A: You can try adding items to your pods ArrayList by creating the inner ArrayLists first, and then using pods.add:
// create your initial ArrayList
private ArrayList<ArrayList<String>> pods = new ArrayList<ArrayList<String>>();

// create an ArrayList<String> to add to it
private ArrayList<String> list1 = new ArrayList<String>();
list1.add("foo");

// create another
private ArrayList<String> list2 = new ArrayList<String>();
list2.add("bar");

// add the inner ArrayLists to your main ArrayList
pods.add(list1);
pods.add(list2);

A: You just need to iterate on array and add items to a list.
When you are finished with a row, just add list to main list.
List<List<String>> list = new ArrayList<List<String>>();
for ( int i = 0 ; i < rowsCount ; i++ )
{
   List<String> temp = new ArrayList<String>();
   for ( int j = 0 ; j < colsCount ; j++ )
    temp.add ( arr[i][j]);
   list.add (temp);

}

or you can do as following :
for ( int i = 0 ; i < rowsCount ; i++ )
{
   list.add (Arrays.asList(arr[i]));
}

But using second approach will prevent you from expanding each list item at any index


text:
Q: LDAP: error code 49 - Invalid Credentials when connecting jira to Mac OS X Lion Server LDAP I have the following setup:
- LDAP Server from Mac OS X running with default configuration
- JIRA Standlone installation
I want to:
Use LDAP for user authentication for jura
username: cn=diradmin,dc=my,dc=domain,dc=com
password: password of the diradmin
I quadruppel checked the password, but I always get the [LDAP: error code 49 - Invalid Credentials]; nested exception is javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials] as an error message.
Is there anything I have to do on the server side to allow the LDAP authentication by some third party app? Do I have to use the diradmin at all here? or can I use any user? what group has the user to be in?
I tried to do the same thing with hudson (build server). And there I get the exact same error message. So it's not a jira issue. It must be a configuration issue.

A: the username was wrong, I had to use this:
uid=diradmin,cn=users,dc=my,dc=domain,dc=com
For mor details: https://help.apple.com/advancedserveradmin/mac/10.7/#apd11ff4730


text:
Q: Is Work Manager correct way to delete uploaded files in Android? I am creating an application where I create a post and add attachments to it.
After an image is uploaded to Firebase Storage, the user can delete the attachment.
I am using Work Manager to delete the file as it is intended for deferrable and guaranteed execution. So my intention was to let the user click a button to delete and not wait for it to finish. Some how I am still wondering if there is any problem with it.
I am using OneTimeWorkRequestBuilder and I am passing it data for building storage reference
// Repository
            val workArray = mutableListOf<OneTimeWorkRequest>()
            val work = OneTimeWorkRequestBuilder<CancelUploadWorkManager>()
                .setInputData(getInputData(index, userId = userId, fileName = fileName))
                .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
                .build()
            workArray.add(work)

            WorkManager.getInstance()
            .enqueue(workArray)

// CancelUploadWorkManager

class CancelUploadWorkManager(context: Context, params: WorkerParameters): CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        val position: Int = inputData.getInt(Constants.KEY_POSITION, 0)
        val userId = inputData.getString(Constants.KEY_DIRECTORY)
        val fileName = inputData.getString(Constants.KEY_FILE_NAME)

        return try {
            FirebaseManager().deleteAt(position = position, fileName = fileName!!,userId = userId!!)
            Timber.i("Work Manager executed")
            Result.success()
        } catch (ex: Exception) {
            Timber.e(ex)
            Result.retry()
        }

    }
}

Expected: File should be deleted with a guarantee

A:
Is Work Manager correct way to delete uploaded files in Android?

Yes. The WorkManager API lets you schedule background tasks that need guaranteed completion, whether or not the app process is around. The WorkManager is available only on devices running API 14 and higher.
However, JobScheduler is available on devices running API 21 and higher. So for devices running API 14 and higher, including devices without Google Play services, WorkManager provides capabilities that are like those provided by JobScheduler.

A: It's not clear, but it seems like you're saying that this code isn't running properly.  If that's the case, what is FirebaseManager.deleteAt?  Is it synchronous or asynchronous?


text:
Q: Blazor WASM - Error: Failed to start platform - error sometimes shows once after deploy I have a Blazor WASM application that mostly works. However, often after deploying new version, and sometimes rarely without reason application fails to load itself.
Refreshing page makes the error dissapear and page mostly works until next version is deployed.
I got this result from web console:

I am not sure what could be causing this issue, seems like some kind of caching problem, but I was unable to pinpoint, nor solve it.

A: I have managed to solve my post-deployment integrity errors by adding a little bit of brute force approach. It might not be best solution, but works ok for my case.
First, in service.worker.js I marked file index.html not to be cached:
const offlineAssetsExclude = [/^service-worker\.js$/, /^index\.html$/];

Then I included service-worker-assets.js to loaded scripts. I need it to get access to assetsManifest.version that is automaticaly generated every build. I then compare it with version saved in localstorage, purge all application caches, save  new version to localstorage and force reload.
Note that this approach will force full application download whenever new version is detected, thus avoiding integrity errors, but at cost of potentialy redownloading files that did not need it.
<script src="service-worker-assets.js?s=v1.12"></script>
<script>
    if (localStorage.getItem('currentVersion') != self.assetsManifest.version) {
        window.caches.keys().then(function (keyList) {
            keyList.forEach(key => window.caches.delete(key));
        });
        localStorage.setItem('currentVersion', self.assetsManifest.version)
        document.location.reload(true);
    }
</script>

Also notice ?s=v1.12 suffix added to asset list file. This value has to be incremented during every deployment. It ensures that browser is not caching old file and we have most fresh version.
Since I am paranoid, I added the same suffix to many other files that I do not want to stay cached after deployment
<link href="Project.Client.styles.css?s=v1.12" rel="stylesheet" />
...
<script src="javascript/site.js?s=v1.12"></script>
<script src="_framework/blazor.webassembly.js?s=v1.12"></script>


text:
Q: GPIO of ESP8266 without base resistance I know that the maximum output current of a GPIO of the ESP8266 is 12 ma
I have seen the next circuit and I have done it, it works perfectly, I have measured the base current and it gives 10 ma
My question is..., as it is possible that without a base resistor the transistor and the output of the 8266 will not be damaged?
Is it possible that the gpio has some type of protection or current limitation?
Thanks

A: I never had the case in 10+ years that an micro-controller had been damaged by having a pin short-circuited, so even if it's not specified on the datasheet there are some sort of current limiting protection.
However, if you do so, you will operate outside the specification of the chip, and as a result you might en up with some unexpected behavior, strange bug/issue or the chip not working at all.
It will also cause the chip to heat up and might reduce the lifetime.
It is just better to keep the resistor, use the chip within its specified range and have a "proper" design and not play with the devil.
If you want to remove the resistor, you can use a N-MOSFET, which is basically a voltage controlled BJT, so you don't need any resistor on the gate. You need to find a mosfet with a gate threshold voltage low enough so that it can fully switch at 3.3V (or whatever voltage is your chip at).


text:
Q: Xamarin.Mobile Geolocator reporting 0 heading for android I am trying to build an application that uses geolocation and the compass to indicate a direction.
I am using Xamarin.Forms with the Xamarin.Mobile component

https://components.xamarin.com/view/xamarin.mobile

Here is the geolocation code:
private void UpdateHeading (object sender, EventArgs e)
{
    #if __ANDROID__
    var locator = new Geolocator (Forms.Context)
    #else
    var locator = new Geolocator ()
    #endif
    { DesiredAccuracy = 1 };

    locator.GetPositionAsync (timeout: 10000).ContinueWith (t => {
        var position = t.Result;

        // position.Heading == 0
    }, TaskScheduler.FromCurrentSynchronizationContext());
}

On iOS, everything seems to work fine.
On Android it's a different story though: most of the time, position.Heading is set to 0. However, Latitude and Longitude are correct.
I am new to Android development as well, so there may be something I'm missing here. Can I fix this / what's the best approach to have a reliable heading?

A: As pointed out by Guilherme, Geolocator.SupportsHeading is False for Android.


text:
Q: How to set value of a hidden field with name as an array in jQuery? This is the hidden field I have: <input type="hidden" value="" name="name[]">
I tried this jQuery: $(input[type=hidden]).val('0'); and it seems to work fine.
I'd like to know if I can use:
1) a combination of both input[type=hidden] and input[name=name] in a single query
OR
2) just use something like $(input[name=name]).val('0');?
Both the above don't seem to work. Is it because name[] is an array?

A: You can do it but you as the name contains brackets, you have to do something like that:
$('input[type=hidden]')
// Or
$('input[name="name[]"]')
// Or
$('input[type=hidden][name="name[]"]')

These 3 selectors are actually working.

A: Try this http://jsfiddle.net/naveendalmeida/cgJkr/
$('input[name="' + name + '[]"]').each(function() {

    $(this).val('Some value');

});

A: Use this:
 $(input[name="name[]"]).val('0');

A: You can write it this way
$("input[type='hidden'][name='name[]']").val('hello');

Hope it heps

A: You can do this
$('input[type="hidden"][name*="name"]').val('0');

This checks for every input that has type equals to hidden and input that has name contains name in the value.
$('input[type=hidden][name="name[]"]')

This checks for every input that has type equals to hidden and input that has name equals name[] in the value.
You can do any combination you want for more information look at jquery
Multiple Attribute Selector API doc
http://api.jquery.com/multiple-attribute-selector/
See fiddle


text:
Q: Java got error on console.printf I have type following code in Netbeans but I got error
package learn.java;

import java.io.Console;

public class LearnJava {
    public static void main(String[] args) {
       Console console = System.console();
       console.printf("Hello My Name Is , Nitesh");
    }
}

Error:
Exception in thread "main" java.lang.NullPointerException
    at learn.java.LearnJava.main(LearnJava.java:8) C:\Users\The Alian\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

A: Have you enabled the console? Check here for instructions: https://www.java.com/en/download/help/javaconsole.xml
Failing that, you could replace the Console call with a simple
System.out.println("Hello My Name Is , Nitesh");

or for formatted strings:
String name = "Nitesh";
System.out.format("Hello My Name Is , %s", name);

A: You can write formatted string at std out by call:
System.out.printf("Hello My Name Is %s", "Nitesh");

Also, you can write error messages to err out:
System.err.printf("Some problem %s", "error message");


text:
Q: Media queries to reposition images I'm using media queries to turn my website more responsive but I'm not sure how to do that with images.
I've used position: absolute otherwise when the screen became really narrow the images would "get out" of the screen width and disappear to the left. So I would like some way that they could stay in the centre but either with a smaller size or in a column display which I can't figure it out how to do without them staying on top of each other. Can someone help me with this?
As you won't have the images to see the actual effect this is how it looks with a screen with a  wide width :

This is how it looks with the properties that I used to centre them in a narrow screen:

and even more narrow

This is the code I used:

    @media screen and (max-width: 1100px) {
  .header-container.row,
  .section-1.row,
  .section-2.row,
  .section-3.row,
  .section-5.row,
  .section-6.row,
  .section-7.row {
    flex-direction: column;
    .work-images {
      position: relative;
    }
    .first-line.row,
    .second-line.row {
      display: flex;
      flex-direction: column;
      position: absolute;
      justify-content: center;
    }
    .pcontainer {
      width: 350px;
    }
    .first-line img,
    .second-line img {
      width: 100%;
      height: 250px;
      object-fit: cover;
    }


text:
Q: Having trouble creating an adjustable timer using ReactJS, changing state of a child item to parent CodeSandbox example of my code
I'm trying to make a timer app with a unique UI for the timer. my issue is i cant seem to adjust the timer without it glitching out.
when i try to lower the time, it adds a new number under the "arrow" button. instead of doing this, it should subtract the number above it.
If the up arrow is clicked the time goes to 1, but if we click the down arrow, the time should go back to 0. right now the timer only goes up to 1 which is fine for the purpose of this question.
i know im doing something wrong, i just cant seem to understand it. i would really like to be able to do it using the two components i have set up just to keep the code maintainable.
the two important components are:
TimerSettings.jsx, and Arrows.jsx
CodeSandbox example of my code
import React, { Component } from "react";
import Arrows from "./Arrows";
class TimerSettings extends Component {
    constructor(props) {
        super(props);
        this.state = { timeData: 0 };
    }
    render() {
        let changeTime = ["up", "up", "up", "up", "up", "up", "down", "down", "down", "down", "down", "down"];

        return (
            <React.Fragment>

                                Create Timer

                            {changeTime.map((item, uid) => (
                                <Arrows status={item} uid={uid} timeData={this.state.timeData} /*changeTime={() => this.handleTime()}*/ />
                            ))}

            </React.Fragment>
        );
    }
    handleTime = () => {
        this.setState({ timeData: 1 });
    };
}

export default TimerSettings;

Arrows.jsx - child component
import React, { Component } from "react";

class Arrows extends Component {
    constructor(props) {
        super(props);
        this.state = { flip: "1", timeData: 0 };
        this.posTime = React.createRef();
        this.negTime = React.createRef();
    }

    render() {
        return (

                            ^

{this.state.timeData}

        );
    }

    handleTime = () => {
        this.setState({ timeData: 1 });
        if (this.state.flip === "-1") {
            this.setState({ timeData: 0 });
        }
    };

    componentDidMount = () => {
        if (this.props.status === "down") {
            this.setState({ flip: "-1", timeData: null });
        }
    };
}

export default Arrows;

A: You need to render both up and down arrows in the Arrow component so the up and down arrows can effect the same state.
class Arrows extends Component {
  constructor(props) {
    super(props);
    this.state = { timeData: 0 };
    this.posTime = React.createRef();
    this.negTime = React.createRef();
  }

  handleTime = (val) => () => {
    this.setState((prevState) => ({
      timeData: prevState.timeData + val
    }));
  };

  render() {
    return (

              ^

{this.state.timeData}

              ^

    );
  }
}

And instead of rendering out 12 (6 up/6 down) you just render an array of 6 Arrow components.
class TimerSettings extends Component {
  constructor(props) {
    super(props);
    this.state = { timeData: 0 };
  }

  handleTime = () => {
    this.setState({ timeData: 1 });
  };

  render() {
    let changeTime = [...Array(6).keys()];

    return (
      <React.Fragment>

                Create Timer

              {changeTime.map((item, uid) => (
                <Arrows
                  key={uid}
                  status={item}
                  uid={uid}
                  timeData={this.state.timeData}
                />
              ))}

      </React.Fragment>
    );
  }
}


text:
Q: Concat dataframes in Pandas with different frequency removes the timezone I'm trying to merge 2 time series with Pandas. The first one (df1) is a Series and the second one (df2) is a DataFrame.
df1
2016-07-05 11:30:00+01:00    -100.81
2016-07-05 11:31:00+01:00    -99.34
2016-07-05 11:32:00+01:00    -95.09
..............
..............
2016-07-05 11:45:00+01:00    -83.62
2016-07-05 11:46:00+01:00    -1.57
2016-07-05 11:47:00+01:00    21.01
..............

df2['column1']
2016-07-05 11:30:00+01:00    -79,45
2016-07-05 11:45:00+01:00    -51.11
2016-07-05 12:00:00+01:00    -12.67
2016-07-05 12:15:00+01:00    15.21
..........

The indexes of df1 and df2 are DatetimeIndex with the timezone set as (datetime64[ns, Europe/London])
print df1.index
DatetimeIndex(['2016-07-05 11:30:00+01:00', '2016-07-05 11:31:00+01:00',
               '2016-07-05 11:32:00+01:00', '2016-07-05 11:33:00+01:00',
                ...
               '2016-07-19 14:30:00+01:00', '2016-07-19 14:31:00+01:00'],
               dtype='datetime64[ns, Europe/London]', length=1358, freq=None)

print df2.index
DatetimeIndex(['2016-07-05 11:30:00+01:00', '2016-07-05 11:45:00+01:00',
               '2016-07-05 12:00:00+01:00', '2016-07-05 12:15:00+01:00',
                ...
               '2016-07-19 14:30:00+01:00', '2016-07-19 14:45:00+01:00'],
               dtype='datetime64[ns, Europe/London]', length=1358, freq=None)

I need the average of the values of df1 each 15 minutes, so I resample the Series as follow:
df1 = df1.resample('15Min').mean()

print df1.index
DatetimeIndex(['2016-07-05 11:30:00+01:00', '2016-07-05 11:45:00+01:00',
           '2016-07-05 12:00:00+01:00', '2016-07-05 12:15:00+01:00',
            ...
           '2016-07-19 14:30:00+01:00'],
           dtype='datetime64[ns, Europe/London]', length=1358, freq='15T')

Now I want to merge the series so I run:
df = pd.concat([df1, df2], axis=1)

The problem is that I loose the timezone for some reason, and the result is:
df
2016-07-05 11:30:00+01:00    -100.81    -79,45
2016-07-05 11:45:00+01:00    -83.62     -51.11
2016-07-05 12:00:00+01:00    -12.67     -12.67
2016-07-05 12:15:00+01:00     15.21      15.21
...........

but the index looses the timezone
print df.index
DatetimeIndex(['2016-07-05 11:30:00+01:00', '2016-07-05 11:45:00+01:00',
               '2016-07-05 12:00:00+01:00', '2016-07-05 12:15:00+01:00',
                ...
               '2016-07-19 14:30:00+01:00'],
               dtype='datetime64[ns, UTC]', length=1358, freq='15T')

Since I have a DataFrame , I've tried to use the join also, but the result is the same.
My questions are:

*

*Is there any way to merge the time series without loosing the timezone?

*Does anyone know why this happen? Is it related with the freq attribute in the Datetimeindex?

I know that one solution would be to set the timezone again after the concat(), but I would like to know if there's a way to merge the time series without loosing the timezone.
PS I found this link but it doesn't answer my question


text:
Q: Why are epsilon-delta proofs difficult? What conceptual difficulties do students learning epsilon-delta proofs have, or, why are the proofs difficult?
Motivation
I have to teach people and never found the epsilonistics particularly difficult, so I have trouble relating to the students and understanding their difficulties.
Desirable answers

*

*Personal experiences

*References to essays or academic literature

*What students have told you

I am not interested in

*

*Advice to use a particular method of teaching

*Advice to use a particular book in teaching

*Arguments about the desirability of teaching epsilonistics

A: I think a personal problem I had with epsilontics when first learning it that the proofs tend to be not very indicative of how one can arrive at them. One chooses values according to some inequality and verifies that it works out. The process of actually arriving at the inequalities involved is hidden in such proofs, but essential to creating them.
So I think it is particularly hard to learn epsilontics by simply working through a lot of epsilontics. Later one develps some intuitions and heuristics for getting to these inequaities, but its hard to explicate them. Also, this is one of the first occurances of proofs requiring a significant amount of creativity, they are not purely mechanical.

A: Among the difficulties, I feel that students have trouble with the logic.  When trying to construct a $\delta$ for a given $\epsilon$, it is often necessary to work backwards.  You then notice that all your inequalities were if and only if.  So, you can work them in the reverse, and logically valid, direction.  Students tend not to understand what it means to assume what you are trying to prove.
Then, when presented with an example that cannot be worked out in the reverse direction, they try to do so.  When you tell them that will not work, they often have trouble trying to figure out how to even start the problem.  They lack the tricks to find the appropriate $\delta$.

A: The epsilon-delta definition of a limit is often a student's first exposure to universal and existential quantifiers in a formal setting. It's important to understand each one and how "for all, there exists" differs from "there exists, for all". It was not immediately apparent to me and others in my class that these two statements are wildly different.
Getting the quantifiers straight is also important for helping students understand which variable to "fix" and which to "choose". When the definition says "there exists a $\delta$", students can confuse that as something that is given and that they somehow need to prove that this mysterious $\delta$ works for all $\epsilon$.

A: I am a student, and I always find epsilon-delta proofs hard. The reason is the notation, and the number of things to keep in your head at the same time. It is always something like:

For any epsilon, there exists a delta, such that it holds that ...

Once you get to really understand the underlying mechanics, the epsilon/delta proofs are not that hard - they are just really scary looking!

A: I think the $\epsilon$-$\delta$ definition is difficult to the students who don't know where the definition comes from. I have once tried to teach a student by asking what it means for a sequence to converge and let him make up his own definition. I did give a lot of hints here and there, but I made him think through it. It was a lengthy discussion but fun. Later, the $\epsilon$-$\delta$ definition was built informally by converting "all sequences" into an interval of length $\delta$ (or $2\delta$ if you prefer). This conversion was understood pretty quickly, probably because the concept is the same.
Example situation:
I: How do you define convergence of a series?
Student: It's when the number tends toward something.
I: How do you define "tends toward something"?
Student: ... It gets closer and closer to some number.
I: Ok, so if I have this sequence: $1, 0, \frac 12, 0, \frac 13, 0, \frac 14, 0, \ldots$, does it converge?
Student: It does because it eventually goes to zero.
I: But $\frac 14$ is farther away from zero than the term before it.
Student: ...But afterwards, everything is smaller than $\frac 14$.
And the discussion goes on. These are not exact words, but the content is close to what I actually discussed.

A: One major roadblock that students encounter is that the epsilon-delta proof is a conditional statement, and a direct proof involves assuming the hypothesis. Many Calc I students have not seen logic (even $P \Rightarrow Q$)...

A: Personally, I find the epsilon-delta proofs start to get difficult when students have to prove that one part $X$ is less than $\epsilon /2$, another part $Y$ is less than $\epsilon /2$, so their sum $X+Y <\epsilon$.
More advanced proofs even have a $\epsilon /3+\epsilon /3 +\epsilon /3 <\epsilon$ style of proof.
Sometimes it is not so obvious to students how to get started.
One method I find useful is to think in terms of limits first, non-rigorously, and then translate the idea to epsilon-delta notation.
A pictorial visualisation would probably be of great help too, for beginners.
The problem is most lecturers (especially analysts) teaching analysis are so good at it, they don't use the pictorial visualisation or the "non-rigorous" way of thinking to get the idea.

A: Sometimes language is the obstacle. I stumbled over the difference between 'if' and 'if and only if' when the textbook didn't provide clear enough examples. Linguistically, my math textbook was a bit loose with its explanations for what I'm sure were mathematically rigorous terms. For someone who pays attention to the language used, this can turn a small problem into a large problem when the explanation introduces ambiguity due to said linguistic laxness.


text:
Q: Need some help migrating from meteor 1.6.0.1 to 1.6.1 and from angular2-compilers to angular-compilers I'm trying to update an Angular/Meteor app from Meteor 1.6.0.1 to 1.6.1. First of all I'm doing this after this fix: https://github.com/Urigo/angular-meteor/pull/1889
The first problem I encountered is that the old way of importing html files as templates for Angular components:
import template from './home.component.html';

@Component({
  selector: 'home',
  template
})
export class HomeStartComponent { }

is not working anymore. When I start the application with meteor a "Cannot find module './XXXX.component.html'." message is printed for every Angular component.
The second problem is that I use LESS as CSS pre-compiler and here it says that you need "meteor remove less" in order to use Angular compilers.
I would like to be sure that if I change the old way of importing html templates and use the typical Angular way (templateUrl) for all my components and I switch from LESS to SASS the app will be working.
Despite of the compilation errors when I start the app in the browser the following error is shown in the dev console:
Uncaught ReferenceError: __decorate is not defined
at app.js?hash=16f67970c82d7408c169d90e08545f5c0ba33acc:7411
at current-shop.service.js (app.js?hash=16f67970c82d7408c169d90e08545f5c0ba33acc:7415)
at fileEvaluate (modules-runtime.js?hash=9f9bb5e055614ddf4eb3e743737b7a5b3cfd9d34:353)
at require (modules-runtime.js?hash=9f9bb5e055614ddf4eb3e743737b7a5b3cfd9d34:248)
at admin-root.component.js (app.js?hash=16f67970c82d7408c169d90e08545f5c0ba33acc:3310)
at fileEvaluate (modules-runtime.js?hash=9f9bb5e055614ddf4eb3e743737b7a5b3cfd9d34:353)
at require (modules-runtime.js?hash=9f9bb5e055614ddf4eb3e743737b7a5b3cfd9d34:248)
at app.module.js (app.js?hash=16f67970c82d7408c169d90e08545f5c0ba33acc:7106)
at fileEvaluate (modules-runtime.js?hash=9f9bb5e055614ddf4eb3e743737b7a5b3cfd9d34:353)
at require (modules-runtime.js?hash=9f9bb5e055614ddf4eb3e743737b7a5b3cfd9d34:248)

This is my Meteor versions file:
accounts-base@1.4.2
accounts-facebook@1.3.1
accounts-google@1.3.1
accounts-oauth@1.1.15
accounts-password@1.5.1
alanning:roles@1.2.16
allow-deny@1.1.0
angular-compilers@0.2.9_3
angular-html-compiler@0.2.9
angular-scss-compiler@0.2.9_1
angular-typescript-compiler@0.2.9_7
autoupdate@1.4.0
babel-compiler@7.0.5
babel-runtime@1.2.2
base64@1.0.11
binary-heap@1.0.10
blaze@2.3.2
blaze-tools@1.0.10
boilerplate-generator@1.4.0
caching-compiler@1.1.11
caching-html-compiler@1.1.2
callback-hook@1.1.0
check@1.3.1
ddp@1.4.0
ddp-client@2.3.2
ddp-common@1.4.0
ddp-rate-limiter@1.0.7
ddp-server@2.1.2
deps@1.0.12
diff-sequence@1.1.0
dynamic-import@0.3.0
ecmascript@0.10.5
ecmascript-runtime@0.5.0
ecmascript-runtime-client@0.6.2
ecmascript-runtime-server@0.5.0
ejson@1.1.0
email@1.2.3
es5-shim@4.7.3
facebook-oauth@1.4.0
geojson-utils@1.0.10
google-oauth@1.2.5
hot-code-push@1.0.4
html-tools@1.0.11
htmljs@1.0.11
http@1.4.0
id-map@1.1.0
jalik:ufs@0.7.4_1
jalik:ufs-gridfs@0.2.1
jquery@1.11.11
launch-screen@1.1.1
livedata@1.0.18
localstorage@1.2.0
logging@1.1.20
matb33:collection-hooks@0.8.4
meteor@1.8.6
meteor-base@1.3.0
meteorhacks:aggregate@1.3.0
meteorhacks:collection-utils@1.2.0
minifier-css@1.3.1
minifier-js@2.3.3
minimongo@1.4.3
mobile-experience@1.0.5
mobile-status-bar@1.0.14
modules@0.11.5
modules-runtime@0.9.2
mongo@1.4.5
mongo-dev-server@1.1.0
mongo-id@1.0.7
mongo-livedata@1.0.12
npm-bcrypt@0.9.3
npm-mongo@2.2.34
oauth@1.2.1
oauth2@1.2.0
observe-sequence@1.0.16
ordered-dict@1.1.0
promise@0.10.2
random@1.1.0
rate-limit@1.0.9
reactive-var@1.0.11
reload@1.2.0
retry@1.1.0
reywood:publish-composite@1.5.2
routepolicy@1.0.13
server-render@0.3.0
service-configuration@1.0.11
sha@1.0.9
shell-server@0.3.1
shim-common@0.1.0
socket-stream-client@0.1.0
spacebars@1.0.15
spacebars-compiler@1.1.3
srp@1.0.10
standard-minifier-css@1.4.1
standard-minifier-js@2.3.2
templating@1.3.2
templating-compiler@1.3.3
templating-runtime@1.3.2
templating-tools@1.1.2
tmeasday:check-npm-versions@0.3.2
tracker@1.1.3
underscore@1.0.10
url@1.2.0
webapp@1.5.0
webapp-hashing@1.0.9

and this my packages.json file:
{
  "name": "shop",
  "private": true,
  "scripts": {
    "start": "meteor run"
  },
  "dependencies": {
    "@angular/animations": "^5.2.9",
    "@angular/common": "^5.2.9",
    "@angular/compiler": "^5.2.9",
    "@angular/compiler-cli": "^5.2.9",
    "@angular/core": "^5.2.9",
    "@angular/forms": "^5.2.9",
    "@angular/http": "^5.2.9",
    "@angular/platform-browser": "^5.2.9",
    "@angular/platform-browser-dynamic": "^5.2.9",
    "@angular/platform-server": "^5.2.9",
    "@angular/router": "^5.2.9",
    "@babel/runtime": "^7.0.0-beta.42",
    "@ng-select/ng-select": "^0.17.2",
    "@types/googlemaps": "^3.30.8",
    "@types/meteor-publish-composite": "0.0.32",
    "angular2-meteor-polyfills": "^0.2.0",
    "ap-angular2-fullcalendar": "^1.3.7",
    "babel-runtime": "^6.26.0",
    "bcrypt": "^1.0.3",
    "bootstrap": "^3.3.7",
    "chart.js": "^2.7.2",
    "fullcalendar": "^3.9.0",
    "gm": "^1.23.1",
    "less": "^2.7.3",
    "meteor-node-stubs": "~0.2.4",
    "meteor-rxjs": "^0.4.10",
    "moment": "^2.21.0",
    "mydatepicker": "^2.6.3",
    "mydaterangepicker": "^4.2.1",
    "ng2-currency-mask": "^4.4.1",
    "ng2-dnd": "^5.0.2",
    "ngx-infinite-scroll": "^0.8.3",
    "ngx-papaparse": "^1.2.5",
    "node-schedule": "^1.3.0",
    "reflect-metadata": "^0.1.12",
    "rxjs": "^5.5.7",
    "spawn-sync": "^1.0.15",
    "try-thread-sleep": "^1.0.2",
    "typescript": "^2.7.2",
    "typings": "^2.1.1",
    "underscore": "^1.8.3",
    "zone.js": "^0.8.20"
  },
  "devDependencies": {
    "@types/chartjs": "0.0.31",
    "@types/meteor": "^1.4.13",
    "@types/underscore": "^1.8.8",
    "meteor-typings": "^1.4.1"
  }
}

These are other compilations errors I get:
node_modules/meteor-typings/1.4/test/test.ts (691, 5): Subsequent variable declarations must have the same type.  Variable 'handle' must be of type 'LiveQueryHandle', but here has type '{ stop: () => void; }'.
node_modules/meteor-typings/1.4/test/test.ts (737, 24): Type '(userId: string) => boolean' has no properties in common with type 'Matcher'.
node_modules/rx/ts/core/es5.ts (3, 17): Duplicate identifier 'ObservableOrPromise'.
node_modules/rx/ts/core/es5.ts (5, 17): Duplicate identifier 'ArrayLike'.
node_modules/rx/ts/core/es5.ts (8, 17): Duplicate identifier 'ArrayOrIterable'.
node_modules/rx/ts/core/es6.ts (5, 17): Duplicate identifier 'ObservableOrPromise'.
node_modules/rx/ts/core/es6.ts (7, 17): Duplicate identifier 'ArrayLike'.
node_modules/rx/ts/core/es6.ts (10, 17): Duplicate identifier 'ArrayOrIterable'.
node_modules/rx/ts/core/es6.ts (20, 22): Interface 'IPromise<T>' cannot simultaneously extend types 'PromiseLike<T>' and 'Promise<T>'.
  Named property 'then' of types 'PromiseLike<T>' and 'Promise<T>' are not identical.
node_modules/rx/ts/core/observer-extras.ts (65, 39): Property 'exception' does not exist on type 'Notification<number>'.
client/imports/app/not-found.component.ts (3, 22): Cannot find module './not-found.component.html'.
[client]: TypeScript Files Compilation: 51651.520ms
[server]: HTML Files Compilation: 0.163ms    -
[server]: ES2015 modules Compilation: 1013.129ms
node_modules/rx/ts/core/linq/observable/pairs.ts (28, 5): Type 'Observable<[string, string]>' is not assignable to type 'Observable<[number, string]>'.
  Type '[string, string]' is not assignable to type '[number, string]'.
    Type 'string' is not assignable to type 'number'.
node_modules/rx/ts/core/linq/observable/pairs.ts (29, 5): Type 'Observable<[string, string]>' is not assignable to type 'Observable<[number, string]>'.
node_modules/meteor-typings/1.4/test/test.ts (691, 5): Subsequent variable declarations must have the same type.  Variable 'handle' must be of type 'LiveQueryHandle', but here has type '{ stop: () => void; }'.
node_modules/meteor-typings/1.4/test/test.ts (737, 24): Type '(userId: string) => boolean' has no properties in common with type 'Matcher'.
node_modules/rx/ts/core/es5.ts (3, 17): Duplicate identifier 'ObservableOrPromise'.
node_modules/rx/ts/core/es5.ts (5, 17): Duplicate identifier 'ArrayLike'.
node_modules/rx/ts/core/es5.ts (8, 17): Duplicate identifier 'ArrayOrIterable'.
node_modules/rx/ts/core/es6.ts (5, 17): Duplicate identifier 'ObservableOrPromise'.
node_modules/rx/ts/core/es6.ts (7, 17): Duplicate identifier 'ArrayLike'.
node_modules/rx/ts/core/es6.ts (10, 17): Duplicate identifier 'ArrayOrIterable'.
node_modules/rx/ts/core/es6.ts (20, 22): Interface 'IPromise<T>' cannot simultaneously extend types 'PromiseLike<T>' and 'Promise<T>'.
  Named property 'then' of types 'PromiseLike<T>' and 'Promise<T>' are not identical.
node_modules/rx/ts/core/observer-extras.ts (65, 39): Property 'exception' does not exist on type 'Notification<number>'.
server/admin/admin-reservations.publication.ts (368, 36): Property 'aggregate' does not exist on type 'Collection<Reservation>'.
server/admin/stats.methods.ts (43, 36): Property 'aggregate' does not exist on type 'Collection<Reservation>'.
server/admin/stats.methods.ts (84, 36): Property 'aggregate' does not exist on type 'Collection<Reservation>'.
server/admin/stats.methods.ts (125, 36): Property 'aggregate' does not exist on type 'Collection<Reservation>'.
server/admin/stats.methods.ts (168, 36): Property 'aggregate' does not exist on type 'Collection<Reservation>'.
server/reCAPTCHA.ts (32, 96): Argument of type '{ content: any; headers: { 'Content-Type': string; 'Content-Length': number; }; }' is not assignable to parameter of type 'HTTPRequest'.
  Types of property 'headers' are incompatible.
    Type '{ 'Content-Type': string; 'Content-Length': number; }' is not assignable to type '{ [id: string]: string; }'.
      Property ''Content-Length'' is incompatible with index signature.
        Type 'number' is not assignable to type 'string'.
[server]: TypeScript Files Compilation: 19101.137ms
=> Started your app.

=> App running at: http://localhost:3000/

I would appreciate any help. It is very important to me to keep up to date with Meteor releases. Thank you very much.

A: Changing the old way of importing html templates for templateUrl for all my components and switching from LESS to SASS did the trick. The app is now working with the latest version of Meteor.


text:
Q: Problema com Trigger Após Update com Update interno em Mysql Estou criando uma trigger no mysql, a trigger é criada porém quando vou dar update na flag para testar o mysql me retorna este erro
ERROR 1442 (HY000): Can't update table 'aux_Batelada'
in stored function/trigger because it
is already used by statement which invoked this stored function/trigger.

Se alguém puder ajudar. Segue o sql da trigger:
DELIMITER $$

CREATE TRIGGER Data_entrada AFTER UPDATE ON scadabr.aux_Batelada FOR EACH ROW
BEGIN
if OLD.flag_entrada=0 AND NEW.flag_entrada=1 THEN
    UPDATE scadabr.aux_Batelada SET dtEntrada=NOW() where idBatelada = 0;
end if;
if NEW.flag_final=1 then
    INSERT INTO `scadabr`.`Batelada` (`dtEntrada`, `QTCerragem`, `QTKnor`, `QTCinzas`, `QTRest`, `QTPodas`, `QTPalha`, `VLTempMax`, `VLPesoTotal`,  `VLTempRetirada`,`QtSuper`,`QtComplex`) VALUES (NEW.dtEntrada, NEW.QTCerragem, NEW.QTKnor, NEW.QTCinzas, NEW.QTRest, NEW.QTPodas, NEW.QTPalha, NEW.VLTempMax, NEW.VLPesoTotal, NEW.QtSuper, NEW.QtComplex);
end if;
END$$

DELIMITER ;

A: Boa tarde.
Você não pode executar um update na mesma tabela que está criando a trigger isso pode fazer sua tabela entrar em loop.
Sendo assim uma alternativa é alterar quando a trigger é acionada de AFTER para BEFORE.
Aí você consegue manipular como vai ficar os dados usando o NEW.
DELIMITER $$

DROP TRIGGER IF EXISTS Data_entrada;
DELIMITER |
CREATE TRIGGER Data_entrada BEFORE UPDATE ON scadabr.aux_Batelada FOR EACH ROW
BEGIN

if OLD.flag_entrada=0 AND NEW.flag_entrada=1 THEN
    SET NEW.dtEntrada = NOW();
end if;

if NEW.flag_final=1 then
    INSERT INTO `scadabr`.`Batelada` (`dtEntrada`, `QTCerragem`, `QTKnor`, `QTCinzas`, `QTRest`, `QTPodas`, `QTPalha`, `VLTempMax`, `VLPesoTotal`,  `VLTempRetirada`,`QtSuper`,`QtComplex`) VALUES (NEW.dtEntrada, NEW.QTCerragem, NEW.QTKnor, NEW.QTCinzas, NEW.QTRest, NEW.QTPodas, NEW.QTPalha, NEW.VLTempMax, NEW.VLPesoTotal, NEW.QtSuper, NEW.QtComplex);
end if;

END
|
DELIMITER ;


text:
Q: Process running in only one processor I have a 40 v core machine in which a java process running. I can see that this process is running in cpu6 all the time.
$watch ps -o pid,psr,comm -p 4076
Every 2.0s: ps -o pid,psr,comm -p 4076                                                                                Mon Apr 11 02:24:12 2016

  PID PSR COMMAND
 4076   6 java

$ sudo taskset -c -p 4076
pid 4076's current affinity list: 0-39
$ sudo taskset -p 4076
pid 4076's current affinity mask: ffffffffff

This is how top command for cpu utilisation looks
$ top -c
top - 02:27:37 up 47 days, 10:49,  9 users,  load average: 2.83, 2.89, 3.01
Tasks: 470 total,   1 running, 469 sleeping,   0 stopped,   0 zombie
%Cpu0  : 36.0 us,  8.3 sy,  0.0 ni, 40.7 id,  8.7 wa,  0.0 hi,  6.3 si,  0.0 st
%Cpu1  :  1.3 us,  0.7 sy,  0.0 ni, 97.7 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu2  :  0.3 us,  0.3 sy,  0.0 ni, 99.3 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu3  :  0.7 us,  0.7 sy,  0.0 ni, 98.0 id,  0.7 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu4  :  1.4 us,  1.0 sy,  0.0 ni, 97.3 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu5  :  1.0 us,  1.3 sy,  0.0 ni, 97.0 id,  0.7 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu6  :  0.3 us,  0.3 sy,  0.0 ni, 99.0 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu7  :  0.3 us,  0.0 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu8  :  0.3 us,  0.0 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu9  :  1.0 us,  1.0 sy,  0.0 ni, 97.7 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu10 :  0.7 us,  0.7 sy,  0.0 ni, 98.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu11 :  0.7 us,  0.0 sy,  0.0 ni, 99.3 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu12 :  0.7 us,  1.3 sy,  0.0 ni, 97.7 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu13 :  0.3 us,  0.7 sy,  0.0 ni, 99.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu14 :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu15 :  0.7 us,  0.3 sy,  0.0 ni, 99.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu16 :  0.3 us,  0.0 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu17 :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu18 :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu19 :  1.7 us,  0.3 sy,  0.0 ni, 97.7 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu20 :  0.7 us,  0.3 sy,  0.0 ni, 99.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu21 :  0.7 us,  0.0 sy,  0.0 ni, 99.3 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu22 :  0.3 us,  0.0 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu23 :  0.7 us,  0.3 sy,  0.0 ni, 98.7 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu24 :  1.3 us,  0.7 sy,  0.0 ni, 98.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu25 :  2.0 us,  0.3 sy,  0.0 ni, 97.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu26 :  0.7 us,  0.3 sy,  0.0 ni, 99.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu27 :  0.3 us,  0.7 sy,  0.0 ni, 98.7 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu28 :  0.3 us,  0.7 sy,  0.0 ni, 98.7 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu29 :  0.7 us,  0.7 sy,  0.0 ni, 98.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu30 :  1.0 us,  0.3 sy,  0.0 ni, 98.3 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu31 :  1.0 us,  0.7 sy,  0.0 ni, 98.0 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu32 :  0.7 us,  0.0 sy,  0.0 ni, 99.3 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu33 :  0.0 us,  0.3 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu34 :  0.7 us,  0.3 sy,  0.0 ni, 99.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu35 :  0.7 us,  0.0 sy,  0.0 ni, 99.0 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu36 :  0.0 us,  0.3 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st

Cpu6 is idle most of the time as you see it in top command. So scheduling process on same processor is possible and it will help to reduce cache invalidation. But how is scheduler doing all this? Is it keeping a track of each process and their last executed processor?

A: Yes, Linux's scheduler keeps track of where each thread was last scheduled, and favors keeping a thread on the same CPU if it can. You guessed the reason: migrating a thread from a CPU to another is more expensive than keeping it on the same CPU. There's even more to it: the scheduler knows about multiple levels of cache coherency, and tries not to migrate threads too far: moving a thread inside the same hyperthreaded core is very cheap, moving to another core on the same CPU chip is less cheap, moving to another CPU chip is more expensive, etc. The tool for this is scheduling domains.


text:
Q: Computing the expectation of a Tricky R.V. (Brought form Neuroscience). I need to compute $\Bbb{E}(\tau^{X} \ \Bbb{1}_{\{\tau^{X}<+\infty\}})$ where:
$1) $ $\tau^y$ is a r.v. representing the time spent by a particle until it "jumps", ( $ y \in R_{\geq 0} $ is the starting position of the particle ). Its law is given by
$$ P(\tau^y > t)= e^{y(e^{-t}-1)}$$ Observe that $ P(\tau^y =+\infty ) = e^{-y}$
. I've also computed (for other purposes,but I think it may help) the law and expectation of $\hat{\tau}^y:=\tau^y \Bbb{1}_{\{\tau^{y}<+\infty\}} $:
$$P(\hat{\tau}^y>t)=e^{-y}(e^{ye^{-t}}-1)\ ;\ \Bbb{E}(\hat{\tau}^y)=e^{-y}\int_0^y\frac{e^s-1}{s}ds $$
$2)$ $ X $ is a R.V. with values in $R_{\geq 0} $ with
$$ F_X(a) = \begin{cases}
0 \ \ \ \ \ \ if\ \ a<0\\
e^{-2}\ \ \ \ \ if\ \ a\in[0,1]\\
e^{2(a-2)}\ \ \ if\ \ a\in(1,2)\\
1 \ \ \ \ \ \ if\ \ a\geq 2
\end{cases} $$
Note that $P(X=0)=e^{-2}$, so it has an atom in $0$
I thought about conditional expectation, conditioning on $X$ , but I'm not sure how to handle it.

A: @Did
A few questions about your answer:
1) Which property did you use to get that result? Could you lend me useful bibliography  where that property appears?
2) When computing $u(s)$ did you "compute" the "density" of $X$ ? ( I put the "" because I'm not sure it DO have density, since $F_X$ has a jump at 0; and also I'm wondering if a minus is missing .


text:
Q: cv2.error: OpenCV(4.1.0) Código abaixo:
import cv2

imagemCarregada = cv2.imread("exemplo.jpg", 0)

cv2.imshow("imagem", imagemCarregada)

cv2.waitKey(0)

cv2.destroyAllWindows()

Erro apresentado:

A: Esse erro significa que você está carregando uma imagem vazia. Como especificado no erro, a imagem deve ter um width > 0 e um height > 0.
Aqui, consegui abrir uma imagem sem problemas com exatamente o mesmo código.
Possíveis causas do erro:

*

*A imagem não existe no diretório. Vale verifica novamente e tentar
algo como: cv2.imread("C:\\path\\to\\image.png") ou
cv2.imread("C:/path/to/image.png"));

*A extensão da imagem pode está errada. Lembre-se, .jpg é
diferente de .jpeg

*Você pode não ter diretos para acessar a pasta da imagem.


text:
Q: In a square matrix, where each cell is black or white. Design an algorithm to find the max sub-square such that all 4 borders are black Given a square matrix, where each cell is black or white. Design an algorithm to find the max sub-square such that all 4 borders are black.
I have O(n^2) algorithm:
Scan each column from left to right, for each cell in each column, scan each row to find the max sub-square with back borders.
Are there better solutions ?
thanks

A: O(n^2) is possible. I guess it is optimal, as you have n^2 cells.
Notice that the top-left corner and the bottom-right corner of any square lie along the same diagonal.
Now if we could process each diagonal in O(n) time, we would have an O(n^2) time algorithm.
Say we have a candidate for a top-left corner. We can compute the number of continuous black cells below it, and to the right of it and take the minimum of the two and call it T.
For a bottom-right candidate, we can compute the number of continuous black cells to the left of it, and to the top and take the minimum of the two, call it B.
Once we have the two numbers T and B, we can tell if the given top-left, bottom-right candidate actually give us a square with all black borders.
Now those two numbers can be computed for each cell, in O(n^2) time by making four passes through the whole matrix (How?).
So let us assume that is done.
Now consider a diagonal. Our aim is to find a top-left,bottom-right pair along this diagonal in O(n) time.
Let us assume we have the T's computed in an array T[1...m] where m is the length of the diagonal. Similarly we have an array B[1...m]. T[1] corresponds to the top-left end of the diagonal and T[m] to the bottom-right. Similarly with B.
Now we process the diagonal as follows, for each top-left candidate i, we try to find a bottom-right candidate j which will give the largest square. Notice that j >= i. Also notice that if (i,j) is a candidate, then (i',j) isn't, where i' > i.
Note that i and j form a square if T[i] >= j-i+1 and B[j] >= j-i+1.
i.e. T[i] +i - 1 >= j and B[j] -j - 1 >= -i.
So we form new arrays such that TL[k] = T[k] + k -1 and BR[k] = B[k] -k - 1.
So given the two new arrays TL and BR, and an i, we need to answer the following queries:

What is the largest j such that TL[i] >= j and BR[j] >= -i ?

Now suppose we were able to process BR for range maximum queries (can be done in O(m) time).
Now given TL[i], in the range [i, TL[i]] we find the maximum value of BR, say BR[j1].
Now if BR[j1] >= -i, we find the maximum of BR in the range [j1, TL[i]] and continue this way.
Once we find the (TL[i],BR[j]) candidate, we can ignore the array BR[1...j] for future i.
This allows us to process each diagonal in O(n) time, giving an O(n^2) total algorithm.
I have left out a lot of details and given a sketch, as it was already too long. Feel free to edit this with clarifications.
Phew.

A: C++ Code:
#include<iostream>
using namespace std;

int min(int a,int b,int c)
{
    int min = a;
    if(min > b)
        min = b;
    if(min > c)
        min = c;
    return min;
}

int main()
{
    const int size  = 5;
    char a[size][size] = { {'b','b','b','b','w'},{'b','b','b','b','b'},{'b','b','b','b','b'},{'b','b','w','b','b'},{'b','w','w','b','b'} };
    int arr[size+1][size+1];
    // First row and First column of arr is zero.
    for(int i=0;i<size+1;i++)
    {
        arr[0][i] = 0;
        arr[i][0] = 0;
    }
    int answer = 0;
    for(int i=0;i<size;i++)
    {
        for(int j=0;j<size;j++)
        {
            if(a[i][j] == 'w')
                arr[i+1][j+1] = 0;
            if(a[i][j] == 'b')
            {
                int minimum = min(arr[i][i],arr[i+1][j],arr[i][j+1]);
                arr[i+1][j+1] = minimum + 1;
                if( arr[i+1][j+1] > answer)
                    answer = arr[i+1][j+1];
            }
        }
    }
    for(int i=0;i<size+1;i++)
    {
        for(int j=0;j<size+1;j++)
        {
            cout<<arr[i][j]<<"\t";
        }
        cout<<endl;
    }
    cout<<answer<<endl;
    return 0;
}

A: /* In a square matrix, where each cell is black or white.
 * Design an algorithm to find the max sub-square such that all 4 borders are black. The right Java implementation based on a previous post.
 */
public int maxSubsquare(boolean[][] M){
    int n = M.length;
    maxsize=0;
    checkDiag(M, 0, 0, n);
    for (int i=1; i<n; i++){
        checkDiag(M, i, 0, n);
        checkDiag(M, 0, i, n);
    }
    return maxsize;
}
int maxsize;
void checkDiag(boolean[][] M, int i, int j, int n){
    if (i>=n-maxsize || j>=n-maxsize) return;
    int step = 0;
    while (step<(n-Math.max(i, j))&& M[i][j+step]&&M[i+step][j]){
        int s = step;
        while (s>0){
            if (M[i+s][j+step]&&M[i+step][j+s]) s--;
            else break;
        }
        if (s==0)
            maxsize = Math.max(maxsize, step+1);
        step++;
    }
    if (step==0) checkDiag(M, i+step+1, j+step+1, n);
    else checkDiag(M, i+step, j+step, n);
}

A: I don't know why you can get an O(n^2) algorithm. Mathematically, it is impossible.
Let's say you have an NxN matrix. You need to check:
1. 1 matrix of size: NxN,
2. 2*2 matrices of size: (N-1)x(N-1),
3. 3*3 matrices of size: (N-2)x(N-2),
....
In total, you have to check: 1+ 2^2 + 3^2 + ... + N^2 = N(N+1)(2N+1)/6.
So any algorithm cannot do better than O(N^3)


text:
Q: new template in joomla not working properly I've uploaded my new template successfully but on the site it is ging following error
500 - Unable to load renderer class
Error details are as follows:
You may not be able to visit this page because of:
an out-of-date bookmark/favourite
a search engine that has an out-of-date listing for this site
a mistyped address
you have no access to this page
The requested resource was not found.
An error has occurred while processing your request.

Please help me :(

A: From my experience with Joomla that means you have a 404 not a 500 error. Can you provide a link to your site where you are experiencing the error? Also, what template and version of joomla are you using?


text:
Q: Cucumber Testing, Should Stay on Same Page I'm using Cucumber and running BDD tests.
I'm unsure how to test that I stay on the same page. Suggestions are appreciated.

A: "Staying on the same page" doesn't seem valuable to me. As a user, I don't care that I stay on the same page.
I might care that, for instance, if I was looking at my basket, when I finish , I am still looking at my basket.
If I'm looking at an Acme 2000 Super Widget, when I finish, I'm still looking at the Acme 2000 Super Widget.
I often find a lot of BDD problems can be answered if I ask, "Can you give me an example of that?" So, can you give me an example of a page that you might want to stay on?
Those specific examples end up being scenarios. Your rule, "should stay on the same page", can go in the explanation at the top of the feature file to explain the examples below.

A: If you aren't using a one page app then you should just be able to assert based on the url.  If you are using watir then
assert_equal 'http://www.yourpage.com', @browser.url

If you are using a different framework then there will be an equivalent.


text:
Q: The encrypted sample was not found when using the PadBuster to padding oracle Though the PadBuster is a great tool in padding oracle,but when I attempt to decrypt the viewstate or the cookies in asp.net apps, it all tell me that The encrypted sample was not found.
Something may be wrong when I using it, but there is not so much information to tell me how to use it.
Does anyone has the experience about using the padbuster?
Can you show it to me?

A: Have you asked the authors of the paper? (http://netifera.com/research/) They said they will publish more details about the ASP NET vulnerability. What you need is an encrypted sample that you can find in the website looking for WebResource.axd?d=(this) or ScriptResrouce?d=(this) or may be an encrypted viewstate (if it starts with weP is not encrypted)

A: It only works for the values, not cookies and viewstates.
There are now a few blogs that demonstrate the usage.
Search for something like, MS10-070 exploit padbuster.pl.


text: Q: AngularJS, ng-include file not loading I want to include an external html file (form-to-add.html) in angularjs page, but I failed to load it into my main page.