text:
Q: Installed Word on the server but cannot find it to set permissions in Component Services I was looking at this problem on SO; System.UnauthorizedAccessException: Retrieving the COM class factory for Word Interop fails with error 80070005.
We had word installed in the test server in order to get the Word Interop to work on it.
That lead to this new bug, and I cannot apply the fix recommended by I cannot find Microsoft Word on the Componenet Services DCOM Config.
So how can I fix this?

A: Using the ERR tool we see the error: 80070005 is an Access Denied, so you either do not have permissions or its by-design.
 for hex 0x80070005 / decimal -2147024891 :
  COR_E_UNAUTHORIZEDACCESS                                      corerror.h
 MessageText:
 Access is denied.
  DIERR_OTHERAPPHASPRIO                                         dinput.h
  DIERR_READONLY                                                dinput.h
  DIERR_HANDLEEXISTS                                            dinput.h
  DSERR_ACCESSDENIED                                            dsound.h
  ecAccessDenied                                                ec.h
  ecPropSecurityViolation                                       ec.h
  MAPI_E_NO_ACCESS                                              mapicode.h
  STIERR_READONLY                                               stierr.h
  STIERR_NOTINITIALIZED                                         stierr.h
  E_ACCESSDENIED                                                winerror.h
 General access denied error
 11 matches found for "0x80070005"

I mention by-design because of all the problems documented in this KB article: Considerations for server-side Automation of Office.
Installing Office on Server OS's leads to all sorts of problems. For VSTO development I install TFS on Win7 for automated builds to avoid server-side interop problems.
Dont use a Server OS for Office automation, as per the KB article its not supported, use Win7!

Microsoft strongly recommends a number of alternatives that do not
  require Office to be installed server-side, and that can perform most
  common tasks more efficiently and more quickly than Automation. Before
  you involve Office as a server-side component in your project,
  consider alternatives.

A: Without knowing what you tried from your linked stackoverflow post: when the COM objects do not appear you usually need to run
mmc -32

And manually add the Component Services snap ins.  This worked for me in both Windows Server 2008 R2 and Windows Server 2012.
You also need to make Desktop directories at the following locations:

C:\Windows\SysWOW64\config\systemprofile
C:\Windows\System32\config\systemprofile

A: You should seek not for exact 000209FF-0000-0000-C000-000000000046 code, in you case it could have different name. I have 00021401-0000-0000-C000-000000000046, try to seek according to last for pairs of digits. And don't forget to add service components tab in mmc Console.
UPDATED

A: This is much easier done than typed in a SO answer, because there are various palaces that need to be checked and aligned.
But the overall goal is to 1) track down the security account that attempted the access and launch/activation of the COM component, and 2) which COM component was at fault.
NOTE: Procedures described increase your security exposure, so be sure to create great logs of all changes you do, so that you know what exactly fix your problem, but also, so you can roll back everything that was irrelevant.
NOTE 2 One change at a time, regardless whether server reboot was needed or not.\ - so you know what fixed it.

*

*Start with your Windows logs - they usually log the exact security principal involved and the DCOM component that it tried to access/activate. Usually both: security context and component are pretty obvious - in such case you can skip to the dcomcnfg paragraph below.

*One way to temporirely test if you've located the
component/account is to allow admin privileges to the security
account or "EVERYONE" access to the component and see if you
eliminate the error
NOTE: These are temporary measures, only to test. Don't forget to roll everything back.

*Your permanent configuration changes will be done in the Component Services MMC snippet. You can either go by manually adding it to an elevated MMC window, or, easier, by running under administrator's privileges the following command:

/>dcomcnfg

*

*Try locating the component of interest under Component Services/Computers/My Computer/DCOM Config/, right-click and do Properties:

*Go to the Security tab and adjust Activate and Access permissions to the minimum that is going to fix your issue, but stay as close as the locked-down state, as possible. NOTE: I have never done this with the MS Office interops. Please be sure to consider all security implications of doing this:
That's pretty much how you start. I have done this on all flavors of Windows and it always feels different. Often I have to rely on other methods of tracking this condition: SysInternals "spying" tools, Windows Security auditing, COM+ Applications properties, and on a few occasions direct modification of file system or registry key ACLs. Most of the times it's lab/dev machines, so hacks, like editing registry keys' security, was okay.
And again - keep track and roll back all changes you did not need!


text:
Q: Word VBA is saying "Wrong number of arguments or invalid property assignment" but I think my code is correct I am working on a Word macro to print a letter and its envelope to two different printers:
Sub PrintEnvelopeAndLetter()
'
' PrintEnvelopeAndLetter Macro
'
'
    Dim sCurrentPrinter As String
    Dim pageCount As Integer
    Dim currentPosition As Range
    Set currentPosition = Selection.Range 'Save the current cursor position
    pageCount = ActiveDocument.ActiveWindow.Panes(1).Pages.Count

    ' Prompt the user to ask if they are sure they are ready to print
    Result = MsgBox("Are you sure you are ready to print?" & vbCr & vbCr & "Read through your letter one last time.", _
        vbYesNo + vbDefaultButton2 + vbApplicationModal + vbExclamation)
    If Result = vbNo Then
        Exit Sub
    End If

    ' Display a message box asking if the user has entered the correct date
    ' at the top of their letter.
    Result = MsgBox("Did you enter the correct date at the top of your letter?", _
        vbYesNo + vbDefaultButton2 + vbApplicationModal + vbExclamation)
    If Result = vbNo Then
        Exit Sub
    End If

    ' Launch the Spelling and Grammar Check
    ActiveDocument.CheckSpelling
    ActiveDocument.CheckGrammar

    ' Save the document to the disk and do not prompt the user
    ' to save it if the user has made changes
    If ActiveDocument.Saved = False Then
        ActiveDocument.Save True
    End If

    ' Get the total number of pages in the document. NOTE: The
    ' envelope counts as a page
    sCurrentPrinter = ActivePrinter 'Save the current printer

    ActivePrinter = "HP ENVY Photo 7800 series"
    Selection.HomeKey Unit:=wdStory ' move to the top of the document (envelope)
    Application.PrintOut FileName:="", Range:=wdPrintCurrentPage, Item:= _
        wdPrintDocumentWithMarkup, Copies:=1, Pages:="", PageType:= _
        wdPrintAllPages, Collate:=True, Background:=True, PrintToFile:=False, _
        PrintZoomColumn:=0, PrintZoomRow:=0, PrintZoomPaperWidth:=0, _
        PrintZoomPaperHeight:=0
    ActivePrinter = "HP OfficeJet Pro 8030 series"
    For J = pageCount To 2 Step -1
        Selection.GoTo wdGoToPage, wdGoToAbsolute, J
        Application.PrintOut FileName:="", Range:=wdPrintCurrentPage, Item:= _
            wdPrintDocumentWithMarkup, Copies:=1, Pages:="", PageType:= _
            wdPrintAllPages, Collate:=True, Background:=True, PrintToFile:=False, _
            PrintZoomColumn:=0, PrintZoomRow:=0, PrintZoomPaperWidth:=0, _
            PrintZoomPaperHeight:=0
    Next
    ActivePrinter = sCurrentPrinter 'Restore the original printer

    ' Scroll the insertion point to the very beginning of the document
    Selection.HomeKey Unit:=wdStory

    ' Save the document to the disk and do not prompt the user
    ' to save it if the user has made changes
    If ActiveDocument.Saved = False Then
        ActiveDocument.Save NoPrompt:=True
    End If
End Sub

I think that my code is correct, but I was hoping if I could get a second pair of eyes.  It seems to be indicating that the invalid line is:
ActiveDocument.Save NoPrompt:=True

But I think that it is correct -- see the following link:
https://learn.microsoft.com/en-us/office/vba/api/word.document.save
Consulted the link:
https://learn.microsoft.com/en-us/office/vba/api/word.document.save
I checked my own VBA code and it seems as if I am specifying the NoPrompt property correctly.
I am using Microsoft® Word for Microsoft 365 MSO (Version 2210 Build 16.0.15726.20188) 64-bit on Windows 10.  I did not change my code (at least, I do not think so).  The macro worked perfectly the day before yesterday.
I have also checked my printers, and both of the printers listed in the macro are installed:

Figure 1.  A screenshot of my installed Printers and Scanners.
I am not entirely sure what else to check.
FIRST UPDATE
I commented out both occurrences of the code
' Save the document to the disk and do not prompt the user
' to save it if the user has made changes
If ActiveDocument.Saved = False Then
    ActiveDocument.Save NoPrompt:=True
End If

in the macro, and the macro works, so I know for certain that this is the code that it is complaining about.  It would seem that the compiler is complaining about a syntax error somewhere, or a function parameter that is not valid.   However, every source I've consulted seems to point to this as being valid code, so I am stumped.
I'd really appreciate it if someone could help me out.
Am I doing something wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Definição para campo data e hora Estou definindo 2 atributos, um será data e o outro hora:
@Getter
@Setter
private Date dataOcorrencia;

@Getter
@Setter
private Calendar horaOcorrencia;

Gostaria de saber se é a melhor definição para ambos, porque tem ainda a classe SimpleDataFormat. Essa é a melhor definição pra ambos?

A: Sugiro unificar estes 2 atributos em um campo apenas, utilizando o tipo oriundo do Java 8:
@Getter
@Setter
private LocalDateTime dhOcorrencia;

Além de vários benefícios, como imutabilidade, interface fluente, fácil manipulação (operações básicas como soma, subtração, cálculo de períodos), tratamento de datas inválidas, terá mais facilidade para ordenação por esta informação.
Alguns exemplos de uso do LocalDateTime:
LocalDateTime hojeAoMeioDia = LocalDate.now().atTime(12,0);

LocalTime agora = LocalTime.now();
LocalDate hoje = LocalDate.now();
LocalDateTime dataEhora = hoje.atTime(agora);

LocalDateTime dateTime = LocalDateTime.of(2014, 12, 25, 10, 30);


text:
Q: Корректная структура кода в перехватчике http-запросов Имеется файл http.interseptor.ts :
import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent,
         HttpInterceptor, HttpHandler,
         HttpRequest, HttpErrorResponse,
         HttpResponse
} from '@angular/common/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HttpIntercept implements HttpInterceptor {
intercept (reqest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (reqest.method === 'POST') {
      if ( localStorage.getItem('auth_token') !== null) {
        reqest = reqest.clone({
            setHeaders: {
                Authorization: `JWT ${localStorage.getItem('auth_token')}`,
                Accept: 'application/json'
            }
        });
      } else {
        reqest = reqest.clone({
            setHeaders: {
                Accept: 'application/json'
            }
        });
      }
    }
    if (reqest.method === 'GET') {
      if ( localStorage.getItem('auth_token') !== null ) {
        reqest = reqest.clone({
            setHeaders: {
                Authorization: `JWT ${localStorage.getItem('auth_token')}`,
                Accept: 'application/json'
            }
        });
      } else {
        reqest = reqest.clone({
            setHeaders: {
                Accept: 'application/json'
            }
        });
      }
    }
    if (reqest.method === 'PUT') {
        if ( localStorage.getItem('auth_token') !== null ) {
          reqest = reqest.clone({
              setHeaders: {
                  Authorization: `JWT ${localStorage.getItem('auth_token')}`,
                  Accept: 'application/json'
              }
          });
        } else {
          reqest = reqest.clone({
              setHeaders: {
                  Accept: 'application/json'
              }
          });
        }
    }
    if (reqest.method === 'DELETE') {
        if ( localStorage.getItem('auth_token') !== null ) {
          reqest = reqest.clone({
              setHeaders: {
                  Authorization: `JWT ${localStorage.getItem('auth_token')}`,
                  Accept: 'application/json'
              }
          });
        } else {
          reqest = reqest.clone({
              setHeaders: {
                  Accept: 'application/json'
              }
          });
        }
    }
    if (reqest.method === 'PATCH') {
        if ( localStorage.getItem('auth_token') !== null ) {
          reqest = reqest.clone({
              setHeaders: {
                  Authorization: `JWT ${localStorage.getItem('auth_token')}`,
                  Accept: 'application/json'
              }
          });
        } else {
          reqest = reqest.clone({
              setHeaders: {
                  Accept: 'application/json'
              }
          });
        }
    }
    return next.handle(reqest);
  }
}

Хочу спросить не будет ли лучше объединить все условия в подобное:
if (
       reqest.method === 'POST'
       || reqest.method === 'GET'
       || reqest.method === 'PUT'
       || reqest.method === 'DELETE'
       || reqest.method === 'PATCH'
) {
  if ( localStorage.getItem('auth_token') !== null) {
    reqest = reqest.clone({
        setHeaders: {
            Authorization: `JWT ${localStorage.getItem('auth_token')}`,
            Accept: 'application/json'
        }
    });
  } else {
    reqest = reqest.clone({
        setHeaders: {
            Accept: 'application/json'
        }
    });
  }
}

Или потом такое решение может вылезть боком?

A: С учётом, того что токен нужен при всех запросах, то проще так сделать:
if ( localStorage.getItem('auth_token') !== null) {
reqest = reqest.clone({
    setHeaders: {
        Authorization: `JWT ${localStorage.getItem('auth_token')}`,
        Accept: 'application/json'
    }
});
} else {
    reqest = reqest.clone({
        setHeaders: {
        Accept: 'application/json'
        }
   });
}

и не проверять на тип запроса.


text:
Q: Putty - Automatically closes on authentication I'm on a Windows 7 machine. I am using the Putty.exe executable for connecting to my remote machine. I enter the right credentials, and click open. The console pops up with the following and closes with no errors or warnings.

How do I make it work?

A: Check Putty setting: Connection > SSH > Remote command.
Try to tweak or simply remove the remote command and see if it helps solving the issue.

A: What you are describing is trying to log into the shell with a user that is an "ftp only" user (not authorized shell access).

Go to Control Panel -> Users -> Manage Users, select the "Edit" link
  adjacent to the user you are having trouble with, and make sure that
  the radio button for "shell" is selected. Submit the form, and wait
  for it to take effect (usually a matter of a few minutes).

Once the change has taken effect, you should be able to telnet (though, please do not use telnet, as it is insecure) or ssh into the shell without problem (assuming the user/pass is correct).


text:
Q: Sudden disappearance of four votes on a question I am troubled by the sudden disappearance of votes on this Question. I distinctly remember there being two upvotes (one of them being mine) and three downvotes. Then suddenly there was only one downvote but no upvotes. While the net vote total did not change, it still bothers me that this happened.
What might explain this disappearance?

A: There's no record of any up-votes to that particular question, ever. You can certainly up-vote it now if you're so inclined.
You can view your recent votes here: https://history.stackexchange.com/users/825/eugene-seidel?tab=votes
FWIW, someone did up-vote that question anonymously about three hours ago; these "votes" are recorded, but not shown as ordinary votes on the post. However, the IP address this vote came from isn't one that you've used (at least, not one that shows up in our logs associated with your account) - it's possible you visited it from an unusual location and voted without realizing you weren't logged in, but I can't prove that.


text:
Q: Mvc: get values from json using javascript arrays to mvc controller I need to read each value from a json result i request to a controller action.
this is my client side.
$.ajax({
        type: "POST",
        url: "List",
        data: { firstArray: arrayCountries, secondArray: arrayLang },
        success: function (result) {

             //here i need each value from json, but it's not working for me
        },
        dataType: "json",
        traditional: true
    });

Ok now i use this way because i need to send 2 javascript arrays and after finding a lot this way works for me.
And this is my server side. According to How can I post an array of string to ASP.NET MVC Controller without a form? i have created this.
public ActionResult List(List<String> firstArray, List<String> secondArray)
{
    //But here i need a list of sections, so i call a method for that
      var sections = SomeClass.getSections(fistArray, secondArray);

    //And return the json with the collection
      return Json(sections, JsonRequestBehavior.AllowGet);
}

Now this is my getSections Method
public static IEnumerable getSections(List<String> firstArray, List<String>secondArray)
{
    entities db = new entities();

    var result = from values in db.Sections
                 where ...
                 select new SectionsModel{ // do something  };

    return result.OrderBy(p => p.Description);
}

Now im getting well json in client side but i don't know how to acces it, and how can i get each value from it ? ... thanks in advance.

A: You need to parse it first, after that you can just access the properties similarly as what you would do in .NET
$.ajax({
        type: "POST",
        url: "List",
        data: { firstArray: arrayCountries, secondArray: arrayLang },
        success: function (result) {

             var sections = JSON.parse(result);

             // access properties here
        },
        dataType: "json",
        traditional: true
    });


text:
Q: Magento-Adobe Acquisition - What does it mean for the community version? Any idea of how the Magento-Adobe acquisition will affect the developers or the community version in general?

A: While this question may be more relevant elsewhere, there has been similar concerns raised through out the community. A good read on what Adobe's view point on keeping Magento open source/CE is https://medium.com/@5bf90f4ff4fa/c9f8246e83e2 while it doesn't offer specific examples of how but I would anticipate more rolling in of Adobe's cloud services & more front end tech like nodejs.


text:
Q: How can I make an inner join with 3 tables? I have tables Professors, Inspectors and Students and I want to display in a report associate with table Students, the name of the Inspectors. But, how you can see in table Inspectors I've got only ID's. How can i make an inner join with these 3 tables?
Thanks a lot!
Professors:
IdProfessor
LastName
FirstName
Adress

Inspectors:
IdInspector,
IdProfessor

Students:
IdStudent,
FirstName,
LastName,
Adress,
CNP,
IdInspector

A: Even if it doesn't look like you've been thinking about an answer right now, here is a possible solution for you.
To get students and their corresponding inspectors you can use this query:
select s.FirstName, s.LastName, s.Adress, s.CNP, p.LastName, p.FirstName, p.Adress
from Students as s
inner join Inspectors as i on s.IdInspector = i.IdInspector
inner join Professors as p on i.IdProfessor = p.IdProfessor


text:
Q: Android Relative Layout on top other element I'm currently trying to make a data structure visualization app. The data structure I am trying to make is a stack.
I am struggling to make an element on top of another once the user presses "Push". Below is the code that makes an element go to the bottom of the screen.
I was wondering if are there any methods that could directly tells the next element to be aligned to the element that is already at the bottom now?
public void moveElem() {

    element1 = findViewById(R.id.element1);

    RelativeLayout.LayoutParams positionRules = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    positionRules.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    positionRules.addRule(RelativeLayout.CENTER_HORIZONTAL);
    element1.setLayoutParams(positionRules);

    ViewGroup.LayoutParams sizeRules = element1.getLayoutParams();
    sizeRules.width = 400;
    sizeRules.height = 200;
    element1.setLayoutParams(sizeRules);
}

Thank you all so much!

A: Use ALIGN_TOP and ALIGN_LEFT/ALIGN_RIGHT depends on what you need so it will make the next element the same alignment as the previous element and just add margins for the next element as well so it won't be exactly on top of the last one according the direction you need making it look like a stack.


text:
Q: How to create a hash from 3 ordered int? Let's say I have a structure like this,
struct point3d{

  int x;

  int y;

  int z;

};

How can I create a hash value from this structure?
Thanks

A: A lot depends on what you want to achieve and how much distribution you need.
Most non-cryptographic hash would be similar to :
int64_t Hash(const point3d & point){
       int64_t start = 1234; //magic number
       int64_t multiplier = 3467; //some other magic number
       int64_t hash = start + point.x;
       hash = hash*multiplier + point.y;
       hash = hash * multiplier + point.z;
       return hash;

}

Test this out on your data set by tuning start and multiplier.


text:
Q: How to select netcat-traditional in Ubuntu in a Dockerfile I want to use netcat-traditional in Ubuntu but configure this in a Dockerfile, so obviously I cannot use the helpful command prompt triggered when running sudo update-alternatives --config nc
How do I select the correct option automatically without being prompted?
These instructions explain what I want to do but assume access to a command prompt.

A: To set the default netcat without being prompted at the command line, type:
sudo update-alternatives --set nc /bin/nc.traditional

From the manpage:

--set name path

Set the program path as alternative for name. This is
  equivalent to --config but is non-interactive and thus
  scriptable.


text:
Q: Angular 2 import statement wildcard syntax I defined several classes in one file like this
my.classes.ts
export class Class1 {....}
export class Class2 {....}
export class Class3 {....}

Now I want to import them all using wildcard like this
import {*} from './my.classes';

It showed syntax error.
What is the correct syntax to import * from a module?

A: Here you go,
 import * as MyClasses from './my.classes';

 MyClasses.Class1 ....


text:
Q: When does std::string reallocate memory? When using an std::string object and I want to add characters to it, would it preallocate some memory, or would it only allocate as much as I need?
To be precise:
 std::string s;
 s.reserve(20);
 char c = 'a';
 s = "";
 for(int i = 0; i < 25; i++)
    s += c;

In the above example I reserve an amount of memory. Now when I clear the string, will it cause the reserved memory to be discarded?
In the loop would it fill up the reserved memory and then reallocate for the extra 5 characters each time?

A: There is no requirement that std::string release allocated memory when you assign an empty string to it.  Nor when you assign a short string to it.  The only requirement is that when it allocates memory to hold a larger string, the allocation must be done in a way that achieves amortized constant time.  A simple implementation would be to grow by a factor of 2 each time more space is needed.
If you want the string's capacity to be minimized, you can use string::shrink_to_fit() in C++11.  Before C++11 some people resorted to the "swap trick" when they needed to reduce capacity.

A: string doesn't "remember" that you said 20 characters, it just knows its current capacity. So your reserve(20) call increases the capacity to at least 20 and has no further effect.
When you add 25 characters to the string, the capacity increases to at least 25 along the way. Then it remains at this new level unless you do something that reduces the capacity. Calling clear() does not alter the capacity.

A: No, reserved memory isn't discarded, swapwith an empty object for that.
Yes, when your reserve space is full, the next append, etc will cause a reallocation.


text:
Q: Prove that there $B : H\to H $ bounded such $ B^n = A $. Let $ A : H\to H $ a compact self-adjoint operator. Suppose $ A $ is positive. let $ n \geq 2 $. Prove that there is $B : H\to H $ bounded such $ B^n = A $.

A: By the Spectral Theorem, $A$ is of the form
$$
A=\sum_j\lambda_j\,P_j,
$$
where $\lambda_j\in\mathbb R$ and $P_j$ is a finite-rank projection for all $j$.
Now choose numbers $\mu_j\in\mathbb C$ with $\mu_j^n=\lambda_j$ and define
$$
B=\sum_j\mu_jP_j.
$$


text:
Q: data.table approach for creating a running sequential number for each row in a group I need to create a running sequential number for every row in a group. The groups are both the artist IDs and also the course number. The course number is also a sequential running number created based off of a very specific criteria: If an artist goes more than 7 days in between recording, a new course number is created.
For example, let's say that we have an artist_id whose data looks like this:

artist_id
session_number_total
CustomerRecordId
SiteRecordId
recording_date
control_panel
year

1
1
3
3
1/1/2000
Left
2000

1
2
3
3
1/3/2000
Right
2000

1
3
3
3
1/8/2000
Right
2000

1
4
3
3
5/1/2000
Left
2000

This artist_id came in for a session on 1/1/2000, 1/3/2000, 1/8/2000, and 5/1/2000. Based off of the aforementioned criteria for creating the course number groups (no more than 7 days in between recording dates) while also adding in the running count of the number of sessions for that artist, the final dataset should look like this:

artist_id
session_number_total
CustomerRecordId
SiteRecordId
recording_date
control_panel
year
days_between
Status
course_number
session_in_course

1
1
3
3
1/1/2000
Left
2000
0
Existing Course
1
1

1
2
3
3
1/3/2000
Right
2000
2
Existing Course
1
2

1
3
3
3
1/8/2000
Right
2000
5
Existing Course
1
3

1
4
3
3
5/1/2000
Left
2000
114
New Course
2
1

I am able to achieve this using some very convoluted code with dplyr. It works every time but the problem is that with 2.5 million rows in my dataset, the code can take 20-30 minutes to run each time I open a new session in R.
Considering how great data.table is for large sets of data, I'm wondering if anyone knows a data.table solution for creating the sequential group numbers and the running session count inside each of the groups based off of the criteria mentioned above? Any help would be appreciated so thank you in advance.
Here is a reproducible dataset and the code I used in dplyr to accomplish creating the final dataset:
library(tidyverse)
library(scales)
library(tibbletime)
library(lubridate)
library(data.table)

x <- structure(list(artist_id = c(257L, 257L, 257L, 257L, 257L, 257L,
                             257L, 257L, 421L, 421L, 421L, 421L, 421L, 421L, 421L, 421L, 421L,
                             421L, 421L, 421L, 421L, 421L, 421L, 421L, 421L, 421L), session_number_total = c(1L,
                                                                                2L, 3L, 4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
                                                                                10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L), CustomerRecordId = c(4L,
                                                                                4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
                                                                                5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), SiteRecordId = c(5L, 5L,
                                                                                5L, 5L, 5L, 5L, 5L, 5L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
                                                                                10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L), recording_date = structure(c(16062,
                                                                                16063, 16065, 16066, 16074, 16079, 16087, 16092, 16027, 16028,
                                                                                16035, 16038, 16056, 16058, 16065, 16072, 16073, 16077, 16079,
                                                                                16083, 16086, 16087, 16090, 16091, 16094, 16111), class = "Date"),
               control_panel = c("Left", "Left", "Left", "Left", "Left",
                                 "Left", "Left", "Left", "Bilateral", "Bilateral", "Bilateral",
                                 "Bilateral", "Bilateral", "Bilateral", "Bilateral", "Bilateral",
                                 "Bilateral", "Bilateral", "Bilateral", "Bilateral", "Bilateral",
                                 "Bilateral", "Bilateral", "Bilateral", "Bilateral", "Bilateral"
               ), year = c(2013L, 2013L, 2013L, 2013L, 2014L, 2014L, 2014L,
                           2014L, 2013L, 2013L, 2013L, 2013L, 2013L, 2013L, 2013L, 2014L,
                           2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L,
                           2014L)), class = "data.frame", row.names = c(NA, -26L))

x

final_df <- x %>%
  arrange(artist_id, recording_date) %>%
  group_by(artist_id) %>%
  mutate(days_between = recording_date - lag(recording_date, 1)) %>%
  arrange(artist_id, recording_date) %>%
  mutate(days_between = ifelse(is.na(days_between), 0, days_between)) %>%
  mutate(Status = ifelse(days_between > 7, "New Course", "Existing Course")) %>%
  mutate(num = ifelse(Status == "New Course", seq(1, 100000), 1)) %>%
  group_by(artist_id, Status, num) %>%
  mutate(group_num = row_number()) %>%
  ungroup() %>%
  group_by(artist_id, group_num) %>%
  mutate(course_number = ifelse(group_num == 1, seq(1, 100000),NA)) %>%
  ungroup() %>%
  group_by(artist_id) %>%
  fill(course_number) %>%
  ungroup() %>%
  group_by(artist_id, course_number) %>%
  mutate(session_in_course =row_number()) %>%
  select(-num, -group_num)

final_df <- as.data.frame(final_df)

final_df

A: How about this data.table solution:
library(data.table)
setDT(x)
x[, days_between := c(0, diff(recording_date)), by = .(artist_id)
  ][, course_number := 1L + cumsum(days_between > 7), by = .(artist_id)
  ][, session_in_course := seq_len(.N), by = .(artist_id, course_number)]
#     artist_id session_number_total CustomerRecordId SiteRecordId recording_date control_panel  year days_between course_number session_in_course
#         <int>                <int>            <int>        <int>         <Date>        <char> <int>        <num>         <int>             <int>
#  1:       257                    1                4            5     2013-12-23          Left  2013            0             1                 1
#  2:       257                    2                4            5     2013-12-24          Left  2013            1             1                 2
#  3:       257                    3                4            5     2013-12-26          Left  2013            2             1                 3
#  4:       257                    4                4            5     2013-12-27          Left  2013            1             1                 4
#  5:       257                    5                4            5     2014-01-04          Left  2014            8             2                 1
#  6:       257                    6                4            5     2014-01-09          Left  2014            5             2                 2
#  7:       257                    7                4            5     2014-01-17          Left  2014            8             3                 1
#  8:       257                    8                4            5     2014-01-22          Left  2014            5             3                 2
#  9:       421                    1                5           10     2013-11-18     Bilateral  2013            0             1                 1
# 10:       421                    2                5           10     2013-11-19     Bilateral  2013            1             1                 2
# 11:       421                    3                5           10     2013-11-26     Bilateral  2013            7             1                 3
# 12:       421                    4                5           10     2013-11-29     Bilateral  2013            3             1                 4
# 13:       421                    5                5           10     2013-12-17     Bilateral  2013           18             2                 1
# 14:       421                    6                5           10     2013-12-19     Bilateral  2013            2             2                 2
# 15:       421                    7                5           10     2013-12-26     Bilateral  2013            7             2                 3
# 16:       421                    8                5           10     2014-01-02     Bilateral  2014            7             2                 4
# 17:       421                    9                5           10     2014-01-03     Bilateral  2014            1             2                 5
# 18:       421                   10                5           10     2014-01-07     Bilateral  2014            4             2                 6
# 19:       421                   11                5           10     2014-01-09     Bilateral  2014            2             2                 7
# 20:       421                   12                5           10     2014-01-13     Bilateral  2014            4             2                 8
# 21:       421                   13                5           10     2014-01-16     Bilateral  2014            3             2                 9
# 22:       421                   14                5           10     2014-01-17     Bilateral  2014            1             2                10
# 23:       421                   15                5           10     2014-01-20     Bilateral  2014            3             2                11
# 24:       421                   16                5           10     2014-01-21     Bilateral  2014            1             2                12
# 25:       421                   17                5           10     2014-01-24     Bilateral  2014            3             2                13
# 26:       421                   18                5           10     2014-02-10     Bilateral  2014           17             3                 1
#     artist_id session_number_total CustomerRecordId SiteRecordId recording_date control_panel  year days_between course_number session_in_course


text:
Q: javascript for loop increment by > 1 problems I have this for loop which works for i and i+1, but i+2 onwards does not work.
The error is:
Cannot read property 'logo_sm' of undefined

Here's my code:
var jsonObj = JSON.parse(http_request.responseText);
var rows = '';
for(var i=0;i<jsonObj.length;i=i+2){
    rows += '
' + "" + '	' + "" + '	' + "" + '
';
    i++;
}
document.getElementsByTagName('table')[0].innerHTML += rows;

In the for loop, if increment is i++ and final column has i+1 instead of i+2 then it works.
Seems simple but still in learning phase. So, I am struggling with it.

A: The way your for loop is setup you will be trying to access array indexes for items that do not exist.
If you initialize i=json.length and have your loop increment by i+2 each time. When i is equal to the length of the JSON object, your loop will be trying to access elements at the length of the JSON object plus 2, which do not exist.
If you are just trying to output an image in each table row then do the following:
    var jsonObj = JSON.parse(http_request.responseText);
var rows = '';
for(var i=0;i<jsonObj.length;i++)
{
    rows += "

";
}

document.getElementsByTagName('table')[0].innerHTML += rows;


text:
Q: Struggling with \multirow and \multicolumn I have been struggling with \multirow and \multicol to try to fit the title of the first of the columns "Characteristics of organisational processes". For the moment, the best I accomplished (Case A) was reducing the font size (the rest is footnotesize):
\documentclass[a4paper,12pt, oneside]{report}

\usepackage{longtable}
\usepackage{multirow}

% Subscripts - defining new command
\newcommand{\textunderscript}[1]{$_{\textup{#1}}$}

\begin{document}
 ....

 %Case A

 \begin{longtable}{|p{3cm}||p{3.4cm}|p{3.4cm}|p{3.4cm}|}
 \hline \hline
 \multirow{2}{3cm}{\tiny{Characteristics of organisational processes}} & \multicolumn{3}{c|}{Degree of \textit{organicity}} \\ \cline{2-4}
& \textsl{d\textunderscript{1}}: High & \textsl{d\textunderscript{2}}:  Intermediate & \textsl{d\textunderscript{3}}: Low \\ \hline \hline \hline

...

\end{longtable}

 % Case B

\begin{longtable}{|p{3cm}||p{3.4cm}|p{3.4cm}|p{3.4cm}|}
\hline \hline
\multirow{2}{3cm}{Characteristics of organisational processes} & \multicolumn{3}{c|}{Degree of \textit{organicity}} \\ \cline{2-4}
 & \textsl{d\textunderscript{1}}: High & \textsl{d\textunderscript{2}}:    Intermediate & \textsl{d\textunderscript{3}}: Low \\ \hline \hline \hline

 ...

 \end{longtable}

 ...

 \end{document}

However, I would like to be able to fit with the same size as the rest of the table (Case B):

Nevertheless, I have not been able to either use the "p" type in this cell, or to extend it so it can fit by merging and extra row. Any ideas on how would it be possible to achieve this?
Thank you very much!

A: I expected the extra space to be evenly divided between the first two rows.
\documentclass[a4paper,12pt, oneside]{report}

\usepackage{multirow}
\usepackage{longtable}

% Subscripts - defining new command
\newcommand{\textunderscript}[1]{$_{\textup{#1}}$}

\begin{document}

\begin{longtable}{|p{3cm}||p{3.4cm}|p{3.4cm}|p{3.4cm}|}
\hline \hline
\def\arraystrecth{1.5}
\multirow{2}{3cm}[\normalbaselineskip]{Characteristics of organisational processes} & \multicolumn{3}{c|}{Degree of \textit{organicity}} \\ \cline{2-4}
\strut & \textsl{d\textunderscript{1}}: High & \textsl{d\textunderscript{2}}:  Intermediate & \textsl{d\textunderscript{3}}: Low \\ \hline \hline \hline
\def\arraystrecth{1}
\end{longtable}

\end{document}

This solution uses custom struts to make the first two rows taller.  Note: you cannot put the struts in front of \multicolumn, only inside.  Note the (somewhat fudged) fixup for \multirow.
\documentclass[a4paper,12pt, oneside]{report}

\usepackage{multirow}
\usepackage{longtable}

% Subscripts - defining new command
\newcommand{\textunderscript}[1]{$_{\textup{#1}}$}

\def\mystrut{\rule[-1.5\dp\strutbox]{0pt}{1.5\normalbaselineskip}}%

\begin{document}

\begin{longtable}{|p{3cm}||p{3.4cm}|p{3.4cm}|p{3.4cm}|}
\hline \hline
\multirow{2}{3cm}[\dp\strutbox]{Characteristics of organisational processes} & \multicolumn{3}{c|}{\mystrut Degree of \textit{organicity}} \\ \cline{2-4}
\mystrut & \textsl{d\textunderscript{1}}: High & \textsl{d\textunderscript{2}}:  Intermediate & \textsl{d\textunderscript{3}}: Low \\ \hline \hline \hline
\end{longtable}

\end{document}

A: I suggest using \makecell to control the line breaks in the first cell.  In addition, the package allows to define vertical spacing to add at top and bottom of cells.
Further, as your table is nearly text-wide, I replaced longtable with tabularx, and loaded ltablex which extends the functionalities of longtable to tabularx (which inherits longtable syntax).
Last point, double rules with hhline will intersect more neatly.
\documentclass{article}
\usepackage[showframe]{geometry}

\usepackage{booktabs}
\usepackage{ragged2e, setspace}
\usepackage{multirow, hhline, longtable, makecell}
\setcellgapes{3pt}
\usepackage{ltablex}
\keepXColumns

\begin{document}

\makegapedcells\setlength\tabcolsep{4pt}
\begin{tabularx}{\linewidth}{|>{\RaggedRight}X||*{3}{>{\RaggedRight}p{3.5cm}|}}
\caption{Summary of main characteristics of categories according to different degrees of \textit{organicity} identified in the organisational processes of the Drupal community}
\label{tab:layers-summary}\\
\hhline{=:t:=:=:=}
\multirow{2}{=}{\makecell[lc]{Characteristics\\[-0.5ex] of organisational\\[-0.5ex] processes}} & \multicolumn{3}{c|}{Degree of \textit{organicity}} \\ \cline{2-4}
& \textsl{d\textsubscript{1}}: High & \textsl{d\textsubscript{2}}: Intermediate & \textsl{d\textsubscript{3}}: Low \\
\hhline{:=::=:=:=:}
\endfirsthead
\hhline{=:t:=:=:=}
\multirow{2}{=}{\makecell[lc]{Characteristics\\[-0.5ex] of organisational\\[-0.5ex] processes}} & \multicolumn{3}{c|}{Degree of \textit{organicity}} \\ \cline{2-4}
& \textsl{d\textsubscript{1}}: High & \textsl{d\textsubscript{2}}: Intermediate & \textsl{d\textsubscript{3}}: Low \\
\hhline{:=::=:=:=:}
\endhead
Amount of explicit & Based on implicit & Intermediate amount & Large amount of explicit \\
\end{tabularx}

\end{document}

A: Slightly modified nice Bernard' answer:
\documentclass{article}
\usepackage[showframe]{geometry}

\usepackage{ragged2e, setspace}
\usepackage{booktabs, hhline, makecell, multirow, ltablex, longtable}
\setcellgapes{4pt}
\keepXColumns

\begin{document}

\makegapedcells
\begin{tabularx}{\linewidth}{|>{\RaggedRight}X||
                         *{3}{>{\RaggedRight}p{3.5cm}|}}
\caption[Summary of main characteristics of categories according to \textit{organicity}]
        {Summary of main characteristics of categories according to different degrees of \textit{organicity} identified in the organisational processes of the Drupal community}
\label{tab:layers-summary}\\
\hhline{=:t:=:=:=}
\multirow{2}{=}{\linespread{0.8}\selectfont % changed
                Characteristics of organisational processes}
    &   \multicolumn{3}{c|}{Degree of \textit{organicity}} \\
    \cline{2-4}
    &   $d_1$: High
        &   $d_2$: Intermediate
            &   $d_3$: Low                                  \\
\hhline{:=::=:=:=:}
    \endfirsthead
%%%%
\caption{Summary of main characteristics of categories according to \textit{organicity}
         (cont.)}% added
\label{tab:layers-summary}                                  \\
\hhline{=:t:=:=:=}
\multirow{2}{=}{\linespread{0.8}\selectfont
                Characteristics of organisational processes}
    &   \multicolumn{3}{c|}{Degree of \textit{organicity}}  \\
    \cline{2-4}
    &   $d_1$: High
        &   $d_2$: Intermediate
            &   $d_3$: Low            \\
\multirow{2}{=}{\linespread{0.8}\selectfont % changed
                Characteristics of organisational processes}
    &   \multicolumn{3}{c|}{Degree of \textit{organicity}} \\
    \cline{2-4}
    &   $d_1$: High % changed
        &   $d_2$: Intermediate
            &   $d_3$: Low                                  \\
\hhline{:=::=:=:=:}
    \endhead
%%%%
\hhline{-:t:-:-:-}
\multicolumn{4}{r}{\footnotesize\itshape
                    continue on the next page}
    \endfoot
\hhline{:=::=:=:=:}
    \endlastfoot
%%%%
Amount of explicit
    &   Based on implicit
        &   Intermediate amount
            &   Large amount of explicit                    \\
... &...&...& ...
\end{tabularx}


text:
Q: Improve a clojure function I have a homogeneous list of maps, like the following
({:x 1 :y 2} {:x 3 :y 5} {:x 1 :y 7} {:x 2 :y 0} {:x 3 :y -1})

I'd like to sum the :y values of the pairs with equal :x values.  I mean, I want a function y-adder that if applied to the preceding list gives the list (the order doesn't matter, it could be a set instead of a list)
({:x 1 :y 9} {:x 3 :y 4} {:x 2 :y 0})

What I wrote is the following:
(defn y-adder [Ps]
  (let [xs (set (map :x Ps))]
   (let [y+ (fn [v] (apply + (map :y (filter #(= (:x %) v) Ps))))]
    (map #(hash-map :x % :y (y+ %)) xs))))

It works, but it seems over-complicated for such a simple task.  So I'm wondering if there is a simpler (and maybe more efficient) solution.

A: To me this is a bit simpler, but I haven't checked to see if it's more efficient.
> (for [[k v] (group-by :x xs)] {:x k :y (apply + (map :y v))})
({:x 1, :y 9} {:x 3, :y 4} {:x 2, :y 0})

The key is the group-by:
> (group-by :x xs)
{1 [{:x 1, :y 2} {:x 1, :y 7}],
 3 [{:x 3, :y 5} {:x 3, :y -1}],
 2 [{:x 2, :y 0}]}

Once you have that it's a short trip to your desired result.

A: You can use group-by:
(defn y-adder [ps]
  (map (fn [[x-val matches]]
         {:x x-val :y (apply + (map :y matches))})
       (group-by :x ps)))


text:
Q: DateTimeOffset, not clear understanding I read a documentation about DateTimeOffset, property DateTime.
https://msdn.microsoft.com/en-us/library/system.datetimeoffset.datetime(v=vs.110).aspx

The DateTime property is not affected by the value of the Offset
  property. This property returns both the date and the time component
  of a DateTimeOffset object, which makes it useful for performing
  DateTimeOffset to DateTime conversion. For example, if the
  DateTimeOffset object has a date and time value of "1/12/07 4:01pm +
  7:30", the property returns a date of "1/12/07 4:01pm".

I have +2 GMT timezone and try the following code:
    var dateString = "2012-03-01 00:00:00-23:00";
    var birthDay = DateTime.Parse(dateString);
    DateTimeOffset dtOffset = new DateTimeOffset(birthDay);

then I look at property DateTime of dtOffset object and see {3/2/2012 1:00:00 AM} value. UtcDateTime has {3/1/2012 11:00:00 PM} value, LocalDateTime has {3/2/2012 1:00:00 AM} value. So, property DateTime of DateTimeOffset instanse has DateTime WITH Offset. Where am I wrong?

A: The DateTimeOffset really should be called ADateTimeWithAnOffset, because it has two properties -- the DateTime you supply, and the Offset. This makes it useful for conversions, but does NOT convert anything itself.
From the docs...The DateTimeOffset structure includes a DateTime value, together with an Offset property that defines the difference between the current DateTimeOffset instance's date and time and Coordinated Universal Time (UTC).
Your time is interesting, not because of the DateTimeOffset, but because of your initial string format.  As soon as you add the offset to the send of the string, it takes into account your local time offset as well when creating the underlying DateTime.  In my time zone, which is UCT-5, this is what happens...
Console.WriteLine(DateTime.Parse( "2012-03-01"));
3/1/2012 12:00:00 AM

Console.WriteLine(DateTime.Parse("2012-03-01  00:00:00-23:00"));
3/1/2012 6:00:00 PM

And if you check the Kind property on the underlying DateTime, you'll see that it is Local as soon as you create it from the string with the offset.

A: I think what you missed is that UtcDateTime and LocalDateTime actually are conversions. So if you reference these two properties, you are asking for converted values. For that reason, the values they got you do not contradict the statement "The DateTime property is not affected by the value of the Offset property."
UtcDateTime converts the DateTime property's value to UTC using the offset (it adds 23 hours to the DateTime part).
LocalDateTime converts the DateTime property's value to YOUR local time according to your Windows TimeZone setting (which must be UTC-1?).


text:
Q: Using XAMPP to access .accdb I am working on a web interface for a book database that my wife and I use. We have always kept it in .accdb and just used Access to make any changes but I would like to make it more accessible. I have a setup on XAMPP running that I use for other things so I made a folder there to test this with.
<?php
    //$dbName = $_SERVER["DOCUMENT_ROOT"] . "/db/Books.mdb";
    $dbName = $_SERVER["DOCUMENT_ROOT"] . "db/Books.accdb";

    if (!file_exists($dbName)){
        die("No database file.");
    }

    $db = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbName; Uid=; Pwd=;");
    // $db = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=$dbName; Uid=; Pwd=;");

    $sql = "SELECT * FROM Books ORDER BY author";
    $rs = $db->query($sql);
?>

If I convert the file to .mdb I can access it no problem but if I try it as .accdb and change the connection string to be for *.accdb or *.mdb, *.accdb it fails with:
Uncaught PDOException: SQLSTATE[HY000] SQLDriverConnect: -1028 [Microsoft][ODBC Microsoft Access Driver] Cannot open database '(unknown)'. It may not be a database that your application recognizes, or the file may be corrupt. in C:\xampp\htdocs\_index.php:13 Stack trace: #0 C:\xampp\htdocs\_index.php(13): PDO->__construct('odbc:DRIVER={Mi...') #1 {main}

With XAMPP I was thinking it would be completely independent from the machine and use it's own driver but it's like the drive/connection is missing. I have ran phpinfo and have confirmed the ODBC connection is enabled but I can't find where to confirm what extensions it supports to make sure that's not the issue.

A: Well... you need the Access database engine to work with .accdb files.
You can download the database engine 2016 here: https://www.microsoft.com/en-us/download/details.aspx?id=54920
Make sure you use the x64 version of the engine when using 64-bits PHP, and the 32-bits version for 32-bits PHP.
You need the Microsoft Access Driver (*.mdb, *.accdb) for accdb files, as the name implies. So switch comments on that line.
Note that you can get in trouble with a 32-bits office installation and 64-bits php, and the reverse. So match those.


text:
Q: Rails background image upload I'm using "carrierwave" gem for uploading image files and also "carrierwave backgrounder" to process the uploading + processing the image with RMagick in the background (I use Delayed Job for this).
Everything works like a charm. Except one thing - I want to upload the images and show them right under the upload form (so ,everything happens on the same page). So, basically, what happens - since the uploading and image-processing are relatively slow, by the time the page has been rendered after the posting - the image itself is not yet ready: so image_tag shows broken "assets" link (href = "assets"). After waiting 2-3 seconds (couple of refreshes), the image appears on the screen.
So, my question would be - can I somehow show the "LOADING" animation (or text, or another picture - doesn't matter) instead of broken (not yet available) image, and once it is ready - to display the image to the user. Can this be done without AJAX ? Or should I consider re-doing it with AJAX ?
Sorry for the long story. Hope for your help!
Thanks in advance! :)

A: My solution is pretty simple: I observe if I have any images containing "tmp" field in the database (s.t tmp != null). If so - they are being processed in the background, so I use setInterval function, that keeps asking if tmp is null or not: Once it is null - processing is done for sure. if not - loading animation is running instead of the uploaded image. Quite simple.

A: You have different way of achieving this :
One is to use https://github.com/lardawge/carrierwave_backgrounder , so you'll know if the image is being processed with the new column it uses.
You could also use the JS File API as described here : http://kellishaver.tumblr.com/post/21428272282/using-the-file-api-to-preview-images-before-uploading
And I guess there are other options.


text:
Q: ¿Existe el usuario o es Administrador? ¿Cómo hacer un middleware con ésto? os pongo en situación.
Tengo una aplicación típica donde existe el rol de usuario y el rol de administración.
A algunos métodos (Crear un producto, editarlo, borrarlo...etc) Solo tendrían permiso los administrador mientras que, para ver estos productos, comprarlos...etc tendría permiso el usuario.
He creado un código que funciona a la perfección y es éste:
if (\Auth::user()==null) {
            return redirect()->route('home');
        }elseif (\Auth::user()->role != 'admin') {
            return redirect()->route('home');
        }

Esto me comprobaría en cada método que quisiese si el usuario está logueado y si lo está comprobaría si es administrador. El caso es que, es un poco engorroso incluir este método en CADA UNO de los métodos.
¿Alguna solución un poco más practica? He probado a usarlo en un helper pero he comprobado que no puedo incluir métodos estáticos y bajo un middleware no me funciona (tal vez no lo haya implementado bien)

A: La respuesta es más fácil de lo que pensaba.
Incluir en el constructor de la clase del Controlador:
$this->middleware('auth');

Este middleware ya viene hecho al general los Auth con Laravel y así puedes implementarlo.
Si quieres exceptuar algunos métodos:
$this->middleware('auth')->except('metodo)';

Para hacerlo con el Administrador:
php artisan make:middleware IsAdmin

Y dentro de handle escribimos:
if(Auth::user()->role == 'admin'){
            return $next($request);
        }else{
            return redirect()->route('home');
        }

(En este caso, la propiedad de mi tabla que comprueba si un usuario es administrador es 'role')
Añadimos el middleware en el archivo Kernel que está en App\Http
(lo metemos dentro del array $routeMiddleware)
'admin' => \App\Http\Middleware\IsAdmin::class,

Con esto ya estaría. Ahora únicamente llamamos al middleware en nuestro constructor
$this->middleware('admin');


text:
Q: Bold text in result set from the text I am trying to find a solution to this problem.
I have a text input, and when the user types in the text input "trending". I return a result set of text containing the word trending. What I want to do is display the text that was entered bold (example: trendingitems).
The solution I have currently works, sort of.
    String resultText = "trending items";
    int x = resultText.toLowerCase().indexOf(queriedText.toLowerCase()); // Problem happens here, I get -1 as a result
    List parts = [ // I use this list to display in a Rich Text to adjust the style of the text the user input
      if (resultText.substring(0, x).isNotEmpty) resultText.substring(0, x).trim(),
      queriedText,
      if (resultText.substring(x + queriedText.length).isNotEmpty)
        resultText.substring(x + queriedText.length).trim()
    ];

    int idx = resultText.toLowerCase().indexOf(queriedText.toLowerCase());
    while (idx > 0 && idx < resultText.length) {
      String _subT = resultText.substring(idx + queriedText.length);
      idx = _subT.toLowerCase().indexOf(queriedText.toLowerCase());
    }

If the user enters trending items but the result set has trendingitems, int x is returned a value of -1 which is where the widget crashes (understandably).
What I would like to get is the following:
This scenario works:

*

*User types: trending

*Display: trending items in the list

This scenario crashes:

*

*User types: trending items

*Display: trending items in the list

TIA

A: I've made a package for this: text_chunk_styling
dependencies:
  text_chunk_styling: ^2.0.1

Basically it will apply a custom TextStyle to some part of your text in your case the code would be something like this:
Sample 1
TextChunkStyling(
  text: 'trending items',
  highlightText: const ['trending'],
  highlightTextStyle: const TextStyle(fontWeight: FontWeight.bold),
)

Sample 2
TextChunkStyling(
  text: 'trending items',
  highlightText: const ['trending items'],
  highlightTextStyle: const TextStyle(fontWeight: FontWeight.bold),
)


text:
Q: Does a tower bell ringing prevent thunderstorms? Introduction
This is the beginning of an apparently physics-unrelated question, which involves 1700-1800 Italian law, atmospheric processes, sound waves propagating through fluid and clouds, and lightning strikes burning down churches.
The core of the question is figuring out if and how a sound wave influences the formation / disruption of clouds and eventual thunderstorms.
Background and Context
I live next to the European Alps, in northern Italy. Here weather is often cloudy and thunderstorms are not rare. For religious purposes, every town in this area has a church with a tall bell tower alongside it. And of course, a huge bronze bell hangs in each tower to ring every hour.
I've talked to a local elderly (who happens to manage the bell tower) about thunderstorms, and I was told that when a thunderstorm approaches he rings the bell repeatedly and vigorously to try to "break up the storm", in order to supposedly avoid rain and thunder falling on the town. This is a practice still widely used to this day in this area. Me being a engineering student, I wanted to figure out if that really made sense and what effects ringing the bell really had.
Question formalization
A bronze bell ringing multiple times produces sound. The kinetic energy of the bronze clapper is cast on the bell, which converts it into sound energy.
Specifically, the bronze bell vibrates and transfers the sharp vibration to the layer of air molecules wrapped around the bell, which initiates a chain transmission. This produces sound waves, which are longitudinal (compression) waves transmitted through a fluid (air).

Longitudinal waves are waves in which the vibration of the medium is
parallel ("along") to the direction the wave travels and displacement
of the medium is in the same (or opposite) direction of the wave
propagation. Mechanical longitudinal waves are also called
compressional or compression waves, because they produce compression
and rarefaction when traveling through a medium, and pressure waves,
because they produce increases and decreases in pressure. [source]

Those waves are then spread out more or less spherically (following the inverse square law) from the bell top point.
The natural questions to ask at this point are:

*

*What happens when the sound wave passes through the cloud?

*Does the wave have enough energy to reasonably alter the formation of the cloud and therefore prevent / allow the thunderstorm?

*Is there such thing as "breaking up the storm" or is it just a popular belief?

I genuinely have no idea since I have no first hand experience with this.
Thunderstorm formation looks like a whole different process, and I can't seem to find a connection with sound waves.

Thunderstorms form when warm, moist air rises into cold air. The warm
air becomes cooler, which causes moisture, called water vapor, to form
small water droplets - a process called condensation. The cooled air
drops lower in the atmosphere, warms and rises again. [source]

Historically relevant experiments
While doing my research I found papers from the late 1700s where Italian scientist were trying to answer one of our questions: does ringing the tower bell disrupt an incoming thunderstorm?
Their answer is the opposite of what I expected: they thought that ringing the bell actually amplified the storm.
You can find the original version of these papers here
Their results look extremely nonrigorous, but it can be a starting point to reflect on.
Note: I can do a full translation of the paper if someone is interested, right now I'll do my best to translate and summarize the key concepts (sparing you a ton of mid-1700 religious and legal drama)
Paper published in 1770
Key: Total nonsense

The vibration induced by the bell sharp sound has 2 effects on air: it
rubs together different parts [of the cloud] and it thins out the mass
[of the cloud]. The rubbing, as it is known, awakens the "electric
fire" (I have no clue about what that is). The thinning out attracts
it [the electric fire], diminishing air resistence. Vibrations in
general unite instead of breaking up.

It is also said that the bell sound (while storming) attracts the lightning strikes on the tower bell (which is pure nonsense), instead of letting lightning target houses or fields, and it is thought to be a good thing.
Plus, the bell sound would warn locals that a storm is approaching.
Act of 1783
Key: Law prohibits ringing bells during storms

A series of sad experiences says that the tower bell ring, instead of
dissipating the clouds and the storms, activates and puts in danger
the towers and the churches, which have been subject to numerous
strikes, fires and deaths during storms. It is therefore prohibited to
ring bells during storms.

Paper published in 1787:
Key: Evaluation of air vibration effects on clouds
This paper exposes 2 reasons backing up the law against ringing bells during storms.

1: Atmospheric Sound Ondulations.
Vibrations originated from
percussion of objects propagate spherically, generating "compression
and approachment of parts". Not heavy clouds break under this
condition. But a cloud is a electrified conductor. It is known that
the stress exercised from the electric fire is inversely proportional
to its capacity, and its capacity is directly proportional to the
surface area. If the cloud volume decreases, its surface area must
decrease too. Therefore, the capacity will decrease and the intensity
of the electric fire will increase.  From this we can infer that
vibrations, which compress the volume of a cloud, necessarily increase
the intensity of the electric fire, which will discharge on the
closest bodies, thus on the bell tower.

2: Air rarity around bell tower. Vibrations continuously remove air and turn it into thinner and thinner air. There is therefore an
air current towards the sound source. The electric fire will follow
that direction.

It ends with:

It is demonstrated that ringing the bell promotes the striking of a lightning and targets the strike on the source of the vibrations.

A: The question whether ringing a bell on a tower can influence lightning strikes involves two aspects: hypothesizing physical processes which might be relevant, and then figuring out (or measuring) whether they are. Here are two physical processes I can think of: the sound waves in the air, and the bell itself with the clapper hitting it.
Sound waves could conceivably influence electrical conductivity of damp air, but I doubt whether this effect is large enough to have a non-negligible influence on the charge and field build-up which leads to a lightning strike.
The final image in the question shows a lightning rod (also called lightning conductor) not a bell. Such rods were introduced in the 1750s  (says Wiki). They work via two effects: a gradual one and a sudden one. The electric field near a charged conductor has a much larger value near a sharp point. So by using a pointed conductor one encourages modest currents in the air near the tip of the lightning rod which, gradually, tend to reduce the charge build-up in the cloud and thus reduce the overall frequency and strength of lightning strikes. This is not enough to entirely suppress strikes but overall it does help. These currents also have the effect of making the lightning more likely to strike the rod than other nearby things. This offers protection to the building as long as the long thick copper wire from ground to rod can itself conduct most of the current without melting.
Coming now to the ringing bell, if the clapper is metal then as it strikes the bell there might conceivably be an increase in the electrical emission from the bell (in the presence of the kind of charge build-up which occurs in thunderstorms). Thus it begins to play the first part of the role of a lightning rod. However I guess this effect is pretty small, and of course without the rest of the rod the bell offers no protection against an actual strike. As another answer has already pointed out, if such effects were non-negligible then one would think it would have been noticed and investigated by now, and bells would be recommended as a solution for some buildings. But last time I looked pretty much all church towers have lightning rods.
Finally, concerning cloud formation: this also is a big issue in many parts of the world so one would think that if bells could help then it would have been noticed and documented more fully and convincingly by now. Disturbing air which is already supersaturated will in general encourage (not discourage) droplets to form. However there have been many efforts to do this by seeding the air and it appears that it is hard to do on a large enough scale to have any useful impact.

A: There is enormous energy in a storm, which will be randomly oriented with respect to a bell tower.
The energy in the bell's sound will be radially falling with $1/r^2$ and is not directional. The energy that a man can input to the bell ringing is limited.
The physics answer must be: there is no connection.
Then the question becomes metaphysics, the bell ringing raises the religious impulses of people to diffuse the storm. Are prayers effective? Uneducated religious people in general seem to believe so. Physics has not reached the level of detecting whether there is anything in metaphysics, (from  telepathy to, in this case, manipulating storms)
Taking the expectation of bell ringing to defuse storms as a metaphsyics  experiment, the answer seems to be "prayers are not effective"

Churches and castles were often extremely dangerous buildings during thunderstorms in the days before the lightning rod was invented. Being so tall, they were highly vulnerable to lightning strikes: hundreds of bell-ringers across Europe were killed over the centuries in the mistaken belief that ringing the bells would ward off lightning. But an even greater hazard was the habit of storing gunpowder in castles and church vaults.

A: In addition to the energy considerations of a human generated sound wave, there is this to consider too:
As you state, sound is a longitudinal wave of pressure variation through the air.  Let's suppose we have the capacity to generate a VERY strong sound wave.
At the atmospheric level of the thundercloud, where water vapor is forming droplets, assuming the temperature stays relatively constant, the phase diagram of water would tell us that an increase in pressure will likely only increase the size of the water droplet (i.e. more water will be forced into the liquid portion of the phase diagram).  Conversely, a rarefaction or decrease in pressure, will likely only decrease the size of water droplets.
Since compressions and rarefactions follow one another, the net effect of this on water droplet size would likely be zero.
(Adding in the fact that things won't stay isothermal further supports this.  A pressure increase will lead to a temperature increase, which will work opposite that of the pressure increase: droplet size would likely decrease.  So the net effect of a pressure increase on droplet size is likely net zero.  Same for a pressure decrease when taking into account temperature changes due to the pressure change.)

A: The energy scale of thunderstorm is much larger than that of a bell (most other devices built by humans), so it is unlikely that such devices can affect thunderstorms in a controllable way.
A single bolt of lightning is can carry 108 to 1010  joules of energy. This is similar to the amount of electrical energy that the average US household uses in month (3×109 J). A complete thunderstorm has been estimated to carry 1015 J, which is enough energy to power 300,000 US households for one month or as much energy as would be released by 16 copies of the nuclear bomb dropped on Hiroshima, Japan in 1945.
A bell rung by a human can't use more than the power output of the human body which is about 400 W maximum. Even if this power was converted to sound with high efficiency and the person could maintain this level of effort for 10 minutes, the amount of energy released would only be 2.4×105 J. This is 4 billion times smaller than the estimated energy of the storm.
It is likely that only a device operating on similar energy scale on the time scale of thunderstorm could reliably control a thunderstorm. Nuclear weapons are the only technology we have that operates at this scale, but their energy can be easily controlled or directed with current technology and the collateral damage would be huge. Perhaps some tricks could be used to reduce the energy scale somewhat, which would be dependent on a very good understanding of storm dynamics and the ability to simulate them and potential interventions realistically. In any case, this is beyond the current technology level of humanity and probably will be for some time.
In any case, your question is an interesting case of people trying to find regularity in noise, with some thinking that ringing the bell makes the storm less dangerous and others thinking it makes the storm worse. The truth is that the bell is unlikely to have any consistent effect on the storm and the medieval people trying the bell method were finding patterns in random noise.

A: Of course a ringing bell has no effect on the weather. Imagine, if it did, bells would be a standard addition to any equipment or structure that is especially vulnerable to lightning strikes.

A: The sonic energy from thunder dwarfs any bell and I have seen no evidence that the pressure waves from thunder affect a storm.

A: The problem is, we don't know. Well, the rain and thunder can't be prevented, like a butterfly can't change the course of a storm. But it could prevent a lightning bolt from blitzing the ringer, while it could change the paths of the lighting strokes so he'll be blitzed down and stop his ringing, which has happened frequently.
So it could influence the storm and paths of lightning (chaos theory), but the energy thrown down from the clouds and the rain falling will not be influenced. Maybe if the ringer gives off a strong directed yell it will bump off the blitz...
So, while the ringing might influence the chaotic processed that are super sensitive to initial conditions, like lighting flashes are, it will have no effect on the clouds that run, the wind that blows and the rain that falls.

A: Ringing the bell will not stop a discharge of electricity between clouds but the intensity of sound waves generated thereby may well be reduced i.e.that of the clap.


text:
Q: When should you use a mount point in Azure Synapse Analytics? The documentation of Azure Synapse Analytics mentions two ways read/write data to an Azure Data Lake Storage Gen2 using an Apache Spark pool in Synapse Analytics.

*

*Reading the files directly using the ADLS store path

adls_path = "abfss://<containername>@<accountname>.dfs.core.windows.net/<filepath>"

df = spark.read.format("csv").load(adls_path)

*Creating a mount point using mssparkutils and reading the files using the synfs path

mssparkutils.fs.mount(
    "abfss://<containername>@<accountname>.dfs.core.windows.net",
    "/data",
    {"linkedService":"<accountname>"}
)

synfs_path = "synfs:/<jobid>/data/<filepath>"

df = spark.read.format("csv").load(synfs_path)

What is the difference between the two methods? When should you prefer to use a mount point?

A: The main difference between the two methods is in how the data is accessed and managed by the Apache Spark pool.
When you read data directly using the ADLS store path, the data is accessed directly from the storage account, without any intermediate caching or processing. This method is suitable when you need to access data that is stored in a different account or container than the one associated with the Synapse Analytics workspace, or when you need to perform operations on the data that are not supported by the Synapse file system (synfs).
On the other hand, when you use a mount point, you create a virtual file system that is mapped to the ADLS storage account. This allows you to access the data as if it were stored locally in the Synapse workspace, using the synfs path. The advantage of using a mount point is that you can leverage the Synapse file system capabilities, such as metadata management, caching, and access control, to optimize data processing and improve performance.
In general, you should prefer to use a mount point when you need to perform frequent read and write operations on the same data, or when you need to access the data from multiple Spark pools or jobs. This allows you to take advantage of the caching and performance optimization features of the Synapse file system. However, if you only need to access the data once or perform a simple operation, it may be more convenient to read the data directly using the ADLS store path.


text:
Q: Lost form validation when changed button type I have a form which validates that an option is selected using a returned boolean from a function:
<form  id="checkoutForm" action="https://www.paypal.com/cgi-bin/webscr" onsubmit="return validateForm()" method="post" name="paypal">

And I was submitting the form with this standard image button:
<input name="submit" type="image"  src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" value="Checkout">

However I've been updating and am using a CSS button instead so submit the form as so:
 Checkout with PayPal

I can just use the standard button like so:
<input name="submit" type="submit"  class="shopbutton" value="Checkout">

But this causes me some other small issues and I'd like to know how to ensure the form validates using the other method?
TIA
Edit: I should also mention that when using the <a href type button that the button is declared outside of the <form> tags.

A: You are bypassing the onsubmit when directly submitting the form with javascript. This is one example why client-sided validation is bad.
One solution to your problem would be to append your a link like this:
Checkout with PayPal

And then just add some error count to the validation function, and submit within the function if no errors were found, like so:
function validateForm() {
    var errors = 0;
    if(inputFieldHere.value.length<3) errors++;
    if(errors) return false; //Or display some error or something
    else document.forms["checkoutForm"].submit();
}

A: Try this:
<!DOCTYPE html>

    <title>element</title>

    <form name="form" id="form" method="post" action="#" onSubmit="return checkme();">
      <input type="checkbox" name="agree" id="agree" value="agree_terms" class="terms">
       I´ve read terms and conditions and I´m ready to shop
      <input type="submit" name="btnSubmit" value="Submit" class="submit">
    </form>
    Submit form

A: I suggest keeping <input> button inside the form as hidden (e.g. with style="display:none;").
This way you may keep  to submit form with onclick, and keep validation in place (I wouldn't be surprised if validation code looks for some reason for <input type="submit" /> inside a form)


text:
Q: How to create a Scratch Card in Android? I need to create a "Scratch Card" App for my final project in school and can't find the way how to implement the scratching event (How do I create background image and put Grey rectangles over it, so when I will scratch those rectangles I will see the picture under them)
The Implementation must be in Android because I don't how to develop In Objective-C yet.
I saw a reference for Objective-C Implementation, but it's no good as I don't understand it.
My Code is:
public class FingerPaint extends Activity {

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

        try {
            MyView myView = new MyView(this);
            myView.requestFocus();
            myView.PaintObjectInit();
            // setContentView(myView);

            LinearLayout upper = (LinearLayout) findViewById(R.id.LinearLayout01);
            upper.addView(myView);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        // MyImageView myImageView = new MyImageView(this);
        // setContentView(myImageView);
    }
}

public class MyView extends View {

    private Paint mPaint;
    private Bitmap mBitmap;
    private Canvas mCanvas;
    private Path mPath;
    private Paint mBitmapPaint;

    public MyView(Context context) {
        super(context);
        this.mPaint = new Paint();
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    }

    protected void PaintObjectInit() {
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        //mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        //mPaint.setColor(0xFFFF0000);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(12);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        try
        {

        //Bitmap bm1 = BitmapFactory.decodeResource(this.getResources(),R.drawable.scratch).copy(Bitmap.Config.ARGB_8888, true);;
        //Bitmap bm2 = BitmapFactory.decodeResource(this.getResources(),R.drawable.main).copy(Bitmap.Config.ARGB_8888, true);;

        //mBitmap = toTransparency(bm1, 0xFFAAAAAA, true, bm2);

        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);
        }
        catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {

        canvas.drawColor(0xFFAAAAAA);
        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
        canvas.drawPath(mPath, mPaint);
    }

    private float mX, mY;
    private static final float TOUCH_TOLERANCE = 4;

    private void touch_start(float x, float y) {
        // mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
    }

    private void touch_move(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
            mX = x;
            mY = y;
        }
    }

    private void touch_up() {
        mPath.lineTo(mX, mY);
        // commit the path to our offscreen
        mCanvas.drawPath(mPath, mPaint);
        // kill this so we don't double draw
        // mPath.reset();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touch_up();
            invalidate();
            break;
        }
        return true;
    }
}

Please help regarding this.

A: I found this library very useful.
https://github.com/sharish/ScratchView
Very easy to integrate
<com.cooltechworks.views.ScratchImageView
    android:id="@+id/sample_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:src="@drawable/img_sample2"
/>

A: I come across this problem recently and then I created a library for this so everyone can have a quick implementation of scratch view, hope this can help those who still looking for answer
https://github.com/winsontan520/Android-WScratchView

A: you can make "Scratch Card" application like this way. you need to follow the below code which is working code. you just need to required understand and implement your own logic.
public class MainActJava extends AppCompatActivity {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        setContentView(new MyView(this, bitmap));
    }

    public class MyView extends View implements View.OnTouchListener {

        private static final float TOUCH_TOLERANCE = 4;
        private Paint mPaint;
        private Bitmap oBitmap;
        private Bitmap holder;
        private Canvas mCanvas;
        private Path mPath;
        private Paint mBitmapPaint;
        private float mX, mY;

        public MyView(Context context) {
            super(context);
        }

        public MyView(Context context, Bitmap bitmap) {
            super(context);
            setOnTouchListener(this);
            this.oBitmap = bitmap;
            this.mPaint = new Paint();
            mPath = new Path();
            mBitmapPaint = new Paint(Paint.DITHER_FLAG);
            init();
        }

        protected void init() {
            mPaint.setAntiAlias(true);
            mPaint.setDither(true);
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeJoin(Paint.Join.ROUND);
            mPaint.setStrokeCap(Paint.Cap.ROUND);
            mPaint.setStrokeWidth(35);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            holder = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            mCanvas = new Canvas(holder);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            onDrawing(canvas);
        }

        private void onDrawing(Canvas canvas) {
            mCanvas.drawColor(0xFFAAAAAA);
            mCanvas.drawPath(mPath, mPaint);
            canvas.drawBitmap(oBitmap, getWidth()/2, getHeight()/2, mBitmapPaint);
            canvas.drawBitmap(holder, 0, 0, mBitmapPaint);
        }

        private void touch_start(float x, float y) {
            mPath.moveTo(x, y);
            mX = x;
            mY = y;
        }

        private void touch_move(float x, float y) {
            float dx = Math.abs(x - mX);
            float dy = Math.abs(y - mY);
            if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
                mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
                mX = x;
                mY = y;
            }
        }

        private void touch_up() {
            mPath.lineTo(mX, mY);
            mCanvas.drawPath(mPath, mPaint);
        }

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    touch_start(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_MOVE:
                    touch_move(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    touch_up();
                    invalidate();
                    break;
            }
            return true;
        }
    }
}

Output:


text:
Q: JSF 2.0 Injecting managed bean with a different scope I have a controller that is stateless which takes care of processing forms. This is defined as ApplicationScoped. On my page I have a form associated to a backing bean defined as a  ViewScoped.
The error I got when I want to process the form:
serverError: class com.sun.faces.mgbean.ManagedBeanCreationException Unable to create managed bean myController.  The following problems were found:
     - The scope of the object referenced by expression #{myFormBean}, view, is shorter than the referring managed beans (myController) scope of application

In my form:
       Name: <h:inputText value="#{myFormBean.name}" id="name" />
        <h:commandButton value="Save Name" action="#{myController.processForm}">
            <f:ajax render="nameResult" />
        </h:commandButton>
       Your name is <h:outputText value="#{myFormBean.name}" id="nameResult"/>

The controller:
@ManagedBean
@ApplicationScoped
public class MyController {
    @ManagedProperty("#{myFormBean}")
    private MyFormBean myBean;
    public void processForm() {
        System.out.println(myBean.getName());
        // Save current name in session
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(
                "name", myBean.getName());
    }
}

The backing bean:
@ManagedBean
@ViewScoped
public class MyFormBean {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

I could solve that by setting the controller as SessionScoped but it's not a clean way since the controller is stateless, so I don't need one controller for each session. One controller for the whole application should be sufficient.
I have a Spring MVC background, that's why I am confused on how to do things with JSF 2.0

A: I have JSF Managed Beans with different scopes referencing each other, and I have found Spring adequately addresses my needs.  The key to success was the Spring AOP that proxifies bean references and gives me more flexible autowiring.  I think it would make sense for you to mix JSF and Spring similarly to achieve your goals.
I don't use the JSF scope declaration annotations to declare my beans.  Instead, I use Spring to declare my beans, assign their scopes, and specify that I want the oddly-scoped beans to have aop proxies generated for them (so they can get autowired appropriately whenever they are referenced.)  I use the spring el-resolver to make my Spring beans addressable as JSF2 managed beans in EL.
I don't use view scope in my program, I use session scope with request-scoped beans referencing them.  But, I suspect my approach could be adapted for your view-scoped beans as well.
I don't use annotations to declare my beans, I use XML for declaring my beans and their scopes.  I just find it handy to have all of my bean declarations cataloged in one place.  I'm sure there's a pure annotation-based approach to achieve what I've got.  I do use the @Autowired annotation in my beans to indicate where references to other beans should be wired in.  This keeps my XML configuration short, eliminates the need for getter/setters, and gives me a little more Java-side flexibility than I've been able to get from going pure XML.
Finally, I gave myself a custom "SmartSession" scope.  This is essentially just like session scope, except, it re-autowires every time a bean is pulled out of session (this guards against bean replicas appearing unwired in a failover scenario in a cluster.)
I have come to the conculsion that for session- (and I presume view-) scoped beans to work, you need to make the bean Serializable and mark any @Autowired fields as transient.  The SmartSession gives me the confidence in that context to be assured that I stay autowired even in exceptional cases.  I based my SmartSession custom scope idea off of this answer: Initialize already created objects in Spring as well as internet sources for how to write custom scopes.
Here's some code snippets to hopefully give you some ideas -
Sample Session-scoped bean:
public class UserProfileContainer implements Serializable {
    private static final long serialVersionUID = -6765013004669200867L;

    private User userProfile;

    public void setUserProfile(User userProfile) {
        this.userProfile = userProfile;
    }

    public User getUserProfile() {
        return this.userProfile;
    }
}

Bean that references my smartSession-scoped bean:
public class KidProfileEditor implements Serializable {
    private static final long serialVersionUID = 1552049926125644314L;

    private String screenName;
    private String password;
    private String confirmPassword;
    private String firstName;
    private String lastName;
    private String city;
    private String state;
    private String notes;
    private String country;

    @Autowired
    private transient UserProfileContainer userProfileContainer;
}

Snippet from my applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:jee="http://www.springframework.org/schema/jee"
     xmlns:util="http://www.springframework.org/schema/util"
     xmlns:lang="http://www.springframework.org/schema/lang"
     xmlns:jms="http://www.springframework.org/schema/jms"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
         http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
         http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"

    default-lazy-init="true" >

    <!-- BOILERPLATE magic AOP setup tags -->
    <context:annotation-config />
    <context:component-scan base-package="com.woldrich.kidcompy" />
    <aop:aspectj-autoproxy />

    <!-- JSF2+Spring custom scope configurations -->
    <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
        <property name="scopes">
            <map>
                <entry key="safetySession">
                    <bean class="com.woldrich.kidcompy.faces.util.SpringSafetySessionScope"/>
                </entry>
            </map>
        </property>
    </bean>

    <bean id="userProfileContainer" class="com.woldrich.kidcompy.auth.UserProfileContainer" scope="safetySession">
        <aop:scoped-proxy />
    </bean>
    <bean id="kidProfileEditor" class="com.woldrich.kidcompy.faces.actionview.KidProfileEditor" scope="request" />
</beans>

web.xml snippet:
<web-app xsi:schemaLocation="http://java.sun.com/xml/ns/javaee /WEB-INF/includes/schema/web-app_2_5.xsd" id="KidCompy" version="2.5" metadata-complete="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee">
    <distributable/>

    <context-param>
        <description>Allows the Spring Context to load multiple application context files</description>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/mainApplicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
</web-app>

faces-config.xml snippet:
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee /WEB-INF/includes/schema/web-facesconfig_2_0.xsd"
              version="2.0">
    <application>
        <el-resolver>
            org.springframework.web.jsf.el.SpringBeanFacesELResolver
        </el-resolver>
    </application>
</faces-config>

A: There is a flaw in your design. Your controller is not stateless at all. It has a property which is different for each request/view, namely the myBean. If it was supported, then every new request/view would override the previously set one and the enduser will face the property value of a completely different enduser. This leads to problems in high concurrent situations.
You need to make it request/view scoped instead of application scoped. Still then, I believe that you have to approach it completely different. You're manually setting an attribute in the session scope in the action method instead of setting it as a property of an (injected) session scoped bean. How to solve it properly depends on the functional requirement which is not clear from the question.


text:
Q: API SOAP: Method retrieve, combine 3 or more filter conditions I am trying to apply 3 filter conditions to a soap call to get DataFolder info.
Single conditions are (as SimpleFilterPart elements):
<Filter xsi:type="SimpleFilterPart">
    <Property>ContentType</Property>
    <SimpleOperator>equals</SimpleOperator>
    <Value>email</Value>
</Filter>
<Filter xsi:type="SimpleFilterPart">
    <Property>IsActive</Property>
    <SimpleOperator>equals</SimpleOperator>
    <Value>true</Value>
</Filter>
<Filter xsi:type="SimpleFilterPart">
    <Property>ParentFolder.Name</Property>
    <SimpleOperator>equals</SimpleOperator>
    <Value>my emails</Value>
</Filter>

But in this way only first condition was applied.
To combine 2 conditions i have to use ComplexFilterPart, so my selection conditions become:
<Filter xsi:type="par:ComplexFilterPart" xmlns:par="http://exacttarget.com/wsdl/partnerAPI">
   <LeftOperand xsi:type="par:SimpleFilterPart">
      <Property>IsActive</Property>
      <SimpleOperator>equals</SimpleOperator>
      <Value>true</Value>
   </LeftOperand>
   <LogicalOperator>AND</LogicalOperator>
   <RightOperand xsi:type="par:SimpleFilterPart">
      <Property>ContentType</Property>
      <SimpleOperator>equals</SimpleOperator>
      <Value>email</Value>
   </RightOperand>
</Filter>
<Filter xsi:type="SimpleFilterPart">
    <Property>ParentFolder.Name</Property>
    <SimpleOperator>equals</SimpleOperator>
    <Value>my emails</Value>
</Filter>

But in this way only conditions between ComplexFilterPart were applied...
How can I set the conditions?

A: The SOAP logic will look something like this after combining the ComplexFilterParts and SimpleFilterParts.
<Filter xsi:type="ComplexFilterPart">
    <LeftOperand xsi:type="ComplexFilterPart">
        <LeftOperand xsi:type="SimpleFilterPart">
            <Property>IsActive</Property>
            <SimpleOperator>equals</SimpleOperator>
            <Value>true</Value>
        </LeftOperand>
        <LogicalOperator>AND</LogicalOperator>
        <RightOperand xsi:type="SimpleFilterPart">
           <Property>ContentType</Property>
           <SimpleOperator>equals</SimpleOperator>
           <Value>email</Value>
        </RightOperand>
    </LeftOperand>
    <LogicalOperator>AND</LogicalOperator>
    <RightOperand xsi:type="SimpleFilterPart">
        <Property>ParentFolder.Name</Property>
        <SimpleOperator>equals</SimpleOperator>
        <Value>my emails</Value>
    </RightOperand>
</Filter>


text:
Q: Apache error for setting django on webfaction im setting up a django project on webfaction, and after all configuration the website is showing a 200 error. In the apache error log this is the info:
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1] mod_wsgi (pid=803732): Target WSGI script '/home/hammad/webapps/gccfishing/gccFishing/gccFishing/gccFishing/wsgi.py' cannot be loaded as Python module.
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1] mod_wsgi (pid=803732): Exception occurred processing WSGI script '/home/hammad/webapps/gccfishing/gccFishing/gccFishing/gccFishing/wsgi.py'.
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1] Traceback (most recent call last):
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1]   File "/home/hammad/webapps/gccfishing/gccFishing/gccFishing/gccFishing/wsgi.py", line 27, in <module>
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1]     from django.core.wsgi import get_wsgi_application
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1]   File "/home/hammad/webapps/gccfishing/lib/python2.7/site-packages/django/core/wsgi.py", line 1, in <module>
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1]     from django.core.handlers.wsgi import WSGIHandler
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1]   File "/home/hammad/webapps/gccfishing/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 4, in <module>
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1]     import logging
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1]   File "/usr/local/lib/python3.2/logging/__init__.py", line 26, in <module>
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1]     import sys, os, time, io, traceback, warnings, weakref
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1]   File "/home/hammad/webapps/gccfishing/lib/python2.7/warnings.py", line 107
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1]     except _OptionError, msg:
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1]                        ^
[Fri Nov 01 15:04:38 2013] [error] [client 127.0.0.1] SyntaxError: invalid syntax

Can anyone please help?

A: Got it working. The error was caused because of mismatch between python versions. The mod_wsgi application on webfaction was running on python 3 and my app was using python 2.7.
Re-created a new mod_wsgi application with python2.7 and everything is now working.