问:
How to set the SelectedValue of a ComboBox used as Font selector?
I have a combobox which I fill font's inside. The method I use to do so is in this link. I will share the answer from that question here.

```<code>public YourForm()
{
    InitializeComponent();

    ComboBoxFonts.DrawItem += ComboBoxFonts_DrawItem;
    ComboBoxFonts.DataSource = System.Drawing.FontFamily.Families.ToList();
}

private void ComboBoxFonts_DrawItem(object sender, DrawItemEventArgs e)
{
    var comboBox = (ComboBox)sender;
    var fontFamily = (FontFamily)comboBox.Items[e.Index];
    var font = new Font(fontFamily, comboBox.Font.SizeInPoints);

    e.DrawBackground();
    e.Graphics.DrawString(font.Name, font, Brushes.Black, e.Bounds.X, e.Bounds.Y);
}
</code>```

now I have only made 1 change to this code and that's this :

```<code>cmbFonts.DrawMode = DrawMode.OwnerDrawFixed;
</code>```

there is no problem with loading fonts and it's working but I try to set the selectedvalue on my form load. For example I try to set font named "arial". In order to do so I use this :

```<code>var dataSource = cmbFonts.DataSource as List<FontFamily>;
int res = -1;
try
{
  res = dataSource.IndexOf(new FontFamily(StaticVariables.FontName));
}
catch { }
if (res != -1)
  cmbFonts.SelectedIndex = res;
</code>```

now when I do this I get System.ArgumentOutOfRangeException error because I did not add any Items to Combobox I bind a DataSource therefore when I try to set SelectedIndex I get this error and I know that, I also tried this :

```<code>cmbFonts.SelectedValue = StaticVariables.FontName;
</code>```

but when I run my code with breakpoints in Visual studio I see that my SelectedValue never changes. Before the line is executed I see null and after the execution I still see null in SelectedValue, I checked my StaticVariables.FontName variable and the font is presented in there.

I've also tried to use combobox.Text property but no luck, it's like SelectedValue, was empty string before and still same after I skip it with breakpoint.

TL;DR:
I try to select an item on form load in combobox which I filled with DataSource

答:
Here's a custom owner-drawn ComboBox class (here, named FontListCombo) that shows compatible System Font Families, representing each ComboBox Item using the FontFamily name as the Item Text and the corresponding Font to draw the Item's text (a classic ComboBox Font selector, in practice).

The Custom Control automatically fills itself, at run-time, with the list of available Fonts in the System. It also react to WM_FONTCHANGE messages (broadcast when the System Font pool changes; e.g., a Font is added to or removed from the Fonts folder), to updated the Font list and reflect the change (to also avoid to try and use a Font that doesn't exist anymore).

The text of the ComboBox Items is drawn using TextRenderer.DrawText() instead of Graphics.DrawString(), since the former grants sharper results in this context.

The ComboBox.Items collection is represented by a collection of FontObject class objects, a public class that stores some of the properties of each FontFamily and also exposes a couple of static methods used internally to return a Font object or a FontFamily object, calling the corresponding public methods of the custom ComboBox:

The GetSelectedFont(SizeInPoints, FontStyle) method return a Font object from the current ComboBox.SelectedItem.

GetSelectedFontFamily() return the FontFamily object from the current ComboBox.SelectedItem.

It also overrides ToString(), to return a summary of values of its properties.

This kind of object container is a better fit here: storing FontFamily object as the ConboBox Items would, most surely, create different sorts of problems, the most visible and tragic is that some FontFamily objects become invalid over time or even right after they have been stored. These objects are not meant to be stored permanently to begin with, so it's not exactly a surprise.

As shown in the example, to get the current Font and FontFamily from the ComboBox.SelecteItem:

(here, the ComboBox instance is named cboFontList)

```<code>private void cboFontList_SelectionChangeCommitted(object sender, EventArgs e)
{
    Font font = cboFontList.GetSelectedFont(this.Font.SizeInPoints, FontStyle.Regular);
    FontFamily family = cboFontList.GetSelectedFontFamily();
    string fontDetails = (cboFontList.SelectedItem as FontListCombo.FontObject).ToString();
}
</code>```

The FontObject class stores some important details of the FontFamily, such as the Cell Ascent, the Cell Descent, the EM Size and the Line Spacing.

Some details on how to use these features are described here:

Properly draw text using Graphics Path

Fonts and text metrics

This is how it works:

FontListCombo Custom Control:

```<code>using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

[DesignerCategory("Code")]
public class FontListCombo : ComboBox
{
    private List<FontObject> fontList = null;

    public FontListCombo() {
        SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        this.DrawMode = DrawMode.OwnerDrawVariable;
    }

    protected override void OnHandleCreated(EventArgs e) {
        base.OnHandleCreated(e);
        if (!DesignMode) GetFontFamilies();
    }

    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        if ((Items.Count == 0) || e.Index < 0) return;
        e.DrawBackground();
        var flags = TextFormatFlags.Left | TextFormatFlags.VerticalCenter;
        using (var family = new FontFamily(this.GetItemText(Items[e.Index])))
        using (var font = new Font(family, 10F, FontStyle.Regular, GraphicsUnit.Point)) {
            TextRenderer.DrawText(e.Graphics, family.Name, font, e.Bounds, this.ForeColor, flags);
        }
        e.DrawFocusRectangle();
        base.OnDrawItem(e);
    }

    protected override void OnMeasureItem(MeasureItemEventArgs e) {
        base.OnMeasureItem(e);
        e.ItemHeight = this.Font.Height + 4;
    }

    private void GetFontFamilies()
    {
        this.fontList = new List<FontObject>();

        fontList.AddRange(FontFamily.Families
            .Where(f => f.IsStyleAvailable(FontStyle.Regular))
            .Select(f => new FontObject(f)).ToArray());
        this.DisplayMember = "FamilyName";
        this.ValueMember = "EmHeight";
        this.DataSource = fontList;
    }

    public FontFamily GetSelectedFontFamily()
    {
        if (this.SelectedIndex < 0) return null;
        return FontObject.GetSelectedFontFamily((FontObject)this.SelectedItem);
    }

    public Font GetSelectedFont(float sizeInPoints, FontStyle style)
    {
        if (this.SelectedIndex < 0) return null;
        return FontObject.GetSelectedFont((FontObject)this.SelectedItem, sizeInPoints, style);
    }

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        switch (m.Msg) {
            case WM_FONTCHANGE:  // The System Font pool has changed
                GetFontFamilies();
                break;
        }
    }

    public class FontObject
    {
        public FontObject(FontFamily family) { GetFontFamilyInfo(family); }
        public string FamilyName { get; set; }
        public int EmHeight { get; set; }
        public int CellAscent { get; set; }
        public int CellDescent { get; set; }
        public int LineSpacing { get; set; }

        private void GetFontFamilyInfo(FontFamily family)
        {
            this.FamilyName = family.Name;
            this.EmHeight = family.GetEmHeight(FontStyle.Regular);
            this.CellAscent = family.GetCellAscent(FontStyle.Regular);
            this.CellDescent = family.GetCellDescent(FontStyle.Regular);
            this.LineSpacing = family.GetLineSpacing(FontStyle.Regular);
        }
        internal static FontFamily GetSelectedFontFamily(FontObject fobj)
            => new FontFamily(fobj.FamilyName);

        internal static Font GetSelectedFont(FontObject fobj, float sizeInPoints, FontStyle style)
            => new Font(GetSelectedFontFamily(fobj), sizeInPoints, style);

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.AppendLine(this.FamilyName);
            sb.AppendLine($"Em Height: {this.EmHeight}");
            sb.AppendLine($"Cell Ascent: {this.CellAscent}");
            sb.AppendLine($"Cell Descent: {this.CellDescent}");
            sb.AppendLine($"Line Spacing: {this.LineSpacing}");
            return sb.ToString();
        }
    }
}
</code>```

Body:
I have a combobox which I fill font's inside. The method I use to do so is in this link. I will share the answer from that question here.

public YourForm()
{
    InitializeComponent();

    ComboBoxFonts.DrawItem += ComboBoxFonts_DrawItem;
    ComboBoxFonts.DataSource = System.Drawing.FontFamily.Families.ToList();
}

private void ComboBoxFonts_DrawItem(object sender, DrawItemEventArgs e)
{
    var comboBox = (ComboBox)sender;
    var fontFamily = (FontFamily)comboBox.Items[e.Index];
    var font = new Font(fontFamily, comboBox.Font.SizeInPoints);

    e.DrawBackground();
    e.Graphics.DrawString(font.Name, font, Brushes.Black, e.Bounds.X, e.Bounds.Y);
}

now I have only made 1 change to this code and that's this :

cmbFonts.DrawMode = DrawMode.OwnerDrawFixed;

there is no problem with loading fonts and it's working but I try to set the selectedvalue on my form load. For example I try to set font named "arial". In order to do so I use this :

var dataSource = cmbFonts.DataSource as List<FontFamily>;
int res = -1;
try
{
  res = dataSource.IndexOf(new FontFamily(StaticVariables.FontName));
}
catch { }
if (res != -1)
  cmbFonts.SelectedIndex = res;

now when I do this I get System.ArgumentOutOfRangeException error because I did not add any Items to Combobox I bind a DataSource therefore when I try to set SelectedIndex I get this error and I know that, I also tried this :

cmbFonts.SelectedValue = StaticVariables.FontName;

but when I run my code with breakpoints in Visual studio I see that my SelectedValue never changes. Before the line is executed I see null and after the execution I still see null in SelectedValue, I checked my StaticVariables.FontName variable and the font is presented in there.

I've also tried to use combobox.Text property but no luck, it's like SelectedValue, was empty string before and still same after I skip it with breakpoint.

TL;DR:
I try to select an item on form load in combobox which I filled with DataSource

Body:
Here's a custom owner-drawn ComboBox class (here, named FontListCombo) that shows compatible System Font Families, representing each ComboBox Item using the FontFamily name as the Item Text and the corresponding Font to draw the Item's text (a classic ComboBox Font selector, in practice).

The Custom Control automatically fills itself, at run-time, with the list of available Fonts in the System. It also react to WM_FONTCHANGE messages (broadcast when the System Font pool changes; e.g., a Font is added to or removed from the Fonts folder), to updated the Font list and reflect the change (to also avoid to try and use a Font that doesn't exist anymore).

The text of the ComboBox Items is drawn using TextRenderer.DrawText() instead of Graphics.DrawString(), since the former grants sharper results in this context.

The ComboBox.Items collection is represented by a collection of FontObject class objects, a public class that stores some of the properties of each FontFamily and also exposes a couple of static methods used internally to return a Font object or a FontFamily object, calling the corresponding public methods of the custom ComboBox:

The GetSelectedFont(SizeInPoints, FontStyle) method return a Font object from the current ComboBox.SelectedItem.

GetSelectedFontFamily() return the FontFamily object from the current ComboBox.SelectedItem.

It also overrides ToString(), to return a summary of values of its properties.

This kind of object container is a better fit here: storing FontFamily object as the ConboBox Items would, most surely, create different sorts of problems, the most visible and tragic is that some FontFamily objects become invalid over time or even right after they have been stored. These objects are not meant to be stored permanently to begin with, so it's not exactly a surprise.

As shown in the example, to get the current Font and FontFamily from the ComboBox.SelecteItem:

(here, the ComboBox instance is named cboFontList)

private void cboFontList_SelectionChangeCommitted(object sender, EventArgs e)
{
    Font font = cboFontList.GetSelectedFont(this.Font.SizeInPoints, FontStyle.Regular);
    FontFamily family = cboFontList.GetSelectedFontFamily();
    string fontDetails = (cboFontList.SelectedItem as FontListCombo.FontObject).ToString();
}

The FontObject class stores some important details of the FontFamily, such as the Cell Ascent, the Cell Descent, the EM Size and the Line Spacing.

Some details on how to use these features are described here:

Properly draw text using Graphics Path

Fonts and text metrics

This is how it works:

FontListCombo Custom Control:

using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

[DesignerCategory("Code")]
public class FontListCombo : ComboBox
{
    private List<FontObject> fontList = null;

    public FontListCombo() {
        SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        this.DrawMode = DrawMode.OwnerDrawVariable;
    }

    protected override void OnHandleCreated(EventArgs e) {
        base.OnHandleCreated(e);
        if (!DesignMode) GetFontFamilies();
    }

    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        if ((Items.Count == 0) || e.Index < 0) return;
        e.DrawBackground();
        var flags = TextFormatFlags.Left | TextFormatFlags.VerticalCenter;
        using (var family = new FontFamily(this.GetItemText(Items[e.Index])))
        using (var font = new Font(family, 10F, FontStyle.Regular, GraphicsUnit.Point)) {
            TextRenderer.DrawText(e.Graphics, family.Name, font, e.Bounds, this.ForeColor, flags);
        }
        e.DrawFocusRectangle();
        base.OnDrawItem(e);
    }

    protected override void OnMeasureItem(MeasureItemEventArgs e) {
        base.OnMeasureItem(e);
        e.ItemHeight = this.Font.Height + 4;
    }

    private void GetFontFamilies()
    {
        this.fontList = new List<FontObject>();

        fontList.AddRange(FontFamily.Families
            .Where(f => f.IsStyleAvailable(FontStyle.Regular))
            .Select(f => new FontObject(f)).ToArray());
        this.DisplayMember = "FamilyName";
        this.ValueMember = "EmHeight";
        this.DataSource = fontList;
    }

    public FontFamily GetSelectedFontFamily()
    {
        if (this.SelectedIndex < 0) return null;
        return FontObject.GetSelectedFontFamily((FontObject)this.SelectedItem);
    }

    public Font GetSelectedFont(float sizeInPoints, FontStyle style)
    {
        if (this.SelectedIndex < 0) return null;
        return FontObject.GetSelectedFont((FontObject)this.SelectedItem, sizeInPoints, style);
    }

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        switch (m.Msg) {
            case WM_FONTCHANGE:  // The System Font pool has changed
                GetFontFamilies();
                break;
        }
    }

    public class FontObject
    {
        public FontObject(FontFamily family) { GetFontFamilyInfo(family); }
        public string FamilyName { get; set; }
        public int EmHeight { get; set; }
        public int CellAscent { get; set; }
        public int CellDescent { get; set; }
        public int LineSpacing { get; set; }

        private void GetFontFamilyInfo(FontFamily family)
        {
            this.FamilyName = family.Name;
            this.EmHeight = family.GetEmHeight(FontStyle.Regular);
            this.CellAscent = family.GetCellAscent(FontStyle.Regular);
            this.CellDescent = family.GetCellDescent(FontStyle.Regular);
            this.LineSpacing = family.GetLineSpacing(FontStyle.Regular);
        }
        internal static FontFamily GetSelectedFontFamily(FontObject fobj)
            => new FontFamily(fobj.FamilyName);

        internal static Font GetSelectedFont(FontObject fobj, float sizeInPoints, FontStyle style)
            => new Font(GetSelectedFontFamily(fobj), sizeInPoints, style);

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.AppendLine(this.FamilyName);
            sb.AppendLine($"Em Height: {this.EmHeight}");
            sb.AppendLine($"Cell Ascent: {this.CellAscent}");
            sb.AppendLine($"Cell Descent: {this.CellDescent}");
            sb.AppendLine($"Line Spacing: {this.LineSpacing}");
            return sb.ToString();
        }
    }
}


来源: stackexchange

问:
How to Make Kivy File Chooser auto refresh in python
So I have been coding this file explorer program. I have coded the copy function so far and the problem I am running into is that after I copy a file to its new directory(i.e. the directory that I am on currently in the filechooser) the file isn't showing up in the the actual filechooser. I am using the icon view and I saw only one mention of this online here:Refresh / Reload FileChooser and I tried this method and like the actual _update_files() function is getting executed.(checked it with a couple of print statements) But I am noticing that there is not any change in the actual filechooser.What am i doing wrong here? THANK YOU!!!

This is the python code that is executed when ever the file is copied. I assigned the actual screen that contains the file chooser to a variable named MainScreenVar

```<code>        for i in range(0, self.execute_data_length):

            if self.execute_data[i][2] == "File" :
                shutil.copy2(self.execute_data[i][1], current_path)
                MainScreenvar = MainScreen()
                return MainScreenvar.ids.filechooser._update_files()
        mycursor.execute("DELETE FROM selection")
        mydb.commit()
</code>```

This is part of the kivy file:

```<code><MainScreen>:
FileChooserIconView:
    id:filechooser
    size_hint:1,.9
    pos_hint:{"top": .9}
    color: 0,0,0,0
</code>```

and the source code for the kivy file chooser is here:
https://kivy.org/doc/stable/_modules/kivy/uix/filechooser.html

答:
The error in your code is the line:

```<code>MainScreenvar = MainScreen()
</code>```

which is creating a new instance of MainScreen. This will not be the instance that is displayed in your GUI, so the line:

```<code>return MainScreenvar.ids.filechooser._update_files()
</code>```

is calling _update_files() for a FileChooserIconView that is not displayed in your GUI. The solution is to use a reference to the actual FileChooserIconView that is in your GUI. Probably something like:

```<code>MainScreenvar = self.manager.get_screen('main')
</code>```

However, this is only a guess since you haven't provided much of your code. This assumes that your posted code is from a Screen, and that the name that you provided for MainScreen is main.

ContentLicense: CC BY-SA 4.0

Body:
So I have been coding this file explorer program. I have coded the copy function so far and the problem I am running into is that after I copy a file to its new directory(i.e. the directory that I am on currently in the filechooser) the file isn't showing up in the the actual filechooser. I am using the icon view and I saw only one mention of this online here:Refresh / Reload FileChooser and I tried this method and like the actual _update_files() function is getting executed.(checked it with a couple of print statements) But I am noticing that there is not any change in the actual filechooser.What am i doing wrong here? THANK YOU!!!

This is the python code that is executed when ever the file is copied. I assigned the actual screen that contains the file chooser to a variable named MainScreenVar

        for i in range(0, self.execute_data_length):

            if self.execute_data[i][2] == "File" :
                shutil.copy2(self.execute_data[i][1], current_path)
                MainScreenvar = MainScreen()
                return MainScreenvar.ids.filechooser._update_files()
        mycursor.execute("DELETE FROM selection")
        mydb.commit()

This is part of the kivy file:

<MainScreen>:
FileChooserIconView:
    id:filechooser
    size_hint:1,.9
    pos_hint:{"top": .9}
    color: 0,0,0,0

and the source code for the kivy file chooser is here:
https://kivy.org/doc/stable/_modules/kivy/uix/filechooser.html

Body:
The error in your code is the line:

MainScreenvar = MainScreen()

which is creating a new instance of MainScreen. This will not be the instance that is displayed in your GUI, so the line:

return MainScreenvar.ids.filechooser._update_files()

is calling _update_files() for a FileChooserIconView that is not displayed in your GUI. The solution is to use a reference to the actual FileChooserIconView that is in your GUI. Probably something like:

MainScreenvar = self.manager.get_screen('main')

However, this is only a guess since you haven't provided much of your code. This assumes that your posted code is from a Screen, and that the name that you provided for MainScreen is main.


问:
"Database" structure in XML file
So I have to define a "database" in an xml document that has to have a school, grades, rooms, courses and students and afterwards I have to write some classes in C# that has to get and save data to the xml file with the help of Deserialization and Serialization.
But the problem is I don't know how I should structure the XML file, right now my file looks like this:

```<code><?xml version="1.0" encoding="utf-8" ?>
<School>
   <Grades>

   </Grades>
   <Rooms>

   </Rooms>
   <Courses>

   </Courses>
   <Students>

   </Students>
</School>
</code>```

But I have been wondering if this might be a better way:

```<code><?xml version="1.0" encoding="utf-8" ?>
<School>
   <Grades>
      <Rooms>
         <Courses>
            <Students>

            </Students>
         </Courses>
      </Rooms>
   </Grades>
</School>
</code>```

Or maybe there is some third way I'm overlooking, any help would be appreciated

答:
This question is opinion-based. So, this is just my opinion:

Choose the first layout and use attribute @IDs to link between them.

For example:

```<code><?xml version="1.0" encoding="utf-8" ?>
<School>
   <Grades>
     <Grade id="gr1">...</Grade>
   </Grades>
   <Rooms>
     <Room id="rm1">...</Room>
   </Rooms>
   <Courses>
     <Course id="crs1">
       <RoomNr>rm1</RoomNr>  <!-- Referring to the Rooms/Room/@id rm1 -->
       ...
     </Course>
   </Courses>
   <Students>
     <Student id="1">
       <Course>crs1</Course> <!-- Referring to the Courses/Course/@id crs1 -->
       <Course>...</Course>
     </Student>
   </Students>
</School>
</code>```

This layout is easily query-able and changing the links won't significantly change the layout.

For example (Because you tagged your question with xslt):

Retrieving all <Student>s can be done with the XPath-1.0 expression

```<code>/School/Students/Student
</code>```

Retrieving all <Student>s which visit a certain course (e.g. crs1)

```<code>/School/Students/Student[Course='crs1']
</code>```

...and so on.

Title: "Database" structure in XML file

Body:
So I have to define a "database" in an xml document that has to have a school, grades, rooms, courses and students and afterwards I have to write some classes in C# that has to get and save data to the xml file with the help of Deserialization and Serialization.
But the problem is I don't know how I should structure the XML file, right now my file looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<School>
   <Grades>

   </Grades>
   <Rooms>

   </Rooms>
   <Courses>

   </Courses>
   <Students>

   </Students>
</School>

But I have been wondering if this might be a better way:

<?xml version="1.0" encoding="utf-8" ?>
<School>
   <Grades>
      <Rooms>
         <Courses>
            <Students>

            </Students>
         </Courses>
      </Rooms>
   </Grades>
</School>

Or maybe there is some third way I'm overlooking, any help would be appreciated

Body:
This question is opinion-based. So, this is just my opinion:

Choose the first layout and use attribute @IDs to link between them.

For example:

<?xml version="1.0" encoding="utf-8" ?>
<School>
   <Grades>
     <Grade id="gr1">...</Grade>
   </Grades>
   <Rooms>
     <Room id="rm1">...</Room>
   </Rooms>
   <Courses>
     <Course id="crs1">
       <RoomNr>rm1</RoomNr>  <!-- Referring to the Rooms/Room/@id rm1 -->
       ...
     </Course>
   </Courses>
   <Students>
     <Student id="1">
       <Course>crs1</Course> <!-- Referring to the Courses/Course/@id crs1 -->
       <Course>...</Course>
     </Student>
   </Students>
</School>

This layout is easily query-able and changing the links won't significantly change the layout.

For example (Because you tagged your question with xslt):

Retrieving all <Student>s can be done with the XPath-1.0 expression

/School/Students/Student

Retrieving all <Student>s which visit a certain course (e.g. crs1)

/School/Students/Student[Course='crs1']

...and so on.


问:
Java: How do you enforce a class type parameter to be the same as generic type specified in a generic method?
I created a NotificationManager class, which let's you register a generic listener to some generic notification service. In the NotificationManager class I have a generic method for registering a listener with a service:

```<code>public static <E> void registerNotify(Class<E> type, INotificationListener<E> listener) {
    @SuppressWarnings("unchecked")
    INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
    service.registerNotificationListener(listener);
}
</code>```

So, for some INotificationListener of a particular type I'd like to force the user, when calling this method, to specify the same type as the listener. The type maps to all the INotificationListeners of the same type, however this method doesn't enforce what I'm trying to enforce. For example, I could call:

```<code>INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(String.class, locationListener);
</code>```

and the code compiles fine. What I thought this would enforce is the following:

```<code>INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(Location.class, locationListener);
</code>```

Any ideas on how to accomplish this?

Update:

Sorry for the mixup, the above does in fact work. The method in the same class which does not work is actually the following:

```<code>public static <E> void broadcastNotify(Class<E> type, E data)
    {
        @SuppressWarnings("unchecked")
        INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
        service.notifyListeners(data);
    }
</code>```

And calling:

```<code>Location location = new Location();
NotificationManager.broadcastNotify(Object.class, location);
</code>```

Does not cause a compilation error, which is what I would like it to do.

答:
One way to avoid the problem is to use reflection and obtain the type from the class itself. This will avoids the need to provide the same type twice. It will only provide a warning is a non-generic type is used.

You can get the generic type from the interface for the implementing class.

ContentLicense: CC BY-SA 3.0

Body:
I created a NotificationManager class, which let's you register a generic listener to some generic notification service. In the NotificationManager class I have a generic method for registering a listener with a service:

public static <E> void registerNotify(Class<E> type, INotificationListener<E> listener) {
    @SuppressWarnings("unchecked")
    INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
    service.registerNotificationListener(listener);
}

So, for some INotificationListener of a particular type I'd like to force the user, when calling this method, to specify the same type as the listener. The type maps to all the INotificationListeners of the same type, however this method doesn't enforce what I'm trying to enforce. For example, I could call:

INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(String.class, locationListener);

and the code compiles fine. What I thought this would enforce is the following:

INotificationListener<Location> locationListener = this;
NotificationManager.registerNotify(Location.class, locationListener);

Any ideas on how to accomplish this?

Update:

Sorry for the mixup, the above does in fact work. The method in the same class which does not work is actually the following:

public static <E> void broadcastNotify(Class<E> type, E data)
    {
        @SuppressWarnings("unchecked")
        INotificationService<E> service = (INotificationService<E>) NotificationServiceFactory.get(type);
        service.notifyListeners(data);
    }

And calling:

Location location = new Location();
NotificationManager.broadcastNotify(Object.class, location);

Does not cause a compilation error, which is what I would like it to do.


问:
xpath attribute with ampersand ( ) throws error 'XPST0003: No closing ';' found for entity or character reference'
I'm working with a solution that relies on xpath expressions to gather data. One of those expressions was working just fine until data with special characters showed up.

Example of xml field that contains the data:

```<code><variable id="name" value="STICKS & STONES"/>
</code>```

This is the xpath expression to fetch data data:

```<code>contract/variable[@id \= 'info']/variable[@id \= 'client']/variable[@id \= 'name']/@value
</code>```

(The backslash preceding the equals sign is required for the application to work).

I tried to replace the entity representation with the & sign :

```<code>replace(/contract/variable[@id \= 'info']/variable[@id \= 'client']/variable[@id \= 'name']/@value, '&', '&')
</code>```

It works, but only fixes this particular case. I want to find a way to deal with all occurrences of entity representations.

Is there a way to "unescape" the content gathered from the xpath expression?

答:
I suppose you can use string() function to circumvent the semi-colon problem :

```<code>string(contract/variable[@id \= 'info']/variable[@id \= 'client']/variable[@id \= 'name']/@value)
</code>```

should output the desired STICKS & STONES.

Body:
I'm working with a solution that relies on xpath expressions to gather data. One of those expressions was working just fine until data with special characters showed up.

Example of xml field that contains the data:

<variable id="name" value="STICKS & STONES"/>

This is the xpath expression to fetch data data:

contract/variable[@id \= 'info']/variable[@id \= 'client']/variable[@id \= 'name']/@value

(The backslash preceding the equals sign is required for the application to work).

I tried to replace the entity representation with the & sign :

replace(/contract/variable[@id \= 'info']/variable[@id \= 'client']/variable[@id \= 'name']/@value, '&', '&')

It works, but only fixes this particular case. I want to find a way to deal with all occurrences of entity representations.

Is there a way to "unescape" the content gathered from the xpath expression?

Body:
I suppose you can use string() function to circumvent the semi-colon problem :

string(contract/variable[@id \= 'info']/variable[@id \= 'client']/variable[@id \= 'name']/@value)

should output the desired STICKS & STONES.


问:
SimpleJdbcInsert fail to insert because of null autogenerated id (HSQLDB)
Good morning everyone

I am unit testing the persistence tier of a project with JUnit using HSQLDB. The project is using Spring with Hibernate + JPA. I'm using Spring's SimpleJdbcInsert to insert some data in the database for testing. However whenever I try to insert something I am getting:
org.hsqldb.HsqlException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID as shown below:

```<code>org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [INSERT INTO picture (DATA, MIME_TYPE, NAME, SIZE) VALUES(?, ?, ?, ?)]; violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID; nested exception is java.sql.SQLIntegrityConstraintViolationException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID

    at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:85)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:645)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:866)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:927)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:932)
    at org.springframework.jdbc.core.simple.AbstractJdbcInsert.executeInsertInternal(AbstractJdbcInsert.java:362)
    at org.springframework.jdbc.core.simple.AbstractJdbcInsert.doExecute(AbstractJdbcInsert.java:341)
    at org.springframework.jdbc.core.simple.SimpleJdbcInsert.execute(SimpleJdbcInsert.java:122)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.insertPicture(AppointmentDaoImplTest.java:330)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.insertUser(AppointmentDaoImplTest.java:345)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.insertPatient(AppointmentDaoImplTest.java:449)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.testCreateAppointmentSuccessfully(AppointmentDaoImplTest.java:557)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:168)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.sql.SQLIntegrityConstraintViolationException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
    at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:873)
    at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:866)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:629)
    ... 41 more
Caused by: org.hsqldb.HsqlException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.Table.enforceRowConstraints(Unknown Source)
    at org.hsqldb.Table.insertSingleRow(Unknown Source)
    at org.hsqldb.StatementDML.insertSingleRow(Unknown Source)
    at org.hsqldb.StatementInsert.getResult(Unknown Source)
    at org.hsqldb.StatementDMQL.execute(Unknown Source)
    at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
    at org.hsqldb.Session.execute(Unknown Source)
    ... 46 more
</code>```

Here is my test (where insertPatient() is failing):

```<code>@Test
public void testCreateAppointmentSuccessfully() {
    cleanAllTables();
    insertPatient();

    ... some code ...
}
</code>```

The insertPatient function (where insertPicture() is failing):

```<code>private void insertPatient() {
    insertUser();

    ... some code ...
}

private void insertUser() {
    insertPicture();

    ... some code ...
}

private void insertPicture() {
    Map<String, Object> map = new HashMap<>();
    map.put("data", IMG_DATA);
    map.put("mime_type", MIME_TYPE);
    map.put("size", IMG_SIZE);
    map.put("name", PICTURE);
    pictureJdbcInsert.execute(map);
}
</code>```

The SimpleJdbcInsert pictureJdbcInsert instance is set in the following method:

```<code>@Before
public void setUp(){
    this.pictureJdbcInsert = new SimpleJdbcInsert(this.ds)
                .withTableName(PICTURES_TABLE) // private static final String PICTURES_TABLE = "picture";
                .usingGeneratedKeyColumns("picture_id");

    ... some code ...
}
</code>```

The test class is annotated with @Sql(scripts = "classpath:sql/schema.sql") being schema.sql:

```<code>create table if not exists picture
(
    picture_id identity        not null constraint picture_pk primary key,
    name      varchar(1023),
    mime_type varchar(255)     not null,
    size      bigint           not null default 0,
    data      varbinary(65535) not null
);

... some more tables ...
</code>```

As you can see, I am not putting the key  manually. I am expecting that usingGeneratedKeyColumns method will automatically generate it for me. From the stacktrace I understand that is trying to execute the following query:
INSERT INTO picture (DATA, MIME_TYPE, NAME, SIZE) VALUES(?, ?, ?, ?) where the ? are replaced by the corresponding values in the map, but failing because there was no value for picture_id specified. I don't understand is this happening as the schema.sql file specifies that picture_id is of type identity meaning that is auto-generated and by default starting by 0 and with increment of 1.

I have been trying and looking for solutions but everything suggests this should be working.

答: The actual problem was in the configuration class. I had this properties.setProperty("hibernate.hbm2ddl.auto", "update"); in the EntityManagerFactory bean. Therefore, JPA was creating the table before running the schema.sql file. This was causing that the picture_id column was not of identity type. Deleting that line from the bean solved the issue.

Body:
Good morning everyone

I am unit testing the persistence tier of a project with JUnit using HSQLDB. The project is using Spring with Hibernate + JPA. I'm using Spring's SimpleJdbcInsert to insert some data in the database for testing. However whenever I try to insert something I am getting:
org.hsqldb.HsqlException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID as shown below:

org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [INSERT INTO picture (DATA, MIME_TYPE, NAME, SIZE) VALUES(?, ?, ?, ?)]; violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID; nested exception is java.sql.SQLIntegrityConstraintViolationException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID

    at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:85)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:645)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:866)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:927)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:932)
    at org.springframework.jdbc.core.simple.AbstractJdbcInsert.executeInsertInternal(AbstractJdbcInsert.java:362)
    at org.springframework.jdbc.core.simple.AbstractJdbcInsert.doExecute(AbstractJdbcInsert.java:341)
    at org.springframework.jdbc.core.simple.SimpleJdbcInsert.execute(SimpleJdbcInsert.java:122)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.insertPicture(AppointmentDaoImplTest.java:330)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.insertUser(AppointmentDaoImplTest.java:345)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.insertPatient(AppointmentDaoImplTest.java:449)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.testCreateAppointmentSuccessfully(AppointmentDaoImplTest.java:557)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:168)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.sql.SQLIntegrityConstraintViolationException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
    at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:873)
    at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:866)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:629)
    ... 41 more
Caused by: org.hsqldb.HsqlException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.Table.enforceRowConstraints(Unknown Source)
    at org.hsqldb.Table.insertSingleRow(Unknown Source)
    at org.hsqldb.StatementDML.insertSingleRow(Unknown Source)
    at org.hsqldb.StatementInsert.getResult(Unknown Source)
    at org.hsqldb.StatementDMQL.execute(Unknown Source)
    at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
    at org.hsqldb.Session.execute(Unknown Source)
    ... 46 more

Here is my test (where insertPatient() is failing):

@Test
public void testCreateAppointmentSuccessfully() {
    cleanAllTables();
    insertPatient();

    ... some code ...
}

The insertPatient function (where insertPicture() is failing):

private void insertPatient() {
    insertUser();

    ... some code ...
}

private void insertUser() {
    insertPicture();

    ... some code ...
}

private void insertPicture() {
    Map<String, Object> map = new HashMap<>();
    map.put("data", IMG_DATA);
    map.put("mime_type", MIME_TYPE);
    map.put("size", IMG_SIZE);
    map.put("name", PICTURE);
    pictureJdbcInsert.execute(map);
}

The SimpleJdbcInsert pictureJdbcInsert instance is set in the following method:

@Before
public void setUp(){
    this.pictureJdbcInsert = new SimpleJdbcInsert(this.ds)
                .withTableName(PICTURES_TABLE) // private static final String PICTURES_TABLE = "picture";
                .usingGeneratedKeyColumns("picture_id");

    ... some code ...
}

The test class is annotated with @Sql(scripts = "classpath:sql/schema.sql") being schema.sql:

create table if not exists picture
(
    picture_id identity        not null constraint picture_pk primary key,
    name      varchar(1023),
    mime_type varchar(255)     not null,
    size      bigint           not null default 0,
    data      varbinary(65535) not null
);

... some more tables ...

As you can see, I am not putting the key  manually. I am expecting that usingGeneratedKeyColumns method will automatically generate it for me. From the stacktrace I understand that is trying to execute the following query:
INSERT INTO picture (DATA, MIME_TYPE, NAME, SIZE) VALUES(?, ?, ?, ?) where the ? are replaced by the corresponding values in the map, but failing because there was no value for picture_id specified. I don't understand is this happening as the schema.sql file specifies that picture_id is of type identity meaning that is auto-generated and by default starting by 0 and with increment of 1.

I have been trying and looking for solutions but everything suggests this should be working.


问:
almost increasing sequence java
I am trying to write code that determines if is it possible to attain an array of strictly increasing integers by removing only one element from that array.

I have my code working for 16 out of 17 cases but cannot think of a way to neatly rewrite my code so that it accounts for the case of a number being bigger than the one before it as well as smaller than the one after it the way I've written this for loop. Here is my code. The case that this doesn't work for is the array: [1, 2, 3, 4, 3, 6], since it doesn't consider the last 3 in the array as an offender the way my for loop is currently constructed.

```<code>boolean almostIncreasingSequence(int[] sequence) {

int offenderPosition = 0;
int[] arrCopy = Arrays.copyOf(sequence, sequence.length);
boolean ordered = true;

//trying to neatly rewrite this for loop
for(int i= 0; i < sequence.length; i++){
    if(i<sequence.length-1){
        for(int j = i+1; j < sequence.length; j++) {
            if(!(sequence[i] < sequence[j])){
                ordered = false;
                offenderPosition = i;
            }
        }
    }
    if(i == sequence.length-1){
        if(!(sequence[i] > sequence[i-1])){
            ordered = false;
            offenderPosition = i;
        }
    }

}

if(ordered == false) {
    //remove offender
    int currentSize = arrCopy.length;
    for(int i = offenderPosition+1;i< currentSize; i++) {
        arrCopy[i-1] = arrCopy[i];
    }
    currentSize--;

    //reassign array
    arrCopy = Arrays.copyOf(arrCopy, currentSize);

    boolean lastChance = true;

    for(int i = 0; i < currentSize-1; i++){
        for(int j = i+1; j < currentSize; j++) {
            if(!(arrCopy[i] < arrCopy[j])){
                lastChance = false;
            }
        }
    }
    return lastChance;
}
else{
    return true;
}
</code>```

}

答:
Here is the solution:</p>

```<code>  boolean almostIncreasingSequence(int[] sequence) {
       int count = checkSeq(sequence);
     if(count == -1) {
         return true;
     }
     int index = count;
     count = checkSeq(removeIndex(sequence,count-1));
    if(count == -1) {
         return true;
     }
     count = checkSeq(removeIndex(sequence,index));
if(count == -1) {
         return true;
     }
return false;
}
int checkSeq(int[] source){
    int index = -1;
     for(int i=1; i<source.length;i++){
           if(source[i] <= source[i-1]){
             index = i;
             break;
         }
     }

    return index;
}

int[] removeIndex(int[] source , int index){
    int[] dist = new int[source.length-1];
    int x = 0;
    for(int i=0; i<source.length;i++){
         if(i==index){
            continue;
        }
        dist[x++] = source[i];
    }
    return dist;
}
</code>```

Title: almost increasing sequence java

Body:
I am trying to write code that determines if is it possible to attain an array of strictly increasing integers by removing only one element from that array.

I have my code working for 16 out of 17 cases but cannot think of a way to neatly rewrite my code so that it accounts for the case of a number being bigger than the one before it as well as smaller than the one after it the way I've written this for loop. Here is my code. The case that this doesn't work for is the array: [1, 2, 3, 4, 3, 6], since it doesn't consider the last 3 in the array as an offender the way my for loop is currently constructed.

boolean almostIncreasingSequence(int[] sequence) {

int offenderPosition = 0;
int[] arrCopy = Arrays.copyOf(sequence, sequence.length);
boolean ordered = true;

//trying to neatly rewrite this for loop
for(int i= 0; i < sequence.length; i++){
    if(i<sequence.length-1){
        for(int j = i+1; j < sequence.length; j++) {
            if(!(sequence[i] < sequence[j])){
                ordered = false;
                offenderPosition = i;
            }
        }
    }
    if(i == sequence.length-1){
        if(!(sequence[i] > sequence[i-1])){
            ordered = false;
            offenderPosition = i;
        }
    }

}

if(ordered == false) {
    //remove offender
    int currentSize = arrCopy.length;
    for(int i = offenderPosition+1;i< currentSize; i++) {
        arrCopy[i-1] = arrCopy[i];
    }
    currentSize--;

    //reassign array
    arrCopy = Arrays.copyOf(arrCopy, currentSize);

    boolean lastChance = true;

    for(int i = 0; i < currentSize-1; i++){
        for(int j = i+1; j < currentSize; j++) {
            if(!(arrCopy[i] < arrCopy[j])){
                lastChance = false;
            }
        }
    }
    return lastChance;
}
else{
    return true;
}

}

Body:
Here is the solution:

  boolean almostIncreasingSequence(int[] sequence) {
       int count = checkSeq(sequence);
     if(count == -1) {
         return true;
     }
     int index = count;
     count = checkSeq(removeIndex(sequence,count-1));
    if(count == -1) {
         return true;
     }
     count = checkSeq(removeIndex(sequence,index));
if(count == -1) {
         return true;
     }
return false;
}
int checkSeq(int[] source){
    int index = -1;
     for(int i=1; i<source.length;i++){
           if(source[i] <= source[i-1]){
             index = i;
             break;
         }
     }

    return index;
}

int[] removeIndex(int[] source , int index){
    int[] dist = new int[source.length-1];
    int x = 0;
    for(int i=0; i<source.length;i++){
         if(i==index){
            continue;
        }
        dist[x++] = source[i];
    }
    return dist;
}


问:
Can a user change the value of Redux/Mobx in Chrome to gain access to restricted views?
I have a react + firebase app. In the user's collection I have a permissions object where I track what the user has access to. Then in my react app, I have the following:

```<code>  // Login component
    const userRecord = await Firebase.login(email,password)
    store.user = await this.fetchUser(userRecord.uid)

</code>```

For admin-only views, I wrap them in a withAuthorization HOC, where I check for store.user.permissions.admin

```<code>  // Not exactly this, but this is the general idea
  {store.user.permissions.admin && <RestrictedView />
</code>```

My question is, could the user change the value of permissions in chrome to gain access to the restricted views? If so, is there a better approach? I may eventually use customClaims, but would like to use the above for now.

Thank you in advance!

答:
Always assume that the adversary has full control over the browser.

Typically if you want your app to be secure against malicious entities, the security of it has to come from the server. Make authorization/bearer tokens or a cookie scheme that can be verified by your server (i.e. https://jwt.io/). Then only allow data to be sent from to the users you want to based on that information. Security/validation in the front-end is more about making sure users don't unintentionally mess things up.

The user has full ability to modify any HTML/CSS/JS you have in the browser via various dev-tools.

The user has full access to any information being sent via the JavaScript (even if it's minified, there are tools to unminify it to some extent).

All React state can be modified pretty easily using React's dev tools, If you are using redux, you might have the redux dev tools set up.

In firebase, there's a whole section on security in the docs. Set up the data that would be behind your RestrictedViews to require the levels of authentication you need them to. Make sure that firebase does it's share of your application security. The section on insecure rules is also a good place to start reading up on what firebase can do for you and how to configure their security rules.

Some further reading:

OWASP Top Ten (2017) Broken Access Control (bold is added for emphasis)

Access control is only effective if enforced in trusted server-side
code or server-less API, where the attacker cannot modify the access
control check or metadata.

With the exception of public resources, deny by default.

Implement access control mechanisms once and re-use them throughout the application, including minimizing CORS usage.

Model access controls should enforce record ownership, rather than accepting that the user can create, read, update, or delete any
record.

Unique application business limit requirements should be enforced by domain models.

Disable web server directory listing and ensure file metadata (e.g. .git) and backup files are not present within web roots.

Log access control failures, alert admins when appropriate (e.g. repeated failures).

Rate limit API and controller access to minimize the harm from automated attack tooling.

JWT tokens should be invalidated on the server after logout. Developers and QA staff should include functional access control unit and integration tests.

Understanding React Frontend security

We need to make one thing clear — everything you put in the client
browser can be easily changed by the client.

Later in that article:

How do I prevent the user from accessing non-public parts of my site?

You do it exactly as you though to do it — you create a variable, set
it to true for admins only and once the check passes, show the admin
only content.

“Ok, that’s not secure at all — everyone can then go to the admin page
and delete everything!” you scream.

Fair — but only if you implement your application in a bad way. The
frontend part should not be concerned with the validity or not of
credentials provided. It should always accept the data as “true” and
just render all the data it is passed.

It it’s the backend job to perform this validation!

Body:
I have a react + firebase app. In the user's collection I have a permissions object where I track what the user has access to. Then in my react app, I have the following:

  // Login component
    const userRecord = await Firebase.login(email,password)
    store.user = await this.fetchUser(userRecord.uid)

For admin-only views, I wrap them in a withAuthorization HOC, where I check for store.user.permissions.admin

  // Not exactly this, but this is the general idea
  {store.user.permissions.admin && <RestrictedView />

My question is, could the user change the value of permissions in chrome to gain access to the restricted views? If so, is there a better approach? I may eventually use customClaims, but would like to use the above for now.

Thank you in advance!


问:
iOS Swift Combine: cancel a Set<AnyCancellable>
If I have stored a cancellable set into a ViewController:

```<code>private var bag = Set<AnyCancellable>()
</code>```

Which contains multiple subscription.

1 - Should I cancel subscription in deinit?  or it does the job automatically?

2 - If so, how can I cancel all the stored subscriptions?

```<code>bag.removeAll() is enough?
</code>```

or should I iterate through the set and cancel all subscription one by one?

```<code>for sub in bag {
   sub.cancel()
}
</code>```

Apple says that the subscription is alive until the stored AnyCancellable is in memory. So I guess that deallocating the cancellables with bag.removeAll() should be enough, isn't it?

答:
I test this code

```<code>let cancellable = Set<AnyCancellable>()

Timer.publish(every: 1, on: .main, in: .common).autoconnect()
  .sink { print("===== timer: \($0)") }
  .store(in: &cancellable)

cancellable.removeAll() // just remove from Set. not cancellable.cancel()
</code>```

so I use this extension.

```<code>import Combine

typealias CancelBag = Set<AnyCancellable>

extension CancelBag {
  mutating func cancelAll() {
    forEach { $0.cancel() }
    removeAll()
  }
}
</code>```

Body:
If I have stored a cancellable set into a ViewController:

private var bag = Set<AnyCancellable>()

Which contains multiple subscription.

1 - Should I cancel subscription in deinit?  or it does the job automatically?

2 - If so, how can I cancel all the stored subscriptions?

bag.removeAll() is enough?

or should I iterate through the set and cancel all subscription one by one?

for sub in bag {
   sub.cancel()
}

Apple says that the subscription is alive until the stored AnyCancellable is in memory. So I guess that deallocating the cancellables with bag.removeAll() should be enough, isn't it?

Body:
I test this code

let cancellable = Set<AnyCancellable>()

Timer.publish(every: 1, on: .main, in: .common).autoconnect()
  .sink { print("===== timer: \($0)") }
  .store(in: &cancellable)

cancellable.removeAll() // just remove from Set. not cancellable.cancel()

so I use this extension.

import Combine

typealias CancelBag = Set<AnyCancellable>

extension CancelBag {
  mutating func cancelAll() {
    forEach { $0.cancel() }
    removeAll()
  }
}


问:
How do I get ggplot to produce a plot in python
I'm familiar with ggplot in R. Using RStudio, a plot would be produced in the bottom right window.

If I try to run a python program to generate a ggplot, nothing happens in my terminal. The code runs without error, but nothing is produced. Am I missing something?

Matplot seems to work fine, and produces a plot.

I'm using Fedora 32, python 3.8, and ggplot found on pip.

```<code>from ggplot import *
import pandas

data = pandas.read_csv(
    "path-to-data")
g = ggplot(data,  aes('TIMEn', 'ENTRIESn_hourly')) + \
    geom_point() + stat_smooth(method="lm")
g
</code>```

UPDATE: OK, I think part of the problem was the size of the data in the csv. I can get a plot produced now, but only if I run the code line by line in terminal. Nothing will be produced if I run "python filename.py"

答: OK, I got something to work. I just used the .save() method to save the plot in a working directory. That seemed to fix everything.

Body:
I'm familiar with ggplot in R. Using RStudio, a plot would be produced in the bottom right window.

If I try to run a python program to generate a ggplot, nothing happens in my terminal. The code runs without error, but nothing is produced. Am I missing something?

Matplot seems to work fine, and produces a plot.

I'm using Fedora 32, python 3.8, and ggplot found on pip.

from ggplot import *
import pandas

data = pandas.read_csv(
    "path-to-data")
g = ggplot(data,  aes('TIMEn', 'ENTRIESn_hourly')) + \
    geom_point() + stat_smooth(method="lm")
g

UPDATE: OK, I think part of the problem was the size of the data in the csv. I can get a plot produced now, but only if I run the code line by line in terminal. Nothing will be produced if I run "python filename.py"


问:
Generator for random long hex strings in PHP
I have written a generator of strings, but I don't know how to create a random hex string with length, for instance 100 digits, for inserting into a database. All these strings have to be same length.

How can I generate random hex strings?

答:
I like to a have single general function that can handle similar situations. By that I mean a function which receives both the requried length of the generated string and the possible characters that can occure in it.

That way a single function can create: 40-digit decimal number, 16-digit uppercase hex number, 100 letter lowercase string, etc...

Here is my implementation:

```<code>/**
 * Generate a random string.
 *
 * @param int    $length Length of the generated string.
 * @param string $chars  The string containing all of the available characters.
 *
 * @return string The generated string.
 */
function getRandomString($length = 10, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
    $str = '';

    $size = strlen($chars);
    for ($i = 0; $i < $length; $i++) {
        $str .= $chars[mt_rand(0, $size - 1)];
    }

    return $str;
}
</code>```

IMPORTANT: Do not use this function to generate random string for any security purpose. For a secure string generator check out the answer from @danorton.

Body:
I like to a have single general function that can handle similar situations. By that I mean a function which receives both the requried length of the generated string and the possible characters that can occure in it.

That way a single function can create: 40-digit decimal number, 16-digit uppercase hex number, 100 letter lowercase string, etc...

Here is my implementation:

/**
 * Generate a random string.
 *
 * @param int    $length Length of the generated string.
 * @param string $chars  The string containing all of the available characters.
 *
 * @return string The generated string.
 */
function getRandomString($length = 10, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
    $str = '';

    $size = strlen($chars);
    for ($i = 0; $i < $length; $i++) {
        $str .= $chars[mt_rand(0, $size - 1)];
    }

    return $str;
}

IMPORTANT: Do not use this function to generate random string for any security purpose. For a secure string generator check out the answer from @danorton.


问:
Generate a plaintext file from list of words on a webpage
I am trying to generate a plain text file containing a list of words that is on a webpage. The problem is that the list is divided into multiple pages.

http://www.whonamedit.com/eponyms/A/?start=50&maxrows=25

This is what I mean. Like for the letter A, I need all 13 pages of words and I also need every letter of the alphabet.

I was thinking of maybe modifying a webcrawler to do this task, would that be the easiest way?

I prefer Java, but Python is ok.

Sorry if the answer is obvious, but any nudges in the right direction would be SO GREATLY appreciated!!

答:
Assuming this is specifically for the whonamedit website, you can do the following:</p>

```<code>List<String>getWordsOnPage(String url) {
  // read words within <ul class="result-list"> element.
}

void getAllWords() {
  List<String> all = new ArrayList<String>();
  for (char letter = 'A'; letter <= 'Z'; ++letter) {
    for (int start = 0; true; start += 25) {
      List<String> page = getWordsOnPage("http://www.whonamedit.com/eponyms/" + letter + "/?start=" + start + "&maxrows=25");
      if (page.isEmpty()) {
        break;
      }
      all.addAll(page);
    }
  }
}
</code>```

Body:
Assuming this is specifically for the whonamedit website, you can do the following:

List<String>getWordsOnPage(String url) {
  // read words within <ul class="result-list"> element.
}

void getAllWords() {
  List<String> all = new ArrayList<String>();
  for (char letter = 'A'; letter <= 'Z'; ++letter) {
    for (int start = 0; true; start += 25) {
      List<String> page = getWordsOnPage("http://www.whonamedit.com/eponyms/" + letter + "/?start=" + start + "&maxrows=25");
      if (page.isEmpty()) {
        break;
      }
      all.addAll(page);
    }
  }
}


问:
Save local file from MS SQL varbinary
I'm trying to save a local document stored in SQL db using UiPath.
From the execute query activity it returns a DataTable value with one column(“Data”).

If I'm not wrong somehow I need to transform the DataTable.rows(0)(“Data”) (studio is interpreting it as object) to an array of bytes.

I used invoke code but the file is broken:

```<code>Dim _MemoryStream As New System.IO.MemoryStream()
Dim _BinaryFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
_BinaryFormatter.Serialize(_MemoryStream, inputObj)
_MemoryStream.ToArray()

File.WriteAllBytes(“C:\Users\Desktop\test.tiff”, _MemoryStream.ToArray())
</code>```

答:
Unless you serialised an object when saving, which I doubt, there's no reason to try to deserialise an object when retrieving. Every field from a DataRow is returned as an Object reference, because it must support any type of object, but that object still has its own type. If you saved binary data then that type will be Byte(), i.e. a Byte array. Kinda looks like File.WriteAllBytes takes a Byte array:

File.WriteAllBytes(“C:\Users\Desktop\test.tiff”, DirectCast(inputObj, Byte()))
```

That is what I would expect that you need to do. It does depend on how you saved the data in the first place but if you used File.ReadAllBytes or Image.Save then this should do the job. If not, show us how you sabed the data in the first place.

Title: Save local file from MS SQL varbinary

Body:
I'm trying to save a local document stored in SQL db using UiPath.
From the execute query activity it returns a DataTable value with one column(“Data”).

If I'm not wrong somehow I need to transform the DataTable.rows(0)(“Data”) (studio is interpreting it as object) to an array of bytes.

I used invoke code but the file is broken:

Dim _MemoryStream As New System.IO.MemoryStream()
Dim _BinaryFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
_BinaryFormatter.Serialize(_MemoryStream, inputObj)
_MemoryStream.ToArray()

File.WriteAllBytes(“C:\Users\Desktop\test.tiff”, _MemoryStream.ToArray())

Body:
Unless you serialised an object when saving, which I doubt, there's no reason to try to deserialise an object when retrieving. Every field from a DataRow is returned as an Object reference, because it must support any type of object, but that object still has its own type. If you saved binary data then that type will be Byte(), i.e. a Byte array. Kinda looks like File.WriteAllBytes takes a Byte array:

File.WriteAllBytes(“C:\Users\Desktop\test.tiff”, DirectCast(inputObj, Byte()))

That is what I would expect that you need to do. It does depend on how you saved the data in the first place but if you used File.ReadAllBytes or Image.Save then this should do the job. If not, show us how you sabed the data in the first place.


问:
NPM is giving me an error using npm install
A friend shared with me a theme he is developing for WordPress, and I cloned his repo in my /themes folder, first thing I tried was to run "npm install" in the theme folder in order to get gulp and other npm cool features.

This is what it returns:

```<code>$ npm install
npm ERR! code EINTEGRITY
npm ERR! sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc= integrity checksum failed when using sha1: wanted sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc= but got sha512-kV/CThkXo6xyFEZUugw/+pIOywXcDbFYgSct5cT3gqlbkBE1SJdwy6UQoZvodiWF/ckQLZyDE/Bu1M6gVu5lVw== sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=. (36808 bytes)

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\rinor\AppData\Roaming\npm-cache\_logs\2020-04-04T17_30_54_859Z-debug.log
</code>```

After trying installing it globally it gave me back the same error so I came up with uninstalling node.js from my pc and then download and install the LTS version (12.16.1). Rebooted, tested and it seemed to work as I tried typing "node -v" && "npm -v". But when I return to my theme and go for "npm install" it gives me the same error.

Here is my package.json content

```<code>{
  "name": "ruce-theme",
  "version": "1.0.0",
  "description": "A starter theme",
  "scripts": {
    "watch": "gulp watch"
  },
  "dependencies": {
    "bootstrap": "^4.0.0-beta.3",
    "jquery": "^3.2.1",
    "npm": "^6.4.1",
    "slick-carousel": "^1.8.1"
  },
  "devDependencies": {
    "@babel/core": "^7.3.3",
    "@babel/preset-env": "^7.3.1",
    "@babel/preset-react": "^7.0.0",
    "babel-core": "^6.25.0",
    "babel-loader": "^8.0.5",
    "babel-plugin-transform-react-jsx": "^6.24.1",
    "babel-preset-env": "^1.6.0",
    "cross-env": "^5.0.1",
    "css-loader": "^2.1.0",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "file-loader": "^3.0.1",
    "gulp": "^4.0.0",
    "gulp-babel": "^8.0.0-beta.2",
    "gulp-clean-css": "^3.9.1",
    "gulp-clone": "^1.1.4",
    "gulp-concat": "^2.6.1",
    "gulp-cssnano": "^2.1.2",
    "gulp-ignore": "^2.0.2",
    "gulp-imagemin": "^4.0.0",
    "gulp-merge": "^0.1.1",
    "gulp-plumber": "^1.2.0",
    "gulp-rename": "^1.2.2",
    "gulp-rimraf": "^0.2.2",
    "gulp-sass": "^3.1.0",
    "gulp-sequence": "^0.4.6",
    "gulp-sourcemaps": "2.6.2",
    "gulp-uglify": "^3.0.0",
    "gulp-watch": "^4.3.11",
    "node-sass": "^4.11.0",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.29.0",
    "webpack-cli": "^3.2.1"
  },
  "license": "ISC"
}
</code>```

These are the erros that the debug shows

```<code>20111 error code EINTEGRITY
20112 error sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc= integrity checksum failed when using sha1: wanted sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc= but got sha512-kV/CThkXo6xyFEZUugw/+pIOywXcDbFYgSct5cT3gqlbkBE1SJdwy6UQoZvodiWF/ckQLZyDE/Bu1M6gVu5lVw== sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=. (36808 bytes)
20113 verbose exit [ 1, true ]
</code>```

答:
You don't mention whether you had package-lock.json or not. In some cases the following might help. But first make sure you understand what's going on. npm tells you that the checksum from https://registry.npm.org doesn't match the one from package-lock.json. Either it changed in the registry, or...

Solution Consider the line from the output:

```<code>npm ERR!
  sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc=
integrity checksum failed when using sha1: wanted
  sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc=
but got
  sha512-kV/CThkXo6xyFEZUugw/+pIOywXcDbFYgSct5cT3gqlbkBE1SJdwy6UQoZvodiWF/ckQLZyDE/Bu1M6gVu5lVw== sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=
. (36808 bytes)
</code>```

Find the package in package-lock.json by the first two integrity checksums (sha1-...), and put the third one (sha512-...) into its "integrity" field.

More on it here.

Body:
A friend shared with me a theme he is developing for WordPress, and I cloned his repo in my /themes folder, first thing I tried was to run "npm install" in the theme folder in order to get gulp and other npm cool features.

This is what it returns:

$ npm install
npm ERR! code EINTEGRITY
npm ERR! sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc= integrity checksum failed when using sha1: wanted sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc= but got sha512-kV/CThkXo6xyFEZUugw/+pIOywXcDbFYgSct5cT3gqlbkBE1SJdwy6UQoZvodiWF/ckQLZyDE/Bu1M6gVu5lVw== sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=. (36808 bytes)

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\rinor\AppData\Roaming\npm-cache\_logs\2020-04-04T17_30_54_859Z-debug.log

After trying installing it globally it gave me back the same error so I came up with uninstalling node.js from my pc and then download and install the LTS version (12.16.1). Rebooted, tested and it seemed to work as I tried typing "node -v" && "npm -v". But when I return to my theme and go for "npm install" it gives me the same error.

Here is my package.json content

{
  "name": "ruce-theme",
  "version": "1.0.0",
  "description": "A starter theme",
  "scripts": {
    "watch": "gulp watch"
  },
  "dependencies": {
    "bootstrap": "^4.0.0-beta.3",
    "jquery": "^3.2.1",
    "npm": "^6.4.1",
    "slick-carousel": "^1.8.1"
  },
  "devDependencies": {
    "@babel/core": "^7.3.3",
    "@babel/preset-env": "^7.3.1",
    "@babel/preset-react": "^7.0.0",
    "babel-core": "^6.25.0",
    "babel-loader": "^8.0.5",
    "babel-plugin-transform-react-jsx": "^6.24.1",
    "babel-preset-env": "^1.6.0",
    "cross-env": "^5.0.1",
    "css-loader": "^2.1.0",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "file-loader": "^3.0.1",
    "gulp": "^4.0.0",
    "gulp-babel": "^8.0.0-beta.2",
    "gulp-clean-css": "^3.9.1",
    "gulp-clone": "^1.1.4",
    "gulp-concat": "^2.6.1",
    "gulp-cssnano": "^2.1.2",
    "gulp-ignore": "^2.0.2",
    "gulp-imagemin": "^4.0.0",
    "gulp-merge": "^0.1.1",
    "gulp-plumber": "^1.2.0",
    "gulp-rename": "^1.2.2",
    "gulp-rimraf": "^0.2.2",
    "gulp-sass": "^3.1.0",
    "gulp-sequence": "^0.4.6",
    "gulp-sourcemaps": "2.6.2",
    "gulp-uglify": "^3.0.0",
    "gulp-watch": "^4.3.11",
    "node-sass": "^4.11.0",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.29.0",
    "webpack-cli": "^3.2.1"
  },
  "license": "ISC"
}

These are the erros that the debug shows

20111 error code EINTEGRITY
20112 error sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc= integrity checksum failed when using sha1: wanted sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc= but got sha512-kV/CThkXo6xyFEZUugw/+pIOywXcDbFYgSct5cT3gqlbkBE1SJdwy6UQoZvodiWF/ckQLZyDE/Bu1M6gVu5lVw== sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=. (36808 bytes)
20113 verbose exit [ 1, true ]

Body:
You don't mention whether you had package-lock.json or not. In some cases the following might help. But first make sure you understand what's going on. npm tells you that the checksum from https://registry.npm.org doesn't match the one from package-lock.json. Either it changed in the registry, or...

Solution Consider the line from the output:

npm ERR!
  sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc=
integrity checksum failed when using sha1: wanted
  sha1-fjL3W0e4epHQRhHxvxQQmsAGUdc=
but got
  sha512-kV/CThkXo6xyFEZUugw/+pIOywXcDbFYgSct5cT3gqlbkBE1SJdwy6UQoZvodiWF/ckQLZyDE/Bu1M6gVu5lVw== sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=
. (36808 bytes)

Find the package in package-lock.json by the first two integrity checksums (sha1-...), and put the third one (sha512-...) into its "integrity" field.

More on it here.


问:
jquery how to figure out what the JSON Object contains
I'm using JQuery with CodeIgniter PHP to figure make AJAX calls and return data via JSON. I want to figure out what my JSON object has returned, but I'm not sure what the syntax might be. Is there a way to just alert or log all the contents of the JSON object somehow? This is my code:

```<code>$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
        alert (parent);
    }
});
</code>```

If I do this - I get an object, but I don't know what it contains.

答: You can use firebug and set a breakpoint in the success method, then you'll be able to look at the json object. </p>

Body:
I'm using JQuery with CodeIgniter PHP to figure make AJAX calls and return data via JSON. I want to figure out what my JSON object has returned, but I'm not sure what the syntax might be. Is there a way to just alert or log all the contents of the JSON object somehow? This is my code:

$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
        alert (parent);
    }
});

If I do this - I get an object, but I don't know what it contains.


问:
Run python script inside bash file in Windows
I was tasked with running a script developed by someone else. It's quite simple, but it's a bash script and I had almost never touched Linux, so I'm not sure on how to proceed. I was able to install WLS so I can run bash on Windows, but now I have to run a specific python script inside the bash script. The script goes like this:

```<code>#!/bin/bash
BASE_DIR=dir

find $BASE_DIR -type f | grep '\.pdf' | while read pdf_filename; do
  filebase=`echo $pdf_filename | cut -d '.' -f 1`
  txt_filename="$filebase.txt"
  echo "Processing $pdf_filename..."
  pdf2txt.py $pdf_filename > $txt_filename
  echo "Done!"

done
</code>```

It should run the pdf2txt.py script, but I'm getting this error:

```<code>convert_all.sh: line 8: pdf2txt.py: command not found
</code>```

So, I'm not sure how to connect bash to my Python installation, I'm guessing it's not being able to find it. I would ideally  like to link it to this project's virtual environment . Any ideas on how to proceed?

Edit:

This is my current error based on what I responded to @DV82XL:

```<code>/mnt/c/Users/jeco_/Desktop/Otros repositorios/sesgo_medios/Code/hello.py: line 1: $'\r': command not found
/mnt/c/Users/jeco_/Desktop/Otros repositorios/sesgo_medios/Code/hello.py: line 2: syntax error near unexpected token `"hello world"'
/mnt/c/Users/jeco_/Desktop/Otros repositorios/sesgo_medios/Code/hello.py: line 2: `print("hello world")'
</code>```

答:
Can you convert the bash script to Python? That way you can easily run in Windows or Linux without WSL.

If you must run the bash script in WSL, make sure Python is installed in WSL:

Type type -a python or type -a python3. This will give you the interpreter path.

If it doesn't show up, you will need to install Python on WSL:

sudo apt update && upgrade
sudo apt install python3 python3-pip ipython3
```

Then do these things:

Make sure the Python interpreter is in the PATH env var by typing echo $PATH. If it's not there, add it by typing export PATH="$PATH:/usr/bin/python3" or add it to ~/.profile. On Linux, it's usually included by default.

Add the path to the script to PATH env var if you want to run it from anywhere

Type python --version or python3 --version to get versions and make sure python path was set correctly.

Add a shebang with the interpreter path at the start of the python script:

#!/path/to/interpreter

Typically: #!/usr/bin/python3

For specific interpreter version: #!/usr/bin/python2.7

Make the script executable: chmod +x pdf2txt.py

Now you should be able to run pdf2txt.py directly instead of python pdf2txt.py.

Hint: In WSL, you can access your Windows files at /mnt/c/Users/<user>/path/to/file if you need to.

If this doesn't work, please let us know which Linux distro/version you are running and what version of Python these scripts require.

Body:
I was tasked with running a script developed by someone else. It's quite simple, but it's a bash script and I had almost never touched Linux, so I'm not sure on how to proceed. I was able to install WLS so I can run bash on Windows, but now I have to run a specific python script inside the bash script. The script goes like this:

#!/bin/bash
BASE_DIR=dir

find $BASE_DIR -type f | grep '\.pdf' | while read pdf_filename; do
  filebase=`echo $pdf_filename | cut -d '.' -f 1`
  txt_filename="$filebase.txt"
  echo "Processing $pdf_filename..."
  pdf2txt.py $pdf_filename > $txt_filename
  echo "Done!"

done

It should run the pdf2txt.py script, but I'm getting this error:

convert_all.sh: line 8: pdf2txt.py: command not found

So, I'm not sure how to connect bash to my Python installation, I'm guessing it's not being able to find it. I would ideally  like to link it to this project's virtual environment . Any ideas on how to proceed?

Edit:

This is my current error based on what I responded to @DV82XL:

/mnt/c/Users/jeco_/Desktop/Otros repositorios/sesgo_medios/Code/hello.py: line 1: $'\r': command not found
/mnt/c/Users/jeco_/Desktop/Otros repositorios/sesgo_medios/Code/hello.py: line 2: syntax error near unexpected token `"hello world"'
/mnt/c/Users/jeco_/Desktop/Otros repositorios/sesgo_medios/Code/hello.py: line 2: `print("hello world")'

Body:
Can you convert the bash script to Python? That way you can easily run in Windows or Linux without WSL.

If you must run the bash script in WSL, make sure Python is installed in WSL:

Type type -a python or type -a python3. This will give you the interpreter path.

If it doesn't show up, you will need to install Python on WSL:

sudo apt update && upgrade
sudo apt install python3 python3-pip ipython3

Then do these things:

Make sure the Python interpreter is in the PATH env var by typing echo $PATH. If it's not there, add it by typing export PATH="$PATH:/usr/bin/python3" or add it to ~/.profile. On Linux, it's usually included by default.

Add the path to the script to PATH env var if you want to run it from anywhere

Type python --version or python3 --version to get versions and make sure python path was set correctly.

Add a shebang with the interpreter path at the start of the python script:

#!/path/to/interpreter

Typically: #!/usr/bin/python3

For specific interpreter version: #!/usr/bin/python2.7

Make the script executable: chmod +x pdf2txt.py

Now you should be able to run pdf2txt.py directly instead of python pdf2txt.py.

Hint: In WSL, you can access your Windows files at /mnt/c/Users/<user>/path/to/file if you need to.

If this doesn't work, please let us know which Linux distro/version you are running and what version of Python these scripts require.


问:
How to inflate progressBar layout without code duplication when there is an api call
I have this flow in my app:

declare endpoints:

```<code>public interface EndPoints {
    @GET(Constants.POPULAR)
    Call<AllData> getAllData(
            @Query("api_key") String apiKey
    );
}
</code>```

Retrofit service:

```<code>  private static EndPoints endPoints = retrofit.create(EndPoints.class);

    public static EndPoints getEndpoints() {
        return  endPoints ;
    }
</code>```

And I call this inside my view model:

```<code>   private void getDataFromApi() {
    Call<AllData> call = RetrofitService.getEndPoints().getAllData(Constants.API_KEY);
    call.enqueue(new Callback<AllData>() {
        @Override
        public void onResponse(Call<AllData> call, Response<AllData> response) {

        }
            if (response.isSuccessful()) {
                _allData.setValue(response.body());
        }

        @Override
        public void onFailure(Call<AllData> call, Throwable t) {
        }
    });

}
</code>```

Base Activity:

```<code>public abstract class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
    }
</code>```

Progress bar layout(I updated this instead of using frame layout every xml file, I created xml called progress bar layout and I want to inflate this every call):

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>
</FrameLayout>
</code>```

How can I set progress bar every api call?

Initally I checked in getDataFromApi if is loading or not, set the value into bool LiveData and observed this inside my activity.

The problem with this is it's an insane amount of code duplication.

Every api call I need to set loading state, every activity I need to observer the loading state and call View.Visible and View.Hide and every activity xml I need to create frame layout with progress bar.

I believe the answer is somewhere inside the base activity as it is the only place that can "control" all the activities in the app, but I can't think of a way of solving this problem

答:
Create a list to save all of your fragment and listen on the status:</p>

```<code>List<FrameLayout> frameLayoutList = new ArrayList<>();
// register you own FrameLayout
frameLayoutList.add(frameLayout);

mainViewModel.getStaus().observe(this, new Observer<MainViewModel.Status>() {
    @Override
    public void onChanged(MainViewModel.Status status) {
        if (status == MainViewModel.Status.LOADING) {
            for (FrameLayout frameLayout : frameLayoutList) {
                frameLayout.setVisibility(View.VISIBLE);
            }
        } else {
            for (FrameLayout frameLayout : frameLayoutList) {
                frameLayout.setVisibility(View.GONE);
            }
            frameLayout.setVisibility(View.GONE);
        }
    }
});
</code>```

Body:
I have this flow in my app:

declare endpoints:

public interface EndPoints {
    @GET(Constants.POPULAR)
    Call<AllData> getAllData(
            @Query("api_key") String apiKey
    );
}

Retrofit service:

  private static EndPoints endPoints = retrofit.create(EndPoints.class);

    public static EndPoints getEndpoints() {
        return  endPoints ;
    }

And I call this inside my view model:

   private void getDataFromApi() {
    Call<AllData> call = RetrofitService.getEndPoints().getAllData(Constants.API_KEY);
    call.enqueue(new Callback<AllData>() {
        @Override
        public void onResponse(Call<AllData> call, Response<AllData> response) {

        }
            if (response.isSuccessful()) {
                _allData.setValue(response.body());
        }

        @Override
        public void onFailure(Call<AllData> call, Throwable t) {
        }
    });

}

Base Activity:

public abstract class BaseActivity extends AppCompatActivity {

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

Progress bar layout(I updated this instead of using frame layout every xml file, I created xml called progress bar layout and I want to inflate this every call):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>
</FrameLayout>

How can I set progress bar every api call?

Initally I checked in getDataFromApi if is loading or not, set the value into bool LiveData and observed this inside my activity.

The problem with this is it's an insane amount of code duplication.

Every api call I need to set loading state, every activity I need to observer the loading state and call View.Visible and View.Hide and every activity xml I need to create frame layout with progress bar.

I believe the answer is somewhere inside the base activity as it is the only place that can "control" all the activities in the app, but I can't think of a way of solving this problem

Body:
Create a list to save all of your fragment and listen on the status:

List<FrameLayout> frameLayoutList = new ArrayList<>();
// register you own FrameLayout
frameLayoutList.add(frameLayout);

mainViewModel.getStaus().observe(this, new Observer<MainViewModel.Status>() {
    @Override
    public void onChanged(MainViewModel.Status status) {
        if (status == MainViewModel.Status.LOADING) {
            for (FrameLayout frameLayout : frameLayoutList) {
                frameLayout.setVisibility(View.VISIBLE);
            }
        } else {
            for (FrameLayout frameLayout : frameLayoutList) {
                frameLayout.setVisibility(View.GONE);
            }
            frameLayout.setVisibility(View.GONE);
        }
    }
});


问:
Why does a MySql query, valid in Workbench, return syntax errors in phpmyadmin?
so i have 2 tables as table1 and table2 in 2 different databases as id_information and id_information_backup. Both the tables have the following columns: (id bigint, name varchar, surname varchar) I made this trigger where when the user enters name and surname in table1 , it calculates the ascii code of it and do some calculations and store it in the "name" column of the second table which is "table2". All of these has been done in Mysql workbench. when i import the code into phpmyadmin then it gives me too many syntax errors. I tried to figure what syntax errors do i have but i could not find. I am sharing the trigger below. Kindly help me if you can. I will really appreciate it. I guess it is because of the version that i used is MySQL workbench 8.0 and the version that i am importing this into is PHPmyadmin 4.9.4 . Fix the problem if you can please. </p>

```<code>delimiter $$
CREATE DEFINER = CURRENT_USER TRIGGER `id_information`.`table1_after_INSERT1` AFTER INSERT ON `table1` FOR EACH ROW
BEGIN
declare p , r , copy, result, result1 decimal(64,0);
declare name1, surnam varchar(15);
declare a int;
set name1 = new.name;
set surnam = new.surname;
set a= 100;
set result =0;
set copy = 0;
set result1 =0;
set p =0 ;
set r =0 ;
with recursive cte as (
    select name1 as name1, left(name1, 1) as val, 1 as idx
    union all
    select name1, substring(name1, idx + 1, 1), idx + 1
    from cte
    where idx < char_length(name1)
)
select group_concat(ascii(val) + a order by idx separator '') ascii_word from cte into result;
with recursive ctee as (
    select surnam as surnam, left(surnam, 1) as vall , 1 as idxx
    union all
    select surnam, substring(surnam, idxx+ 1, 1), idxx+ 1
    from ctee
    where idxx< char_length(surnam)
)
select group_concat(ascii(vall )  + a order by idxx separator '') ascii_word from ctee into result1;
select group_concat(result, result1) into copy;
insert into id_information_backup.table2  set table2.name = copy;
END$$
delimiter ;
</code>```

答:
In PHPMyAdmin you need to set up delimiter in a small box under the main query

It should be signed as "Delimiter" ;-)

I ended getting caught by that one a few time :-D

Body:
so i have 2 tables as table1 and table2 in 2 different databases as id_information and id_information_backup. Both the tables have the following columns: (id bigint, name varchar, surname varchar) I made this trigger where when the user enters name and surname in table1 , it calculates the ascii code of it and do some calculations and store it in the "name" column of the second table which is "table2". All of these has been done in Mysql workbench. when i import the code into phpmyadmin then it gives me too many syntax errors. I tried to figure what syntax errors do i have but i could not find. I am sharing the trigger below. Kindly help me if you can. I will really appreciate it. I guess it is because of the version that i used is MySQL workbench 8.0 and the version that i am importing this into is PHPmyadmin 4.9.4 . Fix the problem if you can please.

delimiter $$
CREATE DEFINER = CURRENT_USER TRIGGER `id_information`.`table1_after_INSERT1` AFTER INSERT ON `table1` FOR EACH ROW
BEGIN
declare p , r , copy, result, result1 decimal(64,0);
declare name1, surnam varchar(15);
declare a int;
set name1 = new.name;
set surnam = new.surname;
set a= 100;
set result =0;
set copy = 0;
set result1 =0;
set p =0 ;
set r =0 ;
with recursive cte as (
    select name1 as name1, left(name1, 1) as val, 1 as idx
    union all
    select name1, substring(name1, idx + 1, 1), idx + 1
    from cte
    where idx < char_length(name1)
)
select group_concat(ascii(val) + a order by idx separator '') ascii_word from cte into result;
with recursive ctee as (
    select surnam as surnam, left(surnam, 1) as vall , 1 as idxx
    union all
    select surnam, substring(surnam, idxx+ 1, 1), idxx+ 1
    from ctee
    where idxx< char_length(surnam)
)
select group_concat(ascii(vall )  + a order by idxx separator '') ascii_word from ctee into result1;
select group_concat(result, result1) into copy;
insert into id_information_backup.table2  set table2.name = copy;
END$$
delimiter ;


问:
How to get BouncingScrollPhysics overscroll value offset?
For example, I have SingleChildScrollView with BouncingScrollPhysics.
I want something like print(_overscrollOffsetValue) when content jumps from edge, e.g. the more offset value of overscroll, the bigger _overscrollOffsetValue.

答:
You can listen for ScrollUpdateNotification:</p>

```<code>NotificationListener<ScrollNotification>(
  onNotification: (notification) {
    if (notification is ScrollUpdateNotification) {
      final offset = notification.metrics.pixels;
      if (offset < 0) {
        print(offset.abs());
      }
    }
    return false;
  },
  child: SingleChildScrollView(
    physics: BouncingScrollPhysics(),
    child: Text('A' * 10000),
  ),
)
</code>```

Body:
You can listen for ScrollUpdateNotification:

NotificationListener<ScrollNotification>(
  onNotification: (notification) {
    if (notification is ScrollUpdateNotification) {
      final offset = notification.metrics.pixels;
      if (offset < 0) {
        print(offset.abs());
      }
    }
    return false;
  },
  child: SingleChildScrollView(
    physics: BouncingScrollPhysics(),
    child: Text('A' * 10000),
  ),
)