问:
Button click wont trigger function
I'm having trouble triggering a function. I have the following code:</p>

```<code>var dnfmomd;

dnfmomd = new function () {
//function content
}

$("#launch_button").on("click", dnfmomd.init);
</code>```

答:
I would recommend doing it this way</p>

```<code> var dnfmomd = function() {
 //function content
}

$("#launch_button").on("click", function() {
  dnfmomd();
});
</code>```

Title: Button click wont trigger function

Body:
I'm having trouble triggering a function. I have the following code:

var dnfmomd;

dnfmomd = new function () {
//function content
}

$("#launch_button").on("click", dnfmomd.init);

Body:
I would recommend doing it this way

 var dnfmomd = function() {
 //function content
}

$("#launch_button").on("click", function() {
  dnfmomd();
});


来源: stackexchange

问:
MaterializeCSS - Select native for IOS & Android
Is it possible to make all select dropdowns native for IOS and Android ?

because currently the selection under IOS 13 with materializecss does not work properly.

Cordially

答:
1. Use .browser-default

You can add the class browser-default to get the browser default.

https://materializecss.com/select.html

```<code><select class="browser-default">
     <option value="" disabled="" selected="">Choose your option</option>
     <option value="1">Option 1</option>
     <option value="2">Option 2</option>
     <option value="3">Option 3</option>
</select>
</code>```

2. There is a temporary workaround

Serving the below patched select.js file after materialize.js is working for most users.

https://github.com/Dogfalo/materialize/blob/v1-dev/js/select.js

ContentLicense: CC BY-SA 4.0

Body:
1. Use .browser-default

You can add the class browser-default to get the browser default.

https://materializecss.com/select.html

<select class="browser-default">
     <option value="" disabled="" selected="">Choose your option</option>
     <option value="1">Option 1</option>
     <option value="2">Option 2</option>
     <option value="3">Option 3</option>
</select>

2. There is a temporary workaround

Serving the below patched select.js file after materialize.js is working for most users.

https://github.com/Dogfalo/materialize/blob/v1-dev/js/select.js


问:
Refresh required to detect authentication state using nuxt auth module
My app is unable to detect the state change that occurs when a user logs in without completely refreshing the page. Upon refreshing everything displays correctly. I am using Nuxt and its included auth module documented here - https://auth.nuxtjs.org/.

Here is the v-if statement that is unable to detect the state change:

```<code>  <template v-if="$auth.$state.loggedIn">
    <nuxt-link
      to="/profile"
    >
      Hello, {{ $auth.$state.user.name }}
    </nuxt-link>
  </template>
  <template v-else>
    <nuxt-link
      to="/logIn"
    >
      Sign In
    </nuxt-link>
  </template>
</code>```

Here is the login method in my login page.

```<code>  methods: {
    async onLogin() {
      try{

        this.$auth.loginWith("local", {
          data: {
            email: this.email,
            password: this.password
          }
        });

        this.$router.push("/");

      }catch(err){
        console.log(err);
      }

    }
  }
</code>```

I tried fetching the state via a computed property but got the same result. I can see the vuex store data change to indicate I am correctly logged in/out in the 'Application' tab in Chrome Dev Tools but the Vue Dev seems to constantly indicate I'm logged in.. Not sure if its just buggy though..

I also encounter the same problem in reverse when logging out. Here's the method:

```<code>async onLogout() {
  try{
    await this.$auth.logout();
  }catch(err){
    console.log(err);
  }
}
</code>```

I am happy to provide further details.

答:
Sometimes Vue's reactivity system falls short and you just need to manually trigger a re-render and the simplest way to do so is by wrapping your function logic in setTimeout()

setTimeout(async () => {
   await this.$auth.logout();
}, 0);

```

Body:
My app is unable to detect the state change that occurs when a user logs in without completely refreshing the page. Upon refreshing everything displays correctly. I am using Nuxt and its included auth module documented here - https://auth.nuxtjs.org/.

Here is the v-if statement that is unable to detect the state change:

  <template v-if="$auth.$state.loggedIn">
    <nuxt-link
      to="/profile"
    >
      Hello, {{ $auth.$state.user.name }}
    </nuxt-link>
  </template>
  <template v-else>
    <nuxt-link
      to="/logIn"
    >
      Sign In
    </nuxt-link>
  </template>

Here is the login method in my login page.

  methods: {
    async onLogin() {
      try{

        this.$auth.loginWith("local", {
          data: {
            email: this.email,
            password: this.password
          }
        });

        this.$router.push("/");

      }catch(err){
        console.log(err);
      }

    }
  }

I tried fetching the state via a computed property but got the same result. I can see the vuex store data change to indicate I am correctly logged in/out in the 'Application' tab in Chrome Dev Tools but the Vue Dev seems to constantly indicate I'm logged in.. Not sure if its just buggy though..

I also encounter the same problem in reverse when logging out. Here's the method:

async onLogout() {
  try{
    await this.$auth.logout();
  }catch(err){
    console.log(err);
  }
}

I am happy to provide further details.


问:
Filter My Array / JSON Data (including multi values) Based on Multiple Criteria in JavaScript?
The tricky part here is:

Some includes more than 1 value (like active substances: ["Morphine", "Fentanyl"])

Some values are repeating (retrospective: "1" for "true; ward_focused: "1" for true (again))

So the previous solutions here did not work for my project.

jsonData

```<code>[
 {
  "title": "Real-world evidence of high-cost drugs for metastatic melanoma",
  "url": "https://.../Suppl_1/A5.1",
  "filters": {
    "retrospective": "1",
    "ward_focused": "2",
    "indication_focused": "1",
    "active_substance": "2"
  }
 },
 {
  "title": "Real-world safety and tolerability of the recently commercialised palbociclib",
  "url": "https://.../Suppl_1/A223.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "1",
    "indication_focused": "2",
    "active_substance": "Palbociclib"
  }
 },
 {
  "title": "Cost-effectiveness of morphine versus fentanyl in managing ventilated neonates",
  "url": "https://.../Suppl_1/A7.3",
  "filters": {
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": ["Morphine", "Fentanyl"]
  }
 },
 {
  "title": "Chemical risk assessement in a quality control laboratory",
  "url": "https://.../Suppl_1/A9.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "2",
    "indication_focused": "2",
    "active_substance": "2"
  }
 },
 {
  "title": "The economic burden of metastatic breast cancer in Spain",
  "url": "https://.../27/1/19",
  "filters":{
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": "2"
  }
 }
]
</code>```

query

```<code>const selectedFilters = {
      retrospective: ["1"],
      ward_focused: ["2"],
      indication_focused: ["1"],
      active_substance: []
  };
</code>```

The closest solution was when I've converted my data into an array and work on it as:

```<code>  const filterArr = Object.values(selectedFilters).flat();

  const output = myDataArray.filter(({filters}) => {
      const objFilters = Object.values(filters).flat();
      return filterArr.every(val => objFilters.includes(val));
  })
  console.log(output);
</code>```

BUT it failed for the reason that the "1"s "true" and the "2"s for false are repeating many times in every profile.

I'm open to work on both as JSON and array for my data. Also I may modify the "1" -"2" structure for my boolean data types. You may also change the data structure if needed by removing the “filters” detail and working on one-depth.

Any help is appreciable. Best regards

答:
The below snippet should filter your data using the js filter function and checking each possible filter against the filters obj

const json =[
 {
  "title": "Real-world evidence of high-cost drugs for metastatic melanoma",
  "url": "https://.../Suppl_1/A5.1",
  "filters": {
    "retrospective": "1",
    "ward_focused": "2",
    "indication_focused": "1",
    "active_substance": "2"
  }
 },
 {
  "title": "Real-world safety and tolerability of the recently commercialised palbociclib",
  "url": "https://.../Suppl_1/A223.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "1",
    "indication_focused": "2",
    "active_substance": "Palbociclib"
  }
 },
 {
  "title": "Cost-effectiveness of morphine versus fentanyl in managing ventilated neonates",
  "url": "https://.../Suppl_1/A7.3",
  "filters": {
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": ["Morphine", "Fentanyl"]
  }
 },
 {
  "title": "Chemical risk assessement in a quality control laboratory",
  "url": "https://.../Suppl_1/A9.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "2",
    "indication_focused": "2",
    "active_substance": "2"
  }
 },
 {
  "title": "The economic burden of metastatic breast cancer in Spain",
  "url": "https://.../27/1/19",
  "filters":{
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": "2"
  }
 }
];
function filterJson(filterObj) {
  let hasRetrospective = false,
    hasWardFocused = false,
    hasIndicationFocused = false,
    hasActiveSubstance = false;
  const arr = json.filter(function (j) {
    hasRetrospective = filterObj.retrospective.indexOf(j.filters.retrospective) > -1;
    hasWardFocused = filterObj.ward_focused.indexOf(j.filters.ward_focused) > -1;
    hasIndicationFocused = filterObj.indication_focused.indexOf(j.filters.indication_focused) > -1;
    hasActiveSubstance = Array.isArray(j.filters.active_substance) ?
      j.filters.active_substance.some(function (jf) {
        return filterObj.active_substance.indexOf(jf) > -1;
      }):
      filterObj.active_substance.indexOf(j.filters.active_substance) > -1;
    return hasRetrospective && hasWardFocused && hasIndicationFocused && hasActiveSubstance;
  });
  console.log(arr);
}
filterJson({
    retrospective: ["1"],
    ward_focused: ["1"],
    indication_focused: ["1"],
    active_substance: ["Morphine", "Fentanyl"]
});```

Body:
The tricky part here is:

Some includes more than 1 value (like active substances: ["Morphine", "Fentanyl"])

Some values are repeating (retrospective: "1" for "true; ward_focused: "1" for true (again))

So the previous solutions here did not work for my project.

jsonData

[
 {
  "title": "Real-world evidence of high-cost drugs for metastatic melanoma",
  "url": "https://.../Suppl_1/A5.1",
  "filters": {
    "retrospective": "1",
    "ward_focused": "2",
    "indication_focused": "1",
    "active_substance": "2"
  }
 },
 {
  "title": "Real-world safety and tolerability of the recently commercialised palbociclib",
  "url": "https://.../Suppl_1/A223.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "1",
    "indication_focused": "2",
    "active_substance": "Palbociclib"
  }
 },
 {
  "title": "Cost-effectiveness of morphine versus fentanyl in managing ventilated neonates",
  "url": "https://.../Suppl_1/A7.3",
  "filters": {
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": ["Morphine", "Fentanyl"]
  }
 },
 {
  "title": "Chemical risk assessement in a quality control laboratory",
  "url": "https://.../Suppl_1/A9.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "2",
    "indication_focused": "2",
    "active_substance": "2"
  }
 },
 {
  "title": "The economic burden of metastatic breast cancer in Spain",
  "url": "https://.../27/1/19",
  "filters":{
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": "2"
  }
 }
]

query

const selectedFilters = {
      retrospective: ["1"],
      ward_focused: ["2"],
      indication_focused: ["1"],
      active_substance: []
  };

The closest solution was when I've converted my data into an array and work on it as:

  const filterArr = Object.values(selectedFilters).flat();

  const output = myDataArray.filter(({filters}) => {
      const objFilters = Object.values(filters).flat();
      return filterArr.every(val => objFilters.includes(val));
  })
  console.log(output);

BUT it failed for the reason that the "1"s "true" and the "2"s for false are repeating many times in every profile.

I'm open to work on both as JSON and array for my data. Also I may modify the "1" -"2" structure for my boolean data types. You may also change the data structure if needed by removing the “filters” detail and working on one-depth.

Any help is appreciable. Best regards


问:
Can I write my simple Python code in a better way?
I should rewrite my own function in a better way. The function takes an iterator and a sequence of boolean functions and returns an iterator of the elements in the input iterator which returns a truthy value.

```<code>def allTrue (iterator, funz):
for i in iterator:
    count = 0
    for f in funz:
        if f(i):
            count = count+1
        if count==len(funz):
            yield i
</code>```

I tried to write this:

```<code>def allTrue2 (iterator, funz):
    return (filter (f , iterator) for f in funz)
</code>```

But it's wrong. How could I improve the code?

Output:

```<code>print(list(allTrue(range(50),
               (lambda x: x % 3 == 0,
                lambda x: x > 10,
                lambda x: x < 44)
               )))

>>> [12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]
</code>```

答:
Keeping things close to your initial approach, you might use a for/else to break once a function returns False and move on to the next element. Only if all functions returned True and the loop never broke, the else part will be executed and yield this result:

def allTrue (iterator, funz):
    for i in iterator:
        for f in funz:
            if not f(i):
                break
        else:
            yield i
```

<hr>

<p>Regarding your <code>filter</code> approach, you basically created an iterator of iterators. You have an iterator filtering the list according to each function <strong>separatly</strong>. You want to filter the list, returning <strong>a single</strong> iterator, with the condition that <strong>all</strong> functions return <code>True</code>:</p>

<pre class="lang-py prettyprint-override"><code>def allTrue2 (iterator, funz):
    return filter(lambda i: all(f(i) for f in funz), iterator)
</code>```

Body:
I should rewrite my own function in a better way. The function takes an iterator and a sequence of boolean functions and returns an iterator of the elements in the input iterator which returns a truthy value.

def allTrue (iterator, funz):
for i in iterator:
    count = 0
    for f in funz:
        if f(i):
            count = count+1
        if count==len(funz):
            yield i

I tried to write this:

def allTrue2 (iterator, funz):
    return (filter (f , iterator) for f in funz)

But it's wrong. How could I improve the code?

Output:

print(list(allTrue(range(50),
               (lambda x: x % 3 == 0,
                lambda x: x > 10,
                lambda x: x < 44)
               )))

>>> [12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]

Body:
Keeping things close to your initial approach, you might use a for/else to break once a function returns False and move on to the next element. Only if all functions returned True and the loop never broke, the else part will be executed and yield this result:

def allTrue (iterator, funz):
    for i in iterator:
        for f in funz:
            if not f(i):
                break
        else:
            yield i

Regarding your filter approach, you basically created an iterator of iterators. You have an iterator filtering the list according to each function separatly. You want to filter the list, returning a single iterator, with the condition that all functions return True:

def allTrue2 (iterator, funz):
    return filter(lambda i: all(f(i) for f in funz), iterator)


问:
Store representations in SQL rather than whole strings?
I want to mark my users with one out of four static strings: indestructible, unstoppable, superefficient and megafantastic.

Would it be faster and more efficient to store a one char representation of the string rather than the whole string? Sort of like a key<->value mapping. The DB would only need to match one letter instead of a whole string when I do a search.

In the DB these words would only be represented as i,u,s and m. On the users profile I print indesctuctible if I get an i, unstoppable if I get a u etc.

Do I actually speed up anything by doing like this or is it just unnecessary work?

What if I have 10 more of these representations?

答:
Yes this should make your code faster, using a code 1,2,3,4 would be even fastest for 2 reasons

1) It takes less time to compare an int(that can be compared in 1 CPU cycle) than comparing two strings. Even 1 char may take more cycles because it needs to work if 'A' equals 'a' etc.

2) it takes up less space in the table, in a DB the smaller your rows are the faster your DB will be becaus SQL will be able to fit more rows onto a page.

You may need to have a serious number of users to notice the difference, but it would defenitley be good practice to store codes instead of values.

Regards GJ

ContentLicense: CC BY-SA 3.0


问:
how to use azure speaker recognition api in python
I am using python 2.7. I want to use speaker identification. I want to know how can i Enroll and get profile identified.

Can anyone send me code and module required to be downloaded. It would work by changing audio and subscription key.

thank you

答:
Please go to
https://azure.microsoft.com/en-us/services/cognitive-services/speaker-recognition/
and follow the 'API' link (on the row of links that starts with "Explore Speaker Recognition:"). It will take you to API documentation, starting right at the first topic about how to create enrollment. Each topic page has a code sample at the bottom in various languages, incl. Python.</p>


问:
CSV File: counting how many times the word "life" appears in a column
```<code>with open("billboard_songs.csv") as data:
for line in data:
    line_strip = line.split(",")
    if "life" in line[1]:
        continue
    else:
        print(line)
</code>```

What I want to accomplish is to count how many times the word "life" comes up in song titles. The CSV file is as follow: rank, song, artist, year, lyrics, source and it is split by commas (obviously). So we are looking in location [1] with song.

What am I doing wrong? My output gives me a list of songs but none have the word "life" in them.

答:
It looks like you've split your line into the array line_strip, so shouldn't your code read:

```<code>with open("billboard_songs.csv") as data:
for line in data:
    line_strip = line.split(",")
    if "life" in line_strip[1]:
        print(line)
    else:
        continue
        print(line)
</code>```

Body:
with open("billboard_songs.csv") as data:
for line in data:
    line_strip = line.split(",")
    if "life" in line[1]:
        continue
    else:
        print(line)

What I want to accomplish is to count how many times the word "life" comes up in song titles. The CSV file is as follow: rank, song, artist, year, lyrics, source and it is split by commas (obviously). So we are looking in location [1] with song.

What am I doing wrong? My output gives me a list of songs but none have the word "life" in them.

Body:
It looks like you've split your line into the array line_strip, so shouldn't your code read:

with open("billboard_songs.csv") as data:
for line in data:
    line_strip = line.split(",")
    if "life" in line_strip[1]:
        print(line)
    else:
        continue
        print(line)


问:
How to make the Firebase functions emulator trigger based on a database emulator update
In short, I want to test a Firebase function locally, specifically one that is triggered from a realtime database trigger. According to the docs for local testing, it seems that there are two ways of accomplishing local testing of Firebase functions:

Using the firebase functions emulator (firebase emulators:start --only functions)

Using the firebase functions shell (firebase functions:shell)

First, the differences between the two, at least in the linked guide, are very unclear. For the Firebase folks reading this, doc updates here would be great (considering local testing of this stuff is such an important feature).

My focus in this question (with respect to what I've tried) is based on the emulator, namely because it's mentioned that there are "interactions with other services". Interestingly, the list there only includes two items:

Cloud Firestore

Firebase Hosting

There is a notable omission of Realtime Database, and maybe that's where the gap is, but here we go.

My function looks something like this:

console.log("Hello World")

exports.myDatabaseTrigger = functions.database.ref('/a/path/{id}').onCreate((data, context) => {
  console.log(`myDatabaseTrigger triggered - here's my path ${data.ref.path}`);

  //manipulate some other stuff in the DB
})
```

<p>In my project, I am using both Functions and Realtime Database, so I run the command <code>firebase emulators:start</code> and it starts up both emulators.</p>

<p>In Postman, I use the local Realtime Database REST API to post some data with the following params:</p>

```POST
http://localhost:9000/a/path.json
{
  "some": "data"
}
```

And I get back a response containing the name of the newly created item under /a/path. However, my Firebase function never fires, and I never see the inner log (although the Hello World log does print when the emulator starts).

So, is the interaction between these two emulators possible? Or, am I forced to use the functions shell? My issue with the shell is that, based on the realtime database examples, it's not clear what the DataSnapshot variables (i.e. data.ref.path) will be if I simply call my function with some random value (e.g. myDatabaseTrigger({"some": "data"})).

答:
It looks like you may have just forgotten the project/namespace ID.

Try adding the ?ns= parameter to your POST:

```<code>POST
http://localhost:9000/a/path.json?ns="YOUR_PROJECT_ID"
{
  "some": "data"
}
</code>```

Emulated functions only trigger from writes to a single database instance, just like in production.

As for your points of confusion:

functions:shell is just a REPL for functions. It does not emulate any other services (Database, Firestore, etc).  Instead you directly pass in the data that would come from those services.

If you want to test Functions <--> Database interactions use emulators:start --only database,functions

In general the rule with emulators:start is that we comprehensively emulate whatever is running.  So for example if you're running the Functions and Database emulator, all writes from functions (through admin.database().... will be redirected to the Database emulator.  But writes to Firestore (admin.firestore()...) will try and hit production because that emulator is not running.

Body:
In short, I want to test a Firebase function locally, specifically one that is triggered from a realtime database trigger. According to the docs for local testing, it seems that there are two ways of accomplishing local testing of Firebase functions:

Using the firebase functions emulator (firebase emulators:start --only functions)

Using the firebase functions shell (firebase functions:shell)

First, the differences between the two, at least in the linked guide, are very unclear. For the Firebase folks reading this, doc updates here would be great (considering local testing of this stuff is such an important feature).

My focus in this question (with respect to what I've tried) is based on the emulator, namely because it's mentioned that there are "interactions with other services". Interestingly, the list there only includes two items:

Cloud Firestore

Firebase Hosting

There is a notable omission of Realtime Database, and maybe that's where the gap is, but here we go.

My function looks something like this:

console.log("Hello World")

exports.myDatabaseTrigger = functions.database.ref('/a/path/{id}').onCreate((data, context) => {
  console.log(`myDatabaseTrigger triggered - here's my path ${data.ref.path}`);

  //manipulate some other stuff in the DB
})

In my project, I am using both Functions and Realtime Database, so I run the command firebase emulators:start and it starts up both emulators.

In Postman, I use the local Realtime Database REST API to post some data with the following params:

POST
http://localhost:9000/a/path.json
{
  "some": "data"
}

And I get back a response containing the name of the newly created item under /a/path. However, my Firebase function never fires, and I never see the inner log (although the Hello World log does print when the emulator starts).

So, is the interaction between these two emulators possible? Or, am I forced to use the functions shell? My issue with the shell is that, based on the realtime database examples, it's not clear what the DataSnapshot variables (i.e. data.ref.path) will be if I simply call my function with some random value (e.g. myDatabaseTrigger({"some": "data"})).

Body:
It looks like you may have just forgotten the project/namespace ID.

Try adding the ?ns= parameter to your POST:

POST
http://localhost:9000/a/path.json?ns="YOUR_PROJECT_ID"
{
  "some": "data"
}

Emulated functions only trigger from writes to a single database instance, just like in production.

As for your points of confusion:

functions:shell is just a REPL for functions. It does not emulate any other services (Database, Firestore, etc).  Instead you directly pass in the data that would come from those services.

If you want to test Functions <--> Database interactions use emulators:start --only database,functions

In general the rule with emulators:start is that we comprehensively emulate whatever is running.  So for example if you're running the Functions and Database emulator, all writes from functions (through admin.database().... will be redirected to the Database emulator.  But writes to Firestore (admin.firestore()...) will try and hit production because that emulator is not running.


问:
Selenium Element not Visible Exception : Despite Using Correct XPATH and Putting Breakpoint to Wait for Element to Be Displayed in HTML
$x("//input[contains(@id,'default-column')]") - returns 10 elements

```<code>public List<WebElementFacade> defaultFieldsCheckBox;
</code>```

$x("(//input[contains(@id,'default-column')])[1]") - returns 1 element

```<code>public WebElementFacade firstFieldsCheckBox;
</code>```

"Customize Click" Opens List Of Check-boxes

Check Boxes are Displayed in View after "Customize Click"

I even put a breakpoint after "Customize Click" to ensure the Check-boxes are displayed (see image)

mpAuthPage.firstFieldsCheckBox.isDisplayed()
throws ElementNotVisibleException: Element not available

mpAuthPage.defaultFieldsCheckBox.size()
throws NoSuchElementException: Element not Visible

firstFieldsCheckBox can be found by XPATH and is clearly displayed in HTML

defaultFieldsCheckBox.size() should return 10 instead of error Element not
Visible

Any Ideas as to my issue ??

Checkbox Display In HTML

Image Of HTML Added

答:
This is actually kind of tricky. The custom-checkbox class makes the checkbox input itself hidden so it can't be interacted with.

You should instead try to click on the label like

```<code>//label[text() = '{Text of Label}']
</code>```

You could also target them by the for attribute to get all of them in one shot like this

```<code>//label[contains(@for, 'default-column')]
</code>```

Edit: Based on your comment, I got around this by

```<code>@driver.find_element(:xpath, "//label[contains(text(), '{label text}')]/preceding::input[1]").attribute("checked")
</code>```

That's ruby code. You didn't mention explicitly which language you're working with (I don't recognize it), but you should be able to convert it over fairly easily.

Body:
$x("//input[contains(@id,'default-column')]") - returns 10 elements

public List<WebElementFacade> defaultFieldsCheckBox;

$x("(//input[contains(@id,'default-column')])[1]") - returns 1 element

public WebElementFacade firstFieldsCheckBox;

"Customize Click" Opens List Of Check-boxes

Check Boxes are Displayed in View after "Customize Click"

I even put a breakpoint after "Customize Click" to ensure the Check-boxes are displayed (see image)

mpAuthPage.firstFieldsCheckBox.isDisplayed()
throws ElementNotVisibleException: Element not available

mpAuthPage.defaultFieldsCheckBox.size()
throws NoSuchElementException: Element not Visible

firstFieldsCheckBox can be found by XPATH and is clearly displayed in HTML

defaultFieldsCheckBox.size() should return 10 instead of error Element not
Visible

Any Ideas as to my issue ??

Checkbox Display In HTML

Image Of HTML Added

Body:
This is actually kind of tricky. The custom-checkbox class makes the checkbox input itself hidden so it can't be interacted with.

You should instead try to click on the label like

//label[text() = '{Text of Label}']

You could also target them by the for attribute to get all of them in one shot like this

//label[contains(@for, 'default-column')]

Edit: Based on your comment, I got around this by

@driver.find_element(:xpath, "//label[contains(text(), '{label text}')]/preceding::input[1]").attribute("checked")

That's ruby code. You didn't mention explicitly which language you're working with (I don't recognize it), but you should be able to convert it over fairly easily.


问:
SQL Server Procedure with dynamic IN operator and INT datatype
I have a SQL Server Table with some basic Sales information as follows

```<code>SaleID  |   TotalValue  |   PaymentMethod   |   User    |     Date
--------|---------------|-------------------|-----------|--------------
   1    |     10        |   CASH            |   USER 1  |   2020-01-01
   2    |     120       |   DEBIT CARD      |   USER 2  |   2020-01-01
   3    |     1000      |   CREDIT CARD     |   USER 2  |   2020-01-01
   4    |     305       |   CREDIT CARD     |   USER 1  |   2020-01-01
   5    |     15        |   CASH            |   USER 5  |   2020-01-01
</code>```

I need to write a Dynamic Procedure os something of the sort that's able to search for the sales information using an array of SaleIDs as a filter. It's a simple select query, as follows:

```<code>SELECT
     [SaleID]
    ,[TotalValue] as 'Total Value'
    ,[Date] as 'Date'
FROM
    [Sales]
WHERE
    [SaleID] in (1, 2, 3, 4)
</code>```

I created the following Stored Procedure so I can input an array of SalesID:

```<code>CREATE PROCEDURE [dbo].[usp_SearchSales]
(
      @SaleID NVARCHAR(max)
)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @ParameterDef NVARCHAR(500)

    SET @ParameterDef = '@SaleID NVARCHAR(max)'

SET @SQL = 'SELECT
                 [SaleID]
                ,[TotalValue]
                ,[PaymentMethod]
                ,[User]
                ,[Date]
            FROM
                [Sales]
            WHERE
                -1=-1'

IF @SaleID IS NOT NULL
SET @SQL = @SQL+ ' AND SaleID in (@SaleID)'

EXEC sp_Executesql @SQL, @ParameterDef, @SaleID = @SaleID

END

GO
</code>```

Then I execute the Procedure through the Exec command

```<code>EXEC [usp_SearchSales] @SaleID = '1, 2, 3, 4'
GO
</code>```

Then the procedure returns the following error uppon execution:

Msg 245, Level 16, State 1, Procedure usp_SearchSales, Line 26 [Batch Start Line 49]

Conversion failed when converting the nvarchar value '1, 2, 3, 4' to data type int.

Here is a SQL Query to create and insert some values on the designed table

```<code>CREATE TABLE [Sales] (
    [SaleID] int,
    [TotalValue] float,
    [PaymentMethod] varchar(50),
    [User] varchar(50),
    [Date] date
)

insert into sales values (1, 10, 'CASH', 'USER 1', '2020-01-01')
insert into sales values (2, 120, 'DEBIT CARD', 'USER 2', '2020-01-01')
insert into sales values (3, 10000, 'CREDIT CARD', 'USER 2', '2020-01-01')
insert into sales values (4, 305, 'CREDIT CARD', 'USER 1', '2020-01-01')
insert into sales values (5, 15, 'CASH', 'USER 5', '2020-01-01')
</code>```

I need some help to create a procedure, or something of the sort, where an array of SalesIDs gives me back the Sales informations of those Sales.

答:
Unfortunately SQL Server does not natively supports arrays, which makes that you are trying to do pretty hard (or cumbersome) to achieve.

While it should be possible to use string functions to search for values in the CSV list, let me suggest a cleaner option, that works by creating table type.

It starts by creating the type:

```<code>create type dbo.id_array as table (id int);
</code>```

Then your procedure can be simplified as a simple query:

```<code>create procedure dbo.usp_searchsales
    @sale_ids as dbo.id_array readonly
as
begin
    set nocount on;
    select
        s.saleid,
        s.totalvalue,
        s.paymentmethod,
        s.[user],
        s.date
    from sales s
    inner join @sale_ids a on a.id = s.saleid;
end
</code>```

Finally, when you want to invoke the procedure, you create a variable of the given type, fill it, and pass it as argument:

```<code>declare @my_sale_ids dbo.id_array;
insert into @my_sale_ids values (1), (2), (3), (4);
execute dbo.usp_searchsales @my_sale_ids;
</code>```

Demo on DB Fiddle:

```
saleid | totalvalue | paymentmethod | user   | date
-----: | ---------: | :------------ | :----- | :---------
     1 |         10 | CASH          | USER 1 | 2020-01-01
     2 |        120 | DEBIT CARD    | USER 2 | 2020-01-01
     3 |      10000 | CREDIT CARD   | USER 2 | 2020-01-01
     4 |        305 | CREDIT CARD   | USER 1 | 2020-01-01
```

Body:
I have a SQL Server Table with some basic Sales information as follows

SaleID  |   TotalValue  |   PaymentMethod   |   User    |     Date
--------|---------------|-------------------|-----------|--------------
   1    |     10        |   CASH            |   USER 1  |   2020-01-01
   2    |     120       |   DEBIT CARD      |   USER 2  |   2020-01-01
   3    |     1000      |   CREDIT CARD     |   USER 2  |   2020-01-01
   4    |     305       |   CREDIT CARD     |   USER 1  |   2020-01-01
   5    |     15        |   CASH            |   USER 5  |   2020-01-01

I need to write a Dynamic Procedure os something of the sort that's able to search for the sales information using an array of SaleIDs as a filter. It's a simple select query, as follows:

SELECT
     [SaleID]
    ,[TotalValue] as 'Total Value'
    ,[Date] as 'Date'
FROM
    [Sales]
WHERE
    [SaleID] in (1, 2, 3, 4)

I created the following Stored Procedure so I can input an array of SalesID:

CREATE PROCEDURE [dbo].[usp_SearchSales]
(
      @SaleID NVARCHAR(max)
)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @ParameterDef NVARCHAR(500)

    SET @ParameterDef = '@SaleID NVARCHAR(max)'

SET @SQL = 'SELECT
                 [SaleID]
                ,[TotalValue]
                ,[PaymentMethod]
                ,[User]
                ,[Date]
            FROM
                [Sales]
            WHERE
                -1=-1'

IF @SaleID IS NOT NULL
SET @SQL = @SQL+ ' AND SaleID in (@SaleID)'

EXEC sp_Executesql @SQL, @ParameterDef, @SaleID = @SaleID

END

GO

Then I execute the Procedure through the Exec command

EXEC [usp_SearchSales] @SaleID = '1, 2, 3, 4'
GO

Then the procedure returns the following error uppon execution:

Msg 245, Level 16, State 1, Procedure usp_SearchSales, Line 26 [Batch Start Line 49]

Conversion failed when converting the nvarchar value '1, 2, 3, 4' to data type int.

Here is a SQL Query to create and insert some values on the designed table

CREATE TABLE [Sales] (
    [SaleID] int,
    [TotalValue] float,
    [PaymentMethod] varchar(50),
    [User] varchar(50),
    [Date] date
)

insert into sales values (1, 10, 'CASH', 'USER 1', '2020-01-01')
insert into sales values (2, 120, 'DEBIT CARD', 'USER 2', '2020-01-01')
insert into sales values (3, 10000, 'CREDIT CARD', 'USER 2', '2020-01-01')
insert into sales values (4, 305, 'CREDIT CARD', 'USER 1', '2020-01-01')
insert into sales values (5, 15, 'CASH', 'USER 5', '2020-01-01')

I need some help to create a procedure, or something of the sort, where an array of SalesIDs gives me back the Sales informations of those Sales.

Body:
Unfortunately SQL Server does not natively supports arrays, which makes that you are trying to do pretty hard (or cumbersome) to achieve.

While it should be possible to use string functions to search for values in the CSV list, let me suggest a cleaner option, that works by creating table type.

It starts by creating the type:

create type dbo.id_array as table (id int);

Then your procedure can be simplified as a simple query:

create procedure dbo.usp_searchsales
    @sale_ids as dbo.id_array readonly
as
begin
    set nocount on;
    select
        s.saleid,
        s.totalvalue,
        s.paymentmethod,
        s.[user],
        s.date
    from sales s
    inner join @sale_ids a on a.id = s.saleid;
end

Finally, when you want to invoke the procedure, you create a variable of the given type, fill it, and pass it as argument:

declare @my_sale_ids dbo.id_array;
insert into @my_sale_ids values (1), (2), (3), (4);
execute dbo.usp_searchsales @my_sale_ids;

Demo on DB Fiddle:

saleid | totalvalue | paymentmethod | user   | date
-----: | ---------: | :------------ | :----- | :---------
     1 |         10 | CASH          | USER 1 | 2020-01-01
     2 |        120 | DEBIT CARD    | USER 2 | 2020-01-01
     3 |      10000 | CREDIT CARD   | USER 2 | 2020-01-01
     4 |        305 | CREDIT CARD   | USER 1 | 2020-01-01


问:
C/C++ line number
In the sake of debugging purposes, can I get the line number in C/C++ compilers?
(standard way or specific ways for certain compilers)

e.g

```<code>if(!Logical)
    printf("Not logical value at line number %d \n",LineNumber);
    // How to get LineNumber without writing it by my hand?(dynamic compilation)
</code>```

答:
Use __LINE__, but what is its type?

LINE The presumed line number (within the current source file) of the current source line (an integer constant).

As an integer constant, code can often assume the value is __LINE__ <= INT_MAX and so the type is  int.

To print in C, printf() needs the matching specifier: "%d".  This is a far lesser  concern in C++ with cout.

Pedantic concern: If the line number exceeds INT_MAX1 (somewhat conceivable with 16-bit int),  hopefully the compiler will produce a warning.  Example:

```<code>format '%d' expects argument of type 'int', but argument 2 has type 'long int' [-Wformat=]
</code>```

Alternatively, code could force wider types to forestall such warnings.

```<code>printf("Not logical value at line number %ld\n", (long) __LINE__);
//or
#include <stdint.h>
printf("Not logical value at line number %jd\n", INTMAX_C(__LINE__));
</code>```

Avoid printf()

To avoid all integer limitations: stringify.  Code could directly print without a printf() call: a nice thing to avoid in error handling2 .

```<code>#define xstr(a) str(a)
#define str(a) #a

fprintf(stderr, "Not logical value at line number %s\n", xstr(__LINE__));
fputs("Not logical value at line number " xstr(__LINE__) "\n", stderr);
</code>```

1 Certainly poor programming practice to have such a large file, yet perhaps machine generated code may go high.

2 In debugging, sometimes code simply is not working as hoped.  Calling complex functions like *printf() can itself incur issues vs. a simple fputs().

Title: C/C++ line number

Body:
In the sake of debugging purposes, can I get the line number in C/C++ compilers?
(standard way or specific ways for certain compilers)

e.g

if(!Logical)
    printf("Not logical value at line number %d \n",LineNumber);
    // How to get LineNumber without writing it by my hand?(dynamic compilation)

Body:
Use __LINE__, but what is its type?

LINE The presumed line number (within the current source file) of the current source line (an integer constant).

As an integer constant, code can often assume the value is __LINE__ <= INT_MAX and so the type is  int.

To print in C, printf() needs the matching specifier: "%d".  This is a far lesser  concern in C++ with cout.

Pedantic concern: If the line number exceeds INT_MAX1 (somewhat conceivable with 16-bit int),  hopefully the compiler will produce a warning.  Example:

format '%d' expects argument of type 'int', but argument 2 has type 'long int' [-Wformat=]

Alternatively, code could force wider types to forestall such warnings.

printf("Not logical value at line number %ld\n", (long) __LINE__);
//or
#include <stdint.h>
printf("Not logical value at line number %jd\n", INTMAX_C(__LINE__));

Avoid printf()

To avoid all integer limitations: stringify.  Code could directly print without a printf() call: a nice thing to avoid in error handling2 .

#define xstr(a) str(a)
#define str(a) #a

fprintf(stderr, "Not logical value at line number %s\n", xstr(__LINE__));
fputs("Not logical value at line number " xstr(__LINE__) "\n", stderr);

1 Certainly poor programming practice to have such a large file, yet perhaps machine generated code may go high.

2 In debugging, sometimes code simply is not working as hoped.  Calling complex functions like *printf() can itself incur issues vs. a simple fputs().


问:
Python "requests" with decorator
There is my code I'm trying to do:

```<code>import json
import requests

class Request(object):
  def __init__(self, method, path):
    self.method = method
    ## Q1
    self.url = ''.join([***MyClass.host***, path])
    self.h = {
      "Content-Type": "application/json;charset=UTF-8"
    }

  def __call__(self, f):
    def wrapper(*args, **kwargs):
      # Q2
      getattr(requests, self.method)(url = self.url, headers = h***, data = json.dumps(body)***)
    return wrapper

class MyClass(object):
  def __init__(self, host):
    self.host = host

  @Request(method = "post", path = "/add_mission")
  def AddMission(self, mission):
    body = {
      "mission_id": mission
    }

  @Request(method = "get", path = "/system_info")
  def GetInfo(self):
    print("I want get info")
</code>```

There are some questions hope someone can solve my problems:

1. How can my decorator "Request" get the variable "host" from "MyClass"? (In comment ## Q1)

2. How can I pass the function's variable "body" to decorator, is it possible? (In comment ## Q2)

Because I need to access different url(host+path) with [post, get, delete].
I'm not sure isn't decorator match on this case?
Or maybe there are better ways to deal with this case?

答:
The host is available once you call the decorated function, via the invoking object's host attribute, so wait until you actually call the method to build the URL. You'll want to call the underlying function to get back a value, if any, to use as the payload.

```<code>import json
import requests

class Request(object):
    def __init__(self, method, path):
        self.method = method.upper()
        self.h = {
            "Content-Type": "application/json;charset=UTF-8"
        }
        self.path = path

  def __call__(self, f):
      def wrapper(obj, *args, **kwargs):
          payload = f(*args, **kwargs)
          args = {
              'method': self.method,
              'url': 'http://{}/{}'.format(obj.host, self.path),
              'headers': self.h
          }
          if payload is not None:
              args['json'] = payload
          return requests.request(**args)
      return wrapper

class MyClass(object):
    def __init__(self, host):
        self.host = host

    @Request(method="post", path="/add_mission")
    def AddMission(self, mission):
        return {"mission_id": mission}

    @Request(method="get", path="/system_info")
    def GetInfo(self):
        print("I want get info")
</code>```

Then you can write, for example,

```<code>api = MyClass("www.example.com")
add_response = api.AddMission("mars")
info_response = api.GetInfo()
</code>```

Each decorated function returns the Response object produced by the call to requests.request.

You might consider subclasses of Request for each method:

```<code>class GetRequest(Request):
    def __init__(self, path):
        super().__init__("GET", path)

class PostRequest(Request):
    def __init__(self, path):
        super().__init__("POST", path)

# etc
</code>```

Title: Python "requests" with decorator

Body:
There is my code I'm trying to do:

import json
import requests

class Request(object):
  def __init__(self, method, path):
    self.method = method
    ## Q1
    self.url = ''.join([***MyClass.host***, path])
    self.h = {
      "Content-Type": "application/json;charset=UTF-8"
    }

  def __call__(self, f):
    def wrapper(*args, **kwargs):
      # Q2
      getattr(requests, self.method)(url = self.url, headers = h***, data = json.dumps(body)***)
    return wrapper

class MyClass(object):
  def __init__(self, host):
    self.host = host

  @Request(method = "post", path = "/add_mission")
  def AddMission(self, mission):
    body = {
      "mission_id": mission
    }

  @Request(method = "get", path = "/system_info")
  def GetInfo(self):
    print("I want get info")

There are some questions hope someone can solve my problems:

1. How can my decorator "Request" get the variable "host" from "MyClass"? (In comment ## Q1)

2. How can I pass the function's variable "body" to decorator, is it possible? (In comment ## Q2)

Because I need to access different url(host+path) with [post, get, delete].
I'm not sure isn't decorator match on this case?
Or maybe there are better ways to deal with this case?

Body:
The host is available once you call the decorated function, via the invoking object's host attribute, so wait until you actually call the method to build the URL. You'll want to call the underlying function to get back a value, if any, to use as the payload.

import json
import requests

class Request(object):
    def __init__(self, method, path):
        self.method = method.upper()
        self.h = {
            "Content-Type": "application/json;charset=UTF-8"
        }
        self.path = path

  def __call__(self, f):
      def wrapper(obj, *args, **kwargs):
          payload = f(*args, **kwargs)
          args = {
              'method': self.method,
              'url': 'http://{}/{}'.format(obj.host, self.path),
              'headers': self.h
          }
          if payload is not None:
              args['json'] = payload
          return requests.request(**args)
      return wrapper

class MyClass(object):
    def __init__(self, host):
        self.host = host

    @Request(method="post", path="/add_mission")
    def AddMission(self, mission):
        return {"mission_id": mission}

    @Request(method="get", path="/system_info")
    def GetInfo(self):
        print("I want get info")

Then you can write, for example,

api = MyClass("www.example.com")
add_response = api.AddMission("mars")
info_response = api.GetInfo()

Each decorated function returns the Response object produced by the call to requests.request.

You might consider subclasses of Request for each method:

class GetRequest(Request):
    def __init__(self, path):
        super().__init__("GET", path)

class PostRequest(Request):
    def __init__(self, path):
        super().__init__("POST", path)

# etc


问:
Importing a range vs one cell (using a query)
I have the following code which imports a cell-based on it falling in a given date range (set in separate cells).

```<code>=QUERY({2020!I:I},
 "where Col1 >= date '"&TEXT('[H] Target Date'!B7, "yyyy-mm-dd")&"'
 and Col1 <= date '"&TEXT('[H]Target Date'!B3, "yyyy-mm-dd")&"'", 0)
</code>```

I am now hoping to pull the entire row of data vs the single cell.

答:
try:</p>

```<code>=QUERY({2020!A:Z},
 "where Col9 >= date '"&TEXT('[H] Target Date'!B7, "yyyy-mm-dd")&"'
    and Col9 <= date '"&TEXT('[H] Target Date'!B3, "yyyy-mm-dd")&"'", 0)
</code>```

Body:
I have the following code which imports a cell-based on it falling in a given date range (set in separate cells).

=QUERY({2020!I:I},
 "where Col1 >= date '"&TEXT('[H] Target Date'!B7, "yyyy-mm-dd")&"'
 and Col1 <= date '"&TEXT('[H]Target Date'!B3, "yyyy-mm-dd")&"'", 0)

I am now hoping to pull the entire row of data vs the single cell.

Body:
try:

=QUERY({2020!A:Z},
 "where Col9 >= date '"&TEXT('[H] Target Date'!B7, "yyyy-mm-dd")&"'
    and Col9 <= date '"&TEXT('[H] Target Date'!B3, "yyyy-mm-dd")&"'", 0)


问:
How to add a picture next to a table?
```<code><style>

table.greyGridTable {
  border: 2px solid #2196F3;
  width: 50%;
  text-align: center;
  border-collapse: collapse;
  font-family: 'Times New Roman', Times, serif, Helvetica, sans-serif;
}
table.greyGridTable td, table.greyGridTable th {
  border: 1px solid #FFFFFF;
  padding: 3px 4px;
}
table.greyGridTable tbody td {
  text-align: left;
  font-size: 25px;
}
table.greyGridTable td:nth-child(even) {
  background:  #2196F3;
}
table.greyGridTable thead {
  background: #2196F3;
  border-bottom: 4px solid #333333;
}
table.greyGridTable thead th {
  font-size: 30px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  border-left: 2px solid #333333;
}
table.greyGridTable thead th:first-child {
  border-left: none;
}

table.greyGridTable tfoot {
  font-size: 14px;
  font-weight: bold;
  color: #333333;
  border-top: 4px solid #333333;
  background:  #2196F3 ;
}
table.greyGridTable tfoot td {
  font-size: 14px;
}

</style>
<style>
.Pa_Kreisi {
    float: left;
    width: 100%;
    height: top;
}
.Pa_Labi {
    float: right;
    width: 100%;
    height: top;
}
</style>

<div class="Pa_Kreisi">
    <table class="greyGridTable">
    <thead>
    <tr>
    <th>Atsēgas vārdi kurus meklēt mūsu mājas lapā:</th>

    </tr>
    </thead>
    <tfoot>
    <tr>
    <td>Meklēt iespējams caur logu lapas augšējā, labajā stūrī!</td>

    </tr>
    </tfoot>
    <tbody>
    <tr>
    <td>Komercprogrammatūra</td>

    </tr>
    <tr>
    <td>Izplatāmprogrammatūra</td>

    </tr>
    <tr>
    <td>Brīvprogrammatūra</td>

    </tr>
    <tr>
    <td>Bezmaksas programmatūra</td>
    </tr>

    </tr>
    </tbody>
    </table>
</div>
<div class="Pa_Labi">

    <img src="snow-run-final.jpg">

</div>
</code>```

Don't mind the text in the table. How do you put the picture next to the table at the top of the website?
I tried it with float, but it didn't work... maybe i made a mistake? Any help appreciated.

For some reason this website want's me to add more details to the question, so ill tell you about myself. I am 18 years old from Latvia, just started to learn how to code, and i am doing a homework for school right now. Since i want it to look pleasing as well, not just tick all the boxes teacher asked us to do, i am hereby asking for your help.

答:
You were setting the width to 100%, so the divs will take up the whole width. You need to set the width to 50% or possibly smaller, so that both divs can fit side by side. Also, div elements by default are block elements, which means that they take up the whole width, which can be solved using display: inline-block.

```<code><style>
.Pa_Kreisi {
    display: inline-block;
    width: 50%;
    height: top;
}

.Pa_Labi {
    display: inline-block;
    width: 50%;
    height: top;
}
</style>
</code>```

Alternatively, you can use float. In your question, you set one div to float: left and the other div to float: right, when they should ideally both be float: left.

```<code><style>
.Pa_Kreisi {
    float: left;
    width: 50%;
    height: top;
}

.Pa_Labi {
    float: left;
    width: 50%;
    height: top;
}
</style>
</code>```

As a side note, you are setting height: top, which is not valid.

Title: How to add a picture next to a table?

Body:
    Atsēgas vārdi kurus meklēt mūsu mājas lapā:

    Meklēt iespējams caur logu lapas augšējā, labajā stūrī!

    Komercprogrammatūra

    Izplatāmprogrammatūra

    Brīvprogrammatūra

    Bezmaksas programmatūra

Don't mind the text in the table. How do you put the picture next to the table at the top of the website?
I tried it with float, but it didn't work... maybe i made a mistake? Any help appreciated.

For some reason this website want's me to add more details to the question, so ill tell you about myself. I am 18 years old from Latvia, just started to learn how to code, and i am doing a homework for school right now. Since i want it to look pleasing as well, not just tick all the boxes teacher asked us to do, i am hereby asking for your help.

Body:
You were setting the width to 100%, so the divs will take up the whole width. You need to set the width to 50% or possibly smaller, so that both divs can fit side by side. Also, div elements by default are block elements, which means that they take up the whole width, which can be solved using display: inline-block.

<style>
.Pa_Kreisi {
    display: inline-block;
    width: 50%;
    height: top;
}

.Pa_Labi {
    display: inline-block;
    width: 50%;
    height: top;
}
</style>

Alternatively, you can use float. In your question, you set one div to float: left and the other div to float: right, when they should ideally both be float: left.

<style>
.Pa_Kreisi {
    float: left;
    width: 50%;
    height: top;
}

.Pa_Labi {
    float: left;
    width: 50%;
    height: top;
}
</style>

As a side note, you are setting height: top, which is not valid.


问:
Using 1:n relations in django admin
I want to build a questionary in Django and use django's admin-interface to enter the data.
The site-admin should be able to set-up new questionaries with questions. Define models which questions have always a querstionary in relation is no problem:

```<code>class Questionary(models.Model):
    title = models.CharField(max_length=50)

    def __unicode__(self):
        return self.title

class Question(models.Model):
    text = models.CharField(max_length=150)
    questionary = models.ForeignKey(Questionary)

    def __unicode__(self):
        return self.text
</code>```

Using this I can create and edit questionaries (but only it's title) in the admin. Also I can edit every single Question with an relation to the questionary. But only one question a time.

Is there a way to set up the models (or a part of the admin-area) to have the "questionary-part" at the top and the questions below that in the admin-interface? With buttons to add and delete questions?

Thanks a lot,

mfapl

答: Yes you can, take a look at InlineModelAdmin</p>

Title: Using 1:n relations in django admin

Body:
I want to build a questionary in Django and use django's admin-interface to enter the data.
The site-admin should be able to set-up new questionaries with questions. Define models which questions have always a querstionary in relation is no problem:

class Questionary(models.Model):
    title = models.CharField(max_length=50)

    def __unicode__(self):
        return self.title

class Question(models.Model):
    text = models.CharField(max_length=150)
    questionary = models.ForeignKey(Questionary)

    def __unicode__(self):
        return self.text

Using this I can create and edit questionaries (but only it's title) in the admin. Also I can edit every single Question with an relation to the questionary. But only one question a time.

Is there a way to set up the models (or a part of the admin-area) to have the "questionary-part" at the top and the questions below that in the admin-interface? With buttons to add and delete questions?

Thanks a lot,

mfapl


问:
Display number 0 in excel cell
I'm using a userform to add numbers in my excel sheet.

When someone add 01234  in the userform, I only see 1234  in the excel cell.

So I modified the cell format, it worked but whenever i wanted to only add 1234 , excel would display a 0 so 01234 .

I just want to be able to add the textbox value as it is in excel sheets.

Thank you

EDIT:

This is a part of the code that takes the textbox value and enters in the requested cell :

```<code>Sheets("Sheet3").Range("B4").Select
ActiveCell.Value = UCase(TextBox2)
</code>```

答:
Prefix zero-prefixed entries with ' (single quote), no prefix for non-zero prefixed entries?

```   A
1'01234
2 1234```

=A1+A2->2468 (OK)

Title: Display number 0 in excel cell

Body:
I'm using a userform to add numbers in my excel sheet.

When someone add 01234  in the userform, I only see 1234  in the excel cell.

So I modified the cell format, it worked but whenever i wanted to only add 1234 , excel would display a 0 so 01234 .

I just want to be able to add the textbox value as it is in excel sheets.

Thank you

EDIT:

This is a part of the code that takes the textbox value and enters in the requested cell :

Sheets("Sheet3").Range("B4").Select
ActiveCell.Value = UCase(TextBox2)

Body:
Prefix zero-prefixed entries with ' (single quote), no prefix for non-zero prefixed entries?

   A
1'01234
2 1234

=A1+A2->2468 (OK)


问:
Power Query: Apostrophe in Custom Column Name
I have an odd situation that I haven't been able to find an answer to. In Power Query, my custom columns have suddenly developed an apostrophe before the field name.

[

The code line is below, which doesn't include any tick marks and the field is formatted as dates so not sure where this is coming from. I tried deleting the apostrophe manually once the results loaded in Excel, but wasn't successful (delete apostrophe, hit enter, return to cell and it's still there). Any ideas?

```<code>"Added Custom" = Table.AddColumn(#"Changed Type3", "Renewal_Date", each Date.EndOfMonth([DATE_MATURITY_NEXT]))
</code>```

答:
There is no apostrophe in the field name. You are loading the results into a table on the excel sheet, and that is how it displays left-aligned text in the formula bar.  Try formatting the cell as right-aligned and the display will show "Renewal_Date; with center alignment formatting will show ^Renewal_Date

See prefix section of excel documentation

Text value corresponding to the "label prefix" of the cell. Returns single quotation mark (') if the cell contains left-aligned text, double quotation mark (") if the cell contains right-aligned text, caret (^) if the cell contains centered text, backslash () if the cell contains fill-aligned text, and empty text ("") if the cell contains anything else.

Body:
I have an odd situation that I haven't been able to find an answer to. In Power Query, my custom columns have suddenly developed an apostrophe before the field name.

[

The code line is below, which doesn't include any tick marks and the field is formatted as dates so not sure where this is coming from. I tried deleting the apostrophe manually once the results loaded in Excel, but wasn't successful (delete apostrophe, hit enter, return to cell and it's still there). Any ideas?

"Added Custom" = Table.AddColumn(#"Changed Type3", "Renewal_Date", each Date.EndOfMonth([DATE_MATURITY_NEXT]))


问:
Typescript Open File Dialog to Upload File from an Angular Service without using an input element
I have an Angular keystroke service that I am listening to keyboard keystrokes & performing actions based on the keystroke pressed.

I have a keyboard shortcut that I would like for it to open the file dialog, & the user should select a specific JSON file to upload, & then use this JSON data & convert to an object to use in the system.

The normal way of uploading a file is trough a HTML: <input type="file" />. However I am in a service and I don't need an input element, nor do I have where to put it. as I don't think a service should contain HTML.

How can I accomplish to trigger the file dialog box to open in a function & get the data of the selected JSON file that without an input and without downloading any external npm packages.

答:
Unfortunately, <input type="file"> is a little bit special in HTML. You cannot generate such an event in JavaScript that would correspond clicking this input.

The only way to trigger this programmatically is to have a hidden UI component where this input is added and then the click triggered.


问:
Getting the selected value on autocomplete in Jquery
I added an Autocomplete feature to a form on a HTML template, i would like to perform some actions when an hint is selected, is there any way to do it? I'm using Jquery-Typeahead. Here is my actual code:</p>

```<code>$(document).ready(function(){

  // Defining the local dataset
  $.getJSON('http://127.0.0.1:8000/myapi', function(data) {
    console.log(data)

    var dt = data

    $(() => {

      $('#myform').typeahead({
        source: {
          data: dt.results.map(record => record.item)
        },
        callback: {
          onInit: function($el) {
            console.log(`Typeahead initiated on: ${$el.prop('tagName')}#${$el.attr('id')}`);
          },
          onClick: function() {
            console.log(); //How can i console.log() the selected value here, for example?
          }
        }
      });

    });

  });
});
</code>```

答:
Try defining an onClickAfter callback, it's called right after user clicks on an item. Something like this:

onClickAfter: function(node, a, item, event) {
  // item will be the item you selected
  console.log(item);
}```

You can also define the onClickBefore callback the same way, and it will be called immediately before "normal" typeahead behaviour kicks in

Body:
I added an Autocomplete feature to a form on a HTML template, i would like to perform some actions when an hint is selected, is there any way to do it? I'm using Jquery-Typeahead. Here is my actual code:

$(document).ready(function(){

  // Defining the local dataset
  $.getJSON('http://127.0.0.1:8000/myapi', function(data) {
    console.log(data)

    var dt = data

    $(() => {

      $('#myform').typeahead({
        source: {
          data: dt.results.map(record => record.item)
        },
        callback: {
          onInit: function($el) {
            console.log(`Typeahead initiated on: ${$el.prop('tagName')}#${$el.attr('id')}`);
          },
          onClick: function() {
            console.log(); //How can i console.log() the selected value here, for example?
          }
        }
      });

    });

  });
});

Body:
Try defining an onClickAfter callback, it's called right after user clicks on an item. Something like this:

onClickAfter: function(node, a, item, event) {
  // item will be the item you selected
  console.log(item);
}

You can also define the onClickBefore callback the same way, and it will be called immediately before "normal" typeahead behaviour kicks in


问:
Solver cannot loop over rows with linked formulas?
I have a spreadsheet that contains multiple columns/rows. I am trying to apply Solver for certain rows in a column.

I have my formulas set in column 22, I have defined initial values that needs to be solved by Solver in column 24, and I want to match the value in the column 10 for each row.

So far, I have developed this code:

```<code>Sub SolverLoop()
Dim i As Long

For i = 4 To 10

    SolverReset
    SolverOk SetCell:=Cells(i, 22).Address, MaxMinVal:=3, ValueOf:=Cells(i, 10).Address, ByChange:=Cells(i, 24).Address, Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverSolve Userfinish:=True

Next

End Sub
</code>```

But this is not doing anything to the column 24, which I expect to change. What am I missing?

Formula in the column 22 is =R123C12*NORMSDIST(RC[-2])-RC[-10]*EXP(-R16C2)*NORMSDIST(RC[-1]). Subsequently, in 20 and 21 are =(LN(R123C12/RC[-8])+(R15C2+RC[4]^2/2)*R14C2)/(RC[4]*SQRT(R14C2)) and =RC[-1]-RC[3]*SQRT(R14C2), respectively.

答:
```<code>Sub SolverLoop()
Dim i As Long

For i = 4 To 10

    SolverReset
    SolverOk SetCell:=Cells(i, 22), MaxMinVal:=3, ValueOf:=Cells(i, 10).Value, ByChange:=Cells(i, 25), Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverSolve Userfinish:=True

Next

End Sub
</code>```

Looks like I was just missing .Value part for ValueOf:=Cells(i, 10).Value.

Body:
I have a spreadsheet that contains multiple columns/rows. I am trying to apply Solver for certain rows in a column.

I have my formulas set in column 22, I have defined initial values that needs to be solved by Solver in column 24, and I want to match the value in the column 10 for each row.

So far, I have developed this code:

Sub SolverLoop()
Dim i As Long

For i = 4 To 10

    SolverReset
    SolverOk SetCell:=Cells(i, 22).Address, MaxMinVal:=3, ValueOf:=Cells(i, 10).Address, ByChange:=Cells(i, 24).Address, Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverSolve Userfinish:=True

Next

End Sub

But this is not doing anything to the column 24, which I expect to change. What am I missing?

Formula in the column 22 is =R123C12*NORMSDIST(RC[-2])-RC[-10]*EXP(-R16C2)*NORMSDIST(RC[-1]). Subsequently, in 20 and 21 are =(LN(R123C12/RC[-8])+(R15C2+RC[4]^2/2)*R14C2)/(RC[4]*SQRT(R14C2)) and =RC[-1]-RC[3]*SQRT(R14C2), respectively.

Body:
Sub SolverLoop()
Dim i As Long

For i = 4 To 10

    SolverReset
    SolverOk SetCell:=Cells(i, 22), MaxMinVal:=3, ValueOf:=Cells(i, 10).Value, ByChange:=Cells(i, 25), Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverSolve Userfinish:=True

Next

End Sub

Looks like I was just missing .Value part for ValueOf:=Cells(i, 10).Value.


问:
How to set start and end time for fullcalendar agendaWeek view?
Is it possible to set a start and end time for the agendaWeek view in fullcalendar? I want to save the actual chosen week in a cookie and open this week when the user opens the calendar the next time.</p>

答:
http://arshaw.com/fullcalendar/docs/

How did I do?

First of all - everything can be found in this amazing site.. the plugin actual manual.

http://arshaw.com/fullcalendar/docs/

Then you can use this

```<code>.fullCalendar( 'changeView', viewName )
</code>```

Avaialble views

month available since version 1.3

basicDay - since version 1.3

agendaWeek available since version 1.4

agendaDay - since version 1.4

Apart from that - You can call the gotoDate from a cookie or other variable after the initialisation of the calendar

gotoDate

Moves the calendar to an arbitrary year/month/date.

```<code> .fullCalendar( 'gotoDate', year [, month, [ date ]] ) IMPORTANT: month is 0-based, meaning January=0, February=1, etc.
</code>```

and that should be called form an anonymous function - something in the line of

```<code> $("#youCalendarID").fullCalendar( 'gotoDate', getCookie.year, getCookie.Month)
</code>```

Ya MAN! Dont forget to look at this site
http://arshaw.com/fullcalendar/docs/

Body:
http://arshaw.com/fullcalendar/docs/

How did I do?

First of all - everything can be found in this amazing site.. the plugin actual manual.

http://arshaw.com/fullcalendar/docs/

Then you can use this

.fullCalendar( 'changeView', viewName )

Avaialble views

month available since version 1.3

basicDay - since version 1.3

agendaWeek available since version 1.4

agendaDay - since version 1.4

Apart from that - You can call the gotoDate from a cookie or other variable after the initialisation of the calendar

gotoDate

Moves the calendar to an arbitrary year/month/date.

 .fullCalendar( 'gotoDate', year [, month, [ date ]] ) IMPORTANT: month is 0-based, meaning January=0, February=1, etc.

and that should be called form an anonymous function - something in the line of

 $("#youCalendarID").fullCalendar( 'gotoDate', getCookie.year, getCookie.Month)

Ya MAN! Dont forget to look at this site
http://arshaw.com/fullcalendar/docs/


问:
Render components conditionally, based on items of deeply nested array
I have a React component that's receiving a data object returned from an API response.

I'm trying to write a function that accepts a field from that data response, checks an element inside of that field and iterates over it checking each object inside the array for the value of a specific alert.

If a value for a specific alert is found I need to render an Icon for that alert.

The data object looks like this:

```<code>location: {
  ...,
details: {
  summary: [
            {
             type: 'calling',
             icon: 'phone'
             },
             {
             type: 'power',
             icon: 'electric'
             },
             {
             type: 'water',
             icon: 'water-icon'
             },
           ]
        }
      }
</code>```

And here's the section where I'm trying to conditionally render the icons (this was my first pass and rudimentary attempt):

```<code>           <div>
            {location.alertDetails && (
                <IconBox title={`Alerts`}>
                  <IconSection>
                  {location.details.summary.includes(type === calling) &&
                   <CallIcon />
                   }
                   {location.details.summary.includes(type === power) &&
                   <ElectricIcon />
                   }
                  {location.details.summary.includes(type === water) &&
                   <WaterIcon />
                  }
                  </IconSection>
                </IconBox>
              )}
            </div>
</code>```

答:
You may store within components state the array of fetched types:

```<code>const [types, setTypes] = useState(location.details.summary.map(({type}) => type))
</code>```

With that, you may simply render (or not) your icons conditionally:

```<code> <div>
  {location.alertDetails && (
      <IconBox title={`Alerts`}>
        <IconSection>
           {types.includes('calling') && <CallIcon />}
           {types.includes('power') && <ElectricIcon />}
           {types.includes('water') && <WaterIcon />}
        </IconSection>
      </IconBox>
    )}
  </div>
</code>```

Here's the demo (with all of your components rendered as a
's, since I dont have those):

const { render } = ReactDOM,
      { useState } = React

const apiData = {location:{details:{summary:[{type:'calling',icon:'phone'},{type:'power',icon:'electric'},{type:'water',icon:'water-icon'},]}}}

const IconTray = ({data}) => {
  const [types, setTypes] = useState(data.location.details.summary.map(({type}) => type))
  return (

        {data.location.details && (

                 {types.includes('calling') &&
I am a CallIcon
}
                 {types.includes('power') &&
I am an ElectronIcon
}
                 {types.includes('water') &&
I am a WaterIcon
}

          )}

  )
}

render (
  <IconTray data={apiData} />,
  document.getElementById('root')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div></code>```

Body:
I have a React component that's receiving a data object returned from an API response.

I'm trying to write a function that accepts a field from that data response, checks an element inside of that field and iterates over it checking each object inside the array for the value of a specific alert.

If a value for a specific alert is found I need to render an Icon for that alert.

The data object looks like this:

location: {
  ...,
details: {
  summary: [
            {
             type: 'calling',
             icon: 'phone'
             },
             {
             type: 'power',
             icon: 'electric'
             },
             {
             type: 'water',
             icon: 'water-icon'
             },
           ]
        }
      }

And here's the section where I'm trying to conditionally render the icons (this was my first pass and rudimentary attempt):

            {location.alertDetails && (
                <IconBox title={`Alerts`}>
                  <IconSection>
                  {location.details.summary.includes(type === calling) &&
                   <CallIcon />
                   }
                   {location.details.summary.includes(type === power) &&
                   <ElectricIcon />
                   }
                  {location.details.summary.includes(type === water) &&
                   <WaterIcon />
                  }
                  </IconSection>
                </IconBox>
              )}

Body:
You may store within components state the array of fetched types:

const [types, setTypes] = useState(location.details.summary.map(({type}) => type))

With that, you may simply render (or not) your icons conditionally:

 <div>
  {location.alertDetails && (
      <IconBox title={`Alerts`}>
        <IconSection>
           {types.includes('calling') && <CallIcon />}
           {types.includes('power') && <ElectricIcon />}
           {types.includes('water') && <WaterIcon />}
        </IconSection>
      </IconBox>
    )}
  </div>

Here's the demo (with all of your components rendered as a <div>'s, since I dont have those):

const { render } = ReactDOM,
      { useState } = React

const apiData = {location:{details:{summary:[{type:'calling',icon:'phone'},{type:'power',icon:'electric'},{type:'water',icon:'water-icon'},]}}}

const IconTray = ({data}) => {
  const [types, setTypes] = useState(data.location.details.summary.map(({type}) => type))
  return (
     <div>
        {data.location.details && (
            <div>
              <div>
                 {types.includes('calling') && <div>I am a CallIcon</div>}
                 {types.includes('power') && <div>I am an ElectronIcon</div>}
                 {types.includes('water') && <div>I am a WaterIcon</div>}
              </div>
            </div>
          )}
     </div>
  )
}

render (
  <IconTray data={apiData} />,
  document.getElementById('root')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>


问:
Counting duplicates when using "IN" operator
I think I narrowed my query down to an easy-to-understand example here:

```<code>SELECT SUM(cost) FROM tableX WHERE prod_id IN
(SELECT prod_id FROM tableY WHERE val = 7)
</code>```

My issue is this - sometimes the same prod_id will be returned multiple times.  But because of the nature of the "IN" operator, it would only be counted once by the "SUM(cost)" function.  What is the best way to handle this?  Thanks!

答:
I have a hunch that you just need to group by the product.</p>

```<code>SELECT prod_id, SUM(cost) AS TotalCost
FROM tableX
WHERE prod_id IN (
    SELECT DISTINCT prod_id
    FROM tableY
    WHERE val = 7
)
GROUP BY prod_id
</code>```

Body:
I think I narrowed my query down to an easy-to-understand example here:

SELECT SUM(cost) FROM tableX WHERE prod_id IN
(SELECT prod_id FROM tableY WHERE val = 7)

My issue is this - sometimes the same prod_id will be returned multiple times.  But because of the nature of the "IN" operator, it would only be counted once by the "SUM(cost)" function.  What is the best way to handle this?  Thanks!

Body:
I have a hunch that you just need to group by the product.

SELECT prod_id, SUM(cost) AS TotalCost
FROM tableX
WHERE prod_id IN (
    SELECT DISTINCT prod_id
    FROM tableY
    WHERE val = 7
)
GROUP BY prod_id


问:
How to show which values of one list are in other list?
Having 2 lists, I want check which values of List1 are in List2. I'm trying as below but I get error

```<code>List1 = {3,2,8,7,5}
List2 = {1,3,4,2,6,7,9}
= List.Transform(List1, each Text.Contains(List2, _))

Expression.Error: We cannot convert a value of type List to type Text.
Details:
    Value=[List]
    Type=[Type]
</code>```

My expected output would be 3,2,7.

How can I do this?

答:
@horseyride has probably the best answer but using your original logic, you could also write the intersection like this:

```<code>List.Select(List1, each List.Contains(List2, _))
</code>```

This uses Select instead of Transform since you are trying to select/filter instead of changing the elements and uses the appropriate List type instead of Text for the Contains part.

Body:
Having 2 lists, I want check which values of List1 are in List2. I'm trying as below but I get error

List1 = {3,2,8,7,5}
List2 = {1,3,4,2,6,7,9}
= List.Transform(List1, each Text.Contains(List2, _))

Expression.Error: We cannot convert a value of type List to type Text.
Details:
    Value=[List]
    Type=[Type]

My expected output would be 3,2,7.

How can I do this?

Body:
@horseyride has probably the best answer but using your original logic, you could also write the intersection like this:

List.Select(List1, each List.Contains(List2, _))

This uses Select instead of Transform since you are trying to select/filter instead of changing the elements and uses the appropriate List type instead of Text for the Contains part.


问:
Design a FA to accept L, where L = Strings in which ‘a’ always appears tripled
Design a FA to accept L, where L = {Strings in which ‘a’ always appears tripled} over the input set Σ = {a, b}.

This is my solution (A is start state):

From what I understand the question doesn't say it should always contain "a",
it should also accept strings like {b,bb,bbb}. Is this correct?

答:
Your solution appears right to me! It really depends on the interpretation of the question. I also interpreted that a's could also be separated, as long as they were always tripled.

abbabbbab should be accepted as a's are tripled always, come in threes.

You should make sure of that! I also did this FA in the case above, but my generic understanding of the question would be your interpretation which looks fine!


问:
Store representations in SQL rather than whole strings?
I want to mark my users with one out of four static strings: indestructible, unstoppable, superefficient and megafantastic.

Would it be faster and more efficient to store a one char representation of the string rather than the whole string? Sort of like a key<->value mapping. The DB would only need to match one letter instead of a whole string when I do a search.

In the DB these words would only be represented as i,u,s and m. On the users profile I print indesctuctible if I get an i, unstoppable if I get a u etc.

Do I actually speed up anything by doing like this or is it just unnecessary work?

What if I have 10 more of these representations?

答: Sure, you might see a little performance boost. That said, it may not be worth it if you compromise your database design. This is a normalization question. Without knowing how you're planning on using the data it is difficult to say exactly how you should structure your data.</p>


问:
Endianess macros not correctly defined
I'm trying to compile grpc, and one of the targets uses /usr/include/netinet/tcp.h which contains this :

```<code># if __BYTE_ORDER == __LITTLE_ENDIAN
        uint8_t th_x2:4;        /* (unused) */
        uint8_t th_off:4;       /* data offset */
# endif
# if __BYTE_ORDER == __BIG_ENDIAN
        uint8_t th_off:4;       /* data offset */
        uint8_t th_x2:4;        /* (unused) */
# endif
</code>```

Somehow, the two conditions are fulfilled which makes the compilation fail (error: duplicate member 'th_off'). I wrote a test C program and it seems that the three macros are not correctly defined.

I tried to reinstall gcc and g++, and also downgrade them to a previous version. I also tried to reinstall the Linux headers. I finally tried to compile with clang, but it doesn't work either.

My two test computers are running Ubuntu 19.10 and the result is the same on both of them. Is there a compiler flag or a system configuration needed to define these macros?

EDIT : tcp.h is a system header. I did not write it and it's an almost fresh install of Ubuntu with a standard installation of build-essentials.

EDIT 2 : I used a test program and it works correctly in this case. It shows little:

```<code>#include <iostream>
#include <netinet/tcp.h>

int main() {
#if __BYTE_ORDER == __LITTLE_ENDIAN
    std::cout << "little\n";
#endif
#if __BYTE_ORDER == __BIG_ENDIAN
    std::cout << "big\n";
#endif
}
</code>```

答:
On my Debian system, __LITTLE_ENDIAN and __BIG_ENDIAN are defined in /usr/include/endian.h. I believe this file is intended to be generic across architectures.

__BYTE_ORDER is defined to be one of them in /usr/include/bits/endian.h. I think the bits directory contains headers that are specific to a particular architecture.

tcp.h includes <types.h>, which I think should indirectly include these and define the macros. I'm not sure why it's not happening for you.

Title: Endianess macros not correctly defined

Body:
I'm trying to compile grpc, and one of the targets uses /usr/include/netinet/tcp.h which contains this :

# if __BYTE_ORDER == __LITTLE_ENDIAN
        uint8_t th_x2:4;        /* (unused) */
        uint8_t th_off:4;       /* data offset */
# endif
# if __BYTE_ORDER == __BIG_ENDIAN
        uint8_t th_off:4;       /* data offset */
        uint8_t th_x2:4;        /* (unused) */
# endif

Somehow, the two conditions are fulfilled which makes the compilation fail (error: duplicate member 'th_off'). I wrote a test C program and it seems that the three macros are not correctly defined.

I tried to reinstall gcc and g++, and also downgrade them to a previous version. I also tried to reinstall the Linux headers. I finally tried to compile with clang, but it doesn't work either.

My two test computers are running Ubuntu 19.10 and the result is the same on both of them. Is there a compiler flag or a system configuration needed to define these macros?

EDIT : tcp.h is a system header. I did not write it and it's an almost fresh install of Ubuntu with a standard installation of build-essentials.

EDIT 2 : I used a test program and it works correctly in this case. It shows little:

#include <iostream>
#include <netinet/tcp.h>

int main() {
#if __BYTE_ORDER == __LITTLE_ENDIAN
    std::cout << "little\n";
#endif
#if __BYTE_ORDER == __BIG_ENDIAN
    std::cout << "big\n";
#endif
}


答:
I have not verified it, but I don't see a reason why this won't work:</p>

```<code>SELECT SUM(cost)
FROM tableX
INNER JOIN tableY ON tableX.prod_id = tableY.prod_id AND tableY.val = 7
</code>```

Title: Counting duplicates when using "IN" operator

Body:
I have not verified it, but I don't see a reason why this won't work:

SELECT SUM(cost)
FROM tableX
INNER JOIN tableY ON tableX.prod_id = tableY.prod_id AND tableY.val = 7


问:
How to exit app from login while logout from the app using navigation component?
Below is my code;

navigation.xml

```<code> <fragment android:id="@+id/HomeFragment"
          android:label="Home Screen">
    <action
            android:id="@+id/action_activeRefillDeviceFragment_to_loginFragment"
            app:destination="@id/loginFragment"
            app:popUpTo="@id/loginFragment"
            app:popUpToInclusive="true"/>
</fragment>

  <fragment android:id="@+id/loginFragment"
          android:name="com.example.dprefilldevice.login.fragment.LoginFragment"
          android:label="LoginFragment">
    <action android:id="@+id/action_loginFragment_to_activeRefillDeviceFragment"
            app:destination="@id/activeRefillDeviceFragment"
            app:popUpTo="@id/loginFragment"
            app:popUpToInclusive="true"/>
</fragment>
</code>```

Logout button click event;

```<code> override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        R.id.logout -> {
            Utils.getPreferrence(context)?.edit()?.clear()?.apply()
            findNavController().navigate(R.id.action_activeRefillDeviceFragment_to_loginFragment)
        }
    }
    return super.onOptionsItemSelected(item)
}
</code>```

答: May be you should try to make change to your graph: change first action to have app:popUpTo="@id/HomeFragment". Idea behind this: to remove home fragment from backstack and then place login fragment into backstack. I do not recommend to forcibly finish your activity.

Body:
Below is my code;

navigation.xml

 <fragment android:id="@+id/HomeFragment"
          android:label="Home Screen">
    <action
            android:id="@+id/action_activeRefillDeviceFragment_to_loginFragment"
            app:destination="@id/loginFragment"
            app:popUpTo="@id/loginFragment"
            app:popUpToInclusive="true"/>
</fragment>

  <fragment android:id="@+id/loginFragment"
          android:name="com.example.dprefilldevice.login.fragment.LoginFragment"
          android:label="LoginFragment">
    <action android:id="@+id/action_loginFragment_to_activeRefillDeviceFragment"
            app:destination="@id/activeRefillDeviceFragment"
            app:popUpTo="@id/loginFragment"
            app:popUpToInclusive="true"/>
</fragment>

Logout button click event;

 override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        R.id.logout -> {
            Utils.getPreferrence(context)?.edit()?.clear()?.apply()
            findNavController().navigate(R.id.action_activeRefillDeviceFragment_to_loginFragment)
        }
    }
    return super.onOptionsItemSelected(item)
}


答:
You could create a lookup table and which has a fk into the main table

```<code>Character
------------
CharacterID
Name
ProfileID int (FK)

Profile
--------
ProfileID
ProfileDesc
</code>```

where profile table is

```<code>ProfileID, ProfileDesc
----------------------
1        , indestructable
2        , ...
</code>```

This would allow you to add a smaller more efficient index onto the ProfileID in the Character table

Title: Store representations in SQL rather than whole strings?

Body:
I want to mark my users with one out of four static strings: indestructible, unstoppable, superefficient and megafantastic.

Would it be faster and more efficient to store a one char representation of the string rather than the whole string? Sort of like a key<->value mapping. The DB would only need to match one letter instead of a whole string when I do a search.

In the DB these words would only be represented as i,u,s and m. On the users profile I print indesctuctible if I get an i, unstoppable if I get a u etc.

Do I actually speed up anything by doing like this or is it just unnecessary work?

What if I have 10 more of these representations?

Body:
You could create a lookup table and which has a fk into the main table

Character
------------
CharacterID
Name
ProfileID int (FK)

Profile
--------
ProfileID
ProfileDesc

where profile table is

ProfileID, ProfileDesc
----------------------
1        , indestructable
2        , ...

This would allow you to add a smaller more efficient index onto the ProfileID in the Character table


问:
Can the Python .replace() function replace whole phrases?
I'm a video editor trying to automate word docs of talent scripts into STR files for captions to speed up the process. Since each video is structured the same, the idea works pretty well. In the scripts, there are editing directions that I'm trying to remove from the STR file I'm creating with Python and the python-docx library by using the .replace() function, however this doesn't seem to be working. These all begin with '(CUT' and the following possible sentences vary. The program correctly picks up where these sentences are occurring but the replace function yields no resulting change. What am I doing wrong here?</p>
```<code>for x in range(2,len(doc.paragraphs)):
newPara = doc.paragraphs[x].text

if (newPara.find('(CUT') != -1):
    newPara.replace('(CUT', '')

    if (newPara.find('COMPLETE)') != -1):
        newPara.replace(' AWAY COMPLETE)', '')

    elif (newPara.find('TITLE)') != -1):
        newPara.replace(' AWAY TO TITLE)', '')

    elif (newPara.find('SIDE)') != -1):
        newPara.replace(' BACK TO SIDE)', '')
</code>```

答:
str.replace() doesn't mutate the original string - it returns the mutated string.
you should re-assign to you variable:

#...
if (newPara.find('(CUT') != -1):
    newPara = newPara.replace('(CUT', '')

    if (newPara.find('COMPLETE)') != -1):
        newPara = newPara.replace(' AWAY COMPLETE)', '')

    elif (newPara.find('TITLE)') != -1):
        newPara = newPara.replace(' AWAY TO TITLE)', '')

    elif (newPara.find('SIDE)') != -1):
        newPara = newPara.replace(' BACK TO SIDE)', '')
```

Body:
I'm a video editor trying to automate word docs of talent scripts into STR files for captions to speed up the process. Since each video is structured the same, the idea works pretty well. In the scripts, there are editing directions that I'm trying to remove from the STR file I'm creating with Python and the python-docx library by using the .replace() function, however this doesn't seem to be working. These all begin with '(CUT' and the following possible sentences vary. The program correctly picks up where these sentences are occurring but the replace function yields no resulting change. What am I doing wrong here?

for x in range(2,len(doc.paragraphs)):
newPara = doc.paragraphs[x].text

if (newPara.find('(CUT') != -1):
    newPara.replace('(CUT', '')

    if (newPara.find('COMPLETE)') != -1):
        newPara.replace(' AWAY COMPLETE)', '')

    elif (newPara.find('TITLE)') != -1):
        newPara.replace(' AWAY TO TITLE)', '')

    elif (newPara.find('SIDE)') != -1):
        newPara.replace(' BACK TO SIDE)', '')


问:
How can I use layers of existing docker image when build another one?
I have built one docker image via Dockerfile. And then I've found a mistake in the last layer. So when I rebuild the image I see that the layers are made anew. Can I use existing layers of the existing image? It takes too much time to make them.

UPD

Thanks for the answering, I have rebuild the image without time-wasting layers (Qt debian packages comes enough, without building Qt from sources). For the moment I cannot make sure that layers are reused so I believe they are so.

答:
The build process will reuse the existing layers, Depending on how you are positioning your Dockerfile directives. There are some best practices to use.

Back to the caching the cached layers will show up as "Using Cache" in you build output.

For even more enhancements your can use the new BUILDKIT to do to the builds.
to enable build kit do:
DOCKER_BUILDKIT=1 docker build .

More over buildkit.


答:
Using join instead of IN will ensure that each x item would be counted as many times as there are records in the y:

```<code>SELECT SUM(cost)
FROM tableX x
JOIN tableY y ON x.prod_id = y.prod_id AND val = 7
</code>```

Note that this approach works only in situations when you don't want to retrieve any other columns from x. If that is not the case, you would need to group by on the additional columns that you wish to return:

```<code>SELECT x.prod_id, x.name, SUM(cost), COUNT(*)
FROM tableX x
JOIN tableY y ON x.prod_id = y.prod_id AND val = 7
GROUP BY x.prod_id, x.name
</code>```

Body:
Using join instead of IN will ensure that each x item would be counted as many times as there are records in the y:

SELECT SUM(cost)
FROM tableX x
JOIN tableY y ON x.prod_id = y.prod_id AND val = 7

Note that this approach works only in situations when you don't want to retrieve any other columns from x. If that is not the case, you would need to group by on the additional columns that you wish to return:

SELECT x.prod_id, x.name, SUM(cost), COUNT(*)
FROM tableX x
JOIN tableY y ON x.prod_id = y.prod_id AND val = 7
GROUP BY x.prod_id, x.name


问:
Dynamically loading resource dictionary files to a wpf application gives an error
I am trying to add a xaml resource file dynamically using the statement,

```<code>Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("resources/leaf_styles.xaml", UriKind.Relative) });
</code>```

This is throwing an exception, Cannot locate resource 'resources/leaf_styles.xaml'.

I added the leaf_styles.xaml file to the project under resource folder and the BuildAction is set to "Content", CopyAlways is set to True. Still I get this error. Could some one help me out pointing whats wrong??

Additional information -

I don't want to embed the xaml file as a resource

The current project is a .net 3.5 class library project

The above mergedictionary statement is written in a class belonging to the same project

I also added the [assembly: AssemblyAssociatedContentFile("resources/leaf_styles.xaml")] manually once I figured that this is not working (for testing)

Update

If I give it as an absolute location, it is working properly.

```<code>Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(@"D:\foo\trunk\bin\resources\leaf_styles.xaml", UriKind.Absolute) });
</code>```

答:
To load a content file, you can call the GetContentStream method of the Application class, passing a pack URI that identifies the desired content file.

Checkout

http://msdn.microsoft.com/en-us/library/aa970494.aspx#Content_Files

EDIT

I did it successfully like this

```<code>    Uri uri = new Uri("Resources/MyDict.xaml", UriKind.Relative);
    StreamResourceInfo info = Application.GetContentStream(uri);
    System.Windows.Markup.XamlReader reader = new System.Windows.Markup.XamlReader();
    ResourceDictionary myResourceDictionary =
                                   (ResourceDictionary)reader.LoadAsync(info.Stream);
    Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);
</code>```

Body:
I am trying to add a xaml resource file dynamically using the statement,

Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("resources/leaf_styles.xaml", UriKind.Relative) });

This is throwing an exception, Cannot locate resource 'resources/leaf_styles.xaml'.

I added the leaf_styles.xaml file to the project under resource folder and the BuildAction is set to "Content", CopyAlways is set to True. Still I get this error. Could some one help me out pointing whats wrong??

Additional information -

I don't want to embed the xaml file as a resource

The current project is a .net 3.5 class library project

The above mergedictionary statement is written in a class belonging to the same project

I also added the [assembly: AssemblyAssociatedContentFile("resources/leaf_styles.xaml")] manually once I figured that this is not working (for testing)

Update

If I give it as an absolute location, it is working properly.

Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(@"D:\foo\trunk\bin\resources\leaf_styles.xaml", UriKind.Absolute) });

Body:
To load a content file, you can call the GetContentStream method of the Application class, passing a pack URI that identifies the desired content file.

Checkout

http://msdn.microsoft.com/en-us/library/aa970494.aspx#Content_Files

EDIT

I did it successfully like this

    Uri uri = new Uri("Resources/MyDict.xaml", UriKind.Relative);
    StreamResourceInfo info = Application.GetContentStream(uri);
    System.Windows.Markup.XamlReader reader = new System.Windows.Markup.XamlReader();
    ResourceDictionary myResourceDictionary =
                                   (ResourceDictionary)reader.LoadAsync(info.Stream);
    Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);