text:
Q: How to change color of mat-chips within a mat-chip-list programmatically? I am using the mat-chips for filtering a table and everything seems to work just fine:
home.html
<mat-chip-list>
   <mat-chip (click)="onSectorChipSelect(sector)" [color]="chipColor(sector)" *ngFor="let sector of sectors" selected>{{sector}}</mat-chip>
   <mat-chip (click)="clearSectors()">
     Clear
   </mat-chip>
</mat-chip-list>

home.ts adding the sectors to a list called filteredSectors which holds all the selected sectors at a time.
onSectorChipSelect(sector: string) {
 if (this.filteredSectors.includes(sector)) {
  this.filteredSectors.splice(this.filteredSectors.indexOf(sector), 1);
 } else {
  this.filteredSectors.push(sector);
 }
}

home.ts this method colors the chip blue (primary) if selected, otherwise it stays white (basic).
chipColor(sector: string) {
  if (this.filteredSectors.includes(sector)) {
    return 'primary';
  }
  return 'basic';
}

the "problem" is that the method chipColor() is bound to the color attribute of the chip and therefore called several times when just scrolling or clicking around in the home component. My guess is that everytime the browser renders, the method is being called again? (i don't really know, maybe someone can explain?)
There are around 20 sectors so it's not really a performance issue I guess? It's just annoying to know and not a good practice I think. But how can I change that?
What I tried so far is setting the color of each chip to white (basic):
home.html
<mat-chip (click)="onSectorChipSelect(sector)" color="basic" *ngFor="let sector of sectors" selected>{{sector}}</mat-chip>

home.ts
  @ViewChild(MatChipList) chipList: MatChipList;

Getting the chipList with ViewChild annotation and then iterating over the chips and setting their color but this doesn't work. After selecting a second chip, the first chip gets a white color again.
onSectorChipSelect(sector: string) {
    if (this.filteredSectors.includes(sector)) {
      this.filteredSectors.splice(this.filteredSectors.indexOf(sector), 1);
    } else {
      this.filteredSectors.push(sector);
    }

    this.chipList.chips.forEach(chip => {
      if(this.filteredSectors.includes(chip.value)) {
        chip.selected = true;
        chip.color = 'primary';
      } else {
        chip.selected = false;
        chip.color = null;
      }
    });
}


text:
Q: connect 4 (4-in-a-row) , place a mark on the board, c program I made a connect 4 game where the player can choose the number of rows and columns.
this is my function to put the player's mark on the board:
void get_and_check_place_on_the_board (char player_sign, char board[][25], int columns_number, int rows_number, int place_on_board)
{
    int column_chosen;
    while (place_on_board[0] == -1)
    {
    do {
        printf(game_messages[MSG_GET_COLUMN]);
        scanf("%d", &column_chosen);
       } while (column_chosen <= 0 && column_chosen > columns_number);

    for (int i = rows_number - 1; i >= 0; i--)
    {
        if (board[i][column_chosen - 1] == ' ')
        {
            board[i][column_chosen - 1] = player_sign;
            place_on_board[0] = i;
            place_on_board[1] = column_chosen - 1;
            return;
        }
    }
    printf("column full");
    }
}

player_sign is "R" or "Y", the player decide the rows and columns number (not more than 25), and the place_on_board is an array, initialized to {-1, -1}.
The compiler says that: "subscripted value is neither array nor pointer nor vector", and that: "parameter 'place_on_board' set but not used"
what can i do?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django raised 'django.utils.datastructures.MultiValueDictKeyError: 'image'' at uploading image I was trying to upload an image via a form, but django raised "django.utils.datastructures.MultiValueDictKeyError: 'image'" in line 106, views.py.
I don't know what's happening, and why is throwing me an error when I submit via a custom form, but it does not happen via admin interface. Can anybody help?
My code:
models.py:
class listings(models.Model):
    is_sold = models.BooleanField(
        default=False, verbose_name="Is Sold")
    title = models.CharField(max_length=100)
    description = models.TextField(max_length=750)
    price = models.FloatField()
    user = models.ForeignKey(to=User, on_delete=models.CASCADE)
    category = models.IntegerField(default=0, choices=categoryChoices)
    image = models.ImageField(upload_to='uploads/', blank='True', null='True')
    time_posted = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-time_posted',)

    def get_image(self):
        if self.image:
            return 'http://127.0.0.1:8000' + self.image.url
        return ''

    def __str__(self):
        return f"{self.id}: {self.title}"

views.py:
def add_auction(request):
    if request.method == "POST":
        title = request.POST["title"]
        description = request.POST["description"]
        price = request.POST["price"]
        image = request.POST["image"]
        category = request.POST["category"]
        user = request.user
        listing = listings(title=title, description=description,
                           price=price, image=image, category=category, user=user)
        try:
            listing.save()
        except ValueError:
            return render(request, "auctions/add_auction.html", {
                "message": "Error adding auction."
            })
        return HttpResponseRedirect(reverse("index"))

    else:
        return render(request, "auctions/add_auction.html")

template:

Add Listing

<form action="{% url 'add_auction' %}" method="POST">

        Title
        <input type="text" class="form-control" id="title" name="title" placeholder="Title">

        Description
        <textarea class="form-control" id="description" name="description" rows="3"></textarea>

        Price
        <input type="float" class="form-control" id="price" name="price" placeholder="Price">

        Image
        <input type="image" class="form-control" id="image" name="image" placeholder="Image">

        Category
        <select class="form-control" id="category" name="category">
            <option value="1">Books</option>
            <option value="2">Clothing</option>
            <option value="3">Electronics</option>
            <option value="4">Furniture</option>
            <option value="5">Home</option>
            <option value="6">Toys</option>
            <option value="7">Vehicles</option>
            <option value="8">Other</option>
        </select>
        {% csrf_token %}
        <button type="submit" class="btn btn-primary">Submit</button>
</form>

Can anybody help me?

A: Plz correct those things
views.py
if request.method == "POST":
    title = request.POST["title"]
    description = request.POST["description"]
    price = request.POST["price"]
    image = request.FILES["image"] # <----- need to be correct this

in HTML
<form action="" method="POST" enctype="multipart/form-data">

</form>

Check those things is correct or not ???
settings.py
MEDIA_ROOT =  BASE_DIR / 'media'
MEDIA_URL = '/media/'

(urls.py) of project folder
from django.conf.urls.static import static
from django.urls import path

urlpatterns = [
    path("", include("myapp.urls")),
    path('admin/', admin.site.urls),

]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


text:
Q: public synonym creation How can I create a public synonym in oracle 7.3.4 for a common table located in different users.

A: "common table located in different users" doesn't make sense .. if each user has his/her own table in their own schema, then you have multiple tables, and a public synonym won't work.
With a public synonym you have a single table (located in a "central" schema) that everyone can use (if the appropriate rights are GRANTed, as APC has noted).
All the synonym does is that it makes addressing the table a little bit easier, instead of some_user.some_table you can use some_table.

A: You need a user with CREATE PUBLIC SYNONYM privilege.
This is not granted to non SYSDBA accounts by default, and should be granted only with due consideration.  There is a matching DROP PUBLIC SYNONYM privilege.
Remember that a synonym is just a name (an interface).  It doesn't grant privileges on the underlying object.


text:
Q: rails search db for something like a return result So i have this at the moment
    tmname = Apple

    viaurldb = Via.where('tmname LIKE ?', 'product_name?').all

At the moment i have the product_name in the Via table.
I'm wanting it to be able to search the table for tmname and return the row whats in the table.
In the table i have Granny Smiths Apples
Afterwards im looking at doing the date of this. So in the table i have
  viadate = viaurldb.specifications.split(' ')[0]

Would the above, (depending if it finds anything in the viaurldb work?)
Thanks for any help or guidance
Sam

A: You should change your first query to:
tmname   = 'Apple'
viaurldb = Via.where('product_name ILIKE ?', "%#{tmname}%").first


text:
Q: Deleting from table if check box unticked This is probably an easy one but I am stuck. I have a form with checkboxes that show employees and there skills, these are taken from a table with a many to many relationship.
The below code works for updating the records but I am unsure on how to delete records if the checkbox is un-checked
$emp=$_POST['emp'];

if(isset($_POST['chk1'])){
    $checkbox=$_POST['chk1'];
    $arr_num=count($checkbox);
    $i=0;

    while ($i < $arr_num)
    {
        $qry = "INSERT IGNORE INTO skillsets (skill_id, empr_id )VALUES(?, ?)";
        $stmt = $mysqli->prepare($qry);
        $stmt->bind_param('ii', $checkbox[$i], $emp);
        $stmt->execute();
        $i++;
    }
}
 else .... delete from .....

I am not sure of the syntax for the else, can someone help me out?

A: You can define hidden inputs for every checkbox (before it) with the same name. Eg.
<input type="hidden" name="items[1]" value="no" />
<input type="checkbox" name="items[1]" value="yes" />

1 is your item ID.
And now if checkbox is checked then its value will be send. In other case, value from hidden field will be send to your server. With this data you can iterate through items array, get ID from index and check value to know if it's checked or not.


text:
Q: Excel Workbook Opens On Only The Second Worksheet I am working on a current project with Excel VBA, and it involves opening a pre-existing workbook with content already on it.  I'm not doing anything particularly complex, only copying content from the other workbook and pasting it in the workbook that I already had open.  At any rate, when I open the workbook with VBA, it opens it on the second Worksheet, regardless of what I change my code to, which is confusing because there was a point that the code I have now worked just fine, but now it seems to be broken for whatever reason; here's the format of it as it was before it broke:
With Workbooks.Open(fileName:="C:\Users\u333161\Desktop\HGIs\GVII-G600 Stress Report Burndown Master  (plus GSNs) 3Q Rev 8-22 update.xlsx", ReadOnly:=True).Range("A1:X2500")
    'All the content that the script contains is here'
End With

Any help would be greatly appreciated; thanks so much and have a great afternoon.
For those of you that wanted the content in between the With statements, this is it:
With Workbooks.Open(fileName:="C:\Users\u333161\Desktop\HGIs\GVII-G600 Stress Report Burndown Master  (plus GSNs) 3Q Rev 8-22 update.xlsx", ReadOnly:=True).Worksheets(1).Range("A1:X2500")
'Opens the G600 Burndown from the original location ^
.AutoFilter                                                                         'Clears any filters on the document
.AutoFilter 20, "y"                                                                 'Sets "Cert Doc" to filter for "y"
.AutoFilter 13, ""                                                                  'Sets "Release Date" to (blanks)
.Rows.Sort Key1:=Columns("I"), Order1:=xlAscending                                  'Sets "3Q Replan" to sort "Oldest To Newest"
Dim columnRange As Range, cell As Range, comparingDate As Range                     'Declares variables
Set columnRange = Range("I1: I2500")                                                'Sets a variable equal to a range
For Each cell In columnRange                                                        'Loop to go through all the rows in the "I" column
  If CDate(cell.Value) > Now() Then                                                 'Compares each date in the "I" column to today
    Range("A1:X" & cell.Offset(-1, 0).Row).Copy                                     'Copies the entire range above the current if the date for the current row happens after today
    ActiveWorkbook.Close
    Exit For                                                                        'Terminates the for loop because there is no reason to keep looping
  End If                                                                            'End of the if statement
Next cell                                                                           'Goes to the next cell
End With                                                                              'We're done with this sheet, so we can end it

A: Corrected in comments, but to clarify what's wrong:
With Workbooks.Open(fileName:="C:\Users\u333161\Desktop\HGIs\GVII-G600 Stress Report Burndown Master  (plus GSNs) 3Q Rev 8-22 update.xlsx", ReadOnly:=True).Worksheets(1).Range("A1:X2500")
Here you specify a Workbook to open and it opens on "default" worksheet. Worksheet specification is used for With statement, not for Workbook.Open.
First you work with your With, but at some point you begin to work on active worksheet:
Set columnRange = Range("I1: I2500")
So you need to activate proper worksheet first:
Workbooks.Open(fileName:="C:\Users\u333161\Desktop\HGIs\GVII-G600 Stress Report Burndown Master (plus GSNs) 3Q Rev 8-22 update.xlsx", ReadOnly:=True)
Worksheets(1).Activate
With Range("A1:X2500")


text:
Q: NullPointerException creating EntityManager from EntityManagerFactory I have created a EntityManagerFactory successfully, using the persistence unit added in my persistence.xml, but the console log shows an exception when creating the EntityManager this way:
EntityManagerFactory emf;
EntityManager em;
...
emf = Persistence.createEntityManagerFactory("unidadPersistencia");
em = emf.createEntityManager(); //the error is in this line.

The app recognizes the connection and the correct table. but I am not able to create the EntityManager.
Entity:
@Entity
@Table(name = "CVINSTELEMATICA")
public class SolicitudTelematica extends AbstractEntity{

    private static final long serialVersionUID = 1L;

    @Id
    @NotNull
    @Column(name = "ID")
    private long idTelematica;

    @Column(name = "NUMEROMENORES", columnDefinition = "smallint")
    private int numeroMenores;

    @Column(name = "NIFTUTOR", columnDefinition = "nvarchar")
    private String nifTutor;

Persistence.xml:
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="unidadPersistencia"  transaction-type="JTA">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
         <class>es.xunta.amtega.vp301b.entity.SolicitudTelematica</class>
         <properties>
            <property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
            <property name="javax.persistence.jdbc.url" value="DB_URL"/>
            <property name="javax.persistence.jdbc.user" value="usr"/>
            <property name="javax.persistence.jdbc.password" value=pwd/>
         </properties>
    </persistence-unit>
</persistence>

It is possible that something is missing in the persistence file or in the entity?
Trace:
09:26:45,867 INFO  [stdout] (http-localhost/127.0.0.1:8443-2) 2019-03-26 09:26:45,865 ERROR [http-localhost/127.0.0.1:8443-2] Error: es.xunta.amtega.vp301b.interfaz.web.InterfazController.sacarString() es.xunta.amtega.transversal.archam.core.exception.InternalErrorException

09:26:45,867 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at es.xunta.amtega.transversal.archam.core.aop.LoggingAspect.translate(LoggingAspect.java:130)

09:26:45,867 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at es.xunta.amtega.transversal.archam.core.aop.LoggingAspect.logAfterExceptionThrowing(LoggingAspect.java:67)

09:26:45,867 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

09:26:45,867 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)

09:26:45,867 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

09:26:45,867 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at java.lang.reflect.Method.invoke(Method.java:606)

09:26:45,867 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:627)

09:26:45,867 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:609)

09:26:45,868 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:66)

09:26:45,868 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

09:26:45,868 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)

09:26:45,868 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

09:26:45,868 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)

09:26:45,868 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at es.xunta.amtega.vp301b.interfaz.web.InterfazController$$EnhancerBySpringCGLIB$$fa3183e9.sacarString(<generated>)

09:26:45,868 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

09:26:45,868 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)

09:26:45,868 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

09:26:45,868 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at java.lang.reflect.Method.invoke(Method.java:606)

09:26:45,868 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)

09:26:45,869 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)

09:26:45,870 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295)

09:26:45,870 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)

09:26:45,870 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at es.xunta.amtega.transversal.archam.core.web.filter.RefererManagerFilter.doFilter(RefererManagerFilter.java:78)

09:26:45,870 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246)

09:26:45,870 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)

09:26:45,870 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)

09:26:45,870 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)

09:26:45,870 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)

09:26:45,870 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,870 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)

09:26:45,871 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,871 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)

09:26:45,871 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,871 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)

09:26:45,871 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,871 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)

09:26:45,871 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,871 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)

09:26:45,871 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,871 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)

09:26:45,871 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,872 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)

09:26:45,872 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,872 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:124)

09:26:45,872 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

09:26:45,872 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,872 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)

09:26:45,872 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

09:26:45,872 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,872 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)

09:26:45,872 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

09:26:45,872 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,873 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)

09:26:45,873 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)

09:26:45,873 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)

09:26:45,873 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)

09:26:45,873 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347)

09:26:45,873 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263)

09:26:45,873 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246)

09:26:45,873 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)

09:26:45,873 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at es.xunta.amtega.transversal.archam.core.web.filter.ExecutionContextFilter.doFilter(ExecutionContextFilter.java:73)

09:26:45,873 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246)

09:26:45,873 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)

09:26:45,874 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:122)

09:26:45,874 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at es.xunta.amtega.transversal.archam.core.web.filter.ExceptionAwareMultipartFilter.doFilterInternal(ExceptionAwareMultipartFilter.java:64)

09:26:45,874 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

09:26:45,874 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246)

09:26:45,874 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)

09:26:45,874 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)

09:26:45,874 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

09:26:45,874 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246)

09:26:45,874 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)

09:26:45,874 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)

09:26:45,875 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246)

09:26:45,875 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)

09:26:45,875 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:231)

09:26:45,875 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149)

09:26:45,875 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50)

09:26:45,875 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50)

09:26:45,875 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169)

09:26:45,875 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:150)

09:26:45,875 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97)

09:26:45,875 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102)

09:26:45,875 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)

09:26:45,876 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:854)

09:26:45,876 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653)

09:26:45,876 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:926)

09:26:45,876 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at java.lang.Thread.run(Thread.java:745)

09:26:45,876 INFO  [stdout] (http-localhost/127.0.0.1:8443-2) Caused by: java.lang.NullPointerException

09:26:45,876 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:76)

09:26:45,876 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:118)

09:26:45,876 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149)

09:26:45,876 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.hibernate.jpa.spi.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1602)

09:26:45,877 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.hibernate.jpa.spi.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:210)

09:26:45,877 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.hibernate.jpa.internal.EntityManagerImpl.<init>(EntityManagerImpl.java:91)

09:26:45,877 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.hibernate.jpa.internal.EntityManagerFactoryImpl.internalCreateEntityManager(EntityManagerFactoryImpl.java:345)

09:26:45,877 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.hibernate.jpa.internal.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:313)

09:26:45,877 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at es.xunta.amtega.vp301b.interfaz.web.InterfazController.sacarString(InterfazController.java:122)

09:26:45,877 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at es.xunta.amtega.vp301b.interfaz.web.InterfazController$$FastClassBySpringCGLIB$$3a2d1d25.invoke(<generated>)

09:26:45,877 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)

09:26:45,877 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)

09:26:45,877 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)

09:26:45,877 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62)

09:26:45,877 INFO  [stdout] (http-localhost/127.0.0.1:8443-2)   ... 90 more

I am using JBoss EAP 6.1 and Java 7.

A: I think when you are using JTA as a transaction type you must be in a JEE environment so the container (JBoss, in your case) will handle the entity manager with the annotation @PersistenceContext, but here you are handling the entity manager by yourself, creating the entity manager factory, you are not in JEE environment, you are just using Java SE, so I think you must change transaction-type="JTA" to transaction-type="RESOURCE_LOCAL" in your persistence unit XML file.


text:
Q: CasperJS looping through each URL This question is similar to others, but the problem I had was more basic.
This is my code:
var links = [];
var casper = require('casper').create();

function getLinks() {
    var links = document.querySelectorAll('div#mw-content-text table.wikitable tbody tr td i b a');
    return Array.prototype.map.call(links, function(e) {
        return 'https://en.wikipedia.org' + e.getAttribute('href');
    });
}

casper.start('https://en.wikipedia.org/wiki/David_Bowie_discography');

casper.then(function() {
    // aggregate results for the 'casperjs' search
    links = this.evaluate(getLinks);
});

casper.each(links, function (self, link) {
    self.thenOpen(fullURL, function () {
        this.echo(this.getTitle() + " - " + link);
    });
});

casper.run();

I know that links get created as it is copied from the Quickstart, but I then modified it to open all the links that were found.
What I'm getting is that nothing is echo'd instead of outputting the each title which is what I expect. This is how I'm calling the file:
~ $ casperjs casper-google-disco.js

A: The fix was very easy in the end, but took me ages to find it as there were no errors and no-one else seemed to have hit this.
The problem is that the links variable doesn't get set before the each is called. Putting the each inside the then function solves my problem.
The each.js example in the CasperJS samples was helpful for confirming that you can loop through an array without any need for IIFE.
var links = [];
var casper = require('casper').create();

function getLinks() {
    var links = document.querySelectorAll('div#mw-content-text table.wikitable tbody tr td i b a');
    return Array.prototype.map.call(links, function(e) {
        return 'https://en.wikipedia.org' + e.getAttribute('href');
    });
}

casper.start('https://en.wikipedia.org/wiki/David_Bowie_discography');

casper.then(function() {
    // aggregate results for the 'casperjs' search
    links = this.evaluate(getLinks);

    casper.each(links, function (self, link) {
        self.thenOpen(link, function () {
            this.echo(this.getTitle() + " - " + link);
        });
    });
});

casper.run();


text:
Q: Vanishing Gaussian curvature So let us assume that we have a surface in $\mathbb{R}^3$ with its first fundamental form $ds^2=E(u)du^2+G(v)dv^2$. Does its Gaussian curvature vanish? The answer is supposed to be yes, and I tried computing the Gaussian curvature using the intrinsic formula $K=R_{121}^\ell g_{\ell2}/g$ where $g$ is the determinant of the metric tensor, but I wasn't able to get everything to cancel. I was hoping someone could do the computation so I can identify where I'm going wrong.
EDIT Here is what I got. Let us assume the chart were working in is $x(u,v)$.
$$
\begin{align}
\Gamma_{11}^1&=\frac{\partial_1E}{2}E^{-1}\\
\Gamma_{12}^1&=0\\
\Gamma_{22}^1&=0\\
\Gamma_{11}^2&=\langle x_{11},x_2\rangle g^{22}\\
\Gamma_{12}^2&=0\\
\Gamma_{22}^2&=\frac{\partial_2G}{2}G^{-1}
\end{align}
$$
Using the intrinsic formula I got
$$K=\frac{\partial_2\langle x_{11},x_2\rangle G}{G^2}-\frac{\langle x_{11},x_2\rangle \langle x_{22},x_2\rangle}{G^2}$$

A: I think in your case you should use Brioschi Formula. Since $E=E(u)$ and $G=G(v)$ and $F=0$, hence by the above formula, Gaussian Curvature, $K=0$.


text:
Q: Word for politicians and judges Is there a word to describe a group of politicians and judges?
The best I came up with is "public figures" which is both too wide (there are lots of public figures which are not politicians or judges) and too long. Is there a single word grouping or describing politicians and judges?

A: The most specific term I can think of that encompasses both is official, but it may not be narrow enough for your purpose.

official
noun: official; plural noun: officials

*

*a person holding public office or having official duties, especially as a representative of an organization or government
  department.ODO

A: Office holder: A person who holds a position of authority or service, especially within a government or government organization.

A: That can be a magistrate, but by his ancient meaning:
In ancient Rome, a magistratus was one of the highest government officers and possessed both judicial and executive powers.
But it's more a person with both the role of a politician and a judge than a group of those two types of people.

A: If you aren't too fussy, legislators will be understood. Technically, judges administer the law rather than make it, but anyone involved knows the line is a fuzzy one, and only matters if you are discussing fine constitutional points.


text:
Q: encodeURIComponent() difference with browsers and [ä ö å] characters I have a problem with encodeURIComponent() as it seems to behave differently than browsers (tested with Chrome and Firefox):

*

*encodeURIComponent('ä') returns %C3%A4

*escape('ä') returns %E4

*Chrome/Firefox encodes ä in x-www-form-urlencoded forms as %E4
So, why does encodeURIComponent behave differently than all the others (mainly browsers)? This actually causes problems as some websites don't understand what I'm trying to feed them. The website in question is http://verkkopalvelu.vrk.fi/Nimipalvelu/default.asp?L=1 (click "Etunimihaku" as it is iframe based).
Is encodeURIComponent broken and how should this situation be corrected? What would be the correct way to encode characters like ä ö å? escape() seems to encode the same as those browsers, but escape() is deprecated.
I tested the browsers with Fiddler and also the Console/Network tab shows the encoding as %E4 when I submit a form. Also a test link here: A http://jsfiddle.net/tcyfktvg/1/

A: encodeURIComponent() is not broken. It encodes the chars using UTF-8 char set. Always. (ECMAScript 3rd Edition (ECMA-262) page 82)
escape() uses Unicode for encoding (ECMAScript 1st Edition (ECMA-262) page 60). If the unicode code is < 256 then the simple two letter representation is used, as you see for "ä". If the unicode code is >= 256, then the extended four char representation with a leading "u" is used. Example: escape("겧") == "%uACA7".
The problem arises when a http server receives a encoded URL. It has to decode it. But the URL itself doesn't tell which encoding was used to create it.
This URL: http://server/%C3%A4 could be a http://server/ä if it was encoded by encodeURIComponent() (using UTF-8), but it could also be a http://server/ä encoded by escape() (using Unicode):
encodeUriComponent("ä") == "%C3%A4"
escape("ä") == "%C3%A4"

It's up to the configuration of the server which encoding it will use to decode the URL. So here's the solution to your problem: know which URL encoding the http server expects and choose the appropriate encoding method.


text:
Q: How to use javascript to get the value of checked checkbox dynamically I'm new to JavaScript.
I have a webpage that the users can search the document ID and add it to their favourite. after submitting the search criteria, it shows a list ID and a checkbox next to it. so the user can check the checkbox or uncheck it to add and remove them from their list.
My issue is my code can't get the value of the checkbox generated. for example, there are three checkbox generated, chk1,chk2,chk3. when none of them are checked, my code is working I can get the value of the checkbox. but when one of them is checked for example, chk3 is checked, when I check chk1, it still shows the value of chk3 rather than chk1. I want to get the value of that checkbox just checked. I'm struggled to make it right.

<%do until results_rs.EOF%>
   <%Response.Write results_rs("id")%>
   <input type="checkbox" id="myCheckbox" name ="myf[]" value="<%=results_rs("id")%>" onchange="myfc()">

    <%results_rs.MoveNext%>

A: The minimal change would be to pass this into myfc:
onchange="myfc(this)"

...and then use that in myfc:
 function myfc(cb){
    alert(cb.value);
 }

But you might look into more modern event handling with addEventListener and such.

Note that there's no need to put an id on the checkbox, and in fact, it's invalid to have more than one checkbox with the same id, so probably best to just remove the id="myCheckbox" part entirely.

A: IDs in JS must be unique. Use a class class="myCheckbox"
Then you can do
window.addEventListener("load",function() {
  var checks = document.querySelectorAll(".myCheckbox");
  for (var i=0;i<checks.length;i++) { // all .myCheckbox
    checks[i].addEventListener("click",function() {
      console.log(this.checked,this.value); // this specific box
      var checks = document.querySelectorAll(".myCheckbox:checked");
      for (var i=0;i<checks.length;i++) { // all CHECKED .myCheckbox
        console.log(checks[i].value); // only checked checkboxes are shown
      }
    });
  }
});

In your case for example
window.addEventListener("load",function() {
  var checks = document.querySelectorAll(".myCheckbox");
  for (var i=0;i<checks.length;i++) { // all .myCheckbox
    checks[i].addEventListener("click",function() {
      if (this.checked) myfc(this.value); // this specific box
    });
  }
});


text:
Q: ASP.NET MVC - Merge Multiple Small Apps We have a number of small ASP.NET MVC apps. All are basically a bunch of forms which capture data and store them in a SQL Server database, usually which are then loaded through to our datawarehouse and used for reporting.
We are looking to rewrite all the small applications and apply a level of consistency and good practice to each. All the applications are fairly similar and I think from a user perspective it would be better if they seemed to be part of the same large application so we were considering merging them together in some way as part of the re-write.
Our two currently preferred options seem to be:

*

*Create a separate portal application which will be the users point of entry to the apps. This could have 'tiles' on the homepage, one for each of the apps (which would be registered in this parent app) and could link them through to all. In this scenario all the Apps would remain in different projects and be compiled/deployed independently. This seems to have the advantage of keeping the separate so we can make changes to an app and deploy without affecting the others. I could just pull common code out into a class library? One thing that annoys me about this is that the parent app must basically use hard coded links to link to each app.

*I looked into using 'areas' in ASP.NET MVC and have all the small apps as different areas in one big project. This seems kindof cleaner in my head as they are all in one place, however it has the disadvantage of requiring the whole app deployed when any of the individual ones are changed, and I have a feeling we will run into trouble after adding a number of apps in to the mix.

*We have a SharePoint installation and someone suggested creating the portal type app in SharePoint... This doesn't sound like the best idea to me but am willing to consider if anyone can point out advantages to this method.
Are there any recommendations on the architecture of this? Has anyone completed similar projects in the past and something worked well/not well?
We have 4 developers and we do not expect the apps to change too much once developed (except to fix potential bugs etc.). We will however plan to add new apps to the solution as time goes on.
Thank you

A: MVC Areas advantage would be allowing code sharing, by refactoring the repeated redundant parts of each app to use the same infrastructure code (security, logging, data access, etc.)
But it will also mean more conflicts when merging the code initially.
Deployment concerns can be mitigated with a continuous deployment tool (there are many in the market) or if you deploy to an Azure WebApp, then deployment slots can give you a zero down time deployment.


text:
Q: Watch Service Java 7 polling loop I was a bit surprised that Watch Service should be implemented as a process/thread with a polling loop. I don't remember any other API in Java that is supposed to do it.
Wouldn't it be much better to implement it as a set of callbacks (listeners, observers, etc..)?
BTW - is there any third-party library that does pretty much the same, but using callbacks model?

A: Apache Commons has some file watching services which I think are much better than the ones in Java 7. Im not sure if they use callbacks, but they are much more intuitive in my opinion.
And yes, I think that an observer model would be much better. I read somewhere that its a bit tougher to do this with Java because it runs through a virtual machine, and to get listeners on files you need to talk directly to the OS. Im not sure of the details or validity of this though.

A: I build on Alexeis answer, but I don't think he was clear enough... look at this example code:
WatchService service = dir.getFileSystem().newWatchService();
WatchKey key = dir.register(service, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
System.out.println(key);

for(;;) {
    WatchKey k = service.take();
    System.out.println(k);
    for(WatchEvent<?> ev:k.pollEvents()) {
        System.out.println(ev.kind());
        if(ev.kind() == OVERFLOW) continue;
        //TODO
        System.out.println(ev.context());
    }
    if(!k.reset()) break;
}

key.cancel();

If you check the println(key) / println(k) outputs, you'll see that the same object is returned over and over; take() returns every time that key is signalled, so to use multiple keys with the same WatchService, just check what key was returned every time. That also means that your loop blocks as long as the key was not signalled - exactly what you want.
the if(!k.reset()) break; is crucial too; this is what I forgot when writing my comment on Alexeis answer. My assumption was that take() is called by register(), and thus no key should be returned in my user code, because register() already consumed it. With that mis-assumption, I didn't recognize what was actually going on.

A: You don't have to use polling, you can use WatchService.take(), which returns immediately when a change occur. Yes it requires a thread, but single thread can be used for multiple objects being watched. So it is easy to implement a singleton which owns a watching thread and allows to register callbacks for each object.
As for third party libraries, look at Guava EventBus. I did not try it and am not sure if it fits your needs.


text:
Q: HTMLUnit and handling cookies ("WARNING: Cookie rejected") I'm looking for a way to accept cookies (all cookies) using HTMLUnit
I'm trying to login to my wordpress site using HTMLUnit but I can't submit the form (and therefor can not login) when the cookies are rejected as my error is:

Jul 14, 2012 10:42:24 PM
  org.apache.http.client.protocol.ResponseProcessCookies processCookies
  WARNING: Cookie rejected:

CODE:
package backend;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Set;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;

public class temp {

    WebClient myClient = new WebClient(BrowserVersion.FIREFOX_3);
    CookieManager cm = new CookieManager();
    HtmlPage page;

    public void Someting() throws FailingHttpStatusCodeException, MalformedURLException, IOException{

    //Disabling Javascript for now.
    myClient.setJavaScriptEnabled(false);
    myClient.setCssEnabled(false);
    myClient.setCookieManager(cm);

    page = myClient.getPage("http://nick.wordpress.com/wp-admin");

    Set<Cookie> cookies = myClient.getCookieManager().getCookies();

    System.out.println("Page status code: " + page.getWebResponse().getStatusCode() + "\nPage status message: "  + page.getWebResponse().getStatusMessage());

    if(cookies != null)
    {
        for(Cookie cookie : cookies)
        {
            this.myClient.getCookieManager().addCookie(cookie);
        }
    }

    System.out.println("We have: " + myClient.getCookieManager().getCookies().size() + " cookie");
    }

    public static void main(String args[]) throws FailingHttpStatusCodeException, MalformedURLException, IOException{
        temp t = new temp();
        t.Someting();
    }
}

This code is excluding the WordPress form filling/submitting function as this doesn't seem relevant.
When searching the web I could only find 1 or 2 vague answers where I should modify the "http.client.protocol.ResponseProcessCookies" class but I hope it can be done without this.

A: You question is answered here
You have to recreate the  CookieManager class.
Find the method public synchronized Set<Cookie> getCookies(final URL url) and remove the statement if (spec.match(cookie, cookieOrigin)).


text:
Q: Speed Impact of a WHERE Clause in a SQL Update I have a very simple SQL Update command on a DB2 (IBM System I) table, which holds approx. 30 million records.
UPDATE tablename SET field = 0 where field > 0

Now, given that the field never can be < 0 and is not nullable, isn't the "where" clause unnecessary? Does the WHERE clause have an impact of the duration of this process?
From what I understand, it is unnecessary and has an impact on the speed because the database has to evaluate each record. I am trying to find this out, because I cannot run the SQLs myself and our subcontractor says it has no impact; and we don't have the knowledge to prove / falsify that.

A: If the column type for field can be NULL it does have an impact. NULL would evaluate to false in field > 0. If field is set to a value only after you get some data ie lets say that field represents emails sent today and the original DBA let field be NULL ie for Unknown. If you run this
UPDATE tablename SET field = 0;

Everyone gets reset and you lose the ability to find out how many people never sent an email, ever ie.
select count(*) from tablename where field = NULL

So depending on your schema and semantics it can mean quite a bit. Note, this is an example, I'm not suggesting it's a good design or a good use for NULL.

A: Conclusion: if there is no 0 in the field column, the where only has a very small difference in runtime.
If there are a few 0's a where soon gets faster
The where clause soon wins in speed and imo should always be in the query if there is a possibility of 0's in the field column
I made a db table with 4.967.877 rows.
I filled half of the rows with 0, the other half with 1
UPDATE HugeDummyTable
SET field = 0
WHERE HugeDummyTableID < 2483938

UPDATE HugeDummyTable
SET field = 1
WHERE HugeDummyTableID >= 2483938

The query with the where:
SET STATISTICS TIME ON
UPDATE HugeDummyTable SET field = 0 where field > 0

gives result:
SQL Server Execution Times:
CPU time = 1829 ms,  elapsed time = 1842 ms.
(2483940 row(s) affected)

Resetting the table with the same first query.
Doing the query without the where
SET STATISTICS TIME ON
UPDATE HugeDummyTable SET field = 0

Gives this result:
SQL Server Execution Times:
CPU time = 2765 ms,  elapsed time = 2791 ms.
(4967877 row(s) affected)

So I think the where makes the query faster.
EDIT after comments: Filled the column 'field' with random numbers
To make sure I'll be using the same table with the 2 try's I make a backup.
Update HugeDummyTable
SET field = ABS(Checksum(NewId()) % 100000)

Taking a look at how much 0's I have:
SELECT COUNT(field)
FROM HugeDummyTable
WHERE field = 0
"45"

Running the query with the where:
SET STATISTICS TIME ON
UPDATE HugeDummyTable SET field = 0 where field > 0

SQL Server Execution Times:
CPU time = 3313 ms,  elapsed time = 3325 ms.

(4967829 row(s) affected)

Restored table, reran without where:
SET STATISTICS TIME ON
UPDATE HugeDummyTable SET field = 0

SQL Server Execution Times:
CPU time = 3094 ms,  elapsed time = 3121 ms.

(4967877 row(s) affected)

The difference is smaller, but still there. The where seems to cut off a bit of time, even with only 45 records difference.
Edit 2: tested with no 0's
This time there is no 0 in the field column
Without where
SQL Server Execution Times:
CPU time = 3109 ms,  elapsed time = 3238 ms.

With where
SQL Server Execution Times:
CPU time = 3172 ms,  elapsed time = 3337 ms.


text:
Q: Excel macro does not rename data series if triggered via ole I have a Excel macro that creates some charts and assigns the series data ranges and series names like
Dim srsIdx
For Each srs In ActiveChart.SeriesCollection
   srs.xValues = ...
   srs.name = "series_name " & seriesIdx
   srsIdx = srsIdx + 1

(just a small part of the macro)
Works fine if I trigger the macro from the editor or a push button within the workbook, but if I trigger it via OLE the names are not changed but the data ranges and everything else like textboxes, headlines, etc. is as expected.
Any idea what is going on here?


text:
Q: Probability that you're on a cancelled flight Let's say that I fly around four times per year, and one in every hundred flights is cancelled. What is the probability that I end up on a cancelled flight in a given year?
My intuition is that I can take the odds that all four flights aren't cancelled ($\bar p$), and subtract that from 1:
$$1 - \bar p^4 = 1 - 0.99^4 = 0.03940399 \approx 4\%$$
Is this correct, and if not, what should I have done instead?
EDIT:
My first version of the math assumed two flights a year and not four. Silly me :)


text:
Q: List of specific class names in Python Is there a way to flag class declarations so that later you can get a list of them flagged?
Or a way to get all classes starting with a certain string ?
Or all classes that are a subclass of a specific class?

A: Note: in the following I assume Python 3.x. For Python 2.x, use new style classes, i.e. write class T(object): pass instead of class T: pass.

*

*First, define some classes:
>>> class T: pass
...
>>> class S: pass
...
>>> class U(T): pass
...

*To get a list of classes defined in the current scope, iterate over the globals (or locals) and test whether they are an instance of type (thus a class!) using isinstance:
>>> [n for n, o in globals().items() if isinstance(o, type)]
['S', 'U', 'T']

*Use issubclass to restrict your search to the subclasses of a given class (in this case T):
>>> [n for n, o in globals().items() if isinstance(o, type) and issubclass(o, (T,))]
['U', 'T']

*You may want to omit T itself:
>>> [n for n, o in globals().items() if o != T and isinstance(o, type) and issubclass(o, (T,))]
['U']

*To get all classes starting with a certain string, call startswith on the class name:
>>> [n for n, o in globals().items() if n.startswith('T') and isinstance(o, type)]
['T']

*To flag certain classes at creation, use a class decorator† to add an attribute, e.g. __flagged__:
>>> def flag(cls):
...     cls.__flag__ = 'flagged'
...     return cls
...
>>> @flag
... class X: pass
...
>>> @flag
... class Y: pass
...
>>> class Z: pass
...

*Now you can just select only those classed with the __flag__ attribute:
>>> [n for n, o in globals().items() if isinstance(o, type) and hasattr(o, '__flag__')]
['X', 'Y']

  †: As bobince notes, class decorators are new in Python 2.6.

A: You can also use metaclasses to collect up the classes as they are defined:
class AllSeeingMetaClass(type):
    # This will be a list of all the classes that use us as a metaclass.
    the_classes = []

    def __new__(meta, classname, bases, classDict):
        # Invoked as new classes are defined.
        print "Defining %r" % classname
        new_class = type.__new__(meta, classname, bases, classDict)
        meta.the_classes.append(new_class)
        return new_class

class MyBase(object):
    # A base class that pulls in our metaclass.
    __metaclass__ = AllSeeingMetaClass

class Cat(MyBase):
    def __init__(self):
        pass

class Dog(MyBase):
    def __init__(self):
        pass

print AllSeeingMetaClass.the_classes

prints:
Defining 'MyBase'
Defining 'Cat'
Defining 'Dog'
[<class '__main__.MyBase'>, <class '__main__.Cat'>, <class '__main__.Dog'>]

A: To get a list of subclasses of your class from within itself, use the __subclasses__ method from the parent class.
>>>class Parent(object):
...    pass
...
>>>class Child(Parent):
...    pass
...
>>>Parent.__subclasses__()
>>>[<class '__main__.Child'>]

Unfortunately there is a dearth of documentation on this method.


text:
Q: Get radio button value on form post in Zend Form i have an element of type Radio in zend form .
how can i get value of radio button on form post.
keep in mind i am using Zend Form
if ($this->_request->isPost()) {
    if ($form->isValid($_POST)) {
        $values = $form->getValues();
    }
}

i am already doing the above code it is really correct way to get values of posted elements but for radio button it only posts the last value of that radio button.
for example: my radio button is like
$type = array("0"=>"0", "1"=>"1", "2"=>"2")
// add Order element
   $order = $this->CreateElement('Radio', 'order');
   $order->setMultiOptions( $type );
   $elements[] = $order;

then after post it always returns : order = 2
On the other hand, if i use the same code while json = False like:
// ------------------------------------------------
// prepare the form for ProductInfo
// ------------------------------------------------
$productinfo = new Form_ProductInfo();
$this->view->productinfo = $productinfo;
$this->view->productinfo->setAction($this->view->url());
$this->view->jsonEncoded = false;

then it works fine & pick selected radio button value.

A: By Using Zend_Form
Just check your radio button name by viewing source code of your page and replace it in Controller file,if u want to set the names of your input control then go throw helper class.

A: If you have the following HTML:
<input type="radio" name="radioButtonName" value="someValue">

You can use the following PHP (plain PHP, not Zend Framework-specific) code in the page that handles the POST request:
<?php echo $_POST['radioButtonName']; ?>

A: if ($this->_request->isPost()) {
    if ($form->isValid($_POST)) {
        $values = $form->getValues();
    }
}

You can than access the value of your form element from the $value variable.
$vale['name-of-the-radio-button-element']

EDITED
For the example you have provided in the comment:
    $form = new Zend_Form();
    $type = array("0"=>"0", "1"=>"1", "2"=>"2");
    // add Order element
    $order = $form->createElement('Radio', 'order');
    $order->setMultiOptions( $type );
    $form->addElement($order);
    $form->addElement(new Zend_Form_Element_Submit('submit'));
    echo $form;

    if ($this->_request->isPost()) {
        if ($form->isValid($_POST)) {
            $values = $form->getValues();
            var_dump($values['order']);
        }
    }

This will dump the selected value of the $order element.


text:
Q: extract a value from returned json I have the following json return from the url:
{"token_type":"Bearer","expires_in":"3599","expires_on":"1433956297","not_before":"1433952397","resource":"https://outlook.office365.com/","access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQi????...."

I want to extract the access_token in ASP.NET VB, but no matter what I try, it generates error. What is the the best solution to do this?
This is my code:
Dim parsedObject = JObject.Parse(<json string>)
Dim docs = parsedObject("access_token")

For Each doc In docs
    Dim snippet As String = doc("access_token")
Next

label1.text = snippet

A: Your variable snippet is not accessible outside the loop: you can't access it outside of the loop.
Step thru your debugger: you need to figure out what the value and data type of docs are before you go any further. Since you're already referring to the value of "access_token" from docs, you probably can't get it again from the resultant value. I'm guessing it should just give you a string; it's hard to say without the error.


text:
Q: My Program Creates 1 Ball not 2 I made a program that creates a frame and then creates 2 balls and moves them around seperately, my problem is that somehow the first or second ball is getting the coordinates of the other, and therefore are being painted on each other, sorry for the bad indentation this is my first time posting a question .
Main Class:
    public class Game extends JPanel {
        Ball ball01 = new Ball();
        Ball ball02 = new Ball();
        int ball01x = 0,ball01y = 0,ball02x = 0,ball02y = 0;
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.fillOval(ball01x, ball01y, 10, 10);
        g2d.setColor(Color.RED);
        g2d.fillOval(ball02x, ball02y, 10, 10);
    }

    public static void main(String[] args) throws InterruptedException {
        JFrame frame = new JFrame("Sample Frame");
        Game game = new Game();
        frame.add(game);
        frame.setSize(400, 400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        game.createBalls();
        while (true) {
            game.getCoords();
            game.updateBalls();
            game.repaint();
            System.out.println("Ball01 x: " + game.ball01x + " Ball02 x " + game.ball02x);
            Thread.sleep(10);
        }
    }

    public void getCoords(){
        ball01x = ball01.getX();
        ball01y = ball01.getY();
        ball02x = ball02.getX();
        ball02y = ball02.getY();
    }

    public void createBalls(){
        ball01.create(300,300);
        ball02.create(50,20);
    }

    public void updateBalls(){
        ball01.Ball();
        ball02.Ball();
    }
}

Ball Class:
public class Ball{
    private static int x;
    private static int y;
    private static int xSize = 30;
    private static int ySize = 30;
    static boolean xright = true,ydown = true;
    static boolean grow = false;
    public void Ball(){
        this.moveBall();
        this.ballSize();
    }

    public void create(int startX, int startY){
        this.x = startX;
        this.y = startY;
    }

    private void moveBall() {
        if(this.x >= 370){
            xright = false;
        }
        if(this.x <= 0){
            xright = true;
        }
        if(this.y >= 370){
            ydown = false;
        }
        if(this.y < 0){
            ydown = true;
        }

        if(xright == true){
            this.x = this.x + 1;
        }else if (xright == false){
            this.x = this.x - 1;
        }

        if(ydown == true){
            this.y = this.y + 1;
        }else if (ydown == false){
            this.y = this.y - 1;
        }

    }

    private void ballSize(){
        if (xSize <= 5 && ySize <= 5){
            grow = true;
        }else if (xSize >= 10 && ySize >= 10){
            grow = false;
        }

        if (grow == true){
            xSize = xSize + 1;
            ySize = ySize + 1;
            //System.out.println("Debug");
        }else if (grow == false){
            xSize--;
            ySize--;
            //System.out.println("Debug");
        }
    }

    public int getX(){
        return x;
    }

    public int getY(){
        return y;
    }
}


text: Q: Role based registration in wordpress I have a requirement to register users in two different categories like Employer and Job seeker. So I need two separate registration page for two type of users. I couldn't find any suitable plugin for that. and each user will get assigned their roles depending the page submission. If an Employer is logged in they have to post their jobs and their informations, can view the applications against their posted jobs, and if a job seeker gets logged in they have the access to view the jobs, apply against jobs, can read reviews about their applications etc. I am a newbie to wordpress. I need a guidance regarding this.


text:
Q: CA0001: Object reference not set to an instance of an object Please read the question first, before flagging it as duplicate for "Object reference not set to an instance of an object"
I run a build with SonarQube. I get the following error:
CA0001 : Rule=Microsoft.Design#CA1011, Target=Company.Project.Service.Report.Wrappers.Helper.ReportPrintingOrderDriver`2.#DrivePrintingProcess(Company.Product.Service.Contracts.Report.CommonExportReportRequest,Company.Project.Common.Containers.LIHierarchy`3<!0,!1,System.Int32>,Company.Project.Service.Report.Wrappers.Helper.ReportPrintingOrderDriver`2<!0,!1>+IReportPrintingOrderDriven) : Object reference not set to an instance of an object.

The error happens since I turned on NDepend Analysis in SonarQube.
I tried excluding the File from Analysis by adding it to the Source File Exclusions in the SonarQube Analysis scope. When that did not work, I added a exclusion into the csproj file:
<Compile Include="Wrappers\Helper\ReportPrintingOrderDriver.cs" >
        <!-- Exclude the file from analysis -->
       <SonarQubeExclude>true</SonarQubeExclude>
</Compile>

But unfortunately, the error still keeps popping up. When I run the Visual Studio Code Analysis for the project, the same error appears. So I think it has nothing to do with NDepend. After turning off all the NDepend rules, the error still fails the build.
NDepend Support referred me to the following WebSite
The class that it cannot analyse starts like this:
public class ReportPrintingOrderDriver<TInnerNode, TDataNode> where TDataNode : IComparable<TDataNode>, IMergeable<TDataNode>
    {
      ...
    }

Any suggestions how to get rid of this error?

A: I don't have a way to fix this error. But there is a workaround. It is a known issue of the Microsoft Code Analysis that occurs, when a generic class contains and uses an interface. The issue can be found on Microsoft Connect. The linked issue contains an Attachment which reproduces the problem.
The workaround is to extract the interface and define it outside of the generic class.


text:
Q: \mathellipsis in XeLaTeX with mathspec Following the solutions Punctuation marks in math mode in xetex/mathspec and XeTeX/mathspec punctuation issue, I am making adjustments to mathspec to force XeTeX to use punctuation marks of the appropriate font. However, the spacing of ellipsis cannot be done properly when it is followed by a comma. LaTeX, of course, has no problem. MWE (pdftex gives an error on ^^^^ characters, but it doesn't matter; Old Standard is a free font):
\documentclass{article}
\usepackage{amsmath}
\usepackage{iftex}
\ifXeTeX
\usepackage{mathspec}
\defaultfontfeatures{Mapping=tex-text}
\setallmainfonts{Old Standard}
\makeatletter
\def\eu@MathPunctuation@symfont{Latin:m:n}
\DeclareMathSymbol{,}{\mathpunct}{\eu@MathPunctuation@symfont}{`,}
\DeclareMathSymbol{.}{\mathord}{\eu@MathPunctuation@symfont}{`.}
\XeTeXDeclareMathSymbol{^^^^2026}{\mathinner}%
        {\eu@MathPunctuation@symfont}{"2026}[\mathellipsis]
\makeatother
\fi
\begin{document}
$\left<i_1, i_2,\ldots,i_n\right>$
\end{document}

Does anyone have a suggestion on what to do?

A: Maybe this is what you're looking for:
\documentclass{article}
\usepackage{amsmath}
\usepackage{mathspec}
\usepackage{newunicodechar}

\defaultfontfeatures{Ligatures=TeX}% not needed with last version of fontspec
\setallmainfonts{Old Standard}

\makeatletter
\def\eu@MathPunctuation@symfont{Latin:m:n}
\DeclareMathSymbol{,}{\mathpunct}{\eu@MathPunctuation@symfont}{`,}
\DeclareMathSymbol{.}{\mathord}{\eu@MathPunctuation@symfont}{`.}
\XeTeXDeclareMathSymbol{^^^^2026}{\mathinner}%
        {\eu@MathPunctuation@symfont}{"2026}[\mathellipsis]
\AtBeginDocument{\renewcommand{\mathellipsis}{\mathinner…}}
\newunicodechar{…}{\ifmmode\mathinner…\else…\fi}
\makeatother

\begin{document}
Here… again

Here\ldots{} again

$\langle i_1, i_2,\ldots,i_n\rangle$

$\langle i_1, i_2,\dots,i_n\rangle$ % better!

$\langle i_1, i_2,…,i_n\rangle$

\end{document}

Note that … is not defined as \mathinner, whereas \mathellipsis just does … (by default). So I redefine \mathellipsis and also the action of …, so it should be correct in all cases.


text:
Q: cakePHP renaming Database names I have spend hours trying to find where this issue is.
I have a database called tapplicant with a corresponding TapplicantController and Tapplicant model.
The View folder is called Tapplicant.
When ever i query e.g : $count = $this->Tapplicant->find()
It always looks for database table 'tapplicants' , it adds a 's'.

A: I assume you mean to say you have a table name tapplicants, not a database.
By default, Cakephp uses the plural form of the model name. If you need to change the table name, use useTable.
In your Tapplicant model:
public useTable = 'tapplicant';


text:
Q: Python 3.4.2 urllib Error: urllib.error.HTTPError: HTTP Error 403: Forbidden I run the following program:
import urllib.request

def download_web_image(url):
    full_name = "test.pdf"
    urllib.request.urlretrieve(url, full_name)

download_web_image("http://papers.xtremepapers.com/CIE/Cambridge%20IGCSE/Mathematics%20(0580)/0580_s03_qp_1.pdf")

but then get the following error:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 579, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden

A: try this
import urllib.request

def download_file(url, filename):
    downloaded_file = open(filename, "wb")
    req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    file_on_web = urllib.request.urlopen(req)
    print("downloading...")
    while True:
        buf = file_on_web.read(65536)
        if len(buf) == 0:
            break
        downloaded_file.write(buf)
    downloaded_file.close()
    file_on_web.close()
    print("done")

url=r'http://papers.xtremepapers.com/CIE/Cambridge%20IGCSE/Mathematics%20(0580)/058 0_s03_qp_1.pdf'
name = 'test.pdf'
download_file(url,name)


text:
Q: ASP.NET treeview manipulation api for jquery? In my asp.net solution, I have a asp.net tree view, and I want to make some client side manipulations to it. I am basically looking for a way in jQuery, to do

*

*iterate through all root nodes

*iterate through all sub nodes given a node

*get the text of the given node

*get the value of the given node

*add a blue highlight around the text of the given node

*expand/collapse given node

I don't want to use any other kind of jQuery tree view plugins either. Does anyone know if there is a project that someone did to do this? Or can provide links or code to do this?
Thanks.

EDIT :
Here is an example of the HTML structure:

                <A id=ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewt0 class="ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_0 ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_1" onclick="javascript:TreeView_ToggleNode(ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_Data,0,ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewn0,' ',ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewn0Nodes)" href="javascript:void(0);" target=_self>1. A

                    <A id=ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewt1 class=ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_0 onclick="javascript:TreeView_SelectNode(ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_Data, this,'ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewt1');" href='javascript:DisplayPDF("ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_pdf_and_searchResults_container","http://mydomain/mylibrary/1. A/5.5 Quick Reference Guide.pdf","850","1100", null);' target=_self>1. 5.5 Quick Reference Guide

                    <A id=ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewt2 class=ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_0 onclick="javascript:TreeView_SelectNode(ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_Data, this,'ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewt2');" href='javascript:DisplayPDF("ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_pdf_and_searchResults_container","http://mydomain/mylibrary/1. A/5.6 Upgrade.pdf","850","1100", null);' target=_self>2. 5.6 Upgrade

                <A id=ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewt3 class="ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_0 ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_1" onclick="javascript:TreeView_ToggleNode(ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_Data,3,ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewn3,' ',ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewn3Nodes)" href="javascript:void(0);" target=_self>2. B

                    <A id=ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewt4 class=ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_0 onclick="javascript:TreeView_SelectNode(ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_Data, this,'ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewt4');" href='javascript:DisplayPDF("ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_pdf_and_searchResults_container","http://mydomain/mylibrary/2. B/8830 Downloading PodCasts.pdf","850","1100", null);' target=_self>1. 8830 Downloading PodCasts

                <A id=ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewt5 class="ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_0 ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_1" onclick="javascript:TreeView_ToggleNode(ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_Data,5,ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewn5,' ',ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewn5Nodes)" href="javascript:void(0);" target=_self>3. C

                    <A id=ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewt6 class=ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_0 onclick="javascript:TreeView_SelectNode(ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeview_Data, this,'ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_my_treeviewt6');" href='javascript:DisplayPDF("ctl00_m_g_7276d5bd_969d_40e4_b299_08b2f89c43e9_ctl00_pdf_and_searchResults_container","http://mydomain/mylibrary/3. C/8830 International Roaming.pdf","850","1100", null);' target=_self>1. 8830 International Roaming

A: Alright, as i mentioned, I don't know of any links. That HTML was a little tuff, ASP default design I'm assuming. Been a while since I worked with ASP. Any who. I made an example fiddle with a lot of comment in "per item demand" detail based on your question. I give a small example of how to perform each task separately along with some other useful information. For more information, be sure to frequently check http://api.jquery.com/
Examples
//  the following will get the main tree view wrapper, unless you change your ID names of course
//  by useing `.not('[id*=Nodes]')`, we can eliminate all div's having "my_treeview" without elementating the parent
//  you could also use `.first()` and get the same result
//  simply showing a couple different ways jQuery offers "selection" of elements
var treeView = $('div[id*=my_treeview]').not('[id*=Nodes]');
clog(treeView, 'Tree View Element');

//  ***  iterate through all root nodes  ***
treeView.children('table').each(function(i) { // `i` = index number (0 based)
    var node = $(this),  //  get current node
        nodeSub = $(this).next("div");  //  get sub nodes if avaialbe, if not, this will be empty jQuery Object
    clog([node, nodeSub], 'Node && Sub');
})

//  ***  iterate through all sub nodes given a node  ***
var given = treeView.children('table').first(); // in this case, just grabs first node, since it has multiple subs
clog(given, 'Given Sub Node');
given.next('div').children('table').each(function(i) {
    var subNode = $(this);
    clog(subNode, 'Sub Nodes of First Node');
});

//  ***  get the text of the given node  ***
//  this selector based on given HTML example of all node text being in an A tag having an
//  ID that contains the phrase `my_treeviewt`
//  i would suggest using class names like ('node-text') instead
treeView.find('a[id*=my_treeviewt]').each(function(i) {
    clog($(this).text(), 'Node Text by Each Node && Sub Node');
});

//  ***  get the value of the given node  ***
//  ??? UNSURE of your intent with this one ???

//  ***  add a blue highlight around the text of the given node  ***
given.find("a").last().css({ 'background-color': '#2AF', 'color': '#FFA' })
//  here i change the css of an element by hand using traditional CSS names
//  jQuery does include some shortcut options, my suggestiong would be to make a 'highglight' class,
//  then simply use `addClass('highlight')` or `removeClass('highligh')`

//  ***  expand/collapse given node  ***
//  selector based on layout, but again, I would suggest setting up class names to use like
//  `.node` and/or '.node.sub-node'
$('div > table a').attr('onclick', ''); // first i remove all the set onclicks for now, they cause their own interference
$(document).on('click', 'div > table a', function(e) {
    e.preventDefault();  //  stop href link from working on an A tag
    var parent = $(this).closest('table');  //  finds first parent table, aka, the "node"
    if (parent.next('div').length) {    //  will return false if there is not a sub node
        var sub = parent.next('div');
        if (sub.is(':visible')) {   //  note, this does not just check 'visible' css state, it also checks if 'display' css is set or if it is 'none'
            sub.hide();
        }
        else {
            sub.show();
        }
    }
})


text:
Q: iOS UITabBarController "Configure" icon color I am using a UITabBarController and I have 7 tabs, such that the "more" tab is displayed in the UITabBarController. I am trying to change the color to green for all of the selected titles and icons from the UITabBar, but in the configure screen, I only managed to change the title color - the icons remain in blue. How can I change the remaining blue color to green?
Here are my customizations in the AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [...]

    [[UITabBar appearance] setTintColor:[MyColor lightGreenColor]];
    [[UITabBar appearance] setSelectedImageTintColor:[MyColor lightGreenColor]];
    [[UINavigationBar appearance] setTintColor:[MyColor lightGreenColor]];
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [MyColor lightGreenColor] } forState:UIControlStateSelected];

    return YES;
}

For better comprehension, here is a screenshot.

EDIT
I use the approach of Sen and combine it together with a UIImage category from here. In addition to that, I had to give each Tab Bar View own Tag Id, such that I can use it as an index for the icon image array. That way I do not have to manually color the icons in the green color and so, I use a quite efficient workaround for the illustrated problem. Here is the snippet, that I am using in my AppDelegate.m. I am looking forward to improvements by the community!
UIViewController *mainViewController = self.window.rootViewController;
if ([mainViewController isKindOfClass:[UITabBarController class]]) {
    UITabBarController *tabBarController = (UITabBarController *) mainViewController;

    if (tabBarController && tabBarController.tabBar &&
        [tabBarController.tabBar items] && [[tabBarController.tabBar items] count]) {
        NSArray *tabIcons = @[@"ICON1", @"ICON2", @"ICON3", ...];

        for (UITabBarItem *tabBarItem in [tabBarController.tabBar items]) {
            if (tabBarItem.tag < [tabIcons count]) {
                [tabBarItem setSelectedImage:[[UIImage imageNamed:[tabIcons objectAtIndex:tabBarItem.tag]
                                                        withColor:LIGHT_GREEN_COLOR]
                      imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
            }
        }
    }
}

A: You should have images with the right colors, and then set the images of the icons
// unselected
[tabBarItem setImage: [img1 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

// selected
[tabBarItem setSelectedImage: [img2 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

Do it in application:didFinishLaunchingWithOptions:. You can get you tab bar view controller by
UITabBarController * tc = (UITabBarController *)self.window.rootViewController;

You can get the ith item by
UITabBarItem *tabBarItem = [tc.tabBar items][i];


text:
Q: Securing Spring Boot with vaadin Instead of using InMemory Auth I am trying to authenticate with BD user, so a created class user and roles, and added this code to this class
@EnableWebSecurity
@Configuration
public class SecurityConfig extends VaadinWebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetails customUserDetails;

    @Autowired
    CustomAuthenticationProvider customAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Set default security policy that permits Vaadin internal requests and
        // denies all other
        super.configure(http);
        setLoginView(http, LoginView.class, "/logout");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth.inMemoryAuthentication().withUser("user").password("{noop}userpass").roles("USER");
        auth.userDetailsService(customUserDetails).passwordEncoder(passwordEncoder());
    }

    @Bean
    public DaoAuthenticationProvider createDaoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(customUserDetails);
        provider.setPasswordEncoder(passwordEncoder());
        return provider;
    }
}

But when i try to authenticate it does not accept

A: There is more than one way to do this, but usually it goes roughly like this. The relevant pieces, the complete solution is too lengthy for SO. There should not be anything Vaadin specific, but just follow Spring documentation on the matter.
@EnableWebSecurity
@Configuration
public class SecurityConfig extends VaadinWebSecurityConfigurerAdapter {
    ...
    private final UserDetailsService userDetailsService;

    @Autowired
    public SecurityConfig (UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }
    ...
}

And then implement UserDetailsService according to Spring spec.
@Service
@Primary
public class UserDetailsServiceImpl implements UserDetailsService {
    ...
    @Autowired
    private UserRepository repository; // or what ever you have named it ...

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // implement this according to your actual implementation of user database
    }

}


text:
Q: CSS is blank on site hosted by gh-pages It seems my CSS has been deleted from my gh-pages but when I check my GitHub repo the CSS is there.  What did I do for this to happen?

A: I checked the folder structure. Html resource are case sensitive. Please change from css/styles.css to CSS/styles.css in the link tag href attribute.
The folder you created is "CSS" not "css".


text:
Q: How to match by using partial names I got a problem with selecting the primary key for match. My problem is as below:
Given two tables, one contains employee name and their employee ID, another one only contains employee name(not in standard format) and related information. I would like to combine them together, but since the names cannot be matched exactly. What can I do?
The tables might be like below:
T1
FirstName    LastName     EmployeeID
  Newsom       Tom           001
  Greg         Thomas        002
  Henry        Peter         003

T2
 FirstName      LastName        HiringDate    Gender
   Tom          Newson Jr.      01/01/2019      M
   Greg          Thomas         01/01/2019      M
   Peter Sr.      Henry         01/01/2019      M

From the table, the names are mismatched.
Is there a way to formalize it? And can the name be the primary key?

A: There are a few solutions. If you can alter the table to make EmployeeID as primary key and use it as a foreign key in another table too, then that would be best.
Other then that, you could try the below query:
This sql is for Mysql database
select * from
T1 join T2
on (
    concat(T2.Firstname,T2.Lastname) like concat('%',T1.Firstname, T1.Lastname,'%')
    OR
    concat(T2.Lastname,T2.Firstname) like concat('%',T1.Firstname, T1.Lastname,'%')
)

A: This is too long for a comment.
You really cannot automate name matching in this way.  The first obvious issue is that two employees could have the same name, "Jane Doe", for instance.  Then there is no way to disambiguate them.
Another problem is that names can be reversed.  "Is "Thomas Williams" the same as "William Thomas"?
The best you can do is to set up a manual process.  This might take the form of dumping all the names into a spreadsheet and manually choosing a canonical form.  Then, load the database with two new tables:

*

*Names which has the employee id and the correct form of the name.

*Nicknames which has alternative renderings of the names.

This is a manual process, possibly arduous.  For large numbers of names, there are definitely tools that can help.  For a few hundred, you'll probably be finished before you can even do a proper investigation into other tools.

A: You could start with something like this:

    with t1 (fnam,lnam,eid) as (values
('Newsom','Tom','001'),
('Greg','Thomas','002'),
('Henry','Peter','003')
),
     t2 (fnam,lnam,hired,gender) as (values
('Tom','Newson Jr.','01/01/2019','M'),
('Greg','Thomas','01/01/2019','M'),
('Peter Sr.','Henry','01/01/2019','M')
) select t1.lnam as fnam,
       t1.fnam as lnam,
       t1.eid as emp_id,
       t2.hired as date_hired,
       t2.gender as gender
  from   t1
  cross  join t2
  where  ((t1.lnam like '%' concat t2.fnam concat '%' or
         t1.fnam like '%' concat t2.lnam concat '%')
        and
        (t2.fnam like '%' concat t1.lnam concat '%' or
         t2.lnam like '%' concat t1.fnam concat '%'))
        or
       ((t1.fnam like '%' concat t2.fnam concat '%' or
         t1.lnam like '%' concat t2.lnam concat '%')
        and
        (t2.fnam like '%' concat t1.fnam concat '%' or
         t2.lnam like '%' concat t1.lnam concat '%'))


text:
Q: Parsing network protocols using meta-programming in Go In JavaScript (Node), I've written a module which accepts a list of fields and their types and returns an object with pack and unpack methods. Below is the code to pack and unpack IPv4:
var ipv4 = proto.add('struct', {
  name: 'IPV4',
  fields: {
    version:       'int:4',
    ihl:           'int:4',
    dscp:          'int:6',
    ecn:           'int:2',
    length:        'int:16',
    id:            'int:16',
    flags:         'int:3',
    offset:        'int:13',
    ttl:           'int:8',
    protocol:      'int:8',
    checksum:      'int:16',
    src:           'IPV4_ADDR',
    dst:           'IPV4_ADDR',
    // TODO: IPv4 OPTIONS
    options:       'raw'
  },
  $length: 'length'
});
//then I can do
ipv4.pack({ version: 4, ... }); //=> buffer
//and
ipv4.unpack(buffer); //=> { ... }

Since JavaScript is dynamic, I can meta-program (reasonably) optimised pack and unpack functions. From what I understand, you cannot dynamically create functions in Go, though it appears this would be possible using the reflect package. Is this worth pursuing? Or would it be too costly to use reflect?
I'm hoping to avoid writing code like this for every network protocol I wish to parse.

A: If can accept a semi-dynamic solution, you could take inspiration in the numerous JSON alternative packages for Golang that are designed for speed. Their approach is to tag a struct, then run a tool (as part of a make configuration for example) to generate the MarshalJSON and UnmarshalJSON methods for the desired types. Which is clearly faster than using tags.
Some examples to help you :

*

*https://github.com/pquerna/ffjson

*https://github.com/benbjohnson/megajson


text:
Q: Can the norm of a non-algebraic integer be an integer? Let L/K be a finite field extension and define the norm of an element as the product of each K-embedding evaluated at that element.
Can the norm of a non-algebraic integer be an integer?
I know that the norm of an algebraic integer is always an integer as it corresponds to the final term in the minimum polynomial, I was wondering if there was a converse to this- even under special conditions.
EDIT: Sorry yes an element which belongs to L.

A: $\newcommand{\Q}{\mathbb{Q}}$I believe you could take a root $\alpha$ of $f = 2x^2 + x + 2$.
Clearly $f$ is irreducible in $\Q[x]$, so $\alpha$ is not an algebraic integer as its minimal monic polynomial  $f/2$ over $\Q$ does not have integer coefficients.
But the norm of $\alpha$ in $\Q(\alpha)/\Q$ is the constant coefficient of $f/2$, that is, $1$.

A: Hint $ $ Over $\,\Bbb Q,\,$ a quadratic number is an algebraic integer iff its $\,\color{#0a0}{\rm norm}\,$ and $\,\rm\color{#c00}{trace}$ are integers, i.e. iff its monic minimal polynomial has integer coefficients. So your question reduces to finding an irreducible polynomial $\,x^2\! + \color{#c00}b\,x + \color{#0a0}c\in\Bbb Q[x] $ with $\,\color{#c00}{b\not\in \Bbb Z},\ \color{#0a0}{c\in \Bbb Z},\,$ which is quite easy.
Remark $\ $ The same argument works over any integrally-closed domain $\,D,\,$ since then monic minimal polynomials of $D$-integral eements must have coefficients in $\,D\,$  (a property that is equivalent to $\,D\,$ being integrally-closed).

A: The norm of
$$
\frac35+\frac45i\in\Bbb Q[i]
$$
is
$$
\left(\frac35\right)^2+\left(\frac45\right)^2=1
$$
More generally, any primitive pythagorean triple $(a,b,c)$ can be used to construct elements in $\Bbb Q(i)$ of norm 1 which are not integers, just take $z=\frac ac+\frac bci$
Even more generally if $K$ is a quadratic field and $0\neq z\in K$ any, the quotient $z/\bar z$ has always norm 1.


text:
Q: Flair with a lot of badges wraps to a new line I was looking at this answer by PaxDiablo and noticed that their flair had a newline in it:

I have no idea if this is a bug or not, but it kinda looks wrong to me. For fun, I changed all badge counts to 9999 and the user-info user-hover <div> that wraps the whole thing needs a width of 210px instead of 200px.


text:
Q: jQuery is duplicating POST requests? I've made a web page that sends data to a page via jQuery.  The form can be duplicated by clicking "New".  For some reason, the submit function is run multiple times.  If I create three forms, and click "Submit" on the first one, it makes three entries for that.  The form is then deleted.  When I submit the second form, it makes two entries, and so forth.
Can anyone tell me what's wrong with the following code?
function listen() {
$(".addBook").on('click', function() {
    $(this).fadeOut("fast", function() {
        $(this).parent().find(".loadingImg").fadeIn();
    });
    var target = $(this).parent();
    var title = $(target).find(".bookTitle").val();
    var author = $(target).find(".bookAuthor").val();
    var genre = $(target).find(".bookGenre").val();
    var barcode = $(target).find(".bookBarcode").val();
    var img = encodeURIComponent($(target).find(".coverSelect").val());
    var data = 'barcode=' + barcode + '&title=' + title + '&author=' + author + '&genre=' + genre + '&img=' + img;
    $.post('addBook', data, function() { alert(title); });
    $(this).parent().parent().slideUp("med", function() {
        $(this).remove();
    });
});
}

//new form function
function newBook(barcode) {
var data = 'barcode=' + barcode;
$.post('bookInfo', data, function(data) {
    $('.accordion').append(data);  //php script returns html for form
    $('.accordion > dd').hide();
    $("#closeAccordion").show();
    listen();
});
}

Thanks!

A: You're binding duplicate events, instead, just use event delegation so that you don't even need to call listen().
//function listen() {
$(document).on('click', '.addBook', function() {
    $(this).fadeOut("fast", function() {
        $(this).parent().find(".loadingImg").fadeIn();
    });
    var target = $(this).parent();
    var title = $(target).find(".bookTitle").val();
    var author = $(target).find(".bookAuthor").val();
    var genre = $(target).find(".bookGenre").val();
    var barcode = $(target).find(".bookBarcode").val();
    var img = encodeURIComponent($(target).find(".coverSelect").val());
    var data = 'barcode=' + barcode + '&title=' + title + '&author=' + author + '&genre=' + genre + '&img=' + img;
    $.post('addBook', data, function() { alert(title); });
    $(this).parent().parent().slideUp("med", function() {
        $(this).remove();
    });
});
//}

//new form function
function newBook(barcode) {
var data = 'barcode=' + barcode;
$.post('bookInfo', data, function(data) {
    $('.accordion').append(data);  //php script returns html for form
    $('.accordion > dd').hide();
    $("#closeAccordion").show();
    //listen();
});
}

Note:
You should replace document with a selector that selects whatever element you are appending forms to, such as .accordion.
$('.accordion').on('click', '.addBook', function() {....

A: Probably you bind the button when a new form is generated.
When you do it you will bind the same event to one button that already have a click event attached.
Then, when you click all events will run.
Use click or on('click', ... to prevent this behaviour.
Demo

A: With oldest jquery you can use the "live" and "on('click')" solution, but before it, you also need to "kill" the bindings with die and unbind.
In 1.9+ jquery version the "live(..." syntax replaced with "on(..." syntax.
Keep in mind the Upgrade / Change stuff.
On(.. syntax usage:
 $("#myButton").on("click", function(){
    alert("you call me!");
});

About old binding methods you can found some doc's here.