text:
Q: How does one parse XML files? Is there a simple method of parsing XML files in C#? If so, what?

A: In Addition you can use XPath selector in the following way (easy way to select specific nodes):
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");

var found = doc.DocumentElement.SelectNodes("//book[@title='Barry Poter']"); // select all Book elements in whole dom, with attribute title with value 'Barry Poter'

// Retrieve your data here or change XML here:
foreach (XmlNode book in nodeList)
{
  book.InnerText="The story began as it was...";
}

Console.WriteLine("Display XML:");
doc.Save(Console.Out);

the documentation

A: If you're using .NET 2.0, try XmlReader and its subclasses XmlTextReader, and XmlValidatingReader. They provide a fast, lightweight (memory usage, etc.), forward-only way to parse an XML file.
If you need XPath capabilities, try the XPathNavigator. If you need the entire document in memory try XmlDocument.

A: I'm not sure whether "best practice for parsing XML" exists. There are numerous technologies suited for different situations. Which way to use depends on the concrete scenario.
You can go with LINQ to XML, XmlReader, XPathNavigator or even regular expressions. If you elaborate your needs, I can try to give some suggestions.

A: Use a good XSD Schema to create a set of classes with xsd.exe and use an XmlSerializer to create a object tree out of your XML and vice versa. If you have few restrictions on your model, you could even try to create a direct mapping between you model classes and the XML with the Xml*Attributes.
There is an introductory article about XML Serialisation on MSDN.
Performance tip: Constructing an XmlSerializer is expensive. Keep a reference to your XmlSerializer instance if you intend to parse/write multiple XML files.

A: It's very simple. I know these are standard methods, but you can create your own library to deal with that much better.
Here are some examples:
XmlDocument xmlDoc= new XmlDocument(); // Create an XML document object
xmlDoc.Load("yourXMLFile.xml"); // Load the XML document from the specified file

// Get elements
XmlNodeList girlAddress = xmlDoc.GetElementsByTagName("gAddress");
XmlNodeList girlAge = xmlDoc.GetElementsByTagName("gAge");
XmlNodeList girlCellPhoneNumber = xmlDoc.GetElementsByTagName("gPhone");

// Display the results
Console.WriteLine("Address: " + girlAddress[0].InnerText);
Console.WriteLine("Age: " + girlAge[0].InnerText);
Console.WriteLine("Phone Number: " + girlCellPhoneNumber[0].InnerText);

Also, there are some other methods to work with. For example, here. And I think there is no one best method to do this; you always need to choose it by yourself, what is most suitable for you.

A: You can parse the XML using this library System.Xml.Linq. Below is the sample code I used to parse a XML file
public CatSubCatList GenerateCategoryListFromProductFeedXML()
{
    string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);

    XDocument xDoc = XDocument.Load(path);

    XElement xElement = XElement.Parse(xDoc.ToString());

    List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
    {
        Code = Convert.ToString(d.Element("CategoryCode").Value),
        CategoryPath = d.Element("CategoryPath").Value,
        Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
        SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
    }).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();

    CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);

    return catSubCatList;
}

A: If you're processing a large amount of data (many megabytes) then you want to be using XmlReader to stream parse the XML.
Anything else (XPathNavigator, XElement, XmlDocument and even XmlSerializer if you keep the full generated object graph) will result in high memory usage and also a very slow load time.
Of course, if you need all the data in memory anyway, then you may not have much choice.

A: I'd use LINQ to XML if you're in .NET 3.5 or higher.

A: Use XmlTextReader, XmlReader, XmlNodeReader and the System.Xml.XPath namespace. And (XPathNavigator, XPathDocument, XPathExpression, XPathnodeIterator).
Usually XPath makes reading XML easier, which is what you might be looking for.

A: I have just recently been required to work on an application which involved the parsing of an XML document and I agree with Jon Galloway that the LINQ to XML based approach is, in my opinion, the best. I did however have to dig a little to find usable examples, so without further ado, here are a few!
Any comments welcome as this code works but may not be perfect and I would like to learn more about parsing XML for this project!
public void ParseXML(string filePath)
{
    // create document instance using XML file path
    XDocument doc = XDocument.Load(filePath);

    // get the namespace to that within of the XML (xmlns="...")
    XElement root = doc.Root;
    XNamespace ns = root.GetDefaultNamespace();

    // obtain a list of elements with specific tag
    IEnumerable<XElement> elements = from c in doc.Descendants(ns + "exampleTagName") select c;

    // obtain a single element with specific tag (first instance), useful if only expecting one instance of the tag in the target doc
    XElement element = (from c in doc.Descendants(ns + "exampleTagName" select c).First();

    // obtain an element from within an element, same as from doc
    XElement embeddedElement = (from c in element.Descendants(ns + "exampleEmbeddedTagName" select c).First();

    // obtain an attribute from an element
    XAttribute attribute = element.Attribute("exampleAttributeName");
}

With these functions I was able to parse any element and any attribute from an XML file no problem at all!

A: You can use ExtendedXmlSerializer to serialize and deserialize.
Instalation
You can install ExtendedXmlSerializer from nuget or run the following command:
Install-Package ExtendedXmlSerializer

Serialization:
ExtendedXmlSerializer serializer = new ExtendedXmlSerializer();
var obj = new Message();
var xml = serializer.Serialize(obj);

Deserialization
var obj2 = serializer.Deserialize<Message>(xml);

Standard XML Serializer in .NET is very limited.

*

*Does not support serialization of class with circular reference or class with interface property,

*Does not support Dictionaries,

*There is no mechanism for reading the old version of XML,

*If you want create custom serializer, your class must inherit from IXmlSerializable. This means that your class will not be a POCO class,

*Does not support IoC.

ExtendedXmlSerializer can do this and much more.
ExtendedXmlSerializer support .NET 4.5 or higher and .NET Core. You can integrate it with WebApi and AspCore.

A: You can use XmlDocument and for manipulating or retrieve data from attributes you can Linq to XML classes.


text:
Q: Update cell value if new value is availiable So I am brainstorming a few different ways to accomplish this task... but none of the ways I am thinking are very clean. I am looking for a clean way to accomplish this.
I have 2 workbooks (workbook A, workbook B).
Workbook A looks like this:
 A    B    C    D    E
Tom  Bob  Sam  Ted  Meg
 1    4    9    3    2

The A,B,C... are the columns (not actually on the sheet) and the 1,4,9,3,2 is data on the last row (could be row 10 or row 1000, etc...)
Workbook B looks like this:
  A    B
 Sam   5
 Meg   1

I want to update workbook A with any values on workbook B. So... in this example... Sam and Meg has a new value... So I want to update workbook A to look like this:
 A    B    C    D    E
Tom  Bob  Sam  Ted  Meg
 1    4    5    3    1

I feel like the simplest way to do this may be to make something like a dictionary or something like that but I have never used a dictionary and don't know if some other method would be easier / simpler.

A: So if you want to get data from one book to another then vlookup is the simplest solution
https://photos.app.goo.gl/CRjxhJHVKm6xKJ8x7
I nested it within an if statement that checks to see if there is an error, if there is an error then it just grabs the value from the line above. I.e. if the Name doesn't exist on your second sheet, then there is an error and it will just grab from the line above.
=IF(ISERROR(VLOOKUP(A1,[Book2]Sheet1!$A$2:$B$5,2,FALSE)),A11,VLOOKUP(A1,[Book2]Sheet1!$A$2:$B$5,2,FALSE))

On the face value, this does what you are asking but the way you phrased the question implies that there is some other functionality and some other things you need to do that this solution will possibly get in the way of. That's why I was trying to clarify what you really want to achieve.
Anyway, hopefully its a step in the right direction... Goodluck!

A: Here is my take on it. No dictionary, however going through memory in an array:

Sample data:
Sheet1:

Sheet2:

Sample code:
Sub Test()

Dim lr As Long, x As Long, col As Long
Dim arr As Variant

'Step 1: Get the values to update
With Sheet1
    lr = .Cells(.Rows.Count, 1).End(xlUp).Row
    arr = .Range("A1:B" & lr)
End With

'Step 2: Go through our values to update
With Sheet2
    For x = LBound(arr) To UBound(arr)
        col = .Rows(1).Find(arr(x, 1), Lookat:=xlWhole).Column
        .Cells(.Cells(.Rows.Count, col).End(xlUp).Row + 1, col) = arr(x, 2)
    Next x
End With

End Sub

Result:

Remove the +1 in case you want to rewrite the last entry in the found column. I just assumed you wanted to paste the value underneath. Also, I refered to sheets, you can simply refer to the other open workbook.

A: Firstly, a little more background on my problem. I am opening text files, extracting data, re-arranging the data on an excel sheet (wkbTemp), and then copying the re-arranged data to "wkbCompiledDataTable."
Here is how i solved my problem.
wkbTemp.Sheets(1).Activate
LRow = Cells(Rows.Count, 9).End(xlUp).Offset(0, 0).row

wkbTemp.Sheets(1).Range("J1:N" & LRow).Copy

wkbCompiledDataTable(1).Activate
LRow = Cells(Rows.Count, 1).End(xlUp).Offset(0, 0).row

wkbCompiledDataTable(1).Sheets(1).Range("D" & LRow).PasteSpecial _
                                                          Paste:=xlPasteValues, _
                                                          SkipBlanks:=True, _
                                                          Transpose:=True

As I said earlier, the actual application is much more complicated. This routine is actually in a loop. So for example I actually have "wkbCompiledDataTable(i)" instead of "wkbCompiledDataTable(1)." But for me this was the simplest solution. wkbTemp.Sheets(1) Column "J" has data. Column "K" is blank. Column "L", Column "M", Column "N" has data (These 3 columns are the columns I was concerned with data changing).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trim data frame using input select in ggvis & shiny I'm trying to add an input slider that will trim the data frame which is being used to create a ggvis object as following:
runApp(list(
  ui = bootstrapPage(
    ggvisOutput("p"),
    uiOutput("p_ui")
  ),
  server = function(..., session) {
    for_plot[age>input_slider(0, 300, value = 0, step = .1, label = "Trim first values") ] %>% ggvis(x = ~age, y = ~sum) %>%
       layer_points() %>%
      bind_shiny("p", "p_ui")

  }
))

I'm getting the following error:
Listening on http://127.0.0.1:4088
Error in age > input_slider(0, 300, value = 0, step = 0.1, label = "Trim first values") :
  comparison (6) is possible only for atomic and list types

The Data:
> dput(for_plot)
structure(list(age = -1:137, sum = c(2.9127625202, 1136.15788767452,
273.533113629, 182.577023, 259.43127, 252.508971, 275.684614,
215.032984, 175.90742, 148.352428, 113.003169, 161.357073209,
115.466020271, 156.797340424, 175.038016749, 176.488390764, 91.7729895453,
91.7239276033, 98.9969827211, 102.388825709, 163.942421421, 118.938171624,
134.030560948, 145.528713073, 84.0943510378, 115.900420968, 160.417479634,
141.631984678, 168.467217905, 181.655436653, 148.207568964, 124.859941782,
183.997252898, 156.513051044, 188.82588873, 137.168202013, 123.305076295,
218.081338481, 141.886229086, 93.1080326721, 135.859208991, 227.694944957,
144.246245253, 97.2852532409, 63.379350963, 100.227810825, 127.057637341,
138.673543227, 122.797269725, 127.785499103, 78.9781895255, 94.6973510316,
81.2852298166, 77.0061306202, 101.976840318, 83.4868494245, 68.6421595439,
119.399666, 61.027956, 90.133668, 88.624048, 58.100079, 46.529205,
70.834879, 57.513635, 65.62522, 59.748113, 51.254763, 60.01,
60.041919, 105.772536, 85.564368969, 89.6614592424, 42.607413704,
52.3980349542, 62.0695635701, 85.9011843079, 64.7162277064, 56.1468546477,
46.9516467187, 56.0426098096, 130.354148072, 165.365221108, 69.6146107006,
40.1394275162, 77.6468523819, 60.8783613406, 62.6635625966, 105.87122289,
55.6055641606, 61.8159765316, 72.1644279856, 74.4649577482, 80.1998824221,
45.9350257767, 103.843842017, 98.9039021267, 59.1849148128, 67.5026269702,
52.0332749562, 216.69104441, 85.9505852324, 104.008136809, 200.005094773,
102.962733793, 56.2068235785, 41.0352422907, 51.7020950197, 33.2931629372,
65.704230091, 79.6758468335, 79.4543446244, 103.260073438, 76.7873225476,
37.6227208976, 40.6325385694, 70.9006911716, 51.4076995898, 38.1693658093,
109.9354882, 95.8973745099, 19.0864056748, 69.3897454729, 61.7374836761,
66.5707198551, 63.8689019338, 42.7001939824, 14.5081003557, 40.127732022,
65.8789453554, 95.1309843037, 8.6965147506, 34.625986323, 44.5887916163,
14.4472523862, 35.7203407751, 10.0911065622, 30.1301061724, 12.9129026453
)), .Names = c("age", "sum"), row.names = c(NA, -139L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x0000000001390788>)

Thanks For any help on that!

A: There were some syntax errors in your for_plot filtering above. Also used a shiny slider instead.
library(shiny)
library(ggvis)

for_plot <- structure(
  list(age = -1:137,
       sum = c(2.9127625202, 1136.15788767452,
               273.533113629, 182.577023, 259.43127, 252.508971, 275.684614,
               215.032984, 175.90742, 148.352428, 113.003169, 161.357073209,
               115.466020271, 156.797340424, 175.038016749, 176.488390764, 91.7729895453,
               91.7239276033, 98.9969827211, 102.388825709, 163.942421421, 118.938171624,
               134.030560948, 145.528713073, 84.0943510378, 115.900420968, 160.417479634,
               141.631984678, 168.467217905, 181.655436653, 148.207568964, 124.859941782,
               183.997252898, 156.513051044, 188.82588873, 137.168202013, 123.305076295,
               218.081338481, 141.886229086, 93.1080326721, 135.859208991, 227.694944957,
               144.246245253, 97.2852532409, 63.379350963, 100.227810825, 127.057637341,
               138.673543227, 122.797269725, 127.785499103, 78.9781895255, 94.6973510316,
               81.2852298166, 77.0061306202, 101.976840318, 83.4868494245, 68.6421595439,
               119.399666, 61.027956, 90.133668, 88.624048, 58.100079, 46.529205,
               70.834879, 57.513635, 65.62522, 59.748113, 51.254763, 60.01,
               60.041919, 105.772536, 85.564368969, 89.6614592424, 42.607413704,
               52.3980349542, 62.0695635701, 85.9011843079, 64.7162277064, 56.1468546477,
               46.9516467187, 56.0426098096, 130.354148072, 165.365221108, 69.6146107006,
               40.1394275162, 77.6468523819, 60.8783613406, 62.6635625966, 105.87122289,
               55.6055641606, 61.8159765316, 72.1644279856, 74.4649577482, 80.1998824221,
               45.9350257767, 103.843842017, 98.9039021267, 59.1849148128, 67.5026269702,
               52.0332749562, 216.69104441, 85.9505852324, 104.008136809, 200.005094773,
               102.962733793, 56.2068235785, 41.0352422907, 51.7020950197, 33.2931629372,
               65.704230091, 79.6758468335, 79.4543446244, 103.260073438, 76.7873225476,
               37.6227208976, 40.6325385694, 70.9006911716, 51.4076995898, 38.1693658093,
               109.9354882, 95.8973745099, 19.0864056748, 69.3897454729, 61.7374836761,
               66.5707198551, 63.8689019338, 42.7001939824, 14.5081003557, 40.127732022,
               65.8789453554, 95.1309843037, 8.6965147506, 34.625986323, 44.5887916163,
               14.4472523862, 35.7203407751, 10.0911065622, 30.1301061724, 12.9129026453
       )), .Names = c("age", "sum"), row.names = c(NA, -139L),
  class = c("data.table",  "data.frame")
)

runApp(list(
  ui = bootstrapPage(
    ggvisOutput("p"),
    sliderInput("agetrimlim", "Trim first values:", min = 0, max = 300, value = 0, step= 1)
  ),
  server = function(input,output, session) {
    output$p <- renderGvis({
      input$agetrimlim
      for_plot[for_plot$age>input$agetrimlim,] %>% ggvis(x = ~age, y = ~sum)  %>% bind_shiny('p')
    })
  }
))

Yielding:


text:
Q: stm32 counter up/down and reset on change direction how to add in this code reset on change direction?
counter is tested with signal for stepper motor and working well,
counting is up and down but limit is 32767 after -32766 -32765 ..
for reset on change direction i think to add this lines:
TIM_SlaveConfigTypeDef SlaveModeselect
TIM_MasterConfigTypeDef MasterConfig

SlaveModeselect.SlaveMode = ....
SlaveModeselect.InputTrigger = TIM_TS_TI1FP1

MasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_......
MasterConfig.MasterOutputTrigger = .....

HAL_TIM_SlaveConfigSynchronization(&timer, &SlaveModeselect)
HAL_TIMEx_MasterConfigSynchronization(&timer, &MasterConfig)

Current code:
#include "mbed.h"
#include "stm32f4xx.h"
#include "stm32f4xx_hal_tim_ex.h"

TIM_HandleTypeDef timer;
TIM_Encoder_InitTypeDef encoder;

//direction to PA_9 -- step pulse to PA_8

int main(){
     GPIO_InitTypeDef GPIO_InitStruct;
        __TIM1_CLK_ENABLE();
        __GPIOA_CLK_ENABLE();
        GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9;
        GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
        GPIO_InitStruct.Pull = GPIO_PULLDOWN;
        GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
        GPIO_InitStruct.Alternate = GPIO_AF1_TIM1;
        HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    timer.Instance = TIM1;
    timer.Init.Period = 0xffff;
    timer.Init.Prescaler = 1;
    timer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
    timer.Init.CounterMode = TIM_COUNTERMODE_UP;

    encoder.EncoderMode = TIM_ENCODERMODE_TI1;
    encoder.IC1Filter = 0x0f;
    encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_RISING;
    encoder.IC1Prescaler = TIM_ICPSC_DIV1;
    encoder.IC1Selection = TIM_ICSELECTION_DIRECTTI;

    encoder.IC2Filter = 0x0f;
    encoder.IC2Polarity = TIM_INPUTCHANNELPOLARITY_RISING;
    encoder.IC2Prescaler = TIM_ICPSC_DIV1;
    encoder.IC2Selection = TIM_ICSELECTION_INDIRECTTI;

    HAL_TIM_Encoder_Init(&timer, &encoder);
    HAL_TIM_Encoder_Start(&timer,TIM_CHANNEL_1);

    TIM1->EGR = 1;           // Generate an update event
    TIM1->CR1 = 1;           // Enable the counter

 while (1) {
        int16_t count1;
        count1=TIM1->CNT;

        printf("%d\r\n", count1);
        wait(1.0);

 };
}

A: use uint16_t count1 instead of int16_t to have your counter count up to 65535 then reset to 0 when there is an overflow.


text:
Q: Finding the limit of $2^{-1/\sqrt {n}}$ as $n \rightarrow \infty$. Finding the limit of $2^{-1/\sqrt {n}}$ as $n \rightarrow \infty$. I feel like I can put $n = m^2$, them my limit will be $2^{-1/m}$ as $n \rightarrow \infty$. which is equal to lim $\frac{1}{2^{1/m}}$, then how can I solve this last limit?
Could anyone help me please?

A: Since $2^x$ is continuous, $\displaystyle{\lim_{n \to \infty}} 2 ^{-\frac{1}{\sqrt{n}}}  = 2^{\displaystyle{\lim_{n \to \infty}} -\frac{1}{\sqrt{n}}}= 2^0 = 1$

A: It's easy to get more intuition in problems like this. If the limit exists, let it be $L$, then
$$
\ln L = \ln \left( \lim_{n \to \infty} 2^{-1/\sqrt{n}}\right)
      = \lim_{n \to \infty} \ln\left( 2^{-1/\sqrt{n}}\right)
      = \lim_{n \to \infty} \ln 2 \cdot \frac{-1}{\sqrt{n}}
      = 0
$$
so $L = e^{\ln L} = e^0 = 1$.


text:
Q: Missing methods in SheetService class There are a few methods in this class described in the documentation that do not exist when I actually try to use them:

*

*append_spreadsheet_value

*batch_clear_values

*batch_spreadsheet_value_clear_by_data_filter

*batch_spreadsheet_get_by_data_filter

*batch_spreadsheet_update_by_data_filter

*clear_values

*get_spreadsheet_by_data_filter

*get_spreadsheet_developer_metadatum

*search_developer_metadatum_developer_metadata

The source code for the class:

*

*C:\Ruby22-x64\lib\ruby\gems\2.2.0\gems\google-api-client-0.9.9\generated\google\apis\sheets_v4
doesn't show any sign of these methods.
Is the code for these methods supposed to be located somewhere else, is the missing code a big oversight, or is there some other explanation for these methods not working?

A: You seem to have installed an extremely old version of this gem (0.9.9 - June 09, 2016).
The latest one is 0.24.3 (October 09, 2018), and those methods are present in the GitHub repository also:
https://github.com/googleapis/google-api-ruby-client/blob/711dfb83b33c03535076917726956584d5c8bf9a/generated/google/apis/sheets_v4/service.rb#L390


text:
Q: How to manage multiple Rails applications What is the best way to manage multiple Rails applications?
I heard Rack is a good tool to use and I was wondering if all Rails apps can share the same session so the users don't have to login twice.
I'm also using EmberJS aswell.

A: If you're using token-based authentication, you can maintain a single database table for the user model across both apps (have them both connect to the same database, prefix all tables for app 1 with app1_ and for app 2 with app2_, except for the User table which is unprefixed).
To prefix all the tables for one app, you can set
config.active_record.table_name_prefix = "app1_"

in the environments.rb file of app 1, and
config.active_record.table_name_prefix = "app2_"

in the environments.rb file of app 2.


text:
Q: How to refresh flutter UI on AlertDialog close? I'm working on some sort of time tracking application. The main idea behind it is simple - add the number of hours for a wanted project and display the sum of hours per day.
I'm using Flutter and dart for this and I have the following:
- List of cards for every weekday
- Cards have Gesture detector tap implemented - this action will show all projects for the selected day
- AlertDialog pop-up to add the hours
I'm trying to refresh the total number of hours for the selected day on Alert Dialog pop-up close without reloading all the data.
Can someone help me with any idea how to implement the refresh?
What I've tried so far is the following:

*

*I update the data context (the passed values) before I navigate to the previous screen

*I use StatefulWidget in order to add interactivity to my app

*I use setState to change the data before I return to the previous screen but without any success.

*I found multiple ways on google how to "refresh" UI but without any success

*I try to use setState() since it's perfectly working with some data and I got the following error: " A build function returned null."

*I add setState as part of ShowDialog and I got the following error: "setState() or markNeedsBuild() called during the build." so I add additional logic to check if the data is dirty or not but at the end of a day I got the same result.

Desired behavior for this will be to click on the card and display all the projects for the selected day. After adding a new value I want to return to the same place (with opened card) and the newly added project will show up on the list along with updated total hours for the day.
For now, I got edit partially done. I open the card and edit one of the existing project. The data is saved, but when I return to the previous screen I cannot update the hours on the UI. When I open the edit screen once more the shown data is as expected.

A: First you need to call your showDialog within a Stateful Widget in order to have access, has the name suggests, to a state. Then, within that screen, you can call a method and display your dialog and it will return a Future<void> which means you can perform so action after the dialog is dismissed, such as
showDialog(// Yours params).then((_)=>setState((){}));
and your UI will be updated to match changes.

A: Return true in pop Navigator from the dialog when want to refresh the screen
FlatButton(
    onPressed: () {
        Navigator.of(context).pop(true);
      },
    child: Text("Close"))

Refresh screen when getting true in result
   final result = await showDialog<bool>(
      context: context,
      builder: (context) => MyDialog(),
    )
   if(result){// refresh screen}


text:
Q: Jekyll Social Icon's Background Image Trying to orientate myself with Jekyll. I've downloaded the following theme Mediator Theme. I'm trying to adjust the social icons to show icons for things like Github and Linked in. When I pop over to the _icons.scss file in the _assets folder/stylesheets I see this crazy thing for the background image of the icon. I'm assuming I have to create new icons with a similar format? What on earth is going on with this background image? Has anyone seen this before?
.icon-facebook {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAACgCAYAAACbg+u0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoyNzI3RUZFOTE5QUMxMUUzQjlGQkJERENBQjc5RjE3RiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyNzI3RUZFQTE5QUMxMUUzQjlGQkJERENBQjc5RjE3RiI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjI3MjdFRkU3MTlBQzExRTNCOUZCQkREQ0FCNzlGMTdGIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjI3MjdFRkU4MTlBQzExRTNCOUZCQkREQ0FCNzlGMTdGIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+ExBpwAAAA0JJREFUeNrsnTFrFEEYhndF0GA8MZg+BkXERhuN+gustLRMI/4FLbSysFdEwc7GMpAiSqwsLEyjhViqhWCboOilWd+5G9Ts3u3ezGfudnLPA2+VzeXyMLczs7fsmxdFkUE8+1CAwNYJPKOsKV2lID0Pa95Lhbx0DnQHvVE6jK0KW8ol5UPdCLyPvKF0vJ/aEfhLOYCrobiP88E6gaxpmsmZhVnGIBCBgEAEtoH9e+z/+ai8Vt4rX5QfPrP+524Nd0g5oswrx5SLyuVpFugW/0+VR15gKMvTLPClctOPNs6BgdxTrkxSXsoj0Mm7wywch7s2d5dlTBw/lRtZiy56pCbwofKVhXQchV+qsBOJZEP5zE4knleRv3dSOaccVWYG/Pz8tAh8G3j8CeWZssQI7PMp4NgZv0tZ5Bz4l5DZ9+o45KUmsBtw7NK43lRKAr8HHDuHQBsdBCYCAhGIQAQiEKJpw91ZT5THIxz3LuA1j2f9ry5H4blyKsRZ2/bC3wLl/O998zwfYduCew6B8SwwiSBwoiwikBGIQARyDkRgDG79d9j6Im3YiVxXzo5w3LWA17ytXGg4Znav7IWj9qANrGT9b+Z2/X1wNYZzIAIRiEBAIAIRiEBAIAIRiEBAIAIRiEBAIAIRiEBAIAITE9hFSS3dJoHrOKplvUngraz/uF+osuX91Ap0z0h2z0p+oWzjrMe291F5hrQjp4yAWRiBCEQgIHBSuFn432T0iQztEym76vkaIG8TaQOzOUhiWeAqomqzWha4YyGd5zl9Ig0XE+RreJ+IBLItaZ4zuEufZQwCEQgIRGAroE/E2CdS3omkuDtwj4d/oJyOVLAc8vfKOxH6RKb4HEifiFEefSKR0CdigD4RI/SJGKBPxAh9IkboEzFCn4gR+kSM0CdihD4RI/SJjBH6RFIBgQhEIAIRCNG04e6spPpEyndn0SdCn4h5wU2fiIEFJhEEThSepc8IRCACOQciMAr6RGoYW59ISneohrCyW++jfIcqV2M4ByIQgQgEBCIQgQgEBCIQgQgEBCIQgQgEBCIQgQgEBCIwMYH0idRDn4gR+kQMNPeJFEVBn0iVP30i3s8O6BNhFkZg0vwWYACVpaAuJblZHgAAAABJRU5ErkJggg==);
background-size:14px;
background-position:0 0;
width:14px;
height:14px;
}

What is the background image referencing? I've never seen this before. I figured they were just pulling in the font awesome library but the syntax I'm used didn't work and then I found this. Any help would be greatly apprecaited.


text:
Q: glGetUniform returns -1 for active uniform I have this code calling glGetUniform location but it's returning -1 even though I'm using the uniform in my vertex shader. I don't get any errors from glGetError or glGetProgramInfoLog or glGetShaderInfoLog and the shaders/program all gets created successfully. I also only call this after it gets compiled and linked.
int projectionUniform = glGetUniformLocation( shaderProgram, "dfProjection" );
#version 410

uniform float   dfRealTime;
uniform float   dfGameTime;
uniform mat4    dfProjection;
uniform mat4    dfModelView;

layout(location = 0) in vec3 vertPosition;
layout(location = 1) in vec4 vertColor;

smooth out vec4 color;

out vec4 position;

void main() {
    color = vertColor;

    position = (dfModelView * dfProjection) * vec4(vertPosition, 1.0);
}

This is the fragment shader:
smooth in vec4 color;
out vec4 fragColor;

void main() {
    fragColor = color;
}

A: There are three positibilites:

*

*You have mis-spelled dfProjection in glGetUniformLocation, but it doesn't seem so.

*You are not binding the correct program before calling glGetUniformLocation using glUseProgram.

*Or you are not using position in your fragment shader, which means dfProjection is not really active.

Another thing from the code it seems you are passing the shader handle to glGetUniformLocation you should pass the linked program handle instead.
After your edit you are not using position in your fragment shader,
smooth in vec4 color;
out vec4 fragColor;
in vec4 position;
void main() {
    // do sth with position here
    fragColor = color*position;
}

Keep in mind that you still need to use gl_Position in-order for the fragment shader to know the final fragment position. But I was answering the question of why a uniform variable is not being detected.


text:
Q: how to find limit of $\lim_{n\to+\infty}\int_0^{+\infty}|f(x+\frac1n)-f(x)|dx$? Assume $f$ is continuous on $\mathbb R$ and $\int_0^{+\infty}|f(x)|dx\lt+\infty$. Then how does one find $$\lim_{n\to+\infty}\int_0^{\infty}\left|f\!\left(x+\frac{1}{n}\right)-f(x)\right|dx?$$
Thanks for any hint

A: *

*Show that for each $A>0$ and $n\geqslant 1$, $\int_A^{+\infty}\left|f\left(x+\frac 1n\right)-f(x)\right|dx\leqslant 2\int_{A-1}^{+\infty}f(x)dx$.

*So the problem remains to determine the limit of $\int_0^A\left|f\left(x+\frac 1n\right)-f(x)\right|dx$ as $n\to +\infty$ for $A>0$. Use uniform continuity.


text:
Q: How to use Mac Launcher and OAuth2 with stored credentials? I'm using GoogleAppEngineLauncher 1.9.18 from the Google App Engine SDK for Python on Mac (OS X 10.10.3 Yosemite).
OAuth2 through the browser is now the only way to deploy with the Mac Launcher.
When I deploy my app, the console outputs:
*** Running appcfg.py with the following flags:
     --no_cookies --oauth2 update

But I do want my OAuth2 credentials to be stored. And because of the --no_cookies flag, appcfg.py will not store my credentials in ~/.appcfg_oauth2_tokens. So every time I deploy my app my browser will open to the Google Account OAuth2 page so I allow appcfg to manage my apps.
I ran manually:
appcfg.py --oauth2 update myapp/

And it created the ~/.appcfg_oauth2_tokens file after I did the OAuth2. Now each time I run manually appcfg.py with OAuth2 it works without opening the browser.
But with the Mac Launcher, appcfg.py ignores the .appcfg_oauth2_tokens file because of the --no_cookies flag.
How can I force the Mac Launcher not to use the --no_cookies flag?

A: I have premium Google App Engine support and contacted them regarding this same issue. Google told me that this is a known issue which they are tracking internally, under internal ticket #19324800.
They estimate the fix will be ready by version 1.9.19, but it is possible it could slip to release 1.9.20.


text:
Q: Set Theory - I'm new at set theory and this problem I don't know how to start it please help let's consider this two set A and B as:
$$
A=\{ \frac{(\Pi)}{6} + \frac{k\space\Pi}{3} \space \space | \space \space k\in Z\}
$$
$$
B = \{ -\frac{(\Pi)}{4} + \frac{k\space\Pi}{3} \space \space | \space \space k\in Z\ \}
$$
I started learning mathematics on my own, in my house, through the internet, I stadied logic, and now Set Theory, and I encountered some problems like , this set builder have this  numbers, and this other set have this numbers, what is the result if you do intersection or union between them or something like this.
and this question I encountered it I answered the first one about how do you answer if I asked you is this two sets have in their intersection an emptyset like:
$ A \cap B = \emptyset $
and after that I had this question below
Question is:
How to determine the set:
$$
(A \space\cup\space B)\space\cap\space[-\frac{\Pi}{2};\frac{\Pi}{2}]
$$
in my first question I answered it using (A $\cap$ B is x in A and x in B ... and I said that means the first equation pi/6 + kpi/3 = (-pi/4 + kpi/3))  and I solved that equation and I found that k-k' = a/b which is contradiction so the intersection is an empty set, now the second question is what I wrote above I still can't solve it.
here the only question that I need answer for is the one about this :
(
How to determine the set:
$$
(A \space\cup\space B)\space\cap\space[-\frac{\Pi}{2};\frac{\Pi}{2}]
$$
)<<< this is the one
I wrote it again to make sure people understand which exactly question I want the answer for
PS: I edited my question because people didn't like how I asked it , I gave my background with mathematics, and btw this is my first ever question about mathematics on internet.

A: $$
A=\{ \frac{(\Pi)}{6} + \frac{k\space\Pi}{3} \space \space | \space \space k\in Z\}
$$
It might help to read it as the set of $ \frac{(\Pi)}{6} + \frac{k\space\Pi}{3} $ evaluated for each integer $k$. This set is infinite.  A simlar reading works for B.
$ (A \space\cup\space B) $ is just all elements in A and B combined into one set.
$(A \space\cup\space B)\space\cap\space[-\frac{\Pi}{2};\frac{\Pi}{2}]$ is all elements in A or B where the element is between (and including) $ -\frac{\Pi}{2}, \frac{\Pi}{2} $

A: We want to find the intersection between $A\cup B$ and the closed interval $[\frac{-\pi}{2},\frac{\pi}{2}]$. So we want to find all elements that are in the interval, and in either $A$ or $B$. Elements of $A$ that are in the interval are when $k=0,k=-1,k=1$, and in $B$ the elements are when $k=0,k=1,k=2$. I leave it to you to make sure there aren't others. So what I did is:
Used the fact that $(A\cup B)\cap [\frac{-\pi}{2},\frac{\pi}{2}]$=$(A\cap [\frac{-\pi}{2},\frac{\pi}{2}])\cup(B\cap [\frac{-\pi}{2},\frac{\pi}{2}])$ and then I found $A\cap [\frac{-\pi}{2},\frac{\pi}{2}]$ and $B\cap [\frac{-\pi}{2},\frac{\pi}{2}]$. Then I took their union, which gave me six elements:
$$\frac{-\pi}{4}+\frac{k\pi}{3}$$ for $k=0,1,2$ and $$\frac{\pi}{6}+\frac{\pi k}{3}$$ for $k=-1,0,1$.


text:
Q: steam condenser java errors I've been working on a little project involving Steam Condenser, a Steam API written in Java, but I haven't been able to actually do anything with it.
I'll explain. This is what the wiki tells me:

SteamId id = new SteamId("demomenz");
GameStats stats = id.getGameStats("tf2");
List achievements = stats.getAchievements();

The problem is, eclipse doesn't like it apparently, as it spits out this error:

The constructor SteamId(String) is undefined

and it gives me the option to change it to:

SteamId id = new SteamId("demomenz", false);

But at this point a different error comes out:

The constructor SteamId(Object, boolean) is not visible

So, I'm assuming this function is internal to the API, and should not be called from the outside.
If anyone is familiar with this, or has a clue on why I'm getting this error (I'm fairly new to Java development), an answer would be greatly appreciated.
UPDATE:

The constructor SteamId(String) is undefined

This is if I use SteamId.create(ConvertedID); (ConvertedID is a String containing the Steam64 ID).
At this point I believe this API is not that well written, at least for java. Any other idea?

A: It looks like the constructor is private. Use this instead:
SteamId id = SteamId.create("demomenz");

A: Try using their static method to create the StreamId:
I see the following method in their API
/**
 * Creates a new SteamID instance or gets an existing one
 * from the cache for the profile with the given ID
 *
 * @param id The 64bit SteamID of the player
 * @return The SteamId instance of the requested profile
 * @throws SteamCondenserException if the Steam ID data is not available,
 *         e.g. when it is private
 */
public static SteamId create(String id)
        throws SteamCondenserException {
    return SteamId.create((Object) id, true, false);
}

usage would be:
SteamId streamId = SteamId.create("myId");


text:
Q: What should one know about abstract sets and structural foundations? Recently I came by accident across the book sets for mathematics by Lawvere. It says:

First we deplete the object of nearly all content. We could think of an idealized
  computer memory bank that has been erased, leaving only the pure locations
  (that could be filled with any new data that are relevant). The bag of pure points
  resulting from this process was called by Cantor a Kardinalzahl, but we will
  usually refer to it as an abstract set.

Note that Kardinalzahl is the german word for cardinal number. What's the purpose of working with abstract sets instead of normal sets? Also, is the term "abstract set" usual? I've seen the term "cardinal number" used more frequently.
Some basic set theory is something one learns early in one's study of mathematics. A first intuitive description might read something like this:

A set is an unordered collection of objects. If $S$ is a set and $o$ an object, then $o\in S$ is a statement which is either true or false. Two sets $S, T$ are equal iff they have the same elements. For example, $\{0, 1, 2\}$ is a set; and $\{1, 2, 100\}$ is a different set (though of course they have some common elements, but after all not exactly the same elements).

Do I understand it correctly that in Lawvere's theory of abstract sets, one identifies sets that are isomorphic (i.e. equinumerous)? I really wonder what the purpose of this is. Ask a mathematician at random whether $\{0, 1, 2\}$ and $\{1, 2, 100\}$ are the same sets.

These were my first thoughts about the topic. After that I visited the nlab and learned about the material vs. structural set theory issue in foundations of mathematics. I don't know much about the foundations of mathematics, but from my own experience I would immediately respond that normally when one says "set" one means what they call "material set" (however, in practice one might want to work with urelements, and not only pure sets). What they refer to as "abstract set" is normally called "cardinal number". So why is there this distinction? Why does Lawvere considers the category of abstract sets? I'm pretty sure that this category is equivalent (isomorphic) to the category of sets.

I know this is not about research math. But there might be people interested in foundations, so I don't see how this question could damage mathoverflow.


text:
Q: How to hook the change on property of array of objects? I want to show the change of property in array of user objects. I use useEffect but it could not hook the change of property (or I missed something?).
an array of user objects.
// list of user
const [user, setUser] = React.useState = ([
  {
    name: 'Tom',
    age: 23
  },
  {
    name: 'Marry',
    age: 24
  },
  {
    name: 'Dan',
    age: 22
  },
  {
    name: 'Rose',
    age: 22
  },
  {
    name: 'Alice',
    age: 23
  }
])

I hook the change of user
React.useEffect(() => {
  console.log('useEffect: hook user')
  console.log(user)
}, [user])

Then, I update property age of the object index 1 after clicked the button by function handleUpdate().
function handleUpdate() {
  let v = user
  v[1].age = 99
  setUser(() => {
    return v
  })
  console.log('updated')
  console.log(user)
}

Log show that the array was updated successfully, but log in useEffect not show anychange.
log after updated array

A: You just need to update your handleUpdate func like this:
  const handleUpdate = () => {
    let v = [...user];
    console.log("user: ", user);
    v[1].age = 99;
    console.warn("v: ", v)
    setUser(oldArray => [...oldArray, v]);
    console.log("updated user: ", user);
  };

Hope this works for you

A: Please , read this article first - https://www.benmvp.com/blog/object-array-dependencies-react-useEffect-hook/
I am just used spread operator to return new array  :
import "./styles.css";
import React from "react";

export default function App() {
  const [user, setUser] = React.useState([
    {
      name: "Tom",
      age: 23
    },
    {
      name: "Marry",
      age: 24
    },
    {
      name: "Dan",
      age: 22
    },
    {
      name: "Rose",
      age: 22
    },
    {
      name: "Alice",
      age: 23
    }
  ]);

  React.useEffect(() => {
    console.log("useEffect: hook user");
    console.log(user);
  }, [user]);

  const handleUpdate = () => {
    let v = [...user];
    console.log(user);
    v[1].age = 99;
    setUser(() => {
      return v;
    });
    console.log("updated");
    console.log(user);
  };

  return (

Hello CodeSandbox

Start editing to see some magic happen!

  );
}

https://codesandbox.io/s/solitary-brook-1wdqy?file=/src/App.js


text:
Q: How do I remove selective tables from a MySQL dump How do I remove selective tables from a MySQL dump. I would like to remove the following tables from my dump file. How should I do this.
"DATABASECHANGELOG", "DATABASECHANGELOGLOCK",

A: I guess you could take a mysqldump using the following command to ignore the specific tables on making dump , so you could step away from risks of  removing the tables after taking the dump
mysqldump -u username -p database_name --ignore-table=database_name.table1 --ignore-table=database_name.table2 > test.sql


text:
Q: gearman issues & php cli I'm having some gearman issues when trying to run commands in terminal using php cli. For example I run this command:
gearmand --log-file=/var/log/gearman-job-server/gearman.log
and get:
gearmand: Could not open log file "/usr/local/var/log/gearmand.log", from "/home/jeitnier", switching to stderr. (No such file or directory)
ERROR 2013-01-25 16:25:53.000000 [  main ] bind(Address already in use) -> libgearman-server/gearmand.cc:612
ERROR 2013-01-25 16:25:53.000000 [  main ] bind(Transport endpoint is not connected) -> libgearman-server/gearmand.cc:626
The first line brings up my first issue which after Googling for hours, gives me nothing...Why is there an issue writing to the log? I can't seem to fix this. This occurs after running any commands.
Does anyone know what these errors are? Is it time to remove and re-install all gearman related items?

A: Try the following from the terminal:
sudo mkdir /var/log/gearman-job-server/
sudo touch /var/log/gearman-job-server/gearmand.log
sudo killall gearmand
sudo gearmand --log-file=/var/log/gearman-job-server/gearmand.log


text:
Q: Vim .vimrc custom location I have used the bare bones of Vim under Ubuntu and now I would like to update my .vimrc file.  Although Vim is indeed installed on my PC I don't seem to have a .vimrc file.  I would like to add my .vimrc file but it really should go under my ~/.vim/ folder (I like to keep all my configurations in their respected folders).
How does one create a new vimrc file under this location in Ubuntu 13.04?

A: Two options. (Take a look at :h vimrc which describes the default location and the -u option)
Create an alias to vim -u ~/.vim/vimrc this will cause vim to use that vimrc instead of ~/.vimrc
Or
Upgrade to vim 7.4. One of its default vimrc locations is ~/.vim/vimrc

You can also simulate the vimrc being in a different place.
Create a ~/.vimrc file that contains
runtime vimrc

It's job is to load the first file named vimrc in your runtime path. Which should be ~/.vim/vimrc
Or
You could just symlink ~/.vim/vimrc to ~/.vimrc
ln -s $HOME/.vim/vimrc $HOME/.vimrc

(I've heard some people have had problems with this but I haven't so far)


text:
Q: sendgrid multipart/alternative image from base64 I can't get Sendgrid (using node.js) to send an email with a embedded base64 image in the html. I think I'm quite close...
var base64img='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQgAAAFXCAYAAABeLtDdAAAgAElEQVR4Xu19CXhURdb2ISsJgSQ';//shortened version

sendgrid.send({
    to      : 'address1@gmail.com',
    from    : 'address2@gmail.com',
    subject : 'email with image from base64 data',
    headers:{
      'Content-Type':
      'multipart/alternative; boundary="imagebase64"'+
      '--imagebase64'+
      'Content-Type: image/png; name="base64.png"'+
      'Content-Disposition: inline; filename="base64.png"'+
      'Content-Transfer-Encoding: base64'+
      'Content-ID: <0123456789>'+
      'Content-Location: base64.png'+
      base64img+
      '--imagebase64'
      },
    html    : ''
    });

Can someone help, as I'm failing to find an example close on sendgrid docs or google

A: FIXED!
  var base64img='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQgAAAFXCAYAAABeLtDdAAAgAElEQVR4Xu19CXhURdb2ISsJgSQ';//shortened version
  var data=base64img.replace(/^data:image\/\w+;base64,/,"");
  var buffer=new Buffer(data,'base64');
  fs.writeFile('/home/engine/public_html/img/base64img.png',buffer,function(err){
    fs.readFile('public_html/img/base64img.png',function(err,data){

    sendgrid.send({
      to      : 'address11@gmail.com',
      from    : 'address2@gmail.com',
      subject : 'email with image from base64 data',
      files   : [{filename:'base64.png',content:data,cid:'1234567890'}],
      html    : ''
      },
    function(success,message){
      if(!success){console.log(message);}
      else{
        console.log('sent');
        fs.unlink('public_html/img/base64img.png');
        }
    });});});


text:
Q: What do I need to make a website that references a table of anonymous users to notify using SMS? This is a project I'm working on for use between people at my university.
The idea is simple, it's a website where people can submit anonymous comments to other people based on a unique identifier, which is just a random number. People sign up with their unique identifier and their phone number, which would be saved together. Other people hop on the website and submit a comment with the unique identifier, which is sent via SMS to the corresponding phone number.
Conceptually I feel like this should be easy, the website just searches a table for the identifier and then uses an SMS API to send a message to the associated phone number. Also dynamically adds new lines to the table as people register.
I am real new to web development (if you couldn't tell), but I'm not afraid of a little code so I'm figuring it out. My problem is I have no idea big-picture-wise what building blocks I need to connect together. I think I found a good service called Twilio for the SMS API. I think I need to pay for web hosting, but do I need to rent server time? It's a real simple operation but the data also needs somewhere to live. I want it to be a long-term installation so I don't want to host it myself.
I would be very grateful if someone could real quick make a shopping list of the components I need to make this happen, or just any other tips if you've got 'em


text:
Q: Treetop parser : how to handle spaces? Good morning everyone,
I'm currently trying to describe some basic Ruby grammar but I'm now stuck with parse space?
I can handle x = 1 + 1,
but can't parser x=1+1,
how can I parser space?
I have tried add enough space after every terminal.
but it can't parse,give a nil.....
How can I fix it?
Thank you very much, have a nice day.

grammar Test
  rule main
     s assign
  end

  rule assign
     name:[a-z]+ s '=' s expression s
     {
      def to_ast
        Assign.new(name.text_value.to_sym, expression.to_ast)
      end
    }
  end

  rule expression
     add
  end

  rule add
     left:brackets s '+' s right:add s
     {
      def to_ast
        Add.new(left.to_ast, right.to_ast)
      end
    }
    /
    minus
  end

  rule minus
     left:brackets s '-' s right:minus s
     {
      def to_ast
        Minus.new(left.to_ast, right.to_ast)
      end
    }
    /
    brackets
  end

  rule brackets
      '(' s expression ')' s
      {
       def to_ast
          expression.to_ast
       end
     }
      /
    term
  end

  rule term
    number / variable
  end

  rule number
     [0-9]+ s
     {
      def to_ast
        Number.new(text_value.to_i)
      end
    }
  end

  rule variable
     [a-z]+ s
     {
      def to_ast
        Variable.new(text_value.to_sym)
      end
     }
  end

  rule newline
     s "\n"+ s
  end

  rule s
    [ \t]*
  end
end

this code works
problem Solved!!!!

A: It's not enough to define the space rule, you have to use it anywhere there might be space. Because this occurs often, I usually use a shorter rule name S for mandatory space, and the lowercase version s for optional space.
Then, as a principle, I skip optional space first in my top rule, and again after every terminal that can be followed by space. Terminals here are strings, character sets, etc. So at the start of assign, and before the {} block on variable, boolean, number, and also after your '=', '-' and '+' literals, add a call to the rule s to skip any spaces.
This policy works well for me. It's a good idea to have a test case which has minimum space, and another case that has maximum space (in all possible places).


text:
Q: Add all rows after the first two rows in sql car    sum_of_solds rank
honda   150000       2
mazda   120000       3
tesla   180000       1
toyota  60000        4
I want to add all rows after the first two rows rank wise. So for in the above example, I want something like this:
car    sum_of_solds rank
tesla   150000      1
honda   120000      2
others  180000      others

A: You may use a union query:
SELECT car, sum_of_solds, "rank"
FROM
(
    SELECT car, sum_of_solds, CAST("rank" AS varchar(10)) AS "rank", "rank" AS pos
    FROM yourTable
    WHERE "rank" <= 2
    UNION ALL
    SELECT 'others', SUM(sum_of_solds), 'others', 3
    FROM yourTable
    WHERE "rank" > 2
) t
ORDER BY pos;


text:
Q: how to read data from sd card and display spinner of another activity in android I save file in sd card properly but do not retrieve data of sd card text file and display on spinner of another activity.when I click on read button that data display on spinner of another activity
    when I click on read button txt file item display on spinner
mainactivity.java
btnWriteSDFile = (Button) findViewById(R.id.Write);
btnWriteSDFile.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        Jour = display.getText().toString();
        // write on SD card file data in the text box
        try {
            File myFile = new File("/sdcard/mysdfile.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            myOutWriter.append(display.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(), "Done writing SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    } // onClick
}); // btnWriteSDFile

btnReadSDFile = (Button) findViewById(R.id.Read);
btnReadSDFile.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        // write on SD card file data in the text box
        try {
            File myFile = new File("/sdcard/mysdfile.txt");
            FileInputStream fIn = new FileInputStream(myFile);
            BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn));
            String aDataRow = "";
            String aBuffer = "";
            while ((aDataRow = myReader.readLine()) != null) {
                aBuffer += aDataRow + "\n";
            }
            display.setText(aBuffer);
            myReader.close();
            Toast.makeText(getBaseContext(), "Done reading SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
});

list.java
Spinner sp1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);
    sp1 = (Spinner) findViewById(R.id.spinner1);
    getFilesnames();
}
private void getFilesnames() {
    String[] filenames=getApplicationContext().fileList();
    List<String> list=new ArrayList<String>();
    for(int i = 0; i < filenames.length; i++) {
        list.add(filenames[i]);
    }
    ArrayAdapter<String> filenameAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
    sp1.setAdapter(filenameAdapter);
}


text:
Q: Error: Failed to install provider while installing AWS provider Here's my provider block
terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
    }
  }
}

Here's the full error message
Error while installing hashicorp/aws v4.12.1: chmod
│ .terraform/providers/registry.terraform.io/hashicorp/aws/4.12.1/linux_amd64/terraform-provider-aws_v4.12.1_x5: operation not permitted

This is my first time trying to run Terraform using WSL(Windows Subsystem for Linux) and I've never received this error before when using powershell. Couldn't find any answers or fixes online.

A: I had the same issue recently. WSL restart helped. Win + R →
wsl --shutdown


text:
Q: RecordMyDesktop versus XVIdCap and an importing problem I have both RecordMyDesktop and XVidCap installed. I also have OpenShot and Pitivi installed. OpenShot crashes more than Pitivi, and has more features, but Pitivi has a far better interface. But the lack of features means that I have to deal with OpenShot's unreliability.
If I capture my desktop with RecordMyDesktop, then the resulting video plays fine in the video player. However, once imported into OpenShot, the video is pixelated (even when rendered as an exported video). Ironically, when importing the same captured video into Pitivi, everything works well and as it should.
If I capture my desktop with XVidCap (which isn't as friendly as RecordMyDesktop), then everything works fine in OpenShot (and Pitivi).
What I do know is that RecordMyDesktop saves files as OGG while XVidCap saves files as MPEG. But should that make a difference when using OpenShot and Pitivi? (I have all the restricted extras and Gstreamer stuff installed, for example.)
RecordMyDesktop (and OGG files) are preferable to XVidCap. Any idea what's going on here?
EDIT: Correction. RecordMyDesktop seems to create OGV files.

A: Same here.
Pitivi and Totem uses gstream and work fine with RecordMyDesktop OGV files.
OpenShot, mplayer, mplayer2, smplayer, mencoder and ffmpeg show the video "pixelated"
mplayer says:
==========================================================================
Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family
Selected video codec: [fftheora] vfm: ffmpeg (FFmpeg Theora)
==========================================================================

I fixed it using VLC to convert RecordMyDesktop OGV files to WEBM, then opening in OpenShot.


text:
Q: In Next.js how can I pass data to a dynamic route if 'route.query' is not an available option? I'm working on an embedded app, the main URL doesn't change when I go to my dynamic url page, and router.query keeps returning undefined. When I go to my dynamic route I see my 'hello' so I know it's working, but other than that I'm stumped on how to proceed. My best guess at the moment is to use a span tag instead of a Link tag with an onClick function that not only redirects to the dynamic route, but also sends the path of the dynamic route to a context API so I can retrieve it inside the dynamic route.
Here is my Link code:
        href={{
          pathname: `/customer/[query]`,
          query: { query: `${item.ownerEmail}` },
        }}
      >

And this is the code in the dynamic page:

import { useRouter } from "next/router";

function Customer(props) {
  const router = useRouter;
  console.log(router.query);
  return
Hello
;
}

A: You need to initialize the hook. Should look like this
 const router = useRouter();

Let me know if that solved the problem


text:
Q: PHP mcrypt_decrypt. Same result for two differents strings I am using  mcrypt_encrypt/decrypt to create a coupon whose code is passed through the URL.
public function getReservationIdFromHash($hash) {
    $base64Hash = pack('H*',$hash);
    $encrypted = base64_decode($base64Hash);
    $key = pack("H*", '0123456789abcdef0123456789abcdef');
    $iv =  pack("H*", "abcdef9876543210abcdef9876543210");
    $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv);
    return $str;
}

public function encodeCode($code) {

    $key = pack("H*", '0123456789abcdef0123456789abcdef');
    $iv =  pack("H*", "abcdef9876543210abcdef9876543210");
    $cypherText = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $code, MCRYPT_MODE_CBC, $iv);
    $base64 = base64_encode($cypherText);
    $arr = unpack('H*',$base64);
    $dev = array_pop($arr);
    return $dev;
}

But I am experiencing a weird problem because this encrypted code (which is the result of my function):
785738496771754c66595869566d73446970667444413d3d

and this:
785738496771754c66595869566d73446970667444413d3d44

always are decode to: "XXXXXXXXXXX" (the string I am using to testing), but my common sense says me that they shouldn't be decoded to the exact equal string.
I think I am doing something wrong but I can't imagine what is.
Thanks

A: Display $encrypted, you will probably see the same thing.
In short: if you supply the same (and valid) input to encryption/decryption function you will get the same output. In this case the two inputs must not be the same.
Both look like a hexadecimal display of Base64 encoded data.
The first output is 24 ASCII characters
xW8IgquLfYXiVmsDipftDA==,
the second output is 25 ASCII characters
xW8IgquLfYXiVmsDipftDA==D.
The first ends in ASCII == which can only occur at the end of a Base64 encoding. The second ends in ASCII ==D. My guess is that the Base64 decoding is stopping at the == and ignoring additional characters since that can only occur at the end of a Base64 encoded value.
Also the length of the second is not a valid Base64 length, Base64 encoding are always a multiple of 4-bytes with end padding with 0, 1 or 2 = characters.


text:
Q: Feynman diagram for pair production in matter I'm aware that electron pair-production from a single photon requires the presence of matter — say some large nucleus — able to absorb momentum, as in the process
\begin{align}
N \gamma \rightarrow N e^- e^+
\end{align}
where $N$ represents the nucleus. My question is, how would one represent this process with a Feynman diagram? I'm having trouble constructing one with valid vertices that makes sense. Would the neutron interact with the photon? With the electron-positron pair? Both? Any help would be appreciated.

A: You have a photon that comes in and splits into $e^-e^+$.  One of the electrons escapes, the other has a short segment, where it sheds another photon.  The second electron now escapes and  the photon is absorbed by the nucleus. The center electron segment and the second photon can be off the mass shell.


text:
Q: Export images from Google Sheets I have a Google Sheets sheet that creates QR images from the Google charts API using the IMAGE function that takes a URL to encode as an argument.  I would like to export the created images to an image file,  say a JPG.   Problem is Sheets does not recognize the cell content as an image so SHIFT +  Right click does not show the Save Image As in the context menu.  Any ideas on how to export all of these to separate files.

A: Download the sheet in Microsoft Excel .xlsx format by going to the File > Download menu.
Then open the .xlsx file in your computer using any unzip program (e.g. 7z) and navigate to ../xl/media in the zip file. All the images would be there - extract where you want them.

A: This will fit your needs:

*

*Tools -> Script editor

*Clear the little code you see

*Paste the code from below

*Change sheetname (now Data) to your needs

*sheet.getRange(2,1, ..... This assumes your images starting at row 2 in the first column (A). Change this to fit your needs.

*Changed the folder id to the folder you want the images. (found in url)

*Hit run -> Give permission (once)

Look at the folder.
The script:
function isImageToImage(){
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('Data');
  const formulas = sheet.getRange(2,1, sheet.getLastRow()-1).getFormulas().flat();
  const urls = formulas.map(formula => {
    return /\"(.*?)\"/gmi.exec(formula)[1]
  })

  const folder = DriveApp.getFolderById('1QVo_pr_Wo6xxxxxxxxx9Yx')

  urls.forEach(url => {
    console.log(url)
    const blob = UrlFetchApp.fetch(url).getBlob();
    folder.createFile(blob)
  })

}


text:
Q: angularjs how to avoid access to a just visited route Put the case I've got a route like
.config(function (CONFIG,$routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: CONFIG.site.path_views + '/index/index.html',
                controller: 'IndexCtrl'
            })
            .when('/contestant/create', {
                templateUrl: CONFIG.site.path_views + '/contestant/create.html',
                controller: 'ContestantCreateCtrl'
            })
            .when('/contestant/thanks', {
                templateUrl: CONFIG.site.path_views + '/contestant/thanks.html',
                controller: 'ContestantThanksCtrl'
            })
            .when('/product', {
                templateUrl: CONFIG.site.path_views + '/product/index.html',
                controller: 'ProductCtrl'
            })
            .when('/prize', {
                templateUrl: CONFIG.site.path_views + '/prize/index.html',
                controller: 'PrizeCtrl'
            })
            .otherwise({
                redirectTo: '/'
            });

    })

I'd like to deny access or simply redirect the user
 to /contestant/create if he/she has filled in the form
but I don't find a way :(

A: app.run( function(VisitedRoutes) {
    VisitedRoutes.init();
};
app.factory('VisitedRoutes', function($rootScope,$location) {
        var routes = [];
        return {
            add : function(){
                 routes.push($location.path());
            },
            all:function(){
                return _.uniq(routes);
            },
            hasRoute:function(value){
               return _.indexOf(this.all(), value)
            },
            init:function(){
                var that = this;
                $rootScope.$on('$routeChangeSuccess', function (scope, next, current) {
                    that.add();
                });
            }
        }
    });
app.controller('ContestantCreateCtrl',function($scope,$location,VisitedRoutes) {
    if(VisitedRoutes.hasRoute('/contestant/thanks') !== -1){
        $location.path('/');
    }
});

credit to @Jesus Rodriguez :)


text:
Q: How do I take a column of pandas data based on a scalar condition AND a column comparison? Here's a starting DataFrame:
ipdb> df[["line_amount","modifiedAmount"]]
   line_amount modifiedAmount
0        30.00
1         2.88           2.88
2       199.20          199.2
3      -105.00           -104
4       150.00            150
5        75.00
6      -450.00           -450
7        16.13          16.13
8        20.00
9       111.99         111.99

What I want is a new column of data (or really to replace the modifiedAmount column with one) that contains "" in cases where the original modifiedAmount was EITHER:

*

*already ""   OR

*equal to line_amount

I'm having such trouble figuring out how to accomplish what I'd've expected to be very easy!
I can get this:
ipdb> equal_test = df.modifiedAmount == df.line_amount
ipdb> blank_test = df.modifiedAmount == ""

but I can't do this:
ipdb> blank_test and equal_test
*** ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I see this option when I want to apply a scalar result, but I couldn't figure out how to put df into lambda like this:
ipdb> df.modifiedAmount.apply(lambda x: "" if x == df.line_amount else x)
*** NameError: global name 'df' is not defined

Any ideas?
The desired result look like this:
ipdb> df[["line_amount","modifiedAmount"]]
   line_amount modifiedAmount
0        30.00
1         2.88
2       199.20
3      -105.00         -104.00
4       150.00
5        75.00
6      -450.00
7        16.13
8        20.00
9       111.99

(yes, ideally I want to cast any remaining values to a float to two decimal places)

A: you can use apply column-wise on the whole dataframe.
import pandas as pd
import numpy as np

Create some dummy data and put it in a dataframe. I used np.nan instead of "".
df =pd.DataFrame( { 'lineAmount':[30.00,2.88,199.20,-105.00,150.00,75.00,-450.00,16.13,20.00,111.99], \
                'modifiedAmount':[np.nan,2.88,199.20,-104.00,150.00,np.nan,-450.00,16.13,np.nan,111.99]})

Then you can use a lamda function of the whole dataframe, column-wise using the axis=1 parameter of apply():
df['modifiedAmount'] =df.apply(lambda x: np.nan if x.modifiedAmount == x.lineAmount else x.modifiedAmount, axis =1)

output:
    lineAmount  modifiedAmount
0   30.00       NaN
1   2.88        NaN
2   199.20      NaN
3   -105.00     -104
4   150.00      NaN
5   75.00       NaN
6   -450.00     NaN
7   16.13       NaN
8   20.00       NaN
9   111.99      NaN

A: Building the dataset. Note that i've entered all numbers as float (they seem to be strings in your code)
import pandas as pd
s_dict = {'line_amount': [30, 2.88, 199.2, -105, 150, 75, -450, 16.13, 20, 111.99], 'modifiedAmount': [None,2.88,199.2,-104, 150, None, -450, 16.13, None, 111.99]}
df = pd.DataFrame.from_dict(s_dict)
print df

output :
   line_amount  modifiedAmount
0        30.00             NaN
1         2.88            2.88
2       199.20          199.20
3      -105.00         -104.00
4       150.00          150.00
5        75.00             NaN
6      -450.00         -450.00
7        16.13           16.13
8        20.00             NaN
9       111.99          111.99

This line requires a bit of explanation. Here we are using boolean masks (df.modifiedAmount == df.line_amount and pd.isnull(df.modifiedAmount)), separated by a | (OR comparison), and the ~ at the beginning means NOT.
df['new_mod'] = df.loc[~((df.modifiedAmount == df.line_amount) | (pd.isnull(df.modifiedAmount))), 'modifiedAmount']
print df

output :
   line_amount  modifiedAmount  new_mod
0        30.00             NaN      NaN
1         2.88            2.88      NaN
2       199.20          199.20      NaN
3      -105.00         -104.00     -104
4       150.00          150.00      NaN
5        75.00             NaN      NaN
6      -450.00         -450.00      NaN
7        16.13           16.13      NaN
8        20.00             NaN      NaN
9       111.99          111.99      NaN


text:
Q: Reusing variable in function parameter list int doSomething(int n, int arr[n])

What confuses me here is the reusing of the n variable inside the parameter list. Can anyone explain why this is valid and what are the use cases?

A: C allows several syntaxs for passing an array pointer including:
 int* arr, int arr[] or int arr[10]

However ALL of these are equivalent to the first - that is the compiler sees only an int pointer and does not use any size that may have been specified in the array square brackets to enforce integrity on the size of the array passed.  In all the above cases the compiler will generate:
void __cdecl foo(int * const)

The only way to specify the size of an array is, as you have done, pass a separate parameter indicating the size/length of the array.
In the example you cite the n in arr[n] is not used by the compiler to maintain any integrity on the array bounds - in the example it is only included as an indication that the first parameter is the size.
A less controversial form of the same code might be just to state that more explicitly:
int doSomething(int arr_len, int arr[])

In terms of what is the best convention or preference for passing an pointer and its array size see this question.

A: It is valid.
For this specific case it is equivalent to:
int doSomething(int n, int arr[]);
int doSomething(int n, int *arr);

because the array parameters are automatically transformed into pointers to arrays' elements. In general there are a few differences between array-like and pointer declarations of parameters. See link for more details.
IMO, the better usage should be:
int doSomething(int n, int arr[static n]);

This static n tell the compilers that at least n elements pointer by arr are valid. Moreover it makes the declaration visually different from a declaration of array what helps to avoid surprising issues when sizeof arr is used.


text:
Q: Xcode 13.2 - How to hide git changes in the code editor? In the latest release of Xcode 13.2, there has been a new feature, which allows us to see both old new versions of a line. In my opinion, it's kind of difficult to navigate with this feature enabled. Does anyone know how to turn it off?

A: or you can use this shortcut "Show Code Review" or "Hide Code Review"
shift + opt + cmd + return

A:
Try these arrow press, it will hide the past code.

A: Found it! There is an arrows icon at the top of the editor, which toggles this "code review" mode


text:
Q: How to check if a string contains exactly two words in an SQL query? I need to execute a simple SQL query that will only select those names that are made up of exactly two words
SELECT NAME
FROM GROUP
WHERE NAME <Contains exactly two words>

A: You can use like and not like:
where name like '% %' and not like '% % %'

A: Another option is using LEN() (of course, I assume there are no trailing spaces):
SELECT [NAME]
FROM [GROUP]
WHERE LEN([NAME]) - LEN(REPLACE([NAME], ' ', '')) = 1

If the data in the NAME column has trailing space, you may use TRIM (for SQL Server 2017+) or a combination of LTRIM() and RTRIM() for earlier versions:
SELECT [NAME]
FROM [GROUP]
WHERE LEN(TRIM([NAME])) - LEN(REPLACE(TRIM([NAME]), ' ', '')) = 1

A: If you want both words present and exact:
SELECT *
FROM table
WHERE column LIKE '%word1%'
AND column LIKE '%word2%'


text:
Q: Datepicker Computes Age  I have a code which computes age but it seems wrong because the base I think 1950.

 Now I want to compute the age in  Current time  and selected date on datepicker.

Example: the date now is 11/24/14  and if i pick on datepicker is 11/24/13 the output is 1. PLEASE HELP ME.
HTML

<input id="dob" />

JQUERY
  $('#dob').datepicker({
  onSelect: function(value, ui) {
    console.log(ui.selectedYear)
    var today = new Date(),
        dob = new Date(value),
        age = ui.selectedYear - 1950;

    $('#age').text(age);
},
maxDate: '+0d',
changeMonth: true,
changeYear: true,
defaultDate: '-18yr',
});

here is the working code: http://jsfiddle.net/GCu2D/441/

A: To calculate age, you need to get the current year using getFullYear():
age = today.getFullYear() - ui.selectedYear;

Snippet:

$('#dob').datepicker({
    onSelect: function(value, ui) {
        var today = new Date(),
            age = today.getFullYear() - ui.selectedYear;
        $('#age').text(age);
    },
    maxDate: '+0d',
    changeMonth: true,
    changeYear: true,
    defaultDate: '-18yr',
});
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

<input id="dob" />

A: You need to subtract the current year from the selected date.
$('#dob').datepicker({
    onSelect: function(value, ui) {
        var today = new Date().getTime(),
            dob = new Date(value).getTime();
            age = today - dob;
            yoa = Math.floor(age / 1000 / 60 / 60 / 24 / 365.25); // age / ms / sec / min / hour / days in a year
        if(yoa < 18){
            under18();
        }else{
            overOrEqual18();
        }
    },
    maxDate: '+0d',
    changeMonth: true,
    changeYear: true,
    defaultDate: '-18yr',
});

function overOrEqual18(){
    $('#age').text('you are old enough');
}
function under18(){
    $('#age').text('you are NOT old enough');
}

I suggest that you convert their selected date to a timestamp so that you can more accurately calculate their age rather than just using the year they have selected (this will mean that it accommodates for the day/month as well as the year).
I have added functions that will allow you to perform things based on whether the input is over or under 18 years of age.
DEMO
EDIT:
As per your comment on another answer. If you change maxDate: '+0d' to maxDate: '-18yr' this will disable selection of dates less than 18 years before today
DEMO

A: function comp(){
       var bday=document.getElementById('bday').value;

        var today = new Date();
        var birthDate = new Date(bday);
        var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();

        if (today.getMonth() < birthDate.getMonth() || (today.getMonth() == birthDate.getMonth() && today.getDate() < birthDate.getDate())) {
            age--;

        }

        document.getElementById('age').value=age;
    }


text:
Q: Merge Thunderbird inbox from two separate mailboxes I have used 2 laptops over the last 2 years, and on each laptop I have set up my email accounts on them. I often had to go to each of the different laptops to retrieve specific e-mails, and as bad as it sounds I got used to it and it worked.
However, one of the laptops has now died (although I have a back up of the mailboxes on that laptop) and the other laptop I'm intending to give to my girlfriend for her to use. At the moment I have a desktop PC which I have rebuilt where I'm intending to put all of my emails on to it.
My problem is that I don't know how (or even if it's possible) to merge the different mailboxes from the different laptops and put them in to one mailbox which the desktop PC will use.
On the two laptops I used Thunderbird and on the Desktop PC I will also be using Thunderbird.

A: *

*Backup both of those profile folders to an easily accessible storage for the new PC

*Install Thunderbird on the new PC

*Install ImportExportTools addon (Tools->Add-ons: Search for ImportExportTools)

*Restart Thunderbird

*Tools -> ImportExportTools -> Import mbox file

*If you need your accounts, follow these instructions (ignore the instructions describing how to restore mail if you already did that in the previous step)

*Enjoy :)

A: You can use the copy command at the command line:
copy inboxNEW+inboxOLD inbox

Then start thunderbird.

A: Hi
You can easily merge your two Thunderbird mailbox files with following easy steps
1. First You have to take backup of both profiles which you want to merge.
2. Download and install Thunderbird Application on new PC.
3. Click on Tools > Add-ons: Search ImportExportTools > Install Tool in Add-on.
4. Restart your Thunderbird Application.
5. Goto Tools > ImportExportTools > Import your mbox file.
6. Your file Imported Successfully.
Enjoy your day :)


text:
Q: How to express the days with different temperature? I am wondering a word to express the daily temperature values between. For example, I would like to describe hot/warm days with temperature > 30 C and the days in range 1-10 C. The range of my temperature values are 1 to 40 C. I have thought to express as

*

*very hot/warm days (for temperature > 30 C)

*cold days (for temperature 1-10 C)

Would you please suggest any other suitable phrases to express it.

A: balmy- pleasantly warm, tropical- hot, sultry- hot and humid
mild/temperate- warm/in between,
chilly/chill/nippy- cool, freezing/icy/biting/frigid- cold


text:
Q: How to force the browser to always show images in full size? When I load some pages that have just an image, the browser always tries to fit the image to the current window size, and to view full size, I have to click on the image with the magnifying glass.  This happens with both chrome and firefox.
How can I force these pages to always show at full size, or at least default to showing at full size?

A: You could write a Tampermonkey script to run on all data:image url pages and grab the image's HTML5 naturalWidth and naturalHeight and override the image's width and height properties on load and window resize, or set img inline css width/height !important, as the browser is setting these properties.


text: Q: create a link list of integer numbers it will split the list into two different lists of odd and even numbers and display the resultant We need to create a singly linked list then seperate the odd and even values into a even and odd singly linked list. I may be able to explain it but I am facing difficulty in figuring out the exact code.


text:
Q: Redirect entire command including result to .txt file >%DT%.TXT 2>&1 (
xcopy E:\OUTSIDE\XFORM\%FN%.frm D:\OUTSIDE\XFORM /y
xcopy E:\OUTSIDE\XFORM\%FN%.fsl D:\OUTSIDE\XFORM /y
xcopy E:\OUTSIDE\XIMAGE\%FN%.img D:\OUTSIDE\XFORM /y
)

The code above is a sample of the lines I need redirected to a text file. This currently works with the exception that it only shows where the file is being copied from and how many files are being copied.
I need to be able to redirect the entire line so I can see where the files are being copied to as well for control purposes. Not entirely sure this is even possible via batch. Sadly it's my only option at this time.

A: I offer two simple batch solutions.
The first one is using parameter /F as suggested by MC ND:
>>%DT%.TXT 2>&1 (
    xcopy E:\OUTSIDE\XFORM\%FN%.frm D:\OUTSIDE\XFORM /F /I /Y
    xcopy E:\OUTSIDE\XFORM\%FN%.fsl D:\OUTSIDE\XFORM /F /I /Y
    xcopy E:\OUTSIDE\XIMAGE\%FN%.img D:\OUTSIDE\XFORM /F /I /Y
)

The help of command xcopy can be read by running in a command prompt window xcopy /? which explains parameter /I as well - D:\OUTSIDE\XFORM should be interpreted as destination folder to be created automatically if not already existing.
The second one is echoing the source and destination before making the copy:
>>%DT%.TXT 2>&1 (
    echo Copying E:\OUTSIDE\XFORM\%FN%.frm to D:\OUTSIDE\XFORM
    xcopy E:\OUTSIDE\XFORM\%FN%.frm D:\OUTSIDE\XFORM /I /Y
    echo Copying E:\OUTSIDE\XFORM\%FN%.fsl to D:\OUTSIDE\XFORM
    xcopy E:\OUTSIDE\XFORM\%FN%.fsl D:\OUTSIDE\XFORM /I /Y
    echo Copying E:\OUTSIDE\XFORM\%FN%.img to D:\OUTSIDE\XFORM
    xcopy E:\OUTSIDE\XIMAGE\%FN%.img D:\OUTSIDE\XFORM /I /Y
)


text:
Q: How to adjust Jquery jtable column width in php? paid_date: {
    title: 'Paid Date',
    sorting: 'id DESC',
    type: 'date',
    width: '20%',
},

A: You can use setMinWidth(200) and setPreferredWidth(200) to set column width.

A: jTable is designed to fit it's container element, not for a fixed width. So, all columns will be completed to 100%. If you want to fix table's width, set it's container's width.
But
Width of the column for this field in the table. Can be a percantage value (ex: '30%'). It's required if the field is shown on the table. It's best to complete all shown field widths to 100%.


text:
Q: Use tf.gather to extract tensors row-wise based on another tensor row-wisely (first dimension) I have two tensors with dimensions as A:[B,3000,3] and C:[B,4000] respectively. I want to use tf.gather() to use every single row from tensor C as index, and to use every row from tensor A as params, to get a result with size [B,4000,3].
Here is an example to make this more understandable: Say I have tensors as

A = [[1,2,3],[4,5,6],[7,8,9]],
C = [0,2,1,2,1],
result = [[1,2,3],[7,8,9],[4,5,6],[7,8,9],[4,5,6]],

by using tf.gather(A,C). It is all fine when applying to tensors with dimension less than 3.
But when it is the case as the description as the beginning, by applying tf.gather(A,C,axis=1), the shape of result tensor is

[B,B,4000,3]

It seems that tf.gather() just did the job for every element in tensor C as the indices to gather elements in tensor A. The only solution I am thinking about is to use a for loop, but that would extremely reduce the computational ability by using tf.gather(A[i,...],C[i,...]) to gain the correct size of tensor

[B,4000,3]

Thus, is there any function that is able to do this task similarly?

A: You need to use tf.gather_nd:
import tensorflow as tf

A = ...  # B x 3000 x 3
C = ...  # B x 4000
s = tf.shape(C)
B, cols = s[0], s[1]
# Make indices for first dimension
idx = tf.tile(tf.expand_dims(tf.range(B, dtype=C.dtype), 1), [1, cols])
# Complete index for gather_nd
gather_idx = tf.stack([idx, C], axis=-1)
# Gather result
result = tf.gather_nd(A, gather_idx)


text:
Q: Is there any way to call SceneDelegate methods in iOS 14 app life cycle? We know Apple has drastically simplified the SwiftUI app life cycle (WWDC20). I have seen the video of Mr.Paul Hudson about the new changes in SwiftUI in which he has explained how to access AppDelegate methods in "@main or :App" struct.
I want to know if there is any way to access the SceneDelegate methods?
Thanks in advance. :)

A: There is no access for SceneDelegate now in SwiftUI 2.0 life-cycle. Some of callbacks you can use with .onChange for [.active, .inactive, .background] states as shown for example here
or... there is nothing wrong in continue using UIKit life-cycle

A: It's is an example to access life cycle in AppDelegate.
struct PodcastScene: Scene {
    @Environment(\.scenePhase) private var phase

    var body: some Scene {
        WindowGroup {
            TabView {
                LibraryView()
                DiscoverView()
                SearchView()
            }
        }
        .onChange(of: phase) { newPhase in
            switch newPhase {
            case .active:
                // App became active
            case .inactive:
                // App became inactive
            case .background:
                // App is running in the background
            @unknown default:
                // Fallback for future cases
            }
        }
    }
}

If you add a framework configuration like Firebase, you can override the init and input your code here.
struct PodcastScene: Scene {

    init() {
        FirebaseApp.configure()
    }

    var body: some Scene {
        WindowGroup {
            TabView {
                LibraryView()
                DiscoverView()
                SearchView()
            }
        }
    }
}


text:
Q: Visual Studio Live server responds to updates but github's real hosted website doesn't Problem
I recently bought a website from google domains, I got my code running and tried to run a live server test using a visual studio extension I downloaded, It looked all right until I saw that the live server did look at my new button code. But when on my Github hosted website it didn't.
If anyone could help me work this out It will be a huge help to me and my website. I am new to both HTML, JS and even Github Pages. So sorry if this question is kinda easy to answer. I have some questions about the weird divs in my html, if anyone could anwser that too that would be great.
Button Code

Home

Appeals

Store

Contact


text:
Q: What's a good analogy to explain the concept of wicked problems? Most developers understand the concept of wicked problems. What's a good analogy to use when explaining this concept to project managers?

A: If you want an analogy, I would go with the timeline of NASA.  Still technical based, but you do not need any coding skills to understand the difficulty involved.  I'm also using the Coding Horror definition of a wicked problemm in that:

Horst Rittel and Melvin Webber defined
  a "wicked" problem as one that could
  be clearly defined only by solving it,
  or by solving part of it. This paradox
  implies, essentially, that you have to
  "solve" the problem once in order to
  clearly define it and then solve it
  again to create a solution that works.

When NASA started, they were tasked with getting a man on the moon.  I'm sure at the time they had ideas of how they were going to accomplish the task, but there was no way they could spec out the first moon mission at the start.  They had to develop rockets and find out all the catastrophic things that could go wrong.  They had to get an orbiter flying around the Earth and then bring the astronaut back home safely.  Eventually they got to the point of getting to the moon, but there was still the issue of getting home.
I hope this seems like a non-programming wicked problem to your project manager.  If not, I agree with Glomek.  You are doomed.

A: Every changing requirements lead to an impossible to manage design. Just send him here: Winchester Mystery House. The house is filled with staircases to nowhere and doors that open to brick walls. It was built exactly as spec'd, but isn't really what you'd call usable.
Of course up here in New England a "wicked problem" is one that requires a wicked good engineer to come up with a wicked clever solution :)

A: there's the time-honored "trying to hit a moving target" analogy
which you could step up to wicked level as
trying to hit a moving taget that changes shape,
wears disguises, hides in shadows, recruits minions,
and shoots back

A: Try getting them to read the article with "I wanted to know your thoughts on this article..."
Really, your project managers should know this stuff though.

A: If your project manager has no programming experience, then you are doomed and should find a new place to work.
If your project manager has no programming experience, and is not willing to leave architectural decisions to someone who has some programming experience, then you are double doomed and you very desperately need to find a new place to work.


text:
Q: ASP.NET Bootstrap wrong display I was looking up this style on bootswatch: https://bootswatch.com/simplex/
And especially looked for styling forms, like here:

But when I add the code that you get when clicking on the little red icon in the top right of the form example on bootswatch to my website, it looks like this:

So the text labels and input fields have a line break inbetween them, the a little darker shaded background box isnt shown and other things are misaligned, too. How does that come?
This is the entire code of my Page:
@model WebProto.ViewModels.NewChartConfigViewModel
@using MaschinenModell;

@{
    ViewBag.Title = "Neues Diagramm";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<form class="form-horizontal">
    <fieldset>
        <legend>Legend</legend>

            Email

                <input type="text" class="form-control" id="inputEmail" placeholder="Email">

            Password

                <input type="password" class="form-control" id="inputPassword" placeholder="Password">

                        <input type="checkbox"> Checkbox

            Textarea

                <textarea class="form-control" rows="3" id="textArea"></textarea>
                A longer block of help text that breaks onto a new line and may extend beyond one line.

            Radios

                        <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked="">
                        Option one is this

                        <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
                        Option two can be something else

            Selects

                <select class="form-control" id="select">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                </select>

                <select multiple="" class="form-control">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                </select>

                <button type="reset" class="btn btn-default">Cancel</button>
                <button type="submit" class="btn btn-primary">Submit</button>

    </fieldset>
</form>

A: Okay im so flipping stupid. Its because I displayed the webpage I created in internet explorer. My fault! :D
Firefox, Opera and Chrome show it correctly.


text:
Q: How can I import all of sklearns regressors I'm doing some predictive modeling and would like to benchmark different kinds of regressors in scikit-learn, just to see what's out there and how they perform on a given prediction task.
I got inspired to do this by this kaggle kernel in which the author essentially manually imports a bunch of classifiers (about 10) and benchmarks them.
I'm having trouble finding a comprehensive list of imports for the regressors in sklearn so I'm trying to automatize the import statements to automatically return me a list of classes that I can use.
I tried to dynamically import the classes:
from importlib import import_module
import sklearn

def all_regressors():
    regressors=[]
    for module in sklearn.__all__:
        try:
            regressors.extend([cls for cls in import_module(f'sklearn.{module}').__all__ if 'Regress' in cls ])
        except:
            pass
    regressors.append(sklearn.svm.SVR)
    return regressors
print(all_regressors())

But i only get back the names as strings, rather than the classes:
['RandomForestRegressor', 'ExtraTreesRegressor', 'BaggingRegressor',
'GradientBoostingRegressor', 'AdaBoostRegressor',
'GaussianProcessRegressor', 'IsotonicRegression', 'ARDRegression',
'HuberRegressor', 'LinearRegression', 'LogisticRegression',
'LogisticRegressionCV', 'PassiveAggressiveRegressor',
'RandomizedLogisticRegression', 'SGDRegressor', 'TheilSenRegressor',
'RANSACRegressor', 'MultiOutputRegressor', 'KNeighborsRegressor',
'RadiusNeighborsRegressor', 'MLPRegressor', 'DecisionTreeRegressor',
'ExtraTreeRegressor', <class 'sklearn.svm.classes.SVR'>]

How can I get the actual classes?

A: I figured out i had to use getattr on the module object:
from importlib import import_module
import sklearn

def all_regressors():
    regressors=[]
    for module in sklearn.__all__:
        try:
            module = import_module(f'sklearn.{module}')
            regressors.extend([getattr(module,cls) for cls in module.__all__  if 'Regress' in cls ])
        except:
            pass
    regressors.append(sklearn.svm.SVR)
    return regressors
print(all_regressors())

[<class 'sklearn.ensemble.forest.RandomForestRegressor'>, <class
'sklearn.ensemble.forest.ExtraTreesRegressor'>, <class
'sklearn.ensemble.bagging.BaggingRegressor'>, <class
'sklearn.ensemble.gradient_boosting.GradientBoostingRegressor'>,
<class 'sklearn.ensemble.weight_boosting.AdaBoostRegressor'>, <class
'sklearn.gaussian_process.gpr.GaussianProcessRegressor'>, <class
'sklearn.isotonic.IsotonicRegression'>, <class
'sklearn.linear_model.bayes.ARDRegression'>, <class
'sklearn.linear_model.huber.HuberRegressor'>, <class
'sklearn.linear_model.base.LinearRegression'>, <class
'sklearn.linear_model.logistic.LogisticRegression'>, <class
'sklearn.linear_model.logistic.LogisticRegressionCV'>, <class
'sklearn.linear_model.passive_aggressive.PassiveAggressiveRegressor'>,
<class 'sklearn.linear_model.randomized_l1.RandomizedLogisticRegression'>, <class
'sklearn.linear_model.stochastic_gradient.SGDRegressor'>, <class
'sklearn.linear_model.theil_sen.TheilSenRegressor'>, <class
'sklearn.linear_model.ransac.RANSACRegressor'>, <class
'sklearn.multioutput.MultiOutputRegressor'>, <class
'sklearn.neighbors.regression.KNeighborsRegressor'>, <class
'sklearn.neighbors.regression.RadiusNeighborsRegressor'>, <class
'sklearn.neural_network.multilayer_perceptron.MLPRegressor'>, <class
'sklearn.tree.tree.DecisionTreeRegressor'>, <class
'sklearn.tree.tree.ExtraTreeRegressor'>, <class
'sklearn.svm.classes.SVR'>]

A: You can use all_estimators from sklearn.utils
from sklearn.utils import all_estimators

def get_all_regressors_sklearn():

    estimators = all_estimators(type_filter='regressor')

    all_regs = []
    for name, RegClass in estimators:
        print('Appending', name)
        try:
            reg = RegClass()
            all_regs.append(reg)
        except Exception as e:
            pass
    return all_regs

all_regs = get_all_regressors_sklearn()
print(all_regs)

Gives:
[ARDRegression(), AdaBoostRegressor(), BaggingRegressor(), BayesianRidge(), CCA(), DecisionTreeRegressor(), DummyRegressor(), ElasticNet(), ElasticNetCV(), ExtraTreeRegressor(), ExtraTreesRegressor(), GammaRegressor(), GaussianProcessRegressor(), GradientBoostingRegressor(), HistGradientBoostingRegressor(), HuberRegressor(), IsotonicRegression(), KNeighborsRegressor(), KernelRidge(), Lars(), LarsCV(), Lasso(), LassoCV(), LassoLars(), LassoLarsCV(), LassoLarsIC(), LinearRegression(), LinearSVR(), MLPRegressor(), MultiTaskElasticNet(), MultiTaskElasticNetCV(), MultiTaskLasso(), MultiTaskLassoCV(), NuSVR(), OrthogonalMatchingPursuit(), OrthogonalMatchingPursuitCV(), PLSCanonical(), PLSRegression(), PassiveAggressiveRegressor(), PoissonRegressor(), QuantileRegressor(), RANSACRegressor(), RadiusNeighborsRegressor(), RandomForestRegressor(), Ridge(), RidgeCV(), SGDRegressor(), SVR(), TheilSenRegressor(), TransformedTargetRegressor(), TweedieRegressor()]


text:
Q: VirtualStringTree, changing the row background color I have got some of the latest version of the VirtualTreeView and try to
change the background color of the whole row of TVirtualStringTree both in selected and in non-selected states (toFullRowSelect is included somewhere). There is a lot of similar questions with different answers but none seems to fit well. In all of them you just write a handler that includes the code snippet like this:
  TargetCanvas.Brush.Color := SomeColor;
  TargetCanvas.FillRect(SomeRect);

But it's not that simple as I thought:

*

*OnBeforeCellPaint handler works well only if the row is not
selected

*OnDrawText handler works in both states but the entire
row looks divided by spaces between cells

*OnBeforeItemErased affects the whole row but again if it is not in selected state

*The painting in some other handlers either are repainted later automatically or require fully manual drawing which looks excessive for a simple task.

So I failed to find an easy way.
I added the additional conditions:

*

*The row must stay in selected state cause the tree could be in MultiSelected mode (toMultiSelect is included).

*The colors of selected and unselected states of the row may differ as well as different selected rows may have different colors too.

The best I could create is to write a handler on OnDrawTexr event:

This tree is produced by an array of records (oversimplified):
type
  TJob=record
    Running:Boolean;// the job is stopped or running
    MaxDuration:integer;//0 - infinite, or seconds
    Start:TDateTime;//The job start time
  end;

*

*if the job is stopped its row should behave in the default treeview
way.

*If the job is running and infinite it should be colored e.g. as
green, if selected - as thick green

*If the job is running and have
limited duration its row should have a transitioned color between
green and red that changes constantly while meeting its deadline. If
selected the color should be brighter.

A: in VirtualTrees, if node select, it must draw..
in VirtualTrees.pas line 25974
          if vsSelected in Node.States then
          begin
             if Focused or (toPopupMode in FOptions.FPaintOptions) then
             begin
                Brush.Color := FColors.FocusedSelectionColor;
                Pen.Color := FColors.FocusedSelectionBorderColor;
              end
              else
              begin
                Brush.Color := FColors.UnfocusedSelectionColor;
                Pen.Color := FColors.UnfocusedSelectionBorderColor;
              end;
          ....
          end

you can delete it:
              //Brush.Color := FColors.FocusedSelectionColor;
              //Pen.Color := FColors.FocusedSelectionBorderColor;

also you can do it on OnBeforeCellPaint and change node to not select:
  TargetCanvas.Brush.Color := $00776655;
  TargetCanvas.FillRect(CellRect);
  Exclude(Node.States, vsSelected);

it will like follow:

A: Use OnBeforeCellPaint for non selected row, use Colors.FocusedSelectionColor property for selected row..


text:
Q: When would the Windows environment variable be HOMEPATH=\ set HOME
HOMEDRIVE=C:
HOMEPATH=\
USERDOMAIN=user01
USERNAME=user01
USERPROFILE=C:\Documents and Settings\user01

Microsoft Windows XP [Version 5.1.2600]

On the Windows boxes I've tested until now, USERPROFILE=%HOMEDRIVE%%HOMEPATH%
When I originallydecided to go with HOMEDRIVE/HOMEPATH, I read an article that said it was the safest way to go.
What would be causing HOMEPATH to be /?
If commands are needed to be executed on this machine, please put them in the form of a batch file.  Thank you.

A: HOMEPATH can be set to an equivalent of either %USERPROFILE% or the root of %HOMEDRIVE%. For scripts that you're writing on DOS/CMD on modern versions of windows (XP/Vista), you should use %USERPROFILE%.
That said, if you're writing an application (or vbs, etc), get the shell folders list from windows, as it is (generally) more accurate/reliable than %userprofile%.

A: I found out that USERPROFILE is NOT identical to %HOMEDRIVE%%HOMEPATH%
In short words:

*

*With roaming profiles: HOMEPATH is the roaming location and USERPROFILE is the local location (See git-wrapper.c)

*e.g.  when you use secondary logons run as, HOMEDRIVE, HOMEPATH will not be refresh, and HOMEPATH will always be \Windows\system32 for each user (See meaning-variables-homedrive-homepath why this happens)

To read the full context check issue git-for-windows#2709
EDIT: I found out that HOPMEPATH will be \ when you are useing network profiles, like you can read in how-do-i-change-homedrive-homepath-and-homeshare-in-windows-xp


text:
Q: Where can I change the FileZilla font size running under Windows 7 I consider myself to be a pretty savvy computer user, but this one has escaped me. After reading the documentation, the blogs, the wiki, the bug trac I am still at a loss.
Does anyone know how to adjust the font size of the various FileZilla windows?
Any idea or reference to documentation I missed would be appreciated.

A: You may find this hard to believe... but the filezilla fonts are controlled by the Icon font.
Changed by "Window Color and Appearance"->"Item Icon"->"Font"
Note: This will change all the windows explorer fonts as well

A: It looks like this is now set in Windows. Change your windows font size and filezilla will update.
https://forum.filezilla-project.org/viewtopic.php?t=30353