text:
Q: how to iterate through a table using node and cheerio All day todo I've been working on this web scraper that pulls the date and the sunset time from sunrise-sunset.org
Iv managed to get it to scrape and display the first day and time in the table but I cant find out how to iterate through the table while using node, axios, and cheerio since im pretty new to all three.
my JSON only has one object but im trying to find out how to iterate through the table so I can have every table row as its own object. for example

[
  {
   "day": "Tue, Nov 1",
   "time": "5:59:57 pm"
  }
  {
   "day": "Tue, Nov 2",
   "time": "5:55:37 pm"
  }
  {
   "day": "Tue, Nov 2",
   "time": "5:42:47 pm"
  }
]

This is my code so far that has resulted in pulling the first day and time from the website.

app.get('/results', function (req, res) {
        axios(url)
            .then(response => {
                const html = response.data
                const $ = cheerio.load(html)
                const days = []

                $('#month', html).each(function () {
                    const day = $('.number', '.day').prop('innerText')
                    const time = $('.sunset', '.day').prop('innerText')
                    days.push({
                        day,
                        time
                    })
                })
                res.json(days)
            })
            .catch(err => console.log(err))
    })

I then display the results in an empty div with this code

const feedDisplay = document.querySelector('#feed')

fetch('http://localhost:8000/results')
    .then(response => { return response.json() })
    // .then(data => console.log(data))
    .then(data => {
        data.forEach(daysaray => {
            const dayItem = `<div><h3>` + daysaray.day +`</h3><p>` + daysaray.time +`</div>`
            feedDisplay.insertAdjacentHTML("beforeend", dayItem)
        })
    })
    .catch(err => console.log(err))

EDIT

This is the HTML of the table I'm trying to scrape

<col>
<col>
<col>
<col>
<col>
<col>
<col>
<col>
<col>
<col>
<col>
<col>

Day
Twilight start
Sunrise
Sunset
Twilight end
Day length
Solar noon
Nautical twilight
Astronomical twilight

Start
End
Start
End

Tue, Nov 1
7:19:52 am
7:49:10 am
5:59:22 pm
6:28:40 pm
10:10:12
12:54:16 pm
6:44 am
7:03 pm
6:10 am
7:38 pm

Wed, Nov 2
7:21:11 am
7:50:33 am
5:57:57 pm
6:27:19 pm
10:07:24
12:54:15 pm
6:46 am
7:02 pm
6:11 am
7:36 pm

Thu, Nov 3
7:22:30 am
7:51:57 am
5:56:33 pm
6:26:00 pm
10:04:36
12:54:15 pm
6:47 am
7:01 pm
6:12 am
7:35 pm

Fri, Nov 4
7:23:49 am
7:53:21 am
5:55:11 pm
6:24:42 pm
10:01:50
12:54:16 pm
6:48 am
6:59 pm
6:14 am
7:34 pm

Sat, Nov 5
7:25:08 am
7:54:45 am
5:53:50 pm
6:23:27 pm
09:59:05
12:54:17 pm
6:49 am
6:58 pm
6:15 am
7:33 pm

Sun, Nov 6
6:26:27 am
6:56:09 am
4:52:31 pm
5:22:12 pm
09:56:22
11:54:20 am
5:51 am
5:57 pm
5:16 am
6:32 pm

Mon, Nov 7
6:27:46 am
6:57:32 am
4:51:14 pm
5:21:00 pm
09:53:42
11:54:23 am
5:52 am
5:56 pm
5:17 am
6:31 pm

Tue, Nov 8
6:29:05 am
6:58:56 am
4:49:59 pm
5:19:49 pm
09:51:03
11:54:27 am
5:53 am
5:55 pm
5:18 am
6:29 pm

Wed, Nov 9
6:30:24 am
7:00:20 am
4:48:45 pm
5:18:41 pm
09:48:25
11:54:32 am
5:54 am
5:54 pm
5:20 am
6:28 pm

Thu, Nov 10
6:31:42 am
7:01:43 am
4:47:33 pm
5:17:34 pm
09:45:50
11:54:38 am
5:56 am
5:53 pm
5:21 am
6:27 pm

Fri, Nov 11
6:33:01 am
7:03:07 am
4:46:23 pm
5:16:29 pm
09:43:16
11:54:45 am
5:57 am
5:52 pm
5:22 am
6:26 pm

Sat, Nov 12
6:34:19 am
7:04:30 am
4:45:15 pm
5:15:26 pm
09:40:45
11:54:52 am
5:58 am
5:51 pm
5:23 am
6:25 pm

Sun, Nov 13
6:35:37 am
7:05:53 am
4:44:09 pm
5:14:25 pm
09:38:16
11:55:01 am
5:59 am
5:50 pm
5:24 am
6:25 pm

Mon, Nov 14
6:36:54 am
7:07:15 am
4:43:05 pm
5:13:26 pm
09:35:50
11:55:10 am
6:01 am
5:49 pm
5:26 am
6:24 pm

Tue, Nov 15
6:38:12 am
7:08:37 am
4:42:03 pm
5:12:28 pm
09:33:26
11:55:20 am
6:02 am
5:48 pm
5:27 am
6:23 pm

Wed, Nov 16
6:39:28 am
7:09:59 am
4:41:03 pm
5:11:34 pm
09:31:04
11:55:31 am
6:03 am
5:47 pm
5:28 am
6:22 pm

Thu, Nov 17
6:40:45 am
7:11:21 am
4:40:05 pm
5:10:41 pm
09:28:44
11:55:43 am
6:04 am
5:46 pm
5:29 am
6:21 pm

Fri, Nov 18
6:42:01 am
7:12:42 am
4:39:09 pm
5:09:50 pm
09:26:27
11:55:55 am
6:05 am
5:45 pm
5:30 am
6:21 pm

Sat, Nov 19
6:43:16 am
7:14:02 am
4:38:15 pm
5:09:01 pm
09:24:13
11:56:09 am
6:07 am
5:45 pm
5:31 am
6:20 pm

Sun, Nov 20
6:44:31 am
7:15:22 am
4:37:24 pm
5:08:15 pm
09:22:02
11:56:23 am
6:08 am
5:44 pm
5:33 am
6:19 pm

Mon, Nov 21
6:45:45 am
7:16:41 am
4:36:35 pm
5:07:31 pm
09:19:54
11:56:38 am
6:09 am
5:43 pm
5:34 am
6:19 pm

Tue, Nov 22
6:46:58 am
7:17:59 am
4:35:48 pm
5:06:49 pm
09:17:49
11:56:54 am
6:10 am
5:43 pm
5:35 am
6:18 pm

Wed, Nov 23
6:48:11 am
7:19:17 am
4:35:04 pm
5:06:10 pm
09:15:47
11:57:10 am
6:11 am
5:42 pm
5:36 am
6:18 pm

Thu, Nov 24
6:49:23 am
7:20:34 am
4:34:22 pm
5:05:32 pm
09:13:48
11:57:28 am
6:12 am
5:42 pm
5:37 am
6:17 pm

Fri, Nov 25
6:50:34 am
7:21:50 am
4:33:42 pm
5:04:57 pm
09:11:52
11:57:46 am
6:13 am
5:41 pm
5:38 am
6:17 pm

Sat, Nov 26
6:51:45 am
7:23:05 am
4:33:05 pm
5:04:25 pm
09:10:00
11:58:05 am
6:15 am
5:41 pm
5:39 am
6:16 pm

Sun, Nov 27
6:52:54 am
7:24:19 am
4:32:30 pm
5:03:55 pm
09:08:11
11:58:24 am
6:16 am
5:40 pm
5:40 am
6:16 pm

Mon, Nov 28
6:54:03 am
7:25:31 am
4:31:58 pm
5:03:27 pm
09:06:27
11:58:45 am
6:17 am
5:40 pm
5:41 am
6:15 pm

Tue, Nov 29
6:55:10 am
7:26:43 am
4:31:28 pm
5:03:02 pm
09:04:45
11:59:06 am
6:18 am
5:39 pm
5:42 am
6:15 pm

Wed, Nov 30
6:56:16 am
7:27:54 am
4:31:01 pm
5:02:39 pm
09:03:07
11:59:27 am
6:19 am
5:39 pm
5:43 am
6:15 pm

A: The pattern $("some id").each doesn't make much sense. Identifiers are supposed to be unique in a valid HTML document, so this says "select something guaranteed to be at most a single element, then iterate that single element". Sure, some pages abuse identifiers as classes so this is conceivably useful in rare invalid HTML cases, but that doesn't apply here.
Instead, try selecting
 rows as described in Scraping all rows from table using cheerio and Parse table from HTML with cheerio in node, then loop (or map) over those:
const axios = require("axios");
const cheerio = require("cheerio"); // 1.0.0-rc.12

const url = "https://sunrise-sunset.org/search?location=portland%20oregon&year=2022&month=11#calendar";

axios.get(url).then(({data: html}) => {
  const $ = cheerio.load(html);
  const rows = [...$("#month tr.day")].map(e => ({
    day: $(e).find(".number").text().trim(),
    time: $(e).find(".sunset").text().trim(),
  }));
  console.log(rows);
});


text:
Q: How to tell if TextView text has been truncated due to singleLine="true"? I have a TextView that I would like to know if it has been truncated due to singleLine="true" in the XML.
What are some ideas to achieve this without having to pass in the displayed text but to detect this with the TextView only?

A: The answer the OP was looking for was found in the following link:
Check if textview is ellipsized in android
The answer basically uses this method to compare the length of the text to the ellipse count to tell if has been truncated.
Layout layout = textview1.getLayout();
if(layout != null) {
    int lines = layout.getLineCount();
    if(lines > 0) {
        int ellipsisCount = layout.getEllipsisCount(lines-1);
        if ( ellipsisCount > 0) {
            Log.d(TAG, "Text is ellipsized");
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to deal with non-normal heterocedastic data from a factorial experiment? I ran an experiment with two factors each with two levels, 5 replicates each combination and one response variable. My data are non-normal and heterocedastic. Transformations didn't help. I ran a permutation ANOVA (aovp - package lmperm - R), but I am not sure this is the right way to go and I don't know what to do about a post hoc test, because I have a significant interaction. This is what my data look like:
F1 F2 BIOMASS
A C 0.66
A C 0.31
A C 0.88
A C 0.55
A C 0.81
A D 0.39
A D 0.21
A D 0.17
A D 0.15
A D 0.18
B C 0.00
B C 0.18
B C 0.05
B C 0.00
B C 0.02
B D 0.16
B D 0.04
B D 0.21
B D 0.15
B D 0.06

A: Your response variable is suspicious.  If it is a continuous proportion, you may want to pursue beta regression (I have an example of a BR in R here: Remove effect of factor on continuous proportion data using regression in R.  If it is the outcome of some number of Bernoulli trials (and you know the number), you should disaggregate and use logistic regression (or use a weighted LR).  The following assumes the data are simply from a continuous variable, and happen to be within the (0, 1) interval.
I think most of this may be covered by my answer here: Alternatives to one-way ANOVA for heteroscedastic data.  In general, permutation tests are not recommended when you have heteroscedasticity.  In your case, I might suggest using ordinal logistic regression.  Since you have a 2x2, the post-hoc tests are just two 2-group comparisons, which could be done by repeating the original analysis on the stratified data.  Under the assumption that the global test of the initial model is significant, I wouldn't even worry about multiple comparisons.


text:
Q: How to prevent variable truncation of double/float in Javascript This is probably a simple answer but I haven't been able to figure out how to do it yet.
I have a javascript function that takes the mouse location and passes it to a asmx page so it can process it and convert the x and y to a lat/long. I do however need accuracy of the mouse location. For some reason when the web service gets to it, its truncated down to 0 decimal places and I get like a 49.0, 105.0. I need the exact position like 9.34536. 104.345367.
I have already tried toPrecision() but the javascript wont even execute if I do this
someMethod((e.pageX - posX).toPrecision(15), (e.pageY - posY).toPrecision(15));

Here is the code I am using
<script>
        $(document).ready(function (e) {

            $(".someElement").hover(function (e) {
                var posX = $(this).position().left;
                var posY = $(this).position().top;
                someMethod((e.pageX - posX), (e.pageY - posY));
            });
        })

        function someMethod(xToUse, yToUse) {
            $.ajax({
                url: "aWebServiceURL.asmx/someMethod",
                type: 'POST',
                data: "x=" + xToUse + "&y=" + yToUse,
                dataType: "json",
                async: true,
                success: function iGotData(response, data) {
                    var resultingJSON = JSON.stringify(response);
                    $('#<%= aLabelOnTheScreen.ClientID %>').text(resultingJSON);

                },
                error: function (xhr, status, errorThrown) {
                    alert("Sorry, there was a problem!");
                    console.log("Error: " + errorThrown);
                    console.log("Status: " + status);
                    console.log(xhr);

                },

                // code to run regardless of success or failure

                complete: function (xhr, status) {
                  //  alert("The request is complete!");

                }

            });

        };
</script>

in C# the method definition is:
   public void someMethod(float x, float y)
{
}

Update: It turns out that I am only getting truncation in Safari and Chrome. Firefox and IE are not.


text:
Q: Magento 1.5.0.1 Items vanish from cart when user logs in at checkout Here's a quick step by step of what's been happening.

*

*The user adds a product to their basket/cart and proceeds to the checkout. They may choose to Register, Checkout as Guest or Login with an existing account.

*Customer Logs in with existing account.

*They get taken to a page informing them that their shopping cart is now empty. Yet in the top right the link for My Cart still reads (1 item) next to it. Clicking this link just loads the same 'Shopping Cart is Empty' page.

Some other tests I did showed the following:
User logs in, adds 3 items to his cart, but logs out before going to checkout.
He comes back to the site at a later date and starts a fresh order for just 1 product, choosing to login at checkout.
Upon doing so his cart cart displays the 3 items from his previous session (his new product missing), yet the My Cart link reads (4 items) next to it.
Does anyone know what might be causing the items to vanish from the cart during this transition from not being logged in to being logged in?

A: I have seen this problem before on servers that are uhosin.session.encryptrunning the suhosin patch. I'm assuming that you are running a secure cart (if not you should) what is most likely happening here is that your session is being lost each time you change between http and https.
When you switch between the HTTP and HTTPS, your HTTP session is not being passed to the HTTPS session. This can be resolved by placing the following in your .htaccess or php.ini file:
php_value suhosin.session.encrypt Off

Let me know if it works or if you are still having the same problem, remember to restart your server once you have made the changes.

A: I solved it.
Turns out the ZetaPrints OrderApproval module was installed and was overriding part of the checkout page.
Apparantly it was something that had been added, decided it was no longer needed and then forgotten about.
I disabled it and flushed the cache and got my old checkout page back.
All working again.

A: For me, it was a matter of Cooke Session Control and setting my 'Cookie domain' value as such:
.mydomain.com
Yes, with a period in front.


text:
Q: Cannot find -lInclude on server side After I installed the Theano and genesim by pip install xxx --user on server side, I tried to import them in python code, but I had this error:
Exception: Compilation failed (return status=1): /usr/bin/ld: cannot find -lInclude. collect2: ld returned 1 exit status.
In addition, I have no root permission, how can I make it?


text:
Q: Passing data from a functional component to a parent class component react native So I have a tab navigation in my app and I am trying to scan a UPC number from on of the tab screens which is called ScanScreen and send it to the homeScreen where I have a search bar and I want the upc number to show up there once the navigation has been done. So far I am able to scan the upc number and navigate to the homeScreen but for some reason I am not able to send the upc number. I have tried many ways ex. navigation.navigate('HomeScreen',{upc: data}) and the getParam() on the home screen but nothing works.
Obj = scan the upc and then successfully navigate to the homeScreen tab and show the number on the searchBar
    export default class HomeScreen extends React.Component {

  constructor(props) {
    super(props);
    this.state = { search: '', isLoading: true };
    this.products = [];
  }

  componentDidMount() {

    db.collection("products")
      .get()
      .then(querySnapshot => {
        const data = querySnapshot.docs.map(doc => doc.data());

        this.setState({
          products: data,
          isLoading: false,
          dataSource: data
        },
          function () {
            this.products = data;
          }
        );
      }).catch(error => {
        console.error(error);
      });

  }

  GetFlag(ingredients, status) {
    var Ingredients = Object.values(ingredients);
    for (var i = 0; i < Ingredients.length; i++) {
      if (Ingredients[i].Status == status)
        return true;

    }
  }

  search = text => {
    console.log(text);
  };
  clear = () => {
    this.search.clear();
  };
  SearchFilterFunction(text) {
    const newData = this.products.filter(function (item) {
      const itemData = item.Name ? item.Name.toUpperCase() :
        ''.toUpperCase();
      const upcData = item.UPC;
      const textData = text.toUpperCase();
      if (itemData.indexOf(textData) > -1)
        return true;
      else if (upcData.toString().indexOf(textData) > -1)
        return true;
      else
        return false;

    });
    this.setState({
      dataSource: newData, search: text,
    });

  }
  ListViewItemSeparator = () => {
    return (
      <View
        style={{
          height: 0.4,
          width: '100%',
          backgroundColor: '#141313',
        }}
      />
    );
  };

  render() {
    const { navigate } = this.props.navigation;

    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, paddingTop: 21 }}>
          <ActivityIndicator />
        </View>
      );
    }
    const upc = navigate.getParams('upcCode')
      console.log(upc)

    return (

      <View style={styles.viewStyle}>

        <SearchBar round

          searchIcon={{ size: 25 }}
          onChangeText={text => this.SearchFilterFunction(text)} onClear={text => this.SearchFilterFunction('')}
          placeholder="Type Here to Search..." value={this.state.search}

        />
        {

          this.state.search.trim() != "" ?

            <FlatList data={this.state.dataSource}
              ItemSeparatorComponent={this.ListViewItemSeparator}
              renderItem={({ item }) => (
                <View style={styles.container}>

                  <TouchableHighlight onPress={() => this.props.navigation.navigate('Summary', {
                    ProductObject: item
                  })}
                  >
                    <View >
                      {
                        this.GetFlag(item.ingredients, 'Haram') == true ?

                          <Image source={images['Haram']} style={styles.imageView} /> :

                          this.GetFlag(item.ingredients, 'Halal') == true ?
                          <Image source={images['Halal']} style={styles.imageView} /> :
                          this.GetFlag(item.ingredients,'Doubtful') == true ?
                          <Image source={images['Doubtful']} style={styles.imageView} /> :
                          null
                      }

                      <Text style={styles.baseText}>

                        <Text style={styles.titleText}  >
                          {item.Name}{'\n'}{'\n'}

                        </Text>

                      </Text>
                    </View>
                  </TouchableHighlight>

                </View>

              )}

              enableEmptySections={true}
              style={{ marginTop: 11 }}
              keyExtractor={(item, index) => index.toString()}
            /> : <FlatList></FlatList>

        }

      </View>

    );
  }
}

export default function ScanScreen({navigation}) {
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);

  useEffect(() => {
    (async () => {
      const { status } = await BarCodeScanner.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  const handleBarCodeScanned = ({ type, data }) => {
    setScanned(true);

    navigation.navigate("Home",{
      upcCode: data
    })
  };

  if (hasPermission === null) {
    return <Text>Requesting for camera permission</Text>;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }

  return (
    <View
      style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'flex-end',
      }}>
      <BarCodeScanner
        onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
        style={StyleSheet.absoluteFillObject}
      />

      {scanned && <Button title={'Tap to Scan Again'} onPress={() => setScanned(false)} />}
    </View>
  );
}

Below is my AppNavigator.JS code if it helps seeing the navigation
function MainTabNavigator() {
  return (

    <Tab.Navigator tabBarOptions={{
      activeTintColor: 'red',
      inactiveTintColor: 'gray'
    }}
      screenOptions={({ route }) => ({
        tabBarIcon: ({ color, size }) => {
          let iconName;
          let tabBarVisible = true;
          if (route.name == 'Home') {
            iconName = 'md-home'
          } else if (route.name == 'Scan') {
            iconName = 'md-camera'

          } else if (route.name == 'Menu') {
            iconName = "md-menu"
          }
          else if (route.name == 'Login') {
            iconName = "md-log-in"
          }

          return <Ionicons name={iconName} color={color} size={size} />
        }
      })}
    >

      <Tab.Screen
        name='Home'
        component={HomeScreen}
        options={({route}) => ({
          title: "Search for Products",
          headerBackTitleVisible: false,

          headerStyle: {
            backgroundColor: '#1c2845',
          },
          headerTintColor: '#fff',
          headerTitleStyle: {
            fontSize:22,
            fontFamily: 'DamascusLight'
          }
        })}

      />
      <Tab.Screen
        name='Login'
        component={LoginScreen}
      />
      <Tab.Screen name='Scan' component={ScanScreen} />
      <Tab.Screen name='Menu' component={SearchScreen} />
    </Tab.Navigator>

  )
}

function MainStackNavigator() {

  return (

    <NavigationContainer>
      <Stack.Navigator>

        {/* <Stack.Screen name='Login' component={LoginScreen} /> */}
        <Stack.Screen name='HomeScreen' component={MainTabNavigator}
          options={({ route }) => ({
            title: 'Search for Products',
            headerBackTitleVisible: false,

            headerStyle: {
              backgroundColor: '#1c2845',
            },
            headerTintColor: '#fff',
            headerTitleStyle: {

              fontSize: 22,
              fontFamily: "DamascusLight"
            },
          }
          )} />
        <Stack.Screen name='RegistrationScreen' component={RegistrationScreen} />

        <Stack.Screen
          name="Summary"
          component={SummaryScreen}
          options={({ route }) => ({

            headerTitle: () =>
              <View style={styles.header}>
                <Text numberOfLines={1} style={styles.title}>{route.params.title}</Text>
                <Text numberOfLines={1} style={styles.subtitle}>{route.params.subtitle}</Text>
              </View>,
            headerBackTitleVisible: false,
            headerStyle: {
              backgroundColor: '#1c2845',
              height: 100
            },
            headerTintColor: '#fff',
            headerTitleStyle: {

              fontSize: 12,
              fontFamily: "DamascusLight"
            },
          }
          )}
        />
        <Stack.Screen
          name="ScanSummary"
          component={ScanSummary}
          // options={({route}) => ({
          //   headerTitle: () =>
          //  <View style={styles.header}>
          //      <Text numberOfLines={1}>{route.params.title}</Text>
          //      <Text numberOfLines={1}>{route.params.subtitle}</Text>
          //  </View>,
          //   headerStyle: {
          //     backgroundColor: '#1c2845',
          //     height: 100
          //   },
          //   headerTintColor: '#fff',
          //   headerTitleStyle: {

          //     fontSize: 12,
          //     fontFamily: "DamascusLight"
          //   },
          // })}
        />
      </Stack.Navigator>
    </NavigationContainer>

  )

}

export default MainStackNavigator

A: if you are using react navigation 5
you can access by params by
this.props.route.params
if older
this.props.navigation.state.params


text:
Q: How to fix bad input in this block of code? I am writing a small login script at school, but I'm having trouble with a certain line of code. Here is the full thing:
I have asked my teacher but she isn't quite sure herself.
#!/bin/python3

def login ():
  username = input ('username')
  password = input ('password')

if username == 'TestAcc'*
    if password == 'spectretest':
      print ('Welcome to the SpectreOS developer test system')
    else print ('invalid password')
else print ('invalid username')

*I get an error message on this line and I am not sure of the problem. Thanks for your help. :)

A: Your code has several syntax issues, use the following:
def login ():
    username = input ('username')
    password = input ('password')

    if username == 'TestAcc':
        if password == 'spectretest':
            print ('Welcome to the SpectreOS developer test system')
        else: print ('invalid password')
    else:
        print ('invalid username')

Keep in mind that indentation in Python matters a lot. I strongly suggest you check more about Python's syntax. You can check many tutorials (articles, videos) out there in the web.


text:
Q: Bijection between the power set of $\mathbb R$ and $\mathbb R^{\mathbb R}$ I want to prove that the power set of $\mathbb R$, which can be naturally identified as $\{0,1\}^{\mathbb R}$, is bijective to the set $\mathbb R^{\mathbb R}$. Can the following attempt be altered to get a bijection without invoking Cantor-Schröder-Bernstein ?

Here is my attempt:
Notation. For any $f:\mathbb R\to\mathbb R$, let $\operatorname{graph}f\overset{\text{Def.}}=\{(x, f(x))\in\mathbb R^2: x\in\mathbb R\}$. Let $g:\mathbb R\to\mathbb R^2$ be a bijection.${}^1$${}^2$${}^3$
Now I define the operator
\begin{split}B:\mathbb R^{\mathbb R}&\to\{0,1\}^{\mathbb R}, \\ f&\mapsto B(f),\end{split}
where
\begin{split} B(f): \mathbb R&\to\{0,1\}, \\
r&\mapsto
\begin{cases}
1&\text{if } g(r)\in\operatorname{graph} f\\
0&\text{if } g(r)\not\in\operatorname{graph} f
\end{cases}
\end{split}
Now, $B$ is injective, because if $f_1, f_2:\mathbb R\to\mathbb R$ satisfy $B(f_1)=B(f_2)$, then, since $g$ is a bijection, for any $(y^1, y^2)\in\mathbb R$, we have $(y^1,y^2)\in\operatorname{graph} f_1\iff (y^1, y^2)\in\operatorname{graph} f_2$, i.e. $f_1(y^1)=y^2\iff f_2(y^1)=y^2$ for any $(y^1,y^2)\in\mathbb R^2$, which means that $f_1=f_2$.
However, $B$ is sadly not surjective. Since the inclusion $\{0,1\}^{\mathbb R}\to\mathbb R^{\mathbb R}$ is trivially injective, Cantor-Schröder-Bernstein implies that the two sets are bijective.


text:
Q: Inject controller actions from within Ember Addon Lets say I have a standalone addon with a playback component:
{{my-record play="recordPlay" stop="recordStop"}}

/app/components/my-record.js
import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    play: function() {
      this.sendAction('play');
    },
    stop: function() {
      this.sendAction('stop');
    }
  }
});

I want the addon to work independently with backend and handle all actions internally.
How do I handle these two actions recordPlay and recordStop from within the addon itself so that I don't need to touch controller/routes of the consuming application?
I have tried:

*

*creating application controller within the addon eg. `/app/controllers/application.js - this is never called

*creating application route within the addon eg. `/app/routes/application.js - this is called unless consuming application has it's own ApplicationRoute which overrides the addon's route
Can I use initializers somehow from within the addon to inject these two actions to ApplicationController?
EDIT: Dirty workaround using ApplicationRoute._actions
/app/initializers/record.js
export default {
  name: 'record',

  initialize: function(container, app) {

    var applicationRoute = container.lookup('route:application');

    applicationRoute._actions.recordPlay = function(id) {

        console.log('CALLED recordPlay', id);
    };

    applicationRoute._actions.recordStop = function(id) {

        console.log('CALLED recordStop', id);

    };
  }
};

A: It seems you are struggling to fulfill constraints that are almost contradictory -- this forces you into a solution that is probably worse than violating your constraints.
The constraints are: (1) component unaware of outside world, but (2) add-on as a whole interacts with the back-end autonomously.
Then your component signals it wants something done, and you want your add-on to provide a default way of doing things.
The idea of components unaware of the outside world is that then they can be used in different contexts. Is it realistic to use your component outside your addon? It seems like you want the "default way of doing things" to be baked in.
One way you could compromise is to use a blueprint to inject an adaptor into your component. The adaptor would then interact with the store (etc?). However, if a consumer wanted to do things differently, they could not define the adaptor and define actions instead, or use a different adaptor.


text:
Q: Is there some way to "figure out the application base dir" other than this? I've made a PHP framework. To start it, you do:
require 'framework.php';
framework_start(__DIR__);

I'm trying to eliminate the __DIR__ part, if at all possible. It's telling the framework what the "base dir" for the application is. I can't think of any way to determine the "__DIR__" for the file that calls framework_start(), from within framework_start().
I can't help but feel annoyed that it can't just be:
require 'framework.php';
framework_start();

... and then framework_start(); somehow figures out the __DIR__ value on its own. But if I just reference __DIR__ from the PHP file that contains framework_start(), it will obviously return the wrong dir path.
Is this possible at all? If so, how?

A: I would suggest the following. Define a constant at the top of framework.php file to be used in your framework instead of __DIR__:
$trace = debug_backtrace(false);
$levelsToGoUp = 0; // set to 1 if called from within the function
if (array_key_exists($levelsToGoUp, $trace)) {
    define('PARENTFILE', dirname($trace[$levelsToGoUp]['file']));
} else {
    define('PARENTFILE', __DIR__);
}

If you called debug_backtrace() inside the function framework_start() you would need to look at the entry with key 1 in the array (the first is the function itself), which I would recommend.


text:
Q: Run once inside update loop inside a update loop So, basically I am making a game that includes land mines, which I want to have them release a red shockwave whenever the player gets close. The only problem is since the code looks like this:
loop {
    if (<...Player inside radius...>) {

    spawnShockwave();

    }
}
//This is simplified

Each time the player gets near one of the mines, an large number of shockwave images get created (Once every time the loop is run.) How can I get it so that only shockwave gets created per mine.
The game is being written in SpriteKit, and the mines are there own class , however, I have to enumerate each object as an SKNode. Which sucks because that means I can't use custom properties that an SKNode doesn't have.
If anyone has a solution please help.
(Application written in swift)


text:
Q: how can i make a tablelayout invisible and then visible in winforms i have a winform that needs to print a chessboard, i have a table with some controls in it.
what i did was to set it invisible when the form loads
private void Chess_Load(object sender, EventArgs e)
{
    PromotionTable.Visible =false;
}

and then make it visible once the function is triggered.
public void piecePromotionChange(Pieces[,] pieces, int rowEnd2, int columnEnd2, bool blackOrNot)
{
    PromotionTable.Visible = true;
}

but it still remains, invisible :(

A: You'll need to invalidate/refresh that portion of the screen. Setting the Visible property does not trigger a redraw..
PromotionTable.Visible=true;
PromotionTable.Invalidate();
myForm.Refresh();

A: You probably ment to set its visibility to false on load
private void Chess_Load(object sender, EventArgs e)
{
   PromotionTable.Visible = false; // false here
}

If its not visible to begin with, you might need to check and make sure its added to the controls.


text:
Q: PHP Contact form webpage I have a big problem about a contact formular.
I have for a long time tried to get the form up and running whit php.
I have a captcha function also that I thing is working now whit checking.
But I need help whit form and php part:
 1. check all form field and give a error message when the input fields are not OK (right side off the input field in red color).
 2. Sendt out email if all is ok after check form fields. And give at message that the email have been sendt.
contactform.php
<?php session_start();
if (isset($_POST['Submit'])) {
    if (empty($_POST["first_name"])) {
        $nameError = "Name is required";
    }
    else {
        $name = test_input($_POST["first_name"]);
        // check name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $nameError = "Only letters and white space allowed";
        }
    }

    // code for check server side validation
    if(empty($_SESSION['6_letters_code'] ) || strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0){
        $msg="The Validation code does not match!";// Captcha verification is incorrect.
    }else{// Captcha verification is Correct. Final Code Execute here!
        $msg="The Validation code has been matched.";
    }
}
?>

<!DOCTYPE html>

    <meta charset="utf-8">
  <meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
  <meta name="dcterms.created" content="sø, 22 maj 2016 18:08:14 GMT">
  <meta name="description" content="">
  <meta name="keywords" content="">
  <title></title>

    <form action="" method="post" name="contactform" id="contactform" <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

                First Name *

                <input  type="text" name="first_name" id="first_name" maxlength="50" size="30">
                * <?php echo $nameError;?>

                Last Name *

                <input  type="text" name="last_name" maxlength="50" size="30">

                Email Address *

                <input  type="text" name="email" maxlength="80" size="30">

                Telephone Number

                <input  type="text" name="telephone" maxlength="30" size="30">

                Comments *

                <textarea  name="comments" maxlength="1000" cols="25" rows="6"></textarea>

                <?php if(isset($msg)){?>
                <?php echo $msg;?><?php } ?>

                    <img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' >

                    Enter the code above here :

                    <input id="6_letters_code" name="6_letters_code" type="text">

                    Can't read the image? click here to refresh

                <input name="Submit" type="submit" onclick="return validate();" value="Submit" class="button1">

    </form>

Send_form_email.php
This code is working if I use it:

But then the user is forced away from the form.
And all the error messages is given on a blank php page and not in the form whit the captcha also.
if(isset($_POST['email'])) {
  // EDIT THE 2 LINES BELOW AS REQUIRED
  $email_to = "my email address";
  $email_subject = "this is a message";
  function died($error) {
    // your error code can go here
    echo "We are very sorry, but there were error(s) found with the form you submitted. ";
    echo "These errors appear below.

";
    echo $error."

";
    echo "Please go back and fix these errors.

";
    die();
  }
    // validation expected data exists

  if(!isset($_POST['first_name']) ||
      !isset($_POST['last_name']) ||
      !isset($_POST['email']) ||
      !isset($_POST['telephone']) ||
      !isset($_POST['comments']))
  {
    died('We are sorry, but there appears to be a problem with the form you submitted.');
  }

  $first_name = $_POST['first_name']; // required
  $last_name = $_POST['last_name']; // required
  $email_from = $_POST['email']; // required
  $telephone = $_POST['telephone']; // not required
  $comments = $_POST['comments']; // required

  $error_message = "";

  $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.
';
  }
  $string_exp = "/^[A-Za-z .'-]+$/";

  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.
';
  }

  if(!preg_match($string_exp,$last_name)) {
    $error_message .= 'The Last Name you entered does not appear to be valid.
';
  }

  if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.
';
  }

  if(strlen($error_message) > 0) {
    died($error_message);
  }
  $email_message = "Form details below.\n\n";

  function clean_string($string) {
    $bad = array("content-type","bcc:","to:","cc:","href");
    return str_replace($bad,"",$string);
  }

  $email_message .= "First Name: ".clean_string($first_name)."\n";
  $email_message .= "Last Name: ".clean_string($last_name)."\n";
  $email_message .= "Email: ".clean_string($email_from)."\n";
  $email_message .= "Telephone: ".clean_string($telephone)."\n";
  $email_message .= "Comments: ".clean_string($comments)."\n";

    // create email headers
    $headers = 'From: '.$email_from."\r\n".
    'Reply-To: '.$email_from."\r\n" .
    'X-Mailer: PHP/' . phpversion();
    @mail($email_to, $email_subject, $email_message, $headers);

?>

Thank you for contacting us. We will be in touch with you very soon.
<?php } ?>

Send_email_form.php

A: This is happening because you're using this if statement.
if(strlen($error_message) > 0) {
   died($error_message);
}

If you want to show the error message on the actual contact form. You need to use
// Change in Send_email_form.php
 if(strlen($error_message) > 0)
 {
    header('Location: contactform.php?err='.$error_message);
    exit;
 }

// Change in contactform.php - Use this piece of code where you want to display the errors on page.
if(isset($_GET['err']) && !empty( $_GET['err'] )
{
    echo $_GET['err'];
}


text:
Q: Expand $\cos(x)$ in odd Fourier series.
Expand $\cos(x)$ in sinus-series in the interval $(0,\pi/2)$ and use
  the result to calculate $$\sum_{n=1}^{\infty}\frac{n^2}{(4n^2-1)^2}.$$

Since we only need the odd terms in the Fourier expansion, we know that $a_n=0$, so we only need $b_n$ in order to find the sine expansion.
In my book, there is a chapter on "Fourier series on intervals", and there they state that:

If $f$ is a piecewise smooth function on $[0,l]$, then the Fourier sine expansion is given by
$$f(x)=\sum_{n=1}^{\infty}b_n\sin\left(\frac{\pi n x}{l}\right),\tag{1}$$
where
$$b_n=\frac{2}{l}\int\limits_{0}^{l}f(x)\sin\left(\frac{\pi n x}{l}\right).\tag{2}$$

So we should be able to use only $(1)$ and $(2)$ with $l=\pi/2$ to solve this problem. So
\begin{align}
b_n=\frac{4}{\pi}\int\limits_{0}^{\pi/2}\cos(x)\sin(2nx)dx = \frac{4(\sin(\pi n)-2n)}{\pi(1-4n^2)}\tag{3}.
\end{align}
This gives
$$\cos(x)=\frac{8}{\pi}\sum_{n=1}^{\infty}\frac{n}{4n^2-1}\sin(2nx), \quad \forall \ n\in\mathbb{N}\tag{4}$$
2 questions remain:

*

*I used wolfram alpha to calculate the integral in $(3)$. What methods do I use to do this? Repeated integration by parts and solve for the integral?

*How do I calculate the desired sum?

A: As posted by the OP, two steps remain:

*

*Perform the integral:

$$
b_n=\frac{4}{\pi}\int\limits_{0}^{\pi/2}\cos(x)\sin(2nx)dx \\
= \frac{1}{i \pi}\int\limits_{0}^{\pi/2}e^{ix(1+2n)}- e^{ix(1-2n)}+e^{-ix(1-2n)}-e^{-ix(1+2n)}dx \\
= \frac{1}{i \pi} \left(\frac{e^{ix(1+2n)}}{i(1+2n)}|_{0}^{\pi/2} - \frac{e^{ix(1-2n)}}{i(1-2n)}|_{0}^{\pi/2} + \frac{e^{-ix(1-2n)}}{-i(1-2n)}|_{0}^{\pi/2} -\frac{e^{-ix(1+2n)}}{-i(1+2n)}|_{0}^{\pi/2} \right)\\
= \frac{1}{i \pi} \left(\frac{i(-1)^n - 1}{i(1+2n)} - \frac{i(-1)^n - 1}{i(1-2n)} + \frac{-i(-1)^n - 1}{-i(1-2n)} - \frac{-i(-1)^n - 1}{-i(1+2n)} \right)\\
= \frac{1}{- \pi (1 - 4 n^2)} \left( -4n(i(-1)^n - 1) - 4n (-i(-1)^n - 1)  \right)\\
= \frac{-8n}{\pi(1-4n^2)} \\
= \frac{4(\sin(\pi n)-2n)}{\pi(1-4n^2)}
$$
where the last step only indicates the "desired" solution by WolframAlpha, where anyway $\sin(\pi n) = 0$ .
2 Calculating the desired sum.
From OP's last result,
$$
\cos(x)=\frac{8}{\pi}\sum_{n=1}^{\infty}\frac{n}{4n^2-1}\sin(2nx),
$$
 multiply this formula with $\cos(x) $ and integrate, using the integral which was just derived:
$$
\frac{\pi}{4} = \int\limits_{0}^{\pi/2}\cos^2(x) dx = \frac{8}{\pi} \sum_{n=1}^\infty \frac{n}{4n^2 -1} \int\limits_{0}^{\pi/2}\cos(x)\cdot\sin(2nx) dx = \\
\frac{8}{\pi} \sum_{n=1}^\infty \frac{n}{4n^2 -1} \cdot \frac{2 n}{4n^2 -1}\\
= \frac{16}{\pi} \sum_{n=1}^\infty \frac{n^2}{(4n^2 -1)^2}
$$
so finally
$$
\sum_{n=1}^\infty \frac{n^2}{(4n^2 -1)^2} = \frac{\pi^2}{64}
$$

A: Consider the function $f(x) = \cos(x) \cdot {\rm{sign}}(x)$ in the interval $(-\pi, \pi)$. This function is identical to $\cos(x)$ in the interval $(0, \pi/2)$ so the expansion will be correct in that interval.
You want $f(x) = \sum_{m=1}^\infty b_m \sin(mx)$.
Integrating with $\sin(nx)$ gives
$$
\int\limits_{-\pi}^{\pi}\sin( n x)\sin(nx)dx = \pi
$$
$$
 \int\limits_{-\pi}^{\pi}\sin( m x)\sin(nx)dx = 0 \quad (m\ne n)
$$
and
$$
\int\limits_{-\pi}^{\pi}\cos(x)\cdot {\rm{sign}}(x) \cdot \sin(nx)dx = 2 \int\limits_{0}^{\pi}\cos(x)\cdot \sin(nx)dx =  2 \frac{n (1+\cos(\pi n))}{n^2 - 1} \tag{*}
$$
So you have
$$
\cos(x) = \frac{2}{\pi} \sum_{n=1}^\infty \frac{n (1+\cos(\pi n))}{n^2 - 1} \sin(nx)
$$
where the coefficients are nonzero for even n.
Substituting $n$  with $2 m$ gives
$$
\cos(x) = \frac{8}{\pi} \sum_{m=1}^\infty \frac{m}{4m^2 -1} \sin(2 m x)
$$
No use the integral in (*) again: multiply the last formula with $\cos(x) $ and integrate:
$$
\frac{\pi}{2} = \int\limits_{0}^{\pi}\cos^2(x) dx = \frac{8}{\pi} \sum_{m=1}^\infty \frac{m}{4m^2 -1} \int\limits_{0}^{\pi}\cos(x)\cdot\sin(2mx) dx = \frac{32}{\pi} \sum_{m=1}^\infty \frac{m^2}{(4m^2 -1)^2}
$$
so finally
$$
\sum_{m=1}^\infty \frac{m^2}{(4m^2 -1)^2} = \frac{\pi^2}{64}
$$


text:
Q: How to style a graph according to the direction of the edges and the centrality of the vertices? I'm new to Mathematica and I'm using it to study graph theory and network data processing and analysis. I recently started to deal with graph data visualization and directed graphs. Which lead me to the wonder about ways of presenting directed graphs.
Lets suppose the following graph:
vlist = {1, 2, 3, 4, 5}
vrules = {1 -> 2, 1 -> 3, 1 -> 5, 2 -> 1, 2 -> 4, 2 -> 5, 3 -> 2, 4 -> 1, 4 -> 5, 5 -> 3, 5 -> 4}
g=Graph[vlist,vrules]

Which is rendered as follows:

Now I want to make bidirectional connections to be presented as a thick line with arrowheads in both ends, single direction connections to be presented with a thin line and the arrowhead indicating its direction.
I also want the vertices to reflect the centrality of the nodes, so nodes with higher centrality would be presented bigger in proportion to its centrality up to a maximum size.
Fo example, the betweeness and degree centralities of this graph are:
BetweennessCentrality[g]
{2., 3.5, 1., 1., 1.5}

DegreeCentrality[g]
{5, 5, 3, 4, 5}

I've looked into the documentation but didn't find much insight on how to do this kind of stuff, I know that I essentially have to deal with GraphStyle options, but most of them are either poorly documented or not documented at all.
Regards and thanks in advance,

A: A bit more styling:
color[x_, minmax_] := ColorData[{"GrayTones", "Reverse"}][Rescale[x, minmax, {.1, 1}]];

iEShapeFunction[UndirectedEdge[x_, y_], {vsrule_, vstyle_}, dcheck_:True] :=
  With[{sback = {vsrule[x], vsrule[y]}, acolor = {vstyle[x], vstyle[y]}},
   ({If[TrueQ[dcheck] && dcheck[x] != #[[1]], sback = Reverse[sback];
      acolor = Reverse[acolor]];Blend[acolor, Divide @@ Reverse[sback]],
      Arrowheads[{-.05, .05}], Thickness[.01],
      Arrow[Line[#, VertexColors -> acolor], sback]} &)];

iEShapeFunction[DirectedEdge[x_, y_], {vsrule_, vstyle_}, dcheck_:True] :=
  With[{sback = {vsrule[x], vsrule[y]}, acolor = {vstyle[x], vstyle[y]}},
   ({Blend[acolor, Divide @@ Reverse[sback]],
      Arrowheads[{.03}], Thickness[.001],
      Arrow[Line[#, VertexColors -> acolor], sback]} &)];

For example:
g = RandomGraph[{15, 35}, DirectedEdges -> True];

dc = DegreeCentrality[g];
{vmin, vmax} = {.02, .15};
vsrule = Association[Thread[VertexList[g] -> Rescale[dc, MinMax[dc], {vmin, vmax}]]];
vstyle = color[#, {vmin, vmax}] & /@ vsrule;
labelstyle =
  Normal[Directive[White, Bold, Rescale[#, {vmin, vmax}, {8, 20}]] & /@ vsrule];

vlist = VertexList[g];
vcoords =
  Association[Thread[vlist -> GraphEmbedding[Graph[vlist, edges]]]];

edges = GatherBy[EdgeRules[g],
    Union] /. {{Rule[x_, y_], Rule[y_, x_]} :>
     UndirectedEdge[x, y], {Rule[x_, y_]} :> DirectedEdge[x, y]};

Graph[edges, VertexSize -> Normal[{#, #} & /@ vsrule],
 EdgeStyle -> Blue, VertexStyle -> Normal[vstyle],
 EdgeShapeFunction -> ((# -> iEShapeFunction[#, {vsrule, vstyle}, vcoords]) & /@
     edges), VertexLabels -> Placed["Name", Center],
 VertexLabelStyle -> labelstyle
 ]

A: edges=Flatten[GatherBy[vrules, Union] /. {Rule[x_,y_],Rule[y_,x_]}:>
  Property[UndirectedEdge[x,y],
    EdgeShapeFunction->({Arrowheads[{-.05, .05}], Thickness[.01], Arrow@#}&)]];

vertices=Property[#,VertexSize->#2]& @@@ Transpose[{vlist,{"Scaled",#/2} & /@
   Normalize[DegreeCentrality[Graph[vlist, vrules]], Total]}];

Graph[vertices, edges, VertexLabels -> Placed["Name", Center],
   GraphLayout -> { "RenderingOrder" -> "EdgeFirst"},
   EdgeStyle -> Blue, VertexStyle->White]


text:
Q: ShareX NodeJS Application with NGiNX - Returning Localhost instead of domain I'm working on my old project, a custom ShareX uploader but I've come across an issue with the return from my server (nodejs).
It returns https://localhost/u/blablah.png when it's meant to return https://example.com/u/blablah.png
I'm getting the req.hostname upon the request to the server to upload the image,
which returns localhost:myport on the rawHeaders of the request to upload (post).
I'm starting to assume it's how my NGiNX config is setup, but I would love it if someone could point out if I am assuming correct that it is my NGiNX and not my code.
My NGiNX Config:
server {
    listen 80;
    listen [::]:80;

    server_name example.com;

    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

    location ~ /\.(?!well-known)
    {
        deny all;
    }

    location / {
        proxy_pass http://localhost:1337/;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection upgrade;
        proxy_set_header Accept-Encoding gzip;
    }
}

I am using Cloudflare on top of NGiNX and the UAM is set to Essentially Off so I know it's 100% not Cloudflare side.

A: I figured it out, for anyone who may come across this question at a later date here is how I fixed it:
server {
    listen 80;
    listen [::]:80;

    server_name example.com;

    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

    location ~ /\.(?!well-known)
    {
        deny all;
    }

    location / {
        proxy_set_header Host $host;
        proxy_pass http://localhost:1337/;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection upgrade;
        proxy_set_header Accept-Encoding gzip;
    }
}

I had to add the following proxy header proxy_set_header Host $host; after adding that it now gives the domain.


text:
Q: Debugging why NIC link comes up/down constantly I'm detected an issue on my Ubuntu Intel NUC where the ethernet link drops and comes up again. It's a regular pattern where the NIC goes down for 4 seconds, comes up for 12 and then goes down again for 4 seconds on a cycle.
This may be related to physical damage but I can't swap out the NIC as it's integrated. Obviously I'd like to confirm this before replacing any costly components.
If I remove the kernel module and re-insert it the following output appears in kern.log which is normal to me except for the last couple lines.
kernel: [ 1299.003606] e1000e: Intel(R) PRO/1000 Network Driver - 3.2.6-k
kernel: [ 1299.003608] e1000e: Copyright(c) 1999 - 2015 Intel Corporation.
kernel: [ 1299.004140] e1000e 0000:00:1f.6: Interrupt Throttling Rate (ints/sec) set to dynamic conservative mode
kernel: [ 1299.216578] e1000e 0000:00:1f.6 0000:00:1f.6 (uninitialized): registered PHC clock
kernel: [ 1299.288105] e1000e 0000:00:1f.6 eth0: (PCI Express:2.5GT/s:Width x1) 94:c6:91:a7:78:3f
kernel: [ 1299.288112] e1000e 0000:00:1f.6 eth0: Intel(R) PRO/1000 Network Connection
kernel: [ 1299.288256] e1000e 0000:00:1f.6 eth0: MAC: 13, PHY: 12, PBA No: FFFFFF-0FF
kernel: [ 1299.293482] e1000e 0000:00:1f.6 eno1: renamed from eth0
kernel: [ 1304.424541] e1000e 0000:00:1f.6 eno1: NIC Link is Up 1000 Mbps Full Duplex, Flow Control: Rx/Tx
kernel: [ 1304.424696] IPv6: ADDRCONF(NETDEV_CHANGE): eno1: link becomes ready
kernel: [ 1325.609674] e1000e 0000:00:1f.6 eno1: NIC Link is Down
kernel: [ 1330.702483] e1000e 0000:00:1f.6 eno1: NIC Link is Up 1000 Mbps Full Duplex, Flow Control: Rx/Tx

Things I've tried:

*

*Swapped cables

*Changed ports on the hub it's connected to (another machine on the same hub has no issues)

*Updating the BIOS

*Going back to older kernels

*Attempting to load the module with debug parameters

If I look a the module info with $ modinfo e1000e I can see the debug params in the output
parm:           debug:Debug level (0=none,...,16=all) (int)

but running either modprobe or insmod eg. $ sudo modprobe e1000e debug=16 does not yield additional info in kern.log which is what I would have expected.
Unsure where to go next. If someone can tell me why I'm not getting debug info from the module that would be a great start and any additional info gratefully received.

A: Installed a new kernel but the good news is that it seems I didn't have to. There's a bit of conflicting information on how to get debugging info but the secret was in correctly configuring dynamic debugging.
First dump every debug message for e1000e into the kernel debugFS
echo "module e1000e +flmpt" > /sys/kernel/debug/dynamic_debug/control
Discovered you have to do this after the module is loaded. You can cat /sys/kernel/debug/dynamic_debug/control and see how it's modified based on this command. See https://www.kernel.org/doc/html/v4.11/admin-guide/dynamic-debug-howto.html for more information
You can also crank up the kernel logging this way as well
echo 8 > /proc/sys/kernel/printk but for me this didn't seem work until I'd modified the dynamic debug control settings above. I suspect this method will also provide info at module loading time but haven't taken a look.
This yielded two sets of debug information. kern.log now has plenty of debug information, plus cat /proc/kmsg. Both appear to show the same information.

A: If you really want to debug kernel code,

*

*Figure out how to compile a kernel on your distro, or at least how to compile particular modules on your distro.

*Read the source code of this module (which should also tell you how the debug feature works).

*If necessary (you would know after doing (2)), change your kernel configuration when compiling to enable debugging.

$ sudo modprobe e1000e debug=16 does not yield additional info in kern.log which is what I would have expected.

Potential pitfall: You did remove the old module before trying? And it was removed, i.e. not autoloaded back?

NIC goes down for 4 seconds, comes up for 12 and then goes down again for 4 seconds on a cycle.

Guess: The firmware (or the hardware) is buggy, and you cannot debug either of those, as the firmware is closed source, and you don't have hardware specs.

A: Two things you might want to try:

*

*disable pcie by adding pcie_aspm=off as a kernel parameter

*disabling TSO, GSO and GRO using with ethtool -K eth0 gso off gro off tso off (details in this bug report).
Both come from old threads, but might still work.


text:
Q: VueJS nested data model I am relatively new to VueJS and am wondering how to nest/reference component's properties within others, so that the v-model binding will actually update them properly.
To illustrate, I am trying to do something like this.
Template:

        {{field.label}}

            <input v-model="field.model">

Component:
export default {
    data () {
        return {
            myFields: [
                {
                    "label": "label",
                    "model": this.propertyOne
                },
                {
                    "label": "label",
                    "model": this.propertyTwo
                }
            ],
            propertyOne: "",
            propertyTwo: ""
        }
    }
}

In this example, I am expecting the template to render the propertyOne and propertyTwo values (e.g. empty string) in the inputs at first, and then have those values be updated when I change them via the input, like it would normally do with the v-model.
The first works, which means that if I set to propertyOne to "Foo", it gets used as the input value initially, but subsequent changes still don't update the properties.
I would love for this to work so that I can leverage the power of the v-for hook instead of having to write down a massive static template if I have more than 10 fields.

A: When you do: "model": this.propertyTwo this does not make sure that all subsequent changes to propertyTwo will be reflected in the model. To Achieve this there are few options available for you.
You can use watcher, so whenever  propertyTwo will change you can execute a piece of code, like following:
watch: {
  // whenever propertyTwo changes, this function will run
  propertyTwo: function (newProp) {
    this.myFields[1].model = newProp
  }
},

You can also use Computed-Properties or method, which will be reactive if any associated  data changes, they will execute.


text:
Q: Dirac delta applied to Dirichlet function Let's denote Dirichlet function as $d(x)$:
$$d(x)=\begin{cases}{1,x \in \mathbb{Q}\\ 0,x\not\in \mathbb{Q}}\end{cases}$$
I know that Lebesgue integral of Dirichlet function on any finite domain is zero:
$$\int_a^b d(x) dx=0$$
On the other hand, integral of Dirac function is 1 on any set including $0$ ($a<0<b$):
$$\int_a^b\delta(x)dx=1$$
So, I wonder, what would this integral evaluate to:
$$\int_a^b\delta(d(x))dx$$
? Does $\delta(d(x))$ make sense at all?

A: The "function" $\delta$ is in reality the measure
$$ \delta(A) = 1 \Leftrightarrow 0 \in A$$
which is not absolutely continuous with respect to the Lebesgue measure. So the expression
$$ \delta(d(x))$$
does not have any sense, since it assumes that "function" $\delta$ is the density of the measure $\delta$ with respect to the Lebesgue measure.
If we interpret $\delta(x)$ as the "function" which is infinite at 0 an 0 otherwise (while integrating 1) then $\delta(d(x))$ is a "function" which is infinite at any $ x$ rational and 0 otherwise while integrating ... I think the interpretation has reached its limit.
If there is any mathematical object that could represent $\delta(d(x))$ it is a countable sum of Dirac masses (the generalization of the $\delta(x)$, which is infinite at an arbitrary point $y$, in terms of the 'function' delta that is $\delta_y(x) = \delta(x - y)$) at each rational that is
$$ ``\delta(d(x))  \text{''} = \sum_{y \in \mathbb{Q}} \delta_y $$
and so
$$ ``\int_a^b \delta(d(x)) dx \text{''} =  \sum_{y \in \mathbb{Q}} \delta_y([a,b]) = \sum_{y \in [a,b] \cap \mathbb{Q}} 1  = \infty$$
For $\hat{d}(x) = 1 - d(x)$ is even worse since we would have a non-countable sum of non zero terms an that is not even well-defined in general.


text:
Q: How to extract the value of Excel I have an Excel sheet, where is entered post query, how can I use Python to read and extract certain attributes of the query in Excel and copy this to another column?
I don't know what dictionary I can use.
For example in cell Excel is results of post query. How can I extract the value of bifloor (7.5) and to write it to another column?
{"id":"03CD2B3C22558D83","imp": \[{"id":"03CD2B3C22558D83","video":{"mimes": \["video/mp4","video/x-flv","application/x-shockwave-flash"\],"minduration":3,"maxduration":300,"protocols": \[1,2,3,4,5,6\],"w":1920,"h":1080,"startdelay":0,"sequence":1,"boxingallowed":1,"api": \[1,2\]},"bidfloor":7.5,"bidfloorcur":"USD"}\],"app

I don't know what dictionary I can use

A: Use openpyxl to read the Excel file. Then you can perform some data validation in Python to get your value.


text:
Q: How to handle multiple submits in a form? I'm trying to put two submit buttons into one form, one button will update a record and another button will delete it.
<form>
   <input type="submit" value="UPDATE"/>
   <input type="submit" value="DELETE/>
</form>

How these should be handled in php? What's the best way to do it?

A: You can just add a name:
<form>
   <input type="submit" name="action" value="UPDATE"/>
   <input type="submit" name="action" value="DELETE"/>
</form>

and use $_GET['action'] or $_POST['action'] (depending if you use get or post for form).
if($_POST['action'] == 'DELETE'){
   //.....
} elseif($_POST['action'] == 'UPDATE'){
   //.....
}

A: Javascript should do these work. For example:
<script>
function update() {
//what you want to do
}

function del() {
}
</script>

...

<input type="submit" value="UPDATE" onclick="update();"/>
<input type="submit" value="DELETE  onclick="del();"/>

A: There is no issue:
In your php code just check which button is clicked and process the logic, for example:
if user clicked on DELETE the value of UPDATE will be null, also, if user clicked on UPDATE the value for DELETE will be null, now, consider that your real from looks like this:
<form action="update-delete.php" method="POST">
   <input type="text" name="visibleid" value="<?php echo $id; ?>" disabled="disabled">
   <input type=hidden" name="hiddenid" value="<?php echo $id; ?">
   <!-- other fields will be here -->
   <input type="submit" name="update" value="UPDATE"/>
   <input type="submit" name="delete" value="DELETE"/>
</form>

Note: I used 2 fields for mysql id for that row (record), one for showing it to user, and one for unique identification that you need it when updating and deleting the row.
Now, the PHP file looks like this:
I used $_POST because the form method is set to POST, if you not set this attribute or using GET instead, you have to use $_GET ($update = $_GET['update'])

//use $action for identifying button type
$action = '';
if($update == 'UPDATE'){
 $action = 'update';
}
elseif($delete == 'DELETE'){
 $action = 'delete'
}else{
 $action = 'unknown';
}

//now lets start your logic
if($action == 'update'){
 $query = " UPDATE TABLE `tablename` SET `col1` = '$col1' WHERE `id` = '$id' ";
}
elseif($action == 'delete'){
 $query = " DELETE FROM `tablename` WHERE `id` = '$id'";
}
else{
 //echo "";
}
?>

A: Use JS :
<form id="theForm" action="foo.php">
...
<input type="submit" value="UPDATE" id="first"/>
   <input type="submit" value="DELETE" id="second"/>
</form>

$(document).ready(function() {
    $("#theForm input").click(function(e) {
        e.preventDefault();
        if(e.target.id == 'first') {
            $("#theForm").attr("action", "updatePage.php");
        } else {
            $("#theForm").attr("action", "deletePage.php");
        }
        alert($("#theForm").attr("action"));
        $("#theForm").submit();
    });
});

Read more about JQuery
I recommend you to use JS for this but still if you want to use only PHP then refer Mihai Iorga's answer.
Hope it'll help you.


text:
Q: Laravel 9 Unsupported mail transport [] I have Unsupported mail transport" error when send an email in laravel 9 project.
Here is my .env
MAIL_DRIVER = smtp
MAIL_HOST = smtp.gmail.com
MAIL_PORT = 587
MAIL_USERNAME = *****@gmail.com
MAIL_PASSWORD = *******
MAIL_ENCRYPTION = tls
MAIL_FROM_ADDRESS=*****@gmail.com

Here is my config/mail.php
    'mailers' => [
        'smtp' => [
            'driver' => env('MAIL_DRIVER', 'smtp'),
            'host' => env('MAIL_HOST', 'smtp.gmail.com'),
            'port' => env('MAIL_PORT', 587),
            'from' => ['address' => '*****', 'name' => '*****'],
            'encryption' => env('MAIL_ENCRYPTION', 'tls'),
            'username' => env('MAIL_USERNAME'),
            'password' => env('MAIL_PASSWORD'),
            'sendmail' => '/usr/sbin/sendmail -bs',
            'pretend' => false,
        ],

Please help me. Thanks!

A: i fixed my config/mail.php like this and it works.
'smtp' => [
            'transport' => 'smtp',
            'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
            'port' => env('MAIL_PORT', 587),
            'encryption' => env('MAIL_ENCRYPTION', 'tls'),
            'username' => env('MAIL_USERNAME'),
            'password' => env('MAIL_PASSWORD'),
            'timeout' => null,
            'auth_mode' => null,
        ],


text:
Q: Using facet_wrap with multiple factors Here is my data frame WetNmaPso
   Saison Site Category    NbWB_m2  NbWP_m2 mean_PercentCover
2     Wet   SW  CCA_Nma 19.3333333 7.000000       0.072833333
4     Wet   SW  CCA_Pso  0.8333333 0.000000       0.002500000
18    Wet   BY  CCA_Nma  0.0000000 2.666667       0.001166667
20    Wet   BY  CCA_Pso  3.1666667 1.333333       0.007666667
34    Wet   WF  CCA_Nma  3.5000000 3.333333       0.010333333
36    Wet   WF  CCA_Pso  0.0000000 0.000000       0.000000000
50    Wet   MP  CCA_Nma  0.1666667 0.500000       0.004666667
52    Wet   MP  CCA_Pso  0.0000000 0.000000       0.000000000
66    Wet   PK  CCA_Nma  0.0000000 0.000000       0.000500000
68    Wet   PK  CCA_Pso 20.8333333 2.000000       0.063000000
82    Wet   DB  CCA_Nma  0.0000000 0.000000       0.000000000
84    Wet   DB  CCA_Pso  2.8333333 8.333333       0.017833333

The idea is to plot NbWB_m2 against mean_PercentCover for each Category using a different color for each Category and a different symbol for each Site.
Here is the script:
y <-WetNmaPso$NbWB_m2
x <-WetNmaPso$mean_PercentCover
library(ggplot2)
PlotNmaPso<-ggplot(WetNmaPso,aes(x=x,y=y))+
stat_smooth(method="lm",
aes(color=Category))+
geom_point(aes(color=Category,shape=Site))

Now is my question. How do I make individual plots for each Category and keep the right color and the right symbols? I have tried to use face_wrap but somehow it mixes up my data points. Here is what I have been trying to do:
Individual_plots<-PlotNmaPso + facet_wrap(~Category)

The resulting graph shows two individual graphs for each Category which is good but the data points are not correct and the symbols have been mixed up between the two categories.
I have tried different things but never got the expected result.
Any help would be very much appreciated!

A: I think the points did not displayed correctly because you need to insert x and y inside the geom_point() function.
For example:
ggplot(WetNmaPso) + geom_point(data=WetNmaPso,aes(y=NbWB_m2,x=mean_PercentCover,color=Category,shape=Site,size=7)) + stat_smooth(method="lm",aes(y=NbWB_m2,x=mean_PercentCover,color=Category)) + facet_grid(. ~ Category)

Got the same results with scatterplots in Excel, plotting each category separately.

A: The following snippet
ggplot(WetNmaPso, aes(x=NbWB_m2, y=mean_PercentCover, color=factor(Category))) +
  geom_point(aes(shape=factor(Site)), size=5) +
  stat_smooth(method="lm", size=1.2)+facet_wrap(~Category) +
  scale_shape_discrete(name="Site") +
  scale_color_discrete(name="Category")

Produces this, which seems like what you want:

Notes:

*

*Your script was failing because you created vectors x and y
separately. The first call, ggplot(WetNmaPso,...) sets WetNmaPso as the default
dataset. From then on all references within aes(...),  will be to
columns of WetNmaPso, unless you explicitly specify a new dataset in a
future call (e.g., geom_point(data=some.other.df,...).

*Setting color=factor(Category) in the first ggplot(...) call causes this
grouping to apply to everything that comes after, unless explicitly
changed.

*The last two calls (to scale_*) merely change the legend titles.

*Finally, for whatever its worth, fitting lm to data like this is
fraught because the points at NbWB_m2 ~ 20 have exceptionally high
leverage.


text:
Q: Redirect entire site to a sub folder I am trying to redirect my entire site to a subfolder present in the root directory using the following Redirect command.
Redirect 301 / http://example.com/folder/
However, when I open the website, it gets redirected to something like
http://www.example.com/folder/folder/folder/folder/folder/folder/folder...
Am I doing something wrong here?

A: Yes, you're redirecting anything starting with / so of course that includes /folder/ and it just keeps redirecting. You can't redirect your whole site to a part of itself without excluding that part.
Use this instead:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/folder/
RewriteRule ^(.*)$ /folder/$1 [NE,R=301,L]

It will redirect anything that is not in /folder/.
To only redirect the homepage, use this instead:
RewriteEngine on
RewriteRule ^$ /folder/ [R=301,L]


text:
Q: Android: Updating UI using Handler I implemented an Android Application that consists of four activity (A,B,C,D).
A calls B; B calls C and C calls D.
The activity A implements a Handler
Handler handler=new Handler(){
        public void handleMessage(Message msg){

            Bundle bundle = new Bundle();
            bundle = msg.getData();
            String key = bundle.getString("Changed");

            if(key.compareTo("NotificationType") == 0){
                String completeStr = bundle.getString(key);

                if(completeStr.compareTo("Message") == 0)
                {
                             // update UI of Activity A
                        }
                 }
         }
   };

The Activity D can send a messagge using the hadler.
The question are:
What happens if the Activity A is in background when message is sent from Activity D?
What happens if the Activity A is destroyed before receiving the message through the handler?

A: Use Custom BroadcastReceiver
Write this in ActivityD.java
 Intent intent = new Intent();
 intent.putExtra("message","hi");
 intent.setAction("com.android.activity.SEND_DATA");
 sendBroadcast(intent);

Write this in ActivityA.java
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
   // Extract data included in the Intent
   String message = intent.getStringExtra("message");
   Log.d("receiver", "Got message: " + message);
  }
};

Updated
Now register Receiver
 registerReceiver(mMessageReceiver,
  new IntentFilter("com.android.activity.SEND_DATA"));

A: To avoid issues you mentioned use Broadcast messaging system.


text:
Q: How to retrieve data passed in .ajax request in node.js? I am trying to retrieve the data that I am passing from my homepage javascript index.ejs to a function in routes/index.js
index.ejs
$(".user-create-btn").click(function(e){
    $.ajax({
        url: "/users/create/",
        data: {username: "John123"},
        type: "post",
        dataType : "json",
        success: function(result) {
            console.log("test")
        }
    });
    e.preventDefault(e);
    location.reload();
  });

routes/index.js
/*Create new user*/
router.post('/users/create', (req, res) => {
  //how can i retrieve the the data of the username here?
  models.User.create({
    username: username,
  })
});

A: var express = require('express')
    , router = express.Router()
    , bodyParser = require('body-parser')

var app = express();
app.use(bodyParser.json());

router.post('/users/create', (req, res) => {
  var body = req.body,
    username = body.username;

  models.User.create({
    username: username,
    ...
  })
});

app.use(router);

var http = require('http');
var server = http.createServer(app);
server.listen(3000);


text:
Q: qqFileuploader multiple instances, only the last working For a CMS I'm building I need several uploaders, one for files and one for images, later on it is possible I'll add one for videos, etc.
I had it fully working, the javascript is built partially dynamic so I'd only have to pass a type to my PHP script. My PHP would generate the following code:
function createImageUploader(){
var fileType = 'image';
var uniqueId = '4f2c1e5d42276';
var Imageuploader = new qq.FileUploaderBasic({
    element: document.getElementById('image-uploader'),
    button: document.getElementById(fileType + '-upload-button'),
    action: '/admin/media/upload/' + uniqueId + '/' + fileType,
    debug: true,
    multiple: true,
    onSubmit: function(id, fileName){},
    onProgress: function(id, fileName, loaded, total){

    },
    onComplete: function(id, fileName, responseJSON){
        $('#' + fileType + '-upload-container').append('

      Opties

 Verwijderen

 Bekijken

')
        $('#' + fileType + '-' + responseJSON.data.Medium.id + ' img').attr('src', '/image/admin/' + responseJSON.data.Medium.src);
        $('#' + fileType + '-' + responseJSON.data.Medium.id + ' .js-delete-image').attr('data-id', responseJSON.data.Medium.id);
    },
    onCancel: function(id, fileName){

    },

    template: '

Sleep hier je bestanden om te starten.

Afbeeldingen uploaden

',
    fileTemplate: '
                Annuleren    Niet geslaagd
 ',

    classes: {
    button: fileType + '-upload-button',
    drop: fileType + '-upload-drop-area',
    dropActive: fileType + '-upload-drop-area-active',
    list: fileType + '-upload-list',

    file: fileType + '-upload-file',
    spinner: fileType + '-upload-spinner',
    size: fileType + '-upload-size',
    cancel: fileType + '-upload-cancel',

    success: fileType + '-upload-success',
    fail: fileType + '-upload-fail'
    }
});
}

window.onload = createImageUploader;

This works fine, however when I add a second - the first stops working. It has to be something small, likely someone with more javascript experience notices it quickly. I'm a PHP developer, my javascript skills are still limited.
This is the second script generated: The last one always works, the first never does.

Don't pay too much attention to the html in the code, It's included there with PHP and does not break the script.

A: You most likely would need different uniqueId in the second one.


text:
Q: Linq percentage in C# MVC I am using MVC3 with c# and I'm trying to get the percentage from the following in my model:
I retrieve the numbers:
 ... Code omitted
 AgeGroup = g.Key.AgeGroup,
 Count = (int)g.Count(),
Total = (int)
(from vw_masterview0 in ctx.vw_MasterViews
select new
{
vw_masterview0.ClientID
}).Count()
... Code omitted

I need to divide:
percent = Count/Total * 100
I have no idea how to format this in Linq.

A: You first need to cast to decimal or double to avoid integer division. After multiplying with 100 and rounding, you need to cast back to int.
The casts of the Count()s to int on the other hand are useless, Count() already returns an integer.
int count = g.Count();
int total = ctx.vw_MasterViews.Count();
int percent = (int)Math.Round((Decimal)count/(Decimal)total*100, MidpointRounding.AwayFromZero);


text:
Q: Writing a factorial() function without distinction between 0 and other numbers This question has been bugging me for quite a while: is it possible to write a factorial function (in any programming language) without any if statement (or similar) which returns 1 when called with 0 as argument too?
Many factorial functions are something like this (Python):
def factorial(n):
    for x in range(1, n):
        n *= x
    return n if n > 0 else 1

But I don't know if it can be done without distinction between varied values of n... What do you think? It is not a matter of speed and optimizing, just my curiosity.

A: 0! is defined as 1.
Here are the results from my code.
0 factorial = 1
1 factorial = 1
2 factorial = 2
3 factorial = 6
10 factorial = 3628800

And here's Java code with no if statement,
package com.ggl.testing;

public class Factorial {

    public static void main(String[] args) {
        int n = 0;
        System.out.println(n + " factorial = " + factorial(n));
        n = 1;
        System.out.println(n + " factorial = " + factorial(n));
        n = 2;
        System.out.println(n + " factorial = " + factorial(n));
        n = 3;
        System.out.println(n + " factorial = " + factorial(n));
        n = 10;
        System.out.println(n + " factorial = " + factorial(n));
    }

    public static long factorial(int n) {
        long product = 1L;

        for (int i = 2; i <= n; i++) {
            product *= (long) i;
        }

        return product;
    }

}

A: Here's a Haskell version:
factorial n = product [1 .. n]

Not sure if that's considered cheating, though.

A: There are many ways to calculate the factorial of a number with code.
The original question shows how to do it by recursion, one answer shows how to use a for loop.  The same could be achieved by a while loop.
Another answer shows the product function of an array in Haskell (similar to prod(1:n) in Matlab).
Another way to calculate factorial of n (including n=0) in Javascript whithout using a loop is:
function factorial(n){
    return (new Array(n)).join().split(",").map((x,i) => i+1).reduce((x,y) => x*y)
}

A:     def factor(n):
      fact=1
      for i in range (1,n+1):
        fact= fact*1
      return fact

    try:
      x=int(input('Input a number to find the factiorial: '))
      print(factor(x))

    except:
      print('Number should be an integer')
      x=int(input('Input a number to find the factiorial:  '))
      print(factor(x))

Hope this helps you!


text:
Q: Cobra CMD does not executes completly I have the following code, is really simple. The point is that the code after the first fmt.Println is never executed. Any idea why?
The code creates a random string, and then creates a Gin Router. The code that executes the router is never being runned.
func send(cmd *cobra.Command, args []string) {

    randomString = createRandomString()
    fmt.Println("Code for share: " + randomString)
    var files filesToSend = args

    //Create http to listen to port
    g := gin.Default()
    g.GET("/", files.sendHttpHandler)
    g.Run()
}

A: Problem is the import path in main.go vs the module name in go.mod. The capitalization is different:
package main

import "github.com/mariogmarq/goshare/cmd"

go.mod:
module github.com/mariogmarq/GoShare

It is best practice to use all lowercase for package (and module) names. From the Go Blog:

Good package names are short and clear. They are lower case, with no under_scores or mixedCaps.


text:
Q: are XML entites necessary in attribute values For example is this OK
<meta name="description" content="Foo & Bar"/>

or should I use this instead:
<meta name="description" content="Foo & Bar"/>

The doctype of the page in question is HTML5, i.e.
<!doctype html>

A: In XHTML, which this appears to be about, the first one is not OK, and the second one should be used.
You could quickly check this using the W3C Markup Validator, but the authoritative reference is the XML 1.0 specification, clause 2.4 Character Data and Markup:
"The ampersand character (&) and the left angle bracket (<) MUST NOT appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they MUST be escaped using either numeric character references or the strings "&" and "<" respectively."


text:
Q: Drupal 7 - Theme Info Name Errors After Transferring Site to New Server After transferring over a finished site to a new server, files/database and all, switching over the database settings in settings.php and running update.php I get the following errors:
Notice: Undefined index: name in block_menu() (line 146 of /home/nrsc2533/public_html/modules/block/block.module).
Notice: Undefined index: name in block_menu() (line 165 of /home/nrsc2533/public_html/modules/block/block.module).
Notice: Undefined index: name in system_menu() (line 647 of /home/nrsc2533/public_html/modules/system/system.module).
Notice: Undefined index: name in block_menu() (line 146 of /home/nrsc2533/public_html/modules/block/block.module).
Notice: Undefined index: name in block_menu() (line 165 of /home/nrsc2533/public_html/modules/block/block.module).
Notice: Undefined index: name in system_menu() (line 647 of /home/nrsc2533/public_html/modules/system/system.module).

I also lose most if not all of the items in the admin menu. I looked up the errors and they were all related to the following line of code:
'title' => check_plain($theme->info['name']),

This is a free theme that I customized, it is working fine on my test domain on my server, but not now that it has transferred. I did change the [theme].info file to reflect that it had been customized on the "name =" line. I checked online and found that the encoding may have been changed when I saved it, again strange since I had done this on the test domain and it seemed fine, so I changed the encoding to UTF-* without BOM and still to no avail. I have tried clearing the cache again via update.php and nothing changes. Any help will be GREATLY appreciated.


text:
Q: How to define string arrays in Data Contract? I have a string array in datacontract as below
[DataMember(Name = "photos", IsRequired = true, Order = 3)]
public string[] photos { get; set; }

In WCF REST Service call I am passing below xml input for this string array
<photos>
 <string>http://localhost:13169/MainPortal/ContentLibrary/21/58/1227132014-bmw-x1_100426158_m.jpg</string>
 <string>http://localhost:13169/MainPortal/ContentLibrary/21/58/122713bmw2.jpg</string>
 <string>http://localhost:13169/MainPortal/ContentLibrary/21/58/122713bmw3.jpg</string>
 <string>http://localhost:13169/MainPortal/ContentLibrary/21/58/122713BMW_Hamann_Laguna_Seca.jpg</string><string>http://localhost:13169/MainPortal/ContentLibrary/21/58/1227132014-BMW-X1-SUV-sDrive-28i-4dr-4x2-Sports-Activity-Vehicle-Exterior-2.png</string>
</photos>

My client code able to make WebService call with passing xml in HttpWebRequest without any issues, from the service I could see all other data coming in except this string array. Am I missing something in DataContract to serialize arrays. Please help
Tried with CollectionDataContract as below still no luck
[CollectionDataContract(Name = "photos")]
public class Photos : Collection<string>

Also added KnownTypes which is however not required for ordinal types
[KnownType(typeof(string[]))]
public class PublishPhotos
{

Here is complete data contract class
[DataContract(Namespace = "http://myurl.com/Publisher")]
[KnownType(typeof(string[]))]
public class PublishPhotos
{
    [DataMember(Name = "publicationId", IsRequired = true, Order = 0)]
    public int publicationId { get; set; }

    [DataMember(Name = "issueId", IsRequired = true, Order = 1)]
    public string issueId { get; set; }

    [DataMember(Name = "contentId", IsRequired = true, Order = 2)]
    public string contentId { get; set; }

    [DataMember(Name = "photos", IsRequired = true, Order = 3)]
    public Photos photos { get; set; }

}

A: Finally I figured out what went wrong with XML in HttpWebRequest, the issue is with serializing string array. The easiest way I could have figured out through visiting /PublisherSvc.svc/help for string it requires namespace http://schemas.microsoft.com/2003/10/Serialization/Arrays as below
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">http://localhost:8081/photos/1/1.jpg</string>

Hope this helps someone facing similar issue

A: I have figured out the answer to this problem. Thanks to @HarlanB
I have changed data contract from DataContract Serialization to XmlSerialization
[SerializableAttribute()]
[XmlTypeAttribute(AnonymousType = true)]
[XmlRootAttribute(Namespace = "http://myUrl.com/Publisher", IsNullable = false)]
public class PublishPhotos
{
    //[DataMember(Name = "publicationId", IsRequired = true, Order = 0)]
    [XmlElementAttribute(ElementName="publicationId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
    public int publicationId { get; set; }

    //[DataMember(Name = "issueId", IsRequired = true, Order = 1)]
    [XmlElementAttribute(ElementName = "issueId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 1)]
    public string issueId { get; set; }

    //[DataMember(Name = "contentId", IsRequired = true, Order = 2)]
    [XmlElementAttribute(ElementName = "contentId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 2)]
    public string contentId { get; set; }

    //[DataMember(Name = "photos", IsRequired = true, Order = 3)]
    [XmlElementAttribute(ElementName = "photos", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 3)]
    public string[] photos { get; set; }

}

In client code I am using XmlSerializer to write to HttpWebRequest as below
            pubPhotos.publicationId = Convert.ToInt32(publication.Value);
            pubPhotos.issueId = secName;
            pubPhotos.contentId = selectedMediaItem;

            HtmlDocument divDoc = new HtmlDocument();
            divDoc.LoadHtml(widgetScript);
            HtmlNode divNode = divDoc.DocumentNode.FirstChild;
            HtmlNodeCollection imgs = divNode.SelectNodes("//img");
            Collection<string> photos = new Collection<string>();
            foreach (HtmlNode img in imgs)
            {
                photos.Add(img.Attributes["src"].Value);
            }
            pubPhotos.photos = photos.ToArray();
        HttpWebRequest req = null;
            const string url = "http://localhost:40009/PublisherSvc.svc/PublishPhotos";
            req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/xml; charset=utf-8";
            req.KeepAlive = false;
            req.Timeout = 30000;
            req.Headers.Add("SOAPAction", url);

            XmlSerializer serilizer = new XmlSerializer(typeof(PublishPhotos));
            var sw = new StreamWriter(req.GetRequestStream());
            serilizer.Serialize(sw, pubPhotos);
            sw.Close();

I hope this helps some other people out there that are having similar problems.


text:
Q: Python code from Windows to Linux I have files with code that is formatted for windows. when I try to run them on linux machine i have problem with file encodings. Can anybody suggest a solution for this
on Windows when I run I get -
This was return from redis
Exception in thread Thread-3:
Traceback (most recent call last):
 File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
 File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bsingh/python_files/lib/Site.py", line 85, in monitor
self.update1()
File "/home/bsingh/python_files/lib/Site.py", line 78, in update1
for entry in new_pastes[::-1]:
TypeError: 'NoneType' object has no attribute '__getitem__'

A: You should try -
dos2unix <filename>

To convert files created in windows to unix format. Reference
Please note dos2unix, is not python code conversion, it would convert dos characters to unix equivalent.

A: if you think this is a problem about file encodings.
maybe you should add
# -*- coding: utf-8 -*-

or
# coding: utf-8

in the head(line 1 or line 2) of any python script file.


text:
Q: Regex an unordered list, separated by different 'delimiters' in python I'm trying to construct a regex to capture strings that match \w{0,}?\s\d){0,} i.e, a word followed by space then a number. I've mocked it up here
The first N matches that are only separated by a comma are group 1.
The N matches after the string ' opt ', that are only separated by commas are group 2
The N matches after the string ' and/or ', that are only separated by commas are group 3
My attempt is this: ((\w+?\s\d),\s+(\w+?\s\d))*(\s+and/or\s+(\w+?\s\d))*(\s+opt\s+(\w+?\s\d))*
Mind 3 opt Life 3, Prime 3 and/or Death 3 #This is not matched
Life 3, Mind 3 opt Prime 3 and/or Death 3 #This is matched
Life 3, Death 3 and/or Mind 3 opt Prime 3 #this is matched

But I'm sure there edge cases I'm not thinking of. And I fundamentally know this is order related, which I don't want.

A: (?:|\s+and/or\s+|\s+opt\s+)((\w+?\s\d)(?:,\s+(\w+?\s\d))*)*
You are looking for three separate scenarios:
String starts with nothing or String starts with ' opt ' or String starts with ' and/or '
This is the same as:
(?:                     # Non matching group
    |                   # Nothing or
    \s+and/or\s+|       # ' and/or ' or
    \s+opt\s+           # ' opt '
)                       # followed by

And then in each scenario you're looking for one or more lots of (\w+?\s\d) separated by a comma.
(
    (\w+?\s\d)          # a word followed by a single digit
    (?:,\s+             # preceeding comma and at least one space.
        (\w+?\s\d))*    # zero or more word-digit combinations as above,
)*                      # Any number of these

The explanation is much better on the above link.


text:
Q: what are the techniques to extract files safely? Yesterday I was making some experiments on Slitaz. It uses multiple initrd.img's to store files/changes.
I wanted to extract one of its initrd.gz images (which is a cpio archive) to a folder, edit/remove them, repack again.
I used this code:
cat rootfs.img | cpio -idvm

Then all files are extracted to my root filesystem. My whole OS is corrupted. (What an emberrasing situation...)
What should I do to make such operations safely but in an easy way? Chroot? LXC? (VirtualBox is the last resort)

A: Archived with relative paths
I would advise against running that type of command at your root level, /. That's asking for trouble. I always run cpio -idvm related commands in their own directories, and then use mv or cp to put the files where they need to be manually.
You can also use the method I described in this other U&L Q&A titled: How do I install TazPkg in SliTaz Linux, which also makes use of cpio.
Archived with absolute paths
If the archive was built with absolute paths you can tell cpio with the --no-absolute-filenames switch to block it from extracting into /.
$ mkdir /tmp/cpio-root
$ cd /tmp/cpio-root
$ cat rootfs.img | cpio -idvm --no-absolute-filenames

References

*

*CPIO archive with absolute paths- extraction to a different directory?

A: You can use the unp utility for this.
unp is a utility for unpacking multiple formats. One of it's features (the -U argument) is the ability to look into the archive and see if it has multiple root elements. If it does, it extracts them into a directory.
For example:
$ echo $RANDOM > a
$ echo $RANDOM > b
$ tar -cf archive.tar a b
$ rm a b
$ unp -U archive.tar
$ ls -l a b archive
ls: cannot access a: No such file or directory
ls: cannot access b: No such file or directory
archive:
total 8
-rw-r--r-- 1 root root 5 Jun 15 03:16 a
-rw-r--r-- 1 root root 6 Jun 15 03:16 b

unp works with many different formats (including cpio). It just calls out to the appropriate utility for handling the archive:
# unp -s
Known archive formats and tools:
7z:           p7zip or p7zip-full
ace:          unace
ar,deb:       binutils
arj:          arj
bz2:          bzip2
cab:          cabextract
chm:          libchm-bin or archmage
cpio,afio:    cpio or afio
dat:          tnef
dms:          xdms
exe:          maybe orange or unzip or unrar or unarj or lha
gz:           gzip
hqx:          macutils
lha,lzh:      lha
lz:           lzip
lzma:         xz-utils or lzma
lzo:          lzop
lzx:          unlzx
mbox:         formail and mpack
pmd:          ppmd
rar:          rar or unrar or unrar-free
rpm:          rpm2cpio and cpio
sea,sea.bin:  macutils
shar:         sharutils
tar:          tar
tar.bz2,tbz2: tar with bzip2
tar.lzip:     tar with lzip
tar.lzop,tzo: tar with lzop
tar.xz,txz:   tar with xz-utils
tar.z:        tar with compress
tgz,tar.gz:   tar with gzip
uu:           sharutils
xz:           xz-utils
zip,cbz,cbr,jar,war,ear,xpi,adf: unzip
zoo:          zoo

The --help output showing what it can do:
# unp --help

USAGE:
   /usr/bin/unp [ options ] file [ files... ]
   file: compressed file(s) to expand/extract

   Use -- [ ARGUMENTS ] to pass arguments to external programs, eg. some tar options:
   unp fastgl.tgz xmnt.tgz -- -C /tmp

   Options:
   -f Continue even if program availability checks fail or directory collision occurs
   -u Special helper mode.
      For most archive types:
      - create directory <filename without suffix>/
      - extract contents there
      For Debian/Ubuntu packages:
      - extract data.tar.gz after each operation in local directory
      - extract control.tar.gz into control/<package_version_arch>/
   -U Smart mode, acts like -u (see above) if archive contains multiple
      elements but if there is only one file/directory element then it's stored
      in the current directory.
   -s Show the list of supported formats
   -v More verbosity
   -h Show this help


text:
Q: Android: How to Implement a Settings Page Within a Navigation Drawer? So I'm in the process of creating an app which utilises a Navigation Drawer which is split into separate fragments to access each of the tabs. Now, the thing I would like to find out how to do, is to equally have a Settings/Preferences Fragment or Activity (unsure which one would be appropriate in this context) to open once the user selects the "Settings" tab within the Navigation Drawer. I've looked all over the internet for a CLEAR explanation on how to do this, as I'm not an expert on app development.
Below is a picture of the Navigation Drawer:

If any layout or class code is required, I am happy to provide it. Any help is much appreciated!

A: You can use the PreferenceFragmentCompat, for example:
First you create a Fragment who extends PreferenceFragmentCompat and the layout associated under the folder res/xml
settings.xml
<android.support.v7.preference.PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.preference.PreferenceCategory
        android:key="the_key_to_retrieve_the_preference_in_code"
        android:title="the_preference_title">

        <android.support.v7.preference.Preference
            android:key="key"
            android:summary="subtitle"
            android:title="title" />

        <android.support.v7.preference.Preference
            android:key="key2"
            android:summary="subtitle2"
            android:title="title2" />

        <android.support.v7.preference.CheckBoxPreference
             android:key="key_for_check_box"
             android:summary="subtitle"
             android:title="title" />

    </android.support.v7.preference.PreferenceCategory>
</android.support.v7.preference.PreferenceScreen>

SettingsFragment.java
public class SettingsFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.settings);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
       // To get a preference
       PreferenceScreen preferenceScreen = getPreferenceScreen();
       Preference preference = preferenceScreen.findPreference("preference_ key_defined_in_the_xml");

     //You can set a listener
     preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                return false;
            }
        });

     //change title
     preference.setTitle("my_title");

     // etc
    }
}

Then you create a Activity who will hold the fragment:
SettingsActivity.java
public class SettingsActivity extends AppCompatActivity {
    private Toolbar mToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        setActionBarTitle("Settings");
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
}

settings_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

    <fragment
        android:id="@+id/settings_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:name="package.name.SettingsFragment"/>

</android.support.design.widget.CoordinatorLayout>

Be sure to add the new Settings activity to your manifest
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.app">

    <application
            android:name=".MyApplication"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <!-- add the below line to your AndroidManifest.xml -->
        <activity android:name=".SettingsActivity"></activity>

    </application>

</manifest>

That it , then when you click on the item in your NavigationDrawer you set a new Intent and call it:
Intent intent = new Intent(this /*or the actual context*/, SettingsActivity.class);
startActivity(intent);

Hope this helps.
Sorry for my english.


text:
Q: Please I'm stuck in this homogeneous equation $$(xy'-y)\arctan y/x=x;(xy'-y)=x/(\arctan y/x)$$
$$y=ux$$
$$y'=u'x+u$$
$$(x(u'x+u)-ux)$$
$$\arctan(xu)/x =x; x^2 u'\arctan u=x; x^2$$
$$du/dx= x/(\arctan (u))$$
$$du/dx=1/(x\arctan (u))$$
$$dx/x=\arctan(u)du$$
$$∫dx/x=\ln(x)$$
.... Help?

A: We are trying to solve:
$\displaystyle \left(x  \frac{dy}{dx} -y\right) tan^{-1}\frac{y}{x} = x$
Letting $y = x v$, yields $\displaystyle \frac{dy}{dx}  =  v+x \frac{dv}{dx}$, so:
$\displaystyle \left(x \left(v + x \frac{dv}{dx}\right)-x v\right) \tan^{-1}v = x$
Simplifying yields:
$\displaystyle x^2 \frac{dv}{dx} \tan^{-1}v = x$
Divide both sides by $x^2$, yielding:
$\displaystyle \frac{dv}{dx} \tan^{-1}v  =  \frac{1}{x}$
Integrate both sides with respect to $x$, yielding:
$\displaystyle \int \frac{dv}{dx} \tan^{-1}v dx  =   \int \frac{1}{x} dx$, so
$\displaystyle v \tan^{-1}v -\frac{1}{2} \ln(v^2+1)  =  c_1+\ln(x)$, where $c_1$ is an arbitrary constant.
Substituting back for $y  =  x v$, yields:
$$\displaystyle \frac{y \tan^{-1}(\frac{y}{x})}{x}  -\frac{1}{2} \ln\left(\frac{y^2}{x^2}+1\right) = c_1+\ln(x)$$


text:
Q: LINQ to SQL with stored procedures and user defined table type parameter I am using LINQ to SQL with stored procedures in SQL Server 2008. Everything work well except one problem. L2S cannot generate the method for the stored procedure with user defined table type as parameter.
Method signature in dbml design panel use object for parameter type instead of table type and when I tried to compile I got error:
Error: DBML1005: Mapping between DbType 'Structured' and
Type 'System.Object' in Parameter 'ParaName' of Function 'dbo.StoredProcName'
is not supported.

Is there a way to work around this of this problem? I don't want to go back to traditional ADO.NET data access.

A: I happened upon this post that provides a means of calling stored procedures with TVP parameters from Linq2Sql. It's a round about method that basically creates a partial class extension of your dataContext and passes a dataTable using an SqlCommand. I hope it helps.

A: I don't think there's anything available right now - table-valued parameters were introduced in SQL Server 2008 - after LINQ and LINQ2SQL were out already.
I haven't found any mention in any of the blog post about support for table-valued parameters in LINQ2SQL in .NET 4.0 so far.
UPDATE:
Here's a blog post by Damien Guard on the fixes and improvement for Linq-to-SQL in the .NET 4.0 time frame.
UPDATE 2:
Unfortunately, according to Damien, this feature isn't supported in .NET 3.5, and will not be supported in .NET 4.0 either :-(
Can't be done in 3.5 or 4.0 right now
:( [)amien

A: I had the exact same problem and Ryan Prechel's sample code from the following link helped me solve the problem.
How to pass table value parameters to stored procedure from .net code