问:
How to differentiate and sort data in R
Here is part of my data

```<code>dat<-read.table (text=" Name1   Weight1 Name2   Weight2 Name3   Weight3 Name4   Weight4 Name5   Weight5 Name6   Weight6 Name7   Weight7 Name8   Weight8 Name9   Weight9 Name10  Weight10

Rose    Y   Moli    N   Ali     N   Mo      Y   Ko      N   Rose    N   Ali     N   Moli    N   Rose    N   Ko      Y
Ali Y   Bob     N   Bob     N   Magg    N   Alo     N   Sarah   N   Ali Y   Rose    N   Bob     N   Sarah   N
Rose    Y   Moli    Y   Ali     N   Mo      N   Ko      N   Rose    N   Ali     Y   Moli    N   Rose    Y   Ko      Y
    ", header=TRUE)
</code>```

The logic is that when two or more different Names say "Y", we get Y.
When two names are the same and say Y, we get N. As an example row 2, Ali.
Next, I want to count Y . So the outcome is

```<code>No  Weight
3   Y
2   N
4   Y
</code>```

答:
I don't know if I understand the logic very well, but apparently I will only bring N when I have only a single individual repeating Y in the line. Otherwise, when I have two distinct individuals stating Y, I will always bring Y.</p>
```<code>res = apply(dat, 1, function(l) {
  df = data.frame(matrix(as.character(l), nc = 2, byrow = T))
  df = subset(df, X2 == 'Y')
  if (length(unique(df$X1)) == 1) {
    return(data.frame(No = nrow(df), Weight = 'N'))
  } else {
    return(data.frame(No = length(unique(df$X1)), Weight = 'Y'))
  }
})
do.call(rbind, res)
</code>```

Title: How to differentiate and sort data in R

Body:
Here is part of my data

dat<-read.table (text=" Name1   Weight1 Name2   Weight2 Name3   Weight3 Name4   Weight4 Name5   Weight5 Name6   Weight6 Name7   Weight7 Name8   Weight8 Name9   Weight9 Name10  Weight10

Rose    Y   Moli    N   Ali     N   Mo      Y   Ko      N   Rose    N   Ali     N   Moli    N   Rose    N   Ko      Y
Ali Y   Bob     N   Bob     N   Magg    N   Alo     N   Sarah   N   Ali Y   Rose    N   Bob     N   Sarah   N
Rose    Y   Moli    Y   Ali     N   Mo      N   Ko      N   Rose    N   Ali     Y   Moli    N   Rose    Y   Ko      Y
    ", header=TRUE)

The logic is that when two or more different Names say "Y", we get Y.
When two names are the same and say Y, we get N. As an example row 2, Ali.
Next, I want to count Y . So the outcome is

No  Weight
3   Y
2   N
4   Y

Body:
I don't know if I understand the logic very well, but apparently I will only bring N when I have only a single individual repeating Y in the line. Otherwise, when I have two distinct individuals stating Y, I will always bring Y.

res = apply(dat, 1, function(l) {
  df = data.frame(matrix(as.character(l), nc = 2, byrow = T))
  df = subset(df, X2 == 'Y')
  if (length(unique(df$X1)) == 1) {
    return(data.frame(No = nrow(df), Weight = 'N'))
  } else {
    return(data.frame(No = length(unique(df$X1)), Weight = 'Y'))
  }
})
do.call(rbind, res)


来源: stackexchange

问:
How can I make Spring WebServices log all SOAP requests?
I need all SOAP requests logged in the CommonLogFormat (see http://en.wikipedia.org/wiki/Common_Log_Format), plus the duration (the amount of time it takes to process the request).

What's the best way to do this?  It looks like it's possible to configure log4j for Spring WebServices but will it log all the values I'm interested in?
http://pijava.wordpress.com/2009/12/04/spring-webservice-soap-requestresponse-logging-with-log4j/

EDIT: We're actually using SLF4J, not Log4j.  Also, it looks like it's possible to do this by configuring the PayloadLoggingInterceptor:
http://static.springsource.org/spring-ws/site/reference/html/server.html#server-endpoint-interceptor

But I am not sure where the log messages will go.  I added that interceptor to our interceptors and I don't see any log messages.

答:
You can use this to log the raw payload of incoming and outgoing web service calls..  I'm not sure how to log how long the webservice communication took.

```<code>   <!-- Spring Web Service Payload Logging-->
   <logger name="org.springframework.ws.client.MessageTracing">
    <level value="TRACE"/>
   </logger>
   <logger name="org.springframework.ws.server.MessageTracing">
    <level value="TRACE"/>
   </logger>
</code>```

Additional details can be found at http://static.springsource.org/spring-ws/site/reference/html/common.html#logging

ContentLicense: CC BY-SA 3.0

Body:
You can use this to log the raw payload of incoming and outgoing web service calls..  I'm not sure how to log how long the webservice communication took.

   <!-- Spring Web Service Payload Logging-->
   <logger name="org.springframework.ws.client.MessageTracing">
    <level value="TRACE"/>
   </logger>
   <logger name="org.springframework.ws.server.MessageTracing">
    <level value="TRACE"/>
   </logger>

Additional details can be found at http://static.springsource.org/spring-ws/site/reference/html/common.html#logging

ContentLicense: CC BY-SA 4.0


问:
Is there a way to get the source code from an APK file?
The hard drive on my laptop just crashed and I lost all the source code for an app that I have been working on for the past two months.
All I have is the APK file that is stored in my email from when I sent it to a friend.

Is there any way to extract my source code from this APK file?

答:
Single click solution (Windows only)

after reading this loooooonnnnnngggg post,
i have decided to create an automated process to decompile APKs in a single click,

i have decided to share it on github:

https://github.com/shaybc/apk-decompiler

```<code>simply unzip,
copy the apk you want to decompile into "apk-source" folder
and run "go.bat"
find the result in the: "apk-output" folder
</code>```

thats it, enjoy

Body:
Single click solution (Windows only)

after reading this loooooonnnnnngggg post,
i have decided to create an automated process to decompile APKs in a single click,

i have decided to share it on github:

https://github.com/shaybc/apk-decompiler

simply unzip,
copy the apk you want to decompile into "apk-source" folder
and run "go.bat"
find the result in the: "apk-output" folder

thats it, enjoy


问:
Is there a bash macro?
I am trouble shooting a bash script with some echo statements. Because the script is run from another process, I echo to a text file:

echo "…">>~/debug.txt
```
<p>Does bash have some sort of macro which would let me write something like:</p>
<pre class="lang-sh prettyprint-override"><code>log "…"
</code>```

I am using macOS, but I think the question is OS agnostic.

Failing a macro, what is the alternative?

答:
There isn't a built-in one. You can create your own function easily enough:</p>
```<code>log() {
    echo "$@" >>~/debug.txt
}
</code>```

Title: Is there a bash macro?

Body:
I am trouble shooting a bash script with some echo statements. Because the script is run from another process, I echo to a text file:

echo "…">>~/debug.txt

Does bash have some sort of macro which would let me write something like:

log "…"

I am using macOS, but I think the question is OS agnostic.

Failing a macro, what is the alternative?

Body:
There isn't a built-in one. You can create your own function easily enough:

log() {
    echo "$@" >>~/debug.txt
}


答:
Your conditions are not mutually exclusive. For example, row 3 meets both conditions

There are 4 names with weight = "Y": Rose, Moli, Ali, and Ko

There is also a name that is repeated, and has "Y": Rose.

Therefore, I've shown below how to get both conditions separately:

```<code>library(data.table)
setDT(dat)[,row:=.I]
dat = cbind(
  melt(dat[, .SD, .SDcols = patterns("row|^W")],id="row")[, .(row,weight=value)],
  melt(dat[, .SD, .SDcols = patterns("row|^N")],id="row")[, .(name=value)]
)

# rows with two or more different names with "Y"
dat[weight=="Y", uniqueN(name), by=row][V1>=2, row]
</code>```

Output

```<code>[1] 1 3
</code>```
```<code># rows with two same names, both with weight "Y"
dat[weight=="Y", .N, by=.(name,row)][N>=2, row]
</code>```

Output

```<code>[1] 2 3

</code>```

Title: How to differentiate and sort data in R

Body:
Your conditions are not mutually exclusive. For example, row 3 meets both conditions

There are 4 names with weight = "Y": Rose, Moli, Ali, and Ko

There is also a name that is repeated, and has "Y": Rose.

Therefore, I've shown below how to get both conditions separately:

library(data.table)
setDT(dat)[,row:=.I]
dat = cbind(
  melt(dat[, .SD, .SDcols = patterns("row|^W")],id="row")[, .(row,weight=value)],
  melt(dat[, .SD, .SDcols = patterns("row|^N")],id="row")[, .(name=value)]
)

# rows with two or more different names with "Y"
dat[weight=="Y", uniqueN(name), by=row][V1>=2, row]

Output

[1] 1 3

# rows with two same names, both with weight "Y"
dat[weight=="Y", .N, by=.(name,row)][N>=2, row]

Output

[1] 2 3


问:
CSS reverse a whole website (mirror effect)
I am building a multi-lingual website. Some languages (like Hebrew) read from right-to-left. Besides the actual text, those users are used to having navigation and other visual clues reversed.

For example the main menu on top would be aligned to the right. "back" button would point forward, logo on the top right instead of top left, etc.

One solution is of course to create a whole new design, however that would mean I'd have to maintain 2 templates. Not ideal.

I was just thinking, would it be possible to flip the entire design in CSS? Like looking in a mirror?

I'm also opened to better solutions if this seems far fetched.

Technologies used: PHP, Yii, Less.css, jQuery

答:
I agree to Sean's answer, it actually works! But there's one thing I'd like to mention: he needs to remove the "margin" and the "width" in order to make the page more readable but still flipping.

body { -moz-transform: scaleX(-1); -o-transform: scaleX(-1); -webkit-transform: scaleX(-1); transform: scaleX(-1); filter: FlipH; -ms-filter: "FlipH"; }
```


问:
How do i reference external libraries for g++ compiler in command prompt?
I'm trying to compile and run some C++ code using OpenGL libraries without an IDE using the g++ command in a .bat file.

I have spent some time trying to find the correct syntax for g++ compiling without any luck. I know you are supposed to link the header files for the compiler to create a .o file and then supply the library files to the linker so it can create the executable. The explanations i found about g++ syntax went a bit over my head so i was hoping for a concrete example of how to compile a .cpp file using external libraries.

main.cpp looks like this:

```<code>#include "GLFW/glfw3.h"
#include <thread>

int main()
{
glfwInit();
std::this_thread::sleep_for(std::chrono::seconds(1));
glfwTerminate();
}
</code>```

the full path to glfw3.h is C:\C++\glfw\include\GLFW\glfw3.h

The compilers .bat file looks like this:

```<code>@echo off
g++ -std=c++11^
 -I\C:\C++\glfw\include\^
 -c main.cpp^
 -o main.o
pause
</code>```

The linker .bat file:

```<code>@echo off
g++ -L\C:\C++\glfw\lib-mingw\libglfw3.a^
 -L\C:\C++\glfw\lib-mingw\libglfw3dll.a^
 -c main.o^
 -o main.exe
pause
</code>```

I expect the compiler .bat to produce a main.o file which i can later use the linker to make a main.exe file, but instead i get the following error message:

main.cpp:1:24: fatal error: GLFW/glfw3.h: No such file or directory
compilation terminated.

答:
If someone compile in windows using cmd …

Compiling:

g++ -c main.cpp -o main.o -std=c++11 -IC:\C++\glfw\include

Linking to the static libglfw3.a (don’t put -lglew32s if you don’t use it) :

g++ main.o -o main.exe -LC:\C++\glfw\lib-mingw\ -lgdi32 -lglfw3 -lglew32s -lopengl32 -lglu32

Or linking to the dynamic libglfw3dll.a (glfw3.dll must be with the .exe or in c:\windows\system32 or in the path variable):

g++ main.o -o main.exe -LC:\C++\glfw\lib-mingw\ -lgdi32 -lglfw3dll -lglew32s -lopengl32 -lglu32

NB. Be sure that the libraries are in C:\C++\glfw\lib-mingw\ and not in another folder like C: \glfw-3.3.6.bin.WIN64\lib-mingw-w64

Body:
I'm trying to compile and run some C++ code using OpenGL libraries without an IDE using the g++ command in a .bat file.

I have spent some time trying to find the correct syntax for g++ compiling without any luck. I know you are supposed to link the header files for the compiler to create a .o file and then supply the library files to the linker so it can create the executable. The explanations i found about g++ syntax went a bit over my head so i was hoping for a concrete example of how to compile a .cpp file using external libraries.

main.cpp looks like this:

#include "GLFW/glfw3.h"
#include <thread>

int main()
{
glfwInit();
std::this_thread::sleep_for(std::chrono::seconds(1));
glfwTerminate();
}

the full path to glfw3.h is C:\C++\glfw\include\GLFW\glfw3.h

The compilers .bat file looks like this:

@echo off
g++ -std=c++11^
 -I\C:\C++\glfw\include\^
 -c main.cpp^
 -o main.o
pause

The linker .bat file:

@echo off
g++ -L\C:\C++\glfw\lib-mingw\libglfw3.a^
 -L\C:\C++\glfw\lib-mingw\libglfw3dll.a^
 -c main.o^
 -o main.exe
pause

I expect the compiler .bat to produce a main.o file which i can later use the linker to make a main.exe file, but instead i get the following error message:

main.cpp:1:24: fatal error: GLFW/glfw3.h: No such file or directory
compilation terminated.


问:
DIV / Form alignment
First let me start off by saying that I am NO web developer. I work more on embedded stuff. I am completely ignorant to the web design standards or common practices. Any help with be much appreciated.

What I am trying to accomplish

To make a form with several rows of checkboxes / drop downs / textboxes that is incredibly simple and intuitive to operate. It has to be compatible fully with IE 6+. Any other browsers are non mandatory (this is an in house solution that will only be viewed on IE).

The thing I have been trying to accomplish is create another column of checkboxes that align like the current set.

Here is what it currently looks like in IE

My code

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<style type="text/css">
.right_div_check_boxes { width:70%;float:right;} <!-- 75% -->
.left_div_input_boxes {width:15%;float:left;}    <!--15%-->

</style>

<div class="left_div_input_boxes" style="position:relative">

    <form>
    <label>Submitted by (First Name)</label>
    <input type="text" style="width:150px" name="firstname" /><br>
    <label>Submitted by (Last Name)</label><br>
    <input type="text" name="lastname"/>
    <label>Employee Number</label><br>
    <input type="text" name="employnum"/>

    <form>
    <label>What</label>
    <select style="width:150px" name="observer">
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    </select>

    <label>Who</label>
    <form action="">
    <select style="width:150px" name="who">
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    </select>

    <label>Operation Code</label>
    <select  style="width:150px"  name="opcode">
                       <option value="other">TEST</option>
                       <option value="other">TEST</option>
                    </select>

                    <label>Center</label>
                    <select style="width:150px" name="cost">

                        <option value="Zone 1"> Zone 1 </option>
                        <option value="Zone 2"> Zone 2 </option>
                        <option value="Zone 3"> Zone 3 </option>
                    </select>
                    </form>

</div>

<div class="right_div_check_boxes" style="position:relative">
<label>Dangers</label>
<form>

<input type="checkbox" name="vehicle" value="Bike" />Line of Fire<br />
<input type="checkbox" name="vehicle" value="Car" />Respirtory Protection<br />
<input type="checkbox" name="vehicle" value="Car" />Ears/Hearing Protection<br />
<input type="checkbox" name="vehicle" value="Car" />Eye/Face Protection<br />
</div>
<br />

</head>
<body>

</body>
</html>
</code>```

答:
Heres what you want to do. Wrap the left column form in a div with this class:

```<code>.left_column {
float:left;
width:50%;

}
</code>```

And the right column with a div with this class:

```<code> .right_column {
    float:right;
    width:50%;

    }
</code>```

Title: DIV / Form alignment

Body:
First let me start off by saying that I am NO web developer. I work more on embedded stuff. I am completely ignorant to the web design standards or common practices. Any help with be much appreciated.

What I am trying to accomplish

To make a form with several rows of checkboxes / drop downs / textboxes that is incredibly simple and intuitive to operate. It has to be compatible fully with IE 6+. Any other browsers are non mandatory (this is an in house solution that will only be viewed on IE).

The thing I have been trying to accomplish is create another column of checkboxes that align like the current set.

Here is what it currently looks like in IE

My code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

    <form>
    Submitted by (First Name)
    <input type="text" style="width:150px" name="firstname" />

    Submitted by (Last Name)

    <input type="text" name="lastname"/>
    Employee Number

    <input type="text" name="employnum"/>

    <form>
    What
    <select style="width:150px" name="observer">
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    </select>

    Who
    <form action="">
    <select style="width:150px" name="who">
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    </select>

    Operation Code
    <select  style="width:150px"  name="opcode">
                       <option value="other">TEST</option>
                       <option value="other">TEST</option>
                    </select>

                    Center
                    <select style="width:150px" name="cost">

                        <option value="Zone 1"> Zone 1 </option>
                        <option value="Zone 2"> Zone 2 </option>
                        <option value="Zone 3"> Zone 3 </option>
                    </select>
                    </form>

Dangers
<form>

<input type="checkbox" name="vehicle" value="Bike" />Line of Fire

<input type="checkbox" name="vehicle" value="Car" />Respirtory Protection

<input type="checkbox" name="vehicle" value="Car" />Ears/Hearing Protection

<input type="checkbox" name="vehicle" value="Car" />Eye/Face Protection

Body:
Heres what you want to do. Wrap the left column form in a div with this class:

.left_column {
float:left;
width:50%;

}

And the right column with a div with this class:

 .right_column {
    float:right;
    width:50%;

    }


问:
Initializing data binding variable in corresponding fragment
I have been working through the Android Basics in Kotlin Course available on developer.android.com and have ran into a problem with Data Binding. The project I am working on doesn't have solution code provided, but I have been modeling my approach off of a previous similar Codelab.

I am attempting to initialize data binding variables declared in layout xml files in the fragments corresponding to each layout but when I attempt to initialize the fragment variable I receive an error: "Classifier 'EntreeMenuFragment' does not have a companion object, and thus must be initialized here". build.Gradle has both dataBinding and viewBinding set to true.

```<code><layout
    ...

    <data>
        <variable
            name="viewModel"
            type="com.example.lunchtray.model.OrderViewModel" />

        <variable
            name="EntreeMenuFragment"
            type="com.example.lunchtray.ui.order.EntreeMenuFragment" />
    </data>

   ...
</layout>
</code>```
```<code>class EntreeMenuFragment : Fragment() {
    private var _binding: FragmentEntreeMenuBinding? = null
    private val binding get() = _binding!!
    private val sharedViewModel: OrderViewModel by activityViewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentEntreeMenuBinding.inflate(inflater, container, false)
        val root: View = binding.root
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.apply {
            lifecycleOwner = viewLifecycleOwner
            viewModel = sharedViewModel
            EntreeMenuFragment = this@EntreeMenuFragment  // ERROR
        }
    }

    ....
</code>```

答:
It was sufficient to remove capitalization on the binding variable in order to avoid the error:</p>
```<code><variable
            name="entreeMenuFragment"
            type="com.example.lunchtray.ui.order.EntreeMenuFragment" />
</code>```
```<code>            entreeMenuFragment = this@EntreeMenuFragment  // fixed
</code>```

Body:
I have been working through the Android Basics in Kotlin Course available on developer.android.com and have ran into a problem with Data Binding. The project I am working on doesn't have solution code provided, but I have been modeling my approach off of a previous similar Codelab.

I am attempting to initialize data binding variables declared in layout xml files in the fragments corresponding to each layout but when I attempt to initialize the fragment variable I receive an error: "Classifier 'EntreeMenuFragment' does not have a companion object, and thus must be initialized here". build.Gradle has both dataBinding and viewBinding set to true.

<layout
    ...

    <data>
        <variable
            name="viewModel"
            type="com.example.lunchtray.model.OrderViewModel" />

        <variable
            name="EntreeMenuFragment"
            type="com.example.lunchtray.ui.order.EntreeMenuFragment" />
    </data>

   ...
</layout>

class EntreeMenuFragment : Fragment() {
    private var _binding: FragmentEntreeMenuBinding? = null
    private val binding get() = _binding!!
    private val sharedViewModel: OrderViewModel by activityViewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentEntreeMenuBinding.inflate(inflater, container, false)
        val root: View = binding.root
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.apply {
            lifecycleOwner = viewLifecycleOwner
            viewModel = sharedViewModel
            EntreeMenuFragment = this@EntreeMenuFragment  // ERROR
        }
    }

    ....

Body:
It was sufficient to remove capitalization on the binding variable in order to avoid the error:

<variable
            name="entreeMenuFragment"
            type="com.example.lunchtray.ui.order.EntreeMenuFragment" />

            entreeMenuFragment = this@EntreeMenuFragment  // fixed


问:
How can I specify a margin to a chapter reference link in HTML?
I have a body with an header (100px), and a container with a magin (100px).
Like this :

```<code>.myHeader {
  height: 100px;
}

.myContainer {
  margin-top: 100px;
}
</code>```

I'm writing some texts with chapters and i refers some chapters with a button.

```<code><a href={`#${chapter.step}`}>
    <Button key={chapter.id} >
       {chapter.name}
    </Button>
</a>
</code>```

On the text side, i have obviously a
...text
.

This works well, except the fact that the link leads me to the top of the page, behind the header.

How I can specify the reference to begin at a certain height ?

Thank you

答:
From what I can collect from your post, and I'm not sure I'm correct because you provided a somewhat vague information, you are trying to keep the container 100px from the top of the window, so that the header remains visible. Referring to the window boundaries usually requires position: fixed;. Here is an example that looks like what I think your description refers to:

body {
  margin: 0;
}

.myHeader {
  height: 100px;
  margin: 0;
  background: blue;
  text-align: center;
  font: 50px/100px serif;
}

.myContainer {
  position: fixed;
  top: 100px;
  bottom: 0;
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2 class="myHeader">
  Header
</h2>
<section class="myContainer">
  Jump to Chapter 2
  <h3 id="Chapter_1">Chapter 1</h3>
  Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1.

  <h3 id="Chapter_2">Chapter 2</h3>
  Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2.
</section></code>```

Body:
I have a body with an header (100px), and a container with a magin (100px).
Like this :

.myHeader {
  height: 100px;
}

.myContainer {
  margin-top: 100px;
}

I'm writing some texts with chapters and i refers some chapters with a button.

<a href={`#${chapter.step}`}>
    <Button key={chapter.id} >
       {chapter.name}
    </Button>

On the text side, i have obviously a
...text
.

This works well, except the fact that the link leads me to the top of the page, behind the header.

How I can specify the reference to begin at a certain height ?

Thank you

Body:
From what I can collect from your post, and I'm not sure I'm correct because you provided a somewhat vague information, you are trying to keep the container 100px from the top of the window, so that the header remains visible. Referring to the window boundaries usually requires position: fixed;. Here is an example that looks like what I think your description refers to:

body {
  margin: 0;
}

.myHeader {
  height: 100px;
  margin: 0;
  background: blue;
  text-align: center;
  font: 50px/100px serif;
}

.myContainer {
  position: fixed;
  top: 100px;
  bottom: 0;
  overflow: auto;
}

<h2 class="myHeader">
  Header
</h2>
<section class="myContainer">
  <a href="#Chapter_2">Jump to Chapter 2</a>
  <h3 id="Chapter_1">Chapter 1</h3>
  Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1. Text of chapter 1.

  <h3 id="Chapter_2">Chapter 2</h3>
  Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2. Text of chapter 2.
</section>


问:
Python expecting expected str, bytes or os.PathLike object, not StringVar
Okay, so I'm working on a project that monitors two selected folders and automatically moves files created or edited within the last twenty-four hours from Folder_A to Folder_B.  It also will check the two folders manually when the user clicks the scan button.  So far it will select the two folders, but when I click the scan button I get this error.  How would I go about fixing the error? My code is below the error.  Please be understanding that I am still really new to python, so there might be quite a few really stupid mistakes in here.

```<code> File
"C:\Users\--\AppData\Local\Programs\Python\Python310\Projects\File_transfer.py", line 63, in <module>
   scan_btn=Button(text="Scan", command = submitFunction())
 File "C:\Users\--\AppData\Local\Programs\Python\Python310\Projects\File_transfer.py", line 34, in submitFunction
   for root, dirs,files in os.walk(origin_path):
 File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\lib\os.py", line 342, in walk
   return _walk(fspath(top), topdown, onerror, followlinks)
TypeError: expected str, bytes or os.PathLike object, not StringVar
</code>```

My code for the project:

```<code>import tkinter
import tkinter as tk
from tkinter import *
from tkinter import filedialog
import os,time
import datetime
import shutil
import datetime as dt

def browse_button():
    # Allow user to select a directory and store it in global var
    # called origin_path
    global origin_path
    filename = filedialog.askdirectory()
    origin_path.set(filename)
    print(filename)

def browse_button2():
    # Allow user to select a directory and store it in global var
    # called receiving_path
    global receiving_path
    filename = filedialog.askdirectory()
    receiving_path.set(filename)
    print(filename)

def submitFunction() :
    for root, dirs,files in os.walk(origin_path):
        for fname in files:
            path = os.path.join(root, fname)
            st = os.stat(path)
            mtime = dt.datetime.fromtimestamp(st.st_mtime)
            shutil.move(path, dest)
    print('Submit button is clicked.')

root = Tk()
origin_path = StringVar()
receiving_path = StringVar()

#First Browse Button Label
lbl1 = Label(master=root,textvariable=origin_path)
lbl1.grid(row=0, column=1)
#Second Browse Button Label
lbl1_2 = Label(master=root,textvariable=receiving_path)
lbl1_2.grid(row=1, column=1)

lbl1_3 = Label(master=root)
lbl1_3.grid(row=2, column=1)

button = Button(text="Browse", command=browse_button)
button.grid(row=0, column=3)

button2 = Button(text="Browse", command=browse_button2)
button2.grid(row=1, column=3)

scan_btn=Button(text="Scan", command = lambda:submitFunction())
scan_btn.grid(row=2, column=7)

mainloop()

now = dt.datetime.now()
ago = now-dt.timedelta(hours=24)
strftime = "%H:%M %m/%d/%Y"
created = 'origin_path'
dest = 'receiving_path'
file_path = 'file:///'+os.getcwd()+'/' + ''

print("Last modified: %s" % time.ctime(os.path.getmtime(file_path)))
print("Created: %s" % time.ctime(os.path.getctime(file_path)))

for root, dirs,files in os.walk(origin_path):
    for fname in files:
        path = os.path.join(root, fname)
        st = os.stat(path)
        mtime = dt.datetime.fromtimestamp(st.st_mtime)
        if mtime > ago:
            print("True:  ", fname, " at ", mtime.strftime("%H:%M %m/%d/%Y"))
            shutil.move(path, dest)

def find_info(): #this first func. works fine.for root, dirs, files in os.walk(created):
    for root, dirs, files in os,walk(origin_path):
        for fname in files:
            path = os.path.join(root, fname)
            st = os.stat(path)
            mtime = dt.datetime.fromtimestamp(st.st_mtime)
    if mtime > ago:
        print(True)
    else:
        print(False)

print (find_info())
print (move())

print (os.listdir(dest))
print (os.listdir(created))
</code>```

答:
The problem is that you are calling os.walk with a tkinter StringVar, but os.walk does not accept StringVars; it only accepts objects of type str, bytes, or os.PathLike (e.g. pathlib Path objects).

You can fix the error by using os.walk(origin_path.get()) instead of os.walk(origin_path). This gets the string from the StringVar and passes that to os.walk, instead of passing the StringVar to os.walk directly.

Body:
Okay, so I'm working on a project that monitors two selected folders and automatically moves files created or edited within the last twenty-four hours from Folder_A to Folder_B.  It also will check the two folders manually when the user clicks the scan button.  So far it will select the two folders, but when I click the scan button I get this error.  How would I go about fixing the error? My code is below the error.  Please be understanding that I am still really new to python, so there might be quite a few really stupid mistakes in here.

 File
"C:\Users\--\AppData\Local\Programs\Python\Python310\Projects\File_transfer.py", line 63, in <module>
   scan_btn=Button(text="Scan", command = submitFunction())
 File "C:\Users\--\AppData\Local\Programs\Python\Python310\Projects\File_transfer.py", line 34, in submitFunction
   for root, dirs,files in os.walk(origin_path):
 File "C:\Users\quirk\AppData\Local\Programs\Python\Python310\lib\os.py", line 342, in walk
   return _walk(fspath(top), topdown, onerror, followlinks)
TypeError: expected str, bytes or os.PathLike object, not StringVar

My code for the project:

import tkinter
import tkinter as tk
from tkinter import *
from tkinter import filedialog
import os,time
import datetime
import shutil
import datetime as dt

def browse_button():
    # Allow user to select a directory and store it in global var
    # called origin_path
    global origin_path
    filename = filedialog.askdirectory()
    origin_path.set(filename)
    print(filename)

def browse_button2():
    # Allow user to select a directory and store it in global var
    # called receiving_path
    global receiving_path
    filename = filedialog.askdirectory()
    receiving_path.set(filename)
    print(filename)

def submitFunction() :
    for root, dirs,files in os.walk(origin_path):
        for fname in files:
            path = os.path.join(root, fname)
            st = os.stat(path)
            mtime = dt.datetime.fromtimestamp(st.st_mtime)
            shutil.move(path, dest)
    print('Submit button is clicked.')

root = Tk()
origin_path = StringVar()
receiving_path = StringVar()

#First Browse Button Label
lbl1 = Label(master=root,textvariable=origin_path)
lbl1.grid(row=0, column=1)
#Second Browse Button Label
lbl1_2 = Label(master=root,textvariable=receiving_path)
lbl1_2.grid(row=1, column=1)

lbl1_3 = Label(master=root)
lbl1_3.grid(row=2, column=1)

button = Button(text="Browse", command=browse_button)
button.grid(row=0, column=3)

button2 = Button(text="Browse", command=browse_button2)
button2.grid(row=1, column=3)

scan_btn=Button(text="Scan", command = lambda:submitFunction())
scan_btn.grid(row=2, column=7)

mainloop()

now = dt.datetime.now()
ago = now-dt.timedelta(hours=24)
strftime = "%H:%M %m/%d/%Y"
created = 'origin_path'
dest = 'receiving_path'
file_path = 'file:///'+os.getcwd()+'/' + ''

print("Last modified: %s" % time.ctime(os.path.getmtime(file_path)))
print("Created: %s" % time.ctime(os.path.getctime(file_path)))

for root, dirs,files in os.walk(origin_path):
    for fname in files:
        path = os.path.join(root, fname)
        st = os.stat(path)
        mtime = dt.datetime.fromtimestamp(st.st_mtime)
        if mtime > ago:
            print("True:  ", fname, " at ", mtime.strftime("%H:%M %m/%d/%Y"))
            shutil.move(path, dest)

def find_info(): #this first func. works fine.for root, dirs, files in os.walk(created):
    for root, dirs, files in os,walk(origin_path):
        for fname in files:
            path = os.path.join(root, fname)
            st = os.stat(path)
            mtime = dt.datetime.fromtimestamp(st.st_mtime)
    if mtime > ago:
        print(True)
    else:
        print(False)

print (find_info())
print (move())

print (os.listdir(dest))
print (os.listdir(created))


问:
Regex Match anything inside the string
How Can I match XX.Xx("$\bH.Pt#S+V0&DJT-R&", gM) this pattern in a string shown below, the only constant is XX. two arguments are random

```<code>XX.Xx("$\bH.Pt#S+V0&DJT-R&", gM)
XX.Vx("\'\x40]\tFv9](H\x40J[)", F6)

</code>```

[XX.Ux("gI\ny", sl), Ar, XX.Rx("\t|", pO), Jd, XX.kx("xW\n", CM), Wm, XX.wx("U\vyV", DO), jr, XX.Mx("U\vxW", GO), Zm, XX.tx("a{O", xO), Hm, XX.RV(Qk, Hl, Q0), Qd, XX.Nx("\t|", OM), Br, XX.zx("{I\v", vM), jd, XX.gx("U\vxS", W6), nm, XX.kV(Qk, UM, Q0), Bd, XX.rx("\t|", RM), Xm, XX.mx("V\r", kM), Id, XX.dx("J\t~", KY), Lm, XX.hx("xV\v", wN), Sd, XX.bx("xU\x00", d6), rd, XX.Cx("axK", BM), Wd, XX.qx("}~", h6), Zd, XX.sx("gI\b", b6), Hd, XX.Kx("xU", C6), Lh, XX.Wx("U\ry", q6), pm["fpValStr"], XX.wV(Qk, Ml, F0), vd, XX.Zx("sH", LN), jm, XX.Hx("{I\f", jM), Xh], Vh && (Wr.push(XX.nx("xT", XN), XX.Ax("", VN)), Th = j3(N3)), Wr.push(XX.Fx("J\nu", nY), Md), Kr = ph(j2, [Wr, A0]), Dh = Wr.join(Kr), qr(XX.Ex("9I\x00", TN).concat(Dh["slice"](N3, W0)));
```

https://regex101.com/r/Ui71E9/1

答:
(XX\.[A-Za-z]*\("([^"]*)",\s*([0-9A-Za-z]{2})\),\s*[0-9A-Za-z)]+)

To capture multiple times

run the regexp on the big string

if no matches, break

use the second and third capture groups as you like

get the first capture group

in the big string replace that capture group with an empty string

do it again with the modified string

Old Answer

XX\.[A-Za-z]*\("(.*)",\s*([0-9A-Za-z]{2})\)

I included capture groups if your interested

I can explain it if you'd like

XX\. The beginning is probably obvious. XX\.

it's important to note that . in regex matches anything, however I assume you specifically want to get a period. Thus we escape it like \.

[A-Za-z]* next we are matching any amount of characters from capital A to capital Z and lower case a and lowercase z. I assume that it will always be 2 characters but I'll let it slide for now

\( next we escape the open parenthesis because parenthesis represents a capture group

" next we look for a quotation mark

(.*)" next we capture anything intil we hit another quotation mark.

It's important to note that if the string has an escaped quotation mark, this regexp breaks. If you need an escaped quotation mark also I'll try to help you out

, next we look for a comma

\s* after that we look for any amount of spaces. Could be zero, could be a hundred

(0-9A-Za-z){2} next we capture two characters that could be 0-9 A-Z and A-Z

\) finally we end with a parenthesis

Title: Regex Match anything inside the string

Body:
How Can I match XX.Xx("$\bH.Pt#S+V0&DJT-R&", gM) this pattern in a string shown below, the only constant is XX. two arguments are random

XX.Xx("$\bH.Pt#S+V0&DJT-R&", gM)
XX.Vx("\'\x40]\tFv9](H\x40J[)", F6)

[XX.Ux("gI\ny", sl), Ar, XX.Rx("\t|", pO), Jd, XX.kx("xW\n", CM), Wm, XX.wx("U\vyV", DO), jr, XX.Mx("U\vxW", GO), Zm, XX.tx("a{O", xO), Hm, XX.RV(Qk, Hl, Q0), Qd, XX.Nx("\t|", OM), Br, XX.zx("{I\v", vM), jd, XX.gx("U\vxS", W6), nm, XX.kV(Qk, UM, Q0), Bd, XX.rx("\t|", RM), Xm, XX.mx("V\r", kM), Id, XX.dx("J\t~", KY), Lm, XX.hx("xV\v", wN), Sd, XX.bx("xU\x00", d6), rd, XX.Cx("axK", BM), Wd, XX.qx("}~", h6), Zd, XX.sx("gI\b", b6), Hd, XX.Kx("xU", C6), Lh, XX.Wx("U\ry", q6), pm["fpValStr"], XX.wV(Qk, Ml, F0), vd, XX.Zx("sH", LN), jm, XX.Hx("{I\f", jM), Xh], Vh && (Wr.push(XX.nx("xT", XN), XX.Ax("", VN)), Th = j3(N3)), Wr.push(XX.Fx("J\nu", nY), Md), Kr = ph(j2, [Wr, A0]), Dh = Wr.join(Kr), qr(XX.Ex("9I\x00", TN).concat(Dh["slice"](N3, W0)));

https://regex101.com/r/Ui71E9/1


问:
Getting an empty output when calculating two same numbers and unable to change key name in dict w/ Regex
Edit: I was able to figure out the first part of this question by adding a condition that if the cost and paid are the same and matches a key value in money then it adds it to the dict.

I'm sorry if the title is confusing. Basically, I am writing a function that takes in a number as the item cost and the second as the amount you paid with. Then it tells you your change in bills and coins.

```<code>  def right_change(cost, paid):

  money = {
    "$20 bill" : 20,
    "$10 bill" : 10,
    "$5 bill" : 5,
    "$1 bill": 1,
    "quarter": 0.25,
    "dime" : 0.10,
    "nickel": 0.05,
    "penny": 0.01
  }

  amount = paid - cost
  change = {}

  for item in money:
    while amount >= money[item]:
      amount -= money[item]
      amount = float(f'{amount:.2f}')
      if item not in change:
          change[item] = 1
      else:
          change[item] += 1
</code>```

I get the expected output when I use floats such as (5.40, 20) --> {$10 bill: 1, $1 bill: 4, quarter: 2, dime: 1}
But if I use exact numbers like (20, 20) it will return an empty object when I want {$20 bill: 1}

I am also trying to change the names to plurals if their quantity is more than 1. In order to be less redundant and typing out conditions for each word, I tried using Regex:

```<code>def plurals(dict):
  new_dict = {}
  for item in dict:
    if dict[item] > 1 and re.match('/[^y]$/gm', item):
      new_dict[item+"s"] = dict[item]
      if re.match('p', item):
          new_dict['pennies'] = dict[item]
    else:
        new_dict[item] = dict[item]

  return new_dict
</code>```

It will still output the change but it won't change anything. Any help is appreciated! I've been spending hours trying to figure this out.

答:
For the name change issue:

```<code>def set_to_plural_if_more_than_one(old_dict):
    new_dict = {}
    for item in old_dict:
        if old_dict[item] > 1:
            if item[-1] == "y":
                new_dict[item[:-1] + "ies"] = old_dict[item]
            else:
                new_dict[item + "s"] = old_dict[item]
        else:
            new_dict[item] = old_dict[item]
    return new_dict
</code>```

You can use regex but I feel like in this case it's an overkill since you are simply distinguishing between some basic strings you know and not searching for any advanced patterns.

Also just in general I would avoid overwriting names of pythons builtins such as dict as variable or argument names in your code since they can cause weird and sometimes hard to debug behaviour.

Body:
Edit: I was able to figure out the first part of this question by adding a condition that if the cost and paid are the same and matches a key value in money then it adds it to the dict.

I'm sorry if the title is confusing. Basically, I am writing a function that takes in a number as the item cost and the second as the amount you paid with. Then it tells you your change in bills and coins.

  def right_change(cost, paid):

  money = {
    "$20 bill" : 20,
    "$10 bill" : 10,
    "$5 bill" : 5,
    "$1 bill": 1,
    "quarter": 0.25,
    "dime" : 0.10,
    "nickel": 0.05,
    "penny": 0.01
  }

  amount = paid - cost
  change = {}

  for item in money:
    while amount >= money[item]:
      amount -= money[item]
      amount = float(f'{amount:.2f}')
      if item not in change:
          change[item] = 1
      else:
          change[item] += 1

I get the expected output when I use floats such as (5.40, 20) --> {$10 bill: 1, $1 bill: 4, quarter: 2, dime: 1}
But if I use exact numbers like (20, 20) it will return an empty object when I want {$20 bill: 1}

I am also trying to change the names to plurals if their quantity is more than 1. In order to be less redundant and typing out conditions for each word, I tried using Regex:

def plurals(dict):
  new_dict = {}
  for item in dict:
    if dict[item] > 1 and re.match('/[^y]$/gm', item):
      new_dict[item+"s"] = dict[item]
      if re.match('p', item):
          new_dict['pennies'] = dict[item]
    else:
        new_dict[item] = dict[item]

  return new_dict

It will still output the change but it won't change anything. Any help is appreciated! I've been spending hours trying to figure this out.

Body:
For the name change issue:

def set_to_plural_if_more_than_one(old_dict):
    new_dict = {}
    for item in old_dict:
        if old_dict[item] > 1:
            if item[-1] == "y":
                new_dict[item[:-1] + "ies"] = old_dict[item]
            else:
                new_dict[item + "s"] = old_dict[item]
        else:
            new_dict[item] = old_dict[item]
    return new_dict

You can use regex but I feel like in this case it's an overkill since you are simply distinguishing between some basic strings you know and not searching for any advanced patterns.

Also just in general I would avoid overwriting names of pythons builtins such as dict as variable or argument names in your code since they can cause weird and sometimes hard to debug behaviour.


问:
Can I pass a PHP object to a constructor for that same object?
(SO closed out my previous question, so I will try to be clearer this time)
When I run the following code in my browser:

```<code><?php
class MyNode {
    public $name;
    public $children = array();
    public $parent;

    public function __construct(string $name, $parent) {
        echo "in constructor\n";
      $this->name = $name;
      echo "name: " . $this->name . ".\n";
      $this->parent = $parent;
      #$this->parent = &$parent;
      echo "parent: " . $this->parent . ".\n";
    }
}
$RootNode = new MyNode("Root", null);
echo "done root x\n";
#$ChildNode = new MyNode("Child1", null);
$ChildNode = new MyNode("Child1", $RootNode);
echo "done child\n";
?>
</code>```

The browser prints "in constructor name: Root. parent: . done root x in constructor name: Child1." and then stops with the error (in Developer console) "500 (Internal Server Error)". If I use the line (commented above) that passes null instead of $RootNode, it succeeds.

What is the right way to pass $RootNode to the MyNode constructor?

答:
You're extremely close - if you had error reporting on, the issue would be fairly clear. Your code is emitting an error when it tries to print $this->parent because PHP can't convert instances of MyNode to a string - which PHP needs to do to print it.

Here's an example of your code. It's emitting this error:

```<code>Fatal error: Uncaught Error: Object of class MyNode could not be converted to string in /in/T7Os5:12
Stack trace:
#0 /in/T7Os5(18): MyNode->__construct('Child1', Object(MyNode))
#1 {main}
  thrown in /in/T7Os5 on line 12
</code>```

I suggest implementing a __toString() method (example):

```<code><?php
class MyNode {
    public $name;
    public $children = array();
    public $parent;

    public function __construct(string $name, $parent) {
      echo "in constructor\n";
      $this->name = $name;
      echo "name: " . $this->name . ".\n";
      $this->parent = $parent;
      echo "parent: " . $this->parent . ".\n";
    }

    public function __toString()
    {
        return $this->name;
    }
}

$RootNode = new MyNode("Root", null);
echo "done root x\n";
$ChildNode = new MyNode("Child1", $RootNode);
echo "done child\n";
</code>```

Body:
(SO closed out my previous question, so I will try to be clearer this time)
When I run the following code in my browser:

<?php
class MyNode {
    public $name;
    public $children = array();
    public $parent;

    public function __construct(string $name, $parent) {
        echo "in constructor\n";
      $this->name = $name;
      echo "name: " . $this->name . ".\n";
      $this->parent = $parent;
      #$this->parent = &$parent;
      echo "parent: " . $this->parent . ".\n";
    }
}
$RootNode = new MyNode("Root", null);
echo "done root x\n";
#$ChildNode = new MyNode("Child1", null);
$ChildNode = new MyNode("Child1", $RootNode);
echo "done child\n";
?>

The browser prints "in constructor name: Root. parent: . done root x in constructor name: Child1." and then stops with the error (in Developer console) "500 (Internal Server Error)". If I use the line (commented above) that passes null instead of $RootNode, it succeeds.

What is the right way to pass $RootNode to the MyNode constructor?

Body:
You're extremely close - if you had error reporting on, the issue would be fairly clear. Your code is emitting an error when it tries to print $this->parent because PHP can't convert instances of MyNode to a string - which PHP needs to do to print it.

Here's an example of your code. It's emitting this error:

Fatal error: Uncaught Error: Object of class MyNode could not be converted to string in /in/T7Os5:12
Stack trace:
#0 /in/T7Os5(18): MyNode->__construct('Child1', Object(MyNode))
#1 {main}
  thrown in /in/T7Os5 on line 12

I suggest implementing a __toString() method (example):

<?php
class MyNode {
    public $name;
    public $children = array();
    public $parent;

    public function __construct(string $name, $parent) {
      echo "in constructor\n";
      $this->name = $name;
      echo "name: " . $this->name . ".\n";
      $this->parent = $parent;
      echo "parent: " . $this->parent . ".\n";
    }

    public function __toString()
    {
        return $this->name;
    }
}

$RootNode = new MyNode("Root", null);
echo "done root x\n";
$ChildNode = new MyNode("Child1", $RootNode);
echo "done child\n";


问:
Issues removing words from a list in Python
I'm building a Wordle solver. Basically removing words from a list, if they don't have specific characters, or don't have them at specific locations. I'm not concerned about the statistics for optimal choices yet.

When I run the below code (I think all relevant sections are included), my output is clear that it found a letter matching position to the 'word of the day'. But then the next iteration, it will choose a word that doesn't have that letter, when it should only select from remaining words.

Are words not actually being removed? Or is there something shadowing a scope I can't find?
I've rewritten whole sections, with the exact same problem happening.

```<code>#Some imports and reading the word list here.

def word_compare(word_of_the_day, choice_word):
    results = []
    index = 0
    letters[:] = choice_word
    for letter in letters:
        if letter is word_of_the_day[index]:
            results.append((letter, 2, index))
        elif letter in word_of_the_day:
            results.append((letter, 1, index))
        else:
            results.append((letter, 0, index))
        index += 1
    print("\nIteration %s\nWord of the Day: %s,\nChoice Word: %s,\nResults: %s" % (
        iteration, word_of_the_day, choice_word, results))
    return results

def remove_wrong_words():
    for item in results:
        if item[1] == 0:
            for word in words:
                if item[0] in word:
                    words.remove(word)
    for item in results:
        if item[1] == 2:
            for word in words:
                if word[item[2]] != item[0]:
                    words.remove(word)
    print("Words Remaining: %s" % len(words))
    return words

words, letters = prep([])
# choice_word = best_word_choice()
choice_word = "crane"
iteration = 1
word_of_the_day = random.choice(words)

while True:
    if choice_word == word_of_the_day:
        break
    else:
        words.remove(choice_word)
        results = word_compare(word_of_the_day, choice_word)
        words = remove_wrong_words()
        if len(words) < 10:
            print(words)
        choice_word = random.choice(words)
        iteration += 1
</code>```

Output I'm getting:

```<code>Iteration 1
Word of the Day: stake,
Choice Word: crane,
Results: [('c', 0, 0), ('r', 0, 1), ('a', 2, 2), ('n', 0, 3), ('e', 2, 4)]
Words Remaining: 386

Iteration 2
Word of the Day: stake,
Choice Word: lease,
Results: [('l', 0, 0), ('e', 1, 1), ('a', 2, 2), ('s', 1, 3), ('e', 2, 4)]
Words Remaining: 112

Iteration 3
Word of the Day: stake,
Choice Word: paste,
Results: [('p', 0, 0), ('a', 1, 1), ('s', 1, 2), ('t', 1, 3), ('e', 2, 4)]
Words Remaining: 81

Iteration 4
Word of the Day: stake,
Choice Word: spite,
</code>```

... This continues for a while until solved. In this output, 'a' is found to be in the correct place (value of 2 in the tuple) on the second iteration. This should remove all words from the list that don't have 'a' as the third character. Instead 'paste' and 'spite' are chosen for later iterations from that same list, instead of having been removed.

答: I think one of your issues is the following line: if letter is word_of_the_day[index]:. This should be == not is as the latter checks for whether the two objects being compared have the same memory address (i.e. id()), not whether they have the same value. Thus, results will never return a tuple with a value of 2 in position 1, so this means the second for loop in remove_wrong_words won't do anything either. There may be more going on but I'd like a concrete example to run before digging in further.

Body:
I'm building a Wordle solver. Basically removing words from a list, if they don't have specific characters, or don't have them at specific locations. I'm not concerned about the statistics for optimal choices yet.

When I run the below code (I think all relevant sections are included), my output is clear that it found a letter matching position to the 'word of the day'. But then the next iteration, it will choose a word that doesn't have that letter, when it should only select from remaining words.

Are words not actually being removed? Or is there something shadowing a scope I can't find?
I've rewritten whole sections, with the exact same problem happening.

#Some imports and reading the word list here.

def word_compare(word_of_the_day, choice_word):
    results = []
    index = 0
    letters[:] = choice_word
    for letter in letters:
        if letter is word_of_the_day[index]:
            results.append((letter, 2, index))
        elif letter in word_of_the_day:
            results.append((letter, 1, index))
        else:
            results.append((letter, 0, index))
        index += 1
    print("\nIteration %s\nWord of the Day: %s,\nChoice Word: %s,\nResults: %s" % (
        iteration, word_of_the_day, choice_word, results))
    return results

def remove_wrong_words():
    for item in results:
        if item[1] == 0:
            for word in words:
                if item[0] in word:
                    words.remove(word)
    for item in results:
        if item[1] == 2:
            for word in words:
                if word[item[2]] != item[0]:
                    words.remove(word)
    print("Words Remaining: %s" % len(words))
    return words

words, letters = prep([])
# choice_word = best_word_choice()
choice_word = "crane"
iteration = 1
word_of_the_day = random.choice(words)

while True:
    if choice_word == word_of_the_day:
        break
    else:
        words.remove(choice_word)
        results = word_compare(word_of_the_day, choice_word)
        words = remove_wrong_words()
        if len(words) < 10:
            print(words)
        choice_word = random.choice(words)
        iteration += 1

Output I'm getting:

Iteration 1
Word of the Day: stake,
Choice Word: crane,
Results: [('c', 0, 0), ('r', 0, 1), ('a', 2, 2), ('n', 0, 3), ('e', 2, 4)]
Words Remaining: 386

Iteration 2
Word of the Day: stake,
Choice Word: lease,
Results: [('l', 0, 0), ('e', 1, 1), ('a', 2, 2), ('s', 1, 3), ('e', 2, 4)]
Words Remaining: 112

Iteration 3
Word of the Day: stake,
Choice Word: paste,
Results: [('p', 0, 0), ('a', 1, 1), ('s', 1, 2), ('t', 1, 3), ('e', 2, 4)]
Words Remaining: 81

Iteration 4
Word of the Day: stake,
Choice Word: spite,

... This continues for a while until solved. In this output, 'a' is found to be in the correct place (value of 2 in the tuple) on the second iteration. This should remove all words from the list that don't have 'a' as the third character. Instead 'paste' and 'spite' are chosen for later iterations from that same list, instead of having been removed.


问:
What is a good way to write a function to load multiple years of data - each in its own file - as a function?
The code I have works but I can't help but think there is a much more efficient way to write it. Essentially the function I would want to write would output the df variable.</p>
```<code>read_data_raw<- function(y1,y2) {
  raw_scores_y1_y2 <- read.csv(paste0("raw_scores_",y1,"_",y2,".txt"))
  return(raw_scores_y1_y2)
}

read_data_vegas<- function(y1,y2) {
  vegas_y1_y2 <- read.csv(paste0("vegas_",y1,"_",y2,".txt"))
  return(vegas_y1_y2)
}

raw_scores <- read_data_raw(12,13)
vegas <- read_data_vegas(12,13)
df <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
raw_scores <- read_data_raw(13,14)
vegas <- read_data_vegas(13,14)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)
raw_scores <- read_data_raw(14,15)
vegas <- read_data_vegas(14,15)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)
raw_scores <- read_data_raw(15,16)
vegas <- read_data_vegas(15,16)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)
raw_scores <- read_data_raw(16,17)
vegas <- read_data_vegas(16,17)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)
raw_scores <- read_data_raw(17,18)
vegas <- read_data_vegas(17,18)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)
raw_scores <- read_data_raw(18,19)
vegas <- read_data_vegas(18,19)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)
</code>```

答:
You can try with purrr::map_df to perform inner join and combine all the dataframes into one.

```<code>library(dplyr)
library(purrr)

vals <- 12:18
df <- map_df(vals,
             ~inner_join(read_data_raw(.x,.x + 1),
                         read_data_vegas(.x,.x + 1),
                          by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId")))
</code>```

Body:
The code I have works but I can't help but think there is a much more efficient way to write it. Essentially the function I would want to write would output the df variable.

read_data_raw<- function(y1,y2) {
  raw_scores_y1_y2 <- read.csv(paste0("raw_scores_",y1,"_",y2,".txt"))
  return(raw_scores_y1_y2)
}

read_data_vegas<- function(y1,y2) {
  vegas_y1_y2 <- read.csv(paste0("vegas_",y1,"_",y2,".txt"))
  return(vegas_y1_y2)
}

raw_scores <- read_data_raw(12,13)
vegas <- read_data_vegas(12,13)
df <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
raw_scores <- read_data_raw(13,14)
vegas <- read_data_vegas(13,14)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)
raw_scores <- read_data_raw(14,15)
vegas <- read_data_vegas(14,15)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)
raw_scores <- read_data_raw(15,16)
vegas <- read_data_vegas(15,16)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)
raw_scores <- read_data_raw(16,17)
vegas <- read_data_vegas(16,17)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)
raw_scores <- read_data_raw(17,18)
vegas <- read_data_vegas(17,18)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)
raw_scores <- read_data_raw(18,19)
vegas <- read_data_vegas(18,19)
df2 <- inner_join(raw_scores,vegas, by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId" ) )
df <- rbind(df,df2)

Body:
You can try with purrr::map_df to perform inner join and combine all the dataframes into one.

library(dplyr)
library(purrr)

vals <- 12:18
df <- map_df(vals,
             ~inner_join(read_data_raw(.x,.x + 1),
                         read_data_vegas(.x,.x + 1),
                          by = c("TEAM_ID" = "TeamId","GAME_ID"="GameId")))


问:
data querying issue when using subscribe to get real-time updates in my app
I'm coding a react native mobile application with aws amplify as my backend,

To get real-time updates in my app I used subscribe like this inside a useEffect hook,

const[cartProducts, setcartProducts] = useState <CartProduct[]>([]);
const getCartProduct = async () => {
  await DataStore.query(CartProduct, c=>c.userID("eq", currentUserId))
                 .then(setcartProducts)
};

useEffect(() => {
  const subscription = DataStore.observe(CartProduct, d=>d.userID("eq", UserId))
                                .subscribe(msg => getCartProduct(),);
  return subscription.unsubscribe;
}, []);
```

the querying of data happens inside getCartProduct() function,

But the problem is whenever I close my app and reopen this screen the fetching function(getCartProduct) doesn't run
I guess because there is no change in the data (cartProducts) in the backend.

When ever I change the cartProducts data in backend then the fetching function (getCartProduct) run again

what is the solution to this?

答:
Call getCartProduct in the useEffect block before subscribing

Wrap the getCartProduct() callback in curly brackets

Wrap subscription.unsubscribe in curly brackets and call it with ()

Body:
I'm coding a react native mobile application with aws amplify as my backend,

To get real-time updates in my app I used subscribe like this inside a useEffect hook,

const[cartProducts, setcartProducts] = useState <CartProduct[]>([]);
const getCartProduct = async () => {
  await DataStore.query(CartProduct, c=>c.userID("eq", currentUserId))
                 .then(setcartProducts)
};

useEffect(() => {
  const subscription = DataStore.observe(CartProduct, d=>d.userID("eq", UserId))
                                .subscribe(msg => getCartProduct(),);
  return subscription.unsubscribe;
}, []);

the querying of data happens inside getCartProduct() function,

But the problem is whenever I close my app and reopen this screen the fetching function(getCartProduct) doesn't run
I guess because there is no change in the data (cartProducts) in the backend.

When ever I change the cartProducts data in backend then the fetching function (getCartProduct) run again

what is the solution to this?


问:
SearchView AutoComplete in Android Studio
I need my SearchView to have an AutoComplete dropdown List

Ive found this solution but it doesn't work. I marked error causing lines

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_menu, menu);

    MenuItem item = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) item.getActionView();
    searchView.setBackgroundColor(Color.YELLOW); //It works
    androidx.appcompat.widget.SearchView.SearchAutoComplete searchAutoComplete = searchView.findViewById(R.id.search_src_text);
    searchAutoComplete.setBackgroundColor(Color.YELLOW); //ERROR! null object reference

    String dataArr[] = {"Apple" , "Amazon" , "Amd", "Microsoft", "Microwave", "MicroNews", "Intel", "Intelligence"};
    ArrayAdapter<String> newsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, dataArr);
    searchAutoComplete.setAdapter(newsAdapter); //ERROR! null object reference
    //...
}
</code>```

答:
You don't use SearchAutoComplete with androidx SearchView.

That's for support v7.

Here's the answer to this in another question

You use searchView.setSuggestionsAdapter(adapter)

This has a more complicated set up than the autocomplete, it's already explained in the link with code examples.

Briefly described:

Set up from column names and to view ids to display the data (I think you can include more columns without having to display them, but didn't test it).

Create SimpleCursorAdapter with cursor null.

In SearchView.OnQueryTextListener fetch your data (You could also do this outside, but that'll make your suggestions static)

Create a MatrixCursor with rows of your suggestions, each row with an ID and the columns the adapter needs.

Call searchView.getSuggestionsAdapter().changeCursor(matrixCursor)

Use searchView.setOnSuggestionListener(new OnSuggestionListener()) to react to the user interactions.

Body:
I need my SearchView to have an AutoComplete dropdown List

Ive found this solution but it doesn't work. I marked error causing lines

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_menu, menu);

    MenuItem item = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) item.getActionView();
    searchView.setBackgroundColor(Color.YELLOW); //It works
    androidx.appcompat.widget.SearchView.SearchAutoComplete searchAutoComplete = searchView.findViewById(R.id.search_src_text);
    searchAutoComplete.setBackgroundColor(Color.YELLOW); //ERROR! null object reference

    String dataArr[] = {"Apple" , "Amazon" , "Amd", "Microsoft", "Microwave", "MicroNews", "Intel", "Intelligence"};
    ArrayAdapter<String> newsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, dataArr);
    searchAutoComplete.setAdapter(newsAdapter); //ERROR! null object reference
    //...
}


问:
Can't create a relocatable pe file with cl that generates a ".reloc" section
that's my first question on stack overflow. I'm writing a kernel, and I'm looking for running drivers. The kernel can run some simple user applications in pe32+ format that loads on a fixed virtual address, however i need to load drivers in kernel space and that needs a compatible relocatable image.

I can read the dll import table, the subsystem and section headers of the driver image i created using msvc cl. But it seems to not have a ".reloc" section even though i specified in linker options /DYNAMICBASE and /FIXED:NO. The dll i created for the driver api seems to have the same problem and when i read hexadecimal output in HexDecoder. there is no reloc section. I've also seen the data directories and the relocation base entry is clear.

Here is the compiling options for the driver:

```<code>cl /I inc /I ../../libc/inc /I ../../libc/drv/inc /Fo:obj/x86_64/ /Fe:osdwm.sys src/*.c "../gdk.lib" /link /machine:x64 /subsystem:native /fixed:no /dynamicbase
copy /b osdwm.sys "../../kernel/iso/os/system"
</code>```

Here is for the dll driver kit

```<code> cl src/*.c /dll /dynamicbase  /I ../inc /I ../drv/inc /Fe:gdk.dll /link /dll /fixed:no /dynamicbase /subsystem:native /machine:x64

 copy /b gdk.dll "../../kernel/iso/os/system"
 copy /b gdk.lib "../../drivers/gdk.lib"
</code>```

So i created some symbols like this. the loader relocated them and it worked. But how can i make every function like a symbol because this is a driver and its painful to make that declaration for every symbol.

```<code>extern void _cli();
extern void _hlt();
extern void __stdcall movrbx(UINT64 value);

void (*foofi)() = _hlt;
void (*foo)() = _cli;
GDKSTATUS GDKENTRY DriverEntry(DRIVER_HEADER* DriverHeader, LPCWSTR SystemPath)
{
    foo();
    foofi();
    // ...
}
</code>```

答:
After hard searching and reading the PE specification in these 2 days, I was able to load the driver and link it to the DLL (this operation is called "delay-loading"). And I want to share with you some of what I've found.

First, the driver and any application compiled with MSVC has "dynamic base" enabled by default, which enables ASLR (Address Space Layout Randomization).

Let's take function A, function B (Both in ".text" section) and int C in ".data" section, when linking the linker calculates the difference in virtual address between these symbols. Which makes the executable being able to load at any address in memory without restricting a fixed base address or relocating every function which can take alot of space in the executable image.

Take this example:

```<code> 0x1000 - Function A

 0x1100 - Function B
          callq $ - 0x100 # Current Address - 0x100 which is address of Function A

 mov eax, $ + 0x1F00 # int C

 0x3000 - int C = 123
</code>```

But when declaring a symbol reference like :

```<code>int (*AddressOfA)() = A;
</code>```

If /FIXED is enabled then the result will be a fixed virtual address from the Image Base. But if /FIXED:NO is specified. The linker can't know the address where the image will be loaded since it is a dynamic based image, the linker will create a symbol reference in the ".reloc" section which will be processed by OS at load time and will change its value to be relative to the address where the image has been loaded.

Body:
that's my first question on stack overflow. I'm writing a kernel, and I'm looking for running drivers. The kernel can run some simple user applications in pe32+ format that loads on a fixed virtual address, however i need to load drivers in kernel space and that needs a compatible relocatable image.

I can read the dll import table, the subsystem and section headers of the driver image i created using msvc cl. But it seems to not have a ".reloc" section even though i specified in linker options /DYNAMICBASE and /FIXED:NO. The dll i created for the driver api seems to have the same problem and when i read hexadecimal output in HexDecoder. there is no reloc section. I've also seen the data directories and the relocation base entry is clear.

Here is the compiling options for the driver:

cl /I inc /I ../../libc/inc /I ../../libc/drv/inc /Fo:obj/x86_64/ /Fe:osdwm.sys src/*.c "../gdk.lib" /link /machine:x64 /subsystem:native /fixed:no /dynamicbase
copy /b osdwm.sys "../../kernel/iso/os/system"

Here is for the dll driver kit

 cl src/*.c /dll /dynamicbase  /I ../inc /I ../drv/inc /Fe:gdk.dll /link /dll /fixed:no /dynamicbase /subsystem:native /machine:x64

 copy /b gdk.dll "../../kernel/iso/os/system"
 copy /b gdk.lib "../../drivers/gdk.lib"

So i created some symbols like this. the loader relocated them and it worked. But how can i make every function like a symbol because this is a driver and its painful to make that declaration for every symbol.

extern void _cli();
extern void _hlt();
extern void __stdcall movrbx(UINT64 value);

void (*foofi)() = _hlt;
void (*foo)() = _cli;
GDKSTATUS GDKENTRY DriverEntry(DRIVER_HEADER* DriverHeader, LPCWSTR SystemPath)
{
    foo();
    foofi();
    // ...
}

Body:
After hard searching and reading the PE specification in these 2 days, I was able to load the driver and link it to the DLL (this operation is called "delay-loading"). And I want to share with you some of what I've found.

First, the driver and any application compiled with MSVC has "dynamic base" enabled by default, which enables ASLR (Address Space Layout Randomization).

Let's take function A, function B (Both in ".text" section) and int C in ".data" section, when linking the linker calculates the difference in virtual address between these symbols. Which makes the executable being able to load at any address in memory without restricting a fixed base address or relocating every function which can take alot of space in the executable image.

Take this example:

 0x1000 - Function A

 0x1100 - Function B
          callq $ - 0x100 # Current Address - 0x100 which is address of Function A

 mov eax, $ + 0x1F00 # int C

 0x3000 - int C = 123

But when declaring a symbol reference like :

int (*AddressOfA)() = A;

If /FIXED is enabled then the result will be a fixed virtual address from the Image Base. But if /FIXED:NO is specified. The linker can't know the address where the image will be loaded since it is a dynamic based image, the linker will create a symbol reference in the ".reloc" section which will be processed by OS at load time and will change its value to be relative to the address where the image has been loaded.


问:
How to Create New User under NT Authority\System the System in Window OS using C#
Right now my service is running under the NT Local system. I want to create the NTUser type to run the Service. I don't want to create Local system account.
In the Service when u look some account running under NT Service__ . i also looking to create custom NT Service\CustomName user to run the Service.

答:
I am confused by your question, let me take a guess at what you might be trying to do: You are trying to use the built in [NT AUTHORITY\SYSTEM] account to authorize your application to other services.

Here's how I have used [NT AUTHORITY\SYSTEM] account with my C# MVC web applications to authorize access to a local sql server database.

.NET FRAMEWORK

```<code>// Views/Home/Index.cshtml
@ViewBag.Title="Home Page";

<div class="jumbotron">
    <h1>Hello @Model</h1>
    .....
</code>```

// Controllers/HomeController.cs
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;

public class HomeController : Controller
{
  private string _connStr = @"
    Database=MyDB;Integrated Security=true;";

  public ActionResult Index()
  {
    using var conn = new SqlConnection(_connStr);
    conn.Open();
    var cmd = new SqlCommand(@"
      SELECT TOP 1 [name] FROM [dbo].[person];", conn);
    var reader = cmd.ExecuteReader();
    if (reader.Read())
      return View("index", reader["name"]);
    else
      throw new DataException("Nobody is in Person table!");
  }
}
```
<h2>SQL</h2>
<pre class="lang-sql prettyprint-override"><code>IF NOT EXISTS(SELECT 1 FROM sys.syslogins WHERE name = 'NT AUTHORITY\SYSTEM')
BEGIN
    CREATE LOGIN [NT AUTHORITY\SYSTEM]
        FROM WINDOWS WITH DEFAULT_LANGUAGE = [us_english];

    GRANT CONNECT TO [NT AUTHORITY\SYSTEM];
END

IF NOT EXISTS(SELECT 1 FROM sys.sysusers WHERE name = 'NT AUTHORITY\SYSTEM')
BEGIN
    CREATE USER [NT AUTHORITY\SYSTEM] FOR LOGIN [NT AUTHORITY\SYSTEM];

    ALTER ROLE [db_reader] ADD MEMBER [NT AUTHORITY\SYSTEM];
END

IF NOT EXISTS(SELECT 1 FROM sys.tables WHERE name = 'person')
BEGIN
    CREATE TABLE [dbo].[person] (
        [id]   UNIQUEIDENTIFIER CONSTRAINT [DF_dbo.person_id] DEFAULT (NEWID()) ROWGUIDCOL NOT NULL,
        [name] NVARCHAR (50)    NULL,
        CONSTRAINT [PK_dbo.person] PRIMARY KEY CLUSTERED ([id] ASC)
    );

    INSERT INTO dbo.person
    SELECT NEWID(), 'BILLY'
END
</code>```

IIS

Change the Default App Pool Application Pool to the LocalSystem identity, and Publish your .Net Framework MVC application to your C:\inetpub\wwwroot.

INTEGRATED SECURITY

You now have a web application running under the LocalSystem identity (NT AUTHORITY\SYSTEM), and have granted the built-in NT AUTHORITY\SYSTEM user access to connect to your database server. In SQL Server, you've created an NT AUTHORITY\SYSTEM user for your NT AUTHORITY\SYSTEM login. You've also granted that SQL user [db_reader] over your dbo schema.

WHY IS THIS IMPORTANT?

Integrated Security utilizes Kerberos Authentication to authenticate from Windows server to Windows server. In many organizations, Active Directory users are created to provide Identities for IIS Application Pools to access databases using Integrated Security.

Running an Application Pool under these AD accounts allows fine-grained control over what each application pool has access to. Additionally it prevents passwords from having to be incorporated into application configuration.

PROBLEMS WITH ACTIVE DIRECTORY IDENTITY USER APPROACH WHEN DEVELOPING LOCALLY

The problem with the AD Users being used for Identities is that you require access to Active Directory to mimic a production setup locally. You shouldn't have access to the passwords necessary to mimic the exact AD user based authentication, and you wouldn't want to use it anyways just in case you were accidentally targeting a production database. Worse, you may need to keep an entire development Domain in parity with a production domain to ensure you have access to all necessary AD Accounts.

Built-in auth is our "test double" for Active Directory. Utilizing the NT AUTHORITY\SYSTEM account, you shortcut Using Active Directory altogether, and keep all authentication local. Which is where development work should be done in the first place..

I like to treat integration testing more narrowly and test one integration point at a time by replacing separate services and databases with test doubles. Together with contract testing and running contract tests against test doubles as well as the real implementations you can come up with integration tests that are faster, more independent and usually easier to reason about.

- Martin Fowler: The Practical Test Pyramid

Now we can Debug (running Visual Studio as administrator), directly against IIS, with a "test double" for Active Directory authentication.

Body:
I am confused by your question, let me take a guess at what you might be trying to do: You are trying to use the built in [NT AUTHORITY\SYSTEM] account to authorize your application to other services.

Here's how I have used [NT AUTHORITY\SYSTEM] account with my C# MVC web applications to authorize access to a local sql server database.

.NET FRAMEWORK

// Views/Home/Index.cshtml
@ViewBag.Title="Home Page";

<div class="jumbotron">
    <h1>Hello @Model</h1>
    .....

// Controllers/HomeController.cs
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;

public class HomeController : Controller
{
  private string _connStr = @"
    Database=MyDB;Integrated Security=true;";

  public ActionResult Index()
  {
    using var conn = new SqlConnection(_connStr);
    conn.Open();
    var cmd = new SqlCommand(@"
      SELECT TOP 1 [name] FROM [dbo].[person];", conn);
    var reader = cmd.ExecuteReader();
    if (reader.Read())
      return View("index", reader["name"]);
    else
      throw new DataException("Nobody is in Person table!");
  }
}

SQL

IF NOT EXISTS(SELECT 1 FROM sys.syslogins WHERE name = 'NT AUTHORITY\SYSTEM')
BEGIN
    CREATE LOGIN [NT AUTHORITY\SYSTEM]
        FROM WINDOWS WITH DEFAULT_LANGUAGE = [us_english];

    GRANT CONNECT TO [NT AUTHORITY\SYSTEM];
END

IF NOT EXISTS(SELECT 1 FROM sys.sysusers WHERE name = 'NT AUTHORITY\SYSTEM')
BEGIN
    CREATE USER [NT AUTHORITY\SYSTEM] FOR LOGIN [NT AUTHORITY\SYSTEM];

    ALTER ROLE [db_reader] ADD MEMBER [NT AUTHORITY\SYSTEM];
END

IF NOT EXISTS(SELECT 1 FROM sys.tables WHERE name = 'person')
BEGIN
    CREATE TABLE [dbo].[person] (
        [id]   UNIQUEIDENTIFIER CONSTRAINT [DF_dbo.person_id] DEFAULT (NEWID()) ROWGUIDCOL NOT NULL,
        [name] NVARCHAR (50)    NULL,
        CONSTRAINT [PK_dbo.person] PRIMARY KEY CLUSTERED ([id] ASC)
    );

    INSERT INTO dbo.person
    SELECT NEWID(), 'BILLY'
END

IIS

Change the Default App Pool Application Pool to the LocalSystem identity, and Publish your .Net Framework MVC application to your C:\inetpub\wwwroot.

INTEGRATED SECURITY

You now have a web application running under the LocalSystem identity (NT AUTHORITY\SYSTEM), and have granted the built-in NT AUTHORITY\SYSTEM user access to connect to your database server. In SQL Server, you've created an NT AUTHORITY\SYSTEM user for your NT AUTHORITY\SYSTEM login. You've also granted that SQL user [db_reader] over your dbo schema.

WHY IS THIS IMPORTANT?

Integrated Security utilizes Kerberos Authentication to authenticate from Windows server to Windows server. In many organizations, Active Directory users are created to provide Identities for IIS Application Pools to access databases using Integrated Security.

Running an Application Pool under these AD accounts allows fine-grained control over what each application pool has access to. Additionally it prevents passwords from having to be incorporated into application configuration.

PROBLEMS WITH ACTIVE DIRECTORY IDENTITY USER APPROACH WHEN DEVELOPING LOCALLY

The problem with the AD Users being used for Identities is that you require access to Active Directory to mimic a production setup locally. You shouldn't have access to the passwords necessary to mimic the exact AD user based authentication, and you wouldn't want to use it anyways just in case you were accidentally targeting a production database. Worse, you may need to keep an entire development Domain in parity with a production domain to ensure you have access to all necessary AD Accounts.

Built-in auth is our "test double" for Active Directory. Utilizing the NT AUTHORITY\SYSTEM account, you shortcut Using Active Directory altogether, and keep all authentication local. Which is where development work should be done in the first place..

I like to treat integration testing more narrowly and test one integration point at a time by replacing separate services and databases with test doubles. Together with contract testing and running contract tests against test doubles as well as the real implementations you can come up with integration tests that are faster, more independent and usually easier to reason about.

- Martin Fowler: The Practical Test Pyramid

Now we can Debug (running Visual Studio as administrator), directly against IIS, with a "test double" for Active Directory authentication.


问:
log4net vs. Nlog
Anyone have experience for both?  How do they stack up against each other?

We are planning on using one of them for logging in an enterprise application.

References:

log4net

nlog

EDIT: We have no existing dependencies to either nlog or log4net.

答: You might also consider Microsoft Enterprise Library Logging Block. It comes with nice designer.</p>

OwnerDisplayName: Greg Dean

ContentLicense: CC BY-SA 2.5

Title: log4net vs. Nlog

LastEditorDisplayName: Greg Dean

OwnerDisplayName: Rashack


问:
is there any other Base64 type encryption and decryption in php?
is there any other Base64 type encryption and decryption in php ?

The problem is that base 64 give a longer value and increases the size of the data whereas i'm looking for something to reduce the size of the data.

is there any ?

答:
base64 is not an encryption but an encoding

pick an encryption algorithm from http://docs.php.net/mcrypt, see also http://docs.php.net/refs.crypto

to (possibly) reduce the size use a data compression algorithm, see also http://docs.php.net/refs.compression


问:
How do I force intercept on a python linear regression plot?
How do I force the line and equation through 0 on this dataframe? I only know how to make a line that is the best fit and equation to match.Below is the code of the best fit line without force intercept through 0. Any help getting forced intercept is appreciated!

```<code>import seaborn as sns
import scipy as sp
r, p = sp.stats.pearsonr(x=df['mass(mg)'], y=df['Abs'])
sns.regplot(x=df['mass(mg)'],y=df['Abs']).set(Title='biuret standard plot')

def equation(x,y):
    x_mean = x.mean()
    y_mean = y.mean()

    B1_num = ((x - x_mean) * (y - y_mean)).sum()
    B1_den = ((x - x_mean)**2).sum()
    B1 = B1_num / B1_den
    B0 = y_mean - (B1*x_mean)

    reg_line = 'y = {} + {}β'.format(B0, round(B1, 3))

    return (B0, B1, reg_line)
equation(df['mass(mg)'],df['Abs'])
</code>```

答:
Seaborn's linear regression won't let you do that.

So if you are trying to get the line to go through the origin i.e. (0,0) then your equation is y=mx. There is no B0 if you're doing this. So we use numpy.linalf.lstq to do least squares and force it through origin. And we also add 0 coordinates so it draws on. Taking in your values for mass and Abs, see below:

```<code>import numpy as np
import matplotlib.pyplot as plt

# I'm adding a 0 in both x and y axis to force a line drawn.
x = np.array([0, 5, 4, 3, 2, 1, 0.5])
y = np.array([0, 0.596, 0.464, 0.333, 0.201, 0.121, 0.062])

# We only need a*x. so to figure out a we use lstsq from numpy
# Our x matrix is one dimensional, it needs to be two dimensional to use lstsq so:
x = x[:,np.newaxis]
a, _, _, _ = np.linalg.lstsq(x, y)

plt.plot(x, y, 'bo')
plt.plot(x, a*x, 'r-')
plt.xlim([0, 6])
plt.ylim([0, 0.7])
plt.show()
print(f"y = {a} x + 0")
</code>```

Which outputs:

Feel free to add labelling etc.

Hope this helps, please mark this as the answer if it does!

Body:
How do I force the line and equation through 0 on this dataframe? I only know how to make a line that is the best fit and equation to match.Below is the code of the best fit line without force intercept through 0. Any help getting forced intercept is appreciated!

import seaborn as sns
import scipy as sp
r, p = sp.stats.pearsonr(x=df['mass(mg)'], y=df['Abs'])
sns.regplot(x=df['mass(mg)'],y=df['Abs']).set(Title='biuret standard plot')

def equation(x,y):
    x_mean = x.mean()
    y_mean = y.mean()

    B1_num = ((x - x_mean) * (y - y_mean)).sum()
    B1_den = ((x - x_mean)**2).sum()
    B1 = B1_num / B1_den
    B0 = y_mean - (B1*x_mean)

    reg_line = 'y = {} + {}β'.format(B0, round(B1, 3))

    return (B0, B1, reg_line)
equation(df['mass(mg)'],df['Abs'])

Body:
Seaborn's linear regression won't let you do that.

So if you are trying to get the line to go through the origin i.e. (0,0) then your equation is y=mx. There is no B0 if you're doing this. So we use numpy.linalf.lstq to do least squares and force it through origin. And we also add 0 coordinates so it draws on. Taking in your values for mass and Abs, see below:

import numpy as np
import matplotlib.pyplot as plt

# I'm adding a 0 in both x and y axis to force a line drawn.
x = np.array([0, 5, 4, 3, 2, 1, 0.5])
y = np.array([0, 0.596, 0.464, 0.333, 0.201, 0.121, 0.062])

# We only need a*x. so to figure out a we use lstsq from numpy
# Our x matrix is one dimensional, it needs to be two dimensional to use lstsq so:
x = x[:,np.newaxis]
a, _, _, _ = np.linalg.lstsq(x, y)

plt.plot(x, y, 'bo')
plt.plot(x, a*x, 'r-')
plt.xlim([0, 6])
plt.ylim([0, 0.7])
plt.show()
print(f"y = {a} x + 0")

Which outputs:

Feel free to add labelling etc.

Hope this helps, please mark this as the answer if it does!


问:
How to assign values to dynamic const variable in C?
I got curious about dynamic const variable in C.

So, when I was testing there is a problem with assigning a value to it, while there is no problem with allocating const variable dynamically.

Yeah I am aware that we can use static const variables but it will be more memory efficient if we want to work with big const struct.

so here is a program that I had tested..

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    const int *a = (int*) malloc(sizeof(int));
    *a = 77;
    printf("value of a %d", a);
    return 0;
}
</code>```

The error I am getting..

```<code>main.c:15:8: error: assignment of read-only location ‘*a’
   15 |     *a = 15;
      |        ^
</code>```

So is there any way to do it?

答:
You can initialise the const object when you allocate it. Example:</p>
```<code>auto ptr = std::make_unique<const int>(77);
</code>```

Body:
I got curious about dynamic const variable in C.

So, when I was testing there is a problem with assigning a value to it, while there is no problem with allocating const variable dynamically.

Yeah I am aware that we can use static const variables but it will be more memory efficient if we want to work with big const struct.

so here is a program that I had tested..

#include <stdio.h>
#include <stdlib.h>

int main()
{
    const int *a = (int*) malloc(sizeof(int));
    *a = 77;
    printf("value of a %d", a);
    return 0;
}

The error I am getting..

main.c:15:8: error: assignment of read-only location ‘*a’
   15 |     *a = 15;
      |        ^

So is there any way to do it?

Body:
You can initialise the const object when you allocate it. Example:

auto ptr = std::make_unique<const int>(77);


问:
JDK directory is not set or invalid (unity)?
I am now creating a keystore for my game (in unity) but when I press the add key button, an error pops up

Java Development Kit (JDK) directory is not set or invalid. Please, fix it in Preferences -> External Tools
  UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr) (at /Users/builduser/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:187)

I installed the JDK and checked the path of it in the terminal using the command /usr/libexec/java_home, then it shows me that the path of the JDK is /Library/Java/JavaVirtualMachines/jdk-14.0.1.jdk/Contents/Home.

I copy and paste it in the JDK path in unity but the error still pops up.
I actually checked the JavaVirtualMachines in my computer's library but there's nothing in it.

How can I solve this problem? Any help is greatly appreciated.

答:
There is no 3 dots and there is no installing JDK, Gradle, SDK, or NDK.
I always get Gradle building errors when I install these components manually, although they are the compatible ones of my version.
I want to download them automatically by unity, but the options you are talking about don't exist.

enter image description here


问:
Checking a parent container for children javascript
Just wondering how you can check an element (i.e. a div container) for elements (i.e. buttons) and if they exist, remove them?

If I append a child to a div, how can I on the next look check for that child or those type of children? i.e. adding;

example = document.getElementById('div');
example.appendChild(aButton);

//loop to look for aButton / button type in example div
```

Cheers

答:
To get elements that are of a node type from a subset of the document you can simply do

```<code>document.getElementById('div').getElementsByTagName("button")
</code>```

This will return any buttons under an element with the id of "div" (not a good name for an id btw)

Body:
Just wondering how you can check an element (i.e. a div container) for elements (i.e. buttons) and if they exist, remove them?

If I append a child to a div, how can I on the next look check for that child or those type of children? i.e. adding;

example = document.getElementById('div');
example.appendChild(aButton);

//loop to look for aButton / button type in example div

Cheers

Body:
To get elements that are of a node type from a subset of the document you can simply do

document.getElementById('div').getElementsByTagName("button")

This will return any buttons under an element with the id of "div" (not a good name for an id btw)


问:
edit a string by removing characters without creating a new string, is it legit or not?
EDIT: I think I've understood how this concept works, this is my code

```<code>void delete_duplicate(char* str) {
    if (str == NULL) {
        exit(1);
    }
    for (size_t i = 0; str[i] != 0; i++) {
        if (str[i] == str[i + 1]) {
            str[i] = '\0';
        }
    }
}

    int main(void) {
    char str[] = "hhhhhhhheeeeeeeeyyyyyyyyyyy";
    delete_duplicate(str);
    return 0;
}
</code>```

the output string is "00...0h0...000e0...000y" (with lots of zeros). if the string is "abbbb", the string becomes "a" and not "ab".

I was thinking about an algorithm for this exercise:

given a string, for example "ssttringg" the output must be "string". the function has to remove one character if and only if the current character and the next character are the same.

the exercise expects a function declared like this:

```<code>extern void delete_consecutive(char* str);
</code>```

this is my algorithm:

loop: if the current character is equal to the next character, increment length by 1, and repeat until zero terminator is reached.

critical part: dynamic memory allocation.

allocate enough memory to store the output. Why did I say this is the critical part? because I have to do it in a void function, therefore I can't create a second string, allocate enough memory with malloc, and then return it at the end. I need to edit the original string instead. I think I can do it by means of a realloc, and by decrementing the size of the string. But I don't know how to do it, and more important: I don't know if it's legit to do it, without losing data. I think I'm overcomplicating the homework, but it's a void function, therefore I can't simply create a new string and copying characters in it, because I can't return it.

if it's not clear, I'll edit the question.

答:
```<code>void delete_duplicate(char* str)
{
    if(str && *str)
    {
        char *writeTo = str, *readFrom = str;
        char prev = 0;
        while(*readFrom)
        {
            if(prev != *readFrom)
            {
                prev = *readFrom++;
                *writeTo++ = prev;
            }
            else
            {
                readFrom++;
            }
        }
        *writeTo = 0;
    }
}

int main(void)
{
    char str[] = "hhhhhhhheeeeeeeeyyyyyyyyyyy";
    delete_duplicate(str);
    printf("`%s`\n", str);
    return 0;
}
</code>```

Body:
EDIT: I think I've understood how this concept works, this is my code

void delete_duplicate(char* str) {
    if (str == NULL) {
        exit(1);
    }
    for (size_t i = 0; str[i] != 0; i++) {
        if (str[i] == str[i + 1]) {
            str[i] = '\0';
        }
    }
}

    int main(void) {
    char str[] = "hhhhhhhheeeeeeeeyyyyyyyyyyy";
    delete_duplicate(str);
    return 0;
}

the output string is "00...0h0...000e0...000y" (with lots of zeros). if the string is "abbbb", the string becomes "a" and not "ab".

I was thinking about an algorithm for this exercise:

given a string, for example "ssttringg" the output must be "string". the function has to remove one character if and only if the current character and the next character are the same.

the exercise expects a function declared like this:

extern void delete_consecutive(char* str);

this is my algorithm:

loop: if the current character is equal to the next character, increment length by 1, and repeat until zero terminator is reached.

critical part: dynamic memory allocation.

allocate enough memory to store the output. Why did I say this is the critical part? because I have to do it in a void function, therefore I can't create a second string, allocate enough memory with malloc, and then return it at the end. I need to edit the original string instead. I think I can do it by means of a realloc, and by decrementing the size of the string. But I don't know how to do it, and more important: I don't know if it's legit to do it, without losing data. I think I'm overcomplicating the homework, but it's a void function, therefore I can't simply create a new string and copying characters in it, because I can't return it.

if it's not clear, I'll edit the question.


答:
This pattern is called a retention scan (also a reduction scan, depending on your perspective), and is very common in algorithms that dictate discarding characters whilst keeping others, based on some condition. Often, the condition can change, and sometimes even the methods for starting the scan are somewhat altered

In it's simplest form, it looks something like this, as an example: An algorithm used to discard all but numeric (digit) characters:

Start with reader r and writer w pointers at the head of the string.

Iterate over the string from beginning to terminator using r. The r pointer will always be incremented exactly once per iteration.

For each iteration, check to see if the current character at r satisfies the condition for retention (in this case, is the character a digit char?). If it does, write it at w and advance w one slot.

When finished. w will point to the location where your terminator should reside.

```<code>#include <ctype.h>

void delete_nondigits(char *s)
{
    if (s && *s)
    {
        char *w = s;
        for (char *r = s; *r; ++r)
        {
            if (isdigit((unsigned char)*r))
                *w++ = *r;
        }
        *w = 0;
    }
}
</code>```

Pretty simple.

Now, the algorithm for in-place consecutive-run compaction is more complicated, but has a highly similar model. Because retention is based on a prior-value already-retained you need to remember that last-kept value. You could just use *w, but the algorithm is actually easier to understand (and advance w) if you keep it in a separate memo char as you're about to see:

Start with reader r and writer w pointers as we had before, but starting at second slot of the string, and a single memo char variable c initialized to the first character of the string.

Iterate over the string using r until termination encounter. The r pointer will always be incremented exactly once per iteration.

For each iteration, check to see if the current character at *r is the same as the memo character c If it is, do nothing and continue to the next iteration.

Otherwise, if the character at *r is different than the memo character c, save it as the new value for c, write it to *w, and advance w one slot.

When finished, terminate the string by setting a terminator at *w.

The only hitch to this algorithm is supporting a zero-length string on inception, which is easily circumvented by checking that single condition first. I leave actually implementing it as an exercise for you. (hint: only do the above if (s && *s) is true).

Title: edit a string by removing characters without creating a new string, is it legit or not?

Body:
This pattern is called a retention scan (also a reduction scan, depending on your perspective), and is very common in algorithms that dictate discarding characters whilst keeping others, based on some condition. Often, the condition can change, and sometimes even the methods for starting the scan are somewhat altered

In it's simplest form, it looks something like this, as an example: An algorithm used to discard all but numeric (digit) characters:

Start with reader r and writer w pointers at the head of the string.

Iterate over the string from beginning to terminator using r. The r pointer will always be incremented exactly once per iteration.

For each iteration, check to see if the current character at r satisfies the condition for retention (in this case, is the character a digit char?). If it does, write it at w and advance w one slot.

When finished. w will point to the location where your terminator should reside.

#include <ctype.h>

void delete_nondigits(char *s)
{
    if (s && *s)
    {
        char *w = s;
        for (char *r = s; *r; ++r)
        {
            if (isdigit((unsigned char)*r))
                *w++ = *r;
        }
        *w = 0;
    }
}

Pretty simple.

Now, the algorithm for in-place consecutive-run compaction is more complicated, but has a highly similar model. Because retention is based on a prior-value already-retained you need to remember that last-kept value. You could just use *w, but the algorithm is actually easier to understand (and advance w) if you keep it in a separate memo char as you're about to see:

Start with reader r and writer w pointers as we had before, but starting at second slot of the string, and a single memo char variable c initialized to the first character of the string.

Iterate over the string using r until termination encounter. The r pointer will always be incremented exactly once per iteration.

For each iteration, check to see if the current character at *r is the same as the memo character c If it is, do nothing and continue to the next iteration.

Otherwise, if the character at *r is different than the memo character c, save it as the new value for c, write it to *w, and advance w one slot.

When finished, terminate the string by setting a terminator at *w.

The only hitch to this algorithm is supporting a zero-length string on inception, which is easily circumvented by checking that single condition first. I leave actually implementing it as an exercise for you. (hint: only do the above if (s && *s) is true).