text: Q: XOpenDisplay(NULL) fails to connect to X I was given a fairly large program to compile and run with extremely vague instructions on how to properly configure my system and install the program.  I was told to use a Windows, install Cygwin, navigate to the program's base directory, and type "make".  I installed Cygwin on a 64-bit Windows 7 in C:\cygwin64 as the main user (I also installed all of the default packages, plus a few extras) and then ran the makefile included with the program (this worked with no problems).  When trying to run the executable with a required file argument, I was simply given the error message "cannot connect to X server."  Upon examination of the code, it appears that this error was caused by a line setting display=XOpenDisplay(NULL) and then exiting when this resulted in display == NULL.  Earlier, "display" had been declared as a variable of type Display.  Is there any way I can get the program to connect to the X server?  I have been assured that the installation of the program is extremely easy, but I'm not so sure...  Thanks in advance.


text:
Q: md-slider stop anywhere without jumping to a step I am using the md-slider directive and I have it set up like this:
<md-slider class="md-primary" ng-model="question.sliderPosition" ng-change="handleProducts()" md-discrete step="3" min="3" max="9" aria-label="rating"></md-slider>

There are only 3 positions. But my client doesn't want it to jump to the next position, rather they want it to stop when the user let's go of the mouse and then for my code to work out which step the point is closest to.
Does anyone know if that is even possible?

A: No the API does not expose this as an option.
However most things are possible, if you take a look at the directive's source code and commented out any references to clamp then it would not do as the function suggests, clamp the position of the slider to it's closest position.
When it sets the sliders percentage, e.g. when you release the mouse, it calls clamp and adjusts the position based on the value (current position) passed in.
https://github.com/angular/material/blob/master/src/components/slider/slider.js#L559

redpajama_set_name: RedPajamaStackExchange


text:
Q: WebView2 - Get an attribute I am trying to understand the architecture in WebView2. With WebBrowser i used to get an attribute from a result returned by the GetElementById as follows: Document.GetElementById("DropDownList").GetAttribute("selectedIndex")
I know that the ExecuteScriptAsync in WebView2 can run a javascript and return a result as a string. However, it looks like that it does not know how to get an attribute from an element. The below code returns a null. Although, the getElementById returns the correct result.
ExecuteScriptAsync("document.getElementById('DropDownList').getAttribute('selectedIndex')")
Is my syntax incorrect? How to get an attribute in WebView2?. Do we have to write a function in the script and call it from the host?
Thanks

A: A HTMLSelectElement does not have an attribute called.'selectedIndex'. It has a PROPERTY called 'selectedIndex'.
Call it like this from WebView2:
await ExecuteScriptAsync("document.getElementById('DropDownList').selectedIndex");

A: You need to await this method. see the reference
string res = await ExecuteScriptAsync("document.getElementById('DropDownList').getAttribute('selectedIndex')")


text:
Q: Angular7 Promise cannot be used When I upgraded Angular6 to Angular7, I found that Promise didn't seem to work.
IDE gave me the following tips. I tried to search and couldn't understand why.
Unresolved type Promise less... (Ctrl+F1)
Checks TypeScript called functions to be valid ones

A: I try to add the following to ts.config as a solution.
"compilerOptions": {    "lib": ["es7", "dom"]}


text:
Q: Terraform interpolation syntax error for data template_file In my lambda.tf, I have a data resource
data "template_file" "handler" {
    template = "${file("${path.module}/templates/handler.js")}"

    vars = {
        ENDPOINT = "${var.domain}"
        PASSWORD = "${var.password}"
    }
}

However - I'm encountering a syntax error:
Error: failed to render : <template_file>:280,49-50: Extra characters after interpolation expression; Expected a closing brace to end the interpolation expression, but found extra characters.

  on ../docs/lambda.tf line 1, in data "template_file" "handler":
   1: data "template_file" "handler" {

Is interpolation inside an interpolation allowed for Terraform? If so - any suggestions on pointing towards where the error is would be greatly appreciated.
Terraform v0.12.9.
Provider "aws" version "~> 2.7"

A: Not exactly clear what your template file looks like or what you are trying to do, so here are a couple different answers.

*

*You can escape interpolation with double dollar signs: $${foo} will be rendered as a literal ${foo}.

*Terraform does not allow dynamic construction of variable names, because it needs to be able to analyze the configuration statically (that is, without evaluating any expressions) in order to determine which order the expressions must be resolved in.
Terraform supports a map data structure that can be used to achieve this effect.
variable "var1" {
 default = "value1"
}
variable "var2" {
 default = "value2"
}

locals {
 var3 = "${var.var1}_${var.var2}"
 values = {
   "value1_value2" = "local1"
   "value2_value3" = "local2"
   "value3_value4" = "local3"
 }
}

output "val_output" {
 value = "${local.values[local.var3]}"
}

If neither is what you are looking for, you need to share your template file or a modified version that duplicates the error.

A: The template_file data source continues to exist for users of Terraform 0.11 and earlier, but since you are using a Terraform 0.12 release I'd recommend using the templatefile function instead. Because it's built directly into Terraform, it is able to produce better error messages.
To use it, you can replace your references to data.template_file.handler.rendered with a direct call to templatefile. If you are using that rendered result in multiple locations, you can assign the templatefile result to a local value and reference that in multiple places instead.
templatefile("${path.module}/templates/handler.js", {
  ENDPOINT = var.domain
  PASSWORD = var.password
})

The error message you saw suggests that there's a syntax error in your template itself, but because template_file is implemented in a separate provider it's reporting that syntax error in an unhelpful way, pointing to a particular source location but not including the relevant source code snippet.
If you use templatefile instead, Terraform can hopefully report this syntax error itself and give better information about it.
Either way, it seems like the syntax error is on line 280 column 49 of your handler.js file and is caused by Terraform's template engine expecting to find the } to close a ${ ... } interpolation sequence but finding something else instead. If you correct that syntax error, template rendering should succeed by either approach.


text:
Q: Can't call a nested navigation screen from a deep component in react native I have followed this tutorial and created Drawer and Main Tab Navigations for my react native expo app.
Now I need a screen which should not be listed in Drawer or Tab and which is needed to be called from a deep component where navigations props are not being sent.
I tried useNavigation Hook but got error where react native is unable to find any such screen name.
PFB the tentative sample codes:
Main Tab called from App.js
const Tab = createMaterialBottomTabNavigator();
const HomeStack = createStackNavigator();
const ProfileStack = createStackNavigator();
const ListStack = createStackNavigator();

const MainTabScreen = () => (
    <Tab.Navigator
      initialRouteName="Home"
      activeColor="#fff"
      barStyle={{ backgroundColor: '#009387' }}
    >
      <Tab.Screen
        name="Home"
        component={HomeStackScreen}
        options={{
          tabBarLabel: 'Home',
          tabBarColor: '#009387',
          tabBarIcon: ({ color }) => (
            <Icon name="home" color={color} size={26} />
          ),
        }}
      />
      <Tab.Screen
        name="Profile"
        component={ProfileStackScreen}
        options={{
          tabBarLabel: 'Profile',
          tabBarColor: '#1f65ff',
          tabBarIcon: ({ color }) => (
            <Icon name="aperture" color={color} size={26} />
          ),
        }}
      />
</Tab.Navigator>
);

export default MainTabScreen;

const HomeStackScreen = ({navigation}) => (
  <HomeStack.Navigator screenOptions={{
    headerStyle: {
      backgroundColor: '#009387',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold'
    }
  }}>
    <HomeStack.Screen name = "Home" component = {Home}
    options = {{
      title: 'Overview',
      headerLeft: () => (
        <Icon.Button name="menu" size={25}
        backgroundColor="#009387" onPress={()=>navigation.openDrawer()}
        ></Icon.Button>
        )
    }}
    />
  </HomeStack.Navigator>
);

const ProfileStackScreen = ({navigation}) => (
  <ProfileStack.Navigator screenOptions={{
    headerStyle: {
      backgroundColor: '#d02860',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold'
    }
  }}>
    <ProfileStack.Screen name = "Profile" component = {Profile}
    options = {{
      headerLeft: () => (
        <Icon.Button name="menu" size={25}
        backgroundColor="#d02860" onPress={()=>navigation.openDrawer()}
        ></Icon.Button>
        )
    }}
    />
  </ProfileStack.Navigator>
);

const ListStackScreen = ({navigation}) => (
  <NotificationsStack.Navigator screenOptions={{
    headerStyle: {
      backgroundColor: '#694fad',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold'
    }
  }}>
    <ListStack.Screen name = "List" component = {List}
    options = {{
      headerLeft: () => (
        <Icon.Button name="menu" size={25}
        backgroundColor="#694fad" onPress={()=>navigation.openDrawer()}
        ></Icon.Button>
        )
    }}
    />
  </NotificationsStack.Navigator>
);

useNavigation component section:
import { useNavigation } from '@react-navigation/native';
.
.
.
const SomeStuff = ({item}) => {
......
<ListButton title={Count} screenName="ListStackScreen" />
.....
}
.
.

function ListButton({ title, screenName }) {
  const navigation = useNavigation();

  return (
    <Button
      title={`${title} Total`}
      onPress={() => navigation.navigate(screenName)}
    />
  );
}

also tried:
navigation.navigate('HomeDrawer',{screen: screenName})

I need to call the above ListStackScreen from a deep component. I tried using navigation.navigate(ListStackScreen) but it doesn't work as explained above.
Please let me know how to use the screen without displaying it in any Drawer or Tab visually.
Edit: Update after trying the given answer

I do have this in the main app.js also:
<Drawer.Screen name="HomeDrawer" component={MainTabScreen} />

A: This setup should allow you to navigate between HomeStackScreen and ListStackScreen.
const Stack = createStackNavigator();

function HomeStack() {
  return (
    <Stack.Navigator
      initialRouteName="HomeStackScreen">
      <Stack.Screen
        name="HomeStackScreen"
        component={HomeStackScreen}
      />
      <Stack.Screen
        name="ListStackScreen"
        component={ListStackScreen}
      />
    </Stack.Navigator>
  );
}

    <NavigationContainer>
      <Tab.Navigator
        initialRouteName="HomeStack">
        <Tab.Screen
          name="HomeStack"
          component={HomeStack}
          }}
        />
    …

You can nest stacknavigator into Drawer, the inner stacknavigator screen won't be shown in Drawer.
I have created an sample


text:
Q: Flex: change containers size to wrap the content I'm using TitleWindow with PopupManager.
I programmatically add the children to my TitleWindow and I would like the TitleWindow changing its size in order to avoid scroll-bars.
Is there any property to mek the windows wrapping the content in Flex ?
thanks

A: The way I do this is to give it a minHeight and minWidth, but no height or width properties. That way it shrinks to fit the content.
Be careful, though. If you have too much content it can go off the screen, so set a maxHeight and maxWidth. Or else resize title window based on screen loc and dimensions. Then you still have to handle scrollbars, but it happens much less often.


text:
Q: Программа суммирования чисел выдает ошибку package com.company;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    int n = 0;
    int S = 0;
    String current = "";

    System.out.println("Введите количество чисел для суммирования");
    n = sc.nextInt();

    System.out.println("Введите числа для суммирования");
    current = sc.nextLine();

    ArrayList<String> row = new  ArrayList<String>(Arrays.asList(current.split(" ")));

    ArrayList <Integer> introw = new ArrayList <Integer>();

    for (int i = 0; i < row.size(); i++) {
        introw.add(Integer.parseInt(row.get(i)));
    }

    for (int i = 0; i < introw.size(); i++) {
        S = S + introw.get(i);
    }

    System.out.println("Сумма S = " + S);
}
}

Скриншот ошибки:

A: nextInt() - считывает значение до перевода каретки \n, таким образом nextLine считывает именно его (этот самый перевод каретки).
В итоге либо надо писать nextLine() даже на первой строке и уже потом конвертировать через parseInt(), либо добавить еще один nextLine() после nextInt()

A: Метод nextInt() просто читает первое числовое значение из входного потока, но не "переводит" сканер на следующую строку - после этого вызов nextLine() читает всё, что осталось в текущей строке (а там уже ничего не осталось).
Самое простое решение - добавить ещё один вызов sc.nextLine(); сразу после чтения первого числа и прочитать потом уже следующую строку.

A: import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Введите числа для суммирования: ");
        String current = sc.nextLine();

        boolean prevIsDigit=false;
        StringBuilder sb = new StringBuilder();
        for (char ch : current.toCharArray()) {
            if (Character.isDigit(ch)) {
                sb.append(ch);
                prevIsDigit=true;
            }
            else if (prevIsDigit) {
                sb.append("@");
                prevIsDigit=false;
            }
        }

        int result = 0;
        for (String s : sb.toString().split("@")) result+=Integer.valueOf(s);

        System.out.println("Сумма S = " + result);
    }

}


text:
Q: multilevel corresponding dropdown in codeigniter i have a table with columns id, stud_id, stud_name, stud_email, marks. I want a form with 3 drop-down stud_id, stud_name, stud_email. if anyone select any one of the drop-down the others should fill automatically according to the selected field from database. Thanks in Advance.
i want something like this but with a single table
 http://www.91weblessons.com/codeigniter-ajax-country-state-city-drop-down/

A: You didn't post any specifics so my answer can only be general, but so I'll just give you the logical flow of the process:

*

*Javascript that watches the dropdowns for changes. If you have 3 dropdowns, you'll have to watch the first two.  If you use jquery, it'll be something like:  $('first_dropdown').change({//your ajax call goes here})

*Your ajax call. From inside the watch function mentioned above, create an ajax script that calls a php function that gets the data you want to populate the next dropdown. We're not done with this script though, we'll come back to it later.

*In your controller, call a function in your model like get_all_stud() and use that to get whatever data you need to populate the dropdown, and echo that data as json.

*Now that your controller has returned data to the ajax function we can use it to populate the dropdown. Iterate the object and do something like $('second_dropdown).append({<option>//your data here</option>})
And then you'll repeat the whole thing so that the third dropdown watches for changes on the second dropdown


text:
Q: Why does this process not give me all solutions to $y'=ty^{\frac{1}{2}},\;\;\; y(0)=0$? I have the following differential equation

$$y'=ty^{\frac{1}{2}},\;\;\; y(0)=0 \tag{1}\label{1}$$

My question is: why does the following process not give me all the solutions for ($\ref{1}$)?

My process
$$(1)\implies y'y^{-\frac{1}{2}}=t\iff \int y^{-\frac{1}{2}}y'dt=\int tdt \tag{2}\label{2}$$
let $u=y$ then $du=y'dt$ so
$$(\ref{2}) \implies \int u^{-\frac{1}{2}}du=\frac{t^2}{2}+c$$
$$\implies 2\sqrt{y}=\frac{t^2}{2}+c$$
$$\implies y=\left(\left(\frac{t}{2}\right)^2+c\right)^2$$
but $y(0)=0$ so $c=0$. So we end with the solution
$$y=\left(\frac{t^2}{4}\right)^2.$$

My problem is that, if we let $a>0$ the functions
$$y(t) =
     \begin{cases}
       0 & |t|<a\\
       \left(\frac{t^2-a^2}{4}\right)^2 &|t|\geq a \\
     \end{cases}$$
all satisfy equation ($\ref{1}$) yet none of them came from my process.
Why is it that my process doesn't give me all the solutions? Is there a way to know if I have found all the solutions to an equation? Is there a systematic way of finding them?

A: $y(t)=0$ is obviously a solution.
The $y$-derivative does not exist at $y=0$, there is no local Lipschitz condition, so no enforced uniqueness from the Picard-Lindelöf theorem.
The solution that you found shows that the zero solution can be connected to non-zero values in finite time along solution branches. Everything starting between two of these branches must run into one of these solution when moving in direction of the branching point, so you get an infinity of branches.
Between uniqueness via Lipschitz and obvious branching there exist intermediary situations that have to be treated individually. The main points to explore is if the singular curve is a solution at all, and if it can be reached in finite time from points not on it.


text:
Q: How do I join four MySQL tables in one statement This is my current statement without join
$s1 = "SELECT *
      FROM states
      WHERE
      statecode='".intval($getStateCode)."'
      ";

$s2 = "SELECT *
      FROM county
      WHERE
      statecode='".intval($getStateCode)."'
      AND
      countycode='".intval($getCountyCode)."'
      ";

$s3 = "SELECT *
      FROM town
      WHERE
      statecode='".intval($getStateCode)."'
      AND
      countycode='".intval($getCountyCode)."'
      AND
      towncode='".intval($getTownCode)."'";

$s4 = "SELECT *
      FROM villages
      WHERE
      statecode='".intval($getStateCode)."'
      AND
      countycode='".intval($getCountyCode)."'
      AND
      towncode='".intval($getTownCode)."'
      AND
      villagecode='".intval($getVillageCode)."'";

It's possible to join all of my tables in one statement? Let me know.

A: <?php
$query = "SELECT *
FROM state s
JOIN county c ON s.statecode = c.statecode
JOIN town t ON s.statecode = t.statecode AND c.countycode = t.countycode
JOIN villages v ON s.statecode = v.statecode AND c.countycode = v.countycode AND t.towncode = v.towncode
WHERE
      s.statecode='".intval($getStateCode)."'
      AND
      c.countycode='".intval($getCountyCode)."'
      AND
      t.towncode='".intval($getTownCode)."'
      AND
      v.villagecode='".intval($getVillageCode)."'";

A: This should get you started:
SELECT * FROM state s
INNER JOIN county c ON c.statecode = s.statecode
INNER JOIN town t ON t.statecode = s.statecode AND t.countycode = c.countycode
INNER JOIN villages v ON v.statecode = s.statecode AND v.countycode = c.countycode AND v.towncode = t.towncode

A: You might try this:
$sql = "select * from villages V
    join town T on T.towncode=V.towncode
    join county C on C.countycode=V.countycode
    join state S on S.statecode=V.statecode
    where V.statecode='".intval($getStateCode)."'
    and V.countycode='".intval($getCountyCode)."'
    and V.towncode='".intval($getTownCode)."'
    and V.villagecode='".intval($getVillageCode)."'";


text:
Q: Can't update cordova plugin after first install via plugman I'm developing a Cordova plugin.
Versions:

*

*cordova: 6.4.0

*plugman: 1.4.0

I install the plugin into a sample project I've created, like so:
plugman install --platform android --project ../cordova-echo-example-app/platforms/android --plugin .
The plugin installs into the project successfully, and I can build my sample app.
I change some code, and try to update the plugin again using the same above command, and I get the following error:
Cannot find plugin.xml for plugin "plugins". Please try adding it again.
I tried to uninstall the plugin, then install again, but still get the same error.
If I delete the platforms/ directory from my sample app, I'm able to install the plugin again.  I'd like to not have to do this step every time though.
Here's what my plugin.xml file looks like:
<?xml version='1.0' encoding='utf-8'?>
<plugin id="cordova-echo-example-plugin" version="0.0.1"
  xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
  <name>cordova-echo-example-plugin</name>
  <js-module name="cordova-echo-example-plugin" src="www/echo.js">
    <clobbers target="cordova.plugins.cordova-echo-example-plugin"/>
  </js-module>
  <platform name="android">
    <config-file parent="/*" target="res/xml/config.xml">
      <feature name="Echo">
        <param name="android-package" value="com.jonworek.echo"/>
      </feature>
    </config-file>
    <config-file parent="/*" target="AndroidManifest.xml"></config-file>
    <source-file src="src/android/Echo.java" target-dir="src/com/jonworek/echo"/>
  </platform>
</plugin>

How can I update my plugin in my sample project without going through these steps and avoiding that error?

A: It looks like plugman didn't like the . path reference for the --plugin parameter when it tries to reinstall.  Changing the command to:
plugman install --platform android --project ../cordova-echo-example-app/platforms/android/ --plugin ../cordova-echo-example-plugin/
solved the issue.


text:
Q: Differentiation of multiple domain hosted on same server Suppose that a server (which has ip address 123.123.123.123) is hosting 4 domains named abc.xyz, abc.abc, xyz.abc, xyz.xyz. If I do ping any of the websites I will get ip address 123.123.123.123 (since the dns name of the domains are same ip address). But when someone requests from browser to fetch contents from abc.xyz , in the data packet browser sends only the ip address. So how the server side differentiates which of the domain is requested by the user?

A: As you OS is Windows  Look at  C:\Windows\System32\drivers\etc\hosts  in there will contains the mappings of IP addresses to host names that browser resolve
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost


text:
Q: how to combine two columns in SQL Server 2005 I am having some issues combining two columns in the same table in SQL Server 2005
select cast( FirstName as varchar)+'-'+cast( secondName as varchar)
from table

how to I remove any spaces between the two fields

A: Presumably, the names are already strings, so conversion is useless.
If you have unnecessary spaces, remove them with ltrim() and rtrim():
select ltrim(rtrim(firstname)) + '-' + ltrim(rtrim(lastname))


text:
Q: JavaScript: if variables display:none then I'm trying to see if all variables have display: none and if so, show var slide0.
However, the code is only working with var slide8, if it is active (display:block) var slide0 does not appear. Otherwise, if the other variables are active, they remain active and var slide0 appears when it shouldn't.
What am I doing wrong?
    var slide0 = document.querySelector('#slideshow-zero');
    var slide1 = document.querySelector('#slideshow-one');
    var slide2 = document.querySelector('#slideshow-two');
    var slide3 = document.querySelector('#slideshow-three');
    var slide4 = document.querySelector('#slideshow-four');
    var slide5 = document.querySelector('#slideshow-five');
    var slide6 = document.querySelector('#slideshow-six');
    var slide7 = document.querySelector('#slideshow-seven');
    var slide8 = document.querySelector('#slideshow-eight');

    var slides = [slide0, slide1, slide2, slide3, slide4, slide5, slide6, slide7, slide8];

    for (var i = 0; i < slides.length; i++){
    if (slides[i].style.display === "none") {
        slide0.style.display = "block";
    } else {
        slide0.style.display = "none";
    }
}

A: if(!slides.find(slide => slide.style.display !== "none")){
    slide0.style.display = "block"
} else {
    if(slide0.style.display !== "block") {
       slide0.style.display = "none"
    }
}


text:
Q: Social media icons are not aligning Making a footer with social media icons and the images are entered but one is oddly higher than the other. Not sure how to fix it :(. Here is my html code:

<img src="facebook-box-fill.png" alt="Facebook"

<img src="instagram-fill.png" alt="Instagram"

And the external CSS code:
.socials  {
  display: flex;
  align-items: center;
  justify-content: center;
 }
.socials img  {
  width: 50px;
  height: 50px;
  }
.socials a  {
  text-decoration: none;
  }
.socials li {
  list-style-type: none;
  }
.socials a:hover {
  color: red;
  }

Here's a picture of how it looks rn
All advice and help will be appreciated, thanks in advance :).

A: It is probably because of your typos. "align-items;" "items:","text-decorations","text-decoration"

A: Looks like there might be some typos in your css. Align-items; center; should be: align-items: center;. Also Text-decorations is not a css property, it's text-decoration.
Try that out. (FYI, it's not generally common to capitalize css properties, I'd change those all to lowercase.)

A: .socials {
    align-items:center;
    justify-content:center;
   }

Try this css snippet and make the following changes. You had given semicolon in align-items. In addition, typo error is there so write down in small-case.


text:
Q: Pandas errors in writing chunks to database with df.to_sql() Existing Database and Desired Outcome:
I have a larger SQLite database (12gb, tables with 44 million+ rows) that I would like to modify using Pandas in Python3.

Example Objective: I hope to read one of these large tables (44 million rows) into a DF in chunks, manipulate the DF chunk, and write the result to a new table. If possible, I would like to replace the new table if it exists, and append each chunk to it.
Because my manipulations only add or modify columns, the new table should have the same number of rows as the original table.

Issues:
The primary issue seems to stem from the following line in the below code:
df.to_sql(new_table, con=db, if_exists = "append", index=False)

*

*When this line is run in the below code, I seem to consistently get an additional chunk of size=N, plus one observation than I expected.

*The first time this code runs with a new table name, I get an error:

 Traceback (most recent call last):
  File "example.py", line 23, in <module>
    for df in df_generator:
  File "/usr/local/lib/python3.5/site-packages/pandas/io/sql.py", line 1420, in _query_iterator
    data = cursor.fetchmany(chunksize)
sqlite3.OperationalError: SQL logic error or missing database

*If I then rerun the script, with the same new table name, it runs for each chunk, and an extra chunk, +1 row.

*When the df.to_sql() line is commented out, the loop runs for the expected number of chunks.
Test Example of Issue with Complete Code:
Complete Code: example.py

import pandas as pd
import sqlite3

#Helper Functions Used in Example
def ren(invar, outvar, df):
    df.rename(columns={invar:outvar}, inplace=True)
    return(df)

def count_result(c, table):
    ([print("[*] total: {:,} rows in {} table"
        .format(r[0], table))
        for r in c.execute("SELECT COUNT(*) FROM {};".format(table))])

#Connect to Data
db = sqlite3.connect("test.db")
c = db.cursor()
new_table = "new_table"

#Load Data in Chunks
df_generator = pd.read_sql_query("select * from test_table limit 10000;", con=db, chunksize = 5000)

for df in df_generator:
    #Functions to modify data, example
    df = ren("name", "renamed_name", df)
    print(df.shape)
    df.to_sql(new_table, con=db, if_exists = "append", index=False)

#Count if new table is created
try:
    count_result(c, new_table)
except:
    pass

1. Result when
#df.to_sql(new_table, con=db, if_exists = "append", index=False)
(the problem line is commented out):

$ python3 example.py
(5000, 22)
(5000, 22)

Which I expect since the example code limits my large table to 10k rows.

2. Result when
df.to_sql(new_table, con=db, if_exists = "append", index=False)
a. the problem line is not commented out
b. this is the first time the code is run with a new_table:

$ python3 example.py
(5000, 22)
Traceback (most recent call last):
  File "example.py", line 23, in <module>
    for df in df_generator:
  File "/usr/local/lib/python3.5/site-packages/pandas/io/sql.py", line 1420, in _query_iterator
    data = cursor.fetchmany(chunksize)
sqlite3.OperationalError: SQL logic error or missing database

3. Result when
df.to_sql(new_table, con=db, if_exists = "append", index=False)
a. the problem line is not commented out
b. the above code is run a second time with the new_table:

$ python3 example.py
(5000, 22)
(5000, 22)
(5000, 22)
(1, 22)
[*] total: 20,001 rows in new_table table

Thus, I have the issue of first the code breaking when run the first time (Result 2) and second, the total number of rows when run the second time (Result 3) is more than double what I expected.
Any suggestions on how I can solve this issue would be greatly appreciated.

A: You may try to specify:
db = sqlite3.connect("test.db", isolation_level=None)
#  ---->                        ^^^^^^^^^^^^^^^^^^^^

Beside that you may try to increase your chunksize, because otherwise the time between commits is way to short for SQLite DB - that is causing this error, i guess... I would also recommend to use PostgreSQL, MySQL/MariaDB or something similar - they are much more reliable and appropriate for such DB size...

A: Time Delay in Above Solution
@MaxU's solution adding isolation_level=None to the database connection is short and sweet. For whichever reason, however, it slowed writing/committing each chunk to the database dramatically. For example, when I tested the solution on a table of 12 million rows, the code took over 6 hours to complete. Conversely, building the original table from several text files took a few minutes.

This insight led to a faster but less elegant solution, which took less than 7 minutes to complete on a table of 12 million rows versus over 6 hours. The output rows matched the input rows, solving the problem in my original question.

Faster but less Elegant Solution
Since constructing the original table from text files/csv files and using SQL scripts to load the data, I combined that approach with Panda's chunk capabilities. The essential basic steps are as follows:

*

*Connect to the db

*Use a SQL script to create a new table (columns and order should match whatever you do to the pandas df)

*Read the massive table in chunks

*For each chunk, modify the df as desired, write to csv, load csv using sql, and commit the change.

Main code of solution:
import pandas as pd
import sqlite3

#Note I Used Functions I Wrote in build_db.py
#(shown below after example solution)
from build_db import *

#Helper Functions Used in Example
def lower_var(var, df):
    s = df[var].str.lower()
    df = df.drop(var, axis=1)
    df = pd.concat([df, s], axis=1)
    return(df)

#Connect to Data
db = sqlite3.connect("test.db")
c = db.cursor()

#create statement
create_table(c, "create_test.sql", path='sql_clean/')

#Load Data in Chunks
df_generator = pd.read_sql_query("select * from example_table;", con=db, chunksize = 100000)

for df in df_generator:
    #functions to modify data, example
    df = lower_var("name", df) #changes column order

    #restore df to column order in sql table
    db_order = ["cmte_id", "amndt_ind", "rpt_tp", "transaction_pgi", "image_num", "transaction_tp", \
        "entity_tp", "name", "city", "state", "zip_code", "employer", "occupation", "transaction_dt", \
        "transaction_amt", "other_id", "tran_id", "file_num", "memo_cd", "memo_text", "sub_id"]
    df = df[db_order]

    #write chunk to csv
    file = "df_chunk.csv"
    df.to_csv(file, sep='|', header=None, index=False)

    #insert chunk csv to db
    insert_file_into_table(c, "insert_test.sql", file, '|', path='sql_clean/')
    db.commit()

#Count results
count_result(c, "test_indiv")

Imported User Functions for Above Code
#Relavant Functions in build_db.py

def count_result(c, table):
    ([print("[*] total: {:,} rows in {} table"
        .format(r[0], table))
        for r in c.execute("SELECT COUNT(*) FROM {};".format(table))])

def create_table(cursor, sql_script, path='sql/'):
    print("[*] create table with {}{}".format(path, sql_script))
    qry = open("{}{}".format(path, sql_script), 'rU').read()
    cursor.executescript(qry)

def insert_file_into_table(cursor, sql_script, file, sep=',', path='sql/'):
    print("[*] inserting {} into table with {}{}".format(file, path, sql_script))
    qry = open("{}{}".format(path, sql_script), 'rU').read()
    fileObj = open(file, 'rU', encoding='latin-1')
    csvReader = csv.reader(fileObj, delimiter=sep, quotechar='"')

    try:
        for row in csvReader:
            try:
                cursor.execute(qry, row)
            except sqlite3.IntegrityError as e:
                pass

    except Exception as e:
        print("[*] error while processing file: {}, error code: {}".format(file, e))
        print("[*] sed replacing null bytes in file: {}".format(file))
        sed_replace_null(file, "clean_null.sh")
        subprocess.call("bash clean_null.sh", shell=True)

        try:
            print("[*] inserting {} into table with {}{}".format(file, path, sql_script))
            fileObj = open(file, 'rU', encoding='latin-1')
            csvReader = csv.reader(fileObj, delimiter=sep, quotechar='"')
            for row in csvReader:
                try:
                    cursor.execute(qry, row)
                except sqlite3.IntegrityError as e:
                    pass
                    print(e)

        except Exception as e:
            print("[*] error while processing file: {}, error code: {}".format(file, e))

SQL User Scripts
--create_test.sql

DROP TABLE if exists test_indiv;

CREATE TABLE test_indiv (
    cmte_id TEXT NOT NULL,
    amndt_ind TEXT,
    rpt_tp TEXT,
    transaction_pgi TEXT,
    image_num TEXT,
    transaction_tp TEXT,
    entity_tp TEXT,
    name TEXT,
    city TEXT,
    state TEXT,
    zip_code TEXT,
    employer TEXT,
    occupation TEXT,
    transaction_dt TEXT,
    transaction_amt TEXT,
    other_id TEXT,
    tran_id TEXT,
    file_num NUMERIC,
    memo_cd TEXT,
    memo_text TEXT,
    sub_id NUMERIC NOT NULL
);

CREATE UNIQUE INDEX idx_test_indiv ON test_indiv (sub_id);

--insert_test.sql

INSERT INTO test_indiv (
    cmte_id,
    amndt_ind,
    rpt_tp,
    transaction_pgi,
    image_num,
    transaction_tp,
    entity_tp,
    name,
    city,
    state,
    zip_code,
    employer,
    occupation,
    transaction_dt,
    transaction_amt,
    other_id,
    tran_id,
    file_num,
    memo_cd,
    memo_text,
    sub_id
    )
VALUES (
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?
);

A: Experienced the exact same problem (dealing with > 30 GB data). Here is how I tackled the problem:
Instead of using the Chunk feature of read_sql. I decided to create a manual chunk looper like so:
chunksize=chunk_size
offset=0
for _ in range(0, a_big_number):
    query = "SELECT * FROM the_table %s offset %s" %(chunksize, offset)
    df = pd.read_sql(query, conn)
    if len(df)!=0:
        ....
    else:
        break


text:
Q: i cannot access the value inside a function Here is my code :
let namesList = ref([]);

const GetFormData = (payload) => {
  return new Promise((resolve, reject) => {
    api
      .get("api.php", { params: { search: payload } })
      .then((response) => {
        data.value = response.data;

        // console.log(data.value);
        // convert array objects to array strings
        namesList = data.value.map(function (list) {
          return list["first_name"];
        });
        // console.log(namesList);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

If I console the namelist inside the function it returns the value :
(9) ['Michael Angelodfsed', 'Mardin', 'Joemar', 'Chirs', 'chan', 'loys', 'Lorena', 'kayabusa', 'kayabusa']
0: "Michael Angelodfsed"
1: "Mardin"
2: "Joemar"
3: "Chirs"
4: "chan"
5: "loys"
6: "Lorena"
7: "kayabusa"
8: "kayabusa"
length: 9
[[Prototype]]: Array(0)

but if I console the variable outside the function it gives me this console.log(nameList);
RefImpl {__v_isShallow: false, dep: undefined, __v_isRef: true, _rawValue: Array(0), _value: Proxy}
dep: Set(1) {ReactiveEffect}
__v_isRef: true
__v_isShallow: false
_rawValue: []
_value: Proxy
[[Handler]]: Object
[[Target]]: Array(0)
[[IsRevoked]]: false
value: (...)
[[Prototype]]: Object

please help me guys. really struggling here. really appreciate your help.

A: Follow this:
consf nameList = ref([])

console.log(nameList.value) // get value
nameList.value = ["Shin"] // set value

A: As @Deepak stated, you are trying to access the variable before the function (the api call) ends.
Your namesList is a ref object, so when you log it before it ends, it logs the object.
As your function is calling an api and use a Promise, you can change your function code to this:
const GetFormData = (payload) => {
  return new Promise((resolve, reject) => {
    api
      .get("api.php", { params: { search: payload } })
      .then((response) => {
        data.value = response.data;

        // console.log(data.value);
        // convert array objects to array strings
        namesList = data.value.map(function (list) {
          return list["first_name"];
        });
        // console.log(namesList);
        resolve(namesList);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

GetFormData(payload).then(data => console.log(data))


text:
Q: Как добавить уникальные свойства в название выпадающего списка? У меня есть такие массивы.
const A = [{category: "Walls", id: "1"}, {category: "Walls", id: "2"}];  //first array

const B = [{category: "Window", id: "3"}, {category: "Walls", id: "4"}]; //second array

const C = [{category: "Walls", id: "5"}, {category: "Floor", id: "6"}]; //three array

const D = [{category: "Walls", id: "5"}, {category: "Walls", id: "6"}]; //four array

Мне нужно создать такой список:

Walls
 <button class="A">1</button>
 <button class="A">2</button>
 <button class="B">4</button>
 <button class="B">5</button>
 <button class="C">5</button>
 <button class="D">6</button>

 Window
 <button class="B">3</button>

 Floor
 <button class="D">6</button>

Проблема в том, что я не разбираюсь, как мне добавить нужные данные из js массива на html страницу.
Буду очень благодарен за помощь.

A: надеюсь я правильно понял что Вам нужно)

const array = [
  {
    'category': [
      {
        'name': 'Walls',
        'items': [
          {
            'id': '1'
          },
          {
            'id': '2'
          }
        ]
      },
      {
        'name': 'Window',
        'items': [
          {
            'id': '3'
          },
          {
            'id': '4'
          }
        ]
      },
      {
        'name': 'Walls',
        'items': [
          {
            'id': '5'
          },
          {
            'id': '6'
          }
        ]
      },
      {
        'name': 'Walls',
        'items': [
          {
            'id': '7'
          },
          {
            'id': '8'
          }
        ]
      }
    ]
  }
]

array[0].category.map((category, index) => {
  const categoryNode = `

        ${category.name}

  `

  document.querySelector('#root').innerHTML += categoryNode;
});

[...document.querySelectorAll('details')].forEach(details => {
  const node = document.querySelector('#root');
  const detailsIndex = [...node.children].indexOf(details);

  array[0].category[detailsIndex].items.map((item, index) => {
    const itemNode = `
      <button class="${item.id}">${item.id}</button>
    `

    document.querySelectorAll('details')[detailsIndex].innerHTML += itemNode;
  });
});

A: Если немного изменить формат входных данных, то можно так сделать:

var mas = [{
    key: "A",
    "value": [{
        category: "Walls",
        family: "Basic Walls",
        id: "1"
      },
      {
        category: "Walls",
        family: "Basic Walls",
        id: "2"
      },
      {
        category: "Walls",
        family: "Second Walls",
        id: "22"
      },
      {
        category: "Walls",
        family: "Second Walls",
        id: "23"
      },
    ]
  },
  {
    key: "B",
    "value": [{
        category: "Window",
        family: "Basic Window",
        id: "3"
      },
      {
        category: "Walls",
        family: "Basic Walls",
        id: "4"
      }
    ]
  },
  {
    key: "C",
    "value": [{
        category: "Walls",
        family: "Basic Walls",
        id: "5"
      },
      {
        category: "Floor",
        family: "Basic Floor",
        id: "6"
      }
    ]
  },
  {
    key: "D",
    "value": [{
        category: "Walls",
        family: "Basic Walls",
        id: "5"
      },
      {
        category: "Walls",
        family: "Basic Walls",
        id: "6"
      }
    ]
  }
];

var newarr = [];
var output = {};

mas.forEach(function(element, key) {
  element.value.forEach(function(oneelement, onekey) {
    if (output[oneelement.category] === undefined) output[oneelement.category] = {};
    if (output[oneelement.category][oneelement.family] === undefined) output[oneelement.category][oneelement.family] = [];
    output[oneelement.category][oneelement.family].push({
      clas: element.key,
      val: oneelement.id
    });
  });
});

Object.keys(output).map(function(objectKey, index) {
  var category = output[objectKey];
  var caption = '' + objectKey + '';

  document.querySelector('.list').innerHTML += caption;

  var all = '';
  Object.keys(category).map(function(vaL, iX) {

    var summary = '' + vaL + '';
    document.querySelector('.list_' + index).innerHTML += summary;
    all = '';
    output[objectKey][vaL].forEach(function(val, key) {
      all = all + '<button class="' + val.clas + '">' + val.val + '</button>';
    });
    document.querySelector('.family_' + index + '_' + iX).innerHTML += all;
  });

});
body{font-family:tahoma;font-size:18px}
details details{margin-left:15px}
.list {max-width:400px;background:#eee;padding:15px}

PS: я изменил ответ под ваши требования, но хочу заметить, что это только для частного случая и как вы видите с каждым уровнем вложенности растет размер кода. На будущее советую вам - использовать плоские объекты в качестве входных данных.


text:
Q: Checking whether method is defined in *this* class I have the following piece of code. It is actually three separate scripts except I combined it together. The Main class is something  the two Test classes inherit. They may define an out method, which will do whatever the devs want. This is meant to be a plugin-style sort of design so that people can define their own out methods in their own classes, and then when my main program picks up one of those custom classes I can just say
some_test.run
And if they decided to implement an out method that will be executed.
Is there a better way to implement the run method so that I don't need to explicitly write self.class.method_defined?? The object could be any Test object and I don't want them to have to overwrite the run method to put their own class name in front of the method_defined? call.
class Main
  def run
    send(:out) if self.class.method_defined?(:out)
  end
end

class TestA < Main

  def out
    p "Test A here"
  end
end

class TestB < Main

  def out
    p "Test B here"
  end
end

a = TestA.new
a.run
# will execute a's out method

b = TestB.new
b.run
# will execute b's out method

A: I would just provide an empty out method in the parent class and allow subclasses to override it, just normal OO:
class Main
  def run
    out
  end

  def out
    #out will now always be defined
  end
end

You could also just use defined?:
class Main
  def run
    out if defined? out
  end
end

Note the argument to defined is out, not the symbol :out.
Or, more idiomatically, you can use respond_to?:
class Main
  def run
    out if respond_to? :out
  end
end


text:
Q: Special div shrinking How should I change CSS such way, that

*

*if width of screen > 1100px    then left nav width is constantly 555px, but empty -space is shrinking to 0 when width of screen = 1100px

*if width of screen < 1100px then left nav width is shrinking and empty -space div still is 0px.
Right part (div class=button and div class=right) remains unchanged

.wrapper {
  display: flex;
  margin: 0 auto;
  max-width: 1310px;
  font-size:0.6rem;
}
.wrapper .left {
  flex-basis: 555px;
  background-color: lightblue;
}

.left__nav {
  display: inline-block;
  padding: 5px;
  color: darkblue;
  text-decoration: none;
}

.empty-space {
  flex-basis: 100px;
  flex-shrink:1;
}
.wrapper .right {
  background-color: orange;

  flex-basis: 462px;
  display: flex;
  justify-content: flex-end; /*  align right (at end)  */
}
.wrapper .button {
  flex-basis: 193px;
  background-color: #3ab8a4;
  text-align:center;

}

/* style for this demo */
.wrapper > div {
  box-sizing: border-box;
  background-color: lightgray;
  border-collapse: collapse;
}
.mark-center {
  text-align: center;
  font-size: 30px;
  color: red;
}
.container-small {
  text-align: center;
  background-color: lightgray;
  max-width: 1100px;
  margin: auto;
  padding:1rem 0;

}

empty space

    Link3
    Left Nav

    Links right aligned

    Button

  ↑

  Some content

A: The simplest way to accomplish that is to add 2 wrappers, one for the left side and one for the right side, and with that you will be able to easily center where the left/right links wrapper meet.
Remove the
empty space
 element in the markup/CSS and instead, to create the empty space at the left in the left side, simply add margin-left: auto to the left_inner and it will be pushed to the right.
Stack snippet

.wrapper {
  display: flex;
  margin: 0 auto;
  max-width: 1310px;
  font-size: 0.6rem;
}

.wrapper .left,
.wrapper .right {
  flex-basis: 50%;
  display: flex;
}

.wrapper .left_inner {
  margin-left: auto;
  flex-basis: 555px;
  background-color: lightblue;
}
.wrapper .right_inner {
  flex-basis: 462px;
  background-color: orange;
  display: flex;
  justify-content: flex-end;      /*  align content right (at end)  */
}
.wrapper .button_inner {
  flex-basis: 193px;
  background-color: #3ab8a4;
  display: flex;
  justify-content: center;
  align-items: center;
}

.left__nav {
  display: inline-block;
  padding: 5px;
  color: darkblue;
  text-decoration: none;
}
.right__nav {
  display: inline-block;
  padding: 5px;
  color: darkred;
  text-decoration: none;
}

/* style for this demo */
.wrapper>div {
  box-sizing: border-box;
  background-color: lightgray;
  border-collapse: collapse;
}
.mark-center {
  text-align: center;
  font-size: 30px;
  color: red;
}
.container-small {
  text-align: center;
  background-color: lightgray;
  max-width: 1100px;
  margin: auto;
  padding: 1rem 0;
}

      Link left

      Link right

      Button

  ↑

  Some content

Updated
To be able to fullfil both above requirement and to stack them vertical, centered, on narrower screens, you need a media query or a script.
Here is an updated version using a media query for less than 1000px (max-width: 999px)
Stack snippet

.wrapper {
  display: flex;
  margin: 0 auto;
  max-width: 1310px;
  font-size: 0.6rem;
}

.wrapper .left,
.wrapper .right {
  flex-basis: 50%;
  display: flex;
}

.wrapper .left_inner {
  margin-left: auto;
  flex-basis: 555px;
  background-color: lightblue;
}
.wrapper .right_inner {
  flex-basis: 462px;
  background-color: orange;
  display: flex;
  justify-content: flex-end;      /*  align content right (at end)  */
}
.wrapper .button_inner {
  flex-basis: 193px;
  background-color: #3ab8a4;
  display: flex;
  justify-content: center;
  align-items: center;
}

.left__nav {
  display: inline-block;
  padding: 5px;
  color: darkblue;
  text-decoration: none;
}
.right__nav {
  display: inline-block;
  padding: 5px;
  color: darkred;
  text-decoration: none;
}

@media (max-width: 999px) {
  .wrapper,
  .wrapper .left,
  .wrapper .right {
    flex-basis: auto;
    flex-direction: column;
    align-items: center;
  }
  .wrapper .left_inner {
    flex-basis: auto;
    margin-left: 0;
  }
  .wrapper .right_inner,
  .wrapper .button_inner {
    flex-basis: auto;
  }
}

/* style for this demo */
.wrapper>div {
  box-sizing: border-box;
  background-color: lightgray;
  border-collapse: collapse;
}
.mark-center {
  text-align: center;
  font-size: 30px;
  color: red;
}
.container-small {
  text-align: center;
  background-color: lightgray;
  max-width: 1100px;
  margin: auto;
  padding: 1rem 0;
}

      Link left

      Link right

      Button

  ↑

  Some content

If you want the link and button wrapper to fill the width, give them a width and make their content center aligned.
Stack snippet

.wrapper {
  display: flex;
  margin: 0 auto;
  max-width: 1310px;
  font-size: 0.6rem;
}

.wrapper .left,
.wrapper .right {
  flex-basis: 50%;
  display: flex;
}

.wrapper .left_inner {
  margin-left: auto;
  flex-basis: 555px;
  background-color: lightblue;
}
.wrapper .right_inner {
  flex-basis: 462px;
  background-color: orange;
  display: flex;
  justify-content: flex-end;      /*  align content right (at end)  */
}
.wrapper .button_inner {
  flex-basis: 193px;
  background-color: #3ab8a4;
  display: flex;
  justify-content: center;
  align-items: center;
}

.left__nav {
  display: inline-block;
  padding: 5px;
  color: darkblue;
  text-decoration: none;
}
.right__nav {
  display: inline-block;
  padding: 5px;
  color: darkred;
  text-decoration: none;
}

@media (max-width: 999px) {
  .wrapper,
  .wrapper .left,
  .wrapper .right {
    flex-basis: auto;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
  }
  .wrapper .left_inner {
    flex-basis: auto;
    margin-left: 0;
    text-align: center;
    width: 100%;
  }
  .wrapper .right_inner,
  .wrapper .button_inner {
    flex-basis: auto;
    text-align: center;
    justify-content: center;
    width: 100%;
  }
}

/* style for this demo */
.wrapper>div {
  box-sizing: border-box;
  background-color: lightgray;
  border-collapse: collapse;
}
.mark-center {
  text-align: center;
  font-size: 30px;
  color: red;
}
.container-small {
  text-align: center;
  background-color: lightgray;
  max-width: 1100px;
  margin: auto;
  padding: 1rem 0;
}

      Link left

      Link right

      Button

  ↑

  Some content

A: Try using media queries:
 @media only screen and (max-width: 1100px) {
   /*your css code */
 }

 @media only screen and (min-width: 1100px) {
   /*your css code */
 }

Here's w3c schools link about media queries.
https://www.w3schools.com/css/css_rwd_mediaqueries.asp


text:
Q: Programmatically render Razor Page as HTML string Goal

*

*I'm trying to generate a HTML string on the backend as I want to
convert it to a PDF using a HtmlToPDF library.

*I also want to be able to easily see the generated HTML in the browser, for debugging/tweaking purposes. The page will only be public when IsDevelopment().

*I want it to be as simple as possible.

I'm using ASP.NET Core 3.1
Approach
Razor Page
I figured I'd try the new Razor Pages as they're advertised as super easy.
@page
@using MyProject.Pages.Pdf
@model IndexModel

Test

    @Model.Message

namespace MyProject.Pages.Pdf
{
    public class IndexModel : PageModel
    {
        private readonly MyDbContext _context;

        public IndexModel(MyDbContext context)
        {
            _context = context;
        }

        public string Message { get; private set; } = "PageModel in C#";

        public async Task<IActionResult> OnGetAsync()
        {
            var count = await _context.Foos.CountAsync();

            Message += $" Server time is { DateTime.Now } and the Foo count is { count }";

            return Page();
        }
    }
}

This works in the browser - yay!
Render and get HTML string
I found Render a Razor Page to string which appears to do what I want.
But this is where the trouble start :(
Problems
First off, I find it very odd that when you find the page via _razorViewEngine.FindPage it doesn't know how to populate the ViewContext or the Model. I'd think the job of IndexModel was to populate these. I was hoping it was possible to ask ASP.NET for the IndexModel Page and that would be that.
Anyway... the next problem. In order to render the Page I have to manually create a ViewContext and I have to supply it with a Model. But the Page is the Model, and since it's a Page it isn't a simple ViewModel. It rely on DI and it expects OnGetAsync() to be executed in order to populate the Model. It's pretty much a catch-22.
I also tried fetching the View instead of the Page via _razorViewEngine.FindView but that also requires a Model, so we're back to catch-22.
Another issue. The purpose of the debug/tweaking page was to easily see what was generated. But if I have to create a Model outside IndexModel then it's no longer representative of what is actually being generated in a service somewhere.
All this have me wondering if I'm even on the right path. Or am I missing something?

A: Please refer to the following steps to render A Partial View To A String:

*

*Add an interface to the Services folder named IRazorPartialToStringRenderer.cs.
 public interface IRazorPartialToStringRenderer
 {
     Task<string> RenderPartialToStringAsync<TModel>(string partialName, TModel model);
 }

*Add a C# class file to the Services folder named RazorPartialToStringRenderer.cs with the following code:
 using System;
 using System.IO;
 using System.Linq;
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc.Abstractions;
 using Microsoft.AspNetCore.Mvc.ModelBinding;
 using Microsoft.AspNetCore.Mvc.Razor;
 using Microsoft.AspNetCore.Mvc.Rendering;
 using Microsoft.AspNetCore.Mvc.ViewEngines;
 using Microsoft.AspNetCore.Mvc.ViewFeatures;
 using Microsoft.AspNetCore.Routing;

 namespace RazorPageSample.Services
 {
     public class RazorPartialToStringRenderer : IRazorPartialToStringRenderer
     {
         private IRazorViewEngine _viewEngine;
         private ITempDataProvider _tempDataProvider;
         private IServiceProvider _serviceProvider;
         public RazorPartialToStringRenderer(
             IRazorViewEngine viewEngine,
             ITempDataProvider tempDataProvider,
             IServiceProvider serviceProvider)
         {
             _viewEngine = viewEngine;
             _tempDataProvider = tempDataProvider;
             _serviceProvider = serviceProvider;
         }
         public async Task<string> RenderPartialToStringAsync<TModel>(string partialName, TModel model)
         {
             var actionContext = GetActionContext();
             var partial = FindView(actionContext, partialName);
             using (var output = new StringWriter())
             {
                 var viewContext = new ViewContext(
                     actionContext,
                     partial,
                     new ViewDataDictionary<TModel>(
                         metadataProvider: new EmptyModelMetadataProvider(),
                         modelState: new ModelStateDictionary())
                     {
                         Model = model
                     },
                     new TempDataDictionary(
                         actionContext.HttpContext,
                         _tempDataProvider),
                     output,
                     new HtmlHelperOptions()
                 );
                 await partial.RenderAsync(viewContext);
                 return output.ToString();
             }
         }
         private IView FindView(ActionContext actionContext, string partialName)
         {
             var getPartialResult = _viewEngine.GetView(null, partialName, false);
             if (getPartialResult.Success)
             {
                 return getPartialResult.View;
             }
             var findPartialResult = _viewEngine.FindView(actionContext, partialName, false);
             if (findPartialResult.Success)
             {
                 return findPartialResult.View;
             }
             var searchedLocations = getPartialResult.SearchedLocations.Concat(findPartialResult.SearchedLocations);
             var errorMessage = string.Join(
                 Environment.NewLine,
                 new[] { $"Unable to find partial '{partialName}'. The following locations were searched:" }.Concat(searchedLocations)); ;
             throw new InvalidOperationException(errorMessage);
         }
         private ActionContext GetActionContext()
         {
             var httpContext = new DefaultHttpContext
             {
                 RequestServices = _serviceProvider
             };
             return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
         }
     }
 }

*Register the services in the ConfigureServices method in the Startup class:
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddRazorPages();
     services.AddTransient<IRazorPartialToStringRenderer, RazorPartialToStringRenderer>();
 }

*Using the RenderPartialToStringAsync() method to render Razor Page as HTML string:
 public class ContactModel : PageModel
 {
     private readonly IRazorPartialToStringRenderer _renderer;
     public ContactModel(IRazorPartialToStringRenderer renderer)
     {
         _renderer = renderer;
     }
     public void OnGet()
     {
     }
     [BindProperty]
     public ContactForm ContactForm { get; set; }
     [TempData]
     public string PostResult { get; set; }

     public async Task<IActionResult> OnPostAsync()
     {
         var body = await _renderer.RenderPartialToStringAsync("_ContactEmailPartial", ContactForm);  //transfer model to the partial view, and then render the Partial view to string.
         PostResult = "Check your specified pickup directory";
         return RedirectToPage();
     }
 }
 public class ContactForm
 {
     public string Email { get; set; }
     public string Message { get; set; }
     public string Name { get; set; }
     public string Subject { get; set; }
     public Priority Priority { get; set; }
 }
 public enum Priority
 {
     Low, Medium, High
 }

The debug screenshot as below:

More detail steps, please check this blog Rendering A Partial View To A String.

A: I managed to crack it! I was on the wrong path after all... the solution is to use a ViewComponent. But it's still funky!
Thanks to

*

*Asp.Net Core render ViewComponent to variable

*https://github.com/jakakonda/View2String/blob/master/View2String/Services/ViewRendererService2.cs

*https://forums.asp.net/t/2132316.aspx?Render+ViewComponent+as+string+from+controller

*Render ViewComponent inside html string

*many more...

The Solution
Converted PageModel into ViewComponent
namespace MyProject.ViewComponents
{
    public class MyViewComponent : ViewComponent
    {
        private readonly MyDbContext _context;

        public MyViewComponent(MyDbContext context)
        {
            _context = context;
        }

        public async Task<IViewComponentResult> InvokeAsync()
        {
            var count = await _context.Foos.CountAsync();

            var message = $"Server time is { DateTime.Now } and the Foo count is { count }";

            return View<string>(message);
        }
    }
}

and the view is placed in Pages/Shared/Components/My/Default.cshtml
@model string

Test

    @Model

The Service
using System;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;

public class RenderViewComponentService
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ITempDataProvider _tempDataProvider;
    private readonly IViewComponentHelper _viewComponentHelper;

    public RenderViewComponentService(
        IServiceProvider serviceProvider,
        ITempDataProvider tempDataProvider,
        IViewComponentHelper viewComponentHelper
    )
    {
        _serviceProvider = serviceProvider;
        _tempDataProvider = tempDataProvider;
        _viewComponentHelper = viewComponentHelper;
    }

    public async Task<string> RenderViewComponentToStringAsync<TViewComponent>(object args)
        where TViewComponent : ViewComponent
    {
        var viewContext = GetFakeViewContext();
        (_viewComponentHelper as IViewContextAware).Contextualize(viewContext);

        var htmlContent = await _viewComponentHelper.InvokeAsync<TViewComponent>(args);
        using var stringWriter = new StringWriter();
        htmlContent.WriteTo(stringWriter, HtmlEncoder.Default);
        var html = stringWriter.ToString();

        return html;
    }

    private ViewContext GetFakeViewContext(ActionContext actionContext = null, TextWriter writer = null)
    {
        actionContext ??= GetFakeActionContext();
        var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
        var tempData = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider);

        var viewContext = new ViewContext(
            actionContext,
            NullView.Instance,
            viewData,
            tempData,
            writer ?? TextWriter.Null,
            new HtmlHelperOptions());

        return viewContext;
    }

    private ActionContext GetFakeActionContext()
    {
        var httpContext = new DefaultHttpContext
        {
            RequestServices = _serviceProvider,
        };

        var routeData = new RouteData();
        var actionDescriptor = new ActionDescriptor();

        return new ActionContext(httpContext, routeData, actionDescriptor);
    }

    private class NullView : IView
    {
        public static readonly NullView Instance = new NullView();
        public string Path => string.Empty;
        public Task RenderAsync(ViewContext context)
        {
            if (context == null) { throw new ArgumentNullException(nameof(context)); }
            return Task.CompletedTask;
        }
    }
}

Usage
From Razor Page (the debug/tweaking page)
Note there is no code behind file
@page
@using MyProject.ViewComponents

@await Component.InvokeAsync(typeof(MyViewComponent))

With RouteData
@page "{id}"
@using MyProject.ViewComponents

@await Component.InvokeAsync(typeof(MyViewComponent), RouteData.Values["id"])

From Controller
[HttpGet]
public async Task<IActionResult> Get()
{
    var html = await _renderViewComponentService
        .RenderViewComponentToStringAsync<MyViewComponent>();

    // do something with the html

    return Ok(new { html });
}

With FromRoute
[HttpGet("{id}")]
public async Task<IActionResult> Get([FromRoute] int id)
{
    var html = await _renderViewComponentService
        .RenderViewComponentToStringAsync<MyViewComponent>(id);

    // do something with the html

    return Ok(new { html });
}

The strange
It's very unfortunate that the injected IViewComponentHelper doesn't work out of the box.
So we have do this very unintuitive thing to make it work.
(_viewComponentHelper as IViewContextAware).Contextualize(viewContext);

which causes a cascade of odd things like the fake ActionContext and ViewContext which require a TextWriter but it isn't used for ANYTHING! In fact the hole ViewContext isn't used at all. It just needs to exist :(
Also the NullView... for some reason Microsoft.AspNetCore.Mvc.ViewFeatures.NullView is Internal so we basically have to copy/paste it into our own code.
Perhaps it'll be improved in the future.
Anyway: IMO this is simpler then using IRazorViewEngine which turns up in pretty much every web search :)


text:
Q: Does WP_Query 'responds' badly to empty arguments? I am covering several options in a single file, and loading posts via AJAX so I put in data attributes query variables: cat, tag_id, author, year and monthnum.
Based on what is present or not (if you're on category page the cat query variable will be some number, but tag_id will be empty for instance). Now the query looks like this:
$cat = ( isset( $_GET['cat'] ) && '' !== $_GET['cat'] ) ? sanitize_text_field( wp_unslash( $_GET['cat'] ) ) : ''; // Input var okay.
$tag = ( isset( $_GET['tag'] ) && '' !== $_GET['tag'] ) ? sanitize_text_field( wp_unslash( $_GET['tag'] ) ) : ''; // Input var okay.
$year = ( isset( $_GET['year'] ) && '' !== $_GET['year'] ) ? sanitize_text_field( wp_unslash( $_GET['year'] ) ) : ''; // Input var okay.
$month = ( isset( $_GET['month'] ) && '' !== $_GET['month'] ) ? sanitize_text_field( wp_unslash( $_GET['month'] ) ) : ''; // Input var okay.
$author = ( isset( $_GET['author'] ) && '' !== $_GET['author'] ) ? sanitize_text_field( wp_unslash( $_GET['author'] ) ) : ''; // Input var okay.
$post__not_in = ( isset( $_GET['post__not_in'] ) && '' !== $_GET['post__not_in'] ) ? sanitize_text_field( wp_unslash( $_GET['post__not_in'] ) ) : ''; // Input var okay.

$the_query = new WP_Query(array(
    'cat'          => $cat,
    'tag_id'       => $tag,
    'author'       => $author,
    'date_query' => array(
        array(
            'year'  => $year,
            'month' => $month,
        ),
    ),
    'post_status'  => 'publish',
    'post__not_in' => json_decode( $post__not_in, true ),
));

post__not_in is there to make sure that when I set the home page as a blog page, that I get the correct posts loaded (I had some issues with paged variable and sticky posts, and this solved that issue).
Now what I haven't found is, will having empty query arguments make the query slower?
Should I base my query arguments based on what variable is empty? Is this better thing to do than to just put it all in one array? Something tells me that this is better because there are less query variables and therefore the query is more specific?
Also when loading posts using AJAX, should I add no_found_rows => 1, because I'm not using pagination? This should make my query even more faster from what I've read.
Any advice is welcome :)

A: I would not write it the same way, because the more cluttered a query gets, the more likely it is to return unexpected results.
Here's how I'd handle your code:
$args = array(); // All your WP_Query args go here.

// You don't need to pass 'post_status' => 'publish' because that's default

// Replace all instances of [ isset && '' !== ] with !empty
if ( !empty( $_GET['cat'] ) )
    $args['cat'] = sanitize_text_field( wp_unslash( $_GET['cat'] ) );

if ( !empty( $_GET['tag'] ) )
    $args['tag_id'] = sanitize_text_field( wp_unslash( $_GET['tag'] ) );

if ( !empty( $_GET['year'] ) || !empty( $_GET['month'] ) ) {
    $date_query = array();
    if ( !empty( $_GET['year'] ) )
        $date_query['year'] = sanitize_text_field( wp_unslash( $_GET['year'] ) );
    if ( !empty( $_GET['month'] ) )
        $date_query['month'] = sanitize_text_field( wp_unslash( $_GET['month'] ) );
    $args['date_query'] = array( $date_query );
}

if ( !empty( $_GET['post__not_in'] ) )
     $args['post__not_in'] = sanitize_text_field( wp_unslash( $_GET['post__not_in'] ) );

$the_query = new WP_Query( $args );

It seems a little weird to me that you'd need to unslash paired with sanitize, but if you feel it's necessary, I'll leave it in for the time being, otherwise, I'd probably only run sanitize.
As it pertains to AJAX, I haven't personally used no_found_rows, so I can't speak to that.  The AJAX protocols I've written usually are paired with an input that has the current offset of "pages" of posts being shown.


text:
Q: How to call the generalization of arc length obtained by considering chains in metric space? Consider a metric space $(M, d)$ and a totally ordered set (chain) $X \subset M$
where $a \in M$ is "the initiating element with respect to chain $X$" in the sense that

*

*either $a \in X$ is the first element of chain $X$, i.e. $y \in X \implies a \leq y$,

*or else $a \notin X$;
and where $b \in M$ is "the concluding element with respect to chain $X$" in the sense that

*

*either $b \in X$ is the last element of chain $X$, i.e. $y \in X \implies y \leq b$,
in which case necessarily $b ~~/ \! \! \! \! \! \! \equiv a$,

*or else $b \notin X$, in which case $b$ is not necessarily distinct from $a$.
Note that such a chain $X$ (with "the terminating elements $a$, $b$" added if appropriate)
is not necessarily a curve (in the sense of "curve" as an image of a continuous function from a suitable interval of real numbers into the given metric space):
neither is the order topology (as the one obvious topology) of chain $X$ necessarily homeomorphic to an interval;
nor are "metric gaps" excluded (in a sense which is explicated below) thus possibly spoiling "epsilon-delta" evaluation of continuity.
For any particular $n$-element subset $$P_n \equiv \{ p_k \}_n \subset ((X \cup \{ a, b\}) \setminus \{a, b\})$$ the "$(n + 1)$-segment sum"
$$d[~a, p_1~] + \left( \sum_{k = 1}^{n - 1} d[~p_k, p_{(k + 1)}~] \right) + d[~p_n, b~] := s[~P_n~]$$
may be evaluated (where the expression on the right-hand side has been introduced as a mere abbreviation).
For the class $\mathscr P_n$ of all possible such $n$-element subsets of chain $X$ the supremum of all corresponding "$(n + 1)$-segment sum" values may be evaluated:
$${\text{sup}}_{(\mathscr P_n)}\big\{ P_n \in \mathscr P_n : s[~P_n~] \big\} := \sigma_n[~X_a^b~]$$
(again introducing a descriptive abbreviation on the right-hand side).
Finally, the supremum over all natural numbers $n \in \mathbb N$ may be evaluated:
$${\text{sup}}_{(\mathbb N)}\big\{ n \in \mathbb N : \sigma_n[~X_a^b~] \big\} := \ell_d[~X_a^b~]$$
(where the right-hand side abbreviation aims to display all parameters which were relevant for the evaluation).
(The notion of possible "metric gaps" mentioned above relates to evaluating such "$\ell$"-values for subchains of chain $X$, too, and determining their convergence and continuity or discontinuity with respect to the order topology of $X$.)
My question:
How to call the value $\ell_d[~X_a^b~]$, which is obtained as described for the given chain $X$ (with "the terminating elements $a$, $b$" added if appropriate), referring to the metric $d$ ?
Is it usual terminology to call it "arc length", even though the Wikipedia definitions on "arc" and hence on "arc length" seem to be concerned explicitly and only with curves, and therefore not with the general case described above
?
Or is it perhaps appropriate or even usual terminology to call it "chain length" ?


text:
Q: Thread exit callback I need to be able to inject some exit code for the current running thread. I have struggled with this one for a while, and i finally came up with a solution here is some code similar to what I am doing:
public static void injectThreadExitCallback(final Runnable callback) {
    final curr = Thread.currentThread();
    new Thread() {
        @Override
        public void run() {
            try {
                curr.join();
                callback.run();
            } catch (InterruptedException ex) {
                ... logging ...
            }
        }
    }.start();
}

It seems to work fine and does exactly what I'm wanting, my only concern is, if this causes any leaking or other undesired side effects, that i may not bee seeing.
or is this perfectly fine, if so this is pretty useful. I could see a simple library that can dynamically add exit code to existing threads.

A: You better do
new Thread () {
    @Override
    public void run () {
        try
        {
            // Thread logic here
        }
        finally
        {
            // Thread exit logic here
        }
    }
}.start ();

A: You can't possibly inject code into a running thread unless that thread is actively cooperating, like for example the Event Dispatch Thread in AWT, which at its root has a loop that takes Runnables off of a queue and executes them.
Your design may introduce data races into code that was previously single-threaded and thus had no concurrency issues.
Finally, the design wastes a precious system resource (a thread) to do nothing but wait for another thread to finish.
If you need this to patch up some existing code from the outside, then it may be the only option; if not, it would be better to provide an explicit mechanism for it that was more efficient.

A: You can move the callback.run(); after the catch block or in final block if you want to ensure that it is called anyways


text:
Q: Applying Backslash To A Variable (Not String.raw) I want to get newline character \n from a variable (char) which contains 'n'
I tried this:
`\\${char}`; // Not working, its 2 character not a newline character
'\' + char;  // Obviously this will not work

Did something, for example, String.applyBackslash() exist?

A: There isn't a method like that, no. :-) There are two ways to do it:

*

*A lookup table (object or Map) mapping n to \n, etc. (There aren't that many escape sequences.)

*eval, which is probably overkill but is okay if and only if you control the input sufficiently that you know it won't be used for malicious code injection.
Example of #1:

const mappings = Object.assign(Object.create(null), {
    '"': '"',
    "'": "'",
    "\\": "\\",
    b: "\b",
    f: "\f",
    n: "\n",
    r: "\r",
    t: "\t",
});
const stringToTreatLiterally = "Testing \\n1\\n2\\n3";
console.log(JSON.stringify(
    stringToTreatLiterally.replace(
        /\\(["'\\bfnrt])/g,
        (m, c) => `${mappings[c] || c}`
    )
));

If you want to handle \uNNNN or \u{NNNN}, they aren't that much more complicated, but you have to capture the number and use either String.fromCharCode or String.fromCodePoint to create the ersult.


text:
Q: Find the Number $N$ There is a number $N$  that if we add to him the number $100$ we take a square and if we add to him the number $168$ we take a square.Find this $N$
Any ideas would be apreciated for this puzzle

A: See that $N+100=A^2$ and $N+168=B^2$ for some $A$ and $B$, so $68=B^2-A^2=(B-A)(B+A).$ As $68=17\times 2^2$ it doesn't let a lot of choices for $B-A$ and $B+A,$ and by checking some cases you find $A=16, B=18$ and so $N=156.$

A: Let $s^2 = N+168$ and $t^2 = N+100$.  Then $(s+t)(s-t) = s^2 - t^2 = 68 = 2\cdot 2 \cdot 17$.  The choices for $s-t$ give $s=t+1, s=t+2, s=t+4, s=t+17, s=t+34, s=t+68$.  (Restricting to positive integers because $\pm s$ and $\pm t$ work for any working choice of $s$ and $t$...)

*

*If $s = t+1$, then we started with $(t+1)^2 = N+168$ and subtracting $t^2 = N+100$, we are left with $2t+1 = 68$, which is impossible because the left side is odd and the right side is even.

*If $s = t+2$,  then $(t+2)^2 = N+168$ and after subtraction, we are left with $4t+4 = 68$, which is satisfied by $t = 18$, so $s = 16$ and $N=156$.

*If $s = t+4$,  then $(t+4)^2 = N+168$ and we are left with $8t+16 = 68$, which is unsatisfiable because $8$ does not divide $52$.

*If $s = t+17$,  then $(t+17)^2 = N+168$ and then $34t+389 = 68$, which is unsatisfiable because $34$ does not divide $-321$.  In fact this and the other choices cannot lead to positive $t$s, so we stop.

Having worked through the choices the only solution is $N = 156$.
Edit: Added a little more detail to the cases.


text:
Q: css buttons: forcing them to size themselves automatically i have these buttons on the top of the page:
HOME, BUYING PROPERTY, SELLING PROPERTY, COMMUNITY INFO ETC..

*

*i would like it so that when i add more buttons, they automatically size themselves and i dont have to resize each individual one.

*also i would like them to take up the entire top bar
here is the code
#cssmenu_moo_menu {
-moz-background-clip:border;
-moz-background-inline-policy:continuous;
-moz-background-origin:padding;
background-attachment:scroll;
background-color:#006198;
background-image:url(../images/moomenu.png);
background-position:50% top;
background-repeat:repeat-x;
float:left;
height:35px;
list-style-image:none;
list-style-position:outside;
list-style-type:none;
margin-bottom:0;
margin-left:0;
margin-right:0;
margin-top:0;
padding-bottom:0;
padding-left:0;
padding-right:0;
padding-top:0;
}

i am wondering if the following might be answering my question?
CSS Horizontal Navigation, Dynamic Width Buttons, 100% Width, Img Backgrounds

A: Some people might complain, but a table will size them automatically for you.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <title>Hi</title>

        <input type="button" value="Pick Me 1" style="width:100%;" />
        <input type="button" value="Pick Me 2" style="width:100%;" />
        <input type="button" value="Pick Me 3" style="width:100%;" />

Just add a new table data element for each new button.

A: This is not possible with pure CSS (on a semantic and crossbrowser-compatible manner, thus leaving respectively
 and display: table; outside). You'll have to bring some shot of JavaScript (jQuery?) in, which has however the caveat that this might lead to "wtf?" experiences as the enduser may see the items (or buttons as you call it) being resized on the fly while the page loads.
I would rather stick to altering the CSS on every add/remove of the item. Live with it.

A:

Home

Buying Property

Selling Property

Community Info

CSS:
ul#menu {
    list-style-type: none;
}

ul#menu li {
    float: left;
    margin-right: 1em;
    display: block;
}

ul#menu li a {
    padding: .2em;
    background: #CCC;
    /* etc */
}

.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}

* html .clearfix             { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */

EDIT:
Since there is no pure-CSS solution, it would be better to iterate through the menu-items with PHP:
$pages = array('Page 1' => 'page1.php', 'Page 2' => 'page2.php');
$numPages = count($pages);
$width = ceil(99/$numPages); // 99% is the maximum width, 100% could cause some problems with the last menu item
foreach($pages as $title => $link){
    echo '
' . $title . '
';
}


text:
Q: GoogleMap is moved when another view is hidden, Xamarin I have the following layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:id="@+id/root"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <fragment
    android:id="@+id/fragment_map"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true">
    <RelativeLayout
      android:id="@+id/rel_layout_location"
      android:layout_gravity="right"
      android:layout_margin="10dp"
      android:background="@drawable/white_circular_shadow"
      android:layout_width="60dp"
      android:layout_height="60dp">
      <ImageView
        android:background="@drawable/location"
        android:adjustViewBounds="true"
        android:layout_centerInParent="true"
        android:layout_width="20dp"
        android:layout_height="20dp" />
    </RelativeLayout>
    <RelativeLayout
      android:id="@+id/info_window_container"
      android:background="@color/white"
      android:visibility="gone"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" >
      <TextView
        android:padding="10dp"
        android:id="@+id/textview_title"
        android:text="How you doing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    </RelativeLayout>
  </LinearLayout>
</RelativeLayout>

I have access to the relativelayout:
relativelayout_info_container = FindViewById<RelativeLayout>(Resource.Id.info_window_container);

Everything is working fine, however when I try to hide the relative layout the map goes crazy (this is inside the MarkerClick):
googleMap.MarkerClick += MarkerClick;

then inside MarkerClick:
 relativelayout_info_container.Visibility = ViewStates.Gone;

It cancels the animation, it cancel the tapped marker function, it moves the map to the first location and zoom it was displayed like it has been reset.
Any ideas? If you need more information please let me know in the comments
UPDATE:
I just added another call to set padding to the map so it does not obscure the googlemap sign and the same problem occurs:
googleMap.SetPadding(0, 0, 0, <some_value>);

the change of the map padding is affecting changes I do to marker icons and camera updates inside MarkerClick

A: Completely irrelevant question. The problem really was in another part of my code. I had a ViewTreeObserver that was animating the map. Once I unsubscribed to it, everything just worked ;)


text: Q: Есть ли возможность сказать гуглу проиндексировать вложенные страницы в разделах, что б получить как на скрине? Есть ли возможность сказать гуглу проиндексировать вложенные страницы в разделах, что б получить как на скрине?


text:
Q: How to select two column merge lambda expression in c#? I want to connect to database and database table select merge the two column.And this column return this query should return the records I selected.
For Example;
Connection information
columns is:
Address City
Table Name: Address
Address: 2
City: B
I want to result:
Address+City:2B
Connection information2
columns is:
Address City
Table Name: Address
Address: 3
City: C
I want to result:
Address+City:3C
if 3c is entered, the value is 3c and I want to add it if it is in the 2nd database.
I'm connecting to two databases. I'm going to add the address city in which database it exists. So how do I get this with select.
   SqlConnection conn = new SqlConnection(myconnectınformation);
    GetTables().Address.Select(o => new Model { Address = o.Address, City = o.City });

SqlConnection conn = new SqlConnection(myconnectınformation2);
GetTables().Address.Select(t => new Model { Address = t.Address, City = t.City });

SqlConnection conn = new SqlConnection(myconnectınformation);
GetTables().Address.Select(o => new Model { Address = o.Address, City = o.City });

SqlConnection conn = new SqlConnection(myconnectınformation2);
GetTables().Address.Select(t => new Model { Address = t.Address, City = t.City });

Not error but not merge the select database table.


text:
Q: add interrupt on error code 0x7 : Store/AMO access fault RISCV I want to add an interruption on error code 0x7 : Store/AMO access fault of RISCV.
I created a SoC with LiteX tools. But, i don't happen to add my interruption in the vector interruption in mtvec register. The communication UART works under interruption. So, when i add my interruption, i lose the ability to write printf in the communication UART. I think I'm overriding the UART interruption.
How can i solve my problem ?
Thank you,
In fact, I want to add an interruption on mcause register at the value 0x7 : Store/AMO access fault of RISCV. I tried to change the mode of mtvec register. without any success.


text:
Q: Transferring data between DOORS modules using links How do I use links in DOORS to transfer attribute data from one module to another

A: Actually, there's usually no point in transferring attribute data. The usual way is to show data in another module, so that the data you see in the "other" module is always up to date.
That being said, if you really have to do it, first create a column which shows the data you need using the Analysis Wizard.
Then use DXL to transfer the data to an attribute.
Example: Module "System Requirements" has outgoing Links to Module "Customer Requirements". Module "Customer Requirements" has an Object attribute "Priority". In Module "System Requirements" you want an attribute "Customer Priority".
Open "System Requirements", Open the Standard view. Use the Analysis Wizard to show "Priority" of the outgoing links (do not show attribute names, do not use recursive analysis). You should now have a new column "Out-links (...)" showing the customer prio, it should be the 3rd column in your view (usually, you should now use "Tools -> Support Tools -> convert Layout DXL to Attribute DXL" so that you have up-to-date data all the time. But if you want the data to be fixed): In "System Requirements" create an attribute "Customer Priority". Run the following command:
Object o
Column c = column 2 // 3rd column in the current view (starting from 0)
for o in current Module do {
    string prio = text (c, o)
    o."Customer Priority" = prio
}

Check the result and save the module.


text:
Q: MVC Routing match all routes except resources I've a angularJS application. I've created a controller/action that returns a rendered index.cshtml on any request. This is my only mvc4 controller. I use the webapi for all other behavior. The client-side should only handling the routes. Works well so far.
RouteExistingFiles = false;

routes.MapRoute(
    name: "Default",
    url: "{*url}",
    defaults: new { controller = "Index", action = "Index" }
);

The problem is that this solution matches resources like "localhost/favicon.ico, localhost/template.html".
Can i prevent or ignore all request like this ?

A: You could use IgnoreRoute so the routing module ignores requests for those resources, for example:
routes.IgnoreRoute("favicon.ico");
routes.IgnoreRoute("{templateName}.html");

These have to be added before your current Default route.

A: You can try something like this, then routing module ignores requests for any .html and .ico files :-
routes.IgnoreRoute("{*allhtml}", new {allhtml=@".*\.html(/.*)?"});
routes.IgnoreRoute("{*favicon}", new {favicon=@"(.*/)?favicon.ico(/.*)?"})


text:
Q: Strange behaviour on merging code-coverage of laravel-code tested by browser-kit-testing Hi crowd intelligence!
I have different testsuites that are processed parallel in teamcity with .cov-files as artifacts  and one build-configuration that does a merge of the code-coverage.
The strange thing is:
code that is tested with the browser-kit-testing methods of laravel in such a way
$this->visitRoute('route.name', ['any'=>'params']);
$this->see('any text');
$this->seeElement('#myContainer');

will be correctly shown in code-coverage of the testsuite itself
only real lines of code are marked as covered - curly brackets are white
but after merging the code-coverage with the other results, these codes won't be completely covered anymore because the curly brackets and other structure-code are marked as not executed
after merge structure-code like curly brackets that should not count in code-coverage is marked red
our setup:

*

*running phpunit 9

*with php7.4

*and laravel 6.x

*in docker-containers

*with alpine-based custom-image

*code-coverage via pcov (it is much faster than xdebug)

*in the beginning it worked very fine in this constellation

*maybe any updates in pcov / phpunit / laravel / browser-kit-testing caused this problem?!

*but we have no idea why it works in single coverage-output but not in merged

*merging via phpcov

*also tried nimut/phpunit-merger - same results

*other code (e.g. some service-classes) that was tested with default phpunit-methods is also perfect covered after merging... it seems only code that is covered by browser-kit-testing is not clearly defined in .cov-file ?!

Anyone that has the same problem (or better: a solution) ?


text:
Q: Embedding WebBrowser in Custom pane using Excel-DNA I am trying to embed a browser in Custom task pane of excel using excel DNA but I am getting exception every time. I have modified the Excel dna sample shown here to use WebBrowser control from Windows Forms instead of Label
TheLabel = new WebBrowser{ };
                //TheLabel.Text = "My First CTP!";
                TheLabel.Location = new System.Drawing.Point(20, 20);
                TheLabel.Size = new System.Drawing.Size(200, 60);
                TheLabel.Navigate(new Uri("www.rbs.com"));
                Controls.Add(TheLabel);

This is giving me exception, Please can anybody help in resolving this issue

A: issue got resolved , issue was that the uri was incorrect , it should start with 'http' instead of 'www ' but since the program itself was closing without going to catch block it was difficult to investigate.
I added the user control in Toolbox and then drag and drop it on my windows form which has given me perfect reason of why my code was failing.


text:
Q: How do you generate a custom form in Django? In one of the template pages of my Django app, the page asks for the user to select the choices he wants, from a checkbox list.
The catch is, that there are different choices for different users (for example, based on their past interests, there are different options).
How do you generate Django forms with CheckboxSelectMultiple() fields that generate custom choices for each user?

A: In forms.py you need to override the __init__ method, and set there the choices passed from the view when you call the form class.
Here is an example:
class UserOptionsForm(forms.Form):
    user_personal_options = forms.ChoiceField(choices=(),
                                              widget=forms.CheckboxSelectMultiple)

    def __init__(self, *args, **kwargs):
        choices = kwargs.pop('choices', None) # return the choices or None
        super(UserOptionsForm, self).__init__(*args, **kwargs)
        if choices is not None:
            self.fields['user_personal_options'].choices = choices

So in your view:
def user_options(request, user_id):
    if request.method == 'POST':
        form = UserOptionsForm(request.POST)
            if form.is_valid():
                # proccess form data here
                form.save()
    else:
        # render the form with user personal choices
        user_choices = [] # do shometing here to make the choices dict by user_id
        form = UserOptionsForm(choices=user_choices)


text:
Q: Expected number of coupons occurring at most once As a variation on the coupon collector problem, I would like to find on average how many coupons ($n$ types of coupons) occur in $k$ trials are picked at most once.
I have approached this by summing the probability for a coupon occurring once (binomial) and the probability of it occurring 0 times, this gives me the probability of a single coupon occurring at most once.
However, it has occurred to me that the subsequent coupons don't seem to be independent of this probability, and hence I can't really just multiply this probability by $k$
I do not necessarily need to find an exact expression, and an approximation is acceptable. The value of $k$ I am interested in is $n\ln{n}$ but I am not sure if and how it will help with approximating. I don't know how to evaluate if pretending the probabilities are independent and simply summing them is an acceptable approximation.
I've found something similar here which seems relevant but I am struggling to understand it completely as it seems quite general.
Probability distribution of number of unique coupons after multiple draws

A: As JMoravitz already stated in comments, linearity of expectation doesn't require independence. The probability that a given coupon type is drawn at most once in $k$ trials is
$$
n^{-k}\left((n-1)^k+k(n-1)^{k-1}\right)\;,
$$
and by linearity of expectation the expected number of coupon types drawn at most once in $k$ trials is
$$
n\cdot n^{-k}\left((n-1)^k+k(n-1)^{k-1}\right)=(n-1+k)\left(1-\frac1n\right)^{k-1}\;.
$$

A: Confirming the  accepted answer  we have  a very  simple combinatorial
class here:
$$\def\textsc#1{\dosc#1\csod}
\def\dosc#1#2\csod{{\rm #1{\small #2}}}
\textsc{SEQ}_{=n}(\mathcal{U}+\mathcal{U}\times\mathcal{Z}
+ \textsc{SET}_{\ge 2}(\mathcal{Z}))$$
which gives the generating function
$$G(z, u) = (u+uz+\exp(z)-1-z)^n.$$
The desired statistic is
$$\frac{1}{n^k} k! [z^k] \left. \frac{\partial}{\partial u}
G(z, u) \right|_{u=1}
\\ = \frac{1}{n^k} k! [z^k] \left.
n (u+uz+\exp(z)-1-z)^{n-1} (1+z) \right|_{u=1}
\\ = \frac{1}{n^{k-1}} k! [z^k] (1+z) \exp((n-1)z)
\\ = \frac{1}{n^{k-1}} ((n-1)^k + k (n-1)^{k-1})
= (n-1+k) \frac{1}{n^{k-1}} (n-1)^{k-1}
\\ = (n-1+k) \left(1-\frac{1}{n}\right)^{k-1}.$$


text:
Q: Dynamically set topic name and Kafka Brokers in PublishKafka2_0 processor in Nifi I am using the PublishKafka processor in nifi to publish JSON data in Kafka. I want to set Kafka Server and topic name details from attribute values. I am not able to do this. It's giving the below error

PublishKafka_2_0[id=2cb333e9-5fd6-1254-a10c-d1084b230d03] Processing
halted: yielding [1 sec]: org.apache.kafka.common.KafkaException:
Failed to construct kafka producer

*

*Caused by: org.apache.kafka.common.config.ConfigException: No resolvable bootstrap urls given in bootstrap.servers .

Only hardcoded values of the Kafka server and the topic name is working.
Am I missing something? Any help would be much appreciated!


text:
Q: python 3 tweepy csv encode Please help to resolve the error. I am trying to get tweets from twitter and write it into a csv file.
#!/usr/bin/env python
# encoding: utf-8

import tweepy #https://github.com/tweepy/tweepy
import csv
import codecs

#consumer key, consumer secret, access token, access secret.
--
--
--
--

def get_all_tweets(screen_name):
    #Twitter only allows access to a users most recent 3240 tweets with this method

    #authorize twitter, initialize tweepy
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)

    #initialize a list to hold all the tweepy Tweets
    alltweets = []

    #make initial request for most recent tweets (200 is the maximum allowed count)
    new_tweets = api.user_timeline(screen_name = screen_name,count=200)

    #save most recent tweets
    alltweets.extend(new_tweets)

    #save the id of the oldest tweet less one
    oldest = alltweets[-1].id - 1

    #keep grabbing tweets until there are no tweets left to grab
    while len(new_tweets) > 0:
        print ('getting tweets before %s' % (oldest))

        #all subsiquent requests use the max_id param to prevent duplicates
        new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)

        #save most recent tweets
        alltweets.extend(new_tweets)

        #update the id of the oldest tweet less one
        oldest = alltweets[-1].id - 1

        print ("...%s tweets downloaded so far" % (len(alltweets)))

    #transform the tweepy tweets into a 2D array that will populate the csv
    outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]

    #write the csv
    with codecs.open('%s_tweets.csv' % screen_name, 'wb') as f:

        writer = csv.writer(f)
        writer.writerow([bytes(id,'utf-8'),bytes(created_at,'utf-8'),bytes(text,'utf-8')])
        writer.writerows(outtweets)

    pass

if __name__ == '__main__':
    #pass in the username of the account you want to download
    get_all_tweets("gokul7071")

Error
getting tweets before 529619651269894144
...3 tweets downloaded so far
Traceback (most recent call last):
  File "C:\Users\PraveenMS\Desktop\tweepy-3.3.0\examples\importtweepy.py", line 67, in <module>
    get_all_tweets("gokul7071")
  File "C:\Users\PraveenMS\Desktop\tweepy-3.3.0\examples\importtweepy.py", line 59, in get_all_tweets
    writer.writerow([bytes(id,'utf-8'),bytes(created_at,'utf-8'),bytes(text,'utf-8')])
TypeError: encoding or errors without a string argument

getting tweets before 529619651269894144
    ...3 tweets downloaded so far
Traceback (most recent call last):
  File "C:\Users\PraveenMS\Desktop\tweepy-3.3.0\examples\importtweepy.py", line 67, in <module>
    get_all_tweets("gokul7071")
  File "C:\Users\PraveenMS\Desktop\tweepy-3.3.0\examples\importtweepy.py", line 59, in get_all_tweets
    writer.writerow(["id","created_at","text"])
TypeError: 'str' does not support the buffer interface

A: Writing data with writerow is always difficult you need to follow various encoding characterstics there are other simplier ways to collects tweets and store it in a csv file...if you can tell what exact contents you want to store..that it might be easier to give an appropriate solution..
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import time

ckey = '######'
csecret = '#####'
atoken = '####'
asecret = '#####'

class listener(StreamListener):

    def on_data(self, data):
      try:
          print data
          saveFile = open('Filename.csv','a')
          saveFile.write(data)
          saveFile.write('\n')
          saveFile.close()
          return True
      except BaseException, e:
          print 'failed ondata',str(e)
          time.sleep(5)

    def on_error(self, status):
        print status

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["Obama"],languages='en')

This is sample example of how to stream tweets about the term "Obama"...and it create a file named Filename.csv...I hope this helps...you question is not descriptive about what you want