text:
Q: Convert XML to json from Groovy I want to code xml to json using groovy..i have the following code..but from the output {"note":[{"to":["Tove"]},{"from":["Jani"]},{"heading":["Reminder"]}]} i want to remove "[]" things from the output and how can i remove those things.. code as follows
def xml = '''<root>
        |    <node>Tim</node>
        |    <node>Tom</node>
        |    <node>
        |      <anotherNode>another</anotherNode>
        |    </node>
        |</root>'''.stripMargin()

// Parse it
def parsed = new XmlParser().parseText( xml )

// Deal with each node:
def handle
handle = { node ->
  if( node instanceof String ) {
      node
  }
  else {
      [ (node.name()): node.collect( handle ) ]
  }
}
// Convert it to a Map containing a List of Maps
def jsonObject = [ (parsed.name()): parsed.collect { node ->
   [ (node.name()): node.collect( handle ) ]
} ]

// And dump it as Json
def json = new groovy.json.JsonBuilder( jsonObject )

// Check it's what we expected
assert json.toString() == '{"root":[{"node":["Tim"]},{"node":["Tom"]},{"node":         [{"anotherNode":["another"]}]}]}'

A: You could write a function to return a single object (if the list is of length 1), or the list (if it contains more than one element):
def crush = { list ->
    list?.size() == 1 ? list[ 0 ] : list
}

Then wrap both your collect calls in a call to this method:
  [ (node.name()): crush( node.collect( handle ) ) ]


text:
Q: How to update Github's PAT after regeneration? I had a perfectly working local-remote connection, but after regenerating Github's personal access token my project's git related commands stopped working, as expected.
When typing git pull for example, I was simply getting an authentication error, without opening a prompt for updating the PAT. Also I was unable to update PAT nor on macOS, nor on Windows via their credential managers.

A: The Git FAQ explains how to reset the credential manager's credentials  (substitute user for your username):
$ echo url=https://user@github.com | git credential reject

This will erase the credentials from an existing credential helper, so next time you pull or push, Git will prompt you for credentials again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: It is possible to have two apps running on the same port with expressjs? It is possible to have two apps running on the same port with expressjs?
node app1.js:
const app = express();

app.get('/api/v1/foo', (req, res) => { res.json(...); });

express.listen(3000);

node app2.js:
const app = express();

app.get('/api/v1/bar', (req, res) => { res.json(...); });

express.listen(3000);

The endpoints are not collapse. But node say "the port in use".
Is it possible?

A: You can put both in the same application like this:
const app = express();

app.get('/api/v1/bar', (req, res) => { res.json(...); });
app.get('/api/v1/foo', (req, res) => { res.json(...); });

express.listen(3000);

But you will not be able to run two applications on the same port. That's just how ports work.

A: In addition to the correct reply from @Lalaluka:
If you want to run two applications on the same port and cannot put them in the same application for whatever reason, you can use a reverse proxy like NGINX. A reverse proxy is a server that sits in front of your web server (occupying the port) and directs traffic to the appropriate application.
https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/

A: The answer from @Lalaluka is correct. I think the other way that you can run 2 apps in same port 3000, is by running 1 app using your IP address and the other one using localhost
app.listen(3000, "IP address") // http://ipaddress:3000/ for node app1.js
app.listen(3000) // http://localhost:3000/ for node app2.js

But only the app with IP address can be accessed in the network. Hope it helps. Thanks


text:
Q: Error 404 - Error displaying views of a Springmvc project I am a beginner in spring mvc in general, I am doing a project with that framework in Netbeans, and I am working programmatically instead of working directly with the XML configuration files to configure the servlet. In the index I have a form to search for an element with a specific id, it calls the controller, but the view is not displayed, showing a 404 error that the resource does not exist, but the search I am doing by the get method, and if He performs it. The fact is that I have configured as I see in the spring documentation and on the internet, and even then it does not work. Here I leave the configuration I have, in addition to the packages that are what they contain
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

AppContext class
package edu.co.ucatolica.trabajoya.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@PropertySource("classpath:database.properties")
@EnableTransactionManagement
@ComponentScan(basePackages = {
    "edu.co.ucatolica.trabajoya"
})
public class AppContext {

    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] {
            "edu.co.ucatolica.trabajoya.model"
        });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.user"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.pass"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        return properties;
    }

    @Bean
    public HibernateTransactionManager getTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }
}

AppInitializer Class
package edu.co.ucatolica.trabajoya.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 *
 * @author Carlos
 */
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class < ? > [] getRootConfigClasses() {
        return new Class[] {
            AppContext.class
        };
        //return null;
    }

    @Override
    protected Class < ? > [] getServletConfigClasses() {
        return new Class[] {
            WebMvcConfig.class
        };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {
            "/"
        };
    }
}

WebMvcConf class
package edu.co.ucatolica.trabajoya.config;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * @author Ramesh Fadatare
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {
    "edu.co.ucatolica.trabajoya.controller"
})
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public InternalResourceViewResolver resolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setBasename("messages");
        return source;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/resources/**")
                .addResourceLocations("/resources/");
    }

    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource());
        return validator;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }
}

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome to Spring Web MVC project</title>

    <form action="search" method="get" modelAttribute="trabajos">
        <form:hidden path="id" />
        ID: <input type="text" name="txtIdTrabajo" id="txtIdTrabajo" />

        <input type="submit" value="Buscar"/>
    </form>

trabajos.jsp
<%--
    Document   : trabajos
    Created on : 19/08/2019, 10:48:36 PM
    Author     : Carlos
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

Hello World!

TrabajosController
package edu.co.ucatolica.trabajoya.controller;

import edu.co.ucatolica.trabajoya.model.Trabajos;
import edu.co.ucatolica.trabajoya.service.TrabajosService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author Carlos
 */
@Controller
@RequestMapping("/trabajos")
public class TrabajosController {
    @Autowired
    private TrabajosService trabajosService;

    @GetMapping("/list")
    public String list(Model model){
        List<Trabajos> trab = this.trabajosService.list();
        model.addAttribute("trabajos", trab);
        return "list-trabajos";
    }

    @GetMapping("/search")
    public String search(@RequestParam("txtIdTrabajo")int id, Model model){
        Trabajos t = this.trabajosService.search(id);
        model.addAttribute("trabajo", t);
        return "trabajos";
    }
}

The packages that I have are the following:
edu.co.ucatolica.trabajoya.model = Project entities are saved
edu.co.ucatolica.trabajoya.dao = Project DAO classes
edu.co.ucatolica.trabajoya.services = Project service classes are saved
edu.co.ucatolica.trabajoya.config = All the application settings are saved, here are the 3 main classes of project configuration
edu.co.ucatolica.trabajoya.controller = Package all project controllers
Project
image project
I can not put the image of the project as such, since I do not yet have range for it
I want to know I can only see the views without any problem and solve that error 404. Thank you

A: Try putting your index.jsp file at the same level as your WEB-INF folder.


text:
Q: Data validation for time in format 00:00:00 in Excel VSTO? Data validation for time in format 00:00:00 in Excel VSTO?
I can do data validation for time in Excel cell,
but the strange thing is it also allows you to enter integers and doubles
in the cell. Instead I want to allow ONLY values in the format 00:00:00.
I see you can make a custom formula for data validation in excel, but
is there a formula that can check this?

A: Yes. While I've never used VSTO myself, you can use this formula:
=IF(TIMEVALUE(TEXT(A1,"hh:mm:ss"))=A1, "Time Entry", "Not a Time Entry")

Programatically (VBA) there's certainly a lot of ways to accomplish the same results, and it depends on your context. You could for instance listen to the event Worksheet_Change and call this code in the worksheet module:
Function IsTime(rng As Range) As Boolean
    Dim sValue As String
    sValue = rng.Cells(1).Text
    On Error Resume Next
    IsTime = IsDate(TimeValue(sValue))
    On Error GoTo 0
End Function

Private Sub Worksheet_Change(ByVal Target As Range)
  If not(IsTime(Target.Value)) then
    msgbox "Please enter time in '00:00:00' format!"
    Target.Value = ""
  End if
End Sub

Source: http://excel.tips.net/T003292_Checking_for_Time_Input.html


text:
Q: How to show custom DialogFragment using Android Jetpack Navigation? I am building a game for Android using Kotlin, MVVM and Android Jetpack. Recently I have been trying to show DialogFragments using Navigation component. My navigation.xml file:
<dialog
    android:id="@+id/gamePauseDialog"
    android:name="pl.kamilszustak.innymislowy.dialog.GamePauseDialog"
    android:label="GamePauseDialog" />

Anyway, my custom dialog has got 4 buttons inside, which have got their own onClickListeners:
interface OnButtonsClickListener : DialogInterface.OnDismissListener {
        fun onSoundButtonClick()
        fun onVibrationsButtonClick()
        fun onReturnButtonClick(dialog: GamePauseDialog)
        fun onExitButtonClick(dialog: GamePauseDialog)
}

How to implement these listeners and pass them to my dialog instance? I tried using Safe Args and a wrapper (argument in navigation.xml), which encapsulated my OnButtonsClickListener and marked it as @Parcelize and Parcelable, but it used to crash at runtime.
Showing dialog:
val gamePauseDialogDirection =
            GameFragmentDirections.actionGameFragmentToGamePauseDialog(
                isSoundEnabled,
                areVibrationsEnabled,
                wrapper
            )

findNavController().navigate(gamePauseDialogDirection)

Wrapper:
@Parcelize
class DialogListenerWrapper (
    val listener: @RawValue DialogInterface.OnDismissListener
) : Parcelable

Do you have got any idea how to implement these listeners and pass these it to the dialog using Navigation component?


text:
Q: Why does this simple tf.keras model not train after converting to a tensorflow estimator? I'm trying to convert a tf.keras model to a tensorflow estimator using tf.keras.estimator.model_to_estimator, but the resulting estimator doesn't appear to be trainable.
I've tried modelling y = (x_1 + x_2)/2 using both sequential and functional tf.keras API's, and while the tf.keras models work perfectly fine, neither work after converting to estimators. Using a tf.estimator.LinearRegressor with the same input functions does work, so I don't think the problem is with the input functions.
Here's a minimal working example for the sequentially defined tf.keras model:
import numpy as np
import tensorflow as tf
import functools

sample_size = 1000

x_train = np.random.randn(sample_size, 2).astype(np.float32)
y_train = np.mean(x_train, axis=1).astype(np.float32)

x_test = np.random.randn(sample_size, 2).astype(np.float32)
y_test = np.mean(x_test, axis=1).astype(np.float32)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(1, input_shape=(2,), name="Prediction"))
adam = tf.keras.optimizers.Adam(lr=0.1)
model.compile(loss='MSE', optimizer=adam)
#model.fit(x=x_train, y=y_train, epochs=10, batch_size=64)  # This works

est = tf.keras.estimator.model_to_estimator(keras_model=model)

def train_input_fn(batch_size):
    dataset = tf.data.Dataset.from_tensor_slices(({"Prediction_input": x_train}, y_train))
    return dataset.shuffle(sample_size).batch(batch_size).repeat()

def eval_input_fn(batch_size):
    dataset = tf.data.Dataset.from_tensor_slices(({"Prediction_input": x_test}, y_test))
    return dataset.batch(batch_size)

est.train(input_fn=functools.partial(train_input_fn, 64), steps=10)

eval_metrics = est.evaluate(input_fn=functools.partial(eval_input_fn, 1))
print('Evaluation metrics:', eval_metrics)

The estimator is trained for 10 steps, which should be more than enough to bring the loss down. Increasing the number of steps makes no difference, as far as I can tell.
When I run this on tensorflow 1.5.0, I get a warning about calling reduce_mean with keep_dims being deprecated when the tf.keras model is compiled, but it trains perfectly well as is.
Is this a bug, or am I missing something?

A: It turns out all I needed to do was reshape the target to have shape (sample_size, 1), and increase the number of training steps. I'm still not sure what the estimator was doing when the target had shape (sample_size, ), or why this isn't a problem for the canned estimator, but at least I know how to avoid this.


text:
Q: Fade in content, then fade out, then fade in new content What I'm trying to do:
#leftSide          #rightSide (display:none)
 _______________ _______________________________________________
|               |                                               |
| category      |                                               |
|  -link        |                                               |
|  -link        |                                               |
|               |                                               |
| category      |                                               |
|  -link        |                                               |
|  -link        |                                               |
|               |     1. content fades in on link click         |
|               |     2. new link click fades out old content   |
|               |     3. new content fades in                   |
|               |                                               |
|               |                                               |
|               |click -> fade in -> click -> fade out + fade in|
|               |                                               |
|               |                                               |
|_______________|_______________________________________________|

Every time I click on a link in a category, I want to fade in #rightSide with the content of that link, then if I click a new link, the old content fades out and the new content fades in and so on so forth for all other links.
What I have so far works in the way that I click on a link, and said div fades in, then I click a second link, then the second div fades in right underneath instead of fading out the old div and fading in the new one.

blog

portfolio

Link 1

Link 2

photography

test

another

Div 1

Div 2

A: demo jsBin
$('#div_1, #div_2').addClass('js');

$('.portfolio a').click(function(e){

  e.preventDefault();                      // prevent dafault anchor behav.

  var rel = $(this).attr('rel');           // grab our rel
  $('#'+rel).fadeIn().siblings('div').fadeOut();

});

A: Try this:
$(document).ready(function(){
    $('#div_1, #div_2').addClass('js');
    $('a[rel^=div]').click(function(){
        $('#' + this.rel).filter(":hidden").fadeIn().siblings(":visible").fadeOut();
    });
});

It doesn't fade out if you click the already active link, and it fades in and out both the new and old at the same time.
Make sure your divs are absolutely positioned as suggested by jfriend00 so that they are on top of each other. Otherwise, you will have to fadeOut first and then fadeIn after the fadeOut is finished.
$(document).ready(function(){
    $('#div_1, #div_2').addClass('js');
    $('a[rel^=div]').click(function(){
        var new = $('#' + this.rel).filter(":hidden");
        if (new.length) {
            new.siblings(":visible").fadeOut().promise().done(function(){
                new.fadeIn();
            });
        }
    });
});

Note: Only use one of the two scripts, not both.


text:
Q: When does navigationAction.navigationType == .linkActivated? In a WKWebView, every time I tap on a URL, the navigationType is .other. When does navigationType equal .linkActivated?

A: Very unlikely. Maybe you are interpreting the raw values wrong?
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    print(navigationAction.navigationType.rawValue)
    // -1 "other" seen when assigning the url programatically
    // 0 "linkActivated" a link with an href attribute was tapped
    // 3 "reload" page was refreshed
}

See the docs where you can click on the enumerations listed and and see their raw values


text:
Q: Mysql User can't connect via localhost but from outside i am trying to connect with my database on a Server via a localhost java app on the server. Everything works fine if i use a remote connection but as soon as my program runs on the server with the Database i can't connect.
I am using an Ubuntu 18.04 Server and i opened and checked the standard 3306 Port in my ufw setup.
I set up my Mysql User for the connections with the following commands
CREATE USER 'MYUSER'@'%' IDENTIFIED BY 'MYPASSWORD';
GRANT ALL PRIVILEGES ON *.* TO 'MYUSER'@'%';

I checked them via SELECT user, host FROM mysql.user; and get this result:
mysql> SELECT user, host FROM mysql.user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| MYUSER           | %         |
| debian-sys-maint | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
8 rows in set (0.00 sec)

Also in my cnf file i commented out
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
# bind-address        = 0.0.0.0

I am not sure how to check what the actual error is but i guess there are some wrong permissions in my setup. Has someone an idea what i am doing wrong or how i can figure out more details?


text:
Q: Guardar retorno dos campos em variáveis em python Fiz uma consulta em mysql com python e mostro o resultado:
cursor = db.cursor()
cursor.execute("SELECT Dias, HoraConsulta, HoraSaida, nome, Consulta, centrodb.LocalConsulta.Descricao, Contato FROM centrodb.RegistoConsultas LEFT OUTER JOIN centrodb.LocalConsulta ON centrodb.LocalConsulta.Id = centrodb.RegistoConsultas.`Local` LEFT OUTER JOIN centrodb.utentes ON centrodb.utentes.codigoutente = centrodb.RegistoConsultas.Utente LEFT OUTER JOIN centrodb.DiasSemana ON centrodb.DiasSemana.Id = centrodb.RegistoConsultas.DiaSemana")
myresult = cursor.fetchone()
print(myresult)

Em vez do print, pretendo guardar em variáveis cada coluna retornada na consulta no python

A: Conforme a documentação, o retorno de fetchone será uma tupla com os valores retornados do banco de dados. Assim, para criar variáveis, você pode fazer a desconstrução da tupla:
dias, hora_consulta, hora_saida, ... = myresult

Assim, cada valor da tupla será armazenada na respectiva variável.


text:
Q: Filtering ObservableCollection clears selection I have a page PeopleView which consists of a GridView which displays a list of People. I wish to provide a way of adding a removing from the list of People through a popup user control. The UserControl also allows for searching of all users to add more.
When the UserControl first opens it should display all the People, which it does and any People which are currently visible in the GridView should be already selected in the popup ListView. When a user selects addition People in the UserControl the People collection should be added to and the main GridView reflects this. This all works as intended.
The issue comes when I try to filter the list of People on the popup. This causes the FilteredPeople collection to be reset and as such removes all the selections from the ListView and therefore from the ObservableCollection which clears the GridView on the main page.
I want to search through the People whilst retaining the selection and add and remove from this list whilst searching.
This is the GridView on the main page:
<GridView x:Name="PeopleGridView"
                    Grid.Row="1"
                    Padding="116, 0, 0, 0"
                    ItemsSource="{Binding People}"
                    ItemTemplate="{StaticResource PeopleSelectItemTemplate}"
                    SelectionMode="Multiple" />

On this page is a popup usercontrol which allows for the adding and removing of People from this GridView. It also allows searching of people:
The xaml looks like this:
<TextBlock Style="{StaticResource PopupHeaderTextStyle}"
           Text="Enter person name:"
           TextWrapping="Wrap"/>

<TextBox Grid.Column="1"
         x:Name="SearchFieldTextBox"
         TextChanged="SearchField_Changed"
         Margin="20,0,20,0"
         Height="30" />

<ListView Grid.Row="1"
          Grid.ColumnSpan="2"
          SelectedIndex="1"
          SelectionMode="Multiple"
          ItemsSource="{Binding FilteredPeople}"
          extensions:ListViewExtensions.BindableSelection="{Binding People}"
          ItemTemplate="{StaticResource PeopleSearchItemTemplate}"
          HeaderTemplate="{StaticResource PeopleSearchHeaderTemplate}"/>

People and FilteredPeople are properties on my view model:
private ObservableCollection<PeopleViewModel> _people;
public ObservableCollection<PeopleViewModel> People
{
    get { return people; }
    set
    {
        if (Equals(people, value)) return;

        people = value;
        RaisePropertyChanged(() => People);
    }
}

private IEnumerable<PeopleViewModel> _filteredPeople;
public IEnumerable<PeopleViewModel> FilteredPeople
{
    get { return _filteredPeople; }
    set
    {
        if (_filteredPeople == value) return;

        _filteredPeople = value;
        RaisePropertyChanged(() => FilteredPeople);
    }
}

They are populated on load as such:
FilteredPeople = _allPeople = _peopleService.GetAll();
People = _allPeople.Where(p => p.Selected);

When the search text is entered the FilterPeople method is called on the viewmodel, which looks like this:
private void FilterPeople(string searchField)
{
    FilteredPeople = _allPeople.Where(p => p.Name.Equals(searchField));
    People = FilteredPeople.Where(p => p.Selected);
}

I am using the BindableSelection extension provided by the WinRT XAML Toolkit. When an item in the ListView is selected I update the underlying model object:
void People_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.Action == NotifyCollectionChangedAction.Add)
    {
        var person = e.NewItems[0] as PeopleViewModel;
        person.Selected = true;
        _personService.Save(person);
    }
    else if (e.Action == NotifyCollectionChangedAction.Remove)
    {
        var person = e.OldItems[0] as PeopleViewModel;
        person.Selected = false;
        _personService.Save(person);
    }
}

The issue is that the FilteredPeople collection is reset but I can't figure out of way of doing this. I can't find any examples online of how this could be done.
I'm using MVVM Cross is that is any use in this scenario
What am I doing wrong?


text:
Q: I found what looks like a crystal oscillator with an xdl stamp I haven't seen before I found an old transmitter with a crystal oscillator on it, when I looked at this I saw that it had "xdl 17.734475m" stamped onto it, I've only ever seen oscillators with just their frequency written on them.
I tried searching the internet but it just came up with Chinese websites, so I was wondering what the "xdl" meant (brand name?) and what the "m" after the number means.
Any thoughts?
P.s. I'm fairly new to this so I'm not sure my terms are completely correct.

A: The XDL could be either manufacturer, or (more likely) the series.
The "17.734475m" is the frequency, meaning 17.734475 MHz.
It seems like a silly frequency, but it's the PAL B/G/H color subcarrier (4×4.433618 MHz) (source: Wikipedia).


text:
Q: How to install jenkins under current user (not 'jenkins') on MAC OS X I have configured MAC OS X environment (SDKs, licenses, etc) under current user for build server and would like to reuse all the settings by a build agent. Jenkins was chosen as a good option but for some reason during installation it created a new user jenkins and launch the app under it, causing the environment setup to be not accessible (no SDKs, no licenses are found anymore).
Is it possible to install jenkins under current user?
Probably it could be installed under jenkins but then launched under current user?
Any other good options for me to consider are appreciated.

A: Try this: http://www.sailmaker.co.uk/blog/2013/04/02/advanced-jenkins-for-ios-and-mac/#Installing-Jenkins-itself

I'm also going to recommend installing Jenkins via Homebrew, to avoid
  some nonsense in Jenkins' own installer whereby it puts itself in
  /Users/Shared/. You really don't want that.

A: If you're free to reinstall however you'd like, I'd recommend re-installing as the user you want to use, using whatever type of install you prefer, and then simply copy over the old Jenkins data directory to the new installation's location, and then changing the permissions in that directory.
That is to say, the directory containing the config, plugin and job information (it may be something like /usr/lib/jenkins, but could vary).
Then, chown -R the data directory using the user:group info you want to use so Jenkins has access to the files.
I have used this type of method in the past to transfer all the data from one install to another totally separate install on the same box, and it has worked well (one could use this method to transfer the data to an install on another box, as well).
Note: I would highly recommend making a full backup of the data directory before doing this, in case anything goes awry.


text:
Q: Intercept onOptionsItemSelected I have a top level TabHost that implements the onCreateOptionsMenu method. And I want sub-activities (those within the tabs) to be able to intercept the options menu via onOptionsItemSelected. Like for example, in the options menu I have an item called, "Edit Note" and in one tab there is a ListView with a list of all the notes. I want the "Edit Note" item to be able to be viewed throughout the application, but the top level TabActivity doesn't know information such as title or id of the note.

A: Subclass the tabs, and have the parent call down to the active child in the OnOptionsItemSelected to give it the chance to handle it first.


text:
Q: Symfony Bundle constructor arguments not passed (Autowire not working for custom bundle) I am developing a bundle JohnCorpFormsBundle for my own symfony projects to share extended form logic.
However, when implementing the bundle in a project myproject I always get an error when I load a page in myproject that relies on bundle logic.
Error Message:

Too few arguments to function
JohnCorp\FormsBundle\Form\Builder\Core\ListFilterType::__construct(),
0 passed in /var/www/myproject/vendor/symfony/form/FormRegistry.php on line 81 and exactly 1 expected

It seems, the parameter $requestStack is not being passsed to ListFilterType::__construct() but shouldn't this work automatically using autowire?

MyProject: Controller-Code that causes the error:
// UserListController.php

use JohnCorps\FormsBundle\Form\Builder\Core\ListFilterType;
// ...

// this line runs into the error:
$listFilterForm = $this->createForm(ListFilterType::class);

Bundle: Form class:
// ListFilterType::class

namespace JohnCorp\FormsBundle\Form\Builder\Core;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\HttpFoundation\RequestStack;

class ListFilterType extends AbstractType
{

    protected RequestStack $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    //...

Bundle: Extension
// src/DependencyInjection/JohnCorpFormsExtension.php

namespace JohnCorp\FormsBundle\DependencyInjection;

class JohnCorpFormsExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yaml');
    }
}

Bundle: composer.json autoload
{
  "name": "johncorp/forms-bundle",
  "type": "symfony-bundle",

  ...

  "autoload": {
    "psr-4": {
      "JohnCorp\\FormsBundle\\": "src/"
    }
  }
}

I tried adding the arguments explicitly in the bundles services.yaml to ensure autowire is not a problem, but that does not change a thing.
Bundle: src/Resources/config/services.yaml:
services:
    JohnCorp\FormsBundle\Form\Builder\Core\ListFilterType:
        arguments:
            $requestStack: '@request_stack'

I am not sure if this is required or if it is loaded. (I include this in a src/DependencyInjection/JohnCorpFormsExtension.php)
I also tried adding the yaml-Code from above directly inside the projects services.yaml without any effect.

I also tried explicitly using autowire-Attribute in ListFilterType.php
// ListFilterType::class

public function __construct(
    #[Autowire(service: 'request_stack')] RequestStack $requestStack
)

A: If you use Symfony 6 , you just have to set the autowire and autoconfigure as true in your Bundle like this :
# yourBundle/src/Ressources/config/services.yaml
services:
    JohnCorp\FormsBundle\Form\Builder\Core\ListFilterType:
        autowire: true
        autoconfigure: true

here is the doc : service-container-services-load-example
then after that you have to inject your service in your BundleExtension:
<?php
//yourBundle/src/DepencencyInjection/YourBundleExtension
namespace App\YourBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

class YourBundleExtension extends Extension implements PrependExtensionInterface
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yaml');
    }
...
}


text: Q: Bitbucket в Xubuntu Xubuntu, стоит Netbeans 8.1 - попытался клонировать в него свой репозиторий с bitbucket. И каждый раз выдает при попытке pull/push окно Specify Git repository location с Repository URL https://bitbucket.org/username/nameofrepository.git. Не могу понять что подправить, с Git работает без проблем, в Windows тоже с Git и Bitbucket проблем нет. Хочу понять что тут не так?


text:
Q: How to copy selection top left pixel values in Paint.Net Especially while I am working css sprites for my html mock ups, I am using Paint.Net to focus on selected icon and read left and top and also width and height pixel values. So I can use them in my CSS class.
Is there easy way to copy left and top values into my clipboard and I do not need to manually type every time?
Here is SS for my issue;

A: Sorry, currently it is not possible.
I've tried to write a plugin for you, that copies mouse coordinates to clipboard, or show appropriate Messagebox, but it isn't possible as plugins cannot use C# 'using'  keyword.
You can write to paint.net authors for your feature request- it would be very easy for them to add to the program
Anyway, the code would look like:
#region UICode
bool Amount1 = true; // [0,1] Copy to clipboard
bool Amount2 = false; // [0,1] Show popup
#endregion

void Render(Surface dst, Surface src, Rectangle rect)
{
    Rectangle selection = EnvironmentParameters.GetSelection(src.Bounds).GetBoundsInt();

    int a = System.Windows.Forms.Cursor.Position.X;
    // or int a = Selection.Left;
    int b = System.Windows.Forms.Cursor.Position.Y;
    // or int b = Selection.Top;

    if (Amount1)
    {
        Clipboard.SetText(a.ToString() + ", " + b.ToString());
    }

    if (Amount2)
    {
        MessageBox.Show(a.ToString() + ", " + b.ToString());
    }
}


text:
Q: Google Dataflow spending hours estimating input size I'm fairly new to Google Dataflow and I am finding that the service spends several hours estimating the input file size before actually processing data, and will often do several recounts for large input collections before failing.  I'm using Apache Beam 2.9 and the io.ReadFromText method.
The logs start with a comment about beginning estimation of input file size and continue to log an update every 10k files counted.
Is there a way to skip this step or to significantly increase the pace in which it does the count?

A: The Python ReadFromText source is based on FileBasedSource. If you look at the code for it, you can find that its estimate_size method is inefficient for a very large set of files.
As we discussed in the comments, you may be able to improve this bottleneck by manually partitioning the range of files. For example, if your files are gs://my_bucket/file001, gs://my_bucket/file002, ... gs://my_bucket/file999, you should be able to add 10 sources, something like so:
p = Pipeline()
file_lines = (
  [p | ReadFromText('gs://my_bucket/file%s*' % i) for i in range(10)]
  | beam.Flatten())

This should help your pipeline scale for a case like this.

As for a permanent solution... I imagine that one could try to propose improvements to the source itself, so that a future version may have better performance.
There are also transforms based on Java's FileIO transforms that we are planning to implement. That may be helpful as well. But it's not so near in the horizon.


text:
Q: Selecting Specific record among multiple records in association Rails I have a model called User and associated model Message. So user can have many messages. I have 4 columns in messages table named sent_at, opened_at, clicked_at and email id.
In message table email id is not unique. User would have sent multiple emails. So for a user in messages table he can see same email multiple times.
eg: If user_id is 7 and I need to find out the recent opened emails using the association. I need the records of all the users who have opened the mail recently.
I used this:
User.find(7).messages.select(*).group(:email_id).having("max(opened_at)")

But its giving men the error.
Any help is largely appreciated!! Thanks in advance!!

A: I got the answer after doing lot of research
a = User.find(7).messages.order("opened_at,clicked_at").group_by(&:email_id)

This will return hash. I will convert this to array using a.to_a and from there I can access the entire active record


text:
Q: Is there a way to add 3 seconds to the CountDownTimer? Is there a way to add 3 seconds to the CountDownTimer when the user gets 3 answers correct (nonconsecutive) and when the timer is running? For an example if the user gets 3 answers correct when the timer displays 10 and it should increase to 13 seconds.
This is the code I've implemented and it doesn't work.
class GamePage : AppCompatActivity() {
    var correctCount = 0
    var wrongCount = 0
    val timer: TextView = findViewById(R.id.timer)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game_page)

        val finish = Intent(this, GameOver::class.java)
        var timeCount : Long = 50000

        fun counter(timeCount: Long){

            var countdownTimer = object : CountDownTimer(50000, 1000) {

            override fun onTick(millisUntilFinished: Long) {
                timer.text = "Seconds remaining: " + millisUntilFinished / 1000

            }

            @Override
            override fun onFinish() {
                if (correctCount !=0 && correctCount % 5 == 0) {
                    finish.putExtra("correct", correctCount.toString())
                finish.putExtra("wrong", wrongCount.toString())
                startActivity(finish)
                } else {
                    counter(5000);
                }

            }
        }.start();
        }
        counter(timeCount)
}

A: new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
       //here you can have your logic to set text to edittext
    }

    public void onFinish() {
        mTextField.setText("done!");
    }

}.start();

A: Why not coroutines?
You can easily modify the counter, and the timer will increase.
    fun counter (timeCount: Long) {
        var counter = timeCount
        lifecycleScope.launch(Dispatchers.Main) {
            while (counter > 0) {
                delay(1000L)
                counter -= 1000
                if (isAnswerCorrect()) {
                    counter += 3 * 1000L
                }
            }
            // timer finished
        }
    }

A: You could create a countdown Flow like this:
    fun countdownFlow(duration: Duration) = flow {
        val endTime = System.currentTimeMillis() + duration.inWholeMilliseconds
        while(isActive) {
            val timeRemaining = (endTime - System.currentTimeMillis()).coerceAtLeast(0L).milliseconds
            emit(timeRemaining)
            if (timeRemaining == Duration.ZERO) break
            delay(1)
        }
    }

And then use it like this, where you cancel your coroutine and restart it if you want to increase the timer.
class GamePage : AppCompatActivity() {
    var correctCount = 0
    var wrongCount = 0
    val timer: TextView = findViewById(R.id.timer)

    private var remainingTime = Duration.ZERO
    private var countdownJob: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game_page)
        startCountdown(50.seconds)
    }

    private fun startCountdown(duration: Duration)
        countdownJob?.cancel()
        remainingTime = duration
        countdownJob = lifecycleScope.launch {
            countdownFlow(duration).collect {
                remainingTime = it
                timer.text = "Seconds remaining: ${it.inWholeSeconds}"
            }

            if (correctCount !=0 && correctCount % 5 == 0) {
                val finish = Intent(GamePage.this, GameOver::class.java).apply {
                    putExtra("correct", correctCount.toString())
                    putExtra("wrong", wrongCount.toString())
                }
                startActivity(finish)
            } else {
                startCountdown(5.seconds)
            }
        }
    }

    private fun addTime(duration: Duration) {
        startCountdown(remainingTime.milliseconds + duration)
    }

}


text:
Q: Java Generics Error
Possible Duplicate:
Java how to: Generic Array creation
Error: Generic Array Creation

I am getting this error:
Cannot create a generic array of T

This is my code (error on line 6):
1    public class HashTable<T> {
2
3        private T[] array;
4
5        HashTable(int initSize) {
6            this.array = new T[initSize];
7        }
8    }

I am wondering why this error is appearing and the best solution to fix it. Thanks.
UPDATE:

I adjusted my code so that the array is taking in linked lists instead, but I am getting a new error.

Here is my error:
Cannot create a generic array of LinkedList<T>

Here is my code (error on line six):
1    public class HashTable<T> {
2
3        private LinkedList<T>[] array;
4
5        HashTable(int initSize) {
6            this.array = new LinkedList<T>[initSize];
7        }
8    }

Is this error for the exact same reason? I was just assuming I could create generic linked lists and just store them in the array.

A: Yes, generic arrays cannot be created.
The best workaround I know is to use collections instead:
private List<T> list;

.......

list = new ArrayList<T>();

A: Generic arrays can be created via reflection (although an unsafe cast is required), you just need to pass the class as a parameter (assuming that the following method is inside a class that defines a <T> type parameter):
@SuppressWarnings("unchecked")
public T[] createArray(Class<T> klass, int size) {
    return (T[]) Array.newInstance(klass, size);
}

For example, in your case:
HashTable<Integer> t = new HashTable<Integer>();
Integer[] intArray = t.createArray(Integer.class, 4);
intArray[0] = 1; intArray[1] = 2;
intArray[2] = 3; intArray[3] = 4;

System.out.println(Arrays.toString(intArray));
> [1, 2, 3, 4]

A: You could NOT create a T (in Java), but an T[] is internally the same as
 Object[].
public class HashTable<T> {

    private T[] array;

    @SuppressWarnings("unchecked")
    HashTable(int initSize) {
        this.array = (T[]) new Object[initSize];
    }
}

(Will compile, I checked)
Due to comments of newacct, it would be probably better just to use an Object[] and to cast the items to T.
public class HashTable<T> {

    private Object[] array;

    public HashTable(int initSize) {
        this.array = new Object[initSize];
    }

    public void put(String pKey, T pItem) {
       ...
       array[x] = pItem;
       ....
    }
    public T get(String pKey) {
       ...
       return (T) array[x];
    }
}


text:
Q: Android display value from JSON Object I have json that looks likes this:
{"type":"FeatureCollection","metadata":{"generated":1428783374000,"url":"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-04-04&endtime=2015-04-05","title":"USGS Earthquakes","status":200,"api":"1.0.17","count":328},"features":[{"type":"Feature","properties":{"mag":1.3,"place":"8km SSE of Talmage, California","time":1428191575500,"updated":1428359465102,"tz":-420,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/nc72426686","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=nc72426686&format=geojson","felt":null,"cdi":null,"mmi":null,"alert":null,"status":"reviewed","tsunami":0,"sig":26,"net":"nc","code":"72426686","ids":",nc72426686,","sources":",nc,","types":",cap,general-link,geoserve,nearby-cities,origin,phase-data,scitech-link,tectonic-summary,","nst":12,"dmin":0.08508,"rms":0.06,"gap":154,"magType":"md","type":"earthquake","title":"M 1.3 - 8km SSE of Talmage, California"},"geometry":{"type":"Point","coordinates":[-123.1233333,39.0688333,7.27]},"id":"nc72426686"},

My Main Activity code looks like this:
public class MainActivity extends ActionBarActivity {

private static final String LOG_TAG ="JSON STRING";
TextView httpData;
HttpClient client;
JSONObject json;

final static String URL = "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-04-04&endtime=2015-04-05";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    httpData = (TextView) findViewById(R.id.tvHttp);
    client = new DefaultHttpClient();

    new Read().execute("features");

}

public JSONObject lastEvent(String event) throws ClientProtocolException, IOException, JSONException {
    StringBuilder url = new StringBuilder(URL);

    HttpGet get = new HttpGet(url.toString());
    HttpResponse response = client.execute(get);

    int status = response.getStatusLine().getStatusCode();

    if ( status == 200 ) {
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity);
        JSONArray timeline = new JSONArray(data);
        JSONObject last = timeline.getJSONObject(0);

        return last;
    }
    else {
        Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT);
        return null;
    }
}

public class Read extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        try {
            json = lastEvent("title");
            return json.getString(params[0]);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result ) {
       httpData.setText(result);
    }
}

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
My activity_main.xml looks like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<ScrollView android:layout_height="fill_parent" android:layout_width="fill_parent">
<TextView android:text="Loading Data" android:id="@+id/tvHttp" android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</ScrollView>

I am trying to get the value of 'title' from the first element of the JSONArray, but instead I just get a blank Text View screen. I am somewhat new to Java and Android in general, so if a different format (such as XML) is easier for me to work with, I can try that too. Any insight or hints is greatly appreciated.

A: Okay, assuming we have the JSON you posted
{"type":"FeatureCollection","metadata":{"generated":1428783374000,"url":"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-04-04&endtime=2015-04-05","title":"USGS Earthquakes","status":200,"api":"1.0.17","count":328},"features":[{"type":"Feature","properties":{"mag":1.3,"place":"8km SSE of Talmage, California","time":1428191575500,"updated":1428359465102,"tz":-420,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/nc72426686","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=nc72426686&format=geojson","felt":null,"cdi":null,"mmi":null,"alert":null,"status":"reviewed","tsunami":0,"sig":26,"net":"nc","code":"72426686","ids":",nc72426686,","sources":",nc,","types":",cap,general-link,geoserve,nearby-cities,origin,phase-data,scitech-link,tectonic-summary,","nst":12,"dmin":0.08508,"rms":0.06,"gap":154,"magType":"md","type":"earthquake","title":"M 1.3 - 8km SSE of Talmage, California"},"geometry":{"type":"Point","coordinates":[-123.1233333,39.0688333,7.27]},"id":"nc72426686"},

It's an object. We want to get into the array in key features, and we want the title key in the first element (which is an object) of that array.

Looking at your lastEvent function. You pass a String called event. But that is never used.
public String lastEvent(String event) throws ClientProtocolException, IOException, JSONException {
    StringBuilder url = new StringBuilder(URL);

    HttpGet get = new HttpGet(url.toString());
    HttpResponse response = client.execute(get);

    int status = response.getStatusLine().getStatusCode();

    if ( status == 200 ) {
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity);
        // data now contains the json object I posted above
        // So we fetch it
        JSONObject timeline = new JSONObject(data);
        // We want the features array
        JSONArray features = timeline.getJSONArray("features");
        // The first element
        JSONObject first = timeline.getJSONObject(0);
        // The titles attribute. I assume lastEvent("titles")
        // is the way you call this function
        String last = first.getString(event);

        return last;
    }
    else {
        Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT);
        return null;
    }
}

Note I changed the return type of lastEvent, because we are getting a String from the object. The first parameter event now is for the field we want to get, I think that was your intention, because you call it like that in the AsyncTask.

Also, check your Logcat! A JSONException might be thrown, that you catch and print its message and return null. Returning null, and later calling httpData.setText(null) would result in an empty TextView

Edit: Also your doInBackground function doesn't need to call getString() anymore on the return value of lastEvent.
I don't know how generic your  AsyncTask needs to be. But the code I wrote might help you to get where you want to be.


text:
Q: How do I prevent this form from being submitted if errors still exist? Below function always submit the form at the first render of the component even if firstName and lastName fields are empty.
const [formErrors, setFormErrors] = useState({});

const registerUser = () => {
    if (firstName === "") {
      setFormErrors((prev) => {
        return { ...prev, firstName: "Firstname is required!" };
      });
    }

    if (lastName === "") {
      setFormErrors((prev) => {
        return { ...prev, lastName: "Lastname is required!" };
      });
    }

    if (Object.keys(formErrors).length === 0) {
      console.log("Form Submitted");
    } else {
      console.log("Failed");
    }
}

At first render, the value of Object.keys(formErrors).length is 0, but the errors are shown on the screen, weird!.
I tried to use useRef which worked, but it doesn't display the errors on screen because the component doesn't rerender with useRef.
How do I prevent this form from being submitted if errors still exist?
Thank You

A: Your problem is that you have called set state (formErrors) and then you try to read it immediately. So when you set it, it hasn't been updated yet, you are reading stale data.
To fix it use some local variable in that function (initially you may want to initialize it with state data) to keep track of errors, and then at the end when you are done with it, put that in state.
Something like this
const registerUser = () => {

    let errors = {
        ...formErrors
    }

    if (firstName === "") {
        errors.firstName = "Firstname is required!"
    }

    if (lastName === "") {
        errors.lastName = "lastName is required!"
    }

    if (Object.keys(errors).length === 0) {
        console.log("Form Submitted");
    } else {
        console.log("Failed");
    }

    setFormErrors(errors)
}


text:
Q: Add a mask to the webcam view in the screen I need to add a webcam picture option to take pictures of documents. However, it's importante that the user take the picture with the document in a specific position. With this in mind, a layout requirement is to add a mask in the webcam picture screen, like the image below:

Add the webcam picture option is easy, but there is a way to add/draw a mask to it?

A: Just place a semi transparent div over the top of the canvas that the webcam is rendering to.


text:
Q: How to retrieve image data send from iOS Swift through Alamofire on Heroku Servlet? Hello I have tried to retrieve image that was send from iOS to Heroku Servlet, but i get the following error: "Response status code was unacceptable: 405"
This is my request :
var test = UIImage(named: "test")
    var imageData = UIImagePNGRepresentation(test!)

    let base64String = imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

    let parameters = [
        "img": base64String
    ]

    Alamofire.request(.POST, "https://myapp.com/",parameters:parameters).validate()
        .responseString { (string) in
            print(string)
    }

And this is my doPost method on Heroku:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // TODO Auto-generated method stub
    super.doPost(req, resp);
    String imageBase64 = req.getParameter("img");
     BASE64Decoder decoder = new BASE64Decoder();
     byte[] imgBytes = decoder.decodeBuffer(imageBase64);
      bufImg = ImageIO.read(new ByteArrayInputStream(imgBytes));
      resp.getWriter().write(bufImg.getWidth());

}

Can you advice how can i fix it? Thanks in advance :)


text:
Q: "401 Unauthorized : The audience is invalid" Error with Azure AAD for .Net Core APIs Azure AD by default generates Application URI in below format.
api://<<Client_Id>>
but When you change Application URI with "https://xyz.onmicrosoft.com/<<Client_Id>>" and the token generated using Auth Code Grant or Client Credential flow, if passed to API for Authorization, you will get below error.
WWW-Authenticate: Bearer error="invalid_token", error_description="The audience 'https://xyz.onmicrosoft.com/<<Client_Id>>' is invalid"

A: To solve this, AppSettings should be added as mentioned below,
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "xyz.onmicrosoft.com",
    "TenantId": <<Tenant_Id>>,
    "ClientId": <<Client_Id>>,
    **"Audience": "https://xyz.onmicrosoft.com/<<Client_Id>>"**
  }

Note: If you are using default URI then Audience is not required but with custom Application URI, Audience needs to be added.


text:
Q: Force Close With Viewpager I'm developing an application retrieves the images from the server and store it in the sdcard.
I store the paths of the images in a local database, then i use them while using the viewpager to display them.
When there are only two images, everything works fine, but when there are more than two images , the app stops, and it happens while sliding between images. When i slide more than two times  , the app stops immediately.
class RequestLoadingMeals extends AsyncTask <Void, Void, Void> {
     protected void onPreExecute(){
          super.onPreExecute();
          PD = new ProgressDialog(Meals.this);
          PD.setMessage("Loading Meals, Please wait...");
          PD.setIndeterminate(false);
          PD.setCancelable(true);
          PD.setProgressStyle(ProgressDialog.STYLE_SPINNER);
          PD.show();
     }

    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub

        myDatabaseHandler.openToRead();
        Cursor meals_cursor = myDatabaseHandler.queueSomeMeals(rest_name);
        if (meals_cursor.moveToFirst())
          {
             do
             {
                 try{
                 images.add(meals_cursor.getString(meals_cursor.getColumnIndex(DatabaseHandler.KEY_MEAL_IMAGE_PATH)));
                 } catch (Exception h){
                 }
             }while (meals_cursor.moveToNext());
          }
        myDatabaseHandler.close();
        return null;
    }
    protected void onPostExecute(final Void x) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(Meals.this, images);
        ViewPager myPager = (ViewPager) findViewById(R.id.mypager);
        myPager.setAdapter(adapter);
        myPager.setCurrentItem(0);
        PD.dismiss();
    }
}

Here is the viewpager class
public class ViewPagerAdapter extends PagerAdapter {

 Activity activity;
 ArrayList<String> imageArray = new ArrayList<String>();

 public ViewPagerAdapter(Activity act, ArrayList<String> images) {
      imageArray = images;
      activity = act;
     }
 public int getCount() {
  return imageArray.size();
 }

 public Object instantiateItem(ViewGroup collection, int position) {
  ImageView view = new ImageView(activity);
  view.setLayoutParams(new LayoutParams());
  view.setScaleType(ScaleType.FIT_XY);
  String path = imageArray.get(position);
  Bitmap myBitmap = BitmapFactory.decodeFile(path);
  view.setImageBitmap(myBitmap);
  ((ViewPager) collection).addView(view, 0);
  return view;
 }
 @Override
 public boolean isViewFromObject(View arg0, Object arg1) {
  return arg0 == ((View) arg1);
 }

 @Override
 public Parcelable saveState() {
  return null;
 }

}

Logcat:
12-02 12:46:38.956: E/AndroidRuntime(431): FATAL EXCEPTION: main
12-02 12:46:38.956: E/AndroidRuntime(431):java.lang.UnsupportedOperationException:Required method destroyItem was not overridden
12-02 12:46:38.956: E/AndroidRuntime(431):  at android.support.v4.view.PagerAdapter.destroyItem(PagerAdapter.java:192)
12-02 12:46:38.956: E/AndroidRuntime(431):  at android.support.v4.view.PagerAdapter.destroyItem(PagerAdapter.java:124)
12-02 12:46:38.956: E/AndroidRuntime(431):  at android.support.v4.view.ViewPager.populate(ViewPager.java:1036)
12-02 12:46:38.956: E/AndroidRuntime(431):  at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
12-02 12:46:38.956: E/AndroidRuntime(431):  at android.support.v4.view.ViewPager$3.run(ViewPager.java:244)
12-02 12:46:38.956: E/AndroidRuntime(431):  at android.os.Handler.handleCallback(Handler.java:587)
12-02 12:46:38.956: E/AndroidRuntime(431):  at android.os.Handler.dispatchMessage(Handler.java:92)
12-02 12:46:38.956: E/AndroidRuntime(431):  at android.os.Looper.loop(Looper.java:123)
12-02 12:46:38.956: E/AndroidRuntime(431):  at android.app.ActivityThread.main(ActivityThread.java:3683)
12-02 12:46:38.956: E/AndroidRuntime(431):  at java.lang.reflect.Method.invokeNative(Native Method)
12-02 12:46:38.956: E/AndroidRuntime(431):  at java.lang.reflect.Method.invoke(Method.java:507)
12-02 12:46:38.956: E/AndroidRuntime(431):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-02 12:46:38.956: E/AndroidRuntime(431):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-02 12:46:38.956: E/AndroidRuntime(431):  at dalvik.system.NativeStart.main(Native Method)

A: Add this in your ViewPagerAdapter:
@Override
public void destroyItem(View collection, int position, Object view) {
     ((ViewPager) collection).removeView((View) view);
}

and may I suggest not to do heavy long running tasks in instantiateItem. This is bad idea to decode images on UI thread.


text:
Q: How do I achieve thread safety in following code I'm reading about thread safety and synchronized keyword, but I'm stuck figuring out how it's implemented correctly.
I have a scenario where Thread A saves data to a Buffer while Thread B reads the data and saves it to the database.
How can I achieve thread safety with the following code?
By thread safety I mean Thread B wont start until Thread A finished it's job and same applies to Thread A.
public class Main {
    public static void main(String args[]) throws InterruptedException {

        LinkedBlockingQueue<Document> queue = new LinkedBlockingQueue<>();
        ProducerThread mProducer = new ProducerThread(queue);
        ConsumerThread mConsumer = new ConsumerThread(queue);
        new Thread(mProducer).start();
        new Thread(mConsumer).start();
    }
}

--
public class ProducerThread implements Runnable {
    private LinkedBlockingQueue<Document> queue;

    public ProducerThread(LinkedBlockingQueue<Document> queue) {
        this.queue = queue;
    }
    @Override
    public void run() {
        while(true) {
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            Document document = new Document("timeAdded", timestamp);
            try {
                queue.put(document);
                System.out.println("Document added " + document.toString());
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

--
public class ConsumerThread implements Runnable {
    private LinkedBlockingQueue<Document> queue;
    private Database mDatabase;

    public ConsumerThread(LinkedBlockingQueue<Document> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
            try {
                Document doc;
                mDatabase = Database.getInstance();
                if (Client.isAlive()) {
                    while (queue.take() != null) {
                        mDatabase.insert(queue.take());
//                        Thread.sleep(10);
                        System.out.println("Document consumed " + queue.take().toString());
                        if (!Client.isAlive()) {
                            wait();
                            Client.reconnect();
                        }
                    }
                } else {
                    wait();
                }
            } catch(InterruptedException | IllegalMonitorStateException e){
                e.printStackTrace();
            }
    }
}

I get the following output
> Document added{{timeAdded=2018-04-22 13:20:27.88}}
> Document{{timeAdded=2018-04-22 13:20:27.88}} Document added
> Document{{timeAdded=2018-04-22 13:20:28.881}} Document added
> Document{{timeAdded=2018-04-22 13:20:29.882}} Document added
> Document{{timeAdded=2018-04-22 13:20:30.882}} Consumed
> Document{{timeAdded=2018-04-22 13:20:30.882}} Document added
> Document{{timeAdded=2018-04-22 13:20:31.883}} Document added
> Document{{timeAdded=2018-04-22 13:20:32.883}} Consumed
> Document{{timeAdded=2018-04-22 13:20:33.884}} Document added
> Document{{timeAdded=2018-04-22 13:20:33.884}} Document added
> Document{{timeAdded=2018-04-22 13:20:34.885}} Document added
> Document{{timeAdded=2018-04-22 13:20:35.885}} Document added
> Document{{timeAdded=2018-04-22 13:20:36.886}} Consumed
> Document{{timeAdded=2018-04-22 13:20:36.886}} Document added

A: I don't know if this helps, but I would write a third class called ProductionProcess or something like that...
Short additional explanation: The ProductionClass holds the queue which stores the single Document objects. The Producer thread starts to "produce" objects as long as the queue (At the moment size of 10) is full. Whenever a slot in this queue gets free because the Consumer thread removed a Document object. The Producer thread receives a signal and starts "producing" Document objects again until the queue is full. The complete source code should be thread-safe.
public class ProductionProcess
{
private static final int CAPACITY;
private final Queue QUEUE;

private final Lock LOCK;
private final Condition BUFFER_FULL;
private final Condition BUFFER_EMPTY;

static
{
    CAPACITY = 10;
}

ProductionProcess()
{
    this.QUEUE = new LinkedList <Document> ();
    this.LOCK = new ReentrantLock();

    this.BUFFER_FULL = this.LOCK.newCondition();
    this.BUFFER_EMPTY = this.LOCK.newCondition();
}

public void produce() throws InterruptedException
{
    this.LOCK.lock();

    try
    {
        while(ProductionProcess.CAPACITY == this.QUEUE.size())
        {
            System.out.println(Thread.currentThread().getName() + " : Buffer is full, waiting!");
            this.BUFFER_FULL.await();
        }

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Document document = new Document("timeAdded", timestamp);

        if(true == this.QUEUE.offer(document))
        {
            System.out.printf("Added to queue: " + document);
            this.BUFFER_EMPTY.signalAll();
        }
    }
    finally
    {
        this.LOCK.unlock();
    }
}

public void receive() throws InterruptedException
{
    this.LOCK.lock();

    try
    {
        Database mDatabase = Database.getInstance();

        while(0 == this.QUEUE.size())
        {
            System.out.println(Thread.currentThread().getName() + " : Buffer is empty, waiting!");
            this.BUFFER_EMPTY.await();
        }

        Document mDocument = (Document) this.QUEUE.poll());

        if(null != mDocument)
        {
            mDatabase.insert(mDocument);
            System.out.printf("Consumed from queue: " + document);
            System.out.println(Thread.currentThread().getName() + " : Signalling that buffer may be empty now");
            this.BUFFER_FULL.signalAll();
        }
    }
    finally
    {
        this.LOCK.unlock();
    }
}
}

After that use it like this...
ProductionProcess process = new ProductionProcess();

Runnable runnableProducer = new Runnable() {
    @Override public void run()
    {
        while(true)
        {
        try
        {
            process.produce();
            Thread.sleep(1000);
        }
        catch(InterruptedException exc)
        {
            exc.printStackTrace();
        }
        }
    }
}

Runnable runnableConsumer = new Runnable() {
    @Override public void run()
    {
        while(true)
        {
        try
        {
            process.receive();
            Thread.sleep(1000);
        }
        catch(InterruptedException exc)
        {
            exc.printStackTrace();
        }
        }
    }
}

new Thread(runnableProducer).start();
new Thread(runnableConsumer).start();

I don't test it extensive but it should work. If it doesn't work just comment it...
Moreover its not my code if you can speak german watch this link.


text:
Q: Spring Security: SecurityContextHolder.getContext().getAuthentication() returns null after user registering user and redirecting to after login page After user is registered successfully, i am trying to redirect user to after login page and trying to get the Active user from SecurityContextHolder.getContext().getAuthentication(); which is returning null.
Here is how i am setting context when user is successfully registered
 UsernamePasswordAuthenticationToken authenticatedUser = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
 authenticatedUser.setDetails(userDetails);

 if(authenticatedUser.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
 }

Then i am redirecting user to x page using response.sendRedirect(url);
In the controller method i am trying to the current user as
@RequestMapping("/<pattern>")
public @ResponseBody <method_name>(HttpServletRequest req,HttpServletResponse resp){
     Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if(auth==null){
            System.out.println("this is null");
        }
        else{
          // do something
        }
}

I am seeing the text in console as "this is null".
How to get retain the currentuser/Principal from SecurityContext() through out the user period till user logs out.

A: I got the solution.
The problem was with the pattern attribute for the  tag for that specific URI group.
Earlier it was /path/* and it was failing. I changed it to /path/** and it worked.
It would be helpful if someone can explain between these two pattern matching(/* and /**).


text:
Q: Computing the Frobenius normal form I was wondering whether someone could give me an example how one actually determines the Frobenius normal form of a given matrix. Further, it seems hard to find an example where the new basis is calculated so that a given matrix is in Frobenius normal form. I really tried to find an example where this is done, but most books just use this form as a theoretical example rather than actually calculating this form?
A short summary how you would proceed to calculate the Frobenius normal form and the basis would be more than enough, too.

A: If this is often treated as mostly a theoretical construction, this is probably because there is no really easy procedure for finding the rational canonical form, even though its existence is of fundamental importance.
However here is a basic algorithmic way to compute it.
Write down the matrix $XI-A$, a matrix with polynomial entries, the one whose determinant defines the characteristic polynomial. Now apply the Smith normal form algorithm over the principal ideal domain $K[X]$ of polynomials. This will produce a diagonal matrix with on the main diagonal (monic) polynomials$~P_i$, each of which divides the next, the last of which is the minimal polynomial, and the product of which is the characteristic polynomial. The list will usually start with many occurrences of the constant polynomial$~1$, which can be ignored; for every remaining polynomial write down its companion matrix, and string these together in order to get the block diagonal matrix which is the Frobenius normal form of$~A$.
A more "linear algebraic" way to find the Frobenius normal form is to first find the minimal polynomial of $A$. If it has degree$~n$ then it is also the characteristic polynomial and the Frobenius normal form will just be its companion matrix. If not then the companion matrix of the minimal polynomial will just be the final block in the Frobenius normal form; to find the other blocks, find a vector$~v$ not annihilated by any polynomial in$~A$ of degree less than the minimal polynomial (which is certain to exist, in fact most vectors have this property), take the ($A$-stable) subspace $W$ of$~V$ generated by$~v$ and its repeated images by$~A$, and continue recursively with the linear operator that $A$ induces in the quotient space$~V/W$ (there also exists a $A$-stable complementary subspace to $W$, but I think finding one is unnecessary, and working with the quotient is easier).


text:
Q: Необходимо сравнить элементы массива с ключами объекта Есть функция, которая принимает первым параметром объект, вторым - массив из цепочки свойств, по которому нужно пройти, чтобы получить значение.
Если какое-то из свойств не найдено или массив пустой - функция возвращает undefined.
Пример:
const obj = {
  a: {
    b: {
      c: {
        d: 'Привет!'
      }
    }
  }
}

optionalChaining(obj, ["a", "b", "c", "d"]) // Привет

optionalChaining(obj, ["a", "b", "c", "d", "e"]) // undefined

A:

function optionalChaining(obj, path){
    let cur = obj;

    for(prop of path){
        if(cur[prop])
            cur = cur[prop];
        else
            return undefined;
    }

    return cur;
}

const obj = {a: {b: {c: {d: 'Привет!'}}}};

console.log(optionalChaining(obj, ['a', 'b', 'c', 'd']));
console.log(optionalChaining(obj, ['a', 'b', 'c', 'd', 'e']));


text:
Q: Android Phonegap screen rotation lock kills my app i'm having problems with my application, i added an manifest that must prevent screen rotation but when i rotate the screen it kills the app.
Here is my code:
public class avantdroidActivity extends DroidGap {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.main);
    super.clearCache();
    super.loadUrl("file:///android_asset/www/redir.html");
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}

My AndroidManifest.Xml:
<activity android:name="org.apache.cordova.DroidGap" android:label="@string/app_name" android:configChanges="keyboard|orientation|keyboardHidden"> <intent-filter> </intent-filter> </activity>

What im doing wrong? Thanks!

A: Why are you calling?
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

You can just set your activity orientation in your AndroidManifest.
Just add android:screenOrientation="portrait" to your activity tag.


text:
Q: How can I measure a voltage between two conductive surfaces that are completely isolated? I am in the middle of diagnosing an issue where the case of my battery box (steel) is floating at a potential of 120V relative to the negative terminal of the battery (350V). I've started removing connections but in this process i've been probing a lot.. The battery is completely isolated by several layers from the box. It's modular so i've removed one of the modules and placed it 2 meteres away, on top of two wooden blocks and a towel on a bench.
How is it possible I can measure a solid voltage (In this case, roughly 10V) between a battery terminal and the battery box which is 2 meteres and multiple insulators away? I then started probing random metal surfaces in the area and all showed a voltage, what is happening here? How is the multimeter showing a solid voltage when there is no current path?

A: *

*Voltage is a measure of how much energy a unit charge would gain/loose if it moved through the electric field between two points.  Remember that 1V = 1 Joule per Coulomb.

But its just a measure of how much energy would be lost or gained.  That   potential exists weather or not you actually move any charges.  So voltage can certainly exist without current.

*

*Objects can charge up to all kinds of voltages via static electricity.

*Nothing is ever "completely isolated".  Insulators including the towel, wood blocks, the bench, and even air don't have infinite resistance.  It may be very high but its not limitless.


text:
Q: Extracting sub objects from list in I have the following list in R
> str(Grades.Good)
List of 2
 $ FALSE: Named num [1:10] 89 74 64 61 55 80 78 73 57 87
  ..- attr(*, "names")= chr [1:10] "Bettie" "Dona" "Frances" "Gerri"       ...
 $ TRUE : Named num [1:5] 94 97 94 91 92
  ..- attr(*, "names")= chr [1:5] "Alana" "Consuela" "Elaine" "Kenyatta" ...

I am trying to extract the names from the second item, Grades.Good[2].  I have tried:
> names(Grades.Good[2])
[1] "TRUE"
> names(Grades.Good)[2]
[1] "TRUE"
> names(Grades.Good$TRUE)
Error: unexpected numeric constant in "names(Grades.Good$TRUE"

What is the best way to extract a character vector with just the names "Alana" "Consuela" "Elaine" "Kenyatta" ...?


text:
Q: Drools rule to compare two fields of two pojos i've got the following Java classes:
public class A {

    private String text;

    public A(){
    }

    public void setText(String text) {
        this.text=text;
    }

    public String getText() {
        return text;
    }

}

and
public class B {

    private A firstField;
    private A secondField;
    private Boolean success = false;

    public B(){
    }

    public void setFirstField(A firstField) {
        this.firstField=firstField;
    }

    public A getFirstField(){
        return firstField;
    }

    public void setSecondField(A secondField) {
        this.secondField=secondField;
    }

    public A getSecondField(){
        return secondField;
    }

    public void setSuccess(Boolean success) {
        this.success=success;
    }

    public Boolean isSuccess(){
        return success;
    }

}

i'm trying to write a Drools rule that will allow me to compare the text attribute of firstField to that of secondField in class B. This is my java code:
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("myrule.drl"), ResourceType.DRL);
    KnowledgeBase kbase = kbuilder.newKnowledgeBase();
    StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();
    B obj = new B();
    ksession.execute(obj);

and these are the contents of myrule.drl:
package test
import my.package.A
import my.package.B

rule "myrule"
no-loop
    when
        $obj : B(firstField.getText().equals(secondField.getText()))
    then
        modify($obj){
            setSuccess((Boolean)true);
        }
end

which is unfortunatelly not working, what am i doing wrong? Thanks in advance

A: It is really strange that your code even compile because ksession.execute() expects a Command<T> and not a simple B: http://docs.jboss.org/drools/release/5.6.0.Final/drools-expert-docs/html/ch03.html#d0e3581
In your simple scenario, what you are looking for (I guess) is a Command to insert the B object and another to fire all the rules.
You can achieve this by using a BatchExcecution command:
B obj = new B();
List cmds = new ArrayList();
cmds.add( CommandFactory.newInsertObject(obj) );
ksession.execute( CommandFactory.newBatchExecution( cmds ) );

In the exampleabove, the fire all rules command is implicit.
Hope it helps,


text:
Q: Consuming WebServices in Angular Frontend We have an requirement to consume (old ASMX) Web Services in our client side project (Angular).

*

*The first issue is related to CORS as both projects (Web-Service / Frontend) are on different domains.

*And secondly we don't have source code for that Web Service.

Is there is any possibility to host that Web Service in our domain? equally do we have any other possibilities?
URL Rewrite is one of the possibility to achieve that task.

*

*Create Sub Website under Default Website in IIS.

*Select URL Rewrite

*Create new In-Bound Rule as below:

*Web.Config will be like as below:
<rewrite>
<rules>
    <rule name="ReverseProxyInboundRule1" stopProcessing="true">
        <match url="(.*)" />
        <action type="Rewrite" url="http://domain1.com/sp/WebServices/json.asmx/GetPersonDetails" />
        <conditions>
            <add input="{QUERY_STRING}" pattern="GetPersonDetails" />
        </conditions>
    </rule>
    <rule name="ReverseProxyInboundRule2" stopProcessing="true">
        <match url="(.*)" />
        <action type="Rewrite" url="http://domain1.com/sp/WebServices/json.asmx/DropDownList" />
        <conditions>
            <add input="{QUERY_STRING}" pattern="DropDownList" />
        </conditions>
    </rule>
</rules>

https://domain2.com/SportsPortalAPI/?q=DropDownList
https://domain2.com/SportsPortalAPI/?q=GetPersonDetails
In above we are invoking (02) Get method by using query string value DropDownList and DropDownList respectively

A: You can use angular proxy for the web-service, but I wouldn't recommend that for permanent/production usage.


text:
Q: How to install active-x control from website in IE? I want to install active-x(.ocx) from website in IE.
if(active-x is not registered or installed version is old)
  install/register active-x control
I am a C++ developer, I have developed active-x control(.ocx) I am new in web development.
Currently I am doing registration through (regsvr32 active-x name). I wants to automate this process. As user came to my site plugin should get installed.
Thanks in advance...

A: I have found the way to do it using following links:
http://www.codeproject.com/Articles/14533/A-Complete-ActiveX-Web-Control-Tutorial
http://www.codeproject.com/Articles/22185/A-Complete-Scriptable-ActiveX-Web-Control-Tutorial
Thanks,
Pravin


text:
Q: Norm of a skew symmetric unitary matrix Let $U \in \mathbb{R}^{n \times n}$ be a unitary matrix, $U$ can be nonsymmetric, its eigenvalues can be complex numbers and all have modulus $1$.
Is there an upper bound for the maximum singular value of its skew symmetric part (which is not necessarily unitary) depending on its eigenvalues?
i.e.: Is there an $f$ such that
$\left\|\frac{U - U^T}{2} \right\|_2 = \sigma_\text{max}\left(\frac{U - U^T}{2}\right) \le  f\left(\lambda_i\left(U\right)\right)$ ?
More details:
Observe that if $U=I$ (eigenvalues are real) $\Rightarrow \left\|\frac{U - U^T}{2} \right\|_2 = \sigma_\text{max}\left(\frac{U - U^T}{2}\right) = 0$, and if $U$ is skew-symmetric (eigenvalues purely imaginary) $\Rightarrow\left\|\frac{U - U^T}{2} \right\|_2 = \sigma_\text{max}\left(\frac{U - U^T}{2}\right) = 1$. Therefore there is a relationship between the norm $\left\|\frac{U - U^T}{2} \right\|_2 = \sigma_\text{max}\left(\frac{U - U^T}{2}\right)$ and the argument of the eigenvalues of $U$, i.e. $f\left(\lambda_i\left(U\right)\right) = f\left(\text{arg}(\lambda_i\left(U\right))\right)$.
Further notes: in my work $U$ is the unitary factor of the polar decomposition of an M-matrix, but this may be irrelevant.

A: A unitary is normal, so it is diagonalizable by unitary conjugation. So we can think of $U $ diagonal, with the eigenvalues as the diagonal entries. The imaginary part is then the diagonal matrix of the imaginary parts of the eigenvalues. So
$$
\left\|\frac {U-U^*}2\right\|=\max\{|\text {Im}\,\lambda_j|:\ j=1,\ldots,n\}. $$


text:
Q: Explicit (full) specialization of function with a templated type I have a template function declared as -
template <typename T>
void foo (T &t);

I have specialized it once as -
template <>
void foo<int> (int &t) {
    // Implementation for int
}

Now, I want to specialize the implementation for type - template <typename T> bar<T>.
How should I be writing the specialization? Can I use template inside templates?


text:
Q: How remove UITabBarController from UIViewController How to remove UITabBarController from UIViewController, when we are moving from one UIViewController to another UIViewController with UINavigationController.

A: Overwrite the init function in your code (loadView probably won't work)
self.hidesBottomBarWhenPushed = NO;

// OR you can remove it from app delegate by putting these lines in a method named by urself
[mainMenuTabBarController.view removeFromSuperview];

A: You should set this property of UIViewController to YES: BOOL hidesBottomBarWhenPushed
Example:
The second line of the code below is what you ask.
UIViewController *destinationVC = [[UIViewController alloc] init];
[destinationVC setHidesBottomBarWhenPushed:YES]; // !!!
[self.navigationController pushViewController:destinationVC animated:YES];

A: [self.tabBarcontroller.view removeFromSuperview];

A: [self.tabBarcontroller.view removeFromSuperview];
[self.tabBarcontroller.tabbar removeFromSuperview];

A: UIViewController *yourController = [[UIViewController alloc] init];
[yourController setHidesBottomBarWhenPushed:YES];
[self.navigationController pushViewController:yourController animated:YES];

here you make a instance of your ViewController and then befor pushing it just use the setHidesBottomBarPushed() so that it is hidden when you push it.
But remember it will work only if u do this befor pushing.


text:
Q: Write a $ currency symbol I want to write the $ symbol in my LaTeX file. I tried \$ and also \textdollar. In both cases the dollar sign is printed but I am getting an alert.

I am using Sharelatex to compile the code.
Edit:
Sorry but the problem was not the $, its a \foodnote with _ symbol.  Problem solved by adding \ before each _ symbol.


text:
Q: R: Adding text to a plot does not work i've got the following problem; I wrote a simple code to create some plots for a lecture, but somehow it does not add text to my plot. Thought there is neither a warning nor an error, and after searching in the internet i did not find any solution so far.
Thank you in advance for your help, the code is following. A short note: Anything else of the plot works as i wish, it's just the text-line which is missing.
edit: here is the full code
libraries = c("dygraphs", "quantmod", "stringr", "ggplot2")
lapply(libraries, function(x) if (!(x %in% installed.packages())) { install.packages(x) })
lapply(libraries, library, quietly = TRUE, character.only = TRUE)
tickers = c("AMZN","GOOG", "MSFT")

end = Sys.Date()

getSymbols(tickers, from = "2017-10-01", to = end)

a = seq(1, 51, by =1)

time = index(AMZN.1)
time = time[a]
time = format(time, format = "%d.%m.")
for (i in 1:3){
  assign(paste0(tickers[i], ".1"), Cl(get(tickers[i])))
}
AMZN.2 = as.numeric(AMZN.1)
GOOG.2 = as.numeric(GOOG.1)
MSFT.2 = as.numeric(MSFT.1)

abc = as.numeric(match("27.10.", time))

plot(AMZN.2, type = "l", xlab = "time", ylab = "price (USD, NASDAQ)", xaxs = "i", xaxt = "n", main = "Share price Amazon Inc. (Oct 17 - Dec 17)", sub = "qrtly results announced at oct 26th")
axis(1,a, labels = time) #a is a numeric vector, time a character vector
abline(v = abc, col = "red", lty = "dotted") #abc is a number (=20)
abline(h = 972.43, col = "red", lty = "dotted")
abline(h = 1100.95, col = "red", lty = "dotted")
text(abc, "my text here", col = "red", srt = 90) #abc see above

A: Running your code, it appears to me that the problem is that abc provides an x-coordinate, but a y-coordinate is not provided.  Simply providing the x and y argument as
text(x=abc, y=1000, "my text here", col = "red", srt = 90)

is an example that seems to agree with my theory.


text:
Q: Why it is not positioned in relation to its container? I'm triying to position a point inside a circle to practice CSS position, so I declared .circle with position: relative and inside the point with position: absolute. But I get the point positionated in relation to the body.

.circle {
  width: 600px;
  height: 600px;
  border-radius: 50%;
  background-color: grey;
  position: relative;
}

.point {
  position: absolute;
  top: 0px;
  left: 100px;
  background-color: black;
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

A: .point IS relative to the .circle and not body
My suspicion is that you think that .circle for browser is circle too but in fact it is rectangle and only presented to you as circle because of border-radius property. It can be seen when you insect this element.
Blue rectangle is your .circle element and .point is positioned relative to it just like you told it to.

A: Its working right. If you put position: relative in .circle the position, of point will be relative to circle container.
See Modified Example of your code below. I have set point's position (left and top) to 100%, and removed border-radius. See the point is positioned at bottom right corner of square.

Now, see the position of point, when you remove position: relative from .circle


text:
Q: Unable to build android app because ofKeystore file '/Users/name/Desktop/KEYSTORE/release.keystore' not found for signing config 'release' I have cloned a project already created and failed to build the app in release.keystore. So I again generated the keystore still getting the same issue

A: in app level build.gradle find these two parts and comment them:
//part one
signingConfigs {
    my_app_sign_config {

    }
}

//part two
signingConfig signingConfigs.my_app_sign_config


text:
Q: What happened to Windows Based Application in Xcode 4.2?
Possible Duplicate:
Cannot find window-based application on XCode

I am pretty new to IOS development and have started reading books to help me out.  I only started recently and the books all start you on a windows based application and I see that this does not exist in xcode 4.2.  I have read and found that the way to go is to create an empty project but this does not create a .xib file and I have no idea what I'm doing so it might not seem like a big deal to an experienced IOS developer but this was a huge curve ball for me.  Also there is a bunch more code in the .h and .m file that wasn't there before.  Can someone tell me why this was taken out and maybe sort of guide me to what I should do or what I should start reading.  I know that this may seem like a question that could be solved with a bit more research but the problem is not as much that the windows based app is not there anymore but why is it not there.  Maybe I shouldn't even try and create one anymore?  I have even read posts where they say how to add the .xib file but that didn't really help because when i built my app, it was a blank screen.  Anyways, that's a different problem.

A: There are new editions of many beginner books out there, such as the Apress series
There is a walkthrough of hooking up a XIB to the empty app which should make it fairly easy to go through the book you already have.  If you're having problems with this though, then I really do recommend the book.  I've gone through the last version of it and I found it very easy to follow and understand.
As for why Apple changed it, as per usual they haven't said anything about what motivates them.  We developers are just left to assume that they must have it in for us.

A: How to make window-based app in 4.2: http://www.makebetterthings.com/iphone/where-is-mainwindow-xib-in-xcode-4-2/
Make sure you didn't miss "select MainWindow as the Main Interface" part.

A: Windows Based application are not there in Xcode 4.2. But You can go with option "Empty Applicaion" and manually add Xibs and classes.
For more details please follow this question "Cannot find window-based application on XCode" where you will find your answer in a more clear way.


text:
Q: RadGridView Button Column Content Binding to DataMember I have a telerik rad grid view and assigned buttons to one of the columns using DataTemplate.
        <telerik:RadGridView ItemsSource="{Binding AllJobsCollection}"
                         Grid.Row="2"
                         SelectedItem="{Binding SelectedJob}">

        <!--Jobs List Columns-->
        <telerik:RadGridView.Columns>

            <!--Pin button Column-->
            <telerik:GridViewColumn>
                <telerik:GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <telerik:RadButton
                            Command="{Binding Path=DataContext.PinCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type telerik:GridViewDataControl}} }"
                            CommandParameter="{Binding}">
                        </telerik:RadButton>
                    </DataTemplate>
                </telerik:GridViewColumn.CellTemplate>
            </telerik:GridViewColumn>

            <telerik:GridViewDataColumn Header="Job"
                                        Width="Auto"
                                        IsReadOnly="False"
                                        DataMemberBinding="{Binding Name}"/>

        </telerik:RadGridView.Columns>
    </telerik:RadGridView>

My question is how can I set the content of the button using DataMemberBinding.
I have a data table and i can pin some of the items and i change their Pinned property in database. I want to get the pinned property and set the buttons content accordingly.

A: You can't use DataMemberBinding within a CellTemplate. But you can bind the Content property to the any property of the current item, e.g.:
<telerik:RadButton
    Command="{Binding Path=DataContext.PinCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type telerik:GridViewDataControl}} }"
    CommandParameter="{Binding}"
    Content="{Binding IsPinned}">


text:
Q: BufferedImage very slow compared to ImageIcon I have these two snippets to load an image and draw it to the screen. The first one uses swing's ImageIcon:
import javax.swing.ImageIcon
import java.awt.Image

val g: Graphics2D = get_g2d()
val img : Image = new ImageIcon("image.png").getImage()
g.drawImage(
          img,
          0, 0, 500, 500,  // draw pos / size
          0, 0, 1024, 1024 // clip pos / size
          null)

The second one uses awt's BufferedImage:
import java.io.File
import java.awt.image.BufferedImage
import javax.imageio.ImageIO

val buf : BufferedImage = ImageIO.read(new File("image.png"))
val g: Graphics2D = get_g2d()
g.drawImage(
          buf.getSubImage(0, 0, 1024, 1024) // clip pos / size
          0, 0, 500, 500,  // draw pos / size
          null)

The first snippet that uses ImageIcon loads almost instantly, but if I draw it with a clip, it doesn't work (sub frame within the image to make a sprite sheet). It only works if I remove the clip parameters (clip pos / size), which makes it impossible to segment an image into a sprite sheet.
The second snippet that uses BufferedImage draws correctly both with and without the clip. But, it takes about 5 seconds to load.
I thought ImageIcon was only loading the low resolution cached icon of the file for a moment which would explain the instant loading, but I put the images side by side with the two techniques and they are exactly the same.
I could split my spritesheets sub images into individual images so that I can draw them with ImageIcon without needing to clip them, but I lose the convenience of having them all in one spritesheet.
How can I have an image load as fast as ImageIcon does, but still have clipping support?


text:
Q: Star Bright short story This is a short story about a super intelligent child named Star.
She has a friend almost as intelligent.
They discover a way to get to another dimension or universe where similarly gifted people have gone.
Her father hopes to find a way to follow them to protect her.


text:
Q: How can i import raster image to GRASS GIS without losing RGB Values? I am using GrassGIS 6.4.2, How can I import raster data to GrassGIS without losing RGB Values?
The raster image format is TIFF, the below commmand is using to import raster image:
r.in.gdal input=C:\Users\Administrator\Desktop\renjith\satellite\14feb06053537-s2as-053712789010_01_p004.tif

After importing raster image I am getting like this

A: Use r.composite to merge the bands back into a single raster.
This is the example from the documentation page:
r.composite blue=lsat7_2002_10 green=lsat7_2002_20
    red=lsat7_2002_30 output=lsat7_2002_rgb

Don't forget to set your region!