text:
Q: Error message starting rsyslog after configuring system logging without journald on RHEL 7 I followed this procedure from Red Hat website https://access.redhat.com/articles/4058681 to configuring system logging without journald but after reboot rsyslog failed to start.

*

*edit the /etc/rsyslog.conf rsyslog configuration file; turn "on" use
of imuxsock local messages, comment out the loading of the imjournal
module and uncomment the loading of the imklog module:

module(load="imuxsock"                 # provides support for local system logging (e.g. via the logger command)
SysSock.Use="on")
# module(load="imjournal"             # provides access to the systemd journal
# StateFile="imjournal.state")        # file to store the position in the journal
module(load="imklog") # reads kernel messages (the same are read from journald)

*edit the journald configuration at /etc/systemd/journald.conf;
switch journal to in-memory only mode and enable forwarding:

[Journal]
Storage=none
ForwardToSyslog=yes

*create drop-in for the rsyslog unit configuration file at
/etc/systemd/system/rsyslog.service.d/override.conf with the
following content to ensure socket creation and linking:

[Unit]
Requires=syslog.socket

[Install]
Alias=syslog.service

When I tried to manually start it, I got following error messages
A dependency job for rsyslog.service failed. See 'journalctl -xe' for details.

But it seems rsyslog daemon started ok
$ sudo systemctl start rsyslog | grep Active
A dependency job for rsyslog.service failed. See 'journalctl -xe' for details.

$ sudo systemctl status rsyslog | grep Active
   Active: active (running) since Sat 2020-10-24 01:19:37 EDT; 3s ago

$ sudo systemctl stop rsyslog | grep Active
$ sudo systemctl status rsyslog | grep Active
   Active: inactive (dead) since Sat 2020-10-24 01:19:54 EDT; 2s ago

$ sudo systemctl start rsyslog | grep Active
A dependency job for rsyslog.service failed. See 'journalctl -xe' for details.
$ sudo systemctl status rsyslog | grep Active
   Active: active (running) since Sat 2020-10-24 01:20:07 EDT; 3s ago

journalctl -xe shows following info the date is the day I configured system logging without journald
Oct 16 14:20:34 systemd-journal[89]: Journal stopped
-- Subject: The journal has been stopped
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- The system journal process has shut down and closed all currently
-- active journal files.

any idea why rsyslog did not start during reboot, started OK manually but gave that error message?


text:
Q: A Borel set generated by sequence of Baire one functions Let $\{f_n\}$ be a sequence of Baire one functions from $\mathbb{R}$ to $\mathbb{R}$ in which $f_n(\mathbb{R})$ is isolated in $\mathbb{R}$ for every $n$.
Hence the $H_n = \{x: |f_n(x) - f_{n-1}(x)| <3. 2^{-n}\}$ is a Borel set of the additive class one. My tutor said that $\mathbb{R} - H_n$ is also a Borel set of the additive class one. Why? It should be true using fact that $f_n(\mathbb{R})$ and $f_{n-1}(\mathbb{R})$ are isolated. But I do not how to prove it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't access an aspx page via IIS I'm running IIS 5 on Windows XP professional

I created new Web project and configured VS 2008 to save this application to
location c:\Inteput\wwwroot. Thus VS saved the project into directory:
c:\Inteput\wwwroot\WebApplication1

I then transformed this WebApplication1 folder into virtual directory (this virtual directory is also configured as web application). But whenever I try to access:
c:\Inteput\wwwroot\WebApplication1\WebApplication1\default.aspx

through browser using URL:
http://localhost/WebApplication1/WebApplication1/default.aspx

, I get an exception saying:

Configuration Error
  Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.

Any ideas what I'm doing wrong?
BTW - Virtual directory does have Read and Run scripts permissions set

Q2 - How do I configure Visual studio to run Web app via IIS and not via integrated web server? Thus so that when I'd press CTRL+F5, the browser would be server a page by IIS and not by integrated web server?

thank you

A: You say it is running as an application - is is using the right ASP.NET version? (2.x)
Re debugging in IIS; you do that on the project properties - on the Web panel I believe; change it to "Use Local IIS Web Server" and enter the url to the application root on localhost.

A: Well, you followed a strange (wrong) procedure, for reference create a small project and point to a (new) virtual dir right from the New Project dialog. This gives you a check (IIS 5 is kind of old) and a project to compare.
And/or create a virtual dir and deploy the project to it using the Web Publishing or Web Copy tools.
From the face of it, it looks like you've got one WebApplication1 folder to many in your URL. That rimes with the error, certain web.config settings are only allowed in an Applications root.
Added: regarding Q2, when you set IIS for debugging you will also have to configure the output directory as a Virtual Dir. This is normally done during Project creation by VS.

A: I think this is a problem with you web.config, can you please supply yours? Have you got more that one?
I've had an error like this one before, it doesn't quite fit what you are saying, but maybe you left out some details.
Basically if you have an application, you should not configure the MachineToApplication settings in web.config's in the subdirectories. Although I suppose other things can make this error turn up.
Oh I bet you do have two web.configs
here c:\Inteput\wwwroot\WebApplication1\web.config
and here c:\Inteput\wwwroot\WebApplication1\WebApplication1\web.config

A: 1 - It works now. I created new virtual directory
c:\Inteput\wwwroot\Testing

and copied everything from
c:\Inteput\wwwroot\WebApplication1\WebApplication1

into this new directory, so that now web.config was in the root directory of an application.

A)

certain web.config settings are only allowed in an Applications root.

So was that my web.config one that is only allowed in Application root? How can I know for sure?

2 -

Re debugging in IIS; you do that on the project properties - on the Web panel I believe; change it to "Use Local IIS Web Server" and enter the url to the application root on localhost.

Found it, but now I get the following error:

Access is denied.
  Description: An error occurred while accessing the resources required to serve this request. You might not have permission to view the requested resources.
Error message 401.3: You do not have permission to view this directory or page using the credentials you supplied (access denied due to Access Control Lists). Ask the Web server's administrator to give you access to 'C:\Documents and Settings\kaja\My Documents\Visual Studio 2008\Projects\WebApplication8\WebApplication8\Default.aspx'.

thanx


text:
Q: Ember Hello Word - Test Error in http://localhost:4200/tests but not in command line I am trying to build a hello world Ember.js app by following this tutorial...I have gotten to the part where I test the link to an About page.
My setup is:
QUnit 1.18.0; Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Ember version: 1.13.8
node: 0.12.7
npm: 2.13.4
os: darwin x64

My router.js is:
import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

Router.map(function() {
  this.route('about');
});

export default Router;

My application.hbs is:

Welcome to Boston Ember

{{link-to 'About' 'about'}}

{{outlet}}

My about.hbs is:

About

Boston Ember is the monthly meetup where awesome people get together

to do awesome Ember related things!
My about-page-test.js is:
import Ember from 'ember';
import startApp from 'bostonember/tests/helpers/start-app';

var App;

module('Integration - About Page', {
  beforeEach: function() {
    App = startApp();
  },
  afterEach: function() {
    Ember.run(App, 'destroy');
  }
});

test('Should navigate to the About page', function() {
  visit('/').then(function(assert) {
    click("a:contains('About')").then(function(assert) {
      assert.equal(find('h3').text(), 'About');
    });
  });
});

The page functions as it should and the command line does not return any errors:
file changed templates/application.hbs

Build successful - 691ms.

But when I go to http://localhost:4200/tests I see a bunch of errors...
Integration - About Page: Should navigate to the About page (1, 0, 1)Rerun210 ms
TypeError: Cannot read property 'equal' of undefined@ 190 ms
Expected:   true
Result:     false
Diff:   trufalse
Source:
    at http://localhost:4200/assets/test-support.js:4578:13
    at exports.default._emberTestingAdaptersAdapter.default.extend.exception (http://localhost:4200/assets/vendor.js:52460:34)
    at onerrorDefault (http://localhost:4200/assets/vendor.js:43162:24)
    at Object.exports.default.trigger (http://localhost:4200/assets/vendor.js:67346:11)
    at Promise._onerror (http://localhost:4200/assets/vendor.js:68312:22)
    at publishRejection (http://localhost:4200/assets/vendor.js:66619:15)

JSHint - integration: integration/about-page-test.js should pass jshint (1, 0, 1)Rerun1 ms
integration/about-page-test.js should pass jshint.
integration/about-page-test.js: line 6, col 1, 'module' is not defined.
integration/about-page-test.js: line 15, col 1, 'test' is not defined.
integration/about-page-test.js: line 16, col 28, 'assert' is defined but never used.

3 errors@ 0 ms
Expected:   true
Result:     false
Diff:   trufalse
Source:
    at Object.<anonymous> (http://localhost:4200/assets/bostonember.js:337:12)
    at Object.Test.run (http://localhost:4200/assets/test-support.js:3566:28)
    at http://localhost:4200/assets/test-support.js:3695:11
    at process (http://localhost:4200/assets/test-support.js:3254:24)
    at begin (http://localhost:4200/assets/test-support.js:3299:2)
    at http://localhost:4200/assets/test-support.js:3315:4

I have tried using some different variations of this.route('about'); although I think this is fine, since the functionality works. I have also tried some different things in the test, but nothing gets rid of the browser error.

A: You need to include qUnit for assertions and startApp for ember testing helpers.
import Ember from "ember";
import { module, test } from 'qunit';
import startApp from '../helpers/start-app';

Module can be defined for models.
import { test, moduleForModel } from 'ember-qunit';

moduleForModel('recipe/recipe', 'Unit | Models | Recipe |', {
    needs: ['model:recipe/recipe', 'model:recipe/category', 'model:filerepository/file']
});

where

this.subject()

references to the imported module.
Examples: http://www.ember-cli.com/user-guide/#testing

A: It seems as though I had the asserts in the wrong place. The following passed:
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../helpers/start-app';

var App;

module('Integration - About Page', {
  beforeEach: function() {
    App = startApp();
  },
  afterEach: function() {
    Ember.run(App, 'destroy');
  }
});

test('Should click About link', function(assert) {
  visit('/').then(function() {
    click("a:contains('About')").then(function() {
      assert.equal(find('h3').text(), 'About');
    });
  });
});


text:
Q: Git: possible to point subtree to different commits when switching branches? In a repository with two branches (master & develop) and a git subtree repository included in folder shared, is it possible to automatically synch the shared subtree to a specific version (commit) when changing branches?
My best guess is that I'm probably looking for a way to run a script whenever I change branches locally. The script then performs the necessary git pull/fetch commands on the subtree.
Let's say the master branch should always point to v1.0 tagged commit of the shared subtree repository, while the develop branch always checks out the latest commit. Edits to the shared subtree are only made in the develop branch and will be committed (or stashed) before switching to master.

A: Yes, you can have your subtrees in each branch point to different code versions. The state of the subtrees belong to the commit just like any other set of files, meaning that one branch can have different contents in the subtree from other branches. Upon checkout the state of the subtree will be updated with whatever is on that branch, again, just like any other file.
The simplest way to show this is to have a subtree in master, create a branch from master, and in the branch update the said subtree and commit. Thus the branch will have a modified version of the subtree, and if you check out master it will revert to the state previously left in master.

A: I'm puzzled why this question has been abandoned for so long. I encountered the same problem in an SVN-Git migration, at the point of trying to reconstruct SVN "externals" dependencies.
Just to put another answer into the internet here, I think the way to go would be to create both a script calling git fetch ... and git subtree pull ... as well as a post-checkout hook that executes this script. My idea is that the script would have the same name on every branch, so that the post-checkout hook would do nothing more than call switch_dependency.py or something, and you would manually have to take care of the correct commands in that script.


text:
Q: Is it safe to remove files in Nexus tmp folder? While trying to clear up some disk space, I noticed that many Gigabytes of data lie around in the 'sonatype-work/nexus/tmp' folder. The biggest directory is called 'nexus-maven-repository-index.gz*.dir' and I am hesitating to remove it. Is that just a temporary and unused copy of the repository index which I can safely delete?
The documentation of the Nexus Directories does not provide sufficient information about the 'tmp' folder. It only says that it is the "Folder used for temporary storage".

A: It should be safe to delete this content. Please note that treatment of the tmp folder recently changed in the 2.8.1 release.
Also going forward you should use the Empty Trash scheduled task. See http://blog.sonatype.com/2009/09/nexus-scheduled-tasks/


text:
Q: Why is the accuracy of CNN model changing every time? I got this error, "Allocation of 73138176 exceeds 10% of system memory", when I run image classification codes via CNN. I used different solutions to solve my problem. However, it changed the model accuracy in each testing.
Model accuracy here was 0.6761.
model.fit(X, y, batch_size=32, epochs=9, validation_split=0.3)

Then, when I lowered batch_size to 2, the accuracy here increased to 0.8451. Also, it did not give any errors related to the allocation problem.
model.fit(X, y, batch_size=2, epochs=9, validation_split=0.3)

Then, I was also curious about a code which also solved the allocation problem. However, this time, Model accuracy here was 0.7183. The code is;
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

model.fit(X, y, batch_size=32, epochs=9, validation_split=0.3)

My question is, which code do you actually suggest that I should follow? Also, could you please brighten me why the accuracy changes each time?
Thank you for every help and suggestion.

A: If you want exactly repeatable training results, you need to eliminate all sources of randomness. For a typical model training, the main sources are in 1: your dataset; randomization of the test/train split, or randomization of the order in which batches are generated. And 2: the model initialization; if you want to train the same model every time, you need to start with the same initial parameters every time. How you ensure that you get 'the same random numbers' with every training run varies by framework; and it was unreasonably painful last time I tried years ago in TF; but it can be done and google should know how to do if you search for fixing the random seed in TF.
However, fixing the random seed may not be what you are interested in; for doing repeatable experiments, it's what you want. But as far as the production qualities of your model are concerned, thats a different matter. If you find that the eventual model you end up with, behaves rather different depending on the seed (and many problems will intrinsically have this property, where multiple 'equally valid' but rather different interpretations exist), training an ensemble of such models, with a different random seed each, is a useful thing to do; in this way you can gain an explicit awareness of the amount of 'room for interpretation' that you model and dataset leaves open.


text:
Q: Why should we define a scope of a dependency in Maven? Maven provides a  tag for dependencies which can "limit the transitivity of a dependency". I understand, that by defining, for instance, a test scope for a given dependency, this dependency will not be available in other phases (diagram). But I don't get what is the advantage of doing so?

A: Scopes have three main purposes:

*

*avoid that you use something in your application that you did not want to use (if you declare the implementation as runtime, you cannot accidentally use it in your code).

*reduce the amount of transitive dependencies. Especially test dependencies will not become dependencies of the users of your library.

*reduce the size of a WAR/EAR: If your container already provides the dependencies, you declares them as provided so that they are not packaged into your application.

A: https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#dependency-scope
You don't need hoe and gun for digging, you just need hoe only.
You don't need JUnit dependency for running on web-server (scope runtime), you need JUnit when you test only (scope test), you don't need JUnit when you package for production.
Another benefit is avoiding version conflicting, avoid unnecessary dependencies redundancy.


text:
Q: Another Question about partial Views I feel like a total idiot but for the life of me can't figure out what the heck I am missing here.
I have the following:
 @section TopPane

{
@*@{Html.Action("_OpenIDSignInPartial", "Account");}*@
@{Html.RenderAction("_OpenIDSignInPartial", "Account");}

Sign-in with your mysite.com account or Register for an account

@{Html.RenderPartial("_LoginPartial");}

@{Html.RenderPartial("_RegisterPartial");}

}
As you can see I have 3 Partial Views being rendered.
Now for the Controller Code----
public class AccountController : Controller
{
    private readonly IAuthenticationService _authenticationService;
    OpenIdRelyingParty _openIdRelyingParty = new OpenIdRelyingParty(null);
    public AccountController(IAuthenticationService authenticationService)
    {
        _authenticationService = authenticationService;
    }

    public ActionResult Index()
    {
        return View();
    }
    public ActionResult SignIn()
    {
        return View();
    }
    [HttpPost]
    public ActionResult SignIn(AccountSignInViewModel accountSignInViewModel)
    {
        return View();
    }
    public ActionResult OpenIdSignIn()
    {
         AccountIndexViewModel accountIndexViewModel = new AccountIndexViewModel();
        IAuthenticationResponse authenticationResponse = _openIdRelyingParty.GetResponse();
         switch (authenticationResponse.Status)
         {
             case AuthenticationStatus.Authenticated:
                 try
                 {
                     var claimedIdentifier = authenticationResponse.ClaimedIdentifier.ToString();
                     _authenticationService.OpenIdSignIn(claimedIdentifier);
                 }
                 catch (Exception)
                 {
                     // Do something with this man!
                     throw;
                 }
                 break;
             case AuthenticationStatus.Canceled:
                 accountIndexViewModel.openIdSignInViewModel.ErrorMessage = "An Error Message";
                 break;
         }
         return View("SignIn",accountIndexViewModel); // ALWAYS an ERROR
    }
    [HttpPost]
    public ActionResult OpenIdSignIn(AccountOpenIdSignInViewModel accountOpenIdSignInViewModel)
    {
        IAuthenticationResponse authenticationResponse = _openIdRelyingParty.GetResponse();
        if (authenticationResponse == null)
        {
            Identifier identifier;
            if (Identifier.TryParse(accountOpenIdSignInViewModel.openid_identifier, out identifier))
            {
                try
                {
                    IAuthenticationRequest request =
                        _openIdRelyingParty.CreateRequest(accountOpenIdSignInViewModel.openid_identifier);

                    return request.RedirectingResponse.AsActionResult();
                }
                catch (ProtocolException protocolException) // Prolly should add some errors to the model
                {
                    ModelState.AddModelError("openid_identifier","Unable to authenticate");
                    return View("SignIn");
                }
            }
        }
        return View();
    }
    public ActionResult _OpenIDSignInPartial(AccountOpenIdSignInViewModel accountOpenIdSignInViewModel)
    {
        return PartialView("_OpenIdSignInPartial");
    }
}

When I reurn the view from the OpenIdSignIn ActionResult() I get the following error
The model item passed into the dictionary is of type 'Web.ViewModels.AccountIndexViewModel', but this dictionary requires a model item of type 'Web.ViewModels.AccountSignInViewModel'.
Ok great so I will return a AccountSignInViewModel right?? Then I get an error saying it needs the AccountIndexViewModel... CATCH 22 here.

A: You are returning a AccountIndexViewModel to the main view. This means that the 2 partials must be strongly typed to AccountIndexViewModel:

*

*_LoginPartial

*_RegisterPartial

If they aren't you need to pass the proper view model when rendering them.
As far as _OpenIDSignInPartial is concerned you are rendering it through the _OpenIDSignInPartial action in which you
return PartialView("_OpenIdSignInPartial");

According to the error message it looks like _OpenIdSignInPartial.cshtml is strongly typed to AccountSignInViewModel:
@model AccountSignInViewModel

so make sure that you are passing an instance of this model when returning the partial view:
AccountSignInViewModel signInViewModel = ...
return PartialView("_OpenIdSignInPartial", signInViewModel);


text:
Q: Python and MySQL I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.
I found bpgsql really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?

A: I don't have any experience with http://www.SiteGround.com as a web host personally.
This is just a guess, but it's common for a shared host to support Python and MySQL with the MySQLdb module (e.g., GoDaddy does this).  Try the following CGI script to see if MySQLdb is installed.
#!/usr/bin/python

module_name = 'MySQLdb'
head = '''Content-Type: text/html

%s is ''' % module_name

try:
    __import__(module_name)
    print head + 'installed'
except ImportError:
    print head + 'not installed'

A: I uploaded it and got an internal error
Premature end of script headers

After much playing around, I found that if I had
import cgi
import cgitb; cgitb.enable()
import MySQLdb

It would give me a much more useful answer and say that it was not installed, you can see it yourself -> http://woarl.com/db.py
Oddly enough, this would produce an error
import MySQLdb
import cgi
import cgitb; cgitb.enable()

I looked at some of the other files I had up there and it seems that library was one of the ones I had already tried.

A: You could try setting up your own python installation using Virtual Python.  Check out how to setup Django using it here.  That was written a long time ago, but it shows how I got MySQLdb setup without having root access or anything like it.  Once you've got the basics going, you can install any python library you want.

A: You really want MySQLdb for any MySQL + Python code.  However, you shouldn't need root access or anything to use it.  You can build/install it in a user directory (~/lib/python2.x/site-packages), and just add that to your PYTHON_PATH env variable.  This should work for just about any python library.
Give it a shot, there really isn't a good alternative.

A: MySQLdb is what I have used before.
If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem).  But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do with it.
Another option may be to call your host and complain, or change hosts.  Honestly these days, any self respecting web host that supports python and mysql ought to have MySQLdb pre installed.

A: Take a pick at
https://docs.djangoproject.com/en/1.8/ref/databases/
MySQLdb is mostly used driver, but if you are using python3 and django 1.8.x that will not work, then you should use mysqlclient that is a folk of MySQLdb on the following link
https://pypi.python.org/pypi/mysqlclient


text:
Q: Eror while creating bean on hibernate spring project I'm new in spring and hibernate on this project I'm using netbeans v.8.2 and I'm using library spring 3.2.7 and hibernate 4.3.x
what should I do to fix the error ?
The eror:
Error creating bean with name 'dao' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'template' while setting bean property 'template'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'template' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'mysessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mysessionFactory' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/cache/CacheProvider
this is the application context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName"  value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/kampus"></property>
    <property name="username" value="root"></property>
    <property name="password" value=""></property>
</bean>

<bean id="mysessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>

    <property name="mappingResources">
    <list>
    <value>Mahasiswa.hbm.xml</value>
    </list>
    </property>

    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.show_sql">true</prop>

        </props>
    </property>
</bean>

<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>

<bean id="dao" class="dao.MahasiswaDao">
<property name="template" ref="template"></property>
</bean>

</beans>

this is mahasiswa.java (mahasiswa=student in English):
package entity;

public class Mahasiswa  implements java.io.Serializable {

 private String npm;
 private String nama;
 private String jurusan;
 private String alamat;

public Mahasiswa() {
}

public Mahasiswa(String npm, String nama, String jurusan, String alamat) {
   this.npm = npm;
   this.nama = nama;
   this.jurusan = jurusan;
   this.alamat = alamat;
}

public String getNpm() {
    return this.npm;
}

public void setNpm(String npm) {
    this.npm = npm;
}
public String getNama() {
    return this.nama;
}

public void setNama(String nama) {
    this.nama = nama;
}
public String getJurusan() {
    return this.jurusan;
}

public void setJurusan(String jurusan) {
    this.jurusan = jurusan;
}
public String getAlamat() {
    return this.alamat;
}

public void setAlamat(String alamat) {
    this.alamat = alamat;
}

}

This is Mahasiswa.dao :
package dao;
import entity.Mahasiswa;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class MahasiswaDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public void saveMahasiswa(Mahasiswa m){
    template.save(m);
}
}

this is mahasiswa.hbm.xml:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 30, 2021 6:57:57 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="entity.Mahasiswa" table="mahasiswa" catalog="kampus" optimistic-lock="version">
    <id name="npm" type="string">
        <column name="npm" length="13" />
        <generator class="assigned" />
    </id>
    <property name="nama" type="string">
        <column name="nama" length="100" not-null="true" />
    </property>
    <property name="jurusan" type="string">
        <column name="jurusan" length="100" not-null="true" />
    </property>
    <property name="alamat" type="string">
        <column name="alamat" length="100" not-null="true" />
    </property>
</class>
   </hibernate-mapping>

and this is the main.java :
public class test06 {
public static void main(String[] args) {
    Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);

MahasiswaDao dao=(MahasiswaDao)factory.getBean("dao");

Mahasiswa m=new Mahasiswa();
m.setNpm("1");
m.setNama("test");
m.setJurusan("");
m.setAlamat("");

dao.saveMahasiswa(m);
}
}

Thanks

A: You're missing the org.hibernate.cache.Provider class on the classpath.
As per java.lang.ClassNotFoundException: org.hibernate.cache.CacheProvider exception while integrating spring and hiberate

org.hibernate.cache.Provider was removed in the change from
Hibernate 3 to Hibernate 4.

You're using Hibernate 4, but the Hibernate-related classes from Spring you're using in applicationContext.xml are from org.springframework.orm.hibernate3 package, so they need that missing dependency.
Try using the HibernateTemplate and LocalSessionFactoryBean from the org.springframework.orm.hibernate4 package.
If there isn't such a package in Spring 3.2.7, upgrade to Spring 4.


text:
Q: QString degree symbol I wonder what is the best and cleanest solution to write a degree symbol in a translation.
I had tr( "Snap to 90%1 angles" ).arg( QString::fromUtf8( "°" ) ) but this is not really nice.
I tried without success: tr( "Snap to 90° angles" )
I use this in a QAction: mCommonAngleAction = new QAction( tr( "Snap to 90° angles" ), menu );
Here is the result:

Do you have a good solution?

A: The string you want to print depends quite a lot on where you want to print it. So where do you want to print Snap to 90° angles?
If you want to set a QLabel text to Snap to 90° angles a piece of code like label->setText(tr("Snap to 90° angles")); works just fine.
If you want to print it to console it depends on the console. If the console doesn't support UTF-8, unless you set a flag on that console to support UTF-8 characters, you're out of luck.
In a QMainWindow constructor, using the code
ui->menubar->actions().first()->setText(QObject::tr("Snap to 90° angless"));

generates:


text:
Q: Как импортировать библиотеки "по кругу" У меня есть файл User.py и он импортирует Errors.py и тот в свою очередь импортирует User.py
User.py
from . import Errors

...

raise Errors.ArgumentError

Errors.py
from . import User

...

user = User()
user.test() # raise Errors.ArgumentError

И мне нужен любой способ получить классы без "Кругового" импорта

A: При импорте библиотеки происходит выполнение кода указанного модуля, соответственно, цикличный импорт работать не будет. Вам нужно перераспределить функционал этих модулей, так чтобы избавиться от цикличной зависимости.


text:
Q: How do I get rid of this overflowed pixels error in Flutter Web I have a navigationbar in flutter web and I am getting a render issue.  It works fine when I am full screen, but It shows the error once I minimized the page to almost mobile version.
This is my code:
'''
 class NavigationBar extends StatefulWidget {
  const NavigationBar({Key key}) : super(key: key);

  @override
  _NavigationBarState createState() => _NavigationBarState();
}

class _NavigationBarState extends State<NavigationBar> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(10, 0, 20, 0),
      width: MediaQuery.of(context).size.width,
      color: kNavBarBlueBackground,
      height: 100,
      child: Flexible(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SizedBox(width: 20),
            Image.asset('assets/img/image_logo.png'),
            Spacer(),
            Row(
              children: [
                _NavBarItem('Inicio'),
                SizedBox(width: 35),
                _NavBarItem('Agencias'),

'''
This is the error I am getting.

Edited this with more code because user below asked for code where this navigation bar was placed in code:
'''
lass _ViajeroExpresoPageState extends State<ViajeroExpresoPage> {
  void openDrawer() {
    _drawerKey.currentState.openDrawer();
  }

  @override
  Widget build(BuildContext context) {
    return ResponsiveBuilder(
      builder: (context, sizingInformation) {
        // Check the sizing information here and return your UI
        if (sizingInformation.deviceScreenType == DeviceScreenType.desktop) {
          return Desktop();
        }

        if (sizingInformation.deviceScreenType == DeviceScreenType.tablet) {
          return Mobile(openDrawer: openDrawer);
        }

        return Mobile(openDrawer: openDrawer);
      },
    );
  }
}

class Desktop extends StatelessWidget {
  final Function openDrawer;

  const Desktop({Key key, this.openDrawer}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _drawerKey,
      body: Stack(
        children: [
          ListView(
            children: [
              Container(
                width: MediaQuery.of(context).size.width,
                color: Colors.blue,
                child: NavigationBar(),
              ),

'''

A: try wrapping the listview widget in 'expanded' widget


text:
Q: how to avoid singularity of multiplication of matrix transpose by the matrix itself in Mathematica I wrote next code in Mathematica to get the inverse of multiplication of matrix transpose by matrix itself :
A = RandomInteger[{1, 20}, {3, 51}];
B = A\[Transpose].A;
F = Inverse[B];
F // MatrixForm

it always tell me that matrix (B) is singular -despite (A) is random, while multiplication of the matrix by its transpose is ok !!!!!!!!
A = RandomInteger[{1, 20}, {3, 51}];
O = A.A\[Transpose];
L = Inverse[O];;
L// MatrixForm

do any one can explain to me why the first case give me singular matrix while the second case is ok ? and what shall i do to make the first case non singular ? is it something wrong with the code ?

A: brenderson gives the answer here: B is positive semidefinite (PSD)

in order for B to be invertible, it must be that A is a narrow matrix
(n ≤ m) with full column rank. In the case that A is a strictly wide
matrix (m < n), there is no possibility for B to be invertible.

For example
A = RandomInteger[{1, 20}, {3, 4}];
B = Transpose[A].A;
{m, n} = Dimensions[A];
If[n <= m, "A is a narrow matrix", "A is a wide matrix"] <>
 If[Det[B] == 0, " ; B is singular", " ; B is invertible"]

A is a wide matrix ; B is singular

A = RandomInteger[{1, 20}, {4, 3}];
B = Transpose[A].A;
{m, n} = Dimensions[A];
If[n <= m, "A is a narrow matrix", "A is a wide matrix"] <>
 If[Det[B] == 0, " ; B is singular", " ; B is invertible"]

A is a narrow matrix ; B is invertible


text:
Q: JQuery comparison of parents('tr) and find('tr:first') not working When a cell of the table is clicked, I want to set the content of this cell but only if it is neither in the first row nor in the first column.

$('td').click(function() {

  console.log($(this).parents('tr'));
  console.log($('#matrix').find('tr:first'));
  console.log($('#matrix').find('tr:first') == $(this).parents('tr'));

  if ($(this).parents('tr') != $('#matrix').find('tr:first')) {

    console.log("is ok");
    if ($(this).text() != "x") { // Connect
      $(this).text("x");
      alert("Connecting " +
        $('td:first', $(this).parents('tr')).text() +
        " with " +
        $('tr:first', $(this).parents('td')).text());
    } else { //Disconnect
      $(this).text("");
      alert("Disconnecting Endpoint " +
        $('td:first', $(this).parents('tr')).text() +
        " with Endpoint " +
        $('tr:first', $(this).parents('td')).text());
    };

  }; // row/columns > 0 only
}); // click()
td {
  border: 1px solid black;
}

    Matrix
    _name_
    _name_

    _name_

    _name_

The Firefox debuging console highlights the exact same elements, but
console.log( $(this).parents('tr') == $('#matrix').find('tr:first') );

always shows false, regardless on which cell I click.
What am I doing wrong?

A: Maybe two are pointing to the same dom element but object reference would be different. For checking the equality use is() method in jQuery.
console.log( $(this).parents('tr').is($('#matrix').find('tr:first')));

or compare the DOM object by getting using the index or get() method.

console.log( $(this).parents('tr')[0] == $('#matrix').find('tr:first')[0]);
// or
console.log( $(this).parents('tr').get(0) == $('#matrix').find('tr:first').get(0));

UPDATE : Additionally, you can reduce the code by binding click event only for the td elements which need to update the content. Where use :nth-child pseudo-class selector(pure CSS selector) to filter the td.

$('#matrix tr:nth-child(n + 2) td:nth-child(n + 2)').click(function() {
  //  use text method with callback to update text based on the existing content
  $(this).text(function(i, txt) {
    return txt === 'x' ? '' : 'x';
  })
});

    Matrix
    _name_
    _name_

    _name_

    _name_

A: You don't need to compare object, You can just use :gt() and :not() along with :first-child selector  to exclude first row and first column.

$('#matrix tr:gt(0) td:not(:first-child)').click(function() {
  if ($(this).text() != "x") {
    $(this).text("x");
  } else {
    $(this).text("");
  };
});

    Matrix
    _name_
    _name_

    _name_

    _name_

A: Exclude first row and do it so much easier in the selector:
$('tr:not(:first) > :not(:first-child)').click(function() {
    //Code
});


text:
Q: isomorphism of the group by plus one of its elements Say there's a group G=(S,+), and a is a certain element of it. Then I can get a new group G' by applying a projection f(g)=g+a to every element in G.
Will the new group G' necessarily be isomorphic to G? If it's not, what condition should the original group G satisfy?

A: If you're asking whether $G'$ will be isomorphic to $G$, the answer is yes, since $a\in G$. We can prove this, too. Define a map $\varphi: G\to G'$ by $\varphi(g) = f(g)-a = g+a-a = g$. Then $\varphi$ is the identity map, and you can easily verify that this is an isomorphism.
Another way to check is that $G'$ has the same operation $+$ as $G$, so all we need to check is set inclusion. Clearly for all $g\in G$, $g = (g-a)+a \in G'$ so $G\subseteq G'$. Also, for all $g' \in G'$, we have $g' = f(g) = g+a$ for some $g\in G$, but $g+a\in G$ so $g'\in G$. Thus $G'\subseteq G$ and hence $G=G'$. We have two groups which have the same set and binary operation. They are the same group, and hence they are trivially isomorphic.


text:
Q: Delegate compiles with different return types Let's say I have a class that looks like:
public class MyClass
{
    public delegate void MyDelegate();

    public static void DoWork(MyDelegate aDelegate)
    {
         aDelegate();
    }
}

And I have some code that looks like:
var myBool = false;
MyClass.DoWork(() => myBool = true);

The above builds as expected.  What I can't make sense of is if I change the return type on MyDelegate to bool, it still builds.  To top it off, if I change the return type to say, int, the lambda will show a compilation error of:
Cannot convert expression type 'bool' to return type 'int'.

This leaves me with two questions:
Why are both void and bool acceptable for the delegate's return type?
Why is the expression type on my lambda bool?  Is it not void?
Thanks!

A:
Why is both void and bool acceptable for the delegate's return type?

Lambdas are rather unusual in this regard.  They are one of very few expressions in C# that are contextual, that is they do different things depending on the context in which the expression is used.
In this case the compiler looks at what you are trying to assign the lambda to, and uses that in determining what the type of that lambda should be.  It sees that the lambda needs to be of type MyDelegate, and attempts to match the lambda to that delegate.  The lambda that you have resolves to an expression of type bool, but if the delegate is of type void the return type will be ignored, allowing you to have a non-void lambda assigned to a void returning delegate.

Why is the expression type on my lambda bool? Is it not void?

The assignment operator isn't void returning; it resolves to the value that was assigned to the variable, so in this case, it resolves to true.
So with a simpler code snippet:
bool variable;
bool anotherVariable = (variable = true);

(The parenthesis here are not needed, and are only there for clarity as to the order of execution.)
both variable and anotherVariable will be true after running this.  variable = true will assign true to variable, return true, and then assign that to anotherVariable.


text:
Q: ¿Cómo solucionar este error: java.lang.ArrayIndexOutOfBoundsException: 4 >= 0? También para java.lang.IndexOutOfBoundsException He mirado bastante y no he podido solucionar este error, ademas de que me he dado cuenta de que cuando le doy al botón guardar y si ya hay datos en Jtable que tenga el campo hora salida, este los borra cuando ingresa un estudiante nuevo.

Exception in thread "AWT-EventQueue-0"
  java.lang.ArrayIndexOutOfBoundsException: 3 >= 0  at
  java.util.Vector.removeElementAt(Vector.java:561)     at
  javax.swing.table.DefaultTableModel.removeRow(DefaultTableModel.java:462)
    at Vista.Principal.boton_EliminarActionPerformed(Principal.java:518)
    at Vista.Principal.access$900(Principal.java:14)    at
  Vista.Principal$11.actionPerformed(Principal.java:287)    at
  javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at
  javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at
  javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at
  javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at
  javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6539)    at
  javax.swing.JComponent.processMouseEvent(JComponent.java:3324)    at
  java.awt.Component.processEvent(Component.java:6304)  at
  java.awt.Container.processEvent(Container.java:2239)  at
  java.awt.Component.dispatchEventImpl(Component.java:4889)     at
  java.awt.Container.dispatchEventImpl(Container.java:2297)     at
  java.awt.Component.dispatchEvent(Component.java:4711)     at
  java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
    at
  java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
    at java.awt.Container.dispatchEventImpl(Container.java:2283)    at
  java.awt.Window.dispatchEventImpl(Window.java:2746)   at
  java.awt.Component.dispatchEvent(Component.java:4711)     at
  java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)    at
  java.awt.EventQueue.access$500(EventQueue.java:97)    at
  java.awt.EventQueue$3.run(EventQueue.java:709)    at
  java.awt.EventQueue$3.run(EventQueue.java:703)    at
  java.security.AccessController.doPrivileged(Native Method)    at
  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at
  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
    at java.awt.EventQueue$4.run(EventQueue.java:733)   at
  java.awt.EventQueue$4.run(EventQueue.java:731)    at
  java.security.AccessController.doPrivileged(Native Method)    at
  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)   at
  java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
    at
  java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at
  java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at
  java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at
  java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

String sistFecha=Fecha_Hora.Fecha();
String sistHora=Fecha_Hora.Hora();
Timer tiempo;
public boolean bien = false;//Para La Validacion De Ingreso De Datos
ArrayList<Estudiantes> datos_estudiantes= new ArrayList<Estudiantes>();
DefaultTableModel modelo= new DefaultTableModel();
int filas;

public Principal()
{
    initComponents();
    activar_desactivar(false,0);
    this.setLocationRelativeTo(null);//Pantalla En El Centro
    //this.setExtendedState(MAXIMIZED_BOTH);
    jlFecha_Sistema.setText(sistFecha);//FECHA DEL SISTEMA
    //jlHora_Sistema.setText(sistHora);//HORA DEL SISTEMA
    tiempo=new Timer(100, new Principal.horas());
    tiempo.start();
    this.jtable_Datos.setModel(modelo);
}

private void boton_GuardarActionPerformed(java.awt.event.ActionEvent evt) {
    validacion();
    if(bien==true)
    {
        Estudiantes estudiantes= new Estudiantes(sistFecha, txCodigo.getText(), txNombre.getText(),
        cbCarrera.getSelectedItem().toString(), txHora_Ingreso.getText(), txHora_Salida.getText(),
        cbSala.getSelectedItem().toString(), txServicio.getText(), cbMonitores.getSelectedItem().toString());
        datos_estudiantes.add(estudiantes);
        mostrar();
        activar_desactivar(false,0);
        limpiar_campos();
    }
}

private void boton_EditarActionPerformed(java.awt.event.ActionEvent evt) {
        String []datos=new String[9];
        datos[0]=sistFecha;
        datos[1]=txCodigo.getText();
        datos[2]=txNombre.getText();
        datos[3]=cbCarrera.getSelectedItem().toString();
        datos[4]=txHora_Ingreso.getText();
        datos[5]=txHora_Salida.getText();
        datos[6]=cbSala.getSelectedItem().toString();
        datos[7]=txServicio.getText();
        datos[8]=cbMonitores.getSelectedItem().toString();
        for(int i = 0 ; i<jtable_Datos.getColumnCount();i++)
        {
            jtable_Datos.setValueAt(datos[i], filas, i);
        }
        activar_desactivar(false,0);
}

private void boton_EliminarActionPerformed(java.awt.event.ActionEvent evt) {
    int filaselecionada= jtable_Datos.getSelectedRow();
    System.out.println();
    if(filaselecionada>=0)
    {
        modelo.removeRow(filaselecionada); Aqui Es Dondel Señala el error
    }
    else
    {
        JOptionPane.showMessageDialog(null,"No Ha Seleccionado Ninguna Fila");
    }
}

public void activar_desactivar(boolean desicion, int desicion2)
{
    txCodigo.setEnabled(desicion);
    txNombre.setEnabled(desicion);
    cbCarrera.setEnabled(desicion);
    txHora_Ingreso.setEnabled(desicion);
    if (desicion2==0){txHora_Salida.setEnabled(false);}
    else {txHora_Salida.setEnabled(true);}
    cbSala.setEnabled(desicion);
    txServicio.setEnabled(desicion);
    cbMonitores.setEnabled(desicion);
    boton_Guardar.setEnabled(desicion);
    boton_Cancelar.setEnabled(desicion);
}

public void limpiar_campos()
{
    txCodigo.setText("");
    txNombre.setText("");
    cbCarrera.setSelectedIndex(0);
    txHora_Ingreso.setText("");
    txHora_Salida.setText("");
    cbSala.setSelectedIndex(0);
    txServicio.setText("");
    cbMonitores.setSelectedIndex(0);
}

private boolean validacion()
{
    int carrera = cbCarrera.getSelectedIndex();
    int sala = cbSala.getSelectedIndex();
    int monitores = cbMonitores.getSelectedIndex();

    if(txCodigo.getText().length() == 0)
    {
        JOptionPane.showMessageDialog(null, "Ingrese El Codigo","ERROR",JOptionPane.ERROR_MESSAGE);
    }
    else if(txNombre.getText().length() == 0)
    {
        JOptionPane.showMessageDialog(null, "Ingrese El Nombre","ERROR",JOptionPane.ERROR_MESSAGE);
    }
    else if(carrera==0)
    {
        JOptionPane.showMessageDialog(null, "Ingrese La Carrera","ERROR",JOptionPane.ERROR_MESSAGE);
    }
    else if(txHora_Ingreso.getText().isEmpty())
    {
        JOptionPane.showMessageDialog(null, "Ingrese La Hora de Llegada","ERROR",JOptionPane.ERROR_MESSAGE);
    }
    else if(sala==0)
    {
        JOptionPane.showMessageDialog(null, "Ingrese La Sala","ERROR",JOptionPane.ERROR_MESSAGE);
    }
    else if(txServicio.getText().isEmpty())
    {
        JOptionPane.showMessageDialog(null, "Ingrese El Servicio Utilizado","ERROR",JOptionPane.ERROR_MESSAGE);
    }
    else if(monitores==0)
    {
        JOptionPane.showMessageDialog(null, "Ingrese El Monitor Que Lo Atendio","ERROR",JOptionPane.ERROR_MESSAGE);
    }
    else
    {
        bien=true;
    }
    return bien;
}

private void mostrar()
{
    String matris[][]= new String[datos_estudiantes.size()][9];
    for (int i = 0; i < datos_estudiantes.size(); i++)
    {
        matris[i][0]= datos_estudiantes.get(i).getFecha();
        matris[i][1]= datos_estudiantes.get(i).getCodigo();
        matris[i][2]= datos_estudiantes.get(i).getNombre();
        matris[i][3]= datos_estudiantes.get(i).getCarrera();
        matris[i][4]= datos_estudiantes.get(i).getHora_Ingreso();
        matris[i][5]= datos_estudiantes.get(i).getHora_Salida();
        matris[i][6]= datos_estudiantes.get(i).getSala();
        matris[i][7]= datos_estudiantes.get(i).getServicio();
        matris[i][8]= datos_estudiantes.get(i).getMonitores();
    }
    jtable_Datos.setModel(new javax.swing.table.DefaultTableModel
    ( matris, new String [] {"Fecha", "Codigo", "Nombre", "Carrera", "Hora Ingreso",
                            "Hora Salida", "Sala", "Servicio", "Monitores", } ));
}

A: Un primer paso para resolver problemas con excepciones es saber qué significa, y el Javadoc suele dar la primera aproximación:

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

También vemos en el Javadoc que ArrayIndexOutOfBoundException es una subclase, un caso especial de IndexOutOfBoundsException, que dice:

Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

Es decir, tienes una de estas porque tienes elementos ordenados por un índice de X a Y, pero estás intentando acceder a un índice Z que no está entre X e Y.
Es como poner en fila a cinco niños y que te pidan el nombre del niño que está el décimo en la fila. Obviamente es un error (o debería haber más niños, o el niño en el que están interesados es otro).
La ArrayOutOfBoundsException te indica que el error se da al acceder a un array. Un array tiene elementos entre 0 y [número de elementos del array - 1]. En este caso, el array está dentro de la implementación de java.util.Vector (se puede ver en el stacktrace).
El resto del mensaje 3 >= 0 te indica que intentas acceder al elemento en la posición 3 pero el array tiene 0 posiciones (básicamente, está vacío) así que lanza la excepción. No se puede obtener ningún elemento de un array vacío (lógicamente).
Una vez que sabes qué significa la excepción, eres tú quien debe corregir la causa del error (¿inicializar el array? ¿calcular el índice de otra forma?) de acuerdo con como debe funcionar tu programa.


text:
Q: PHP foreach varable outside loop not updated Can someone help me understand the issue I am having. It's a  bug in some open source api I am trying to fix.
I have simple  function that supposed to  return array. But returns empty array
$this  - is an object and it's correct
public function toArray($minimized = false) {
    $array = [];

    foreach($this->list as $item) {
        $item->updateBeanProperties();
        $array[] = $item->toArray($minimized);
       // here print_r($array) gives correct result
    }
      // here print_r($array) gives empty array
    return $array;
}


text:
Q: What representation theoretic properties does the semi-invariant ring tell us? I'm asking this question as a continuation of discussion and answer given by Hugh Thomas at the following post: Why do people study semi-invariant ring (in general)?
I have been studying about semi-invariant rings in the context of quiver representations but I don't really understand that if a semi-invariant ring turns out to be a polynomial ring or a hypersurface (or complete intersection), what "representation-theoretical" properties does it tell us about the quiver? For what kind of calculation or concept is it useful? Or, in general, what information does it give?
Even if the answer is not particularly in the context of quiver representations, I would still be glad to know.


text:
Q: Copy data from many files to master based on cell values in the master First time poster here.
I have a list of files (file1, file2, file3) and I want to copy a range from those files into a master file. The master file contains a column with this data file1, file2, file3. How can I loop through that column and copy and paste each file's range into the corresponding row in the master? I need the data from file1 to go into a range in the same row as file1.
This is what I have so far:
Dim col As Range

Dim cell As Range
Dim currentRow As Long

Dim varCellValue As String

Dim pasteRangeC As String
Dim pasteRangeE As String

Set col = Range("B3:B5")
currentRow = 3

 For Each cell In col

    varCellValue = cell.Value
    currentRow = 3

    pasteRangeC = "C" & currentRow
    pasteRangeE = "E" & currentRow

    '## Open workbooks:
    Set x = Workbooks.Open("C:\Folder\" & varCellValue &_ ".xlsx")
    Set y = ThisWorkbook

    'Copy from x:
    x.Sheets("Summary").Range("D13:F13").Copy

    'Paste to y worksheet:
    y.Sheets("Sheet1").Range(pasteRangeC & ":" & pasteRangeE).PasteSpecial xlPasteValues

    'Close x:
    x.Close
    currentRow = currentRow + 1

 Next

End Sub

The code works for the first loop then I get a run-time error 1004 that the file cannot be found. So I'm thinking the varCellValue does not get the next cell's value.
Can anyone point me in the right direction?

A: Based on what I read try the following
Option Explicit 'Use every time will keep you from making simple mistakes...
Sub test()

Dim wb As Workbook
Dim ws As Worksheet
Dim wbSource As Workbook
Dim i As Integer

On Error GoTo ErrCatch 'add to catch errors
Set wb = Application.ThisWorkbook
Set ws = wb.Worksheets("Sheet1")

For i = 1 To 5

    '## Open workbooks:
    Set wbSource = Workbooks.Open("C:\Folder\" & ws.Cells(i, 2).Value & ".xlsx") 'Cells(Row,Column) 2 = "B"

    'Copy from wbSource and paste in worksheet
    wbSource.Sheets("Summary").Range("D13:F13").Copy Destination:=ws.Cells(i, 3)  'This syntax keeps you from having to do "Application.CutCopyMode = False" to remove the marching ants.

    'Close source:
    wbSource.Close False
 Next i

ErrCatch:
If Err.Number > 1 Then 'test if an error was thrown
    MsgBox "Error Number: " & Err.Number & vbCrLf & _
        "Error Description: " & Err.Description, vbCritical
End If
End Sub


text:
Q: Google Form Responses in a Notification Email I'm using the Form Notifications add-on in a Google Form. I've edited the Code.gs and CreatorNotification.html files and all works fine - when a Google Form is submitted I get an email. Now I'm trying to get some of the fields from that Form submission into the email. But with the edits I've added below, the email notification stops working.
In the Code.gs script I have:
function sendCreatorNotification() {
    var form = FormApp.getActiveForm();
    var settings = PropertiesService.getDocumentProperties();
    var responseStep = settings.getProperty('responseStep');
    responseStep = responseStep ? parseInt(responseStep) : 10;

    function onFormSubmit(e) {
        //Get information from form and set as variables
        var First_Name = e.value[2];

        // If the total number of form responses is an even multiple of the
        // response step setting, send a notification email(s) to the form
        // creator(s). For example, if the response step is 10, notifications
        // will be sent when there are 10, 20, 30, etc. total form responses
        // received.
        if (form.getResponses().length % responseStep == 0) {
            var addresses = settings.getProperty('creatorEmail').split(',');
            if (MailApp.getRemainingDailyQuota() > addresses.length) {
                var template = HtmlService.createTemplateFromFile('CreatorNotification');
                template.summary = form.getSummaryUrl();
                template.responses = form.getResponses().length;
                template.title = form.getTitle();
                template.responseStep = responseStep;
                template.formUrl = form.getEditUrl();
                template.notice = NOTICE;
                template.firstname = First_Name;
                var message = template.evaluate();
                MailApp.sendEmail(settings.getProperty('creatorEmail'),
                form.getTitle() + ': Case submission',
                message.getContent(), {
                    name: ADDON_TITLE,
                    htmlBody: message.getContent()
                });
            }
        }
    }
}

In the CreatorNotification.html I have:

Form Notifications (a Google Forms add-on) has detected that the      form
titled <a href="<?= formUrl?>"><?= title ?> has received
<?= responses ?> responses so far.

<a href="<?= summary ?>">Summary of form responses

First Name:
 <?= firstname ?>

Any direction would be appreciated.

A: You are trying to run two triggers.  That "Add-on" code creates a trigger.  The Add-on creates an "Installable" trigger.  You already have one trigger set up for the form being submitted.  The onFormSubmit(e) function is a "Simple" trigger.  So, you have two triggers set up to run when a form is submitted.  So, you created a conflict.  If you look in the RESOURCES menu, under CURRENT PROJECT's TRIGGERS, you should see a trigger defined for the sendCreatorNotification() function.
Here's what you can try.    You don't need a seperate onFormSubmit(e) simple trigger. The sendCreatorNotification() function, has the event object available to it.  Just add e to the sendCreatorNotification() function:
sendCreatorNotification(e)

The write your code to get the value out of e.


text:
Q: NFC Plugin for Eclipse I'm trying to use the NFC Plugin but i have an error "Signature could not verify". I write the code generating the signature of the data and a selfsigned certificate. But when I put all them together i shows me that error. Can you help me with this?

A: The Signature Record support is experimental at this point, so I advise you to check out the sources for a deeper investigation.


text:
Q: Jetty https module causing startup to fail When adding the --https module to the start.ini file for jetty, I receive the following "noconstructorclass" error and geoserver fails to startup. This is an out of the box geo server 2.16.0 install on linux.
Geoserver comes with jetty.version = 9.4.18.v20190429
Upon startup on geoserver utilizing jetty, I get the following error:
/usr/lib/jvm/jre-1.8.0/bin/java -server -Xms16G -Xmx16G -Xmn2G -XX:       +UseG1GC -DSTOP.PORT=8079 -DSTOP.KEY=geoserver -jar start.jar
2020-04-14 22:12:01.961:WARN:oejx.XmlConfiguration:main:
java.lang.IllegalStateException: No constructor class.   org.eclipse.jetty.server.ServerConnector([],{}) in file:/opt/software/etc/  jetty-https.xml
Caused by: java.lang.IllegalStateException: No constructor class org.eclipse.jetty.server.ServerConnector([],{}) in file:/opt/software/etc/jetty-https.xml
Caused by: java.lang.IllegalStateException: No constructor class org.eclipse.jetty.server.ServerConnector([],{}) in file:/opt/software/etc/jetty-https.xml

When I startup jetty --list-config option I see:
Jetty Active XMLs:
${jetty.base}/etc/jetty.xml
${jetty.base}/etc/jetty-deploy.xml
${jetty.base}/etc/jetty-http.xml
${jetty.base}/etc/jetty-ssl.xml
${jetty.base}/etc/jetty-ssl-context.xml
${jetty.base}/etc/jetty-https.xml

Other jetty settings are
jetty.base = /opt/software
jetty.base.uri = file:///opt/software
jetty.ssl.port = 8443
jetty.sslContext.keyManagerPassword = MyPassword
jetty.sslContext.keyStorePassword = MyPassword
jetty.sslContext.keyStorePath = etc/keystore
jetty.sslContext.trustStorePassword = MyPassword
jetty.sslContext.trustStorePath = etc/keystore

Everything starts up successful when I disable the --https module but working on getting https working with jetty.
Here is the excerpt form the classPath if that is needed as well.
Jetty Server classpath items:
0: (dir) | ${jetty.base}/resources
1: 3.1.0 | ${jetty.base}/lib/javax.servlet-api-3.1.0.jar
2: 3.1.0.M0 | ${jetty.base}/lib/jetty-schemas-3.1.M0.jar
3: 9.4.18.v20190429 | ${jetty.base}/lib/jetty-http-9.4.18.v20190429.jar
4: 9.4.18.v20190429 | ${jetty.base}/lib/jetty-server-9.4.18.v20190429.jar
5: 9.4.18.v20190429 | ${jetty.base}/lib/jetty-xml-9.4.18.v20190429.jar
6: 9.4.18.v20190429 | ${jetty.base}/lib/jetty-util-9.4.18.v20190429.jar
7: 9.4.18.v20190429 | ${jetty.base}/lib/jetty-io-9.4.18.v20190429.jar
8: 9.4.18.v20190429 | ${jetty.base}/lib/jetty-security-9.4.18.v20190429.jar
9: 9.4.18.v20190429 | ${jetty.base}/lib/jetty-servlet-9.4.18.v20190429.jar
10: 9.4.18.v20190429 | ${jetty.base}/lib/jetty-webapp-9.4.18.v20190429.jar
11: 9.4.18.v20190429 | ${jetty.base}/lib/jetty-deploy-9.4.18.v20190429.jar
12: 9.4.18.v20190429 | ${jetty.base}/lib/jetty-servlets-9.4.18.v20190429.jar

It appears it is finding all of the configuration files correctly...yet can't quite see why it is failing when loading that module.
I will try to update the format. Hard on phone.
If I disable the --https module, everything starts up without issues. This is out of the box config so not sure why https would be failing with default options.


text:
Q: What does the error about default member initializer needed means? I have a code that works fine in Visual Studio:
struct A
{
    struct P{ P() = default; int x = 1; };
    void foo( const P & = {} );
};

However both gcc and clang refuse to compile it with the error:
<source>:4:28: error: default member initializer for 'A::P::x' required before the end of its enclosing class
    4 |     void foo( const P & = {} );

https://gcc.godbolt.org/z/ja3c9zPMY
Could you please suggest what is wrong with the code?


text:
Q: Smooth bijection has a dense open subset in which the inverse is also smooth Let $f:\mathbb{R}^n \longrightarrow \mathbb{R}^n$ be smooth and bijective. Prove there exists open subset $U$ and $V$ dense in  $\mathbb{R}^n$ such that $f: U \longrightarrow V$ has a smooth inverse.
I would like to do this using the rank theorem. I would think that the set of points at which the differential is not invertible are isolated or something like that, but I'm not quite sure how to prove it (if it's even true).
This i my main problem; if I suppose  $\text{rank} df(x)=k<n$ then the rank cannot be equal to $k$ in a neighborhood of x, otherwise the rank theorem applies and it gives me that $f$ is not surjective. Therefore i get a sequence of points converging to $x$ with rank different than $k$, but how does this help me?
Any help would be greatly appreciated, thank you.


text:
Q: System.IO.IOException: 'The parameter is incorrect.' when NamedPipeClientStreamReadMode = PipeTransmissionMode.Message I am trying to create a NamedPipeClientStream and I can't set the ReadMode to Message
            Stream = new NamedPipeClientStream(".", GetPathFromID(id), PipeDirection.InOut);

            Console.WriteLine("Tried to connect: " + id);

            try
            {
                Stream.Connect(100);

                if (Stream.IsConnected)
                {
                    Stream.ReadMode = PipeTransmissionMode.Message;
                    new Thread(StartReading).Start();
                }
            }
            catch (TimeoutException e)
            {
                Console.WriteLine("Faied to connect: " + id);
            }


text:
Q: Error deserializing objects from MemoryStream I'm trying to send a serialized object from a client to server, where a server will read it as a byte array, create a memory stream with the byte array, and then deserialize using the memory stream.
It works properly the first time but when the first client disconnects and the second one connects and sends the object I get this:
Binary stream '0' does not contain a valid BinaryHeader.
or
No assembly ID for object type ''.
This is where the error is occurring:
    private static async void HandleClient(TcpClient tcpClient)
    {
        NetworkStream networkStream;

        try
        {
            networkStream = tcpClient.GetStream();
            byte[] buff = new byte[1024];

            while (true)
            {
                int recieved = await networkStream.ReadAsync(buff, 0, buff.Length);

                if (recieved == 0)
                {
                    Console.WriteLine("Client disconnected.");
                    break;
                }

                using (MemoryStream memoryStream = new MemoryStream(buff))
                {
                    IFormatter formatter = new BinaryFormatter();
                    object obj = formatter.Deserialize(memoryStream);
                    if (obj is PersonData)
                    {
                        PersonData data = (PersonData)obj;
                        Console.WriteLine($"{data.name} - {data.age} - {data.gender}");
                    }
                }
                Array.Clear(buff, 0, buff.Length);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }

A: Turns out the problem was in my client's code. I was serializing it directly to the network stream instead of just converting the object to an array of bytes and sending the array.


text:
Q: IBM Watson Natural Language Understanding Java null pointer exception I am using IBM Watson Natural Language Understanding for analyze a given string. Currently I am following the example given here. I am using maven build tool to add the dependencies. I am getting a null point exception.
I removed the api key for this post.
 public static void main(String[] args) {
        try {
            IamOptions options = new IamOptions.Builder()
                    .apiKey("{APK}")
                    .build();

            NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding("2018-03-16", options);
            service.setEndPoint("{https://gateway.watsonplatform.net/natural-language-understanding/api}");

            String text = "Differences in how writing systems represent language raise important questions about the extent to which the\n" +
"role of linguistic skills such as phonological awareness (PA) and morphological awareness (MA) in reading\n" +
"is universal. In this meta-analysis, the authors examined the relationship between PA, MA, and reading\n" +
"(accuracy, fluency, and comprehension) in 2 languages (English and Chinese) representing different writing\n" +
"systems (alphabetic and logographic). A random-effects model analysis of data from 64 studies with native\n" +
"speakers of each language revealed significant correlations between PA, MA, and all reading outcomes in both\n" +
"languages. The correlations remained significant even after controlling for each other's effect on reading.\n" +
"However, PA was a stronger correlate of reading in English than in Chinese. MA was as good a correlate of\n" +
"reading in English as in";

            CategoriesOptions categories = new CategoriesOptions();

            Features features = new Features.Builder()
                    .categories(categories)
                    .build();

            AnalyzeOptions parameters = new AnalyzeOptions.Builder()
                    .text(text)
                    .features(features)
                    .build();

            AnalysisResults response = service
                    .analyze(parameters)
                    .execute();
            System.out.println(response);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

A: You need to remove the curly brackets from "{https://gateway.watsonplatform.net/natural-language-understanding/api}" -- "https://gateway.watsonplatform.net/natural-language-understanding/api".
(The library is trying to open a request to "{https:..." and throwing a null pointer exception, but it should fail more gracefully.)


text:
Q: Multiple expression in ng-show - AngularJS Why cannot i have multiple expression in ng-show?
Im using this line

when i try this it wont work:

There is no error message just that the ng-repeat then wont work properly by showing both container.isfavorite and container.isHidden (like they are ignored)
How can i have multiple impressions inside ng-show?
Update:
This is my code for isfavorite:
<md-button ng-class="{yellow : container.isfavorite}"
               ng-click="container.isfavorite =!container.isfavorite; AddFavorite(container.isfavorite,container.containerId)"
               class="md-icon-button md-accent md-warn" aria-label="Favorite">
<ng-md-icon icon="favorite" ng-init="container.isfavorite = false;"></ng-md-icon>
</md-button>

This is my code for isHidden:
<md-button ng-class="{zebbi : container.isHidden}"
           ng-click="container.isHidden =!container.isHidden; Hidecontainer(container.isHidden, container.containerId);"
           class="md-icon-button md-accent md-warn" aria-label="Hide">
<ng-md-icon ng-if="!container.isHidden" icon="remove_red_eye"></ng-md-icon>
<ng-md-icon ng-if="container.isHidden" icon="panorama_fisheye"></ng-md-icon>
</md-button>

A: There is no such a limitation. You can use any number of expression in ng-show.
There is no any syntax errors on your code but seem like there should be logical error that's why your code is not working as expected.
Re-check expressions in  ng-show directive.


text:
Q: missing parenthesis in jquery event in xhtml page jsf2 application I tried to use this jquery code to validate my inputs :
$(".maqte , .monpu").on("keypress", function(){
         if (( (event.which != 46) || ($(this).val().indexOf('.') != -1) ) && ( (event.which -lt 48) || (event.which -gt 57) ) {
                event.preventDefault();
              }
        });

but I have always this error in console of browser and the event is not launched  :
in chrome : Uncaught SyntaxError: Unexpected token )
in firefox :
SyntaxError: missing ) in parenthetical

I don't see which is this missing parenthesis
******************EDIT
always the same error :
$(".maqte , .monpu").on("keypress", function(){
        if (( (event.which != 46) || ($(this).val().indexOf('.') != -1) ) &&
                   ((event.which -lt 48) || (event.which -gt 57) )){
            event.preventDefault();
        }
        });

new code above

A: you missing ) at the end.
if (( (event.which != 46) || ($(this).val().indexOf('.') != -1) ) &&
   ((event.which -lt 48) || (event.which -gt 57) ))

A: Maybe it got something to do with -lt and -gt. Try this instead:
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
    event.preventDefault();
}


text:
Q: BigDecimal divide with scale I have
private static final BigDecimal ONE_HUNDRED = new BigDecimal(100);
    private static final BigDecimal TEN = new BigDecimal(10);

BigDecimal decimal = new BigDecimal(1050);
I need to get 10% I write
BigDecimal decimalResult = decimal.divide(ONE_HUNDRED).multiply(TEN)//100, 10
But Intellij IDE says:

'BigDecimal.divide()' called without a rounding mode argument more...

I added BigDecimal.ROUND_HALF_UP and all others but I get wrong result. I need 1050/100 = 10.5  but if I add BigDecimal.ROUND_HALF_UP result = 11.
How can I correctly divide with scale parameters?

A: This example returns 105.0000
public class TestBigDecimal {
  static BigDecimal decimal = new BigDecimal(1050).setScale(4, BigDecimal.ROUND_HALF_UP);
  static BigDecimal ONE_HUNDRED = new BigDecimal(100);
  static BigDecimal TEN = new BigDecimal(10);

  public static void main(String[] args)
  {
    BigDecimal decimalResult = decimal.divide(ONE_HUNDRED).multiply(TEN) ;
    System.out.println(decimalResult);
  }
}

You should adjust the scale during the creation of decimal variable.

A: public static double divide(double d1, double d2) {
    BigDecimal b1 = new BigDecimal(d1);
    BigDecimal b2 = new BigDecimal(d2);
    return b1.divide(b2, 2, RoundingMode.DOWN).doubleValue();
}


text:
Q: get values from local variables to class variables Lets say I have:
class BlaBla{
int x;
int y;

public void actionPerformed(ActionEvent e){

int m1;
int m2;
// algorhythm where i get values for m1 and m2
}
}

How can i assign values of m1 to x and m2 to y?
Because i want to use values of m1 and m2 in another class? in another class where i Have paint method and i would like to  use them as coordinates for painting.
Thanks
my action button will parse XML file. than i need four variables for paint method, which is in another class
public void actionPerformed(ActionEvent e){
        try{

        JFileChooser fch = new JFileChooser();
        int i = fch.showOpenDialog(null);
        if(i==JFileChooser.APPROVE_OPTION){
            File f = fch.getSelectedFile();

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(f);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("line");

            // NodeList nList = doc.getElementsByTagName("point");

            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;

                    Element line = (Element) nList.item(0);

                    Element point1 = (Element) line.getElementsByTagName("point").item(0);
                    Element point2 = (Element) line.getElementsByTagName("point").item(1);

                     int m1 = Integer.parseInt(point1.getElementsByTagName("X").item(0).getTextContent());
                     int n1 = Integer.parseInt(point1.getElementsByTagName("Y").item(0).getTextContent());
                     int m2 = Integer.parseInt(point2.getElementsByTagName("X").item(0).getTextContent());
                     int n2 = Integer.parseInt(point2.getElementsByTagName("Y").item(0).getTextContent());

my main class is:
public class Line {
public static void main(String[] args){
        JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setTitle("Test");
    frame.setLayout(new FlowLayout());
final JPanel pnl = new JPanel(){
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            Vyber v = new Vyber();
            g.drawLine(x1, y1, x2, y2); //values from method from another class
            }

A: In order to get information from one class to another, I would avoid using local variables and instead set class fields, like so:
public class SomeClass {
  Point p1;
  Point p2;

  public void actionPerformed(ActionEvent e) {

    // some code....

    int m1 = Integer.parseInt(point1.getElementsByTagName("X").item(0).getTextContent());
    int n1 = Integer.parseInt(point1.getElementsByTagName("Y").item(0).getTextContent());
    int m2 = Integer.parseInt(point2.getElementsByTagName("X").item(0).getTextContent());
    int n2 = Integer.parseInt(point2.getElementsByTagName("Y").item(0).getTextContent());

    p1 = new Point(m1, n1);
    p2 = new Point(m2, n2);
  }

  public Point getP1() {
    return p1;
  }

  public Point getP2() {
    return p2;
  }

}

Then any class that has a valid reference to the correct instance of SomeClass can simply call the getter method when it needs to obtain a current copy of p1 and p2. Having a valid reference is key since you can't re-create another SomeClass instance and expect that its fields will hold the values of another SomeClass instance that is being used by your program.
The trickier part comes if you want to get the information i an event-driven way, if you want the p1 and p2 Points, after the actionPerformed has occurred. If this is so, I'd use a PropertyChangeSupport instance to allow listeners to be notified if these fields are changed. For example, please look at this answer to see how this could possibly be done.

A: You need an instance of your class, I will use the Point class which already exists to illustrate.
Lets say I have a JTextField and I want to add an ActionListener to it, this will work:
private void addListener(final JTextField textField, final Point point) {
    textField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final double m1 = point.getX();
            final double m2 = point.getY();
        }
    });
}

The issue you will have is that in this example the Point must be final as you cannot refer to non-final method parameters in anonymous inner classes.
You could also declare your class as a class variable, something like this
//somewhere in your class
private Point point;

//somewhere else in your class
private void addListener(final JTextField textField) {
    textField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final double m1 = point.getX();
            final double m2 = point.getY();
        }
    });
}


text:
Q: Nomad failing to pull from GCP container registery due to docker auth This is my server config:
client {
    enabled = true
    servers = ["127.0.0.1:4647"]

}

I get an error of us.gcr.io/PROJECTID/IMAGE/NAME:latest: API error (404): {"message":"pull access denied for us.gcr.io/PROJECTID/IMAGE/NAME, repository does not exist or may require 'docker login'"}
I'm trying to pull an image from google cloud container registery.
How do I instruct nomad to use the docker authentication via gcloud?

A: gcloud auth configure-docker

And the server config:
client {
    enabled = true
    servers = ["127.0.0.1:4647"]

  options   = {
    "docker.auth.helper"     = "gcloud"
  }
}

I have no idea how this works when I'll need other docker auth helpers... But oh well


text:
Q: regex to get first character in a string that isn't in ('a', 'b', 'c', '.', or ' ')? can anybody help me with a regex for this? I tried on and can't get the first character in a string. Thank you.

A: Use a negative character class:
[^abc \\.]

A: ^[abc. ]*[^abc. ]

The last character of the substring that matches this regex is the character you're looking for.


text:
Q: Is it possible to checkout git branch using svn? I have a git repository that needs to be checked out on a server. I cannot install git on this server. But can is already present on it.
Is there any option by which I can checkout git branch using svn?

A: No, you can do nothing with Git, using any SVN-client


text:
Q: Sustituir imagen de usuario en Realtime Database de Firebase estando anidado Estoy intentando actualizar la imagen en todos los comentarios escritos anteriormente en los Comment, a la vez que cambio la imagen de perfil del usuario en Post. Para hacer el cambio de imagen en los 'Post' no tengo problema utilizando este método:
    `public void actualizaNombreEnTodosLosPosts(){
                String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
                DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
                DatabaseReference postsRef = rootRef.child("Posts");
                Query query = postsRef.orderByChild("userId").equalTo(uid);
                ValueEventListener valueEventListener = new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for(DataSnapshot ds : dataSnapshot.getChildren()) {
                            ds.child("userName").getRef().setValue(nombre);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
                        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
                    }
                };
                query.addListenerForSingleValueEvent(valueEventListener);

            }`

Mis Post en Realtime Database quedan así:

Los Comment:

Cuando intento actualizar la imagen en todos los Comment anteriores, no lo hace. Este es el código que no consigo que funcione.
public void actualizaImagenEnTodosLosComment(){

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference postsRef = rootRef.child("Comment").child(PostKey).child(COMMENT_KEY);
    Query query = postsRef.orderByChild("uid").equalTo(uid);
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()) {

                ds.child("uimg").getRef().setValue(String.valueOf(currentUser.getPhotoUrl()));
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
        }
    };
    query.addListenerForSingleValueEvent(valueEventListener);

}

La única diferencia que encuentro respecto a los POST, es que la imagen en los COMMENT está ANIDADA. Le añado hijos con child(...), pasando el COMMENT_KEY y el Postkey, y no consigo que funcione.


text:
Q: Add new html tag into existing component jsf 1.1/1.2 (XPages) There is a standard Pager component which renders below html structure:

      First

      Previous

          1

          2

          3

I would like to add some extra html tags like  into above structure:

      First

      Previous

I was trying to use renderer to do it but I was not able to add anything inside xspPagerContainer div. All I achieved was to add something before or after this div.
Is something like this possible? How can I add html tag to already existing component without javascript (jQuery etc.) ? Should I create own component and create own renderer ?
This is IBM variation of JSF used in Xpages.


text:
Q: Add CRL Distribution Points (CDP) Extension to X509Certificate2 Certificate I trying to add certificate extension to my X509Certificate2 object in pure .NET 4.7.2
I was using BouncyCastle by this method:
private static void AddCdpUrl(X509V3CertificateGenerator certificateGenerator, string cdptUrl)
{
    var uriGeneralName = new GeneralName(GeneralName.UniformResourceIdentifier, cdptUrl);
    var cdpName = new DistributionPointName(DistributionPointName.FullName, uriGeneralName);
    var cdp = new DistributionPoint(cdpName, null, null);
    certificateGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, new CrlDistPoint(new[] { cdp }));
}

Add its works and I get great result:

Now in pure .NET I am using this method:
const string X509CRLDistributionPoints = "2.5.29.31";
certificateRequest.CertificateExtensions.Add(new X509Extension(new Oid(X509CRLDistributionPoints), Encoding.UTF8.GetBytes("http://crl.example.com"), false));

And get this result:

I am missing the sequences for "Distribution Point Name", "Full Name" and "URL="
How can I generate the same result that BouncyCastle does with pure .NET
Thanks

A: If you only want to write one distribution point, and it's less than or equal to 119 ASCII characters long, and you aren't delegating CRL signing authority to a different certificate:
private static X509Extension MakeCdp(string url)
{
    byte[] encodedUrl = Encoding.ASCII.GetBytes(url);

    if (encodedUrl.Length > 119)
    {
        throw new NotSupportedException();
    }

    byte[] payload = new byte[encodedUrl.Length + 10];
    int offset = 0;
    payload[offset++] = 0x30;
    payload[offset++] = (byte)(encodedUrl.Length + 8);
    payload[offset++] = 0x30;
    payload[offset++] = (byte)(encodedUrl.Length + 6);
    payload[offset++] = 0xA0;
    payload[offset++] = (byte)(encodedUrl.Length + 4);
    payload[offset++] = 0xA0;
    payload[offset++] = (byte)(encodedUrl.Length + 2);
    payload[offset++] = 0x86;
    payload[offset++] = (byte)(encodedUrl.Length);
    Buffer.BlockCopy(encodedUrl, 0, payload, offset, encodedUrl.Length);

    return new X509Extension("2.5.29.31", payload, critical: false);
}

Past 119 characters the outer payload length exceeds 0x7F and then you really start wanting a proper DER encoder. You definitely want one for variable numbers of URLs, or including any of the optional data from the extension.

A: This is probably a bit late, but you could use BC as a utility to get the DER-encoded extension and import it into native .NET like so:
// req is a .NET Core 3.1 CertificateRequest object
req.CertificateExtensions.Add(
    new X509Extension(
          new Oid("2.5.29.31"),
          crlDistPoint.GetDerEncoded(), // this is your CRL extension
          false
          )
     );

A: I ran into this problem and now there is a AsnWriter available (thanks @bartonjs, looks like you got the namespace you wanted :)), if you're on at least NET5.
So I've cobbled together a method which creates the extension using the writer:
/// <summary>Derived from https://github.com/dotnet/runtime/blob/main/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Asn1/DistributionPointAsn.xml.cs</summary>
private static X509Extension BuildDistributionPointExtension(string[] fullNames, ReasonFlagsAsn? reasons, string[]? crlIssuers, bool critical) {
    var writer = new AsnWriter(AsnEncodingRules.DER);
    writer.PushSequence();
    writer.PushSequence(Asn1Tag.Sequence);

    writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0));
    writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0));
    //See https://github.com/dotnet/runtime/blob/main/src/libraries/Common/src/System/Security/Cryptography/Asn1/GeneralNameAsn.xml.cs for different value types
    for(int i = 0; i < fullNames.Length; i++) writer.WriteCharacterString(UniversalTagNumber.IA5String, fullNames[i], new Asn1Tag(TagClass.ContextSpecific, 6)); //GeneralName 6=URI
    writer.PopSequence(new Asn1Tag(TagClass.ContextSpecific, 0));
    writer.PopSequence(new Asn1Tag(TagClass.ContextSpecific, 0));

    if(reasons.HasValue) writer.WriteNamedBitList(reasons.Value, new Asn1Tag(TagClass.ContextSpecific, 1));
    if(crlIssuers?.Length > 0) {
        writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 2));
        for(int i = 0; i < crlIssuers.Length; i++) writer.WriteCharacterString(UniversalTagNumber.IA5String, crlIssuers[i], new Asn1Tag(TagClass.ContextSpecific, 2)); //GeneralName 2=DnsName
        writer.PopSequence(new Asn1Tag(TagClass.ContextSpecific, 2));
    }

    writer.PopSequence(Asn1Tag.Sequence);
    writer.PopSequence();

    return new X509Extension(new Oid("2.5.29.31"), writer.Encode(), critical);
}
[Flags] internal enum ReasonFlagsAsn { Unused = 1 << 0, KeyCompromise = 1 << 1, CACompromise = 1 << 2, AffiliationChanged = 1 << 3, Superseded = 1 << 4, CessationOfOperation = 1 << 5, CertificateHold = 1 << 6, PrivilegeWithdrawn = 1 << 7, AACompromise = 1 << 8 }

Just be careful and do your own tests as I've only checked if the CRL is properly displayed in a cert viewer.


text:
Q: Show current location in google map programmatically android I can get current location manually but I want to get it programmatically in android app. I am using LocationListener and LocationManager but I am not getting current location on map. My code is given below, anybody can guide me how can I do that?
package com.example.nabia.myapplication;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;

public class FindNearbyMosque extends AppCompatActivity implements LocationListener, OnMapReadyCallback {
    MapView gMapView;
    GoogleMap gMap = null;
    double latitude;
    double longitude;

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

        LocationManager myManager;
        myManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        myManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

        gMapView = (MapView)findViewById(R.id.map);
        gMapView.getMapAsync(this);
        gMapView.onCreate(savedInstanceState);
        gMapView.onResume(); // needed to get the map to display immediately
        try {
            MapsInitializer.initialize(this.getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onMapReady(GoogleMap map) {

        gMap = map;
        gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    }

    @Override
    public void onLocationChanged(Location location) {

        latitude = location.getLatitude();
        longitude = location.getLongitude();
        gMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude) , 14.0f) );
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

A: I have solved my problem by connecting LocationServicesthrough GoogleApiClient() as you can see in below code.
public class FindNearbyMosque extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {
    private static final int GPS_ERRORDIALOG_REQUEST = 9001;

    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    GoogleMap mMap;
    double lat;
    double lng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (servicesOK()) {
            setContentView(R.layout.activity_map);

            if (initMap()) {
                Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Map not available!", Toast.LENGTH_SHORT).show();
            }
        } else {
            setContentView(R.layout.activity_find_nearby_mosque);
        }
    }

    private boolean servicesOK() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int isAvailable = googleAPI.isGooglePlayServicesAvailable(this);
        if (isAvailable == ConnectionResult.SUCCESS) {
            return true;
        } else if (googleAPI.isUserResolvableError(isAvailable)) {
            Dialog dialog = googleAPI.getErrorDialog(this, isAvailable, GPS_ERRORDIALOG_REQUEST);
            dialog.show();
        } else {
            Toast.makeText(this, "Can't connect to google play services", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    private boolean initMap() {

        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        return (true);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        buildGoogleApiClient();
        }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            lat = mLastLocation.getLatitude();
            lng = mLastLocation.getLongitude();

            LatLng loc = new LatLng(lat, lng);

            CameraUpdate center=
                    CameraUpdateFactory.newLatLng(loc);
            CameraUpdate zoom=CameraUpdateFactory.newLatLngZoom(loc,14);
            mMap.moveCamera(center);
            mMap.animateCamera(zoom);
            mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}


text:
Q: mapply on pairs of elements in a lists in R If I have a symmetric binary operator that I want to apply over the pairs of elements from a list, is there an easy way I can do this in R? I tried:
A <- list(1,2,3)
mapply(function(x,y) x+y, A,A)

but this only gives x[n]+y[n] for all n=1..N but I want x[n]+y[m] for all m=1..n, n=1..N returned as a list. outer(..) does that for m=1..N, n=1..N which involves redundant computation so I want to discount that.
Notice I don't want solution to this simple example. I need a general solution that works for non-numeric input as well. The thing I'm trying to do is like:
mapply(function(set_1, set_2) setequal(intersect(set_1, set_2),  set_3), list_of_sets, list_of_sets)

In both cases addition and intersection are symmetric. In the first example, I expect list(3,4,5) from list(1+2,1+3,2+3). For the second case me input list_of_sets is:
> list_of_sets
[[1]]
numeric(0)

[[2]]
[1] 1

[[3]]
[1] 2

[[4]]
[1] 1 2

[[5]]
[1] 3

[[6]]
[1] 1 3

[[7]]
[1] 2 3

[[8]]
[1] 1 2 3

and set_3 being c(1,2) as a simple example.

A: You may use outer -
values <- c(1, 2, 3)
outer(values, values, `+`)

#     [,1] [,2] [,3]
#[1,]    2    3    4
#[2,]    3    4    5
#[3,]    4    5    6

outer also works for non-numeric input. If the function that you want to apply is not vectorised you can use Vectorize. Since OP did not provide an example I have created one of my own.
list_of_sets_1 <- list(c('a', 'b', 'c'), c('a'))
list_of_sets_2 <- list(c('a', 'c'), c('a', 'b'))

fun <- function(x, y) intersect(x, y)
result <- outer(list_of_sets_1, list_of_sets_2, Vectorize(fun))
result

A: We need combn to do pairwise computation without redundancy
combn(A, 2, FUN = function(x) x[[1]] + x[[2]], simplify = FALSE)

-output
[[1]]
[1] 3

[[2]]
[1] 4

[[3]]
[1] 5

This will also work with non-numeric elements
list_of_sets <- list(c('a', 'b', 'c'), "a", c("a", "c"))
combn(list_of_sets, 2, FUN = function(x) Reduce(intersect, x), simplify = FALSE)

-output
[[1]]
[1] "a"

[[2]]
[1] "a" "c"

[[3]]
[1] "a"

We may also do
combn(list_of_sets, 2, FUN = function(x)
   setequal(intersect(x[[1]], x[[2]]), set_3), simplify = FALSE)