问:
Is it possible to use a function to push the document.getElementByID().innerHTML to an HTML file?
I am back with another question for the community. I know there are a lot of questions and answers on the subject of document.getElementByID(), but I cannot find anything that points me to the path I am looking for, and it may just not exist.

In my text based javascript game, I have a LOT of span's and am looking to shorten the length of code, as for every instance of declaring and changing the variable inside an object, to push it to the HTML page, I am having to spam the use of document.getElementByID().

For instance, in my HTML file I have:

```<code><div id="attributes">
                <div id="main_attributes">
                    <p>
                        Name: <span id="Player.Name">0</span>   Gender: <span id="Player.Gender">0</span><br />
                        Class: <span id="Player.ClassType">0</span><br /><br />
                        Health: <span id="Player.Health">0</span><br />
                        Mana: <span id="Player.Mana">0</span><br />
                        Strength: <span id="Player.Strength">0</span><br/>
                        Defense: <span id="Player.Defense">0</span><br />
                        Endurance: <span id="Player.Endurance">0</span><br />
                        Intelligence: <span id="Player.Intelligence">0</span><br />
                        Current Location: <span id="currentarea">0</span>
                    </p>
                </div>
            </div>
</code>```

With which I have made an object "Player" from a Hero prototype:

```<code>function Hero(Gender, Sexiness, Name, classType, Health, Mana, Strength, Defense, Endurance, Intelligence, Friend, Gold, BattleHealth, BattleMana, BattleStamina,  Experience, Level, Karma,) {
    this.Gender = Gender;
    this.Sexiness = Sexiness;
    this.Name = Name;
    this.ClassType = classType;
    this.Health = Health;
    this.Mana = Mana;
    this.Strength = Strength;
    this.Defense = Defense;
    this.Endurance = Endurance;
    this.Intelligence = Intelligence;
    this.Friend = Friend;
    this.Gold = Gold;
    this.BattleHealth = BattleHealth;
    this.BattleMana = BattleMana;
    this.BattleStamina = BattleStamina;
    this.Experience = Experience;
    this.Level = Level;
    this.Karma = Karma;
}
let Player = new Hero("Spirit", 0, "Spirit", "Undetermined One", 0, 0, 0, 0, 0, 0, "None", 10, 0, 0, 0, 0, 1, 0);
</code>```

Defined some constants:

```<code>const Male = {
    Type: "Male",
    Health: 100,
    Mana: 20,
    Strength: 20,
    Defense: 5,
    Endurance: 15,
    Intelligence: 5,
    Sexiness: 1,
    Friend: "Duncan",
}
const Female = {
    Type: "Female",
    Health: 80,
    Mana: 60,
    Strength: 16,
    Defense: 4,
    Endurance: 12,
    Intelligence: 10,
    Sexiness: 2,
    Friend: "Morgana",
}
</code>```

And a gender assign function:

```<code>function genderAssign() {
    switch (Player.Gender) {
        case "Male":
            Player.Gender = Male.Type;
            Player.Health = Male.Health;
            Player.Mana = Male.Mana;
            Player.Strength = Male.Strength;
            Player.Defense = Male.Defense;
            Player.Endurance = Male.Endurance;
            Player.Intelligence = Male.Intelligence;
            Player.Sexiness = Male.Sexiness;
            Player.Friend = Male.Friend;
            Armor.UpperClothesName = "Chest";
            Armor.LowerClothesName = "Fig Leaves";
            Armor.HelmetName = "Head";
            Armor.BodyName = "Body";
            Armor.ArmName = "Arms";
            Armor.WaistName = "None";
            Armor.LegName = "Legs";
            Armor.BootsName = "Feet";
            Weapons.RightHand = "Right Hand";
            Weapons.LeftHand = "Left Hand";
            Armor.LegCoveringsName = "Hair";
            break;
        case "Female":
            Player.Gender = Female.Type;
            Player.Health = Female.Health;
            Player.Mana = Female.Mana;
            Player.Strength = Female.Strength;
            Player.Defense = Female.Defense;
            Player.Endurance = Female.Endurance;
            Player.Intelligence = Female.Intelligence;
            Player.Sexiness = Female.Sexiness;
            Armor.UpperClothesName = "Nip Coverings";
            Armor.LowerClothesName = "Fig Leaves";
            Armor.HelmetName = "Head";
            Armor.BodyName = "Body";
            Armor.ArmName = "Arms";
            Armor.WaistName = "None";
            Armor.LegName = "Legs";
            Armor.BootsName = "Feet";
            Weapons.RightHand = "Right Hand";
            Weapons.LeftHand = "Left Hand";
            Armor.LegCoveringsName = "Smooth Legs";
            Player.Friend = Female.Friend;
            break;
        default:
    }
    return;
}
</code>```

I don't want to have to do something as follows:

```<code>            Player.Gender = Male.Type;
            document.getElementByID("Male.Type").innerHTML = Male.Type
            Player.Health = Male.Health;
            document.getElementByID("Male.Health").innerHTML = Male.Health
            Player.Mana = Male.Mana;
            document.getElementByID("Male.Mana").innerHTML = Male.Mana
</code>```

And so on...
Is there a way to do something like:

```<code>function printPlayer() {

    Player.Gender = $('#Player.Gender');
    Player.Sexiness = $('#Player.Sexiness');
    Player.Health = $('#Player.Health');
    Player.Mana = $('#Player.Mana');
    Player.Strength = $('#Player.Strength');
    Player.Defense = $('#Player.Defense');
    Player.Endurance = $('#Player.Endurance');
    Player.Intelligence = $('#Player.Intelligence');
    Player.Friend = $('#Player.Friend');
    Player.Gold = $('#Player.Gold');
    Player.Experience = $('#Player.Experience');
    Player.Level = $('#Player.Level');
    Player.ClassType = $('#Player.ClassType');
}
</code>```

OR

```<code>function printPlayer() {

    document.getElementById("Player.Sexiness").innerHTML = Player.Sexiness;
    document.getElementById("Player.Health").innerHTML = Player.Health;
    document.getElementById("Player.Mana").innerHTML = Player.Mana;
    document.getElementById("Player.Strength").innerHTML = Player.Strength;
    document.getElementById("Player.Defense").innerHTML = Player.Defense;
    document.getElementById("Player.Endurance").innerHTML = Player.Endurance;
    document.getElementById("Player.Intelligence").innerHTML = Player.Intelligence;
    document.getElementById("Player.Friend").innerHTML = Player.Friend;
    document.getElementById("Player.Gold").innerHTML = Player.Gold;
    document.getElementById("Player.Experience").innerHTML = Player.Experience;
    document.getElementById("Player.Level").innerHTML = Player.Level;
    document.getElementById("Player.ClassType").innerHTML = Player.ClassType;
}
</code>```

And call it from within, say the genderAssign() function?

Sorry if this is a bit lengthy, but I'd rather give you a broader scope of what I am doing rather than leave it to guessing. I have tried the above functions, and neither seem to work. The error is:

```<code>TypeError: document.getElementById(...) is nullUpdatePlayerCharacter.js:22:14

printPlayer file:///C:/Users/Melseph/Desktop/Game Design/PhoenixDestitute/scripts/UpdatePlayerCharacter.js:22

genderAssign file:///C:/Users/Melseph/Desktop/Game Design/PhoenixDestitute/scripts/CharacterStats.js:78

<anonymous> file:///C:/Users/Melseph/Desktop/Game Design/PhoenixDestitute/scripts/PhoenixDestitute.js:45
jQuery 2
</code>```

Which I am assuming is because I don't have the values inside the printPlayer() function, but there in is where I am stuck and cannot find anymore direction. Is it just impossible to do it the way I am trying?

--Edit--

I always seem to leave this part out, which is why I think everyone tends to want to point towards a button, which is my mistake, sorry...

I have a form for the user to answer questions and a window that shows updates the player makes, and I had it all working with added document.getElementByID()... which (of course) killed it when I took those out. I can see through console.log(Player) that all the items are being updated in the Player object, but I cannot find an easier method of pushing the innerHTML to the HTML file.

Here is what my code is for the console id and a screenshot:

```<code><div class="console">
<div id="console_wrapper">
    <div id="console">
        <p>Would you like to begin your adventure? Type <u><b>yes</b></u> or <u><b>no</b></u>.</p>
        <!--
        PLACEHOLDER: THIS IS WHERE YOUR CHOICES ARE INPUT
        -->
        <div id="placeholder"></div>
    </div>
</div>
<form id="form" onsubmit="return false;">
    <input type="text" autocomplete="off" id="command_line" placeholder="User Input Here" autofocus="autofocus" />
</form>
</code>```

```<code>$(document).ready(function() {
$("#console").fadeIn(3000); //Console fades in.
$(document).keypress(function(key) { //When a key is press:
    if (key.which === 13 && $('#command_line').is(':focus')) { //If enter key is pressed and the focus is on the command line:
        var input = $('#command_line').val().toLowerCase(); //Express what is in the command line in lower case.
        $('#command_line').val(""); //Erase the value of what is shown in the command box.
        $("#console").animate({ scrollTop: "999999999px" }, 'slow'); //Scroll the console to the bottom.
     }
}
</code>```

Not sure if this changes the answer to my question any, or if the use of a button is the only method.

答:
This snippet should give you some ideas for handling properties of your Player object, including showing them on the page.

(See the in-code comments for explanations of particular features of the script.)

//Identifies button for demo
const myButton = document.getElementById("my-button");

// Calls `printInfoToPage` method when button is clicked
myButton.addEventListener("click", printInfoToPage);

// Defines Player object
const Player = {
  Sexiness: 5,
  Health: 5,
  Mana: 3,
  Strength: 4,
  Defense: 3,
  BowlingScore: 5
};

// (Arrow function) prepends "Player." to its string argument
const mapPropNameToElementId = (propName) => "Player." + propName;

// Takes two strings, updates textContent of matching element if possible
function setElementTextById(id, text){
  element = document.getElementById(id);
  if(element){ // Makes sure element exists before proceeding
    element.textContent = text; // `.innerHTML` would also work
  }
};

function printInfoToPage(){

  // Static `.keys` method on `Object` gets an object's property names
  const playerPropNames = Object.keys(Player);

  // `for...of` loops through array
  for(let prop of playerPropNames){

    // Gets IDs
    const elementId = mapPropNameToElementId(prop);

    // Gets value
    const storedValue = Player[prop];

    // Updates element on page
    setElementTextById(elementId, storedValue);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>Sexiness: </span><span id="Player.Sexiness"></span> <br/>
<span>Health: </span><span id="Player.Health"></span> <br/>
<span>Mana: </span><span id="Player.Mana"></span> <br/>
<span>Strength: </span><span id="Player.Strength"></span> <br/>
<span>Defense: </span><span id="Player.Defense"></span> <br/>
<br/>
<button id="my-button">Show Player Info</button></code>```

Edit

BTW, the code can be (shorter and/or) more reusable. I often use more verbose code for clarity, but writing the same imperative code repeatedly makes it not just verbose but more error-prone and harder to maintain.

If you want to handle various groups of properties (ie various objects, eg armor and weapon), the printInfoToPage function can be revised to take an object and its identifying string as arguments, something like:

const
  category1 = { prop1: 111, prop2: 222 },
  category2 = { prop3: 333, prop4: 444 },
  printInfoToPage = (prefix, group) => {
    for(let prop in group){// `for...in` is for objects
      setElementValueById(prefix + prop, group[prop]);
    }
  },
  setElementValueById = (id, val) => {
    const el = document.getElementById(id);
    // `input` elements have a `value` property
    if(el?.tagName == "INPUT"){ el.value = val; }
  };

printInfoToPage("category1.", category1);
printInfoToPage("category2.", category2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label> prop1: <input id="category1.prop1" /></label><br />
<label> prop2: <input id="category1.prop2" /></label><br />
<br />
<label> prop3: <input id="category2.prop3" /></label><br />
<label> prop4: <input id="category2.prop4" /></label></code>```

Body:
I am back with another question for the community. I know there are a lot of questions and answers on the subject of document.getElementByID(), but I cannot find anything that points me to the path I am looking for, and it may just not exist.

In my text based javascript game, I have a LOT of span's and am looking to shorten the length of code, as for every instance of declaring and changing the variable inside an object, to push it to the HTML page, I am having to spam the use of document.getElementByID().

For instance, in my HTML file I have:

                        Name: 0   Gender: 0

                        Class: 0

                        Health: 0

                        Mana: 0

                        Strength: 0

                        Defense: 0

                        Endurance: 0

                        Intelligence: 0

                        Current Location: 0

With which I have made an object "Player" from a Hero prototype:

function Hero(Gender, Sexiness, Name, classType, Health, Mana, Strength, Defense, Endurance, Intelligence, Friend, Gold, BattleHealth, BattleMana, BattleStamina,  Experience, Level, Karma,) {
    this.Gender = Gender;
    this.Sexiness = Sexiness;
    this.Name = Name;
    this.ClassType = classType;
    this.Health = Health;
    this.Mana = Mana;
    this.Strength = Strength;
    this.Defense = Defense;
    this.Endurance = Endurance;
    this.Intelligence = Intelligence;
    this.Friend = Friend;
    this.Gold = Gold;
    this.BattleHealth = BattleHealth;
    this.BattleMana = BattleMana;
    this.BattleStamina = BattleStamina;
    this.Experience = Experience;
    this.Level = Level;
    this.Karma = Karma;
}
let Player = new Hero("Spirit", 0, "Spirit", "Undetermined One", 0, 0, 0, 0, 0, 0, "None", 10, 0, 0, 0, 0, 1, 0);

Defined some constants:

const Male = {
    Type: "Male",
    Health: 100,
    Mana: 20,
    Strength: 20,
    Defense: 5,
    Endurance: 15,
    Intelligence: 5,
    Sexiness: 1,
    Friend: "Duncan",
}
const Female = {
    Type: "Female",
    Health: 80,
    Mana: 60,
    Strength: 16,
    Defense: 4,
    Endurance: 12,
    Intelligence: 10,
    Sexiness: 2,
    Friend: "Morgana",
}

And a gender assign function:

function genderAssign() {
    switch (Player.Gender) {
        case "Male":
            Player.Gender = Male.Type;
            Player.Health = Male.Health;
            Player.Mana = Male.Mana;
            Player.Strength = Male.Strength;
            Player.Defense = Male.Defense;
            Player.Endurance = Male.Endurance;
            Player.Intelligence = Male.Intelligence;
            Player.Sexiness = Male.Sexiness;
            Player.Friend = Male.Friend;
            Armor.UpperClothesName = "Chest";
            Armor.LowerClothesName = "Fig Leaves";
            Armor.HelmetName = "Head";
            Armor.BodyName = "Body";
            Armor.ArmName = "Arms";
            Armor.WaistName = "None";
            Armor.LegName = "Legs";
            Armor.BootsName = "Feet";
            Weapons.RightHand = "Right Hand";
            Weapons.LeftHand = "Left Hand";
            Armor.LegCoveringsName = "Hair";
            break;
        case "Female":
            Player.Gender = Female.Type;
            Player.Health = Female.Health;
            Player.Mana = Female.Mana;
            Player.Strength = Female.Strength;
            Player.Defense = Female.Defense;
            Player.Endurance = Female.Endurance;
            Player.Intelligence = Female.Intelligence;
            Player.Sexiness = Female.Sexiness;
            Armor.UpperClothesName = "Nip Coverings";
            Armor.LowerClothesName = "Fig Leaves";
            Armor.HelmetName = "Head";
            Armor.BodyName = "Body";
            Armor.ArmName = "Arms";
            Armor.WaistName = "None";
            Armor.LegName = "Legs";
            Armor.BootsName = "Feet";
            Weapons.RightHand = "Right Hand";
            Weapons.LeftHand = "Left Hand";
            Armor.LegCoveringsName = "Smooth Legs";
            Player.Friend = Female.Friend;
            break;
        default:
    }
    return;
}

I don't want to have to do something as follows:

            Player.Gender = Male.Type;
            document.getElementByID("Male.Type").innerHTML = Male.Type
            Player.Health = Male.Health;
            document.getElementByID("Male.Health").innerHTML = Male.Health
            Player.Mana = Male.Mana;
            document.getElementByID("Male.Mana").innerHTML = Male.Mana

And so on...
Is there a way to do something like:

function printPlayer() {

    Player.Gender = $('#Player.Gender');
    Player.Sexiness = $('#Player.Sexiness');
    Player.Health = $('#Player.Health');
    Player.Mana = $('#Player.Mana');
    Player.Strength = $('#Player.Strength');
    Player.Defense = $('#Player.Defense');
    Player.Endurance = $('#Player.Endurance');
    Player.Intelligence = $('#Player.Intelligence');
    Player.Friend = $('#Player.Friend');
    Player.Gold = $('#Player.Gold');
    Player.Experience = $('#Player.Experience');
    Player.Level = $('#Player.Level');
    Player.ClassType = $('#Player.ClassType');
}

OR

function printPlayer() {

    document.getElementById("Player.Sexiness").innerHTML = Player.Sexiness;
    document.getElementById("Player.Health").innerHTML = Player.Health;
    document.getElementById("Player.Mana").innerHTML = Player.Mana;
    document.getElementById("Player.Strength").innerHTML = Player.Strength;
    document.getElementById("Player.Defense").innerHTML = Player.Defense;
    document.getElementById("Player.Endurance").innerHTML = Player.Endurance;
    document.getElementById("Player.Intelligence").innerHTML = Player.Intelligence;
    document.getElementById("Player.Friend").innerHTML = Player.Friend;
    document.getElementById("Player.Gold").innerHTML = Player.Gold;
    document.getElementById("Player.Experience").innerHTML = Player.Experience;
    document.getElementById("Player.Level").innerHTML = Player.Level;
    document.getElementById("Player.ClassType").innerHTML = Player.ClassType;
}

And call it from within, say the genderAssign() function?

Sorry if this is a bit lengthy, but I'd rather give you a broader scope of what I am doing rather than leave it to guessing. I have tried the above functions, and neither seem to work. The error is:

TypeError: document.getElementById(...) is nullUpdatePlayerCharacter.js:22:14

printPlayer file:///C:/Users/Melseph/Desktop/Game Design/PhoenixDestitute/scripts/UpdatePlayerCharacter.js:22

genderAssign file:///C:/Users/Melseph/Desktop/Game Design/PhoenixDestitute/scripts/CharacterStats.js:78

<anonymous> file:///C:/Users/Melseph/Desktop/Game Design/PhoenixDestitute/scripts/PhoenixDestitute.js:45
jQuery 2

Which I am assuming is because I don't have the values inside the printPlayer() function, but there in is where I am stuck and cannot find anymore direction. Is it just impossible to do it the way I am trying?

--Edit--

I always seem to leave this part out, which is why I think everyone tends to want to point towards a button, which is my mistake, sorry...

I have a form for the user to answer questions and a window that shows updates the player makes, and I had it all working with added document.getElementByID()... which (of course) killed it when I took those out. I can see through console.log(Player) that all the items are being updated in the Player object, but I cannot find an easier method of pushing the innerHTML to the HTML file.

Here is what my code is for the console id and a screenshot:

Would you like to begin your adventure? Type yes or no.

<form id="form" onsubmit="return false;">
    <input type="text" autocomplete="off" id="command_line" placeholder="User Input Here" autofocus="autofocus" />
</form>

$(document).ready(function() {
$("#console").fadeIn(3000); //Console fades in.
$(document).keypress(function(key) { //When a key is press:
    if (key.which === 13 && $('#command_line').is(':focus')) { //If enter key is pressed and the focus is on the command line:
        var input = $('#command_line').val().toLowerCase(); //Express what is in the command line in lower case.
        $('#command_line').val(""); //Erase the value of what is shown in the command box.
        $("#console").animate({ scrollTop: "999999999px" }, 'slow'); //Scroll the console to the bottom.
     }
}

Not sure if this changes the answer to my question any, or if the use of a button is the only method.

Body:
This snippet should give you some ideas for handling properties of your Player object, including showing them on the page.

(See the in-code comments for explanations of particular features of the script.)

//Identifies button for demo
const myButton = document.getElementById("my-button");

// Calls `printInfoToPage` method when button is clicked
myButton.addEventListener("click", printInfoToPage);

// Defines Player object
const Player = {
  Sexiness: 5,
  Health: 5,
  Mana: 3,
  Strength: 4,
  Defense: 3,
  BowlingScore: 5
};

// (Arrow function) prepends "Player." to its string argument
const mapPropNameToElementId = (propName) => "Player." + propName;

// Takes two strings, updates textContent of matching element if possible
function setElementTextById(id, text){
  element = document.getElementById(id);
  if(element){ // Makes sure element exists before proceeding
    element.textContent = text; // `.innerHTML` would also work
  }
};

function printInfoToPage(){

  // Static `.keys` method on `Object` gets an object's property names
  const playerPropNames = Object.keys(Player);

  // `for...of` loops through array
  for(let prop of playerPropNames){

    // Gets IDs
    const elementId = mapPropNameToElementId(prop);

    // Gets value
    const storedValue = Player[prop];

    // Updates element on page
    setElementTextById(elementId, storedValue);
  }
}

<span>Sexiness: </span><span id="Player.Sexiness"></span> <br/>
<span>Health: </span><span id="Player.Health"></span> <br/>
<span>Mana: </span><span id="Player.Mana"></span> <br/>
<span>Strength: </span><span id="Player.Strength"></span> <br/>
<span>Defense: </span><span id="Player.Defense"></span> <br/>
<br/>
<button id="my-button">Show Player Info</button>

Edit

BTW, the code can be (shorter and/or) more reusable. I often use more verbose code for clarity, but writing the same imperative code repeatedly makes it not just verbose but more error-prone and harder to maintain.

If you want to handle various groups of properties (ie various objects, eg armor and weapon), the printInfoToPage function can be revised to take an object and its identifying string as arguments, something like:

const
  category1 = { prop1: 111, prop2: 222 },
  category2 = { prop3: 333, prop4: 444 },
  printInfoToPage = (prefix, group) => {
    for(let prop in group){// `for...in` is for objects
      setElementValueById(prefix + prop, group[prop]);
    }
  },
  setElementValueById = (id, val) => {
    const el = document.getElementById(id);
    // `input` elements have a `value` property
    if(el?.tagName == "INPUT"){ el.value = val; }
  };

printInfoToPage("category1.", category1);
printInfoToPage("category2.", category2);

<label> prop1: <input id="category1.prop1" /></label><br />
<label> prop2: <input id="category1.prop2" /></label><br />
<br />
<label> prop3: <input id="category2.prop3" /></label><br />
<label> prop4: <input id="category2.prop4" /></label>


来源: stackexchange

问:
Set offset for BitmapDrawable while repeating in the x and y direction?
I'm making a 2D platformer game. I have created a texture for the platform, that is meant to be repeated over and over to fill the entire platform, without going over. My first attempt was to draw all the pixels from the bitmap manually, but this caused the background to flicker through while moving the platform (the movement and drawing threads are seperate, so the movement can run at a specific speed, while the FPS doesn't need to suffer). I found this technique worked better:

```<code>// Init
bitmap = new BitmapDrawable(res, Texture.PLATFORM.getBitmap());
bitmap.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);

// Drawing loop
int x = getX() + (isStill() ? 0 : (int)MainActivity.offsetX);
int y = getY() + (isStill() ? 0 : (int)MainActivity.offsetY);

bitmap.setBounds(x, y, x + getWidth(), y + getHeight());
bitmap.draw(canvas);
</code>```

However, the bitmap appears to be staying static while the platform is acting as a "view hole" to see through to the bitmap. The only work around I can think of is to somehow "offset" the static bitmap:

```<code>bitmap.offset(x, y);
</code>```

Obviously, that isn't a function. I couldn't find one that would do what I want when looking through the docs.

To summon things up, the BitmapDrawable is causing the background to not move with the platform, making it look super weird.

Thanks in advance!

答:
Try these tips in your code:(I assumed the game moves forward in the horizontal direction)

The GUY should only move up and down(with the appropriate touch input) and not forward and backward as you want the focus(or camera alternatively) solely on the GUY.I noticed that the WALL was moving up in your video when the GUY moved from initial higher position of the wall to little bit lower position later, rectify this because the GUY should move down(try to implement Gravity effect).

The WALL should only move forward(mostly) and backward(less often I guess).The WALL shouldn't move up and down normally. Do not apply Gravity effect to it. You can create at least 2 BitmapDrawable instance of WALL for a screen. They are going to be reused sequencially(for eg: If the 1st one goes totally outside of the screen, reshow it in the desired position using setBounds() method) and continue same for others the whole game.

The currently BLUE BACKGROUND, if it is a part of a larger map, then it needs to be appropriately offsetted.

One of the obstacles that I can think of at the time of writing this is to move the WALL down until it goes out of the screen which results in the death of the GUY.

At those places, where I have used the word move, you need to use the setBounds(a, b, c, d) method to make necessary position based changes as I didn't find other way to update the position of a BitmapDrawable instance. I think, you need to use game framework like libGdx to get method of luxury like setOffset(x, y) or of similar sort.

Sorry that I could only present you the ideas without specific code as I do not have past experience working in a project like this. Hope, it helps you in anyway possible.

ContentLicense: CC BY-SA 4.0

Body:
I'm making a 2D platformer game. I have created a texture for the platform, that is meant to be repeated over and over to fill the entire platform, without going over. My first attempt was to draw all the pixels from the bitmap manually, but this caused the background to flicker through while moving the platform (the movement and drawing threads are seperate, so the movement can run at a specific speed, while the FPS doesn't need to suffer). I found this technique worked better:

// Init
bitmap = new BitmapDrawable(res, Texture.PLATFORM.getBitmap());
bitmap.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);

// Drawing loop
int x = getX() + (isStill() ? 0 : (int)MainActivity.offsetX);
int y = getY() + (isStill() ? 0 : (int)MainActivity.offsetY);

bitmap.setBounds(x, y, x + getWidth(), y + getHeight());
bitmap.draw(canvas);

However, the bitmap appears to be staying static while the platform is acting as a "view hole" to see through to the bitmap. The only work around I can think of is to somehow "offset" the static bitmap:

bitmap.offset(x, y);

Obviously, that isn't a function. I couldn't find one that would do what I want when looking through the docs.

To summon things up, the BitmapDrawable is causing the background to not move with the platform, making it look super weird.

Thanks in advance!


问:
Plotly Dash: How to change the button color when it is clicked?
Hi I have 3 buttons designed in dash, I want to change the color of the button when it is clicked, I know there is to change in the @app.callback but I am not sure what to change.
I want to keep everything same but the color should change to "Red"

Can anyone help me with this.

```<code>leftButtons = html.Div(id='framework-left-pane',
                         children=[
                         dcc.Link( children = html.Button(leftButton1,
                                                 id='leftbutton1',
                                                 className='roundbutton',
                                                 style={'backgroundColor': '#111100', 'color':'white','width':'100%', 'border':'1.5px black solid', 'height': '50px','text-align':'center', 'marginLeft': '20px', 'marginTop': 130},  n_clicks = 0)),
                         dcc.Link( children = html.Button(leftButton2,
                                                 id='leftbutton2',
                                                 className='roundbutton',
                                                 style={'backgroundColor': '#111100', 'color':'white','width':'100%' , 'border':'1.5px black solid','height': '50px','text-align':'center', 'marginLeft': '20px', 'marginTop': 20},n_clicks = 0)),
                         dcc.Link( children = html.Button(leftButton3,
                                                 id='leftbutton3',
                                                 className='roundbutton',
                                                 style={'backgroundColor': '#111100', 'color':'white','width':'100%', 'border':'1.5px black solid','height': '50px','text-align':'center', 'marginLeft': '20px', 'marginTop': 20},n_clicks = 0)),
                                                 ],style={'width':'200px','position':'fixed'})
</code>```

`

so right now with app.callback I am returning an image only

```<code>@app.callback(
Output(component_id='tab_1_images', component_property='children'),
[Input('leftbutton1', 'n_clicks'),
Input('leftbutton2', 'n_clicks'),
Input('leftbutton3', 'n_clicks')])

def update_output_div(n_clicks_A, n_clicks_B, n_clicks_C):
    return [a static image for each of the button]
</code>```

答:
To change the color of the button after it is clicked you need to update the corresponding style property in the callback:

```<code>import dash
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

white_button_style = {'background-color': 'white',
                      'color': 'black',
                      'height': '50px',
                      'width': '100px',
                      'margin-top': '50px',
                      'margin-left': '50px'}

red_button_style = {'background-color': 'red',
                    'color': 'white',
                    'height': '50px',
                    'width': '100px',
                    'margin-top': '50px',
                    'margin-left': '50px'}

app.layout = html.Div([

    html.Button(id='button',
                children=['click'],
                n_clicks=0,
                style=white_button_style
    )

])

@app.callback(Output('button', 'style'), [Input('button', 'n_clicks')])
def change_button_style(n_clicks):

    if n_clicks > 0:

        return red_button_style

    else:

        return white_button_style

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

Body:
Hi I have 3 buttons designed in dash, I want to change the color of the button when it is clicked, I know there is to change in the @app.callback but I am not sure what to change.
I want to keep everything same but the color should change to "Red"

Can anyone help me with this.

leftButtons = html.Div(id='framework-left-pane',
                         children=[
                         dcc.Link( children = html.Button(leftButton1,
                                                 id='leftbutton1',
                                                 className='roundbutton',
                                                 style={'backgroundColor': '#111100', 'color':'white','width':'100%', 'border':'1.5px black solid', 'height': '50px','text-align':'center', 'marginLeft': '20px', 'marginTop': 130},  n_clicks = 0)),
                         dcc.Link( children = html.Button(leftButton2,
                                                 id='leftbutton2',
                                                 className='roundbutton',
                                                 style={'backgroundColor': '#111100', 'color':'white','width':'100%' , 'border':'1.5px black solid','height': '50px','text-align':'center', 'marginLeft': '20px', 'marginTop': 20},n_clicks = 0)),
                         dcc.Link( children = html.Button(leftButton3,
                                                 id='leftbutton3',
                                                 className='roundbutton',
                                                 style={'backgroundColor': '#111100', 'color':'white','width':'100%', 'border':'1.5px black solid','height': '50px','text-align':'center', 'marginLeft': '20px', 'marginTop': 20},n_clicks = 0)),
                                                 ],style={'width':'200px','position':'fixed'})

`

so right now with app.callback I am returning an image only

@app.callback(
Output(component_id='tab_1_images', component_property='children'),
[Input('leftbutton1', 'n_clicks'),
Input('leftbutton2', 'n_clicks'),
Input('leftbutton3', 'n_clicks')])

def update_output_div(n_clicks_A, n_clicks_B, n_clicks_C):
    return [a static image for each of the button]

Body:
To change the color of the button after it is clicked you need to update the corresponding style property in the callback:

import dash
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

white_button_style = {'background-color': 'white',
                      'color': 'black',
                      'height': '50px',
                      'width': '100px',
                      'margin-top': '50px',
                      'margin-left': '50px'}

red_button_style = {'background-color': 'red',
                    'color': 'white',
                    'height': '50px',
                    'width': '100px',
                    'margin-top': '50px',
                    'margin-left': '50px'}

app.layout = html.Div([

    html.Button(id='button',
                children=['click'],
                n_clicks=0,
                style=white_button_style
    )

])

@app.callback(Output('button', 'style'), [Input('button', 'n_clicks')])
def change_button_style(n_clicks):

    if n_clicks > 0:

        return red_button_style

    else:

        return white_button_style

if __name__ == '__main__':
    app.run_server(debug=True)


问:
emulate nfc card with selected UID on android
I want to ask 2question about nfc card emulate :

can I emulate nfc card include uid that I select?

I read HCE and don't understand what is the diffrent between HCE and Card Emulation with a Secure Element?.

what are the disadvantage with the Secure Element ? i can't control on the card data/uid and on HCE I can?

答:
This subject may be a bit old but I was asking myself the same question.
Apparently the UID of the card emulated by your phone is random, but if you want to emulate the UID too you need to overwrite /etc/libnfc-nxp.conf, but it requires root privileges.
At least it works (or worked) for MIFARE Classic UID.

You can see more information on this link, slides 37 and +
https://smartlockpicking.com/slides/Confidence_A_2018_Practical_Guide_To_Hacking_RFID_NFC.pdf

ContentLicense: CC BY-SA 3.0


问:
Set background color of the deletion control of a UITableViewCell
In an iPhone/iPad app, I'm using a UITableView to display a list of items that can be edited.  I can successfully alternate the background color of the rows in my table view.  However, when I turn on "editing mode" (i.e., display the deletion control), each cell appears to be shifted to the right, and the deletion control slides in from the left.

My problem is that the deletion control has a white background color.  I'd like the background color of the deletion control to match the background color of my UITableViewCell.

How do I accomplish this?

答:
Try setting the background of the accessoryView which houses the delete button to UIColor clearColor. I'm not sure the exact syntax, but something like:

```<code>[tableView.editingAccessoryView setBackgroundColor:[UIColor clearColor]];
</code>```

If that doesn't do it for you, you may try setting the background of the entire tableview to clear. This should not affect your customized colors for each cell.

Body:
Try setting the background of the accessoryView which houses the delete button to UIColor clearColor. I'm not sure the exact syntax, but something like:

[tableView.editingAccessoryView setBackgroundColor:[UIColor clearColor]];

If that doesn't do it for you, you may try setting the background of the entire tableview to clear. This should not affect your customized colors for each cell.


问:
Simple moviepy script, getting error: unhashable type: 'list'
i'm working on a little script to concat all clips in a folder with a small transition using moviepy, but I'm unable to run it as I'm getting the error unhashable type 'list'. I've been reading through many posts about this error and I understand that you're unable to hash a list, and casting to a tuple can fix the problem, i've tried multiple suggestions from other answers but can't fully understand why my code isn't fully working

```<code>from moviepy.editor import concatenate_videoclips
from moviepy.video.io.VideoFileClip import VideoFileClip
import os

clips = []
    for filename in os.listdir('D:/Clip Project/ClipsTest'):
        if filename.endswith(".mp4"):
            clips.append(VideoFileClip('D:/Clip Project/ClipsTest/' + filename))
    clips = [clip.crossfadein(1) for clip in clips]
    video = concatenate_videoclips(clips, padding=-1, method='compose', )
    video.write_videofile('D:/Clip Project/ClipsTest/League-' + '.mp4', threads=4, fps=24)
</code>```

This is the code I orginally ran into the problem with and am struggling to fix, any tips would be amazing!

Here is the full error:

```<code>Traceback (most recent call last):
  File "teststuff.py", line 2, in <module>
    from moviepy.editor import concatenate_videoclips
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\moviepy\editor.py", line 48, in <module>
    import moviepy.video.fx.all as vfx
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\moviepy\video\fx\all\__init__.py", line 13, in <module>
    __all__ = [name for _, name, _ in pkgutil.iter_modules(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\moviepy\video\fx\all\__init__.py", line 13, in <listcomp>
    __all__ = [name for _, name, _ in pkgutil.iter_modules(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\pkgutil.py", line 129, in iter_modules
    for i in importers:
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\pkgutil.py", line 415, in get_importer
    importer = sys.path_importer_cache[path_item]
TypeError: unhashable type: 'list'
</code>```

Is it possible this is an issue with moviepy itself? I've looked into the documentation below but to no avail, as well as fiddled with the imports.

答:
I do not know exactly what is causing the error but an example to replicate the error:

```<code>d ={ 1:'first', [2,3]:'second'}
print(d)
</code>```

I looked a litter in the pymovie documentation but could not find the parameters. Try to check and see the parameters the compose function requires.

You can see here the functions parameters:
https://github.com/Zulko/moviepy/blob/master/moviepy/video/compositing/concatenate.py
maybe this can help.

Body:
i'm working on a little script to concat all clips in a folder with a small transition using moviepy, but I'm unable to run it as I'm getting the error unhashable type 'list'. I've been reading through many posts about this error and I understand that you're unable to hash a list, and casting to a tuple can fix the problem, i've tried multiple suggestions from other answers but can't fully understand why my code isn't fully working

from moviepy.editor import concatenate_videoclips
from moviepy.video.io.VideoFileClip import VideoFileClip
import os

clips = []
    for filename in os.listdir('D:/Clip Project/ClipsTest'):
        if filename.endswith(".mp4"):
            clips.append(VideoFileClip('D:/Clip Project/ClipsTest/' + filename))
    clips = [clip.crossfadein(1) for clip in clips]
    video = concatenate_videoclips(clips, padding=-1, method='compose', )
    video.write_videofile('D:/Clip Project/ClipsTest/League-' + '.mp4', threads=4, fps=24)

This is the code I orginally ran into the problem with and am struggling to fix, any tips would be amazing!

Here is the full error:

Traceback (most recent call last):
  File "teststuff.py", line 2, in <module>
    from moviepy.editor import concatenate_videoclips
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\moviepy\editor.py", line 48, in <module>
    import moviepy.video.fx.all as vfx
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\moviepy\video\fx\all\__init__.py", line 13, in <module>
    __all__ = [name for _, name, _ in pkgutil.iter_modules(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\moviepy\video\fx\all\__init__.py", line 13, in <listcomp>
    __all__ = [name for _, name, _ in pkgutil.iter_modules(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\pkgutil.py", line 129, in iter_modules
    for i in importers:
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\pkgutil.py", line 415, in get_importer
    importer = sys.path_importer_cache[path_item]
TypeError: unhashable type: 'list'

Is it possible this is an issue with moviepy itself? I've looked into the documentation below but to no avail, as well as fiddled with the imports.

Body:
I do not know exactly what is causing the error but an example to replicate the error:

d ={ 1:'first', [2,3]:'second'}
print(d)

I looked a litter in the pymovie documentation but could not find the parameters. Try to check and see the parameters the compose function requires.

You can see here the functions parameters:
https://github.com/Zulko/moviepy/blob/master/moviepy/video/compositing/concatenate.py
maybe this can help.


问:
Cannot write to kafka, brokers are down
I'm running Kafka locally. When I try to write to Kafka I get the following error:

```<code>kafkacat -b localhost:9092 -t req -T -P -l  msgs
hello
world
% ERROR: Local: Broker transport failure: localhost:9092/bootstrap: Connect to ipv6#[::1]:9092 failed: Connection refused (after 1ms in state CONNECT)
% ERROR: Local: All broker connections are down: 1/1 brokers are down : terminating
</code>```

I have Kafka listening on port 9092:

```<code>bash-3.2$ netstat -an | grep 9092
tcp4       0      0  127.0.0.1.9092         127.0.0.1.50994        ESTABLISHED
tcp4       0      0  127.0.0.1.50994        127.0.0.1.9092         ESTABLISHED
tcp4       0      0  127.0.0.1.9092         127.0.0.1.50986        ESTABLISHED
tcp4       0      0  127.0.0.1.50986        127.0.0.1.9092         ESTABLISHED
tcp4       0      0  127.0.0.1.9092         127.0.0.1.50984        ESTABLISHED
tcp4       0      0  127.0.0.1.50984        127.0.0.1.9092         ESTABLISHED
tcp4       0      0  127.0.0.1.9092         *.*                    LISTEN
bash-3.2$
bash-3.2$ telnet 127.0.0.1 9092
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
</code>```

And here are the relevant parts of the kafka config:

```<code># The id of the broker. This must be set to a unique integer for each broker.
broker.id=0

# Hostname and port the broker will advertise to producers and consumers. If not set,
# it uses the value for "listeners" if configured.  Otherwise, it will use the value
# returned from java.net.InetAddress.getCanonicalHostName().
advertised.listeners=PLAINTEXT://127.0.0.1:9092
bootstrap.servers=127.0.0.1:9092
</code>```

What I am doing wrong? Why can't I write a few entries to my local Kafka?

P.S.

When I use the scripts that Kafka comes with I can create the topic:

```<code>/usr/local/bin/kafka-topics --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic Hoffman02
Created topic Hoffman02.
</code>```

But when I use kafkacat kafkacat -b localhost:9092 -t Hoffman04 -P, it hangs forever but still I can find the file Hoffman04 in the logs folder ls -lrt /usr/local/var/lib/kafka-logs:

```<code>drwxr-xr-x  6 jenia  admin   192 28 May 11:17 Hoffman04-0
</code>```

答:
Depending on your OS (OSX in particular), localhost may resolve to both ipv4 and ipv6 addresses, while your broker is only binding to the IPv4 address.
You can limit the address family to IPv4 in kafkacat by adding -X broker.address.family=v4 to your kafkacat command line.

Title: Cannot write to kafka, brokers are down

Body:
I'm running Kafka locally. When I try to write to Kafka I get the following error:

kafkacat -b localhost:9092 -t req -T -P -l  msgs
hello
world
% ERROR: Local: Broker transport failure: localhost:9092/bootstrap: Connect to ipv6#[::1]:9092 failed: Connection refused (after 1ms in state CONNECT)
% ERROR: Local: All broker connections are down: 1/1 brokers are down : terminating

I have Kafka listening on port 9092:

bash-3.2$ netstat -an | grep 9092
tcp4       0      0  127.0.0.1.9092         127.0.0.1.50994        ESTABLISHED
tcp4       0      0  127.0.0.1.50994        127.0.0.1.9092         ESTABLISHED
tcp4       0      0  127.0.0.1.9092         127.0.0.1.50986        ESTABLISHED
tcp4       0      0  127.0.0.1.50986        127.0.0.1.9092         ESTABLISHED
tcp4       0      0  127.0.0.1.9092         127.0.0.1.50984        ESTABLISHED
tcp4       0      0  127.0.0.1.50984        127.0.0.1.9092         ESTABLISHED
tcp4       0      0  127.0.0.1.9092         *.*                    LISTEN
bash-3.2$
bash-3.2$ telnet 127.0.0.1 9092
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

And here are the relevant parts of the kafka config:

# The id of the broker. This must be set to a unique integer for each broker.
broker.id=0

# Hostname and port the broker will advertise to producers and consumers. If not set,
# it uses the value for "listeners" if configured.  Otherwise, it will use the value
# returned from java.net.InetAddress.getCanonicalHostName().
advertised.listeners=PLAINTEXT://127.0.0.1:9092
bootstrap.servers=127.0.0.1:9092

What I am doing wrong? Why can't I write a few entries to my local Kafka?

P.S.

When I use the scripts that Kafka comes with I can create the topic:

/usr/local/bin/kafka-topics --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic Hoffman02
Created topic Hoffman02.

But when I use kafkacat kafkacat -b localhost:9092 -t Hoffman04 -P, it hangs forever but still I can find the file Hoffman04 in the logs folder ls -lrt /usr/local/var/lib/kafka-logs:

drwxr-xr-x  6 jenia  admin   192 28 May 11:17 Hoffman04-0


问:
how can I finish activity from view
I have got an activity which has custom view.

I have to add activity result:

```<code>    public class ActView extends Activity implements OnClickListener {
<...code...>
@Override
    protected void onCreate(Bundle savedInstanceState) {
    <...code...>
     layout = (LinearLayout) findViewById(R.id.chart_container);
        timelineview = new VDrawTimeLine(this,contentFull);
        timelineview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        timelineview.setBackgroundColor(0xffffffff);
        timelineview.setVisibility(View.VISIBLE);

        layout.addView(timelineview);

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

View class:

```<code>public class VDrawTimeLine extends View implements OnTouchListener{
<...code...>
public VDrawTimeLine(Context context, ArrayList<_MainData> contentFull) {
        super(context);
        this.con = context;
        this.content = contentFull;
        <...code...>
    }
}
@Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        finishFunction();//I need here finish event this activity result for ActView Activity.
        return true;
    }
</code>```

finishFunction - what i have to write here to finish the ActView with the result for parent activity?

I need somethin like this:

```<code>Intent intent = new Intent();
    intent.putExtra(dataname, value);
    setResult(RESULT_OK,intent);
    finish();
</code>```

答:
How to close an Activity from View Model class in MVVM Databinding in Android Kotlin.

You should pass the context/acitivty reference in your View Model class from the activity as below

```<code>private lateinit var registerViewModel: RegisterViewModel
</code>```

initialize it onCreate method

```<code>registerViewModel = RegisterViewModel(this)
</code>```

RegisterViewModel class which is extends to BaseObservable()

Write this below code to close activity on button click

```<code>fun handleOnClick(view: View) {
        when (view.id) {
            R.id.registerBTN -> {
                val activity = context as Activity
                activity.finish()
            }
            else -> Toast.makeText(context, "To-DO", Toast.LENGTH_SHORT).show()
        }
    }
</code>```

You can define in your layout.xml file like below

```<code><Button
                android:id="@+id/registerBTN"
                style="@style/Widget.AppCompat.Button.Colored"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:enabled="@{registerViewModel.isAllowRegister}"
                android:layout_marginVertical="32dp"
                android:text="@string/register"
                android:onClick="@{registerViewModel::handleOnClick}"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/passwordET" />
</code>```

Title: how can I finish activity from view

Body:
I have got an activity which has custom view.

I have to add activity result:

    public class ActView extends Activity implements OnClickListener {
<...code...>
@Override
    protected void onCreate(Bundle savedInstanceState) {
    <...code...>
     layout = (LinearLayout) findViewById(R.id.chart_container);
        timelineview = new VDrawTimeLine(this,contentFull);
        timelineview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        timelineview.setBackgroundColor(0xffffffff);
        timelineview.setVisibility(View.VISIBLE);

        layout.addView(timelineview);

    <...code...>
    }
}

View class:

public class VDrawTimeLine extends View implements OnTouchListener{
<...code...>
public VDrawTimeLine(Context context, ArrayList<_MainData> contentFull) {
        super(context);
        this.con = context;
        this.content = contentFull;
        <...code...>
    }
}
@Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        finishFunction();//I need here finish event this activity result for ActView Activity.
        return true;
    }

finishFunction - what i have to write here to finish the ActView with the result for parent activity?

I need somethin like this:

Intent intent = new Intent();
    intent.putExtra(dataname, value);
    setResult(RESULT_OK,intent);
    finish();

Body:
How to close an Activity from View Model class in MVVM Databinding in Android Kotlin.

You should pass the context/acitivty reference in your View Model class from the activity as below

private lateinit var registerViewModel: RegisterViewModel

initialize it onCreate method

registerViewModel = RegisterViewModel(this)

RegisterViewModel class which is extends to BaseObservable()

Write this below code to close activity on button click

fun handleOnClick(view: View) {
        when (view.id) {
            R.id.registerBTN -> {
                val activity = context as Activity
                activity.finish()
            }
            else -> Toast.makeText(context, "To-DO", Toast.LENGTH_SHORT).show()
        }
    }

You can define in your layout.xml file like below

<Button
                android:id="@+id/registerBTN"
                style="@style/Widget.AppCompat.Button.Colored"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:enabled="@{registerViewModel.isAllowRegister}"
                android:layout_marginVertical="32dp"
                android:text="@string/register"
                android:onClick="@{registerViewModel::handleOnClick}"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/passwordET" />


问:
C++: Access private member vector of structs from other class
from a similiar question here
I tried the solution

```<code>class A {
 ...
  public:

    // Give read-only access to vec_A
    const std::vector<DataStruct> & getVector() const {
        return vec_A;
    }
};
</code>```

but always get error: 'DataStruct' was not declared in this scope.
DataStruct and vec_A are defined in private section , below public section, in same class.

Please, could someone help me.

Regards,
Thomas

答:
I suppose you have code similar to the following example:

```<code>#include <iostream>
struct foo {
    private:
       struct bar {
           void barbar() { std::cout << "hello";}
       };
    public:
    bar foobar() { return bar{}; }
};

int main() {
    foo f;
    foo::bar x = f.foobar();
    x.barbar();
}
</code>```

It has an error:

```<code><source>: In function 'int main()':
<source>:13:10: error: 'struct foo::bar' is private within this context
   13 |     foo::bar x = f.foobar();
      |          ^~~
<source>:4:15: note: declared private here
    4 |        struct bar {
      |               ^~~
</code>```

because bar is private in foo. However, that doesnt mean that you cannot use it outside of foo. You can use auto:

```<code>int main() {
    foo f;
    auto x = f.foobar();
    x.barbar();
}
</code>```

Or decltype:

```<code>int main() {
    foo f;
    using bar_alias = decltype(f.foobar());
    bar_alias x = f.foobar();
    x.barbar();
}
</code>```

You cannot access the name DataType but you can use auto and you can get an alias for the type. This also works for a std::vector<DataType>, only some more boilerplate would be required to get your hands on DataType directly.

Body:
from a similiar question here
I tried the solution

class A {
 ...
  public:

    // Give read-only access to vec_A
    const std::vector<DataStruct> & getVector() const {
        return vec_A;
    }
};

but always get error: 'DataStruct' was not declared in this scope.
DataStruct and vec_A are defined in private section , below public section, in same class.

Please, could someone help me.

Regards,
Thomas

Body:
I suppose you have code similar to the following example:

#include <iostream>
struct foo {
    private:
       struct bar {
           void barbar() { std::cout << "hello";}
       };
    public:
    bar foobar() { return bar{}; }
};

int main() {
    foo f;
    foo::bar x = f.foobar();
    x.barbar();
}

It has an error:

<source>: In function 'int main()':
<source>:13:10: error: 'struct foo::bar' is private within this context
   13 |     foo::bar x = f.foobar();
      |          ^~~
<source>:4:15: note: declared private here
    4 |        struct bar {
      |               ^~~

because bar is private in foo. However, that doesnt mean that you cannot use it outside of foo. You can use auto:

int main() {
    foo f;
    auto x = f.foobar();
    x.barbar();
}

Or decltype:

int main() {
    foo f;
    using bar_alias = decltype(f.foobar());
    bar_alias x = f.foobar();
    x.barbar();
}

You cannot access the name DataType but you can use auto and you can get an alias for the type. This also works for a std::vector<DataType>, only some more boilerplate would be required to get your hands on DataType directly.


问:
My original list is changing when using append or extend
I would like to know if this is normal behavior for Python. Code is:

```<code>>>>abcd = [["a","b","c","d"],[1,2,3,4]]
>>>testlist = []
</code>```

then

>>>testlist.extend(abcd)

or if I use:

```<code>>>>for item in abcd:
    testlist.append(item)
</code>```

the result of calling testlist is the same, which is perfectly fine:

```<code>>>>testlist
[['a', 'b', 'c', 'd'], [1, 2, 3, 4]]
</code>```

but then when I do something with 'testlist' the change appears also in 'abcd'

```<code>>>>testlist[0].append("anything")
>>>testlist
[['a', 'b', 'c', 'd', 'anything'], [1, 2, 3, 4]]
>>>abcd
[['a', 'b', 'c', 'd', 'anything'], [1, 2, 3, 4]]

</code>```

It is making me crazy. How should I proceed without changing original list and not making copies of it every time I need to pull some data from it. Thank you.

答:
You have to distinguish between deep and shallow copies. In your case testlist seems to be a shallow copy, as changes to one are reflected also in the other. Thus, you might want to look into deep copying list.

For example:

```<code>import copy
testlist = copy.deepcopy(abcd)
</code>```

or even simpler:

```<code>testlist = abcd[:]
</code>```

Body:
I would like to know if this is normal behavior for Python. Code is:

>>>abcd = [["a","b","c","d"],[1,2,3,4]]
>>>testlist = []

then

>>>testlist.extend(abcd)

or if I use:

>>>for item in abcd:
    testlist.append(item)

the result of calling testlist is the same, which is perfectly fine:

>>>testlist
[['a', 'b', 'c', 'd'], [1, 2, 3, 4]]

but then when I do something with 'testlist' the change appears also in 'abcd'

>>>testlist[0].append("anything")
>>>testlist
[['a', 'b', 'c', 'd', 'anything'], [1, 2, 3, 4]]
>>>abcd
[['a', 'b', 'c', 'd', 'anything'], [1, 2, 3, 4]]

It is making me crazy. How should I proceed without changing original list and not making copies of it every time I need to pull some data from it. Thank you.

Body:
You have to distinguish between deep and shallow copies. In your case testlist seems to be a shallow copy, as changes to one are reflected also in the other. Thus, you might want to look into deep copying list.

For example:

import copy
testlist = copy.deepcopy(abcd)

or even simpler:

testlist = abcd[:]


问:
DAG's task initialization takes time
We have a composer environment which has below configuration details.

Composer Version:  composer-1.10.0-airflow-1.10.6

Machine Type : n1-standard-4

Disk size (GB): 100

Worker Nodes: 6

python version:3

worker_concurrency: 32

parallelism:128

We have a problem in DAG to initialize it's task and it is taking more time. For example DAG has 3 tasks like Task1 -> Task2 -> Task3. Task1 initializes taking time (minimum 5 mins) and once initialized completion time of that task within seconds. Task2 initialized taking again 5 mins and executed within seconds. Like that task's initialization is taking time but completion of that task is quickly done. Have scheduled this DAG every 5 mins, but completing this DAG takes around 10 mins at least. So affecting functionalities and execution of the process.

Here are the functionalities of each three tasks. Task1 objective is to gather the basic information such as storage location from configuration files/variables. Task2 checks the storage whether any new files are coming and based on the file triggers the relevant DAGs. Task3 objective is to send success email.

Also, I noted that worker nodes did not splitted the work among themselves. Always one worker node's CPU utilization is high compared to other worker nodes. Do not know what could be the reason for it. One more interesting is even though the other DAG's are not running at that time this DAG still takes 10 mins to execute.

Appreciated your help in solving this case.

答:
This should be a comment but I don't have the reputation required.

My initial advice is to upgrade your Composer version, 1.10.0 has a few known bugs that are fixed in later versions. Right now the latest version is 1.10.4. This should correct the CPU that stays at 100% (it did in our case). Are there many other DAGs running on your instance?

Title: DAG's task initialization takes time


问:
First param to schema.plugin must be a function (passport-local-mongoose)
i have been trying to use passport-local-mongoose in my server.
was making this server with the help from a teutorial video. in the teutorial video this same code works perfectly fine, but in my case its not working. Though I have my database connected to mongodbatlas.
but I am getting a error "First param to schema.plugin() must be a function,"
Screenshot of the ERROR

I wonder how would i use plugin as a function! tried searching in everywhere but nothing helpfull.
following is the code

const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = ("passport-local-mongoose");

const app = express();
app.use(session({
    secret: "alpha beta gama",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb+srv://admin-sumit:password@cluster0-bessu.mongodb.net/myBlog", {
   useNewUrlParser: true,
   useUnifiedTopology: true
 });

const userSchema = new mongoose.Schema({
    email:String,
    password:String,
    comments:String
});

userSchema.plugin(passportLocalMongoose);

const User = new mongoose.model("User", userSchema);

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.get("/blog1comment", function(req, res){
    if(req.isAuthenticated()){
        res.render('blogsingle', { title: 'Express' });
    } else{
        res.redirect("/login");
    }
});

app.post('/register', function(req, res){
    User.register({username: req.body.username}, req.body.password, function(err, user){
        if(err){
            console.log(err);
            res.redirect("/register");
        } else {
            passport.authenticate("local")(req, res, function(){
                res.redirect("/");
            });
        }
    });

});

app.post('/login', function(req, res){
    const user = new User({
        username: req.body.username,
        password: req.body.password
    });
    req.login(user, function(err){
        if(err){
            console.log(err);
        } else{
            passport.authenticate("local")(req, res, function(){
                res.redirect("/");
            });
        }
    });
});

app.listen(process.env.PORT || 3000, function(){
    console.log('Server is running');
});```

Kindly help me out in this.

答:
```<code>const passportLocalMongoose = ("passport-local-mongoose");
</code>```

Simply I did not used require in there, silly me.
Now it is solved.

```<code>const passportLocalMongoose = require("passport-local-mongoose");
</code>```

This solved it.

Body:
i have been trying to use passport-local-mongoose in my server.
was making this server with the help from a teutorial video. in the teutorial video this same code works perfectly fine, but in my case its not working. Though I have my database connected to mongodbatlas.
but I am getting a error "First param to schema.plugin() must be a function,"
Screenshot of the ERROR

I wonder how would i use plugin as a function! tried searching in everywhere but nothing helpfull.
following is the code

const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = ("passport-local-mongoose");

const app = express();
app.use(session({
    secret: "alpha beta gama",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb+srv://admin-sumit:password@cluster0-bessu.mongodb.net/myBlog", {
   useNewUrlParser: true,
   useUnifiedTopology: true
 });

const userSchema = new mongoose.Schema({
    email:String,
    password:String,
    comments:String
});

userSchema.plugin(passportLocalMongoose);

const User = new mongoose.model("User", userSchema);

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.get("/blog1comment", function(req, res){
    if(req.isAuthenticated()){
        res.render('blogsingle', { title: 'Express' });
    } else{
        res.redirect("/login");
    }
});

app.post('/register', function(req, res){
    User.register({username: req.body.username}, req.body.password, function(err, user){
        if(err){
            console.log(err);
            res.redirect("/register");
        } else {
            passport.authenticate("local")(req, res, function(){
                res.redirect("/");
            });
        }
    });

});

app.post('/login', function(req, res){
    const user = new User({
        username: req.body.username,
        password: req.body.password
    });
    req.login(user, function(err){
        if(err){
            console.log(err);
        } else{
            passport.authenticate("local")(req, res, function(){
                res.redirect("/");
            });
        }
    });
});

app.listen(process.env.PORT || 3000, function(){
    console.log('Server is running');
});

Kindly help me out in this.

Body:
const passportLocalMongoose = ("passport-local-mongoose");

Simply I did not used require in there, silly me.
Now it is solved.

const passportLocalMongoose = require("passport-local-mongoose");

This solved it.


问:
KeyError pandas dataframe
The purpose of this script is to read a csv file then create a data frame out of it.

The file contains forex historical data.

The file has 7 columns Date, Time, Open, High, Low, Close and Volume, and around 600k rows.

Here is a data sample:

```<code>                        Open     High      Low    Close  Volume
Release Date
2020-02-05 01:50:00  109.450  109.452  109.449  109.451      79
2020-02-05 01:51:00  109.451  109.451  109.449  109.450      26
2020-02-05 01:52:00  109.451  109.453  109.449  109.449      29
2020-02-05 01:53:00  109.449  109.449  109.440  109.442      35
2020-02-05 01:54:00  109.443  109.443  109.432  109.432      49
2020-02-05 01:55:00  109.432  109.439  109.432  109.438      19
2020-02-05 01:56:00  109.439  109.450  109.439  109.449      56
2020-02-05 01:57:00  109.449  109.450  109.446  109.446      20
2020-02-05 01:58:00  109.446  109.451  109.446  109.448      33
2020-02-05 01:59:00  109.449  109.454  109.443  109.443      75
</code>```

After scraping the date and time the script must make some date time calculation like month and day.

Then, some technical analysis using TA-LIB library.

With every new step the code produces a dataframe.

All the new dataframes will be stored in a list.

The last step is to concatenate all these dataframes into one final dataframe.

Here is the code:

```<code>import pandas as pd
import talib

class Data:
    def __init__(self):
        self.dfs = []
        self.names = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']
        self.df = pd.DataFrame()
        self.Close = self.df['Close'].astype(float)

    def file(self, file):
        self.df = pd.read_csv(file, names=self.names,
                              parse_dates={'Release Date': ['Date', 'Time']})
        return self.dfs.append(self.df)

    def year(self):
        self.df['year'] = self.df['Release Date'].dt.year
        return self.dfs.append(self.df['year'])

    def month(self):
        self.df['month'] = self.df['Release Date'].dt.month
        return self.dfs.append(self.df['month'])

    def week(self):
        self.df['week'] = self.df['Release Date'].dt.week
        return self.dfs.append(self.df['week'])

    def day(self):
        self.df['day'] = self.df['Release Date'].dt.day
        return self.dfs.append(self.df['day'])

    def hour(self):
        self.df['hour'] = self.df['Release Date'].dt.hour
        return self.dfs.append(self.df['hour'])

    def minute(self):
        self.df['minute'] = self.df['Release Date'].dt.minute
        return self.dfs.append(self.df['minute'])

    def dema(self):
        self.df['DEMA'] = talib.DEMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['dema'])

    def ema(self):
        self.df['EMA'] = talib.EMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['ema'])

    def KAMA(self):
        self.df['KAMA'] = talib.KAMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['KAMA'])

    def ma(self):
        self.df['MA'] = talib.MA(self.Close, timeperiod=30, matype=0)
        return self.dfs.append(self.df['ma'])

    def action(self):
        self.year()
        self.month()
        self.week()
        self.day()
        self.hour()
        self.minute()
        self.dema()
        self.ema()
        self.KAMA()
        self.ma()

    def print(self):
        self.action()
        print(len(self.dfs))

x = Data()
x.file(r"D:\Projects\Project Forex\EURUSD.csv")
x.print()
</code>```

Here is the error:

```<code>Traceback (most recent call last):

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)

  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'Close'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 74, in <module>
    x = Data()

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 10, in __init__
    self.Close = self.df['Close'].astype(float)

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))

  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'Close'
</code>```

答:
What do you want to accomplish with self.Close?
Do you want a DataFrame with only the column close?

If yes, try self_close instead of self.close.

Title: KeyError pandas dataframe

Body:
The purpose of this script is to read a csv file then create a data frame out of it.

The file contains forex historical data.

The file has 7 columns Date, Time, Open, High, Low, Close and Volume, and around 600k rows.

Here is a data sample:

                        Open     High      Low    Close  Volume
Release Date
2020-02-05 01:50:00  109.450  109.452  109.449  109.451      79
2020-02-05 01:51:00  109.451  109.451  109.449  109.450      26
2020-02-05 01:52:00  109.451  109.453  109.449  109.449      29
2020-02-05 01:53:00  109.449  109.449  109.440  109.442      35
2020-02-05 01:54:00  109.443  109.443  109.432  109.432      49
2020-02-05 01:55:00  109.432  109.439  109.432  109.438      19
2020-02-05 01:56:00  109.439  109.450  109.439  109.449      56
2020-02-05 01:57:00  109.449  109.450  109.446  109.446      20
2020-02-05 01:58:00  109.446  109.451  109.446  109.448      33
2020-02-05 01:59:00  109.449  109.454  109.443  109.443      75

After scraping the date and time the script must make some date time calculation like month and day.

Then, some technical analysis using TA-LIB library.

With every new step the code produces a dataframe.

All the new dataframes will be stored in a list.

The last step is to concatenate all these dataframes into one final dataframe.

Here is the code:

import pandas as pd
import talib

class Data:
    def __init__(self):
        self.dfs = []
        self.names = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']
        self.df = pd.DataFrame()
        self.Close = self.df['Close'].astype(float)

    def file(self, file):
        self.df = pd.read_csv(file, names=self.names,
                              parse_dates={'Release Date': ['Date', 'Time']})
        return self.dfs.append(self.df)

    def year(self):
        self.df['year'] = self.df['Release Date'].dt.year
        return self.dfs.append(self.df['year'])

    def month(self):
        self.df['month'] = self.df['Release Date'].dt.month
        return self.dfs.append(self.df['month'])

    def week(self):
        self.df['week'] = self.df['Release Date'].dt.week
        return self.dfs.append(self.df['week'])

    def day(self):
        self.df['day'] = self.df['Release Date'].dt.day
        return self.dfs.append(self.df['day'])

    def hour(self):
        self.df['hour'] = self.df['Release Date'].dt.hour
        return self.dfs.append(self.df['hour'])

    def minute(self):
        self.df['minute'] = self.df['Release Date'].dt.minute
        return self.dfs.append(self.df['minute'])

    def dema(self):
        self.df['DEMA'] = talib.DEMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['dema'])

    def ema(self):
        self.df['EMA'] = talib.EMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['ema'])

    def KAMA(self):
        self.df['KAMA'] = talib.KAMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['KAMA'])

    def ma(self):
        self.df['MA'] = talib.MA(self.Close, timeperiod=30, matype=0)
        return self.dfs.append(self.df['ma'])

    def action(self):
        self.year()
        self.month()
        self.week()
        self.day()
        self.hour()
        self.minute()
        self.dema()
        self.ema()
        self.KAMA()
        self.ma()

    def print(self):
        self.action()
        print(len(self.dfs))

x = Data()
x.file(r"D:\Projects\Project Forex\EURUSD.csv")
x.print()

Here is the error:

Traceback (most recent call last):

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)

  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'Close'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 74, in <module>
    x = Data()

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 10, in __init__
    self.Close = self.df['Close'].astype(float)

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))

  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'Close'


问:
C How to capture closing a Terminal
Any idea on how to capture closing the terminal window that my program is running in?
While I'm at it, any way to capture when the computer is shutting down but the program is still running, or if the user logs off?</p>

答: If on Unix/Linux: Did you have a look at SIGTERM? This is at least the one sent to you during shutdown.</p>

Title: C How to capture closing a Terminal


问:
Given the lat/long coordinates, how can we find out the city/country?
For example if we have these set of coordinates

```<code>"latitude": 48.858844300000001,
"longitude": 2.2943506,
</code>```

How can we find out the city/country?

答:
Minimize the amount of libraries.

Get a key to use the api at their website and just get the result in a http request:

```<code>curl -i -H "key: YOUR_KEY" -X GET https://api.latlong.dev/lookup?lat=38.7447913&long=-9.1625173
</code>```

Body:
For example if we have these set of coordinates

"latitude": 48.858844300000001,
"longitude": 2.2943506,

How can we find out the city/country?

Body:
Minimize the amount of libraries.

Get a key to use the api at their website and just get the result in a http request:

curl -i -H "key: YOUR_KEY" -X GET https://api.latlong.dev/lookup?lat=38.7447913&long=-9.1625173


问:
Vapor 4/Swift: Middleware development
I'm completely new to Swift and Vapor;

I'm trying to develop an Authorization Middleware that is called from my UserModel (Fluent Model object) and is past in a Required Access Level (int) and Path (string) and

Ensures the user is authenticated,

Checks if the instance of the UserModel.Accesslevel is => the Passed in Required Access level and if not redirects the user to the 'Path'.

I have tried for a couple of days and always get close but never quite get what I'm after.

I have the following (please excuse the poorly named objects):

```<code>import Vapor

public protocol Authorizable: Authenticatable {
    associatedtype ProfileAccess: UserAuthorizable
}

/// status cached using  `UserAuthorizable'
public protocol UserAuthorizable: Authorizable {
    /// Session identifier type.
    associatedtype AccessLevel: LosslessStringConvertible

    /// Identifier identifier.
    var accessLevel: AccessLevel { get }
}

extension Authorizable {
    /// Basic middleware to redirect unauthenticated requests to the supplied path
    ///
    /// - parameters:
    ///    - path: The path to redirect to if the request is not authenticated
    public static func authorizeMiddleware(levelrequired: Int, path: String) -> Middleware {
            return AuthorizeUserMiddleware<Self>(Self.self, levelrequired: levelrequired, path: path)
    }
}

// Helper for creating authorization middleware.
///
//private final class AuthRedirectMiddleware<A>: Middleware
//where A: Authenticatable
final class AuthorizeUserMiddleware<A>: Middleware where A: Authorizable {
    let levelrequired: Int
    let path: String
    let authLevel : Int

init(_ authorizableType: A.Type = A.self, levelrequired: Int, path: String) {
    self.levelrequired = levelrequired
    self.path = path
}

/// See Middleware.respond
   public func respond(to req: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
        if req.auth.has(A.self) {
            print("--------")
            print(path)
            print(levelrequired)
**//            print(A.ProfileAccess.AccessLevel) <- list line fails because the A.ProfileAccess.AccessLevel is a type not value**
            print("--------")
        }
        return next.respond(to: req)
    }
}
</code>```

I added the following to my usermodel

```<code>extension UserModel: Authorizable
{
    typealias ProfileAccess = UserModel
}

extension UserModel: UserAuthorizable {
    typealias AccessLevel = Int
    var accessLevel: AccessLevel { self.userprofile! }
}
</code>```

And Route as such

```<code>    // setup the authentication process
    let session = app.routes.grouped([
      UserModelSessionAuthenticator(),
      UserModelCredentialsAuthenticator(),
      UserModel.authorizeMiddleware(levelrequired: 255, path: "/login"), // this will redirect the user when unauthenticted
      UserModel.authRedirectMiddleware(path: "/login"), // this will redirect the user when unauthenticted
    ])
</code>```

The Path and required level get passed in correctly but I cannot get the instance of the AccessLevel from the current user. (I'm sure I have my c++ hat on and from what I can 'Guess' the UserModel is not actually a populated instance of a user even though the Authentication has already been completed)

I attempted to merge in the 'SessionAuthenticator' process of using a associatedtype to pass across the account info.

My other thought was to check if the user is authenticated and if so I can safely assume the Session Cookie contains my User Id and therefore I could pull the user from the DB (again) and check the users access level from there.

I could be way off here, after a couple of days I don't know which way is the best approach, any guidance would be greatly appreciated.

Cheers

答:
I use the Vapor 4 approach of conforming my User model to ModelAuthenticatable:

```<code>extension User:ModelAuthenticatable
{
    static let usernameKey = \User.$email
    static let passwordHashKey = \User.$password

    func verify(password: String) throws -> Bool
    {
        try Bcrypt.verify(password, created:self.password)
    }
}
</code>```

At the point where I have checked that the user exists and the password is verified as above, then it logs the user in:

```<code>request.auth.login(user)
</code>```

Once logged in, I use a custom Middleware that checks to see if the user is logged in and a 'superuser', if so then the response is passed to the next Middleware in the chain, otherwise it re-directs to the home/login page if not.

```<code>struct SuperUserMiddleware:Middleware
{
    func respond(to request:Request, chainingTo next:Responder) -> EventLoopFuture<Response>
    {
        do
        {
            let user = try request.auth.require(User.self)
            if user.superUser { return next.respond(to:request) }
        }
        catch {}
        let redirect = request.redirect(to:"UNPRIVILEGED")
        return request.eventLoop.makeSucceededFuture(redirect)
    }
}
</code>```

I register the SuperUserMiddleware and use with certain groups of routes in configure.swift as:

```<code>app.middleware.use(SessionsMiddleware(session:MemorySessions(storage:MemorySessions.Storage())))
app.middleware.use(User.sessionAuthenticator(.mysql))
let superUserMW = SuperUserMiddleware()
let userAuthSessionsMW = User.authenticator()
let events = app.grouped("/events").grouped(userAuthSessionsMW, superUserMW)
try EventRoutes(events)
</code>```

Title: Vapor 4/Swift: Middleware development

Body:
I'm completely new to Swift and Vapor;

I'm trying to develop an Authorization Middleware that is called from my UserModel (Fluent Model object) and is past in a Required Access Level (int) and Path (string) and

Ensures the user is authenticated,

Checks if the instance of the UserModel.Accesslevel is => the Passed in Required Access level and if not redirects the user to the 'Path'.

I have tried for a couple of days and always get close but never quite get what I'm after.

I have the following (please excuse the poorly named objects):

import Vapor

public protocol Authorizable: Authenticatable {
    associatedtype ProfileAccess: UserAuthorizable
}

/// status cached using  `UserAuthorizable'
public protocol UserAuthorizable: Authorizable {
    /// Session identifier type.
    associatedtype AccessLevel: LosslessStringConvertible

    /// Identifier identifier.
    var accessLevel: AccessLevel { get }
}

extension Authorizable {
    /// Basic middleware to redirect unauthenticated requests to the supplied path
    ///
    /// - parameters:
    ///    - path: The path to redirect to if the request is not authenticated
    public static func authorizeMiddleware(levelrequired: Int, path: String) -> Middleware {
            return AuthorizeUserMiddleware<Self>(Self.self, levelrequired: levelrequired, path: path)
    }
}

// Helper for creating authorization middleware.
///
//private final class AuthRedirectMiddleware: Middleware
//where A: Authenticatable
final class AuthorizeUserMiddleware: Middleware where A: Authorizable {
    let levelrequired: Int
    let path: String
    let authLevel : Int

init(_ authorizableType: A.Type = A.self, levelrequired: Int, path: String) {
    self.levelrequired = levelrequired
    self.path = path
}

/// See Middleware.respond
   public func respond(to req: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
        if req.auth.has(A.self) {
            print("--------")
            print(path)
            print(levelrequired)
**//            print(A.ProfileAccess.AccessLevel) <- list line fails because the A.ProfileAccess.AccessLevel is a type not value**
            print("--------")
        }
        return next.respond(to: req)
    }
}

I added the following to my usermodel

extension UserModel: Authorizable
{
    typealias ProfileAccess = UserModel
}

extension UserModel: UserAuthorizable {
    typealias AccessLevel = Int
    var accessLevel: AccessLevel { self.userprofile! }
}

And Route as such

    // setup the authentication process
    let session = app.routes.grouped([
      UserModelSessionAuthenticator(),
      UserModelCredentialsAuthenticator(),
      UserModel.authorizeMiddleware(levelrequired: 255, path: "/login"), // this will redirect the user when unauthenticted
      UserModel.authRedirectMiddleware(path: "/login"), // this will redirect the user when unauthenticted
    ])

The Path and required level get passed in correctly but I cannot get the instance of the AccessLevel from the current user. (I'm sure I have my c++ hat on and from what I can 'Guess' the UserModel is not actually a populated instance of a user even though the Authentication has already been completed)

I attempted to merge in the 'SessionAuthenticator' process of using a associatedtype to pass across the account info.

My other thought was to check if the user is authenticated and if so I can safely assume the Session Cookie contains my User Id and therefore I could pull the user from the DB (again) and check the users access level from there.

I could be way off here, after a couple of days I don't know which way is the best approach, any guidance would be greatly appreciated.

Cheers

Body:
I use the Vapor 4 approach of conforming my User model to ModelAuthenticatable:

extension User:ModelAuthenticatable
{
    static let usernameKey = \User.$email
    static let passwordHashKey = \User.$password

    func verify(password: String) throws -> Bool
    {
        try Bcrypt.verify(password, created:self.password)
    }
}

At the point where I have checked that the user exists and the password is verified as above, then it logs the user in:

request.auth.login(user)

Once logged in, I use a custom Middleware that checks to see if the user is logged in and a 'superuser', if so then the response is passed to the next Middleware in the chain, otherwise it re-directs to the home/login page if not.

struct SuperUserMiddleware:Middleware
{
    func respond(to request:Request, chainingTo next:Responder) -> EventLoopFuture<Response>
    {
        do
        {
            let user = try request.auth.require(User.self)
            if user.superUser { return next.respond(to:request) }
        }
        catch {}
        let redirect = request.redirect(to:"UNPRIVILEGED")
        return request.eventLoop.makeSucceededFuture(redirect)
    }
}

I register the SuperUserMiddleware and use with certain groups of routes in configure.swift as:

app.middleware.use(SessionsMiddleware(session:MemorySessions(storage:MemorySessions.Storage())))
app.middleware.use(User.sessionAuthenticator(.mysql))
let superUserMW = SuperUserMiddleware()
let userAuthSessionsMW = User.authenticator()
let events = app.grouped("/events").grouped(userAuthSessionsMW, superUserMW)
try EventRoutes(events)


问:
URL not loading in WebView properly
I have a WebView that I want to point to a certain URL. For some reason the following code just opens the regular Android browser. I want it to load in my webview.</p>

```<code>webView =  (WebView) this.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
</code>```

答:
I followed this example and it worked:

http://marakana.com/forums/android/examples/58.html

Title: URL not loading in WebView properly

Body:
I have a WebView that I want to point to a certain URL. For some reason the following code just opens the regular Android browser. I want it to load in my webview.

webView =  (WebView) this.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");


问:
Why is my array changing after function return?
I have a function, where I filter an array and check whether the property liked of the objects equals one with the help of a checkbox.

```<code>  async getGetLikedMatches(checked){
    if(checked){
      await this.sp.getReleases().subscribe(data => {
        this.allMatches = data;
        this.matches = data;
      });
      this.matches = this.allMatches.filter(match => match.favorit == 1);
      console.log({matches: this.matches, allMatches: this.allMatches}); // matches has correctly 6
                                                                         // elements
      // after the fuction returns matches == allMatches -> 110 element
      // but why?
    }
    else if (!checked){
      await this.sp.getReleases().subscribe(data => {
        this.allMatches = data;
        this.matches = data;
      });
      console.log(this.matches)
    }
</code>```

In my html file I iterate through those matches:

```<code>        <div class="col-3" *ngFor="let match of matches">
            <img [src]="match.images == '' ? url : getImage(match)"
              alt="matches"
             style="min-width: 200px; max-width: 200px; max-height: 200px; min-height: 200px;"
             (click)="onDetailView(match.id, selectedType)"/> <br />
        </div>
</code>```

答:
I think that you wrong use rxjs, try this </p>

```<code>getGetLikedMatches(checked) {
    this.sp.getReleases().subscribe(data => {
       this.allMatches = data;

       if (checked) {
           this.matches = this.allMatches.filter(match => match.favorit == 1);
       } else {
           this.matches = data;
       }

       console.log({ matches: this.matches, allMatches: this.allMatches });
});
</code>```

<p>}</p>

Body:
I have a function, where I filter an array and check whether the property liked of the objects equals one with the help of a checkbox.

  async getGetLikedMatches(checked){
    if(checked){
      await this.sp.getReleases().subscribe(data => {
        this.allMatches = data;
        this.matches = data;
      });
      this.matches = this.allMatches.filter(match => match.favorit == 1);
      console.log({matches: this.matches, allMatches: this.allMatches}); // matches has correctly 6
                                                                         // elements
      // after the fuction returns matches == allMatches -> 110 element
      // but why?
    }
    else if (!checked){
      await this.sp.getReleases().subscribe(data => {
        this.allMatches = data;
        this.matches = data;
      });
      console.log(this.matches)
    }

In my html file I iterate through those matches:

Body:
I think that you wrong use rxjs, try this

getGetLikedMatches(checked) {
    this.sp.getReleases().subscribe(data => {
       this.allMatches = data;

       if (checked) {
           this.matches = this.allMatches.filter(match => match.favorit == 1);
       } else {
           this.matches = data;
       }

       console.log({ matches: this.matches, allMatches: this.allMatches });
});

}


问:
i am a beginner in python can someone help me understand this?
Picture of the code. There is an explanation in the book but i couldn't keep up. Maybe someone can explain this better. Thank you.</p>

答:
I think it about the python function example.
In your pic, it has 2 functions:

print_models: print item of list para 1 and append to list param 2.

show_complete_models: print all item of list input

In function print_models, you can input a parameter, do something and store the result to second parameter.


问:
External JavaScript file will load, but not execute
I'm trying to put a script I had tested succesfully inline in an external file. The script worked fine when I had it inside a pair of html script-tags on the page itself, but when I try to call the script externally the function inside it does not execute and the console does not log the various console.log stages in the script:

```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {

  console.log("Script loaded!");

  $("#btn-april-en").click(function() {

    console.log("Confirm click!");

    $.getJSON("books.json", function(data, status) {

      console.log(data);
      console.log(status);

      $("#img-container").html("<img src=" + data.aprilWitchEn.coverIMG + ">");
      $("#title-en").html("h3>Title: ") + data.aprilWitchEn.title + "</h3>"
    });

  });

});

   </code>```

  <title>Title here</title>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <link rel="stylesheet" href="../assets/css/styles.css">

```
</div>
</div>

</code>```

I have tried to debug it myself with the python http.server, which indicates bootLoader.js is found and loaded:

```<code>Serving HTTP on :: port 8000 (http://[::]:8000/) ...
::1 - - [29/May/2020 08:22:20] "GET / HTTP/1.1" 304 -
::1 - - [29/May/2020 08:22:20] "GET /assets/js/main.js HTTP/1.1" 304 -
::1 - - [29/May/2020 08:22:20] "GET /assets/css/styles.css HTTP/1.1" 304 -
::1 - - [29/May/2020 08:22:20] code 404, message File not found
::1 - - [29/May/2020 08:22:20] "GET /favicon.ico HTTP/1.1" 404 -
::1 - - [29/May/2020 08:22:26] "GET /en/start.html HTTP/1.1" 304 -
::1 - - [29/May/2020 08:22:32] "GET /en/books.html HTTP/1.1" 200 -
::1 - - [29/May/2020 08:22:32] "GET /assets/js/bookLoader.js HTTP/1.1" 200 -
</code>```

But when I press the button with the correct ID, nothing happens.
If there is any more relevant information I can provide to make finding the cause of this problem easier, please let me know?

(A note on directory structure: the HTML above is stored in /root/en/books.html and the JS is in /root/assets/js/bookLoader.js, so the src jumps up a directory level to find the file.)

答:
You should put your scripts at the end of your html file, before the closing body tag.</p>

```<code><body>

  <!-- Your HTML here -->

  <script type="javascript" src="../assets/js/bookLoader.js"></script>
  <script type="javascript" src="../assets/js/main.js"></script>
</body>
</code>```

Body:
I'm trying to put a script I had tested succesfully inline in an external file. The script worked fine when I had it inside a pair of html script-tags on the page itself, but when I try to call the script externally the function inside it does not execute and the console does not log the various console.log stages in the script:

$(document).ready(function() {

  console.log("Script loaded!");

  $("#btn-april-en").click(function() {

    console.log("Confirm click!");

    $.getJSON("books.json", function(data, status) {

      console.log(data);
      console.log(status);

      $("#img-container").html("");
      $("#title-en").html("h3>Title: ") + data.aprilWitchEn.title + "
"
    });

  });

});

  <title>Title here</title>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <link rel="stylesheet" href="../assets/css/styles.css">

I have tried to debug it myself with the python http.server, which indicates bootLoader.js is found and loaded:

Serving HTTP on :: port 8000 (http://[::]:8000/) ...
::1 - - [29/May/2020 08:22:20] "GET / HTTP/1.1" 304 -
::1 - - [29/May/2020 08:22:20] "GET /assets/js/main.js HTTP/1.1" 304 -
::1 - - [29/May/2020 08:22:20] "GET /assets/css/styles.css HTTP/1.1" 304 -
::1 - - [29/May/2020 08:22:20] code 404, message File not found
::1 - - [29/May/2020 08:22:20] "GET /favicon.ico HTTP/1.1" 404 -
::1 - - [29/May/2020 08:22:26] "GET /en/start.html HTTP/1.1" 304 -
::1 - - [29/May/2020 08:22:32] "GET /en/books.html HTTP/1.1" 200 -
::1 - - [29/May/2020 08:22:32] "GET /assets/js/bookLoader.js HTTP/1.1" 200 -

But when I press the button with the correct ID, nothing happens.
If there is any more relevant information I can provide to make finding the cause of this problem easier, please let me know?

(A note on directory structure: the HTML above is stored in /root/en/books.html and the JS is in /root/assets/js/bookLoader.js, so the src jumps up a directory level to find the file.)

Body:
You should put your scripts at the end of your html file, before the closing body tag.

<body>

  <!-- Your HTML here -->

  <script type="javascript" src="../assets/js/bookLoader.js"></script>
  <script type="javascript" src="../assets/js/main.js"></script>
</body>