text:
Q: How can I stop to update data before clicking on update button in edit form? I am working on the vue.js template and I have one content edit and content add form. When I click on the edit button then on that time I passed the object to show data for editing in form but I used v-modal that shows instant changes before clicking on button update.
<v-form v-model="valid" @submit.prevent="updateContact(edit)">
    <v-card-text>
        <v-container grid-list-md>
            <v-layout wrap>
                <v-flex xs12>
                    <v-text-field label="Name" v-model="edit.name"></v-text-field>
                </v-flex>
                <v-flex xs12>
                    <v-text-field label="Designation" v-model="edit.designation"></v-text-field>
                </v-flex>

            </v-layout>
        </v-container>
    </v-card-text>
    <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn color="primary" @click="onEditCancel()">Cancel</v-btn>
        <v-btn color="error" type="submit">Update</v-btn>
    </v-card-actions>
</v-form>

When I click on edit button then I hit following function:
onEditContact(contact) {
    this.dialog1 = true;
    this.edit = contact;
},

Contact update method:
updateContact(edit){
    console.log(edit);
}

A: You can reset the form data changes if that is not save, by adding additional attributes to v-dialog component
<v-dialog v-model="dialog1"
  ref="editDetails"
  :return-value.sync="edit"
>
</v-dialog>

In updateContact, if the item is saved properly you can save perfs
this.$refs.editDetails.save(this.edit);


text:
Q: Writing a SQL query to search for similar addresses in a database I'm attempting to write a query which will find similar addresses in a database.
For example, users may type in a variety of addresses which may be incorrect. A similar address should be shown as the result.
For example, users might search for -
"177 pleasant street"

"177 pleasant st"

"177 pleasant road"

How can I implement this?
So far I have tried -
SELECT * FROM Table WHERE Address LIKE '%177 pleasant st%' AND ...etc...

A: I would consider using full text search for this instead.
The big benefit is that it would help with spellings (pleasant, plesant, pleasont etc.). Of course, it would match similarity primarily on linguistical grounds, not geographical ones.

A: That's not an easy task.
You should extract the entities of the search string and the stored string and compare the same kind of entities.
In your example:

street_number: the numeric part of string.
street_name: the non-numeric part of string excluding words in a dictionary {street, st, road}
IF street_number AND street_name MATCH you can return that address.

Extract entities for general cases is dificult and you can use tools to help you.
Check: https://developers.google.com/maps/documentation/javascript/geocoding

A: SOUNDEX function in SQL Server can get your basic matching done.
SELECT * FROM [Table] WHERE SOUNDEX([Address]) = SOUNDEX('177 pleasant st')

If you want to further customize your search by 'percent of keyword matches', you can go for implementing Jaro Winkler algorithm  in a stored procedure which does the matching for you. You can start reading about Jaro Winkler here. Otherwise as suggested previously, you might need to go for matching tools.
Also take a look here

A: It depends on what you want to achieve. By the looks of it whatever the request the most important information is "177" and "pleasant" and "road" (information from your original database). So, if there are only three search parameters then you can use simple query like one below. If you want to use more then you will have to use full text search.
    DECLARE @DataFromUserInterFace varchar(300)
SET @DataFromUserInterFace='177 pleasant street'

SELECT
[Address]
FROM
[Employer]
WHERE
CHARINDEX
(
 substring([Address], 1, CHARINDEX(' ', [Address], 1)-1)
 , @DataFromUserInterFace
 , 1)!=0
OR
CHARINDEX
(
substring
([Address]
, CHARINDEX(' ', [Address], 1)+1
, CHARINDEX(' ', [Address], CHARINDEX(' ', [Address], 1)+1)
-CHARINDEX(' ', [Address], 1)-1)
, @DataFromUserInterFace
, 1)
!=0
OR
CHARINDEX
(
substring([Address], CHARINDEX(' ', [Address], CHARINDEX(' ', [Address], 1)+1)+1,
CHARINDEX(' ', [Address], CHARINDEX(' ', [Address], 1)+1)
-CHARINDEX(' ', [Address], CHARINDEX(' ', [Address], 1)-1)
)
, @DataFromUserInterFace
, 1)
!=0

A: If you normalize the address a bit the task would become easier or at least more accurate. Break address into it's own table like this:
 Create table Address(
       AddressKey    int not null ,
       addressnumber nvarchar(10),
       street        nvarchar (50),
       streetSuffix  nvarchar (10)
       ... (city,state,zip,etc.)
       )

Your query can then specify what part of the address you want to search for similarities against.
Select *
from table t inner join
address a on a.addresskey=t.addresskey
Where a.street = 'pleasant'
      and a.streetnumber='177'

Note: I Left streetnumber as nvarchar to accommodate '23A' type stuff but even that could be broken out.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delete rows from one workbook based on data in another workbook I extract 2 database reports that export in Excel tables. I have to remove rows from reportA based on data that already exists in reportA.
(Example: If Column 5 contains the word "Pepsi" in any cell of that column, delete the entire row in reportA)
I have to also remove rows from reportA based on data that exists in a specific column in reportB. So if any cell in a specific column of reportA contains the exact cell value from a specific column in reportB based on key words, delete that row in reportA.
(Example: Filter any cell in Column 4 of reportB containing the word "Coke" or "Sprite", reportB has matches of "Coke Zero" and "Sprite Shipment" in 2 cells in Column 4. Delete EVERY row from reportA that contains "Coke Zero" or "Sprite Shipment" in Column 5 of reportA)
Did a bit of research and came up with the below script to at least remove rows from reportA.
Sub Clean_Up_Food_Items()

  Application.Calculation = xlCalculationManual
  Application.ScreenUpdating = False

   Dim lo As ListObject

   Set lo = Sheet2.ListObjects(1)
   lo.Parent.Activate 'Activate sheet that table is on.

   lo.AutoFilter.ShowAllData

   lo.Range.AutoFilter Field:=5, Criteria1:="Coke*"

   Application.DisplayAlerts = False
     lo.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
   Application.DisplayAlerts = True

   lo.AutoFilter.ShowAllData

   lo.Range.AutoFilter Field:=4, Criteria1:="Fanta*"

   Application.DisplayAlerts = False
     lo.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
   Application.DisplayAlerts = True

   lo.AutoFilter.ShowAllData

  Application.Calculation = xlCalculationAutomatic
  Application.ScreenUpdating = True

End Sub

The above works to at least remove rows based on data that exists in reportA, but I can't figure out how to filter out the data based on reportB to remove rows in reportA.

A: You can use several values at once in the filter. To use several values in the filter, you need to use 1) 1-D array for criteria and 2) xlFilterValues enumeration value for Operator parameter. In the example below I filter first column of range A1 with two values.

Sub Z()

    Dim rngA As Range
    Dim arrValuesToFilter As Variant

    arrValuesToFilter = [{"Fanta", "Pepsi"}]
    Set rngA = Range("A1").CurrentRegion
    rngA.AutoFilter Field:=1, Criteria1:=arrValuesToFilter, Operator:=xlFilterValues

End Sub


text:
Q: How to give different user access to different people? I have a video tutorial website where I have to provide videos. For that purpose I have to give different user access to those who login to particular courses.
So can you please help me what is the functionality for user access manager?

A: *

*The most obvious approach to this would be to first create a
special user role for your students.

*Then for users with this role you can expand the profile with extra
fields. Here you can store for every user which courses they
follow.

*Next you define a custom post type that allows you to store the
video labelled with the courses for which it is meant.

*Finally, in your templates, you check if the content of user fields
matches the labels of the video, to make sure users only see the
videos they should get.


text:
Q: Consistent union of months into a quarter, half year, year I have an array of Deposits (first column)
data class Deposit(val term: Int, val termType String, val rate BigDecimal)

I tried to divide the array into blocks of 3 elements in order to combine 1 month into one quarter (assuming the same rate), but in other cases it is more convenient to take 2 elements, although in this case the union may not occur correctly. 2nd and 3rd quarter are merged into half a year.
Tell me how you can, albeit not in an optimal way, recursively perform a sequential conversion of months into a quarter, half a year and a year.
Example:

Input
Step 1..N
Output

1 month – 6%
1 quarter — 6%
1 quarter — 6%

1 month – 6%

1 month – 6%

3 month – 5%
1 quarter – 5%
1 quarter – 5%

3 month – 5%
1 quarter – 5%
1 quarter – 5%

3 month – 3%
1 quarter – 3%
1 quarter – 3%

3 month – 6%
1 half a year – 6%
1 year – 6%

3 month – 6%

3 month – 6%
1 half a year – 6%

3 month – 6%

3 month – 7%
1 half a year – 7%
1 half a year – 7%

3 month – 7%

3 month – 8%
1 half a year – 8%
1 half a year – 8%

3 month – 8%

I tried to divide the array into blocks of 3 elements in order to combine 1 month into one quarter (assuming the same rate), but in other cases it is more convenient to take 2 elements, although in this case the union may not occur correctly. 2nd and 3rd quarter are merged into half a year.


text:
Q: DCount with 2 criteria I am using DCount to help display an error message if the data signals an error.  I have it working with one criteria where a number is equal to another number.  Now I wanted to add another criteria in there where another field, ReturnDate (this field is Text not Date/Time) is equal to a hyphen (-).
I'm just not really sure how to format it.  I have this:
If DCount("*", "CrewTable", "KitNumber=" & _
  Me.AssignKit.Value And "ReturnDate=" & _
  "-") > 0 Then
  Cancel = True
  MsgBox "Kit is already assigned!"
  AssignKit = ""
  AssignKit.SetFocus
Else
...

The error pops up with a 'Type Mistmatch' and the debugger highlights the whole statment from 'If -> Then' and has an error pointing to the line with the hyphen in the quotes.

A: If DCount("*", "CrewTable", "ReturnDate='-' AND KitNumber=" & _
          Me.AssignKit.Value) > 0 Then

A: It's easier to troubleshoot DCount errors when you store its Criteria option in a string variable.
Dim strCriteria As String
strCriteria = "ReturnDate='-' AND KitNumber=" & Me.AssignKit.Value
Debug.Print strCriteria
If DCount("*", "CrewTable", strCriteria) > 0 Then

If you had used this approach, Access would have alerted you to the fact that the original code which built the Criteria string was invalid.  That should make it clearer that the problem wasn't due to the If condition, and it wasn't exactly a DCount problem either ... it was a problem with string concatenation.

A: Me.AssignKit.Value & " And ReturnDate=" & _


text:
Q: What do "great comment" votes do? I understand the idea of voting for a great comment, but why does the comment's score change colors at five-ish up votes?  Comment votes don't seem to give reputation, or anything else, for being great.

A: Expanding on Kyle, the primary purpose of them was to get the best comments loaded on the page for all requests (instead of via AJAX) - so they can be indexed by search engines/visible to all users.

A: All the votes do is help to visually identify good or insightful comments. You are correct, the color of the vote count does change at (IIRC) around 5 upvotes, and then again around 10. The specific color is tied to the site you're on; for example, the color becomes more orange on Stack Overflow.
Also, when the page initially loads, there will be at most 5 comments below each post. The rest of the comments can be expanded out, but the initial comments are the five highest-scoring.
Other than that, the score serves no purpose. However, I will say that even though I don't get reputation from a comment vote, I personally like to see that someone liked my comment and thought it was good or insightful.
For more information, see https://blog.stackoverflow.com/2009/04/comments-top-n-shown/

A: I still think there should be a badge, even a bronze one, for getting 10 upvotes on a comment.


text:
Q: Clover bootloader is missing bootable hard drives I have two installs of Clover EFI

*

*Clover on my SSD

*Clover on my USB

The SSD Clover - Loads clover properly, no option to boot from hard drive I want to fix this.
The USB Clover - Loads clover properly, lists options to boot, including hard drive
Both of them allow me to boot into UEFI shell, but from there it is unclear what to do.
How would I go about adding the hard drive to the clover boot list? Or have it autodetected? In grub2, for example, you can just tell it to reconfigure. In windows, you can use BCDEdit. But for Clover, I am lost.

A: I had an incorrect config.plist file in the /EFI/CLOVER directory. I simply replaced it with an older working one. (You could also regenerate one)


text:
Q: How to pass the name of variable to a function and return its value in C#? i have a case where i have several variables with similar names but not in an array. What i want to do is to pass the names of the variables to some function that i create and that function would return the value of the variable that was passed to the function by its name.
For example:
int valueByName(int x, string variableName){
   string newVar;
   string numString = x.ToString();
   newVar = variableName + numString;

   //and here i should get the value of newVar and return it to use it. but how?
   return valeuof(newVar);???
}

int num1 = 1;
int num2 = 2;
int num3 = 3;
string varName = "num";

for(int i = 1; i < 4; i++){
   Console.WriteLine(valueByName(i, varName));
}

A: You can do this using .NET Reflection:
public class Foo
{
    private int field1 = 1;
    private int field2 = 2;
    private int field3 = 3;

    public int GetValueOf(string field)
    {
        FieldInfo f = this.GetType().GetTypeInfo().GetField(field,
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        return (int)f.GetValue(this);
    }

}

Usage
var x = new Foo();
var y = x.GetValueOf("field2");

// y has value of 2

NOTE: .NET Reflection is not usually the best design choice because it doesn't perform very well. If performance is critical, I recommend you try to come up with a design that doesn't require you to lookup the value by name to avoid the performance impact this will incur.


text:
Q: Links and installation of codelite dependencies I know you might want to mark this as an "duplicate" but it's not.
All the answers on similar questions are either outdated or don't really include dependencies installation. dist-upgrade didn't help either.
sudo apt-get install codelite wxcrafter

gives me following errors:
    The following packages have unmet dependencies:
 codelite : Depends: libglib2.0-0 (>= 2.41.1) but 2.40.2-0ubuntu1 is to be installed
            Depends: libhunspell-1.3-0 (>= 1.3.3) but 1.3.2-6ubuntu2 is to be installed
            Depends: xterm
            Depends: libedit-dev but it is not going to be installed
 libjbig0 : Breaks: libjbig0:i386 (!= 2.0-2ubuntu4.1) but 2.0-2ubuntu1 is to be installed
 libjbig0:i386 : Breaks: libjbig0 (!= 2.0-2ubuntu1) but 2.0-2ubuntu4.1 is to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

I'm looking for links to dependencies or any other solution.
Thanks
EDIT:
I tried sudo apt-get -f install and it reported some broken packages (libjbig0 and libjbig0:i386) so I did force-remove them and now
sudo apt-get install codelite wxcrafter

gives me following:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 codelite : Depends: libglib2.0-0 (>= 2.41.1) but 2.40.2-0ubuntu1 is to be installed
            Depends: libhunspell-1.3-0 (>= 1.3.3) but 1.3.2-6ubuntu2 is to be installed
E: Unable to correct problems, you have held broken packages.

I tried finding those "held broken packages" but without success.
sudo apt-get -f install

gives me:
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

"0 not upgraded" - that looks fine, right?

A: I needed to add trusty repository instead of utopic one.
To install codelite follow instructions on codelite official installation page
except for:
sudo apt-add-repository 'deb http://repos.codelite.org/ubuntu/ trusty universe'
run this instead:
sudo apt-add-repository 'deb http://repos.codelite.org/ubuntu/ utopic universe'


text:
Q: Notification from NodeJs to React client doesn't work (Server-Sent-Events) I'm trying to send a notification to my React UI anytime someone access my NodeJs request.
The request is the following:
 app.get('/notification', (req, res) => {
        res.writeHead(200, {
            "Connection": "keep-alive",
            "Content-Type": "text/event-stream",
            "Cache-Control": "no-cache",
            "Access-Control-Allow-Origin": "*"
          });

        if(req.query.id == 'audio')
        {
            res.write(`data: TEST\n\n`);
            res.write("\n\n");
        }

        res.end();

  })
  .listen(5000, () => {
    console.log("Server running at http://127.0.0.1:5000/");
  });

In my component constructor ( App ) I used a EventSource as follows:
constructor(props) {
    super(props);

    this.eventSource = new EventSource( 'http://' + CONSTANTS.IP_API +':5000/notification');
    this.eventSource.onmessage = function(e) {
            console.log(e.data);
    };
 }

However, as you may have guessed, it doesn't work.
I don't know if this is the expected way EventSource works and if I didn't understand the point, but when calling http://localhost:5000/notification?id=audio, I see my result displayed as a response but this result doesn't show up in the UI console. It seems the EventSource listener doesn't catch it...
The listener tries to connect every second but I need a real time listener. Is EventSource appropriate for this? Or should I use socket.io instead?
Thanks in advance, and forgive me if this sounds trivial, I'm beginning with NodeJs and react :)


text:
Q: Calibrating the axes of a 2D plot When the data
a = Table[Sin[x], {x, 1, 20, 0.1}];
ListPlot[0.1 *a]

is plotted, one finds that the range of x-axes is labeled as 0 to 200:

How can one reset the calibration so that the axis shows the range only up to 20?

A: You can use the DataRange option:
ListPlot[0.1 a, DataRange -> {1, 20}]


text:
Q: Python: await the outer most async function Python coroutine created with 'async' keyword (Python 3.5+) can be awaited, however, the outer most one can't be awaited as Python says "SyntaxError: 'await' outside function"
import asyncio as aio

async def f():
    print(1)
    await aio.sleep(3)
    print(2)
    return 3

print(await f())

How to 'await' the 'f' function in the example above?

A: If you use Python 3.7+, the syntax is even simpler (no need to manually create a loop etc.):
import asyncio as aio

async def f():
    print(1)
    await aio.sleep(3)
    print(2)
    return 3

print(aio.run(f())

A: It's not possible to await at global scope, instead, run an event loop as below:
import asyncio as aio

async def f():
    print(1)
    await aio.sleep(3)
    print(2)
    return 3

def fdone(r):
    print(r.result())

loop = aio.get_event_loop()
t = loop.create_task(f())
t.add_done_callback(fdone)
loop.run_until_complete(t)
print(4)


text:
Q: The best way to design RESTFull API where a method is applicable to both the entity and the list? let's say we have a restful API that returns either a list of all books or an information about an individual book, i.e. something like this:
/books/{book_id}

Now, I need to define a "history" method that would return a history of the book requests. It's applicable to all books as well as an individual book.
What's the best way to design such the API?
Shall I allocate another resource i.e /history and then call it with a parameter that can be either book_id or "*all"
or add the history parameter to the existing book resource?
Thanks,


text:
Q: List all keyvault secrets I would like to know if there is a way to list down all secrets, keys, certificates inside azure keyvault. I can check on portal but that takes lot of time if I have to export this info in excel.
Anyway I can do with powershell ?
Thanks in advance!

A: The Get-AzureKeyVaultSecret module is probably your best bet.
Get-AzureKeyVaultSecret -VaultName "vaultname" | Select Name

Change vaultname to the name of your vault and it will show you the names of all the items stored in the given vault. You can also adjust the Select to get back all the data you need, or pipe to Export-Csv directly.


text:
Q: Creating XML values from values in Pandas Dataframe I am new to XML Element Tree and I am wondering how to properly convert the values I have in a pandas dataframe into XML values.
Here is a sample of what the values of my dataframe look like:
 Id         Email           State      Country      LastName
Mjkx  sealover71@yahoo.com   CA     United States    Withers

I know what I have below probably isn't close to working but I figured what I want to happen is possible with df.iterrows(). How do I create XML values for each column in my dataframe with XML Element Tree?
for row in df.iterrows():
    id = ET.SubElement('ID', 'id')
    lastname = ET.SubElement('LastName', 'lastname')
    email = ET.SubElement('Email', 'email')
    state = ET.SubElement('State', 'state')
    country = ET.SubElement('Country', 'country')

print(ET.tostring(row, pretty_print=True).decode('utf-8'))

Here is what the desired output should look like to post into our crm:
<crc>
  <lead>
    <id>Mjkx</id>
    <lastname>Withers</lastname>
    <email>sealover71@yahoo.com</email>
    <state>CA</state>
    <country>United States</country>
  </lead>
</crc>

Thanks for your help!

A: You had the right idea with ElementTree
from io import StringIO
import pandas as pd
from xml.etree import ElementTree

# in-place prettyprint formatter
# https://web.archive.org/web/20200703234431/http://effbot.org/zone/element-lib.htm
def indent(elem, level=0):
    i = "\n" + level * "  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level + 1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

data = """\
Id,Email,State,Country,LastName
Mjkx,sealover71@yahoo.com,CA,United States,Withers
Asdf,foo@yahoo.com,IL,United States,Capone
Qwer,bar@yahoo.com,NV,United States,Sinatra
"""

f = StringIO(data)
df = pd.read_csv(f)

#print(df)

root = ElementTree.Element('crc')

for _, r in df.iterrows():
    lead = ElementTree.SubElement(root, 'lead')

    for c in df.columns:
        e = ElementTree.SubElement(lead, c)
        e.text = str(r[c])

indent(root)
x = ElementTree.tostring(root)

print(x.decode('UTF-8'))


text:
Q: Installed WDK Version from windows command line How do I find out the installed WDK version on my windows machine via the windows command line? I can find it through Visual studio and "Control Panel -> Installed Softwares" on my local machine but I'm trying to check this on a container and only have access to the windows command line and cannot confirm if there is a wdk installed on the container.

A: I'm not sure, you still need the answer, but I have a crunch.
The easiest way to get latest installed version, would be read file
C:\Program Files (x86)\Windows Kits\10\build\WindowsDriver.Default.props
which is used by MSBuild during the build. This file has following content:
  <!-- some content before... -->

  <PropertyGroup>

    <!-- Current KitOS property -->
    <CurrentKitOS>winv10.0</CurrentKitOS>

    <!-- Latest Target Version property -->
    <LatestTargetVersion>Windows10</LatestTargetVersion>

    <!-- Older TargetPlatformVersion properties -->
    <TargetPlatformVersion_TH1>10.0.10240.0</TargetPlatformVersion_TH1>
    <TargetPlatformVersion_TH2>10.0.10586.0</TargetPlatformVersion_TH2>
    <TargetPlatformVersion_RS1>10.0.14393.0</TargetPlatformVersion_RS1>
    <TargetPlatformVersion_RS2>10.0.15063.0</TargetPlatformVersion_RS2>
    <TargetPlatformVersion_RS3>10.0.16299.0</TargetPlatformVersion_RS3>
    <TargetPlatformVersion_RS4>10.0.17134.0</TargetPlatformVersion_RS4>
    <TargetPlatformVersion_RS5>10.0.17763.0</TargetPlatformVersion_RS5>
    <TargetPlatformVersion_19H1>10.0.17763.0</TargetPlatformVersion_19H1>

    <TargetVersion Condition="'$(TargetVersion)' == ''">$(LatestTargetVersion)</TargetVersion>

    <LatestTargetPlatformVersion>$([Microsoft.Build.Utilities.ToolLocationHelper]::GetLatestSDKTargetPlatformVersion('Windows', '10.0'))</LatestTargetPlatformVersion>
    <LatestWdkPlatformVersion>10.0.18362.0</LatestWdkPlatformVersion>
    <LatestTargetPlatformVersion Condition="'$(LatestTargetPlatformVersion)' != '' and '$(LatestTargetPlatformVersion)' > '$(LatestWdkPlatformVersion)'">$(LatestWdkPlatformVersion)</LatestTargetPlatformVersion>
    <WindowsTargetPlatformVersion Condition="'$(WindowsTargetPlatformVersion)' == ''">$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion>
    <TargetPlatformVersion>$(WindowsTargetPlatformVersion)</TargetPlatformVersion>
    <OverrideCfgV1 Condition="'$(OverrideCfgV1)' == '' and '$(WindowsTargetPlatformVersion)' <= '10.0.14250.0'">true</OverrideCfgV1>
    <MatchingSdkPresent Condition="Exists('$(WDKContentRoot)\DesignTime\CommonConfiguration\Neutral\UAP\$(TargetPlatformVersion)\UAP.props')">true</MatchingSdkPresent>
    <MatchingWdkPresent Condition="Exists('$(WDKContentRoot)\Include\$(TargetPlatformVersion)\km\ntddk.h')">true</MatchingWdkPresent>

  </PropertyGroup>

  <!-- some content after... -->

You could read value of <LatestTargetVersion> tag to get the least installed version of WDK. And it is actually the only one thing need, because by default MSBuild will take the latest WDK, until you override WindowsTargetPlatformVersion property to select particular SDK+WDK pair,
Even if it is not compatible with installed Visual Studio version!
So for proper build you readlly should override WindowsTargetPlatformVersion property during MSBuild call.
The easiest way to get all installed WDK version is to read content of e.g.
C:\Program Files (x86)\Windows Kits\10\Include
Here is the DIR output
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        19.11.2022     11:34                10.0.17763.0
d-----        19.11.2022     11:25                10.0.18362.0
d-----        19.11.2022     11:25                wdf

As you can notice, WDK has version folder for each version SDK/WDK.


text:
Q: Store values into keys with scrapy I want to extract information from a website like price and store that as values in a dictionary. However, I'm trying to learn scrapy so I'd like to know how to achieve this with it.
Here's how it would look like with requests and BeautifulSoup
import numpy as np
import requests as r
import pandas as pd
from bs4 import BeauitfulSoup

html = ['https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=1&_sop=16',
       'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=2&_sop=16',
       'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=3&_sop=16',
       'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=4&_sop=16',
       'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=5&_sop=16']

data = defaultdict(list)
for i in range(0, len(html):
    r = requests.get(html[i])
    soup = BeautifulSoup(r.content, 'lxml')
    name = soup.select(".s-item__title")
    value = soup.select(".ITALIC")
    for n, v in zip(name, value):
        data["card"].append(n.text.strip())
        data["price"].append(v.text.strip())

Here's what I have tried with scrapy but I do not get any values after looking at the json output. I just get the links, how do I get the output like the code above?:
import scrapy
from scrapy.loader import ItemLoader
from scrapy.item import Field
from itemloaders.processors import TakeFirst
from scrapy.crawler import CrawlerProcess

html = np.array(['https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=1&_sop=16',
       'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=2&_sop=16',
       'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=3&_sop=16',
       'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=4&_sop=16',
       'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=5&_sop=16'],
      dtype=object)

url = pd.DataFrame(html, columns=['data'])

class StatisticsItem(scrapy.Item):
    statistics_div = Field(output_processor=TakeFirst())
    url = Field(output_processor=TakeFirst())

class StatisticsSpider(scrapy.Spider):
    name = 'statistics'
    start_urls = url.data.values

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(
                url
            )

    def parse(self, response):

        table = response.xpath("//div[@class='s-item__price']").get()

        loader = ItemLoader(StatisticsItem())
        loader.add_value('values', table)
        loader.add_value('url', response.url)
        yield loader.load_item()

process = CrawlerProcess(
    settings={
        'FEED_URI': 'ebay_data.json',
        'FEED_FORMAT': 'jsonlines'
    }
)
process.crawl(StatisticsSpider)
process.start()

A: I set the custom_settings to write to 'cards_info.json' with json format.
Inside parse I go through each card on the page (see xpath) and get the card's title and price, then I yield them. Scrapy will write them into 'cards_info.json'.
import scrapy
from scrapy.item import Field
from itemloaders.processors import TakeFirst

class StatisticsItem(scrapy.Item):
    statistics_div = Field(output_processor=TakeFirst())
    url = Field(output_processor=TakeFirst())

class StatisticsSpider(scrapy.Spider):
    name = 'statistics'
    start_urls = ['https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=1&_sop=16',
                     'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=2&_sop=16',
                     'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=3&_sop=16',
                     'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=4&_sop=16',
                     'https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=5&_sop=16']

    custom_settings = {
        'FEED_FORMAT': 'json',
        'FEED_URI': 'cards_info.json'
    }

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(
                url
            )

    def parse(self, response):
        all_cards = response.xpath('//div[@class="s-item__wrapper clearfix"]')
        for card in all_cards:
            name = card.xpath('.//h3/text()').get()
            price = card.xpath('.//span[@class="s-item__price"]//text()').get()
            # now do whatever you want, append to dictionary, yield as item.
            # example with yield:
            yield {
                'card': name,
                'price': price
            }

Output:
[scrapy.core.scraper] DEBUG: Scraped from <200 https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=1&_sop=16>
{'card': 'Pokemon 1st Edition Shadowless Base Set 11 Blister Booster Pack Lot - DM To Buy!', 'price': '£93,805.84'}
[scrapy.core.scraper] DEBUG: Scraped from <200 https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=1&_sop=16>
{'card': 'Pokemon Team Rocket Complete Complete 83/82, German, 1. Edition', 'price': '£102,026.04'}
[scrapy.core.scraper] DEBUG: Scraped from <200 https://www.ebay.co.uk/b/Collectable-Card-Games-Accessories/2536/bn_2316999?LH_PrefLoc=2&mag=1&rt=nc&_pgn=1&_sop=16>
{'card': 'Yugioh E Hero Pit Boss 2013 World Championship Prize Card BGS 9.5 Gem Mint', 'price': '£100,000.00'}
...
...

cards_info.json:
[
{"card": "1999 Pokemon Base Set Booster Box GREEN WING", "price": "\u00a340,000.00"},
{"card": "1996 MEDIA FACTORY POKEMON NO RARITY BASE SET CHARIZARD 006 BECKETT BGS MINT 9 ", "price": "\u00a339,999.99"},
{"card": "Yugioh - BGS8.5 Jump Festa Blue Eyes White Dragon -1999 - Limited - PSA", "price": "\u00a340,000.00"},
{"card": "PSA 8 CHARIZARD 1999 POKEMON 1ST EDITION THICK STAMP SHADOWLESS #4 HOLO NM-MINT", "price": "\u00a337,224.53"},
{"card": "PSA 9 MINT Pok\u00e9mon Play Promo 50000 PTS Gold Star Japanese Pokemon", "price": "\u00a338,261.06"},
...
...
]


text:
Q: Provide a proof or counterexample for the following statement: If $a, b$, and $c$ are nonzero integers and $a|bc$ $\rightarrow a|b$ or $a|c.$ Provide a proof or counterexample for the following statement: If $a, b$, and $c$ are nonzero integers and $a|bc$ $\rightarrow a|b$ or $a|c.$
I started off by solving for $a|b$ and $a|c$, but then got confused on how to deal with $a|bc$. Any helps or tips will be appreciated.

A: $a=8$, $b=4$, $c=6$ (so $bc=24$) is a counterexample; $8$ divides $24$ but not $4$ or $6$.


text:
Q: Why does $(e^{-\frac{3}{4}t}-e^{it})(\frac{3}{4}-i) = e^{-\frac{3}{4}t}-\cos t+ \frac{3}{4}\sin t$ I read this while going through some derivations in my mathematical physics class. I thought of multiplying everything and applying Euler's formula but I don't understand how the $ie^{-\frac{3}{4}t}$ could be turned into something real.
A little more context: this was after doing convolution with the Laplace transform and then doing something with real numbers to solve this deceptively easy-looking problem $y''+y'+\frac{3}{16}y(t) = \sin (t),\quad y(0) = y'(0) = 0$.

A: Your simplification is not correct. use $e^{it}=\cos t+ i\sin t$, then
$$(e^{-3t/4}-\cos t-i \sin t)(\frac{3}{4}-i)=\frac{3}{4} e^{-3t/4}-\frac{3}{4} \cos t- \frac{3i}{4}\sin t-i 3^{-3t/4}-i \cos t  -\sin t.$$


text:
Q: Feature importance by output for a predictive model I wanted to predict employee turnover for my company, so I used a dataset set with different factors (SALARY, SATISFACTION, DISTANCE FROM HOME, ETC...) and was able to get a prediction whether the employee will leave or not. I also made a feature importance plot for the whole model.
[enter image description here]

Here is what my results look like. Now I am trying to add feature importance by output. Basically, I wanna be able to see what top 3 factors impacted this employee to quit or will impact them to quit. So for each line with employee ID, I wanna be able to see the coefficients of the factors from highest to lowest. Can someone help with that?
Thanks.

A: The problem you are describing is probably answered by doing a Shapley Additive Explanations analysis.
I would recommend you to use the SHAP python library. I will leave the link for its documentation, but I'm sure some of its functions will do the trick.
SHAP Documentation


text:
Q: Implement VueJS with Laravel Blade? I have create a two different feed component with Laravel and vue js, the first one is pure using laravel controller and passing the data to view. Another one is using controller and passing to vue.js file.
But i trying to combine two together since is would be more user friendly for me which is fetching data into view and binding with vue button.
i had tried with this code but having error.Is there possible to do that?
@foreach($feeds as $feed)

                        user->avatar}}" class="avatar" alt="user profile image">

                            {{ $feed->user->name }}
                            made a post.

{{ $feed->created_at->diffForHumans() }}

{{ $feed->content }}

                        <like id="{{$feed->id}}"></like> <objection id="{{$feed->id}}"></objection>

                            12

                            3

@endforeach

But the problems is how to passing the id into my vue which is
<like :id="post.id"></like>
<objection :id="post.id"></objection>

Here is my Feed.vue file
<template>

                            {{ post.user.name }}
                            made a post.

{{ post.created_at }}

{{ post.content }}

                        <like :id="post.id"></like>
                        <objection :id="post.id"></objection>

                            12

                            3

                <comment :id="post.id"></comment>


text:
Q: If $A$ is compact then $f^{-1}(A)$ compact? Let $f$ be a continuous function. I know that if $A$ is compact then $f(A)$ is compact but is $f^{-1}(A)$ also compact?
I believe it is not but how can I prove it by a counter example?

A: Consider $f:\mathbb R\to\mathbb R $ defined by $f (x)=1$. The set $\{1\} $ is compact, but $f^{-1}(\{1\})=\mathbb R $ is not.


text:
Q: Diffeomorphism in a group action Considering the group action: $\Omega = \{ \mathbb{Z},+  \}$ on $E = \mathbb{R}^2$ and:
$$ \omega \cdot (x,y)=(x+ \omega, (-1)^{\omega} y)$$
knowing that it is a free and proper action, how can we show that $ \mathbb{R}^2\ / \Omega$ is diffeomorphic to the quocient of $S^1 \times \mathbb{R}$ by the action of the group with two elements given by the antipode transformation:
$$ (x,y) \longrightarrow (-x,-y)$$
and what is the manifold we obtain?
EDIT:
Writting the following diagram:

how can I justify that $\alpha$ is a diffeomorfism? If it is, then by a covering I can get to $S^1/\{+1,-1\}$ correct?

A: First, we note that the quotient of $\mathbb{R}^2$ by the subgroup of even numbers is $S^1 \times \mathbb{R}.$ The we are left with the $\mathbb{Z}/2 \mathbb{Z}$ action, which is easily seen to be the antipode action. You should be able to figure out which manifold is obtaied.


text:
Q: Cannot deploy jar file with ejb to glassfish 3.1.1 I've tryed to deploy resulting jar file from
First example of ejb from Enterprise JavaBeans 3.1, 6th Edition by Andrew Lee Rubinger, Bill Burke
to glassfish 3.1.1 and got the following exception:

Caused by: java.lang.IllegalStateException: Method 'public abstract int org.jboss.ejb3.examples.ch04.firstejb.CalculatorCommonBusiness.add(int[])' must throw at least one exception of type java.rmi.RemoteException or one of its super-classes
      at com.sun.corba.ee.impl.presentation.rmi.IDLNameTranslatorImpl.(IDLNameTranslatorImpl.java:232)
      at com.sun.corba.ee.impl.presentation.rmi.IDLNameTranslatorImpl.(IDLNameTranslatorImpl.java:65)
      at com.sun.corba.ee.impl.presentation.rmi.IDLNameTranslatorImpl$2.run(IDLNameTranslatorImpl.java:169)
      at com.sun.corba.ee.impl.presentation.rmi.IDLNameTranslatorImpl$2.run(IDLNameTranslatorImpl.java:167)
      at java.security.AccessController.doPrivileged(Native Method)
      at com.sun.corba.ee.impl.presentation.rmi.IDLNameTranslatorImpl.get(IDLNameTranslatorImpl.java:166)
      at com.sun.corba.ee.impl.presentation.rmi.PresentationManagerImpl$ClassDataImpl.(PresentationManagerImpl.java:153)
      at com.sun.corba.ee.impl.presentation.rmi.PresentationManagerImpl$1.lookup(PresentationManagerImpl.java:103)
      at com.sun.corba.ee.impl.presentation.rmi.PresentationManagerImpl$1.lookup(PresentationManagerImpl.java:100)
      at com.sun.corba.ee.spi.orbutil.misc.WeakCache.get(WeakCache.java:114)
      at com.sun.corba.ee.impl.presentation.rmi.PresentationManagerImpl.getClassData(PresentationManagerImpl.java:131)
      at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.setTarget(ReflectiveTie.java:101)
      at org.glassfish.enterprise.iiop.impl.POAProtocolMgr.validateTargetObjectInterfaces(POAProtocolMgr.java:315)
      at com.sun.ejb.containers.BaseContainer.initializeHome(BaseContainer.java:1248)
      at com.sun.ejb.containers.StatelessSessionContainer.initializeHome(StatelessSessionContainer.java:202)
      at com.sun.ejb.containers.ContainerFactoryImpl.createContainer(ContainerFactoryImpl.java:167)
      at org.glassfish.ejb.startup.EjbApplication.loadContainers(EjbApplication.java:230)
      ... 55 more
  Caused by: com.sun.corba.ee.impl.presentation.rmi.IDLTypeException: Method 'public abstract int org.jboss.ejb3.examples.ch04.firstejb.CalculatorCommonBusiness.add(int[])' must throw at least one exception of type java.rmi.RemoteException or one of its super-classes
      at com.sun.corba.ee.impl.presentation.rmi.IDLTypesUtil.validateExceptions(IDLTypesUtil.java:476)
      at com.sun.corba.ee.impl.presentation.rmi.IDLTypesUtil.validateRemoteInterface(IDLTypesUtil.java:100)
      at com.sun.corba.ee.impl.presentation.rmi.IDLNameTranslatorImpl.(IDLNameTranslatorImpl.java:226)
      ... 71 more
  |#]

But CommonBusiness is just an interface why it must throw any exceptions?!
Resulting jar contains only annotated beans and no ejb-jar.xml or some glassfish specific xml files (but as I understand javaee6 don't require any ejb-jar.xml nor server specific files...)
This jar was successfully deployed to JBoss AS7 so I don't know where to dig...

A: I cannot navigate from pages to pages for a single source code.
But you must throw a RemoteException for that method

A: I also trigger the problem using arquillian-glassfish-managed-3.1 and has sent into glassfish ejb leader.
However, I need to confirm the issue using other ways to judge whether being caused by glassfish or arquillian.


text:
Q: Google Sheets: "Text to Columns", but in single column? I have a huge data file.  Each line may contain one or more entries separated by a pipe:
one|two|three
alpha
uno|dos
beta
gamma

I can use "Text to Columns" to remove the | and put each entry in its own column:
one     two     three
alpha
uno     dos
beta
gamma

But my desired result is to have all items in a single column:
one
alpha
uno
beta
gamma
two
three
dos

How can I easily get all entries into a single column?  (order does NOT matter)

A: try:
=ARRAYFORMULA(QUERY(FLATTEN(IFERROR(SPLIT(FLATTEN(A:Z), "|"))), "where Col1 is not null"))

A: Assume Range A1:A5 is your data
=TRANSPOSE(SPLIT(JOIN("|",A1:A5),"|"))

JOIN them to add "|" to all of them first
then SPLIT text that has "|" to be 1 row, many columns
then TRANSPOSE to get just one column going

This is the basic one I can think of, anyways there are a lot of ways to do this


text:
Q: highlighting uitextview shows inputAccessoryView I have two textviews as subviews of a UITableView with an inputAccessoryView, one that is non editable but I'd still like to allow people to highlight and use (copy | define) on and another one that's inside the inputAccessoryView.
The problem is when highlighting the non editable textView, the input accessory view appears... (why!?) as though the tableView has suddenly become the first responder, I'm guessing because one of it's subviews has become first responder. The question is, do I need to take this non editable textView out of the tableViews subviews or is there some way to suppress the inputAccessoryView popping up when it's highlighted? The latter would be preferred.
-(UITextView *)textView
{
    if (!_textView) {

        _textView = [[UITextView alloc]initWithFrame:CGRectZero];
        //_textView.delegate = self;
        _textView.font = [UIFont questionDemiBoldFontOfSize:36.0f];
        _textView.backgroundColor = [UIColor clearColor];
        _textView.editable = NO;
        _textView.scrollEnabled = NO;
        _textView.textColor = [UIColor whiteColor];
        _textView.tintColor = [UIColor whiteColor];
        _textView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin;

    }

    return _textView;
}

A: This worked for me in a UITextView subclass. Swift 4
override func becomeFirstResponder() -> Bool {
    guard isEditable else { return false }
    return super.becomeFirstResponder()
}

A: I fixed this by adding
- (UIView *)inputAccessoryView
{
    if (self.textView.isFirstResponder)
        return nil;

    return self.accessoryView;
}

note
Obviously in some cases you may have to manually call resignFirstResponder on the non editing textView first before getting your accessoryView back.. still, it's fairly clean and might help someone in the future.


text:
Q: Material on Android 4.4 I am developing my app with Android Studio 2.3.3 and any element is in material design on Android 7 but if run application on Android 4.4 element change position and style.

Run on 7.1.1

Run on 4.4

I know that Android 4 does not support the Material design except with third-party items but I would like to understand why the position changes.
Any idea or fix?
<?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:gravity="center"
        tools:context="com.scannerproject.MainActivity"
        android:layout_weight="1"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="0dp">

 <Button
        android:id="@+id/button"
        android:layout_width="243dp"
        android:layout_height="47dp"
        android:background="@color/colorPrimary"
        android:onClick="scan"
        android:text="SCANSIONE"
        android:textColor="#fff"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.504"
        android:layout_marginBottom="8dp"
        app:layout_constraintVertical_bias="0.457" />

    <Switch
            android:id="@+id/flash"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Attiva Flash"
            android:layout_marginRight="8dp"
            app:layout_constraintRight_toRightOf="@+id/button"
            android:layout_marginLeft="8dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_marginTop="8dp"
            app:layout_constraintBottom_toBottomOf="parent"
            android:layout_marginBottom="8dp"
            app:layout_constraintVertical_bias="0.555" />

    </android.support.constraint.ConstraintLayout>

A: Little fix, point the right toggle with the right button


text:
Q: User should not be able to select past month/year as expiry date Hi am using SRmonthpicker for selection of date as per my requirement. I want to disable previous month/year selection. i.e if current month is june then previous months shold be disabled

Please Help,
Thanks in advance


text:
Q: smallest "scrabble board" containing every word of a list I am looking for an algorithm able to build an array (2D) of letters from which I could extract each word of a given list.
Like in Scrabble, words can cross each other, and be horizontal, vertical or diagonal. Of course there are some obvious solutions, but the goal here is to make it as small as possible, which also means maximizing the number of crossing.
I have thought of a machine learning method using a large set of scrabble grids, either made by humans or computers, but I am sure there is a cleaner way of doing it.
Thanks for your help.
PS: that is for an art project, no kidding.

A: That would be quite some algorithm.  I suspect the solution will involve some sort of recursion.
Let's say you have a grid G0 to start with, with all squares blank, and that f(G0) is the optimised completed grid.
Then I would try:
For each possible position of the first word
- set G1 = the grid with this word in this position and all other squares blank
- work out G1
Go on to next position
To work out G1, you could call f(G1) recursively.
If you had a large grid and a lot of words, this would take forever to run, as it's a wasteful algorithm, but with a typical Scrabble board I should think it would be quick enough on a laptop.


text:
Q: Automatically running a function inside an object when that object is called I am building a text based choice RPG game using Javascript. I am able to add functions inside of an object and run them, however, I want the function to run if the option ( text node ) is chosen.
Currently, I declare a function, and then call it at the bottom of the page. The issue is, I want to function to run as soon as the choice is chosen.
Here is the code I have so far...

function addRadiatedStatus(){
    character.radiated = true;
}

const textNodes = [
    {
        id: 1,
        text: "Do you want to help this person?",
        options: [
           {
            text: "Yes",
            nextText: 2
           },
           {
            text: "No",
            nextText: 2
           },
        ],
        faction: "Greaser"
    },
    {
        id: 2,
        text: "It was a trap, do you run or kill them?",
        options: [
           {
            text: "Run",
            nextText: 3,
            damage: 0,
           },
           {
            text: "Kill",
            nextText: 5,
            damage: 8,
            moneyDrop: 20,
            radiationDamage: 2,
            function: function update(){
            if(character.greaser == true && textNodes[1].faction ==
            "greaser"){
                console.log("greaser check worked");
            }
                console.log("upadte function worked")
            character.health -= this.damage;
            character.cash += this.moneyDrop;
            character.radiationLevel += this.radiationDamage;
            character.maxHP -= this.radiationDamage;
            if(this.radiationDamage >= 1 ){
                addRadiatedStatus();
            }
            console.log("character HP" + " " +  character.health);
            console.log("character maxHP" + " " +  character.maxHP);
            console.log("moneyDrop " + " " +  this.moneyDrop);
            console.log("character cash" + " " +  character.cash);
            console.log("radiation level" + " " +  character.radiationLevel);
            console.log("character Raditated?" + " " +  character.radiated);

            }
           }
        ],
        faction: "Greaser",
    }
]

textNodes[1].options[1].function();

I tried a few different things, including adding another key run: update() , run: this.update(), run: this.function, etc.
I am also a little confused because I thought that ES6 allows me to remove the function keyword, but that doesn't seem to be allowed ( I am probably just doing it wrong, or running into an issue based on how I set up my object ).
I am not sure how to go from calling textNodes[1].options[1].function to dynamically calling whichever function is nested within a specific choice option.
Thanks in advance for the help.

A: You can change this section to this:
update: (function(){
        console.log("upadte function worked")
        character.health -= this.damage;
        character.cash += this.moneyDrop;
        character.radiationLevel += this.radiationDamage;
        character.maxHP -= this.radiationDamage;
        if(this.radiationDamage >= 1 ){
            addRadiatedStatus();
        }
        console.log("character HP" + " " +  character.health);
        console.log("character maxHP" + " " +  character.maxHP);
        console.log("moneyDrop " + " " +  this.moneyDrop);
        console.log("character cash" + " " +  character.cash);
        console.log("radiation level" + " " +  character.radiationLevel);
        console.log("character Raditated?" + " " +  character.radiated);
    });

The function keyword has been changed to update, then the function has been changed to an anonymous function ... You should refrain from using js keywords for your user-defined ones.
Then the anonymous function will not execute until you call it:
textNodes[1].options[1].update()

Here's an example of what I'm talking about:
This shows that you have to actually access the function and any other key for that matter for you to access the values.

var text = [
    {
          data1: "here",
       data2: (function(){
          return "You have to explicitly call me!"
   })
    }
]
console.log("Without calling any data:   " + text[0])
console.log("When you call data2:   " + text[0].data2())
console.log("Let us access data1:   " + text[0].data1)


text:
Q: TransactionTooLargeException from Samsung's SmartClip service crashing my app - can it be intercepted? Android Samsung phones have a SmartClip service that is invoked when a screenshot is taken. It launches an interface to immediately allow the screenshot to be edited.
My app will often crash when this action is performed, specifically when a large number of objects are drawn on the screen. This is a Xamarin.Forms app.
When the crash occurs, two threads are reported as responsible, with the following stack traces:
android.os.BinderProxy.transactNative BinderProxy.java
android.os.BinderProxy.transact BinderProxy.java:605
com.samsung.android.content.smartclip.ISpenGestureService$Stub$Proxy.sendSmartClipRemoteRequestResult ISpenGestureService.java:910
com.samsung.android.content.smartclip.SpenGestureManager.sendSmartClipRemoteRequestResult SpenGestureManager.java:77
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.sendResult SmartClipRemoteRequestDispatcher.java:654
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.dispatchScrollableAreaInfo SmartClipRemoteRequestDispatcher.java:313
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.access$100 SmartClipRemoteRequestDispatcher.java:59
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher$2.run SmartClipRemoteRequestDispatcher.java:154
android.os.Handler.handleCallback Handler.java:938
android.os.Handler.dispatchMessage Handler.java:99
android.os.Looper.loop Looper.java:246
android.app.ActivityThread.main ActivityThread.java:8512
java.lang.reflect.Method.invoke Method.java
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run RuntimeInit.java:602
com.android.internal.os.ZygoteInit.main ZygoteInit.java:1130

com.samsung.android.content.smartclip.SpenGestureManager.sendSmartClipRemoteRequestResult SpenGestureManager.java:81
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.sendResult SmartClipRemoteRequestDispatcher.java:654
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.dispatchScrollableAreaInfo SmartClipRemoteRequestDispatcher.java:313
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher.access$100 SmartClipRemoteRequestDispatcher.java:59
com.samsung.android.content.smartclip.SmartClipRemoteRequestDispatcher$2.run SmartClipRemoteRequestDispatcher.java:154
android.os.Handler.handleCallback Handler.java:938
android.os.Handler.dispatchMessage Handler.java:99
android.os.Looper.loop Looper.java:246
android.app.ActivityThread.main ActivityThread.java:8512
java.lang.reflect.Method.invoke Method.java
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run RuntimeInit.java:602
com.android.internal.os.ZygoteInit.main ZygoteInit.java:1130

So... what do I do? This is a crash originating in third party code that I'm not including myself. Is there a hook somewhere that I can prevent this action from executing, or to handle the exception without crashing my app?
The only other solution would be to reduce the number of objects displayed so it comes under the 1 Mb limit, but I'd like to avoid that.
EDIT to add: Unfortunately, it looks like UnhandledException handling is not going to suffice, it was only meant for logging information about the crash.

A: Thanks to @ToolmakerSteve I have a workaround.
I used the information in the links to detect this exception and restart the activity:
# in MainApplication.cs
private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if ((e.ExceptionObject as RuntimeException)?.InnerException is TransactionTooLargeException)
            {
                Intent intent = new Intent(ApplicationContext, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.NewTask);
                StartActivity(intent);
            }
        }
    }

Trying to do any state-saving action in this method fails. You have to rely on state that's saved prior to the crash. Luckily I already had such a mechanism.
So I just needed to detect a crash on startup (I used AppCenter's Crashes.HasCrashedInLastSessionAsync() and run my state-restoring method. Though for some reason I could only run this check after populating MainPage. Doing it before risked a blank screen.
In addition to this, I implemented limits on the number of objects drawn on the screen, so that the crash happens less frequently.
This isn't the best answer because it would be better to stop the third party code from crashing apps, but I hope it helps someone else.


text:
Q: Javascript- fixed header on scroll using Materialize, small jump I have followed this tutorial on W3schools to create a fixed header on scroll. So the navbar starts at the bottom of the page, and upon scrolling once the navbar reaches the top of the page, it sticks there.
W3Schools How to Create a Fixed Header on scroll
I successfully implemented these instructions from W3schools with the Materialize side navigation menu, meant to be used with the Materialize Scrollspy effect. It is working great so far except for two issues I can't seem to figure out.

*

*Once the navigation menu reaches the top of the screen and it transitions to being sticky, there is a very small jump in it's position. I have altered some settings, but I can't seem to stop that jump. Why is it happening and how can I make it appear smooth?

*When I use Scrollspy to scroll to a different section of the site, and then refresh the page, the side navigation menu disappears until I start scrolling the page again. I am using  window.onscroll, so I am guessing that is why it's happening. But I notice it does not happen with the W3Schools example, so I'm wondering if I have something set up wrong?
Here is a link to my portfolio website where I'm having these issues:
My portfolio website.
Here is the code:

// execute navFunction on scroll
window.onscroll = function(){navFunction()};

// get navbar
const navBar = document.getElementById("contents-wrapper");

// get offset position of navbar
const sticky = navBar.offsetTop;

// reach scroll position - add sticky, leave scroll position - remove sticky
function navFunction() {
  if (window.pageYOffset >= sticky) {
    navBar.classList.add("sticky")
  } else {
    navBar.classList.remove("sticky");
  }
}
#contents-wrapper {
  overflow: hidden;
  float: right;
}

.sticky {
  position: fixed;
  top: 0;
  left: 77.5%;
  width: 100%;
}

.sticky + .content {
  padding-top: 60px;
}

I'm Jennifer Faye

A full stack web developer with an eye for design.

I am passionate about developing well designed websites; both aesthetically,
                        and with attention to user experience and mobile responsiveness.

Home

About

Projects

Skills

Contact

Resume

A: I solved the problem of the little jump. I had float it to the left instead of to the right, then I made the grid l1 instead of l2. Works perfectly now. I'm still trying to figure out the other issue though.

A: Adding this seems to have solved my second issue:
$(document).ready(function(){
$(this).scrollTop(0);
});


text:
Q: Subset multi-indexed DataFrame based on multiple level 1 columns I have a multi=indexed DataFrame, but I want to keep only two columns per level 1, for each of the level 0 variables (i.e. columns 'one' and 'two'). I can subset them separately, but I would like to do it together so I can keep the values side by side
Here is the DataFrame
index = pd.MultiIndex.from_tuples(list(zip(*[['bar1', 'foo1', 'bar1', 'foo2','bar3','foo3'], ['one','two','three','two','one','four']])))
df = pd.DataFrame(np.random.randn(2, 6), columns=index)

Here is the way to subset for one column in level 1
df.iloc[:, df.columns.get_level_values(1)== 'one']
# or
df.xs('one', level=1, axis=1)

# but adding two columns within either command will not work e.g.
df.xs(('one','two), level=1, axis=1)

This would be the expected output
         bar1        foo1       foo2         bar3
          one         two        two          one
0   -0.508272   -0.195379   0.865563     2.002205
1   -0.771565    1.360479   1.900931    -1.589277

A: We can use Index.isin on a specific level to create a Boolean index and select with loc:
df.loc[:, df.columns.isin(['one', 'two'], level=1)]

df:
       bar1      foo1      foo2      bar3
        one       two       two       one
0  0.042062 -0.233098  0.620974  0.330957
1  0.524495 -0.394930  0.572631  0.499279

A: You can reindex and specify the level.
df.reindex(['one', 'two'], axis=1, level=1)

       bar1      foo1      foo2      bar3
        one       two       two       one
0  0.276056  1.956400 -1.495128  1.582220
1 -0.383178  1.159138 -1.646173  0.821942

A: Check the old fashion get_level_values
out = df.loc[:,df.columns.get_level_values(1).isin(['one','two'])]
Out[454]:
       bar1      foo1      foo2      bar3
        one       two       two       one
0 -0.705540 -1.175132 -0.572076 -1.549703
1  0.277905  1.789925  1.104225  0.104453

A: Here's one way using pd.IndexSlice:
idnx = pd.IndexSlice[:, ['one', 'two']]
df.loc[:, idnx]

Output:
       bar1      bar3      foo1      foo2
        one       one       two       two
0  0.589999  0.261224 -0.106588 -2.309628
1  0.646201 -0.491110  0.430724  1.027424

Another way using a little known argument, axis, of pd.DataFrame.loc:
df.loc(axis=1)[:, ['one', 'two']]

Output:
       bar1      bar3      foo1      foo2
        one       one       two       two
0  0.589999  0.261224 -0.106588 -2.309628
1  0.646201 -0.491110  0.430724  1.027424

NOTE: This argument is not listed in the documented API for pd.DataFrame.loc, but is referenced in the User Guide in MultiIndex / Advanced indexing section in the Using Slicers paragraph about middle way down with an example.


text:
Q: How to debug a DO_NOTHING_ON_CLOSE failure? In a swing application I have, as I understand it, told the mainFrame of my application to DO_NOTHING_ON_CLOSE.
public SurveyView(SingleFrameApplication app) throws FileNotFoundException, IOException {
        super(app);

        initComponents();

        JFrame mainFrame = SurveyApp.getApplication().getMainFrame();
        mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        //And on and on it goes...
}

Obviously I'll be adding a window listener and what not to dress it up later, but for now, I just need the window to not close when the X is clicked.  But the window DOES close.
It seems so simple of an operation that I can't even think of how to go about debugging it.  Am I missing something SUPER obvious?
Edit: And here is the getApplication method within the SurveyApp class:
public static SurveyApp getApplication() {
        return Application.getInstance(SurveyApp.class);
    }

Edit2: Since HoverCraft suggests that mainFrame is not the culprit, maybe an overview of the app structure will point us in the right direction.  The entire app is contained in a single JPanel, mainPanel.  The panel, in turn, is contained inside public class SurveyView extends FrameView.  All of my compenents are added to the panel, which is a card layout which cycles through a few various other JPanels.  As I understand it, the close operations are reserved for frames, not for views or panels.  Hence why my first thought was to target the main frame of the app.
I know the main frame DOES exist.  I tried System.out.println(SurveyApp.getApplication().getMainFrame()) and it output this monster(linebreaks for readability):
javax.swing.JFrame[mainFrame,0,0,0x0,invalid,hidden,
layout=java.awt.BorderLayout,title=Accounting Survey,
resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,
rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,
layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,
alignmentY=0.0,border=,flags=16777673,maximumSize=,minimumSize=,preferredSize=],
rootPaneCheckingEnabled=true]

And I noticed the title is, in fact, the title that displays in the title bar of my app.  But then I saw the DO_NOTHING_ON_CLOSE was set, as it should be, but the app still closed, meaning, I think, Hovercraft is right - this isn't the right target.
Edit3: Further research shows that, indeed, netbeans constructs each panel and adds it to mainPanel and once all panels have been added it calls setComponent(mainPanel);, which I'm assuming is established somewhere else, but a Ctrl-F of the entire program turns up nothing.  Does anyone with more experience with netbeans know where all of these methods it uses are defined?  If I could find THAT I might be able to figure out what frame needs the no-close set.
Edit4: Alright I think I'm close.  The mainPanel is set as the component of the FrameView, which seems to be the wrapper created by a java SingleFrameApplication.  I did some reading here: http://bellquel.bo.cnr.it/appframework/org/jdesktop/application/SingleFrameApplication.html and it looks like I was actually correct: the frame created by a SFA is named mainFrame and, according to the docs, "getMainFrame() Returns the JFrame used to show this application."  Meaning I AM targetting the right JFrame, and based on my earlier test, the default close operation IS in fact being set to do nothing.  So what gives?  I'm targetting the correct frame, it is setting the operation correctly, and then it is just being ignored?  What could override the default close operation like that?

A:
I just need the window to not close when the X is clicked. But the window DOES close.

Try this simple code
EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

            frame.addWindowListener(new WindowAdapter() {

                @Override
                public void windowClosing(WindowEvent we) {
                    System.out.println("closing...");
                }

                @Override
                public void windowClosed(WindowEvent we) {
                    System.out.println("closed..");
                }
            });

            frame.setVisible(true);
        }
 }

output (when the X is clicked)
closing...


text:
Q: Android EditText How to disable automatic insertion of spaces when pasting text? Sometimes, when pasting text in an EditText, blanks/spaces are automatically inserted. For example, this happens if text is pasted into the middle or at the end of text that is already contained in the text field. Is there a way to tell the EditText object or the ClipboardManager that leading and trailing blanks should not automatically be inserted?

A: use trim(); it will remove blanks from before and after a string
str = str.trim();

A: This is a Android bug. Check this issue report.
It fixed in 5.

A: I was needed prevent "space" before do work with InputFilter, so I use that:
    mSearchText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            MyLog.d(this, keyEvent);
            if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_SPACE) {
                switch (keyEvent.getAction()) {
                    case KeyEvent.ACTION_DOWN:
                        mSpacePressed = true;
                        break;
                    case KeyEvent.ACTION_UP:
                        mSpacePressed = false;
                }
            }
            return false;
        }
    });

    InputFilter mSearchFilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence arg0, int arg1, int arg2, Spanned arg3, int arg4, int arg5)
        {
            //Prevent adding spaces on Paste
            //Remember: if you want paste " " it will be prevented
            if (arg0.toString().equals(" ")){
                if (!mSpacePressed){
                    return "";
                }
            }

            //do work with filter

            return null;
        }
    };
    mSearchText.setFilters(new InputFilter[]{mSearchFilter});

A: I'm late but in my old tablet, my EditText also works like you said.
So, I fixed it like below.
1.Create a class to store the information about the start index and the length of inserted string.
public class PasteUnit {
    int start = 0;
    int length = 0;

    public PasteUnit(int start, int length) {
        this.start = start;
        this.length = length;
    }
}

2.Create a class that extends EditText.
public class MyEditText extends EditText
{
    boolean pasteStarted = false;
    ArrayList<PasteUnit> pasteUnits = new ArrayList<>();

    public MyEditText(Context context)
    {
        super(context);
    }

    public MyEditText(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTextContextMenuItem(int id) {
        if(id==android.R.id.paste) {//This is called when the paste is triggered
            pasteStarted = true;
        }

        boolean consumed = super.onTextContextMenuItem(id);
        //the super.onTextContextMenuItem(id) processes the pasted string.
        //This is where EditText acts weird.
        //And we can watch what is happening in our TextWatcher to be added below

        switch (id){
            case android.R.id.paste://This is called after we collected all the information

                if(pasteUnits.size()>1) {//When a space or spaces are inserted
                    int startIndex = pasteUnits.get(0).start;
                    int totalLength = 0;
                    for(int i=0;i<pasteUnits.size();i++) {
                        PasteUnit pasteUnit = pasteUnits.get(i);
                        totalLength = totalLength + pasteUnit.length;
                    }
                    int endIndex = startIndex + totalLength;

                    String string = this.getText().toString();
                    String before = string.substring(0, startIndex);
                    String after = string.substring(endIndex);

                    PasteUnit lastPasteUnit = pasteUnits.get(pasteUnits.size()-1);
                    String lastString = string.substring(lastPasteUnit.start, lastPasteUnit.start + lastPasteUnit.length);

                    String result = before + lastString + after;
                    this.setText(result);
                    this.setSelection(startIndex + lastString.length());
                }
                pasteUnits.clear();
                pasteStarted = false;
                break;
            case android.R.id.copy:
                break;
            case android.R.id.cut:
                break;
        }
        return consumed;
    }
}

3.Add TextWatcher to your EditText.
The old EditText acts really weird seeing the TextWatcher. When you paste string A into string B, it first inserts a space into string B, and it inserts another space into string B, and last it inserts string A between the two spaces.
And in other situations like pasting string A after string B, it first appends a space after string B and after that appends string A.
So anyway it seems to insert the original string at the last step.
   MyEditText edit = (MyEditText) findViewById(R.id.mainEditText1);

   edit.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if(edit.pasteStarted) {//when it is processing what we pasted
                    edit.pasteUnits.add(new PasteUnit(start, count));
                   //store the information about the inserted spaces and the original pasted string
                }
            }
        });


text:
Q: Sort pandas DataFrame rows by a list of (index) numbers I have a pandas DataFrame with 229 rows.  I have a list of index numbers ([47, 16, 59, ...]) and I want to re-sort the rows of my DataFrame into this order.
Details: I ran the DF through a filter (specifically, scipy.cluster.hierarchy.dendrogram, setting get_leaves=True). The return value includes a list of index numbers (leaves) in order of the dendrogram leaf nodes. I now want to sort my DF in that order, so that I can plot the clusters.
I'm sure there are many ways that I can merge a bunch of tables and drop columns but... is there a nice idiomatic way to do this?

A: Creating a new column, mapping your indexes to the correct rows and then performing a sort should be the easiest way to do this.
I created some dummy data to provide an example;
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

df
     A   B   C   D
0    8  27   2   9
1   87  17  82  61
2   20  65  42  87
3    6  60  99  22
4    1  54  57  32

indices = [random.randrange(99) for i in range(99)]
#[54, 37, 83, 25, 44, 68, 81, 72, 61, 74, 10, 75, 24, 77, 89, 6, 59, 95, 44, 20, 72, 0, 53, 6, 61, 17, 52, 7, 95, 4, 64, 15, 46, 18, 58, 30, 3, 7, 94, 30, 93, 78, 24, 98, 65, 63, 79, 1, 43, 17, 76, 65, 85, 88, 66, 86, 10, 96, 27, 85, 66, 48, 2, 83, 25, 11, 88, 41, 88, 10, 15, 19, 75, 6, 72, 39, 28, 18, 78, 22, 71, 28, 97, 76, 47, 38, 9, 91, 69, 27, 63, 43, 19, 38, 80, 16, 35, 20, 65]

Code:
df['NewIndex'] = None # Create new column, with only None values

for indx, value in enumerate(indices):
    df['NewIndex'][value] = indx # Set index (List element number) to indx (Order in indices list)

df = df.sort_values(by=['NewIndex']) # Sort by new column

Output:
         A   B   C   D NewIndex
54  69  73  81  31        0
37  54  97  45  31        1
68  27  56  86  50        5
81  60   8  20  29        6
74  95  54  45  59        9
..  ..  ..  ..  ..      ...
84   9  67  88  38     None
87  47   9  97   2     None
90  38   6  98  50     None
92  57  51  84  37     None
99  12  88  38  90     None

Note, the nones and the missing rows will be due to mismatches in the indices and dataframe indexes. I did not take the time to ensure indices had 1-99 and no duplicates.

A: if the list is the same shape as df then just paste it in like so and sort by newly created column
df['List']=ListOfIndices
df.sort_values(by=['List'])

A: df.loc[ListOfIndices]

And if you want to reset the indeces:
df.loc[ListOfIndices].reset_index(drop=True)


text:
Q: Problem with uploading files to firebase storage through firebase function I am currently using firebase function to do video compression, the file is first downloaded from the firebase storage, then through fluent ffmpeg, compress the file. Then, the video is re-uploaded to the firebase storage.
However, the firebase function console shows that there is a error in ffmpeg:
 An error occurred: ffmpeg exited with code 1: compressed-Scooter- One (Always Hardcore).mp3: Read-only file system

But the firebase storage rules is set to read and write:
 service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

My code: https://github.com/MobileProjectTPC/VideoCompressor/blob/master/functions/index.js
The upper part is my own code, while the lower part is the testing code from Can you call out to FFMPEG in a Firebase Cloud Function with some changes.
So, I don't understand why the ffmpeg function wasn't able to convert the file. Do any one know why this keeps happening and how to fix it?
Also, the output of the functions for my code is as follows:

While their code is as follows:

As you can see for my code, the error shows up after the output of function finished. While for their code, there isn't any error at all but no compressed file in firebase.
Does this means the fluent-ffmpeg function wasn't even ran at all for their code?
Thank You.


text:
Q: Mylar capacitor and Electrolytic capacitor Is it a bad practice to use Mylar capacitor and electrolytic capacitor in the same circuit? If so why?

A: Frequently polyester (Mylar) and electrolytic capacitors are used in the same circuit, usually for different purposes.
Electrolytic capacitors are usually used for power supply filtering, sometimes for coupling and filtering. They are available in compact form with large capacitance such as 1000uF/16V for pennies. A polyester capacitor of that value would be huge and expensive.
Polyester capacitors are used for high frequency filters, for AC snubbers and for audio and some RF circuits. They are usually very low leakage and have moderate dielectric absorption and temperature stability. Lately they are often replaced by ceramic multilayer parts, which have different characteristics again.
At higher frequencies, ceramic parts are used more often.


text:
Q: Creating new command in .sty file for LaTeX Beamer I have a beamer theme in a .sty file, and I want to make a command \supervisor that works like \author.
In the .sty file, I added the following:
\newcommand{\supervisor}[1]{#1}

\newcommand{\insertsupervisor}{\supervisor}

But in the main file, when I declare \supervisor{Someone}, before \begin{document}, just like \author and \title etc, I get the error "Missing: begin document". The text then appears at the top of the titlepage, without the fontsize and colour that I assigned to supervisor.
How should I correctly declare this command such that it works like author for example? (I cannot find how \author is actually defined for beamer).

A: The trick is to define a new command \insertsupervisor inside \supervisor
\documentclass{article}

\newcommand{\supervisor}[1]{\gdef\insertsupervisor{#1}}

\supervisor{Foo bar}

\begin{document}

    \insertsupervisor

\end{document}


text:
Q: How to link configmap to external file? With this we can create a configmap linked to external file.
kubectl create configmap database-config --from-file=database.properties

But when we edit the yaml, it will show that complete content of file is dumped there.
Is there anyway to just point to a file in yaml also so that I will keep the properties file in the same folder as the configmap yaml and appy the folder all the yamls with:
kubectl apply -f target_folder\

Please suggest.

A: What configmap is

A ConfigMap is an API object used to store non-confidential data in
key-value pairs. Pods can consume ConfigMaps as environment variables,
command-line arguments, or as configuration files in a volume.
A ConfigMap allows you to decouple environment-specific configuration
from your container images, so that your applications are easily
portable.

In other words when configmap is created from external file (like your case) or from other values, API server will validate if everything is correct and then will save it to etcd. This also explains reasons why when you edit your configmap you see its entire context. This happens because configmap is read from etcd, not any external sources.
This is also one of the reasons why it's not recommended to store save big files as configmaps or secrets - it will affect kubernetes cluster performance as all cluster's objects are stored within etcd.
Kustomize
This is one of the way to achieve your requirement to run one command on creating/configuring configmap based on the file in the same directory.
It is a standalone tool to customize Kubernetes objects through a kustomization file.
I created a short and simple example to show the idea:
$ tree
.
├── application.properties
└── kustomization.yaml
0 directories, 2 files

$ cat kustomization.yaml
generatorOptions:
  disableNameSuffixHash: true # this flag is used to avoid creation of new configmap, instead it will be modified when file context is changed
configMapGenerator:
- name: application-config
  files:
  - application.properties

$ cat application.properties
listen.url=localhost:9010
client.url=some_url:3000

Test this, this command will only render configmap, it won't create it yet:
$ kubectl kustomize application.settings/
apiVersion: v1
data:
  application.properties: |
    listen.url=localhost:9010
    client.url=some_url:3000
kind: ConfigMap
metadata:
  name: application-config

Final step is to apply it:
$ kubectl apply -k application.settings/
configmap/application-config created

$ kubectl get cm
NAME                 DATA   AGE
application-config   1      23s

Short explanation to command above:

To apply those Resources, run kubectl apply with --kustomize or -k
flag.

Useful links:

*

*configmap - official kubernetes documentation

*Declarative Management of Kubernetes Objects Using Kustomize

*etcd


text:
Q: Get the Product Count on Category with only In-Stock Status How to get the product count in a certain category with the product status of in-stock only?

A: Try this:
$collection = Mage::getResourceModel('catalog/product_collection');

$cond = array(
    '{{table}}.use_config_manage_stock = 0 AND {{table}}.manage_stock=1 AND {{table}}.is_in_stock=1',
    '{{table}}.use_config_manage_stock = 0 AND {{table}}.manage_stock=0',
);

    $cond[] = '{{table}}.use_config_manage_stock = 1 AND {{table}}.is_in_stock=1';

$collection->joinField(
    'inventory_in_stock',
    'cataloginventory/stock_item',
    'is_in_stock',
    'product_id=entity_id',
    '(' . join(') OR (', $cond) . ')'
);

$category_model = Mage::getModel('catalog/category');
$category = $category_model->load($category_id);
$collection->addCategoryFilter($category);

For getting count try Count()/getSize();
$count=$collection->count();


text:
Q: Rendering a pandas dataframe as HTML with same styling as Jupyter Notebook I would like to render a pandas dataframe to HTML in the same way as the Jupyter Notebook does it, i.e. with all the bells and wistles like nice looking styling, column highlighting, and column sorting on click.

pandas.to_html outputs just a plain HTML table and requires manual styling etc.
Is the dataframe rendering code used by jupyter available as a standalone module that can be used in any web app?
Also, are the assets such as js/css files decoupled from jupyter so that they can be easily reused?

A: This works well for me
def getTableHTML(df):

    """
    From https://stackoverflow.com/a/49687866/2007153

    Get a Jupyter like html of pandas dataframe

    """

    styles = [
        #table properties
        dict(selector=" ",
             props=[("margin","0"),
                    ("font-family",'"Helvetica", "Arial", sans-serif'),
                    ("border-collapse", "collapse"),
                    ("border","none"),
    #                 ("border", "2px solid #ccf")
                       ]),

        #header color - optional
    #     dict(selector="thead",
    #          props=[("background-color","#cc8484")
    #                ]),

        #background shading
        dict(selector="tbody tr:nth-child(even)",
             props=[("background-color", "#fff")]),
        dict(selector="tbody tr:nth-child(odd)",
             props=[("background-color", "#eee")]),

        #cell spacing
        dict(selector="td",
             props=[("padding", ".5em")]),

        #header cell properties
        dict(selector="th",
             props=[("font-size", "100%"),
                    ("text-align", "center")]),

    ]
    return (df.style.set_table_styles(styles)).render()

iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
getTableHTML(iris)

A: Some points to clarify first:

*

*Pandas doesn't have anything to do with the styling, and the styling happens to all HTML tables, not only dataframes. That is easily checked by displaying an HTML table in Jupyter (example code at the end of the answer).

*It seems that your Jupyter or one of your installed extensions is doing "extra" styling, the default style doesn't include column sorting or column highlighting. There is only odd/even rows coloring and row highlighting (checked on Jupyter source code and my local Jupyter installation). This means that my answer may not include all the styling you want.

The Answer

Is the dataframe rendering code used by jupyter available as a standalone module that can be used in any web app?

Not exactly a standalone module, but all the tables formatting and styling seem to be attached to the rendered_html class. Double-checked that by inspecting the notebook HTML in Firefox.

You can use the .less file linked above directly or copy the required styles to your HTML.

Also, are the assets such as js/css files decoupled from jupyter so that they can be easily reused?

Like any well-designed web project (and actually any software project), the packages and modules are well separated. This means that you can re-use a lot of the code in your project with minimal effort. You can find most of the .less styling files in Jupyter source code here.

An example to check if the styling happens to all HTML tables:
from IPython.display import HTML

HTML('''

	a	b

0	1	3

1	2	4

''')


text:
Q: Radical of an ideal after adjoining roots Let $A$ be a Noetherian domain containing an algebraically closed field $k$. Let $x_1,\ldots,x_r\in A$ be irreducible elements generating a radical ideal $I=(x_1,\ldots,x_r)$. Set $B:=A[y_1,\ldots,y_r]$ where $y_i^n = x_i$. I am wondering whether $\sqrt{I\cdot B} = (y_1,\ldots,y_r)$.
Edit: A minor thought. It would, of course, suffice to show that $J:=(y_1,\ldots,y_r)$ is radical: If $f^n \in IB$, then certainly $f^n\in J$, so $f\in\sqrt{J}$. If $J$ was radical, this would mean $\sqrt{IB}\subseteq J$ and "$\supseteq$" is obvious.

A: As I already noted, it suffices to check that $(y_1,\ldots,y_r)=J$ is a radical ideal. Let
      $\displaystyle f = \sum_{v=(v_1,\ldots,v_r)} \alpha_v \cdot y_1^{v_1} \cdots y_r^{v_r} \in A[y_1,\ldots,y_r]$,      ;       $\alpha_v\in A$
be any element with $f^n\in J$. Any term in the expression $f^n$ will fall into one of three categories:

*

*It is an expression $b\cdot y_i$ with $b\in B$ for some $i$, so it is contained in $J$.

*It is an expression $a\cdot x_i$ with $a\in A$ for some $i$, so it is contained in $I\subseteq J$.

*It is the $n$-th power of the contant term of $f$.

Hence, we may replace $f$ by its constant term, i.e. $f\in A$ and $f^n\in J$. Thus, $f^n\in J\cap A = I$ and since $I$ is radical, $f\in I=J\cap A$.
Edit (Proof that $J\cap A=I$): Consider
$A \hookrightarrow  A[T_1,\ldots,T_r] \twoheadrightarrow B$.
Clearly, the preimage of $J$ under the projection is $(T_1,\ldots,T_r)+(T_1^n-x_1,\ldots,T_r^n-x_n)$ and the constant term in any polynomial generated by these will be generated by the $x_i$, so its preimage under the inclusion will be $I$.


text:
Q: OWASP ZAP share Context between environments and change base URI's addresses I'm new to ZAP tool so sorry in advance if question is stupid, but I cannot find answer on it so far...
I have to fix all the vulnerabilities in some application, so I installed ZAP proxy tool locally, then explored application manually, collected all the requests and ran 'Active scanner' against it. So far everything is good, but the problem is that application quite big and it's very difficult and time consuming to cover everything manually. Fortunately we have dedicated automation environment where I can setup ZAP proxy and let test's go and populate context (set of url's for test) for me
So now my task is somehow share context's between different environments with ability to change base addresses
e.g. I populated context on somedomain/myapp and want run ZAP tool against same application deployed locally, or in different server (e.g. localhost/myapp)
It would be very helpful if someone could share any info how to achieve that.
Thank you in advance,
Eugene

A: It seems that you can create new context and then add existing links to that context.

*

*Craete a new context

*Add existing link to the selected content (right click)

Check this link.
https://chrisdecairos.ca/intercepting-traffic-with-zaproxy/
Tiago


text:
Q: Posterior distribution of $\theta$ with prior Uniform $(0, B)$ and density $p(x;\theta) = e^{-(x-\theta)}$ I am trying to solve this problem from a past exam paper:

Let $X_1, \dots, X_n$ be a random sample of size $n$ from the density:
$p(x; \theta) = exp \{ -(x-\theta) \}, \qquad  x > \theta$
In a Bayesian framework, assume that the prior distribution for
  $\theta$, $\pi(\theta)$, is a Uniform distribution on the interval
  $(0, B)$, where $B$ is a known positive constant. Determine the
  posterior distribution of $\theta$, clearly stating the normalising
  constant.

I know that posterior $\propto$ prior $\times$ likelihood.
Prior: $$\pi(\theta) = \dfrac{1}{B}$$
Likelihood: $$p(\underline{x} ; \theta) = \prod_{i=i}^{n} exp \{ - (x_i - \theta) \} = exp \left\{ - \left(\sum_{i=1}^{n} x_i - n\theta\right) \right\} $$
EDIT: Changed equality to proportionality in response to the comment below.
Posterior: $$ \pi(\theta \mid \underline{x}) \propto \dfrac{1}{B} \times exp \left\{ - \left(\sum_{i=1}^{n} x_i  - n\theta\right) \right\} $$
Now I am stuck. I know the posterior distribution needs to integrate to 1, and this is the way I can find the normalising constant. However, I am unsure about how to find the limits of the integration and how to actually compute this integration (I assume the integration is with respect to $\theta$?)

A: Minor comment: posterior is proportional to the product of prior and maximum likelihood, not equal.

The integration is indeed with respect to $\theta$. To find the limits refer to the definition of p.d.f., namely it's non-zero when $\theta < x$. Hence,
$$
\pi(\theta \mid \underline{x}) = \frac 1 {\mathcal{Z}} \cdot \dfrac{1}{B} \times \exp \left\{ - \left(\sum_{i=1}^{n} x_i  - n\theta\right) \right\}
$$
and we need to find the constant $\mathcal{Z}$. Integrating one gets that
$$
\int \pi(\theta \mid \underline{x}) ~d\theta = \frac 1 {\mathcal{Z}} \cdot \frac 1 {nB} e^{-\sum_{i=1}^n x_i} \int_{-\infty}^{\max(x_i)} e^{n\theta} ~ d(n\theta) = \frac 1{nB} {e^{n\max(x_i) -  \sum_{i=1}^n x_i}} \cdot \frac 1 {\mathcal{Z}} = 1 \implies \\ \mathcal{Z} = Bn \cdot e^{- n\max(x_i) +  \sum_{i=1}^n x_i}.
$$
Finally, the posterior distribution can be written as follows
$$
\pi(\theta \mid \underline{x}) = \frac 1 {B^2n} \cdot \exp\left\{n[\max(x_i) + \theta] -2  \sum_{i=1}^n x_i\right\}.
$$


text:
Q: three Syntax errors in eclipse I just started coding and I am now following a tutorial. I followed the exact steps in the tutorial and changed any variable to what I used. "Example: PutNAMEHERE to MyNAME"
This is the tutorial:
http://bedrockminer.jimdo.com/modding-tutorials/basic-modding-1-7/proxies/
I got three syntax errors though.
This is the piece of code that gives the errors:
@EventHandler
public void postInit(FMLPostInitializationEvent e) {
proxy.postInit (e);
}

The errors are:
*Multiple markers at this line
- Syntax error on token(s), misplaced construct(s)
- Syntax error, insert "enum Identifier" to complete
 EnumHeader
- Syntax error on token "void", @ expected

I did some research before posting this question. I thought there might be a general fix for these errors but it seems it is different for most people.
EDIT:
here is the whole code:
package com.loenabelle.ZAWAM;

import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;

@Mod(modid = Main.MODID, name = Main.MODNAME, version = Main.VERSION)
public class Main {

    public static final String MODID = "ZAWAM";
    public static final String MODNAME = "TZAWAM";
    public static final String VERSION = "1.0.0";

    @Instance
    public static Main instance = new Main();

    @EventHandler
    public void preInit1(FMLPreInitializationEvent e) {

    }

    @EventHandler
    public void init1(FMLInitializationEvent e) {

    }

    @EventHandler
    public void postInit(FMLPostInitializationEvent e) {
       //added a 1 to all but one init//
    }
}

@SidedProxy(clientSide="com.loenabelle.ZAWAM.ClientProxy", serverSide="com.loenabelle.ZAWAM.ServerProxy")
public static CommonProxy proxy;

@EventHandler
public void preInit(FMLPreInitializationEvent e) {
    proxy.preInit(e);
}

@EventHandler
public void init(FMLInitializationEvent e) {
    proxy.init(e);
}

@EventHandler
public void postInit(FMLPostInitializationEvent e) {
    proxy.postInit (e);
    //continue and try to fix this later
}

A: The error in the code above is the closing brace that occurs before "@SidedProxy". Up until that point, everything is inside the class Main. That curly brace ends the class. Code after this closing brace is not in any class at all, which is illegal for method declarations and the like. Nearly everything in Java must be inside a class.
Eclipse does basic matching braces--if you place the cursor on the opening brace of the class (Main {) then Eclipse will highlight the brace that ends the class. (This applies to all sets of matching braces.)


text:
Q: Does rails continue to process a controller method if the page/form that called it is user closed? (rails 2.3.5)
I have a model that when saved creates a long series associated records (4-8 second delay).   If a user were to close the page during this delay, does the contoller finish running the called method ('new', whatever...) until complete?
I'm assuming (hoping) 'yes'.  I just wanted to make sure and can't figure out how to google this.
Thanks!

A: As long as all the processing is in the model than yes, that being said you should consider why it takes that long to create a record and maybe offload it to background processor such as resqueue , background-job or sidekiq


text:
Q: Show overflow menu clicking on an icon list view section header I am creating an App where I need to display an overflow menu on clicking
on an icon from list view section header. The list view has many sections and each section has an icon in the header. Clicking on that icon I need to show up the overflow menu/view both for IOS as well as Android


text:
Q: popto page after few seconds in Ionic 3 I am very new to ionic. Just learning it. Basically I have two pages, welcome and home. First welcome page gets loaded.
I want to load home page after 2-3 seconds when welcome page load. Same I have done using setTimeout in JavaScript.
ionViewDidLoad() {
    console.log('ionViewDidLoad WelcomePage');
    setTimeout(() => {
        this.navCtrl.popToRoot(home);
    }, 2500);
}

The above code not working. Seems like typo error in poptoroot. What can I try to fix this?

A: First you need to declare your variable "home" since it's not defined. Then to have the home page loaded when you get to the welcome page you need to use "ionViewDidEnter". Your problem is that "ionViewDidLoad" only runs once, which is when the page is created, but "ionViewDidEnter" will run even if the page is created or cached.