text:
Q: Cannot receive Strings from Android Firebase Database I want to get the name (String) and the location (String) from my firebase database into a listview of a fragment page of my app. It doesnt give any errors but the name and location text just dont appear on the app. thanks for help. I think there is a problem to get the strings from the firebase server.
Firebase hierarchy : FIREBASE -> Events -> XmasParty -> location = Germany
                                                     -> name = XmasParty

FRAGMENT :
public class RequestsFragment extends Fragment {

    private Button create_event_btn;
    private View mMainView2;
    private RecyclerView mEventList;
    private DatabaseReference mEventsDatabase;
    private LinearLayoutManager mLayoutManager;

    public void ChatsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mMainView2 = inflater.inflate(R.layout.fragment_requests, container, false);
        mEventsDatabase = FirebaseDatabase.getInstance().getReference().child("Events");

        mLayoutManager = new LinearLayoutManager(getContext());
        create_event_btn = (Button) mMainView2.findViewById(R.id.create_btn);
        mEventList = (RecyclerView) mMainView2.findViewById(R.id.event_list);
        mEventList.setHasFixedSize(true);
        mEventList.setLayoutManager(mLayoutManager);

        create_event_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), Create_EventActivity.class);
                startActivity(intent);
            }
        });

        // Inflate the layout for this fragment
        return mMainView2;
    }

    @Override
    public void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Events, RequestsFragment.EventsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Events, EventsViewHolder>(

                Events.class,
                R.layout.users_single_layout,
                RequestsFragment.EventsViewHolder.class,
                mEventsDatabase

        ) {
            @Override
            protected void populateViewHolder(RequestsFragment.EventsViewHolder eventsViewHolder, Events events, int position) {

                eventsViewHolder.setDisplayName(events.getName());
                eventsViewHolder.setUserStatus(events.getLocation());
               // usersViewHolder.setUserImage(users.getThumb_image(), getApplicationContext());

                final String event_id = getRef(position).getKey();

                eventsViewHolder.mView2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        //Intent profileIntent = new Intent(UsersActivity.this, ProfileActivity.class);
                       // profileIntent.putExtra("user_id", user_id);
                       // startActivity(profileIntent);

                    }
                });

            }
        };

        mEventList.setAdapter(firebaseRecyclerAdapter);

    }

    public static class EventsViewHolder extends RecyclerView.ViewHolder {

        View mView2;

        public EventsViewHolder(View itemView2) {
            super(itemView2);

            mView2 = itemView2;

        }

        public void setDisplayName(String name){

            TextView userNameView = (TextView) mView2.findViewById(R.id.user_single_name);
            userNameView.setText(name);

        }

        public void setUserStatus(String status){

            TextView userStatusView = (TextView) mView2.findViewById(R.id.user_single_status);
            userStatusView.setText(status);

        }

        }
    }
}

EVENTS CLASS
public class Events {

    public String name;
    public String location;
    public String time;

    public Events(){

    }

    public Events(String name, String location, String time) {
        this.name = name;
        this.location = location;
        this.time = time;
    }

    public String getName() {return name;}
    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }

    public String getTime() {return time;}
    public void setTime(String time) {this.time = time;}

}

A: To get the value of location and name, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("Events").child("XmasParty");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String location = dataSnapshot.child("location").getValue(String.class);
        String name = dataSnapshot.child("name").getValue(String.class);
        Log.d("TAG", location + " / " + name);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);

The output will be:
Germany / XmasParty


text:
Q: Python error al guardar .txt porque? Intento guardar texto de 1 linea en un .txt pero el ultimo apostrofe (') de la linea 19 se guarda en la siguiente linea (linea 2), por que ?.
Adjunto el codigo y una imagen de lo que me arroja la consola al ejecutar el codigo, asi tal cual se guarda en el .txt
from io import open
import time
import requests

archivo_texto = open('direcciones_convertir.txt', 'r')
dir_num = len(archivo_texto.readlines())
#print ('Direcciones a verificar: ',dir_num)
archivo_texto.close()

for i in range(0,1):
    archivo_texto1 = open('direcciones_convertir.txt', 'r')
    leer_direccion = archivo_texto1.readlines()
    archivo_texto1.close()

    direccion = leer_direccion[i]

    archivo_texto2=open('direcciones_convertidas.txt','a')
    archivo_texto2.write('dir' + str(i) + "='" +  leer_direccion[i] + "'")
    #archivo_texto2.write("'")
    print ('dir' + str(i) + "='" +  leer_direccion[i] + "'")

A: Probablemente el error consiste en que el archivo .txt tenga una linea al final que solo contenga '. Algo así como:

Esto es un ejemplo
  del contenido del archivo txt
  '

Bonus: Esto no tiene que ver con tu error, pero dos consejos:
1: Usa f-strings, es más facil de leer el código si no tienes que usar +. Ejemplo:
print ('dir' + str(i) + "='" +  leer_direccion[i] + "'")  # Sin f-strings
print (f"dir{i}='{leer_direccion[i]}'")  # Con f-strings

2: Utiliza with open() (explicacion aqui) ya que al no cerrar el archivo puede que crees problemas de caché en un futuro. Además, no es necesario importar io. Convertirías esto:
archivo_texto = open('direcciones_convertir.txt', 'r')
dir_num = len(archivo_texto.readlines())
archivo_texto.close()

en esto:
with open('direcciones_convertir.txt', 'r') as archivo_texto:
    dir_num = len(archivo_texto.readlines())

Pero el código se asegura 100% que el archivo va a ser cerrado antes de continuar. Ya que el with cierra el archivo automaticamente.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read a single line of txt file word by word [C++] I need to read a single line of a given file word by word.
The file is a register of exam grades by different students. In particular, for any student there is a first
line formatted as follows:
-name- -surname-
Then, there is a second line reporting the grades of every exam using the following format:
-grade 1- -grade 2- -grade 3- [...] -grade n-
I created a class Student and want to put the grades in an array of int.
I know how to read the file word by word, but I have no idea how to stop once the grades from a student are over (since I don't know how may grades any given student has beforehand).
I thought to write a while repetition statement, but I have no idea what the condition could be.
Is there a way to read a line word by word and then stop reading once the line is over?
This is what I managed to write until now:
cout << "Inserisci il nome del file da analizzare: " << endl;
cin >> _filename;
fstream myfile;
myfile.open(_filename);
if (myfile.is_open())
{
    myfile >> _name >> _surname >> ;  //reading name and surname

}

A: *

*Read a line of text using std::getline.

*Read each token from the line by using a std::istringstream.

std::string line;
if ( ! std::getline(myfile, line) )
{
   // Problem reading the line.
   // Deal with error.
}
else
{
   // Read line successfully.
   std::istringstream str(line);
   std::string token;
   while ( str >> token )
   {
      // Use token.
   }
}


text:
Q: Copying specific columns from multiple sheets after active sheet VBA I'm trying to code a VBA that selects the first column of every sheet after the active sheet I am on (this will change), and copies into the newly created sheet which will appear after the active sheet
This code below won't work but hopefully it gives an idea of what I am trying to achieve
Dim sht As ActiveSheet

Sheets(after.sht).Columns("1").copy 'I want to copy column one from every sheet after the current sheet I'm on
Sheets.Add after:=sht.paste 'then paste into a new sheet which appears after the Active sheet I started on

A: Option Explicit
Sub CopyColumns()

Dim Source As Worksheet
Dim Destination As Worksheet
Dim Last As Long

Application.ScreenUpdating = False

'Checking whether "Master" sheet already exists in the workbook
For Each Source In ThisWorkbook.Worksheets
    If Source.Name = "Master" Then
        MsgBox "Master sheet already exist"
        Exit Sub
    End If
Next

'Inserting new worksheets in the workbook
Set Destination = Worksheets.Add(after:=Worksheets("Main"))

'Renaming the worksheet
Destination.Name = "Master"

'Looping through the worksheets in the workbook
For Each Source In ThisWorkbook.Worksheets

    If Source.Name <> "Master" And Source.Name <> "Main" Then

        'Finding the last column from the destination sheet
        Last = Destination.Range("A1").SpecialCells(xlCellTypeLastCell).Column

        If Last = 1 Then
            'Pasting the data in the destination sheet
            Source.UsedRange.Copy Destination.Columns(Last)
        Else
            Source.UsedRange.Copy Destination.Columns(Last + 1)
        End If
    End If
Next

Columns.AutoFit

Application.ScreenUpdating = True

End Sub

A: Give this a try:
Dim flagSh    As Worksheet
Dim newSh     As Worksheet
Dim i         As Long

With ThisWorkbook
  If ActiveSheet.Index = .Worksheets.Count Then Exit Sub
  Set flagSh = ActiveSheet
  .Worksheets.Add , flagSh
  Set newSh = ActiveSheet

  For i = .Worksheets.Count To newSh.Index + 1 Step -1
    .Worksheets(i).Columns(1).Copy
    newSh.Columns(1).Insert Shift:=xlToRight
  Next
  Application.CutCopyMode = False
End With

Hope this helps you get started.


text:
Q: Find Id of Form bound to "sheetname" in copy of spreadsheet I am making a copy of a Google spreadsheet that contains forms associated with several sheets. I need to access the forms (of the copies) when running the code associated with each copy. Is there any way to do that?
Explication: Sheet1 of SS1 has a Form1, and Sheet2 has Form2. There is also Code1.
I make a copy of SS1: CSS1, which has CSheet1/CForm1, CSheet2/CForm2, and CCode1 (the names of the sheets don't actually change with the copying of course). I need the code in the copy, CSS1.CCode1, to be able to find CForm1 and CForm2. It will know they are associated with sheets named Sheet1 and Sheet2 in CSS1.
Please tell me this is possible :-) Thanks!
Note: there are many copies being made, this is a simplification. It should be obvious I can't use openById() or openByURL(), unless I've missed something. I can't figure out whether I could use getActiveForm(), since there'd be more than one form that's container-bound.

A: Okay, I've spent hours on this, including searching all over the Internet with no results.
I finally found a solution, but I'm too tired to make it formal and provide code, so maybe someone can add to this.
Here's what I found:
All the form URL's and the sheet IDs they are bound to are in the HTML code of the spreadsheet app.
Pressing F12 opens up the HTML editor, making it searchable.
So, let's make use of all that:

*

*I wrote a little script that opened each of my forms (190 of them!!) and put the form's URL, filename, and creation date into spreadsheet columns (of course, add whatever else you may need). Ex. "https://docs.google.com/forms/d/1sFEHY7xZ8mERPABCDjuFX_upPdXg9WA8eHuKRrFVOqI/edit?usp=drivesdk"

*Searching the HTML code of the spreadsheet app for a snippet of any part of the URL from step 1 (ex. "FVOqI") will locate the  tag containing the information we're looking for.

*Copying that tag's contents and pasting it into Word allows you to search it and clean it up. Search the Word text for that URL snippet again and you'll find the block containing the data you want.
ex.
[47296698,null,"1sFEHY7xZ8mABCDE74juFX_upPdXg9WA8eHuKRrFVOqI","1005701629"]],[47667827,[null,"1sFEHY7xZ8mABCDE74juFX_upPdXg9WA8eHuKRrFVOqI","1005701629",0.0]],[47296698,[null,"1V4BtJ7XAF2oVnlHGABCDEnXkKZdmg1vTMYjAX41RKYA","1245366039"]],[47667827,[null,"1V4BtJ7XAF2oVnlHGABCDEnXkKZdmg1vTMYjAX41RKYA","1245366039",0.0]]

and so on. Everything is duplicated for some reason.

*Now you can extract the first string which is the form's URL and the next string which is the sheet ID it is bound to.
4a. I wrote a little code that runs through all the sheets in the spreadsheet and puts the ID's and names into columns. Matching the sheet ID's from step 4 to your spreadsheet ID's and matching the URL's from step 1 will give you the file name, and you'll know which form is bound to which sheet.
Again, I apologize for not being more thorough, but my bosses are coming for me and I've got to get this project finished.


text:
Q: Pattern for copying hierarchical data from one table to another? Imagine a table with three columns: an ID primary key, a nullable ParentID referencing the ID column on that same table, and a TreeID to indicating the records that make up a particular tree. A basic hierarchical structure might look like this. Note that the ordinal values don't necessarily have an effect on a record's position in the hierarchy.
      dbo.TreeNodes             Visual representation:
+----+----------+--------+    --------------------------
| ID | ParentID | TreeID |       Tree 7:     Tree 15:
+----+----------+--------+       1           10
|  1 | NULL     |      7 |       |–3         |–9
|  2 | 4        |      7 |       |–4
|  3 | 1        |      7 |       |–|–2
|  4 | 1        |      7 |       |-5
|  5 | 1        |      7 |
|  9 | 10       |     15 |
| 10 | NULL     |     15 |
+----+----------+--------+

Given another unrelated table with an identical definition (dbo.TreeNodes2, let's say), I've found that copying the data from the first table to the second while maintaining its self-referential hierarchy isn't so straightforward. I get stuck after inserting the new dbo.TreeNodes2 records when it comes time to populate the ParentID values. I would have to have a mapping table of some kind to know which records from the first table map to the new records in the second table. Here's what I've got so far:
DECLARE @TreeID INT = 7;
-- hard code arbitrary TreeID value for the 2nd table for the sake of demo
DECLARE @NewTreeID INT = 42;

CREATE TABLE #InsertedRows
(
    ID INT NOT NULL PRIMARY KEY
);

INSERT INTO dbo.TreeNodes2
(
    ParentID,
    TreeID
)
OUTPUT Inserted.ID INTO #InsertedRows
SELECT
    NULL, -- ParentID can't be added yet because the IDs don't yet exist.
          -- They need to be updated in later.
    @NewTreeID
FROM dbo.TreeNodes AS tn1
WHERE tn1.TreeID = @TreeID;

I could add a non-related OldID column to dbo.TreeNodes2 to copy the original IDs to, which I could then use to create a mapping to join on and populate the new ParentID records, then null out all the OldID values when I'm done, but this seems like bad design. If SQL Server allowed the OUTPUT clause of an INSERT to include columns from a join, then this would be easy, but all of the documentation, as well as my own testing, indicates that only Inserted.* columns, Deleted.* columns, and scalar values/literals can be used in the OUTPUT clause. Nothing from joins.
My pipe dream, non-valid T-SQL that does what I want would look something like this:
CREATE TABLE #InsertedRows
(
    ID INT NOT NULL PRIMARY KEY,
    OldID INT NOT NULL
);

INSERT INTO dbo.TreeNodes2
(
    ParentID,
    TreeID
)
OUTPUT Inserted.ID, tn1.ID INTO #InsertedRows (ID, OldID)
SELECT
    NULL, -- ParentID can't be added yet because the IDs don't yet exist.
          -- They need to be updated in later.
    @NewTreeID
FROM dbo.TreeNodes AS tn1
WHERE tn1.TreeID = @TreeID;

From here, I would have a mapping table I can use to populate the ParentID values in the new table.
Is there a pattern for handing these kinds of cross-table hierarchical inserts without relying on an extra column whose only purpose is to allow the migration, after which it's an irrelevant column?

A: In this scenario I would not use IDENTITY for primary keys, but switch to sequences.
This way you can reserve sequence numbers to a temporary table, which became your mapping table, something like:
CREATE SEQUENCE TreeNodes2Sequence START WITH 1 INCREMENT BY 1 ;

CREATE TABLE TreeNodes2 (
    ID int PRIMARY KEY DEFAULT (NEXT VALUE FOR TreeNodes2Sequence),
    ...
)

CREATE TABLE #InsertedRows
(
    ID INT NOT NULL PRIMARY KEY,
    OldID INT NOT NULL
);

INSERT INTO #InsertedRows
(
    Id,
    OldId
)
SELECT
    NEXT VALUE FOR TreeNodes2Sequence,
    tn1.ID
FROM dbo.TreeNodes AS tn1
WHERE tn1.TreeID = @TreeID;

Then use this temp table to insert all values with null parent and then update parents.


text:
Q: Solving a quasi-linear PDE using the method of characteristics How does one solve the following equation by the method of characteristics?
$$\frac{\partial u}{\partial t}+u\frac{\partial u}{\partial x}=-u^2~\\
$$ with initial data $~u(x,0)=f(x)=x$
What I have so far: we let $V(t)=u(x(t),t)~,$ and $ \frac{dx}{dt}=u$
$ \frac{dV}{dt}=\frac{\partial V}{\partial t}+\frac{dx}{dt}\frac{\partial V}{\partial x}=\frac{\partial V}{\partial t}+u\frac{\partial V}{\partial x}=-u^2=-V^2$
so $\frac{dV}{V^2}=-dt$ and from this $V(t)=\frac{V(0)}{1+tV(0)}=\frac{u(x(0),0)}{1+tu(x(0),0)}=\frac{x(0)}{1+tx(0)}~~~$ since $f(x)=x$
now we use ${dx \over dt}=u=V(t)=\frac{x(0)}{1+tx(0)}$ which integrating gives $$x(t)=x(0)+ln(1+tx(0))$$
As far as I know we must now invert this equation for $x(0)=h(x,t)$ and then the solution to the PDE will be $$u(x,t)=f(x(0))=f(h(x,t))$$ however the equation is not invertible for $x(0)$...please could someone clarify?

A: To solve $x(t) = x(0) + \ln(1 + t x(0))$ for $x(0)$ you can use Lambert's W function: according to Maple,
 $x(0) = W(e^{x(t) + 1/t}/t) - 1/t$.
But if this is homework you're more likely to be expected to leave it in an "implicit" form.

A: $$u_t+uu_x=-u^2$$
This is what I get from the Charpit-Lagrange equations :
$$\frac{dt}{1}=\frac{dx}{u}=\frac{du}{-u^2}$$
A first characteristic from $-\frac{du}{u^2}-\frac{dt}{1}=0\quad\implies\quad \frac{1}{u}-t=\frac{1-ut}{u}=$constant.
$$\frac{u}{1-ut}=c_1$$
A second characteristic from $\frac{dx}{u}=\frac{du}{-u^2}$
$$ue^x=c_2$$
General solution on implicit form $c_2=F(c_1)$ :
$$ue^x=F(\frac{u}{1-ut})$$
Condition : $u(x,0)=x$
$x=xe^x=F(\frac{x}{1-0})=F(x)$
Now the function $F$ is determined for any variable $X$ :
$$F(X)=Xe^X$$
We put it into the above general solution where $X=\frac{u}{1-ut}$
$$\boxed{ue^x=\frac{u}{1-ut}\exp(\frac{u}{1-ut})}$$
This is an implicit form of the solution which can be equivalently written with the LambertW function :
$$\frac{u}{1-ut}=W(ue^x)\quad\text{or}\quad u=\frac{1}{t+\frac{1}{W(ue^x)}}$$
But whose forms with special function have not much interest.


text:
Q: Problem with CoreData and accessing relationships : request for member in something not a structure or union I have a question regarding a rather advanced DataModel which I would like to use with CoreData.
Before I get into details about what I did so far, I will describe what I want to do.
I have a List of Hotel Guests that stay in one Room and have Preferences. Once ready the user should select a guest and see the data and should also be able to add new guest, select the room (maintained also by application) and select their preferences (where the user can also add new preferences). The guest can have no or many preferences.
So here is what I have so far. I created 3 Entities : - Rooms with roomnumber - Preferences with name - GuestInfo with name -> with these Relationships room (Destination Rooms) and prefs (Destination Preferences with "To-Many Relationship") The prefs is a NSSet when you create a Managed Object Class.
So far so good. Now I have a UITableViewController that displays all guests, when I click on a guest I have another UITableViewController showing the details(DetailsViewController). Clicking on the Preferences it will go to another UITableViewController where I can select the Preferences. The problem I have is when I want to actually access the prefs in the DetailsViewController. Here is my cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
        cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

switch (indexPath.row)
{
  case 2:
    cell.textLabel.text = @"Preferences";

    NSEnumerator *e = [info.prefs objectEnumerator];
    id collectionMemberObject;

    while ( (collectionMemberObject = [e nextObject]) )
    {

    Preferences *prefInfo = collectionMemberObject;
    DebugLog(@"===> %@", prefInfo.name);

    }

    break;
}

info is the GuestInfo I pass through to the DetailsViewController.
Now with this I do get "request for member in something not a structure or union" accessing prefInfo.name.
Any idea whats wrong ?
thx

A: I had the same problem, the solution is as simple as you will bang your head against the wall once you hear it ;)
try [prefInfo name] instead of prefInfo.name.


text:
Q: jxdatepicker with Synthetica Aluoxide look and feel not working I have created a simple frame in netbeans and used SyntheticaAluOxide look and feel.
then i added the JXDatePicker from palette to frame;
now when i try to run the code. The program is throwing Exception as :
UIDefaults.getUI() failed: no ComponentUI class for: org.jdesktop.swingx.JXMonthView[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minimumSize=,preferredSize=]
java.lang.Error
    at javax.swing.UIDefaults.getUIError(UIDefaults.java:731)
    at javax.swing.MultiUIDefaults.getUIError(MultiUIDefaults.java:130)
    at javax.swing.UIDefaults.getUI(UIDefaults.java:761)
    at javax.swing.UIManager.getUI(UIManager.java:1013)
    at org.jdesktop.swingx.plaf.LookAndFeelAddons.getUI(LookAndFeelAddons.java:383)
    at org.jdesktop.swingx.JXMonthView.updateUI(JXMonthView.java:789)
    at org.jdesktop.swingx.JXMonthView.<init>(JXMonthView.java:320)
    at org.jdesktop.swingx.JXMonthView.<init>(JXMonthView.java:257)
    at org.jdesktop.swingx.JXDatePicker.initMonthView(JXDatePicker.java:361)
    at org.jdesktop.swingx.JXDatePicker.init(JXDatePicker.java:353)
    at org.jdesktop.swingx.JXDatePicker.<init>(JXDatePicker.java:281)
    at org.jdesktop.swingx.JXDatePicker.<init>(JXDatePicker.java:232)
    at com.test.DatePickerDemo.initComponents(DatePickerDemo.java:33)
    at com.test.DatePickerDemo.<init>(DatePickerDemo.java:21)
    at com.test.DatePickerDemo$1.run(DatePickerDemo.java:89)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:688)
    at java.awt.EventQueue$3.run(EventQueue.java:686)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:697)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

I have used the swingx library provided by Synthetica. Added Addon jar also.
Please help me out.

A: I have had this exception as well, but it some years back already. I remember it because it seems that Synthentica is enforcing the use of its SwingX extention when you only have a license for Synthetica core, and I was "not amused" by that. Turns out that this is not the case (because I'm using Synthetica core + SwingX now), but my memory fails me in how I got rid of that exception. Searchinf through the source code does not help either, so maybe an emailto Jyloo is in order.

A: Solution for my problem I got from jyloo.com is :
Reply from jyloo.com :

Generally SwingX support is provided by SyntheticaAddons - so you
  additionally need SyntheticaAddons.
      We also recommend to use our DateComboBox component instead of JXDatePicker.

so I added the syntheticaAddons.jar and syntheticaAluOxideAddon.jar to my classpath and used the de.javasoft.swing.DateComboBox.
I worked like charm.
Thanks to all the Supporters from stackoverflow.com and jyloo.com support team.


text:
Q: How to open XBRL document in android How to open XBRL document in our android app?any third party library available or is it availble already in android?

A: It seems nothing android specific is available, at least I couldn't find anything. Since Android development is done in Java, you could try integrating an existing java xbrl implementation into your project, usually it should work.
http://www.xbrlapi.org/
looks promising. If you're successful, please post a short review here, as I can imaging, this concerns several other people as well.


text:
Q: How to uppercase every letter of my input sentences? (In Java) First I want to give number of the sentences the user wanted to leave and when his writing ends my codes start to capitalize first letters of every word (in Java).
import java.util.Scanner;

public class India {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int num = input.nextInt();
        num = num + 1;
        String[] array = new String[num];
        for (int i = 0; i < num; i++)
        {
            array[i] = input.nextLine();
        }
        for (int j = 0; j < num; j++)
        {
            StringBuilder a = new StringBuilder();
            for (String s1 : array[j].split(" "))
            {
                char[] str = s1.toLowerCase().toCharArray();
                if (str.length > 0)
                {
                    str[0] = Character.toUpperCase(str[0]);
                    a.append(str);
                    a.append(' ');
                }
                System.out.println(a);
            }
        }
        input.close();
    }
}

And the new problem is

A: You could make your program a little simple by using apache StringUtils class. Inner loop in your program can be replaced by one liner. See if ut helps
Examples
StringUtils.capitalize(null)  = null
StringUtils.capitalize("")    = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"

A: if the input is not needed after printing, the program can be shortened considerably
Scanner input = new Scanner( System.in );
int num = input.nextInt();
input.nextLine();
for( int j = 0; j < num; j++ ) {
  Arrays.asList( input.nextLine().split( "(?<= )" ) ).forEach( s -> {
    System.out.print( StringUtils.capitalize( s ) );
  } );
  System.out.println();
}
input.close();

the changes to the original program:
– the String[] array is omitted
– the inner for-loop is replaced by the forEach lambda
– the argument for split is now "(?<= )" which keeps the blanks at the end of each separated string
after the input.nextInt() a pending \n must be read by a following input.nextLine()


text:
Q: Rails 6 - Sortable I have a problem with HTML sortable update in rails 6
I want to drag and drop the images through web page and that is worked fine but, When I want to update the order I got 404 not found error in console log and also an error in find ID.
by the way, I use this script for HTML sortable
https://github.com/jordanhudgens/devcamp-portfolio/blob/master/app/assets/javascripts/html.sortable.js
Controller :
class PortfoliosController < ApplicationController
  before_action :set_portfolio_item, only:[:edit , :show, :update , :destroy]
  layout "portfolio"
  access all: [:show, :index , :angular], user: {except: [:destroy, :new , :create , :update , :edit , :sort]}, site_admin: :all
    def index
        # You can filter what you want to show in protfolio
        # Portfolio.where(subtitle: "Angular")
        # You can define it in models and call the method here
        # It must create on Portfolio.rb in models
        # You can create scope too on models and call
        @portfolio_items = Portfolio.by_position
    end
    def angular
      @angular_portfolio_items = Portfolio.angular
    end
    def sort
      params[:order].each do |key, value|
        Portfolio.find(value[:id]).update(position: value[:position])
      end
      head :ok
    end
    def new
      @portfolio_item = Portfolio.new
      3.times { @portfolio_item.technologies.build }
    end
    def create
      @portfolio_item = Portfolio.new(portfolio_params)
        respond_to do |format|
        if @portfolio_item.save
          format.html { redirect_to portfolios_path, notice: 'Portfolio was successfully created.' }
        else
          format.html { render :new }
        end
      end
      end
    def edit
    end
    def update
      respond_to do |format|
        if @portfolio_item.update(portfolio_params)
          format.html { redirect_to portfolios_path, notice: 'The record was successfully updated.' }
        else
          format.html { render :edit }
        end
      end
    end
    def show
    end
    def destroy
      # Perform the lookup
      # Destroy/delete the record
      @portfolio_item.destroy
      #Redirect
      respond_to do |format|
      format.html { redirect_to portfolios_url, notice: 'Portfolio was successfully deleted!.' }
    end
  end
    private
    def portfolio_params
      params.require(:portfolio)
    end
    def set_portfolio_item
      @portfolio_item = Portfolio.find(params[:id])
    end
    end

This is my routes.rb
Rails.application.routes.draw do
  devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register' }
  resources :portfolios, except: [:show] do
    put :sort, on: :collection
  end
  get 'portfolio/:id' , to: 'portfolios#show', as: 'portfolio_show'
  get 'angular-items' , to: 'portfolios#angular'
  # we can pass anything here after get
  get 'about', to: 'pages#about'
  get 'contact', to: 'pages#contact'
  resources :blogs do
    member do
      get :toggle_status
    end
  end
  resources :posts
  root to: 'pages#home'
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

This is my CoffeeScript for HTML sortable
ready = undefined
set_positions = undefined

set_positions = ->
  $('.card').each (i) ->
    $(this).attr 'data-pos', i + 1
    return
  return

ready = ->
  set_positions()
  $('.sortable').sortable()
  $('.sortable').sortable().bind 'sortupdate', (e, ui) ->
    updated_order = []
    set_positions()
    $('.card').each (i) ->
      updated_order.push
        id: $(this).data('id')
        position: i + 1
      return
    $.ajax
      type: 'PUT'
      url: '/portfolios/sort'
      data: order: updated_order
    return
  return

$(document).ready ready

Thanks for your helps!


text:
Q: United Kingdom keyboard (language) is added automatically I've set keyboard languages: ENGLISH-US (not United Kingdom!) and ქარ (my local language).
Sometimes, I see that "ENGLISH (UNITED KINGDOM) [now "United States-International"] keyboard layout is added automatically in my keyboards list.

However, in Control Panel/Languages, it is not listed, neither shows in PowerShell:
$list = Get-WinUserLanguageList; echo  $list[0]; echo $list[1];echo $list[2];

so I can't even remove it! Even adding/removing doens't help!

It has become overly annoying, YEARS HAS PASSED but I can't stop it, can't uninstall. (update: I've posted my answer too below).

A: == Method 1==
The best way turned out to avoid United Kingdom  during Installation of Windows. That moment, as your KEYBOARD INPUT,  you should choose this:
English (United States) [if not shown, then English (International/US)]
== Method 2==
Click start and run this command directly:
powershell $LangList = Get-WinUserLanguageList; $MarkedLang = $LangList | where LanguageTag -eq en-GB; $LangList.Remove($MarkedLang); Set-WinUserLanguageList $LangList –Force;

== Method 3 (WORKED BETTER) ==
What worked for sure, was :

*

*Go to Language preferences

*There you should have added two
languages: United States and United Kingdom

*For both languages, click  Options > Add keyboard and add whatever you see
containing "English [US/United Kingdom/International]" add all them.

*Then, after added all ENGLISH/US/United Kingdom/International Languages
& Keyboard in all of them, **REMOVE ALL ENGLISH LANGUAGE ** packs.

*Then re-add only English (US / United States)
== Method 4 (Might be best) ==
Go to Languages > Administrative settings > Copy settings > [check the 2 checkboxes]  and  OK & Restart ("Restart later" doesn't exist!)

Update: to say frankly, none of them were able to fully remove UK package from my Win10. Enormously frustrating, years gone, MS still forcefully kick UKs still..

A: I'm not sure what you've already tried but here are some possible solution that might help you out.
Override default input method
If you go to: Control Panel > All Control Panel Items > Language > Advanced settings
You will see an option to override default input method. You can set this to your wanted keyboard setting.
If you click on Change language bar hot keys (see image bottom) you can change the ALT+SHIFT or CTRL+SHIFT hotkeys. A button in the Advanced tab will say Change key sequence. You can put them on non assigned.
(this is a response to a question similar to this from someone else)

A: You can do that using PowerShell, running on system startup:
powershell command
powershell Set-WinUserLanguageList -LanguageList en-US

Another thing might be needed to uninstall UK package:
Lpksetup /u

A: Add ENGLISH-UNITED KINGDOM keyboard
and remove it

A: I've found the solution here.

To fix this issue, delete the Preload registry folder and restart (or
  sign out) the computer:
HKEY_USERS.DEFAULT\Keyboard Layout\Preload
...
I have created a RemovePreload.reg text file with the following
  content, this way this fix can easily be re-applied every time without
  navigating the registry:
Windows Registry Editor Version 5.00
[-HKEY_USERS\.DEFAULT\Keyboard Layout\Preload]

To use this, save it in
  a text file and change the extension from .txt to .reg. Then whenever
  it comes back, you can just double click it and restart or sign out.

A: *

*Try Control Panel -> Clock, Language, and Region -> Language

*Now change everything to the way you want it to be.

*When you are done, go to:
Change date, time or number formats (left panel) -> Administrative (tab) -> Welcome screen and new user accounts (group box) and click on "Copy settings...".
In "Copy your current settings to" select:

*

*"Welcome screen and system accounts"

*"New user accounts"

*press OK.
Now all is left is to hope for the best because I don't remember if that's the right solution for the right problem.

A: When windows was installed, what was the default language? Images normally have major languages included with them but additional languages need to be downloaded from windows update. Its probably just going back to the Image default language when this happens.

A: Try this...
Open PowerShell as an administrator & type these commands.
Get-WinUserLanguageList
New-WinUserLanguageList en-US
Set-WinUserLanguageList en-US

After that, you can add your local language later.
 Reference: https://www.reddit.com/r/Windows10/comments/8i7ctr/cant_remove_english_uk_language_windows_10_build/?ref=share&ref_source=link

A: I've found a few references in Windows 8, but apparently according to this thread maybe it could help you: https://answers.microsoft.com/en-us/windows/forum/windows_10-other_settings/windows-keeps-automatically-adding-en-us-keyboard/69aaea0d-f588-4d54-89fa-a632ae7bced3
It seems to be one of three issues (see the site for more details):
1) Uncheck "Let me set a different input method for each app window." in language settings,
2) Make sure your region is set to your preference,
3) In Privacy settings, turn your location off.
Hopefully that helps.

A: An application is likely programmatically adding this. Do you use anything like HP iLO or Dell's DRAC? I wrote an app that used LoadKeyboardLayout to add a keyboard layout and the same symptoms appeared (it wasn't in Control Panel but it was in the language switcher).
I've noticed HP iLO plays with keyboard layouts too so that the layout reflects whatever the server is set to.


text:
Q: How to kill all incoming SSH connections? I am developing a driver to remote control a Raspberry Pi over SSH. While this connection is active the RPi displays some message on it's touchscreen. So far everything works just fine.
The Raspberry Pi runs on Raspbian 8 (jessie).
Now, I want to be able to end the SSH connection on the RPi via some button click event. As far as I know, an incoming SSH connection can be terminated by getting the corresponding process' ID and killing it. On said button click event I want to kill all incoming sessions. Is there a shell command or Python module that does that for me? Extracting all running SSH connection's process IDs seems a bit to much work.
Thanks for your help!


text:
Q: Why is this while loop an infinite loop? I want to execute the contents of a loop a maximum of 3 times and every time the program executes, I want it to generate a different number. So the first run could be 2, then 3, then 1, then 2, etc...
Here is the code I have written:
       int i = new Random().Next(3);
        while (i <= 3)
        {

            Console.WriteLine("Hello World");

            i--;
        }**

However, this ends up in an infinite loop. Can someone help me understand what I am doing wrong?
THANKS!

A: You are always decrementing the variable, so it will always be less than 3

A: i will always be less than 3... until it hits Int.MinValue - 1 (overflow).

A: Your correct way of doing it should be setting a minimum value as well as a maximum value such as below
int i = new Random().Next(3);

while (i>0 && i <= 3)
    {

        Console.WriteLine("Hello World");

        i--;
    }**

A: I think if you change the code to say 'i++' instead of 'i--' you'll get the result you were looking for.
int i = new Random().Next(3);
        while (i <= 3)
        {

            Console.WriteLine("Hello World");

            i++;
        }**


text:
Q: Deletar input selecionado de um array com condição jquery Estou com dificuldades para remover inputs selecionados de vários inputs.
Tenho o seguinte código:

$(document).ready(function() {
  var btnremoveimg = $('.remover-img');
  btnremoveimg.click(function() {
    $(this).parent().remove();
  });

});
.img {
  float: left;
  margin-left: 10px;
}
.img img {
  border: solid 1px #ccc;
  padding: 2px;
}
.img button {
  width: 126px;
}

  <input type='hidden' name='upload-img[]' value='http://lorempixel.com/output/abstract-q-c-120-120-6.jpg'>
  <input type='hidden' name='upload-img[]' value='http://lorempixel.com/output/abstract-q-c-120-120-4.jpg'>
    <input type='hidden' name='upload-img[]' value='http://lorempixel.com/output/abstract-q-c-120-120-6.jpg'>

  <button type='button' class='remover-img'>Remover Imagem</button>

  <button type='button' class='remover-img'>Remover Imagem

  <button type='button' class='remover-img'>Remover Imagem

Eu preciso que ao clicar em .Remover Imagem eu delete o input com o mesmo valor do src da imagem. Porem estou tendo dificuldades quando a isso.
Alguém conseguiria me ajudar?

A: Eu não testei, mas veja se funciona dessa maneira, só que você tem que manter o nome do arquivo diferente:
$(document).ready(function() {
  var btnremoveimg = $('.remover-img');
  btnremoveimg.click(function() {
    $(this).parent().remove();
    var valor = $(this).parent().find('img').attr('src');
     $('#list-inputs input').each(function() {
       if ($(this).val() == valor) {
           $(this).remove();
       }

     });
  });

});

Eu sugiro fazer pela ID, tipo na HTML você coloca a ID no input:

      <input type='hidden' id="img_1" name='upload-img[]' value='http://lorempixel.com/output/abstract-q-c-120-120-6.jpg'>
      <input type='hidden' id="img_2" name='upload-img[]' value='http://lorempixel.com/output/abstract-q-c-120-120-4.jpg'>
      <input type='hidden' id="img_3" name='upload-img[]' value='http://lorempixel.com/output/abstract-q-c-120-120-6.jpg'>

  <button type='button' class='remover-img'>Remover Imagem</button>

  <button type='button' class='remover-img'>Remover Imagem

  <button type='button' class='remover-img'>Remover Imagem

E no script, pega pela id:
 $(document).ready(function() {
          var btnremoveimg = $('.remover-img');
          btnremoveimg.click(function() {
          var pai = $(this).parent();
              pai.remove();
          var inputObj = pai.attr('id').replace('elm_','img_');
              $(inputObj).remove();
             });
          });
      });

A: você so precisa procurar pelo input:hidden com value igual ao source da img dentro da div.img que contem o button.remover-img clickado:

var source = document.getElementById("tmpl").innerHTML;
var template = Handlebars.compile(source);
var context = {
  imagens: [
    "http://lorempixel.com/output/abstract-q-c-120-120-1.jpg",
    "http://lorempixel.com/output/abstract-q-c-120-120-2.jpg",
    "http://lorempixel.com/output/abstract-q-c-120-120-3.jpg",
    "http://lorempixel.com/output/abstract-q-c-120-120-4.jpg",
    "http://lorempixel.com/output/abstract-q-c-120-120-5.jpg",
    "http://lorempixel.com/output/abstract-q-c-120-120-6.jpg"
  ]
}
document.body.innerHTML = template(context);

var listInputs = document.getElementById("list-inputs");
var buttons = document.querySelectorAll(".remover-img");
buttons = [].slice.apply(buttons);

var onRemoverImgClick = function () {
  var button = this;
  var container = button.parentNode;
  var imagem = button.parentNode.getElementsByTagName("img")[0];
  var hidden = listInputs.querySelector("[value='" + imagem.src + "']");

  container.parentNode.removeChild(container);
  listInputs.removeChild(hidden);
}

buttons.forEach(function (button) {
  button.addEventListener("click", onRemoverImgClick)
});
.img {
  float: left;
  margin-left: 10px;
}
.img img {
  border: solid 1px #ccc;
  padding: 2px;
}
.img button {
  width: 126px;
}


text:
Q: Blazor client-side System.Net.Http bug In my dataservice (client-side) I try to call controller API with this (the Id 36fc1b86-9697-49c5-978c-825f465de73b is hard coded to show the problem) :
return await JsonSerializer.DeserializeAsync<IEnumerable<Stage>>
(
    await _httpClient.GetStreamAsync($"api/stage/36fc1b86-9697-49c5-978c-825f465de73b"),
    new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }
 );

Server-side (API)
[HttpGet("{id}")]
public IActionResult GetAllStage(string id)
{
    return Ok(_stageRepository.GetAllStagesById(id));
}

And the error :

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Value cannot be null. (Parameter 'source')
System.ArgumentNullException: Value cannot be null. (Parameter 'source')

But if GUID starts with a letter (see below /a...) everything works #1 like this :
return await JsonSerializer.DeserializeAsync<IEnumerable<Stage>>
(
    await _httpClient.GetStreamAsync($"api/stage/a0bdb087-dadc-4382-9a28-75f93917698b"),
    new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });

Workaround.  I put a extra letter (here X) at the very begining :
return await JsonSerializer.DeserializeAsync<IEnumerable<Stage>>
    (await _httpClient.GetStreamAsync($"api/stage/X{id}"), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });

And remove it in the API...
    [HttpGet("{id}")]
    public IActionResult GetAllStage(string id)
    {
        return Ok(_stageRepository.GetAllStagesById(id.Remove(0, 1)));
    }

Any idea about this bug?

A: The clue is in

Unhandled exception rendering component: Value cannot be null. (Parameter 'source')

This means an IEnumerable is null where it shouldn't be. Since this is thrown from WebAssemblyRenderer you probably use the results in a @foreach() { <tag> </tag> }  without a null guard.
And why does it depend on the starting char of the Guid?  That has to be a problem inside GetAllStagesById().
We can't debug code that is not included.


text:
Q: Closing JFrame with a JButton Im having problem with this code , it doesn't compile . Could you help me ?
I need to close the JFrame when i click the button
public class SlotMachine extends JFrame
{
    /*
     *
     */
    JButton btnExit = new JButton("Exit");
    btnExit.addMouseListener(new MouseAdapter()
    {
        @Override
        public void mouseClicked(MouseEvent arg0)
        {
            this.dispose();
        }
    });
}

The error is = The method dispose() is undefined for the type new MouseAdapter(){}
I dont know how to get the SlotMachine object from the mouseClicked method

A: You're calling this.dispose(); the key here being that this refers to the inner class, the MouseListener, and MouseListener doesn't have a dispose() method.
Solution: get rid of this, and it should work, since the compiler will then look into the outer class if the inner class does not contain the method. Alternatively you could specify which this you mean: SlotMachine.this.dispose(); will tell the compiler to call the method of the outer SlotMachine class.
Use an ActionListener on a JButton for several reasons:

*

*Default behavior of buttons is to be activated by spacebar press if the button has focus. This will not work for a MouseListener.

*Also an expected behavior is that if the button is disabled via setEnabled(false), then pressing it should not cause the action to be fired. This does not work with MouseListener but does with ActionListener.

*You can easily share the ActionListener (or better yet, an AbstractAction) with other components including JMenuItems.


text:
Q: Use fetched API data outside of the function To make my code cleaner I want to use fetched API data in a few different functions, instead of one big. Even though I 've did manage to reffer to that data in other functions, the problem is the API im a fetching throws different, randomized results every time it is called. And so the output from userData() does not equal that from userData2(), even though my intention is different and I'd like the result variable contents to be the same between functions.
const getData = () =>
  fetch("https://opentdb.com/api.php?amount=10").then((response) =>
    response.json()
  );

const useData = async () => {
  const result = await getData();
  console.log(result);
};

const useData2 = async () => {
  const result = await getData();
  console.log(result);
};

A: Your getData() function returns a promise. One fun fact about promises is that while they can only resolve once, that resolved value can be accessed and used as many times as you want.
const dataPromise = getData();

const useData = async () => {
  const result = await dataPromise;
  console.log(result);
};

const useData2 = async () => {
  const result = await dataPromise;
  console.log(result);
};

Using await resolves the promise value, the equivalent of...
dataPromise.then((result) => {
  console.log(result);
});
// or `dataPromise.then(console.log)` if you like brevity

I like to point this out about the fetch-api... you should always check the Response.ok property
const getData = async () => {
  const res = await fetch("https://opentdb.com/api.php?amount=10");
  if (!res.ok) {
    throw new Error(`${res.status}: ${await res.text()}`);
  }
  return res.json();
};


text:
Q: CSS problem:
* will shift when I fill it with content Hej there,
I fail to create a simple list made up of list items that have background images and show some info when you click/tap on them. I can't figure out what's wrong, maybe someone can help me.
So I got this unordered list within an article:

Aktivitäten am Freitagnachmittag/-abend

Wassersport

Here be infotext

Lasertag

Here be infotext

Flußsauna

Here be infotext

Then I add the following CSS:
article {
    font-family: 'Raleway', sans-serif;
    margin: 0 auto;
    width: 80%;
    padding-top: 40px;
    padding-bottom: 40px;
}

article h1 {
    text-align: center;
    margin-bottom: 30px;
    font-size: 3rem;
}

article h2 {
    text-align: center;
    margin-bottom: 30px;
    font-size: 2rem;
}

article p {
    font-size: 1.5rem;
    margin-bottom: 1rem;
}

article ul {
    font-size: 1.5rem;
    margin-top: 20px;
    margin-bottom: 20px;
    list-style-position: inside;
}

.programList {
    list-style-position: inside;
    margin: 0 auto;
}

.programList li {
    display: inline-block;
    height: 350px;
    width: 500px;
    margin-bottom: 20px;
}

#wassersportInfo {
    display: none;
}

#flusssaunaInfo {
    display: none;
}

#lasertagInfo {
    display: none;
}

The list shows nicely - I have three images with overlayed headers that show up next to or above each other, depending on the screen size. On my screen, they show in one row.
However when I set one of the p (say, #wassersportInfo) to display: block; (manually or via JS), so that the infotext appears within the list item element, then suddenly the other list items shift down. The list items with the now visible p in it still has the same distance to the h2 above the list, but the others are displayed with some offset from the top.
I suspected it had something to do with the bottom margins I gave h1 and p elements within article elements, so I set the bottom margins of the h1 and p elements within the list items to zero by doing this:
.programList h1 {
    margin-bottom: 0px;
}

.programList p {
    margin-bottom: 0px;
}

That did something, but not all the way, there is still some offset for the list items where the display properties of the p are set to none. Anyway, I don't understand why a list item with a specified height and width shifts its (or other list items') position when you put something in it.
The problem disappears altogether when the screen width is so small that the list items are displayed above each other, but that's of course not what I want for bigger screens.
Can someone help me?

A: I'm not sure if I understand your problem correctly but if I'm wrong please correct me.
You want to have a list of items with a hidden information. After the user clicks on the item the hidden text will pop.
For this you have few option:

*

*You can try using Boostrap's accordions. Customize the header as you wish and upon clicking one you will get the result you want.

*If you want a more "custom" approach you can either use a JS library or JS itself. As a demonstration I will help you with the principle in the following code:

function toggleText(element){
    var p = document.querySelectorAll("p");
    [].forEach.call(p, function(el) {
        if(el.classList.contains("active-element"))
            el.classList.remove("active-element");
    });

  element.querySelector('p').classList.toggle("active-element");
}
article {
    font-family: 'Raleway', sans-serif;
    margin: 0 auto;
    width: 80%;
    padding-top: 40px;
    padding-bottom: 40px;
}

article h1 {
    text-align: center;
    margin-bottom: 30px;
    font-size: 3rem;
}

article h2 {
    text-align: center;
    margin-bottom: 30px;
    font-size: 2rem;
}

article p {
    font-size: 1.5rem;
    margin-bottom: 1rem;
}

article ul {
    font-size: 1.5rem;
    margin-top: 20px;
    margin-bottom: 20px;
    list-style-position: inside;
}

.programList {
    list-style-position: inside;
    margin: 0 auto;
}

.programList li {
    display: inline-block;
    height: 350px;
    width: 500px;
    margin-bottom: 20px;
}

#wassersportInfo {
    display: none;
}

#flusssaunaInfo {
    display: none;
}

#lasertagInfo {
    display: none;
}

.active-element{
display:block!important;
}

Aktivitäten am Freitagnachmittag/-abend

Wassersport

Here be infotext

Lasertag

Here be infotext

Flußsauna

Here be infotext

Please let me know if this covers your question.


text:
Q: Silverlight WebContext is shared between mutipale sessions I have a silverlight Ria application . I use the WebContext to make the authentication staff.
I have these line in the App.cs constructor (it already come with the silverlight business teplate) :
 InitializeComponent();
WebContext webContext = new WebContext();
 webContext.Authentication = new FormsWithTimeoutAuthentication(20);
this.ApplicationLifetimeObjects.Add(webContext);
I face a problem , when I open the application in one browser tab , every thing is ok , I try to open another tab and to log in with different user it affect the application in the first tab .
I traced the WebContext hashcode and get the same thing. So the WebContext seems to be shared on the both application instances.
Do you have any idea why this happen ?
Thanks in advance ...

A: Silverlight uses the browser's http stack for authentication. When you use Forms Authentication, a browser cookie is sent to the browser and this identifies your current browser session's authenticated user. All browser tabs share the same cookie, and hence all tabs are identified as the same user.
To avoid this issue, you should use "Private Browsing" on Internet Explorer, or use "Incognito" on Google Chrome.


text:
Q: Use of threads with fragments Hi I have just started developping in android so I'am not  an expert. My question is:
I am creating an application with two fragments , both the fragments have to retrive data from a service in real-time. (In particular on fragment has to draw a plot using the data read and the other has to make move an avatar with the data read, all of this in real-time).My doubt is: do I have to use two threads, one for each fragments, or I can do this with just a thread ?
thanks for your answers and please let me know if my question is not clear.

A: The best option you can do is to learn first how to properly use certain libraries that may help you to do what you have described (as always, things related to Networking are not an easy or a trivial part in an application).
I propose you to read some things related that may be helpful:

*

*Android Developer Documentation about Threads and Processes

*Best Practices for Consuming Apis on Android

*Durable Android Rest Clients
The last link presents you a great workflow on how to do several parts when dealing with Networking and Intercommunication (like using a Bus). It's related to consuming restful services but much applies to other kind of data.
Libraries like Android Priority JobQueue made by Yigit at Path helps you when dealing with background operations.
If you need more concrete answers please specify more what you want to do and I would gladly help you! :)


text:
Q: Python combo chart add the percentage on the bar but wrong I tried to add the percentage on the bar in combo chart, line and column graphs.
However, all the values displayed are messy.
I provide the data here, this is also my previous post and the answer is provided by Quang Hoang.
Group   yq        Value1    Value2
G       2014Q1     0.07        1.1
G       2014Q2     0.06        1.09
G       2014Q3     0.09        1.11
G       2014Q4     0.04        1.13
I       2014Q1     0.10        1.2
I       2014Q2     0.13        1.25
I       2014Q3     0.15        1.23
I       2014Q4     0.18        1.4

I provided the code I tried:
fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(ax1.get_xticks(), rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((min(dataset['Value2']) - 0.05, max(dataset['Value2']) + 0.05))
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)
ax2.set_yticklabels(['{:.1f}%'.format(a*100) for a in ax2.get_yticks()])
ax2.set_ylabel("")
for index, row in dataset.iterrows():
    ax2.text(row.name,row['Value1'], '{:.1f}%'.format(round(row['Value1'],2)), color='black')
plt.show()

The percentages showing on the plot are messy and do not place properly on each bar and group.
I searched on here and here but I cannot solve it.
Any solution?
I provide my result:

I also provide the correct resulting image created by R's package ggplot2.
There are two packages similar to ggplot2 in Python, plotnine and ggplot. However, I cannot use it in my Python.

I provide my R code as your reference if it helps:
library(data.table)
library(ggplot2)
library(zoo)
dataset <- fread("Group   yq        Value1    Value2
G       2014/1/1     0.07        1.1
G       2014/4/1     0.06        1.09
G       2014/7/1     0.09        1.11
G       2014/10/1     0.04        1.13
I       2014/1/1     0.10        1.2
I       2014/4/1     0.13        1.25
I       2014/7/1     0.15        1.23
I       2014/10/1     0.18        1.4", header = T)
dataset$yq <- as.Date(dataset$yq)
dataset[, yq := as.yearqtr(dataset$yq, format = "%Y-%m-%d")]

ggplot(data = dataset, aes(x = yq, colour = Group, fill = Group,
                           label = scales::percent(Value1, accuracy = 0.1))) +
  geom_col(aes(y = sec_axis_mult * Value1), position = position_dodge2(width = 0)) +
  geom_line(aes(y = Value2)) +
  scale_colour_manual(values = c("red", "darkblue"), labels = c("G", "I")) +
  scale_fill_manual(values = c("red", "darkblue"), labels = NULL, breaks = NULL) +
  scale_x_yearqtr(format = "%YQ%q", breaks = unique(dataset$yq)) +
  scale_y_continuous(name = "Value2",
                     sec.axis = sec_axis(~./sec_axis_mult, name = "Value1",
                                         labels = scales::percent)) +
  theme_bw() +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        axis.title.y.right = element_blank(),
        axis.ticks.x=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.x=element_text(angle = 45, size = 12, vjust = 0.5, face = "bold"),
        axis.text.y=element_blank(),
        axis.line = element_line(colour = "white"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank(),
        plot.background=element_blank(),
        legend.position="left",
        legend.title=element_blank(),
        legend.text = element_text(size = 16, face = "bold"),
        legend.key = element_blank(),
        legend.box.background =  element_blank()) +
  guides(colour = guide_legend(override.aes = list(shape = 15, size = 10))) +
  geom_text(data = dataset, aes(y = sec_axis_mult * Value1, colour = Group),
            position = position_dodge(width = 0.25),
            vjust = -0.3, size = 4)

A: What I'm doing is dynamically labeling the bar graphs based on the coordinates for each patch that's drawn by the bar function.
fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(ax1.get_xticks(), rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((min(dataset['Value2']) - 0.05, max(dataset['Value2']) + 0.05))
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)
ax2.set_yticklabels(['{:.1f}%'.format(a*100) for a in ax2.get_yticks()])
ax2.set_ylabel("")
#iterate through each group of bars
for group in ax2.containers:
    for bar in group:
        #label the bar graphs based on the coordinates of the bar patches
        ax2.text(
            bar.get_xy()[0]+bar.get_width()/2,
            bar.get_height(),
            '{:.1f}%'.format(round(100*bar.get_height(),2)),
            color='black',
            horizontalalignment='center'
        )

Output:

I've adjusted the code to more closely match the desired output that's been added to the original question.
fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twiny().twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(dataset['yq'], rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((0, max(dataset['Value2']) + 0.05))
ax2.set_ylim(0, max(dataset['Value2']) + 0.05)
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)

#iterate through each group of bars
for group in ax2.containers:
    for bar in group:
        #label the bar graphs based on the coordinates of the bar patches
        ax2.text(
            bar.get_xy()[0]+bar.get_width()/2,
            bar.get_height(),
            '{:.1f}%'.format(100*bar.get_height()),
            color='black',
            horizontalalignment='center'
        )

ax1.yaxis.set_visible(False)
ax2.yaxis.set_visible(False)
ax2.xaxis.set_visible(False)

Outputs:


text:
Q: Python using matplotlib and numpy I want to share a Python3.3 tool, which for development convenience is split in variuos files/modules; these modules use tkinter, numpy-1.7.0rc1 and matplotlib-1.2.0.
My questions is:
is there a way to assemble these files/modules into a single self-standing executable file/script, freeing the not skilled user from installing tkinter, numpy and matplotlib, but only having the python3.3 interpreter installed (default in Ubuntu 13)?

A: You probably want to use a freezer like:

*

*PyInstaller

*cx_Freeze
Both are multi-platform (I do however only Windows, which should be the hardest target for freezing). Im my opinion PyInstaller is more complete/more actively developed in regard to packages with binary/data file dependencies but is rather non-standard if your own package contains data/binaries (write .spec files or hook files). cx_Freeze on the other hand is more standard (write a setup script based on setuptools).
As far as I experienced, both handle the nasty parts of matplotlib and its dependencies well and out of the box (pytz could be hairy on cx_Freeze).

A: include a python requirement file which contains the versions of the packages or the minimal version of it.
see https://pythonhosted.org/setuptools/setuptools.html


text:
Q: Revert all files with a specified name Hi i want to revert all changes to the files with a specific filename in a local repository.
In this case AssemblyInfo.vb, i'm using the TortoiseSVN cli.
I have the following directory structure

*

*Root

*

*Project 1

*

*File1.txt

*My Project

*

*AssemblyInfo.vb

*Project 2

*

*File2.txt

*My Project

*

*AssemblyInfo.vb

Now while standing in Root i run the command svn.exe revert --recursive AssemblyInfo.vb and the output i get is:
Skipped 'AssemblyInfo.vb'
I have tried to add double and single * before the filename with no success, does --recursive/-R work or what am i missing?
svn help revert gives the following output:
revert: Restore pristine working copy state (undo local changes).
usage: revert PATH...

  Revert changes in the working copy at or within PATH, and remove
  conflict markers as well, if any.

  This subcommand does not revert already committed changes.
  For information about undoing already committed changes, search
  the output of 'svn help merge' for 'undo'.

Valid options:
  --targets ARG            : pass contents of file ARG as additional args
  -R [--recursive]         : descend recursively, same as --depth=infinity
  --depth ARG              : limit operation by depth ARG ('empty', 'files',
                             'immediates', or 'infinity')
  -q [--quiet]             : print nothing, or only summary information
  --changelist [--cl] ARG  : operate only on members of changelist ARG

Global options:
  --username ARG           : specify a username ARG
  --password ARG           : specify a password ARG (caution: on many operating
                             systems, other users will be able to see this)
  --no-auth-cache          : do not cache authentication tokens
  --non-interactive        : do no interactive prompting (default is to prompt
                             only if standard input is a terminal device)
  --force-interactive      : do interactive prompting even if standard input
                             is not a terminal device
  --trust-server-cert      : deprecated; same as
                             --trust-server-cert-failures=unknown-ca
  --trust-server-cert-failures ARG : with --non-interactive, accept SSL server
                             certificates with failures; ARG is comma-separated
                             list of 'unknown-ca' (Unknown Authority),
                             'cn-mismatch' (Hostname mismatch), 'expired'
                             (Expired certificate), 'not-yet-valid' (Not yet
                             valid certificate) and 'other' (all other not
                             separately classified certificate errors).
  --config-dir ARG         : read user configuration files from directory ARG
  --config-option ARG      : set user configuration option in the format:
                                 FILE:SECTION:OPTION=[VALUE]
                             For example:
                                 servers:global:http-library=serf

If i run svn.exe revert --recursive AssemblyInfo.vb in a directory that directly contains a modified AssemblyInfo.vb it works as intended.

A: On Linux this can be done using combination of find and xargs commands from findutils:
find -name AssemblyInfo.vb | xargs svn revert

On Windows you can probably install and use Cygwin which contain these utilities.

A: svn revert is designed to help fix mistakes, not cause problems by "helping" users to accidentally or unintentionally remove their local and uncommitted changes.
If you want to revert all the changes in your SVN working copy or in a directory and all its childs, you could run svn revert . -R. But you must not run this command if your working copy has a mixture of valid uncommitted changes that you don't want to lose and the changes that you want to revert to unmodified state.
Reverting local changes is an irreversible operation. Therefore, reverting local changes in SVN working copy via svn revert must be done cautiously. Assume that you are working on a task and haven't yet committed some important changes you've been working on a couple of hours. But at the same time you have some changes in a file or directory that you want to revert. Carelessly running svn revert . -R at the root of working copy will revert all the uncommitted changes in the working copy.
Citing SVNBook | svn revert

svn revert is inherently dangerous, since its entire purpose is to
  throw away data—namely, your uncommitted changes. Once you've
  reverted, Subversion provides no way to get back those uncommitted
  changes.
If you provide no targets to svn revert, it will do nothing. To
  protect you from accidentally losing changes in your working copy, svn  revert requires you to explicitly provide at least one target.

Now while standing in Root i run the command svn.exe revert
  --recursive AssemblyInfo.vb and the output i get is:

svn revert does not work this way. By default, it runs with --depth=empty to ensure that it won't revert more than the user intended. But runningsvn revert with -R is the same as running it with --depth=infinity. Generally speaking, in this particular case --recursive is an alias for --depth=infinity and its purpose is to help users revert all the local modifications (e.g. after invalid merge).
When you  run svn revert with --recursive, the tool expects you to specify a path to a directory in your working copy and the operation will revert ALL the changes that are in this directory and its childs. There will be no effect if the command's target is a file.
What you look for is --targets and a bit of scripting. For example, run the following commands in PowerShell console (I'm sure that it could be done more elegantly in PowerShell than in this example):
(dir -Path "files.html" -Recurse -File).FullName | Out-File -Encoding ASCII mytargets.txt
svn revert --targets mytargets.txt

dir is an alias of Get-ChildItem cmdlet in PowerShell. In this case it grabs the list of all files with name files.html and writes the full paths to mytargets.txt file. Then it runs svn revert that reads paths from mytargets.txt and revert local modifications made to the files.
I advise this approach instead of piping the output to svn revert because you can (and should) review the list of items that svn revert will process. This helps you ensure that you won't revert more that you actually intended.


text:
Q: autodesk forge viewer.js update from 6.5.1 to 6.6 or 7.1, 2d hyperlink promise exception change view from 3d to 2d view.
In 6.5.1
 viewer.load(document.getViewablePath(Views2D));
 no exception
In 6.6
 viewer.load(document.getViewablePath(Views2D));
//promise exception in chrome console
In 7.1
 viewer.loadModel(document.getViewablePath(Views2D), {});
//promise exception in chrome console

    Uncaught (in promise)
    {instanceTree: null, maxTreeDepth: 0, err: undefined}
    Promise.then (async)
    loadHyperlinks  @   HyperlinkTool.js:323
    activate    @   HyperlinkTool.js:123
    activateTool    @   ToolController.js:265
    f.load  @   Hyperlink.js:42
    loadExtensionLocal  @   ExtensionManager.js:270
    loadExtension   @   ExtensionManager.js:213
    (anonymous) @   ExtensionManager.js:312
    o.onload    @   globals.js:183
    load (async)
    u   @   globals.js:185
    (anonymous) @   ExtensionManager.js:310
    loadExtensionAsync  @   ExtensionManager.js:309
    loadExtension   @   ExtensionManager.js:205
    (anonymous) @   GuiViewer3D.js:412
    setTimeout (async)
    D.createUI  @   GuiViewer3D.js:406
    (anonymous) @   GuiViewer3D.js:300
    (anonymous) @   GuiViewer3D.js:288
    setTimeout (async)
    (anonymous) @   GuiViewer3D.js:316
    (anonymous) @   Viewer3D.js:1228
    (anonymous) @   F2DLoader.js:420

A: Engineering is still taking time to address this issue.
While we wait for their fix we can work around this issue by disabling the hyperlink extension in our load options:
new Autodesk.Viewing.Private.GuiViewer3D(...),{disabledExtensions:{hyperlink:true}}


text:
Q: GET api with Retrofit I have a web service link which I want to hit with different customerId in the form of
 http://apidev.myserver.com.au:8980/TestService/rest/TestService/jobs/bycustid/customerId

how do I append the value of customerId?
this is my base URL :
 http://apidev.myserver.com.au:8980/TestService/rest/TestService/

this is what my interface for calls look like :
interface CustomerJobs {
    @GET("jobs/bycustid/11726")
    Call<CustomerJobsPojo> getCustomerJobs();
}

A: As the doc says :
interface CustomerJobs {

    @GET("jobs/bycustid/{id}")
    Call<CustomerJobsPojo> getCustomerJobs(@Path("id") int id);

}

A: Try @Path annotation
interface CustomerJobs {
    @GET("jobs/bycustid/{id}")
    Call<CustomerJobsPojo> getCustomerJobs(@Path("id") String id);
}

A: You can embed like
@GET("jobs/bycustid/{custId}")
     Call<CustomerJobsPojo> groupList(@Path("custId") int custId);

A: Yes you can use dynamic urls
interface CustomerJobs {

    @GET("jobs/bycustid/{customerid}")
    Call<CustomerJobsPojo> getCustomerJobs(@Path("id") int customerid);

}

Refer this


text:
Q: WIF Sessions and Case-Sensitivity I'm getting behavior from my WIF web application that I don't yet understand. When I call the app, the standard interaction happens:

*

*call app (https://localhost/MyApp1/)

*app redirects the browser to my STS (in this case ADFS 2.0)

*user authenticates to the STS

*STS sends token to my app

*session cookie is created in my app for the WIF session

From then on, if I navigate to https://localhost/MyApp1/[anything], all is good and I see that my WIF session is being used.
However, if I navigate to the app with different casing for the URL, like https://localhost/myapp1/[anything], the WIF session is not recognized and I see a redirect back to the STS for authentication.
I have 2 questions:

*

*What am I missing? Is it case-sensitivity of the cookies? Is it WIF configuration?

*What is the solution? Put a  rule into my web.config? Is there a way to make my solution not case-sensitive?

Thanks.

A: I think this is your problem:
http://brockallen.com/2013/02/08/beware-wif-session-authentication-module-sam-redirects-and-webapi-services-in-the-same-application/
The real answer is that URLs are case-sensitive :/


text:
Q: Updating a db table based on 2 separate conditions I need to update my table (dependency) and set a new column (vid) to the nextval of a sequence. I can't change the way data is in the table so please don't mention removing redundant data.
However, the where condition is the issue as 2 conditions need to be met (the cols provid and origid). There is a separate primary key (prikey). The table looks like this:-
Table dependency (
  varchar prikey(46),
  varchar provid(46),
  varchar origid(46)
  varchar otherdata(16)
  vid integer
)

Sample Data would look like this:-
(prikey, ORIGID, PROVID, VID)
('AA1', 'C3C87F000001', '23', 1),
('AA2', 'C3C87F000001', '23', 1),
('AA3', 'C3C87F000001', '26', 2),
('AA4', 'C3C87F000001', '53', 3)
('AA5', 'A3C87F000009', '26', 4),
('AA6', 'A3C87F000009', '23', 5)

As can be seen from the data, the prikey is unique, the origid and provid (which are actually Foreign Keys) may repeat. For the sake of this example, I have added in the vid values as they should be. A vid basically identifies a row which has the same origid and provid.
My Question:- what is the sql like for updating this table setting vid = sequence.nextval where origid and distinct(provid)?

A: Try:
merge into dependency
USING (SELECT DENSE_RANK() OVER (ORDER BY prikey, ORIGID, PROVID) g, prikey rid FROM dependency) SOURCE
ON (dependency.prikey = SOURCE.prikey)
WHEN MATCHED THEN UPDATE SET dependency.vid = SOURCE.g


text:
Q: Delete 2d subarray from 3d array in numpy In numpy I have a 3d array and I would ike to remove some of the 2d subarrays. Think about it like this:
r = range(27)
arr = np.reshape(r, (3,3,3))

del = [[0,1,2],[0,0,2]]
flatSeam = np.ravel_multi_index(del, arr.shape)
arr = np.delete(arr, flatSeam)

So at the end I would like to have an array of the shape (3,2,3) without the elements 00, 10, 22 from the original array. My problem is that I acn not use ravel_multi_index for this, because my indices are 2d and the array shape is 3d, so the wrong indices are calculated (the code above also does not execute because the indices array and the shape have to be the same size).
Do you have any ideas how I can achieve this?

A: Here's an approach using advanced-indexing -
# arr: Input array, rm_idx : 2-row list/array of indices to be removed
m,n,p = arr.shape
mask = np.asarray(rm_idx[1])[:,None] != np.arange(n)
out = arr[np.arange(m)[:,None],np.where(mask)[1].reshape(m,-1)]

Alternatively, with boolean-indexing -
out = arr.reshape(-1,p)[mask.ravel()].reshape(m,-1,p)

A bit less memory-intensive approach as we try to avoid creating 2D mask -
vmask = ~np.in1d(np.arange(m*n),rm_idx[1] + n*np.arange(m))
out = arr.reshape(-1,p)[vmask].reshape(m,-1,p)


text:
Q: Unable to automate gmail login using selenium, Asking to enter code after email id input I am getting the following screen to enter code while login into my google account.
Login to dropbox using gmail

Login to accounts.google.com

How can we eliminate this screen while automating this page. Do we have any other suggestion to automate this page.

A: This is the exactly purpose of this.
Google doesn't want you to automate this process for good reasons.

A: This usesd to be able to be done through signing in at stackoverflow and redirecting to gmail account directly.  It seems like it is no longer supported in a session started by Selenium.


text:
Q: Convert the language of the page Does anyone have an idea why my code is not working? I get English strings everywhere.
Note that is not an ASP.NET project but an actual WinForms project.
I have set up a windows forms project to use localization so that it will support Arabic and English languages.
 Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

        Admin admin = new Admin();
        this.Close();
        admin.Show();

 Thread.CurrentThread.CurrentUICulture = new CultureInfo("ar-KW");

        Admin admin = new Admin();
        this.Close();
        admin.Show();

and I try this ;
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
        this.Controls.Clear();
        this.RightToLeftLayout = false;
        InitializeComponent();
        Properties.Settings.Default["lang"] = "en-US";
        Properties.Settings.Default.Save();

            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ar-KW");
        this.Controls.Clear();
        InitializeComponent();
        Properties.Settings.Default["lang"] = "ar-KW";
        Properties.Settings.Default.Save();

It works when I test it by starting to debug
but when I set up the application it stops working.

A: If your application works in debug mode and you can switch languages, then check the "bin\debug" folder and copy/deploy the language folder "ar" or "ar-KW" along with your EXE file on other machines
Go to your debug folder and copy everything including all folders (except the .pdb) files to your target machine.


text:
Q: Slim 3 Middleware Redirect I want to check if a user is logged in. Therefor I have an Class witch returns true or false. Now I want a middleware which checks if the user is logged in.
$app->get('/login', '\Controller\AccountController:loginGet')->add(Auth::class)->setName('login');
$app->post('/login', '\Controller\AccountController:loginPost')->add(Auth::class);

Auth Class
class Auth {
    protected $ci;
    private $account;

    //Constructor
    public function __construct(ContainerInterface $ci) {
        $this->ci = $ci;
        $this->account = new \Account($this->ci);
    }

    public function __invoke($request, \Slim\Http\Response $response, $next) {
        if($this->account->login_check()) {
            $response = $next($request, $response);
            return $response;
        } else {
            //Redirect to Homepage
        }

    }
}

So when the user is logged in the page will render correctly. But when the user is not autoriesed I want to redirect to the homepage. But how?!
$response->withRedirect($router->pathFor('home');

This doesn't work!

A: Building off of tflight's answer, you will need to do the following to make everything work as intended. I tried to submit this as a revision, given that the code provided in tflight's answer would not work on the framework out of the box, but it was declined, so providing it in a separate answer:
You will need the following addition to your middleware:
protected $router;

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

Additionally, when declaring the middleware, you would need to add the following the constructor:
$app->getContainer()->get('router')

Something similar to:
$app->add(new YourMiddleware($app->getContainer()->get('router')));

Without these changes, the solution will not work and you will get an error that $this->router does not exist.
With those changes in place you can then utilize the code provided by tflight
$uri = $request->getUri()->withPath($this->router->pathFor('home'));
return $response = $response->withRedirect($uri, 403);

A: You need to return the response. Don't forget that the request and response objects are immutable.
return $response = $response->withRedirect(...);

I have a similar auth middleware and this is how I do it which also adds a 403 (unauthorized) header.
$uri = $request->getUri()->withPath($this->router->pathFor('home'));
return $response = $response->withRedirect($uri, 403);

A: make basic Middleware and inject $container into it so all your middleware can extends it.
Class Middleware
{
  protected $container;

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

  public function __get($property)
  {
    if (isset($this->container->{$property})) {
      return $this->container->{$property};
    }
    // error
  }
}

make sure your Auth middleware on the same folder with basic middleware or you can use namespacing.
class Auth extends Middleware
{
  public function __invoke($request, $response, $next)
  {
    if (!$this->account->login_check()) {
      return $response->withRedirect($this->router->pathFor('home'));
    }

    return $next($request, $response);
  }
}

A: Use:
http_response_code(303);
header('Location: ' . $url);
exit;


text:
Q: Lightbox popup on WooCommerce add_to_cart action I would like to create a modal 'pop-up' window in WooCommerce to appear when the "Add to cart" button has been clicked. This has to occur after the WC actions that actually add the product to the cart but before/instead of any redirects.
I have found several likely/possible hooks, actions and filters which may be useful to me but I am unsure which I need and how to use them properly (sorry I'm a total WooCom n00b):

*

*woocommerce_template_loop_add_to_cart

*woocommerce_template_single_add_to_cart

*woocommerce_after_add_to_cart_button

*there's also the add_to_cart_redirect filter for $url
I am also not sure how to actually trigger the lightbox to appear from within PHP! (Okay in HTML I use an element like a hyperlink which has to be clicked, but how to trigger the same thing at a certain point in the PHP execution? -- Do I need AJAX?)
Lastly I was planning to use ThickBox as it is bundled with WordPress, is there any reason to avoid this and or a better option available, or is there a lightbox implementation bundled with WooCommerce?
Kind thanks for any and all help!

A: The following works for me for product archive pages (these include both the main shop page as well as archive pages for product categories, for example).
It will show the current cart contents in a thickbox. I chose to show this for this example just because that's the data that one gets back through Ajax after clicking the add-to-cart button, but you may want a different kind of info in your box. You can get the product_id of the product just added, for example, by looking at surrounding html elements.
In your theme's functions.php (or in the class definition for the theme, if you have one) there's probably some 'enqueue_scripts' function. You should add this to this function to ensure the thickbox script is loaded.
if (is_woocommerce() && is_archive()) {
    wp_enqueue_script( 'frontend-custom', get_template_directory_uri() . '/js/frontend-custom.js', array("jquery"));
    add_thickbox();
}

In a file (in your theme directory) js/frontend-custom.js (or wherever you have your theme's js):
jQuery(document).ready(function($) {
    $('body').on('added_to_cart',function(e,data) {
        //alert('Added ' + data['div.widget_shopping_cart_content']);
        if ($('#hidden_cart').length == 0) { //add cart contents only once
            //$('.added_to_cart').after('View my inline content!');
            $(this).append('');
            $(this).append('
'+data['div.widget_shopping_cart_content']+'
');
        }
        $('#show_hidden_cart').click();
    });
});

Some additional notes:

*

*I suppose you can also output javascript directly into the page from php. In this case, I think you probably want to hook with     add_action('woocommerce_ajax_added_to_cart', 'myfunction');
This action is run inside woocommerce_ajax_add_to_cart() right after adding an item to the cart (passing validation, etc), but before redirecting.

*The single product pages do not work in the same way ('add to cart' is there a normal php form, no ajax is involved).

*I haven't tested this, but WooCommerce comes with its own 'prettyphoto.js', which works by adding 'rel="prettyPhoto"' to an href link, pretty much as the thickbox class works in the above example. You might want to give it a try to keep design consistency with WooCommerce.


text:
Q: Is XPath suitable for HTML5 format? We know that XPath is created for XML parsing. What about HTML5 since it doesn't necessarily respect XML rules?

A: There are 2 XMLs: Lexical XML and Parsed XML. XPath works against a Parsed XML representation, such as DOM or XDM. You can therefore create Parsed XML from Lexical HTML5, that way you can query HTML5 using XPath.

A: You can with the huge caveat that you probably shouldn't unless you have too.
Take the following HTML:

 Here is a paragraph

 Here is another, is it inside the first, who knows?

Now most HTML parsers will accept that the above means this:

 Here is a paragraph

 And another, is it inside the first, who knows?

Now, the XPath /div/p[2] should return "And another..." however, it could equally be interpretted as:

 Here is a paragraph

 And another, is it inside the first, who knows?

Where /div/p[2] returns nothing and the XPath /div/p/p returns "And another..." .
HTML isn't XML and doesn't need to be well-formed, so using XML technologies with HTML can lead to idiosyncracies. So as long as you acknowledge those you should be ok.

A: XPath is for querying a DOM, not parsing markup. A DOM can be generated from an HTML document, so you can query it with XPath.


text:
Q: java void functional programming, tight coupling and boilerplate When target Objects excelColumns, pdfColumns partly share same Objects and some of them even conditionally, what is a good OOP pattern to void functional programming, tight coupling and boilerplate like in code below? Lets assume, that there will be a lot of shared columns and only few non shared and conditional ones.
    List<Column> excelColumns = new ArrayList<>();
    List<Column> pdfColumns = new ArrayList<>();

    //shared columns
    Column test = new Column("test", 121, 11);
    excelColumns.add(test);
    pdfColumns.add(test);

    //conditional columns
    if (condition) {
        excelColumns.add(new Column("test2", 12, 21));
    }

    //non shared columns
    pdfColumns.add(new Column("test3", 12, 41));

    //shared columns
    Column test4 = new Column("test4", 12, 331);
    excelColumns.add(test4);
    pdfColumns.add(test4);
    Column test5 = new Column("test5", 72, 11);
    excelColumns.add(test5);
    pdfColumns.add(test5);
    Column test6 = new Column("test6", 82, 121);
    excelColumns.add(test6);
    pdfColumns.add(test6);

A: You can use addAll(...) method instead add(...) for the last shared columns section to add them all for every collection. If you goal is to maintain a conditional order of inserting next columns, there is no point to obfuscate it, because here it is clearly presented.

A: Depending on your appetite for complexity, you can do the following:

*

*Try to group related columns instances into objects like HeaderColumns, BodyColumns, etc.

*Implement the visitor pattern as described here.

Here is a possible implementation of the pattern following the suggestions above:
public class Main {

    interface Visitor {
        void visit(ReportHeader header);

        void visit(ReportBody body);
    }

    interface Visitable {
        void accept(Visitor visitor);
    }

    static class ReportHeader implements Visitable {

        private final List<String> columns = new ArrayList<>();
        private final List<String> extras = new ArrayList<>();

        @Override
        public void accept(Visitor visitor) { visitor.visit(this); }

        public List<String> getColumns() { return columns; }

        public List<String> getExtras() { return extras; }
    }

    static class ReportBody implements Visitable {

        private final List<String> columns = new ArrayList<>();

        @Override
        public void accept(Visitor visitor) { visitor.visit(this); }

        public List<String> getColumns() { return columns; }
    }

    static class ExcelReportVisitor implements Visitor {

        private final List<String> columns = new ArrayList<>();

        @Override
        public void visit(ReportHeader header) {
            columns.addAll(header.getColumns());
            columns.addAll(header.getExtras());
        }

        @Override
        public void visit(ReportBody body) { columns.addAll(body.getColumns()); }
    }

    static class PdfReportVisitor implements Visitor {

        private final List<String> columns = new ArrayList<>();

        @Override
        public void visit(ReportHeader header) {
            columns.addAll(header.getColumns());
            // no extras for PDF
        }

        @Override
        public void visit(ReportBody body) { columns.addAll(body.getColumns()); }
    }
}

You could use it as follows:
public static void main(String args[]) {
    ReportHeader header = new ReportHeader();
    ReportBody body = new ReportBody();

    List<Visitor> visitors = Arrays.asList(new PdfReportVisitor(), new ExcelReportVisitor());
    visitors.forEach(each -> {
        each.visit(header);
        each.visit(body);
    });

    // do something with the visitors like `visitor.exportReport()`
}

Advantages of this approach:

*

*Every time you have to add a new report section to Visitor, it will generate a compile error in all visitor implementations. That avoids typical programming mistakes where people forget to add branches to if or switch statements.

*The conditional logic on how to build the report is placed in the actual implementation of the report. No need for conditional anymore.

Disadvantages of this approach:

*

*For sure the complexity given the additional abstractions you will be required to create.

*Sometimes it might not make sense or possible to encapsulate/group your Column instances into semantically cohesive objects. For example, you might end with weirdness in ReportHeader like this:

static class ReportHeader implements Visitable {

    private final List<String> columns = new ArrayList<>();
    private final List<String> extras = new ArrayList<>();
    private final List<String> dataThatIsOnlyUsedByExcelReport = new ArrayList<>();

    @Override
    public void accept(Visitor visitor) { visitor.visit(this); }

    public List<String> getColumns() { return columns; }

    public List<String> getExtras() { return extras; }

    public List<String> getDataThatIsOnlyUsedByExcelReport() { return dataThatIsOnlyUsedByExcelReport; }
}


text:
Q: Fgets - doesn't work in the loop The problem is that fgets doesn't take any value in the first iteration of the loop. Just simply skips it. As I see it. I get there is some basic mistake in my code, but I don't see it. Fgets starts taking values only on 2d iteration.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main(void)
{
    int t;
    scanf("%i", &t);

    char ways[100];
    for (int j = 0; j <= t; t++)
    {
        fgets (ways, 100, stdin);
        printf("Ways = %s\n", ways);
    }

    return 0;
 }`

A: The easiest way to fix your problem is to use fgets() and sscanf() to read the initial number. Also, it appears that your loop has a couple of errors. You probably meant j < t instead of j <= t, so that the loop executes t times. Also, you almost certainly meant to increment j instead of t, which would lead to an infinite loop.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main(void)
{
    int t;
    char buffer[100];
    fgets(buffer, 100, stdin);
    sscanf(buffer, "%i", &t);

    char ways[100];
    for (int j = 0; j < t; j++)
    {
        fgets (ways, 100, stdin);
        printf("Ways = %s\n", ways);
    }

    return 0;
 }

Note that it is generally a bad idea to add a white-space character to the end of a format string, as this causes scanf() to continue trying to read input until a non-white-space character is encountered, blocking the input.

A: scanf() is reading the digits the uder entered, and leaving his trailing spaces and newline in the buffer. fgets() then reads these and so appears to read an empty string on the first iteration.
To fix add a whitespace character after the %i. Whitespace matches whitespace with scanf.


text:
Q: numpy efficient way of calculating diagonal subtractions without loops I have the below 2d numpy array:
array([[5, 2, 6],
       [4, 5, 6],
       [7, 12, 3]])

I have a (gradient) equation that uses diagonals to perform a calculation like below:
(array[i , j] - array[i + 1, j + 1]) **2 + (array[i+1 , j] - array[i, j + 1]) **2

The equation is very simple. It is getting each  2x2 sub matrix, subtracting the diagonals, squaring them and then adding each result. In the example used above for the first 2x2 matrix the equation would yield:
(5 - 5) ^ 2 + (4 - 2) ^ 2 = 4

This value would then be the first element a new numpy array. And the rest of the elements would be populated the same way by moving on to the next 2x2 submatrix.
The first obvious solution to this is to use a nested for loop over all rows and columns. But is there a more efficient way using numpy (or other libraries) to avoid the for loops. Or if not avoiding the for loops directly, making the calculation more efficient for larger 2D arrays.

A: Here's a few ideas:
import numpy as np
from scipy.signal import convolve2d
from numba import njit, prange

arr0 = np.array(
    [[5, 2, 6],
     [4, 5, 6],
     [7, 12, 3]])

np.random.seed(0)
arr1 = np.random.randint(0, 20, (20, 20))

def weird_quazi_det_op(arr):
    H, W = arr.shape
    out_arr = np.zeros((H-1, W-1))
    for h in prange(H-1):
        for w in prange(W-1):
            out_arr[h, w] = (arr[h, w] - arr[h+1, w+1])**2 + (arr[h+1, w] - arr[h, w+1])**2
    return out_arr

@njit(parallel=True)
def weird_quazi_det_patallel(arr):
    H, W = arr.shape
    out_arr = np.zeros((H-1, W-1))
    for h in prange(H-1):
        for w in prange(W-1):
            out_arr[h, w] = (arr[h, w] - arr[h+1, w+1])**2 + (arr[h+1, w] - arr[h, w+1])**2
    return out_arr

@njit(fastmath=True)
def weird_quazi_det_fastmath(arr):
    H, W = arr.shape
    out_arr = np.zeros((H-1, W-1))
    for h in prange(H-1):
        for w in prange(W-1):
            out_arr[h, w] = (arr[h, w] - arr[h+1, w+1])**2 + (arr[h+1, w] - arr[h, w+1])**2
    return out_arr

def weird_quazi_det_conv(arr):
    sub0kern = np.array([[1, 0,], [0, -1]])
    sub1kern = np.array([[0, -1,], [1, 0]])

    sub0arr = convolve2d(arr, sub0kern, mode = 'valid')
    sub1arr = convolve2d(arr, sub1kern, mode = 'valid')

    out_arr = sub0arr**2+sub1arr**2
    return out_arr

# init runs
weird_quazi_det_patallel(arr0)
weird_quazi_det_fastmath(arr0)

print('===== op example: =====')
print(' - op code:')
%timeit weird_quazi_det_op(arr0)
print(' - op code + parallel:')
%timeit weird_quazi_det_patallel(arr0)
print(' - op code + fastmath:')
%timeit weird_quazi_det_fastmath(arr0)
print(' - conv solution:')
%timeit weird_quazi_det_conv(arr0)

print('===== larger example: =====')
print(' - op code:')
%timeit weird_quazi_det_op(arr1)
print(' - op code + parallel:')
%timeit weird_quazi_det_patallel(arr1)
print(' - op code + fastmath:')
%timeit weird_quazi_det_fastmath(arr1)
print(' - conv solution:')
%timeit weird_quazi_det_conv(arr1)

output:
===== op example: =====
 - op code:
The slowest run took 6.15 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 5: 10.6 µs per loop
 - op code + parallel:
The slowest run took 251.69 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 5: 5.71 µs per loop
 - op code + fastmath:
The slowest run took 32.22 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 5: 678 ns per loop
 - conv solution:
The slowest run took 6.65 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 5: 18.7 µs per loop
===== larger example: =====
 - op code:
1000 loops, best of 5: 714 µs per loop
 - op code + parallel:
The slowest run took 180.35 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 5: 6.33 µs per loop
 - op code + fastmath:
The slowest run took 14.04 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 5: 1.42 µs per loop
 - conv solution:
10000 loops, best of 5: 41 µs per loop

I thought using convolutions to perform the local diagonal subtractions and then summing the differences will be the fastest solution, but it seems there's no beating the speed of numba's compiled code for me, even using the simplest implementation.