text:
Q: Proving particular case of Abel's series convergence criterion I need the following to proof a particular case of the Abel's general convergence criterion which goes as follows:

Let $\Omega$ be a non-empty subset of $\mathbb{C}$ and A a non-empty
  subset of $\Omega$. Let $f_n$ and $g_n$ be two sequences of functions
  from $\Omega$ to $\mathbb{C}$ with the following properties:
1.1) $\sum f_n$ converges uniformly in A.
1.2) The series  $\sum (|g_1|+ \sum |g_n-g_{n+1}|)$ has bouded partial
  sums in A.
Then the series $\sum f_ng_n$ converges uniformly in A.

The particular criterion I want to proof goes as follows:

Let $\Omega$ be a non-empty subset of $\mathbb{C}$ and A a non-empty
  subset of $\Omega$. Let $f_n$ be a sequence of functions from $\Omega$
  to $\mathbb{C}$ and $a_n$ a sequence of complex numbers with the
  following properties:
1.3) $\sum a_n$ is convergent
1.4) For each $z \in A, {f_n(z)}$ is a monotonic sequence of real
  numbers and ${f_n}$ is uniformly bounded in A.
then $\sum a_nf_n$ converges uniformly in A.

The theorem I should be using to proof it is:

If $b_n$ is monotonic and bounded then $\sum |b_n - b_{n+1}|$ is
  convergent.

It is clear for me that 1.4 is a particular case of 1.1 but my problem is that I don't really see how to mix the uniformly bounded condition in 1.3 with the bounded condition of partial sums in 1.2. It should begin like $\forall z \in A,\{f_n(z)\}$ is monotone and bounded therefore...


text:
Q: class design for for a dynamic GetHash function I have the requirement to calculate an internal hashcode of instances of several types (some types are derived from each other). Two aspects are dynamic here and can vary independently. Only the client that requests the hash knows what hash algorithm is to be used and what properties are to be included.

*

*The actual algorithm that is used
for the hash caluctation can change.

*What members for each type should be take into account for the hash calculation can change.

How would you design your types around these requirement?

A: Here are some guidelines for GetHashCode() from Eric Lippert.
http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/
An excerpt:
Rule: the integer returned by GetHashCode must never change while the object is contained in a data structure that depends on the hash code remaining stable
It is permissible, though dangerous, to make an object whose hash code value can mutate as the fields of the object mutate. If you have such an object and you put it in a hash table then the code which mutates the object and the code which maintains the hash table are required to have some agreed-upon protocol that ensures that the object is not mutated while it is in the hash table. What that protocol looks like is up to you.
In short, if the algorithm for generating the hash code can change, then you need to make sure that it doesn't change while the object is in your collection.

A: First, require all "hashable" objects to implement the same interface, with one method: getHash().
Second, introduce an Abstract Factory instantiating hash Strategies.
Example (Java 1.6):
public class Foo implements Hashable {
  private String field;
  @Override
  public String getHash() {
    HashFactory.INSTANCE.getMD5Strategy().hash(this.field);
  }
}

Proper encapsulation of decision making inside your objects, and an effective decoupling of strategies and objects.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How should I return HTML in a React.js class component without getting an error? I am having issues trying to set up a couple of routes in my react web application, and I was hoping someone more knowledgable would be able to help me better understand whats going on.
So, in App.js I am using a creating a BrowserRouter, inside of it I have some HTML, then I also have a few Routes should show a different component on the screen depending on what URL you are at, or if you follow a  within those class components:
// imports omitted for simplicity

function App() {
  return (
    <BrowserRouter>
      <NAVBAR />

          <Routes>
            <Route path="/" element={() => VIEW_LIST } />
            <Route path="/browse" element={() => BROWSE_ITEMS } />
          </Routes>

    </BrowserRouter>
  );
}

export default App;

Where I am running into issues is that whenever I try to access one of those URLs in a browser, none of my elements from that component render and I get an error in the console telling me that:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

Where I think my issue lies is somewhere in my component class with how I try to build my component with data retrieved from some endpoint.
Here is an example of what one of my component classes looks like:
export class VIEW_LIST extends Component {
    constructor (props) {
        super(props);
        this.state = {
            list_elements:''
        }
    }

    componentDidMount() {
        getList()
            .then(res => res.json())
            .then(data => {
                console.log(data);
                this.setState({list_elements: data});
                return(

                        I got the data

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

    render () {
        if(this.state.list_elements != null) {
            return (

            )
        } else {
            return (

                    Loading...

            )
        }

    }

}

Does anyone have any idea what might be going on here?
NO THAT DOES NOT ANSWER MY QUESTION STOP DOING THAT TO ALL MY QUESTIONS


text:
Q: vercel not running build and instal commands and not creating Serverless functions I am trying to move my application's API to Vercel. It is written in Typescript and uses Express.
The index.ts is located in <root>/src. The npm run build compiles it into <root>/dist directory. The file contains the following:
const app = express();
app.use((req: Request, res: Response, next: NextFunction) => {
  //blah, blah, there is a lot going on here
})
app.use('/', common);
//... other app.use(s)

const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on ${port}, http://localhost:${port}`));

module.exports = app;

I've got the following in the vercel.json file which is located in the root directory where the package.json also is:
{
  "version": 2,
  "installCommand": "npm install",
  "buildCommand": "npm run build",
  "outputDirectory": "dist",
  "builds": [
    {
      "src": "dist/index.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "dist/index.js"
    }
  ]
}

When locally I run npm run build, then vercel dev --listen 5000 I get Ready! Available at http://localhost:5000 and can go to http://localhost:5000/ping and get a response.
Now I commit the files to git, the deployment runs, but judging by the logs the npm install and npm run build commands are not running. No functions are created my /ping endpoint returns "Page not found".

Here is the deployment log:

This is what Build & Development Settings look like (the Root Directory is left blank):

I followed several recommendations I found online and according to them everything should work. I probably miss some setting somewhere. What is it?
If more information is needed, please let me know, I'll update my question.
Thank you.
--- UPDATE ---
I have set the Root Directory to src and checked the "Include source files outside of the Root Directory in the Build Step" checkbox. Now the npm install and npm run build are executing. As you can see some static files are deployed, but there are still no serverless functions and my /ping route returns 404 and "home" page, i.e. / route returns the content of the index.js file. In addition the local is not working either anymore, also returning 404 now.

Without that checkbox I was getting
Warning: The vercel.json file should exist inside the provided root directory
and still no install or build running.
Also worth noting that I had to change my tsconfig.json to have "outDir": "src/dist" instead of "outDir": "dist", otherwise I was getting
Error: No Output Directory named "dist" found after the Build completed. You can configure the Output Directory in your Project Settings.
Removed the Root directory and back to square one, no npm commands running but local is working with / route returning Cannot GET / and /ping returning correct response.

A: For everyone out there who's looking for an answer, maybe this will help you.
In my case, what I needed is to create a folder, called api in my src folder, i.e. the folder that is specified as Root Directory in Build & Development Settings in Vercel. Within this directory, each serverless function needs a file named the same as the path of the route. For example, the file named "my-route.js" will be accessible via https://my-app-name.vercel.com/api/my-route.
All this file needs is an import of index.js file and module.exports. For example:
import app from '../index';
module.exports = app;

The index.js should also live the Root and contain your express setup.
If you want to have dynamic path parameters, the files' names in the api directory should be wrapped in square brakets, like [my-param.js]. You can also have sub-directories in the api foler.
Here are a few links that helped me figure this out:
https://dev.to/andrewbaisden/how-to-deploy-a-node-express-app-to-vercel-2aa
https://medium.com/geekculture/deploy-express-project-with-multiple-routes-to-vercel-as-multiple-serverless-functions-567c6ea9eb36
https://ryanccn.dev/posts/vercel-framework/#path-segments
No changes were needed in my existing Express setup and routes files.
Hope this will help someone. Took me quite a while to figure it all out :)


text:
Q: Why doesn't Chrome browser recognize my http2 server? I setup my Nginx conf as per  Digital Ocean paper,
and now http2 is available.
But in Chrome (Version 54.0.2840.98 (64-bit))  Dev tool, it's always on HTTP 1/1:
NAME             METHOD  STATUS  PROTOCOL
shell.js?v=xx..    GET    200     http/1/1

My server is running Ubuntu 16.04 LTS which supports both ALPN & NPN, and the openssl version shipped with it is 1.0.2g.
I checked http2 support with this tool site and the result is:
Yeah! example.com supports HTTP/2.0. ALPN supported...

Also checking with curl is OK:
 $ curl -I --http2 https://www.example.com
  HTTP/2 200
  server: nginx/1.10.0 (Ubuntu)
  date: Tue, 13 Dec 2016 15:59:13 GMT
  content-type: text/html; charset=utf-8
  content-length: 5603
  x-powered-by: Express
  cache-control: public, max-age=0
  etag: W/"15e3-EUyjnNnyevoQO+tRlVVZxg"
  vary: Accept-Encoding
  strict-transport-security: max-age=63072000; includeSubdomains
  x-frame-options: DENY
  x-content-type-options: nosniff

I also checked with is-http2 cli from my console:
is-http2 www.amazon.com
× HTTP/2 not supported by www.amazon.com
Supported protocols: http/1.1

is-http2 www.example.com
✓ HTTP/2  supported by www.example.com
Supported protocols: h2 http/1.1

Why doesn't Chrome recognise it?
How can I check it also with Safari (v 10.0.1)?

A: Will likely be one of two reasons:

*

*You are using anti-virus software and it is MITM your traffic and so downgrading you to HTTP/1.1. Turn off https traffic monitoring on your AV to connect directly to the server. You can check if this is the case by using an online tool to test your site for HTTP/2 support.

*You are using older TLS ciphers and specifically one that Chrome disallows for HTTP/2 (https://http2.github.io/http2-spec/#BadCipherSuites) as per Step 5 of above guide. Scan your site using https://www.ssllabs.com/ssltest/ to check your TLS config and improve it.
The third reason is lack of ALPN support in your SSL/TLS library (i.e. You are using openssl 1.0.1 and need to be one 1.0.2 or later, for example) but you have already confirmed you have ALPN support so skipping that for this answer.

A: I had the same issue. I my case it was because I enabled TLS1.3 in NGINX. See Why is my site not using http/2 while it is http/2 enabled

A: In my case, chrome generated following excerpt in chrome-net-export-log.json file.
HTTP2_SESSION_RECV_INVALID_HEADER--> error = "Invalid character in header name."--> header_name = "x-xss-protection:"--> header_value = "1; mode=block"
After removing : from the header name, the problem was resolved.


text:
Q: Issue implementing infinite scrolling I have an issue implementing infinite scrolling. I have seen some questions similar to mine but didn't find a solution to mine.
I also tried to implement the solution in this question: How to implement pagination on a custom WP_Query Ajax
Mainpage.php:

    <?php
        $postsPerPage = 4;
        // args
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => $postsPerPage,
            'product_cat' => 'seating',
        );
        // get results
        $the_query = new WP_Query( $args );
        // The Loop
    ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <?php wc_get_template_part( 'content', 'product' ); ?>
    <?php
        endwhile;
        echo 'Load More';
    ?>
    <?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>

at the end of same page:


text:
Q: How to toggle drawer navigator in react native? I am using drawer navigation. When I click on the hamburger menu icon the drawer of the drawer navigation is not working, I am not able to toggle the drawer. Code 1 is not working but code 2 is working, can anyone help me figure out why ?
Code:
    Burger menu icon code 1:

    // Inside Header
    navigationOptions: ({ navigation }) => ({
                // headerTitle: 'Rchampz',
                headerLeft:
                <TouchableOpacity  onPress={() => {navigation.dispatch(DrawerActions.toggleDrawer())} }>
                    <MenuImage navigation={navigation}/>
                </TouchableOpacity>,

//Created component and added inside navigationOptions

    const MenuImage = ({navigation}) => {
        if(!navigation.state.isDrawerOpen){
            return <TouchableOpacity><Image source={require('../assets/images/menu.png')} style={{width: 24, height: 24, resizeMode: 'contain' ,marginLeft: 15}}/></TouchableOpacity>
        }else{
            return <MenuIcon style={{paddingLeft: 10, paddingRight: 10}} name="md-arrow-back" size={30} color="black"/>
        }
    }

    Burger menu icon code 2:

    //Inside header

    navigationOptions: ({ navigation }) => ({
                // headerTitle: 'Rchampz',
                headerLeft:
                <TouchableOpacity  onPress={() => {navigation.dispatch(DrawerActions.toggleDrawer())} }>
                    <MenuImage navigation={navigation}/>
                </TouchableOpacity>,

//Created component and added inside navigationOptions

    const MenuImage = ({navigation}) => {
        if(!navigation.state.isDrawerOpen){
            return <MenuIcon style={{paddingLeft: 10, paddingRight: 10}} name="md-menu" size={30} color="black"/>
        }else{
            return <MenuIcon style={{paddingLeft: 10, paddingRight: 10}} name="md-arrow-back" size={30} color="black"/>
        }
    }

A: Because of the way that you have setup your menu image in the first one. You wrapped the Image within another TouchableOpacity which means that the inner TouchableOpacity is picking up the user touch event. This is not actually the behavior you want because you want the TouchableOpacity on headerLeft to be the receiver of the input. So simply remove the "extra" TouchableOpacity.
// Inside Header
navigationOptions: ({ navigation }) => ({
    headerLeft:
    <TouchableOpacity onPress={() => {navigation.dispatch(DrawerActions.toggleDrawer())} }>
        <MenuImage navigation={navigation}/>
    </TouchableOpacity>,

//Created component and added inside navigationOptions
const MenuImage = ({navigation}) => {
    if(!navigation.state.isDrawerOpen){
        // No need of Touchable here. Since you want the above Touchable to pick up the onPress event.
        return <Image source={require('../assets/images/menu.png')} style={{width: 24, height: 24, resizeMode: 'contain' ,marginLeft: 15}}/>.
    }else{
        return <MenuIcon style={{paddingLeft: 10, paddingRight: 10}} name="md-arrow-back" size={30} color="black"/>
    }
}

The reason why the second example works is simply that, there is no extra Touchable handling the onPress event.


text:
Q: Calling A javascript function via a form of reflection? in jquery So I have these two javascript functions:
function some_name(say_something){
    console.log('hello' + say_something);
}

call_other_fuction_after_doing_something('some_function')

// In some other file, some where - in the land of make believe.
function call_other_fuction_after_doing_something(function_name){
    $.ajax({
        url : /*Go some where*/,
    type : 'POST'
    data : { /*Some kind of data*/},
    success : function(result){
        if(function_name !== undefined){
        $.fn[success_action](result); // Pay attention to this!
        }
    },
    });
}

So as we can see I do some function in some file, some where that logs to the console: "hello"  which then has what ever the result is that comes back from the ajax call appended to it.
I assumed this would work, as I read something about this here in this question. But apparently I was wrong as the error I get is:
Uncaught TypeError: Object [object Object] has no method 'some_name'

Any ideas how to do this kind of "Reflection" in javascript (jquery)?

A: What you are trying to do is to call a function which is a property of $.fn, which it looks like does not exists.
Try passing the function reference instead of name
function some_name(say_something){
    console.log('hello' + say_something);
}

call_other_fuction_after_doing_something(some_name)

//In some other file, some where - in the land of make believe.
function call_other_fuction_after_doing_something(fn){
    $.ajax({
        url : /*Go some where*/,
    type : 'POST'
    data : { /*Some kind of data*/},
    success : function(result){
        if(typeof fn == 'function'){
            fn(result); // Pay attention to this!
        }
    },
    });
}


text:
Q: change the background color of textview according to textview shape when click on text view I have three Material text views, I want to change the background color of the text view according to the text view shape. I tried multiple options but it goes outside of text view shape. I have round corners text view but color fill like a simple rectangle.
 <com.google.android.material.textview.MaterialTextView
        android:id="@+id/textViewLoseWeight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="65dp"
        android:text="Lose Weight"
        android:textColor="@color/purple_500"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewGoals"
        tools:ignore="MissingConstraints" />

    <com.google.android.material.textview.MaterialTextView
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_marginTop="4dp"
        android:id="@+id/textViewLoseWeightSubtitle"
        android:background="@drawable/textview_outline_style"
        android:paddingStart="16dp"
        android:paddingTop="16dp"
        android:text="Get leaner and improve Your fitness"
        android:textColor="@color/purple_500"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewLoseWeight" />

 //.java
    View.OnClickListener listener = new View.OnClickListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.textViewLoseWeightSubtitle:
                        mLoseWgt.setBackgroundColor(Color.parseColor("#363C60"));
                        mLoseWgt.setTextColor(Color.WHITE);

after clicking on the text view, it changes like above. I want background color inside  round corner shape like the original text view have

A: You define your TextView and also it's android:background attribute:
 <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Get leaner and improve Your fitness"
            android:background="@drawable/round_fill_color"
            android:layout_centerInParent="true"
            android:textColor="#ffffff"
            android:padding="10dp"/>

    </RelativeLayout>

And here the mentioned attribute in a new drawable called round_fill_color.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#363c60"/>
    <stroke android:width="3dp" android:color="#ffffff" />
    <corners android:radius="30dp"/>
    <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
</shape>

That is the suggested way to make custom attributes for single widgets.
If you want to define one layout for all I recommend to do that over styles.xml and themes.
The result:

A: You can use something different:
        <com.google.android.material.textview.MaterialTextView
            android:id="@+id/textview"
             ../>

and then apply a MaterialShapeDrawable
    val radius = resources.getDimension(R.dimen.default_corner_radius)

    val shapeAppearanceModel = ShapeAppearanceModel()
        .toBuilder()
        .setAllCorners(CornerFamily.ROUNDED, radius)
        .build()

    val shapeDrawable = MaterialShapeDrawable(shapeAppearanceModel)
    shapeDrawable.fillColor = ContextCompat.getColorStateList(this,R.color.xxx)
    shapeDrawable.setStroke(2.0f, ContextCompat.getColor(this,R.color.xx));
    ViewCompat.setBackground(textView, shapeDrawable)

Use this ShapeAppearanceModel to have 50% rounded corners:
val shapeAppearanceModel = ShapeAppearanceModel()
    .toBuilder()
    .setAllCorners(RoundedCornerTreatment())
    .setAllCornerSizes(RelativeCornerSize(0.5f))
    .build()


text:
Q: Count all duplicates in ListView column. C# I'm creating a software for a marketplace and want to create a listview that counts all the duplicate values inside a column.
This count will show how many items were oftenly bought by buyers.
This is the concept of the ListView should be.
It counts from column of ListView1, and put the duplicates, count it, and display the data inside of ListView2.

I need to know:

*

*How to Count all the duplicated value inside the "Purchased Items" column.

*And display the count result inside another ListView with the value itself.

Note: In this case, the value inside the "Name" is an Item and the "Purchased Items" is a Subitem. Those data were from simply typing in a textbox and clicking on a button.

A: Group the items of the input ListView by the values of the second ColumnHeader (index = 1) to get IEnumerable<IGrouping<string, ListViewItem>>, then use the elements (of type IGrouping<string, ListViewItem>) Key property and Count method to create the ListViewItem objects of the output ListView.
Here's a one liner:
listView2.Items.AddRange(listView1.Items
    .Cast<ListViewItem>()
    .GroupBy(x => x.SubItems[1].Text, StringComparer.OrdinalIgnoreCase)
    .Select(x => new ListViewItem(new[] { x.Key, x.Count().ToString() }))
    .ToArray());

A: The outcome you want can be achieved using System.Linq.GroupBy for the logic and DataGridView (Winforms Example) for the views:

The amount of code to write is small! Just use Data Binding Winforms, Xamarin, WPF for two lists:
First make two classes containing the properties you wish to display:
internal class UserPurchase
{
    public string Name { get; internal set; } // Internal makes item ReadOnly in view
    public string Purchase { get; internal set; }
}

and
internal class PurchasedItem
{
    public string Description { get; internal set; }
    public int Count { get; internal set; }
}

Then declare two BindingList (Winforms example) or ObservableCollection (others).
internal BindingList<UserPurchase> PurchasesByUser { get; } = new BindingList<UserPurchase>();
internal BindingList<PurchasedItem> PurchasedByItem { get; } = new BindingList<PurchasedItem>();

This shows how to attach the bindings in Winforms (for other platforms use the xaml). As a result DataGridView will now generate columns automatically using the properties of the two classes.
protected override void OnHandleCreated(EventArgs e)
{
    base.OnHandleCreated(e);
    if (!DesignMode)
    {
        // Bind the lists to the UI element to display them.
        dataGridView1.DataSource = PurchasesByUser;
        dataGridView2.DataSource = PurchasedByItem;
        initList1();
    }
}

Here is the list initializer which populates List1 PurchasesByUser then applies System.Linq.GroupBy on List1 to calculate List2 PurchasedByItem:
private void initList1()
{
    XElement xsource = XElement.Parse(source);
    XElement[] xusers = xsource.Elements("user").ToArray();
    foreach (XElement xuser in xusers)
    {
        XElement[] xpurchases = xuser.Element("items").Elements("item").ToArray();
        foreach (XElement xpurchase in xpurchases)
        {
            var xname = xuser.Element("name");
            // Every time you add a record to the list, it appears in the View automatically.
            PurchasesByUser.Add(new UserPurchase { Name = (string)xname, Purchase = (string)xpurchase });
        }
    }
    // Make what is essentially a list *of* lists using System.Linq.GroupBy
    var groups =
        PurchasesByUser.GroupBy(purchase => purchase.Purchase);
    foreach (var group in groups)
    {
        // Decoding the Group:
        Debug.WriteLine(
            $"The group '{group.Key}' holds {group.Count()} items");
        Debug.WriteLine(
            $"The customers are { string.Join(",", group.ToList().Select(item=>item.Name))}");
        var byItem = new PurchasedItem { Description = group.Key, Count = group.Count() };
        PurchasedByItem.Add(byItem);
    }
}

Finally to model your database (with subitems), I used this string in Xml format:
const string source =
    @"<purchases>
        <user>
            <name>John Doe</name>
            <items>
                <item>Shoes</item>
                <item>T-Shirts</item>
                <item>Jeans</item>
            </items>
        </user>
        <user>
            <name>Rick Astley</name>
            <items>
                <item>Baseball bat</item>
                <item>Sandwich</item>
                <item>T-Shirts</item>
                <item>Shoes</item>
            </items>
        </user>
        <user>
            <name>Jane Doe</name>
            <items>
                <item>Shoes</item>
                <item>T-Shirts</item>
            </items>
        </user>
        <user>
            <name>Anonymous</name>
            <items>
                <item>Laptop</item>
            </items>
        </user>
        <user>
            <name>Joe Mm.</name>
            <items>
                <item>Milk</item>
                <item>Shoes</item>
            </items>
        </user>
    </purchases>";

This is just one approach of course but your question is a good way to demonstrate combining concepts from System.Linq System.Xml.Linq and Data Binding. I posted my code on GitHub if you'd like to experiment with it.

A: So if I understand you want to have another listview with duplicates and the count?
If so you can create a List<> and then add that item into the list in this case will be a string I believe, maybe something like this? This is just a console app for demonstration.
List<string> myList = new List<string>();

myList.Add("One");
myList.Add("Two");
myList.Add("Three");
myList.Add("One");
myList.Add("Two");
myList.Add("Four");

List<string> noDupes = myList.Distinct().ToList();

foreach(string dupe in noDupes)
{
    Console.WriteLine(dupe);
}

Console.WriteLine(noDupes.Count());

A: Given the next list:
List<myClass> items = new List<myClass>()
{
    new myClass() { Name = "John Doe", Item = "Shoes" },
    new myClass() { Name = "John Doe", Item = "T-Shirt" },
    new myClass() { Name = "John Doe", Item = "Jeans" },
    new myClass() { Name = "Rick Astley", Item = "Baseball bat" },
    new myClass() { Name = "Rick Astley", Item = "Sandwich" },
    new myClass() { Name = "Rick Astley", Item = "T-Shirt" },
    new myClass() { Name = "Rick Astley", Item = "Shoes" },
    new myClass() { Name = "Jane Doe", Item = "Shoes" },
    new myClass() { Name = "Jane Doe", Item = "T-Shirt" },
    new myClass() { Name = "Joe Mm.", Item = "Shoes" },
    new myClass() { Name = "Joe Mm.", Item = "Milk" },
};

You can group and count in this way:
var l = items.GroupBy(group => group.Item)
                .Select(n => new { Item = n.Key, Count = n.Count() })
                .ToList();

The result:
Item: Shoes  Count: 4
Item: T-Shirt  Count: 3
Item: Jeans  Count: 1
Item: Baseball bat  Count: 1
Item: Sandwich  Count: 1
Item: Milk  Count: 1


text:
Q: Best practice - how to pass SES IAM User credentials to an Fargate Task? I 've got a question regarding the handling of "hardcoded" secrets in AWS. Here is my setup:
We are running a Fargate cluster consisting of 3 services. One of the services (The backend) needs credentials to our SES account (mail sending) and S3 bucket (File Storage). At the moment we use the AWS secrets manager which holds the credentials of the ses-smtp user and the s3 user and injects the secret values as environment variables at the starup of the container. The entire stack (Except the SES which is in an other region) is created using cloud formation templates. The required secrets are also created by a template. And there is my "problem" - at the moment the secrets template contains the hardcoded SES and S3 credentials which is bad since the template gets pushed to the templates bucket (it's not public but anyways) and it could potentially got committed to version control where it will be exposed to anyone who has reading access to the project. The question is - what is the best practice to pass the SES and S3 Credentials to the container without exposing them at any place?
Thanks in advance,
Al

A: Use IAM for SES and S3 Access
Your ECS cluster has a task  role.
It is assumed by your underlining containers, and those will have all of the access defined in your role, policies attached to it.
AWS services access
For your SES and S3 access create policies with restricted access and attach those to the role.
Regular credentials
For some plain text credentials, I would recommend creating those in the parameter store and map those into the container in your task-definition. Pass secrets safely.
You should not create your parameter store secrets in the cloud formation template, it is better to add those manually, and reference from where you need those.


text:
Q: Variables come zero when I call from another class This is my class that I am using to keep all values. In this class I used object oriented model,
but whenever if I want to call in Form2.cs I am not able to reach values properly.
If I call the variables in Form1.cs there is a no problem at all.
class1.cs
public class Class1
    {
        public Class1()
        {

        }
        public Class1(double Yb, double Yz, double Yd, double Cz, double Fz, double qT, double Kt, double Qs, double Sds, double r, double  genislikDeger1, double genislikDeger2, double genislikDeger3, double genislikDeger4, double yukselikDeger1, double yukselikDeger2, double yukselikDeger3, double yukselikDeger4, double ust, double kUst, double l)
        {
            this.genislikDeger1 = genislikDeger1;
            this.genislikDeger2 = genislikDeger2;
            this.genislikDeger3 = genislikDeger3;
            this.genislikDeger4 = genislikDeger4;
            this.yukselikDeger1 = yukselikDeger1;
            this.yukselikDeger2 = yukselikDeger2;
            this.yukselikDeger3 = yukselikDeger3;
            this.yukselikDeger4 = yukselikDeger4;
            this.ust = ust;
            this.kUst = kUst;
            this.L = l;
            this.Yb = Yb;
            this.Yz = Yz;
            this.Yd = Yd;
            this.Cz = Cz;
            this.Fz = Fz;
            this.qT = qT;
            this.Kt = Kt;
            this.Qs = Qs;
            this.Sds = Sds;
            this.r = r;

        }

        public double genislikDeger1 { get; set; }
        public double genislikDeger2 { get; set; }
        public double genislikDeger3 { get; set; }
        public double genislikDeger4 { get; set; }
        public double yukselikDeger1 { get; set; }
        public double yukselikDeger2 { get; set; }
        public double yukselikDeger3 { get; set; }
        public double yukselikDeger4 { get; set; }
        public double ust { get; set; }
        public double kUst { get; set; }
        public double L { get; set; }
        public double Yb { get; set; }
        public double Yz { get; set; }
        public double Yd { get; set; }
        public double Cz { get; set; }
        public double Fz { get; set; }
        public double qT { get; set; }
        public double Kt { get; set; }
        public double Qs { get; set; }
        public double Sds { get; set; }
        public double r { get; set; }
    }

If I set the variable like this;
Form1.cs
private void Form1_Load(object sender, EventArgs e)
{
Class1 obj = new Class1();
obj.yukselikDeger1 = 25;
}

And if I call this variable that I changed before;
Form2.cs
private void Form2_Load(object sender, EventArgs e)
{
Class1 obj = new Class1();
MessageBox.Show(obj.yukselikDeger1 + "");
}

resut is like this;

A: You are creating two separated instances. The values are not kept between instances - they occupy two separate and distinct memory blocks.
If you want to share the same instance between Form1 and Form2, you'll have to inject it into the constructor of Form2, like so.
public partial class Form2 : Form
{
    private Class1 _class1Obj;
    public Form2(Class1 class1Obj)
    {
        InitializeComponent();
        _class1Obj = class1Obj;
    }
}

Remember that you have to initialize Class1 on your Form1, either as a class object, or just before calling Form2.
Also, if your Class1 is supposed to hold values shared between every class on your application, consider implementing the singleton pattern.

A: For now, I'd recommend you use a Singleton Provider to share one instance of Class1 to serve as your Application Model:
public static class AppModelProvider{
     // static readonly property => will always return the same instance of Class1
     public static Class1 Model {get;} = new Class1();
}

Then you can get the model in each of your Forms:
private void Form1_Load(object sender, EventArgs e)
{
    Class1 obj = AppModelProvider.Model;
    obj.yukselikDeger1 = 25;
}

private void Form2_Load(object sender, EventArgs e)
{
    Class1 obj = AppModelProvider.Model;
    MessageBox.Show(obj.yukselikDeger1 + "");
}

This is somewhat similar to the "Resource Locator" (Anti-)Pattern which nowadays mostly would be thrown out in favor of dependency injection. But to just solve your issue, this should be fair enough for now and easy enough to refactor later on.


text:
Q: Error when Adding ASP.net Update panels dynamically A trying to add UpdatePanels dynamically to a page, but whenever I run the code I get an exception of type System.InvalidOperationException' in System.Web.Extensions.dll, I Started getting this error after adding the controls to an UpdatePanel, The code works fine when I add the controls in a panel but I need the update panel for later .
private void loadCandidates()
{
    try
    {
        sql = "exec dbo.spLoadCandidates @NationalID, @PostID";
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            SqlDataReader reader;
            cmd.Parameters.AddWithValue("@NationalID", TextBox2.Text.Trim());
            cmd.Parameters.AddWithValue("@PostID", DropDownList1.SelectedValue);
            conn.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                Label myLabel = new Label();
                ImageButton myImage = new ImageButton();

                myImage.OnClientClick = "ImageClick1(this);";
                UpdatePanel myPanel = new UpdatePanel();

                RadioButton myRadioButton = new RadioButton();
                candidates.Add(myRadioButton);

                myImage.ImageUrl = "Handler4.ashx?ID=" + reader["IDNo"].ToString();

                myRadioButton.GroupName = "Candidates";
                myRadioButton.ID = reader["CID"].ToString();
                myRadioButton.ClientIDMode = ClientIDMode.Static;
                myPanel.Controls.Add(myPanel); //add the panel to the placeholder
                myPanel.Controls.Add(myImage);
                myPanel.Controls.Add(myLabel);
                myPanel.Controls.Add(myRadioButton); //add the radiobutton to the panel

                AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
                trigger.EventName = "Click";
                trigger.ControlID = myImage.UniqueID;
                UpdatePanel1.Triggers.Add(trigger);
            }
            conn.Close();
        }
    }
    catch (Exception ex)
    {
        Label1.Text = ex.Message;
        Label1.Visible = true;
        Label2.Visible = false;
    }
    finally
    {
        conn.Close();
    }
}


text:
Q: Beacon - eddystoneTlm Not Detecting by my code frequently Beacon - eddystoneTlm Not Detecting by my code frequently.
its Detecting by Beacon mobile app @ 1 sec interval but by my code its detecting in about 15 min.
Here is my code -
const noble = require('noble');

// Create a Linking object
const BeaconScanner = require('node-beacon-scanner');
const scanner = new BeaconScanner({'noble': noble});
scanner.onadvertisement = (ad) => {
  console.log(JSON.stringify(ad, null, '  '));
};

// Start scanning
scanner.startScan().then(() => {
  console.log('Started to scan.')  ;
}).catch((error) => {
  console.error(error);
});


text:
Q: Javascript Faceted Search Client (Framework) I wonder if there's any javascript framework (client-side stuff) to manage search results UI in a facet-based way (with facet generation, counting for items matching that facet..).
In other words, something like Ajax Solr (the old SolrJS), but not based on Solr :)
Thank you in advance!

A: Simile Exhibhit seems to fit your description. Have you tried that before?

A: You can also have a look at this implementation of faceted search in javascript.


text:
Q: How to get Telerik radgrid row index value on OnBatchEditCellValueChanged command when grouping is applied? CellValueChanged_grdRoundRobinGroupMatch: function (sender, args) {
 var data = sender.get_batchEditingManager()._getCellDataToOpenEdit(sender.get_batchEditingManager().get_currentlyEditedCell());
    var row = data.row;
    var rowIndex = row.rowIndex - 1;
}

This above code is working fine when there is no grouping applied. But when some grouping is applied
the rowindex value got changed. any help?

A: I found my own solution. I didn't get the row on batch edit mode so I take the row on selected items basis. I also set AllowMultiRowSelection="false" and I did that this way-
CellValueChanged_grdRoundRobinGroupMatch: function (sender, args) {
 var masterTableView = sender.get_masterTableView();
    var selected = masterTableView.get_selectedItems();
    var rowIndex = selected[0]._itemIndex;
}


text:
Q: removing duplicate rows in pandas DataFrame based on a condition I want to delete duplicate rows with respect to column 'a' in a dataFrame with the argument 'take_last = True' unless some condition. For instance, If I had the following dataFrame
 a | b | c
 1 | S | Blue
 2 | M | Black
 2 | L | Blue
 1 | L | Green

I want to drop duplicate rows with respect to column 'a' with the general rule as take_last = true unless some condition say, c = 'Blue', in which case I want to make the argument take_last = false.
so that I get this as my resulting df
 a | b | c
 1 | L | Green
 2 | M | Black

A: #   a  b      c
#0  1  S   Blue
#1  2  M  Black
#2  2  L   Blue
#3  1  L  Green

#get first rows of groups, sort them and reset index; delete redundant col index
df1 = df.groupby('a').head(1).sort('a').reset_index()
del df1['index']

#get last rows of groups, sort them and reset index; delete redundant col index
df2 = df.groupby('a').tail(1).sort('a').reset_index()
del df2['index']
print df1
#   a  b      c
#0  1  S   Blue
#1  2  M  Black
print df2
#   a  b      c
#0  1  L  Green
#1  2  L   Blue

#if value in col c in df1 is 'Blue' replace this row with row from df2 (indexes are same)
df1.loc[df1['c'].isin(['Blue'])] = df2
print df1
#   a  b      c
#0  1  L  Green
#1  2  M  Black


text:
Q: Getting counts for a paged SQL search stored procedure I've written a paged search stored procedure using SQL Server 2005. It takes a number of parameters and the search criteria is moderately complex.
Due to the front-end architecture I need to be able to return the number of results that would come back without actually returning the results. The front end would then call the stored procedure a second time to get the actual results.
On the one hand I can write two stored procedures - one to handle the count and one to handle the actual data, but then I need to maintain the search logic in at least two different places. Alternatively, I can write the stored procedure so that it takes a bit parameter and based on that I either return data or just a count. Maybe fill a temporary table with the data and if it's count only just do a count from that, otherwise do a select from it. The problem here is that the count process could be optimized so that's a lot of extra overhead it seems (have to get unneeded columns, etc.). Also, using this kind of logic in a stored procedure could result in bad query plans as it goes back and forth between the two uses.
The amount of data in the system isn't too high (only a couple million rows for even the larger tables). There may be many concurrent users though.
What are people's thoughts on these approaches? Has anyone solved this problem before in a way that I haven't thought of?
They CANNOT take the results and count at the same time from a single call.
Thanks!

A: I personally go with the two query approach, yes, you have to maintain the search logic in two places, but I've found that the performance optimization benefit, and overall cleanness of the code pays off in the end.
Using a flag passed to a single procedure, is a potential solution, but I just find that very hard to maintain, especially for complex search logic.
The route of using temporary tables etc, that just adds WAY more overhead than what is needed.
Thus, why I have landed with the two query method.  Everything that I find online recommends this approach as well.

A: This isn't a normal problem and you usually want the total counts at the same time your getting a page.
That said, use two different procedures.  The reason is that you have two very different actions which only resemble each other superficially.

A: I'm sure you've considered this: If the data is changing the COUNT and any subsequent actual Paging may be different (if rows added / removed)
You could have a User Defined Function that returned the PKs of the matching rows, relatively easy to do a

SELECT COUNT(*) FROM dbo.MyQueryFunction(@Param1, @Param2)

to get the count, and then

SELECT Col1, Col2, ...
FROM dbo.MyQueryFunction(@Param1, @Param2) AS FN
     JOIN dbo.MyTable AS T
         ON T.ID = FN.ID
     ... more JOINs ...

to get the data.
Don't know how well this sits with Row_Number for the subsequent paging, but it would keep the actual "query logic" contained within MyQueryFunction - you're still going to have all the JOINs for any column to be retrieved duplciate in the Sproc and the Function.

A: Might not help with your specific problem, but SQL 2005 introduces the Row_Number function which is handy for paging check
Row_number example
Much easier than temp tables.

A: I found this thread researching something else, and thought I'd mention that it is possible to return the result set and the record count with one query. You just need an 'out' parameter to carry the value. Below is a copy/paste of an Oracle example, but the technique is very similar for SQL Server (I don't have access to SQL Server atm).
The big thing with SQL Server is you might need to use row_number() vs rownum.
procedure get_sample_results (
    startrow in number default 1,
    numberofrows in number default 10,
    whereclause in varchar2,
    matchingrows out number,
    rc  out sys_refcursor
)
is
    stmnt varchar2(5000);
    endrow number;
begin

    stmnt := stmnt || 'select * from table t where 1=1';
    if whereclause is not null then
        stmnt := stmnt || ' and ' || whereclause;
    end if;

    execute immediate 'select count(*) from (' || stmnt || ')' into matchingrows;

    stmnt := 'select * from (' || stmnt || ') where rownum between :1 and :2';

    -- must subtract one to compenstate for the inclusive between clause
    endrow := startrow + numberofrows - 1;
    open rc for stmnt using startrow, endrow;

end get_sample_results;

A: I know this an old question (that has been marked already), but you can return a recordset (aka the results) AND have an OUTPUT (or multiple output) values which means that you only need one round trip to the database.
This is something i'm thinking out aloud (and it's waaay past my bed time...)
CREATE PROCEDURE WhatEver
(
   @SomeParam1 NVARCHAR(200),
   ....
   @SomeParam_X INT,
   @NumberOfResults INTEGER OUTPUT
)
BEGIN
    SET NOCOUNT ON

    -- Do your search stuff.
    -- ....
    SELECT Whatever
    FROM WhatWhat
    ...

    -- Ok, the results/recordset has been sent prepared.
    -- Now the rowcount
    SET @NumberOfResults = @@ROWCOUNT
END

HTH.


text:
Q: Different CSS for homepage Ok, based on the answer here by traitadmin (scroll down) I am trying to display different CSS for my front page and one for all other pages.
Previously, my body tag looked like this:
<body <?php  body_class() ?>>

Now, I have edited it to look like this:
<body <?php if (is_home()) { ?> id="home"<?php } else { ?> body_class()<?php } ?> >

Also I have put new stylesheets in my enqueue, and all styles for the homepage now have #home in front of them.
However, there is no style at all now and my site broke down entirely, for all pages.
I think I may need body_class() also for the homepage. But how I can edit this code so that it works?

A: Easiest would actually be this:
<link rel="stylesheet" href="main.css">
<?php if (is_home()) {
    echo '<link rel="stylesheet" href="home.css">'
} ?>

Rules in home.css should have a high priority than main.css. So with this if main.css has this:
body { background-color: white; }

and home.css has this:
body { background-color: blue; }

Since home.css is linked after main.css the rule in home.css will take priority and the background will be blue. This way you can only overwrite the styles you need to and all the other styles will still apply.
In your case after your other wp_register_style() just add an if test and then register another style.
if (is_home()) {
    wp_register_style('home-style',get_stylesheet_directory_uri().'/stylesheets/home.css');
}

A: Looks like a wordpress code so here goes:
In the head:
<?php if (is_home()) {
    // loading the stylesheet if it is the homepage
    echo '<link rel="stylesheet" href="home.css">'
} else {
    // loading the other stylesheet if it is not the homepage
    echo '<link rel="stylesheet" href="other.css">'
} ?>

A: By default, WordPress adds two classes to the body tag: on the front page (is_front_page()) the home class is added, and on the home page (is_home()) the blog class is added. So, in your main CSS file, you can use the body class as follows:
#mydiv {background:green;}
.home #mydiv {background:blue;}
.blog #mydiv {background:red;}


text:
Q: Sprite Kit: Can't stop two objects from colliding I've got a player category, enemy category, and a wall category. I want my enemy category to be able to move through my wall category and I want my player category to stop when hitting a wall. I've got my player stopping at the wall but I'm not able to stop my enemy from colliding with my wall as well. I'm not sure why... Here is my code:
 static const int playerCategory =3;
 static const int wallCategory = 2;
 static const int enemyCategory = 1;

Enemy Code:
 self.physicsBody.dynamic = YES;
 self.physicsBody.restitution = 0.2;
 self.physicsBody.allowsRotation = NO;
 self.physicsBody.categoryBitMask = enemyCategory;
 self.physicsBody.collisionBitMask =  playerCategory;
 self.physicsBody.contactTestBitMask =  playerCategory;

Wall Code:
 wallRight.physicsBody.dynamic = NO;
 wallRight.physicsBody.allowsRotation = NO;
 wallRight.physicsBody.categoryBitMask = wallCategory;
 wallRight.physicsBody.collisionBitMask =  playerCategory;
 wallRight.physicsBody.contactTestBitMask =  playerCategory;

Player Code:
self.physicsBody.dynamic = YES;
self.physicsBody.restitution = 0.2;
self.physicsBody.allowsRotation = NO;
self.physicsBody.categoryBitMask = playerCategory;
self.physicsBody.collisionBitMask = wallCategory | enemyCategory;
self.physicsBody.contactTestBitMask = wallCategory | enemyCategory;

What am I missing?


text:
Q: Refresh/auto refresh Facebook comments box I want to refresh the Facebook comments box per click and/or every 30sec.
I tried a bit with the FB.XFBML.parse function, but it doesn't work.
Has somebody a hint how to do this?
Thanks


text:
Q: VB.NET, INFER ON and Enum.GetValues My project manager charged me to remove all "Option Infer On" directives from our solution (in order do not have undefined types, in his opinion).
Dim enums = [Enum].GetValues(enumType) ' here I will use "As Array"

For Each item In enums ' <================== WHAT TYPE TO USE HERE?
  Dim ienum As [Enum] = CType(item, [Enum])

  Dim name As String
  Dim caption As String

  name = ienum.GetPropertyName
  caption = ienum.GetStringValue

  myDict.Add(caption, name)
Next item

A: The return type of GetValues is an Array of Objects. So the type of your "item" variable in the For Each loop will be Object.
Hope that helps.

A: According to MSDN it's an array of constants, so it will be an array of objects that you can cast to Integer.
FWIW I have got some code which does similar work, it picks up Attributes stored against each Enum value. For that I've used GetNames, then reflected back to the backing Enum field, to which I can search for Custom Attributes that store various bits of metadata such as "DisplayName" etc. Then the Enum can be reconstituted using [Enum].Parse().
Hope that helps! Also, I think it's a dumb idea to have to change all your code because your manager doesn't trust the language/devs!


text:
Q: on touch event in android i have a screen which is showing some information about version.there is no controll in the screen.i want to finish this activity when i tap on the screen.can anyone help me plz...

A: Make your activity implement OnTouchListener:
public class MyActivity extends Activity implements OnTouchListener{

// All your code goes here

@Override
    public boolean onTouch(View arg0, MotionEvent arg1) {
        this.finish();
        return false;
    }
}

A: You could override your activity's onTouchEvent method to finish it:
@Override
public boolean onTouchEvent(MotionEvent event)
{
    this.finish();
    return true;
}

A: Override onTouchEvent in your activity.
 @Override
public boolean onTouchEvent (MotionEvent e) {
    this.finish();
    return false;

}


text:
Q: Redirect many old asp pages in htaccess I have converted a site from .asp to .php pages
now I need to redirect many old .asp pages to the home page
the structure of the .asp URLs is:
/dettagli.asp?ID=123456789

I would like any /dettagli.asp page to be redirected to the home page, regardless of the parameter which is passed (these ages no longer exist...)
I have tried some regex so far but no luck....

A: You can use this rule as your very first rule:
RewriteEngine On

RewriteRule ^dettagli\.asp$ /? [L,R=302]

A: Solved.
I simply was using rules AFTER Joomla Rules that were applied BEFORE mine...


text:
Q: How is the word "qua" used? I play Scrabble. I'm learning words with the letter 'q'. What is the usage of the word 'qua'?

A: Beware that qua are truly 3 heteronyms (ie: same spelling, but different meaning and pronunciation). So user 'Alex' 's answer above does NOT refer to the same qua; it only introduces 2 of the 3 heteronyms. (Here is a helpful Venn diagram that depicts the relationships between pronunciation, spelling, and meaning of words)
I exerpt, but don't quote fully, Wiktionary on quā. For ease of readability, I eschew the use of >.
In brief, and if I haven't erred, the meaning of 'as' (discussed above) matches Etymology 1.
The use in 'sine quâ non' matches Etymology 2.

Etymology 1 (of 3)  Adverb declined from quī. [...] (not comparable) [...]

*

*On which side, at or in which place, in what direction, where, by
what way (qua...ea...)

*as; in the capacity or character of

*In so far as (eg ens qua ens ("being as being"))

*In what way, how, by what method; to what degree or extent
Etymology 2 (of 3)
{pronoun} [=] ablative feminine singular of quī ["who, which"]
Etymology 2 (of 3) {pronoun} [=]
    ablative feminine singular of quis

A: I first encountered qua (repeatedly) many years ago in a translation of Thomas Aquinas's Summa Theologica, who used the (Latin) word to convey a specific meaning involving the calling out of a particular inherent quality or identity of a given thing. The term seems to retain a special sense in analytical philosophical works today. Here's a discussion of qua in Richard Cross, The Metaphysics of the Incarnation: Thomas Aquinas to Duns Scotus (2002):

My term 'quar', is thus correctly understood as 'in virtue of'. This definition of reduplication is found most clearly in Scotus:

(8.10) 'Qua' ...properly denotes that that which follows it is the formal reason for the inherence of the predicate: such as 'a human being, qua white, or qua coloured, is seen'.

...
...Think of white-Socrates. It is true of white-Socrates that he is coloured quar white, and it is false of him that he is coloured quar man; but this obviously does not entail that Socrates quar man is not coloured—if it did, Socrates would be (absurdly) both coloured and not coloured.
...
The speculative analysis is more interesting. Consider the following from Aquinas:

(8.11) Just as in human and corporeal matters those things which it can be called into doubt whether they belong to a whole or a part, we do not ascribe to the whole simply or without determination if they inhere in a part: for we do not say that an Ethiopian is white, but that he is white according to his teeth.

Aquinas's point here is that the predicate 'white' is not true of the whole Ethiopian but only of his teeth. Using 'quasa' to pick out this sense of 'qua', Aquinas thus accepts the following definition of 'quasa:

(B) x quasa y is F = y is a part of x, and y is F.

'Quasa' is thus as Aquinas presents it a sign of synecdoche. It qualifies the subject by modifying the reference of the subject term.

The terms quar and quasa that Cross uses (above) in his analysis of the formal logic of Aquinas and Duns Scotus are thus special subcategories of the more general reduplicative sense of qua (as "in virtue of") that he ascribes to Scotus near the outset of the extract.
Evidently one way in which qua continues to be used today is by modern scholars in connection with analyses and discussions of the logic of medieval philosophers.

A: Qua can usually be read as the word "as".
It is an occasionally useful (and rarely used) link-word in English.
I was just reading about qua in Fowler's (incl. the 3rd ed by Burchfield) a couple of days ago. Says Fowler: "The real occasion for the use of qua occurs when a person or thing spoken of can be regarded from more than one point of view or as the holder of various coexistent functions, and a statement about him (or it) is to be limited to him in one of these aspects":

"Qua lover he must be condemned for doing what qua citizen he would be condemned for not doing."

Here, "the lover aspect is distinguished from another aspect in which he may be regarded. The two nouns (or pronouns) must be present, one denoting the person or thing in all aspects (he), and the other singling out one of his or its aspects (lover, or citizen)."
This was the only way in which Fowler preferred the word be used, but in fact (notes Burchfield), it's often used in other ways:

*

*between identical nouns ("X qua X") as an emphatic version of "as":

"The presence of actual words is apt to confuse any estimate of the evocative power of the music qua music."
"I don't think that 'Hard Times' is a particularly good novel qua novel, whatever it may be as a social document."
"James Kirkup's poem about Jesus … is … an indefensibly bad poem qua poem."

*

*And sometimes, merely as "as":

"It cannot, qua film, have the scope of a large book." [i.e., it cannot, as a film,…]
"Qua phonetician, de Saussure has no interest in making precise the notion of species."
"Dressed in an Armani suit and espadrilles, he plays a cop qua existential hero."

But the word can seem pretentious, so you may want to avoid it — it usually adds nothing over "as", anyway.
(Burchfield ends with: "And as to usage, as is often the better choice of word, qua word.")

A: It's from Latin, meaning "what" or "as." The entry at Dictionary.com gives this example:
"The work of art qua art can be judged by aesthetic criteria only."
The point (aside from sounding a little pretentious) would be to contrast "art qua art" with, say, "art as a commercial enterprise" - where the criteria would be whether a particular piece is salable.
It's also used as part of the phrase (also from Latin) "sine qua non," meaning something essential to something else ("money is sine qua non for an American political campaign").


text:
Q: Jquery function does not display animation I have created two functions which will allow me to use them with different CSS classes.
    var CSSElement;
$(document).ready(function(){

  expandBox (".orange");
  minimizeBox(".orange");

});

function expandBox ($CSSElement){
     //When mouse rolls over
    $($CSSElement).mouseover(function(){
        $(this).stop().animate({height:'485px'},{queue:false, duration:600, easing: 'easeOutBounce'})
    });
}

function minimizeBox ($CSSElement){
     //When mouse is removed
    $(CSSElement).mouseout(function(){
        $(this).stop().animate({height:'50px'},{queue:false, duration:600, easing: 'easeOutBounce'})
    });
}

However, only the function expandBox seems to work. If I hover my mouse away the from the .orange element the box does not contract.
I want these animations to appear as functions as I plan to use them few times within my website. If I put my code like below:
$(document).ready(function(){

   //When mouse rolls over
    $($CSSElement).mouseover(function(){
        $(this).stop().animate({height:'485px'},{queue:false, duration:600, easing: 'easeOutBounce'})
    });

  //When mouse is removed
    $(CSSElement).mouseout(function(){
        $(this).stop().animate({height:'50px'},{queue:false, duration:600, easing: 'easeOutBounce'})
    });

});

Everything seems to work ok. Is there a reason why the first code does not work but the second one does?
Thanks,
vnayak

A: I guess you made a typo :
$($CSSElement)

$(CSSElement)

thats why it doesn't work

A: In JavaScript, $ is a perfectly legal character in identifiers (rather than, say, completely forbidden [like in C] or a special sigil [PHP, Perl]). As a result, $CSSElement is a different identifier to CSSElement - if only one is defined, the other won't work. $($CSSElement) and $(CSSElement) are different.
(It is potentially confusing to prefix variable names with $; in JavaScript they work just fine without.)
What is happening here:

*

*Both functions take a parameter named with $.

*expandBox uses that parameter with the $.

*minimizeBox uses it without the $ (thus using some unrelated variable).

My advice: Change everything to not use prefixed $, like this:
function expandBox (CSSElement){
     //When mouse rolls over
    $(CSSElement).mouseover(function(){
        $(this).stop().animate({height:'485px'},{queue:false, duration:600, easing: 'easeOutBounce'})
    });
}

function minimizeBox (CSSElement){
     //When mouse is removed
    $(CSSElement).mouseout(function(){
        $(this).stop().animate({height:'50px'},{queue:false, duration:600, easing: 'easeOutBounce'})
    });
}


text:
Q: Unable to follow image as array in python So Im using this very simple image to understand how image is being stored in an array and how to manipulate it.

SIDE NOTE
Can anyone suggest me a book/blog which starts with these basics, as most of them skipping this part and even though trivial but I cant
  progress with these small nuances eating my head

Its 8x8 pixel image ,with a single dot in fist top left pixel.
#import modules
import matplotlib.pyplot as plt
from PIL import Image
%matplotlib inline
import numpy as np

#Load image as array
i=Image.open("dot.png")
iar=np.asarray(i)

Now for the analysis, first Im starting with displaying some arrays then Ill finally display the "dot.png"
LINK TO dot.png image (use ctrl+s to save it as its very small 2x2 pixel hence not visible ) https://i.stack.imgur.com/y2ot9.png

plt.imshow([0])
TypeError: Invalid dimensions for image data

But
plt.imshow([[0]])

plt.imshow([[255]])

 plt.imshow([[255,0]])

plt.imshow([[255,0,128]])

plt.imshow([[255,0],[23,128]])

plt.imshow(iar[0])

plt.imshow(iar[0:1])

# Checking attributes of iar[0]
subset1=iar[0]
subset1.shape
Out[144]: (8L, 4L)
In [140]:iar[0]
Out[140]:
array([[  0,   0,   0, 255],
   [255, 255, 255, 255],
   [255, 255, 255, 255],
   [255, 255, 255, 255],
   [255, 255, 255, 255],
   [255, 255, 255, 255],
   [255, 255, 255, 255],
   [255, 255, 255, 255]], dtype=uint8)

# Checking attributes of iar[0:1]
subset2=iar[0:1]
subset2.shape
Out[146]: (1L, 8L, 4L)
In [142]:iar[0:1]
Out[141]:
array([[[  0,   0,   0, 255],
    [255, 255, 255, 255],
    [255, 255, 255, 255],
    [255, 255, 255, 255],
    [255, 255, 255, 255],
    [255, 255, 255, 255],
    [255, 255, 255, 255],
    [255, 255, 255, 255]]], dtype=uint8)

My questions :-

*

*Why is plt.imshow([0]) failing but plt.imshow([[0]]) works ?

*Why is it that both plt.imshow([[0]]) & plt.imshow([[255]]) showing blue color only ? Even though 0 doesnt mean blue, nor does
255 mean blue.

*Where is the pixel in these images. plt.imshow([[0]]) is showing an image of size 1x1. Is it one pixel image ? If so then
plt.imshow([[255,0]]) means 2 pixels ?

*Why are the colors blurred and not well defined, I didnt give any information on alpha/blurring. But still
plt.imshow([[255,0,128]]) is showing all colors as blurred on
boundaries. Whats happening here ?

*Why is it that iar[0] is coming as color image even though dot.png is simply black & white image. But iar[0:1] shows the first row of dot.png exactly as its stored there.

A: OK, so some of your questions are about the behaviour of pyplot.imshow.
imshow displays an image, and takes as an argument something that is "array-like", with a shape of (n, m) (for greyscale images), (n, m, 3) (for colour images), or (n, m, 4) (for colour images with transparency, or alpha, information).
When you do plt.imshow([0]), you're passing an argument with a shape of (1,), which is why you get the error.  The list [0] is one-dimensional, not two, and so cannot be displayed by imshow.  By contrast, [[0]] is a two-dimensional array, representing a single pixel, and so can be displayed.
Both [[0]] and [[255]] will be displayed as blue squares.  This is because matplotlib colour-maps the pixel values for greyscale images.  Colour mapping means that matplotlib finds the range of values in the data you pass it, and makes the lowest value one colour, the highest value another colour, and all the values in between map to some range of colours designed either to look pretty, or to be useful in interpreting your data.  If your image only has one pixel, there's no colour range, so the whole image will be displayed in the same colour.  Note that matplotlib defaults to using the jet colourmap, if you don't specify a different value to the argument cmap.
plt.imshow([[255,0]]) is displaying a two-pixel image; the array you've passed has one row with two columns.  Matplotlib shows this as two colours: we can see that red represents high (255), and blue low (0).
The image is blurred because matplotlib interpolates the image data.  You can change this behaviour by giving a value for the interpolation argument to imshow (matplotlib defaults to using 'bilinear', which gets you the "anti-aliased" look).
plt.imshow([[255,0]], interpolation='none')

Next, you're displaying a 3-pixel greyscale image ([[255,0,128]]).  This shows up as a gradient from red to blue to green; those colours are again taken from the jet colour map (red is high, green is middle, and blue is low).  [[255,128,128]] will be red, blue, blue, because the range of this data is from 128 to 255, so 128 will be the new low (blue).
OK, and finally, we come to your 8x8 image.  Your PNG image might contain only black and white pixels, but it is stored in RGB format.  We can see this, for example, using ImageMagick:
$ identify ~/Downloads/y2ot9.png
/home/user/Downloads/y2ot9.png PNG 8x8 8x8+0+0 8-bit sRGB 138B 0.010u 0:00.059

So this means that each pixel is represented by three bytes (for red, green, and blue).  PIL opens this in RGBA mode, adding another byte for the alpha channel:
>>> from PIL import Image
>>> import os
>>> i = Image.open(os.path.expanduser('~/Downloads/y2ot9.png'))
>>> i.size
(8, 8)
>>> i.mode
'RGBA'

The first pixel is black, and the others are white.  We can see that black is the tuple (0, 0, 0, 255) (that is, 0 red, 0 green, 0 blue, and 255, or full, alpha).  Similarly, white is (255, 255, 255, 255):
>>> i.getpixel((0,0))
(0, 0, 0, 255)
>>> i.getpixel((1,0))
(255, 255, 255, 255)

When you put this image into a numpy array, you'll get these same pixel values.  The array is of shape (8, 8, 4):
>>> import numpy as np
>>> a = np.asarray(i)
>>> a.shape
(8, 8, 4)

This means 8 rows, 8 columns, and 4 components for each pixel (red, green, blue, alpha).
Taking a[0] gives you the first row of this array, which is of shape (8, 4).  There's 8 columns of pixels, which have 4 components each.  When you send this to imshow, it gets interpreted as a greyscale image of size 8x4, because you've got two dimensional data.  You'll get a colour-mapped display of the first row of your image.  You can see the first pixel as three blue values (the three 0s of the black pixel).  The last column of the image is red everywhere, because your image has full alpha everywhere.
a[0:1] gives you a slice of the array; this will be of shape (1, 8, 4).  When you send this to imshow, it gets interpreted as a colour image of size 1x8 (because it's three-dimensional data, and the last dimension is 4, signifying colour with alpha information).  That's why showing this gives you a black-and-white bar, which is the picture you're likely expecting to see.  You can get the same result by displaying [a[0]].
Because you're dealing with black-and-white image data, it might be more intuitive to represent your data in greyscale.  You can do this by changing the PNG file to be greyscale, or you can convert the image in Python using PIL:
>>> i2 = i.convert('L')
>>> a2 = np.asarray(i2)
>>> a2.shape
(8, 8)

If you work with greyscale data, imshow will always colour-map everything, so you won't have this unpredictable switching between colour-mapped greyscale information and full-colour information (which depends on the shape of the array data you're sending to imshow).
Summary:

*

*imshow displays values from arrays.  The shape of the array is important, because imshow will automatically switch between displaying colour-mapped greyscale data, or displaying full-colour data.

*By default, imshow interpolates values, leading to a blurry image.

*Be aware of the way that image data is stored, both in your image files, and in the Python data structures.  imshow is usually used to show two-dimensional data with a single component (greyscale); the colour-mapping helps make the plots more appealing, and show variation that would be harder to see if everything was just grey.  Image data, on the other hand, quite often includes colour information.

I'm not sure where you can get a beginner's overview of image processing (maybe try reading through How do I get started with image processing?).  I've heard Lecture 1 Introduction to Digital Image Processing recommended before, and you can also continue exploring, as you've been doing, for instance, by reading up on image data formats like the simple Netpbm format.


text:
Q: Ansible - Returning variable from role/tasks back to the playbook I have a playbook with below format:
- name: Get VM IP
 hosts: local
 connection: local
 gather_facts: true
 roles:
   - operations/get_IP

In my Role/tasks/main.yml
- name: GET IP.
  script: " Script to get the IP"
  register: IP_status

I want to return the variable 'IP_status' back to my playbook. What is the right way to do it?
I want to return this variable as I want to create a JSON object by parsing the value especially in case of errors.

A: That variable is already "available" to your playbook as a hostvar. You can access it directly as long as the role has already run:
- name: Get VM IP
  hosts: local
  connection: local
  gather_facts: true

  roles:
    - operations/get_IP

  post_tasks:
    - debug:
        var: IP_status.stdout


text:
Q: Spacelike, timelike, lightlike vectors and the light-cone structure Consider a semi-Riemannian manifold which of these statements is false:

*

*All vectors on the light-cone are light-like, all vectors in the interior of the light-cone are time-like and all vectors in the exterior of the light-cone are space-like.

*All space-like vectors lie in the exterior of the light-cone, all time-like vectors lie in the interior of light-cone, and all light-like vectors lie on the light-cone.
I can't see which statements are false, any help would be appreciated.


text:
Q: autobooktabular headers with mathematical formulae Let's say I have a table like

which I save as a .csv
and then import with latex like so:
\usepackage{adjustbox}
\usepackage{booktabs,csvsimple}

[...]

\begin{table}[ht]
\begin{adjustbox}{max width=0.9\textwidth}
\csvautobooktabular[]{csvs/test.csv}
\end{adjustbox}
\caption{blah blah blah etc.}
\label{tab:IRTL}
\end{table}

This won't compile (see error message below).
But if I move the formulae from the header cells to some other cells, e.g.
experiment,N,Z[ms],X[requests/ms],R [ms],N/X-Z,difference[ms],rel.difference
S=3 write-to-1,690,0,15.0258730823,47.8550460251,45.9207925038,-1.9342535213,-4.0419008693
S=3 write-to-2,690,0,14.8651324965,48.817562994,46.4173461059,-2.4002168881,-4.9167077193
S=3 write-to-3,690,0,14.6532775453,49.1099377034,47.088441331,-2.0214963724,-4.1162674337
S=5 write-to-1,690,0,13.0724002789,55.1449088796,52.7829614514,-2.3619474282,-4.2831649852
S=5 write-to-3,690,0,13.1264672245,54.9158028824,52.5655523452,-2.3502505371,-4.2797344549
S=5 write-to-5,690,0,12.5929567643,57.5819507206,54.7925330734,-2.7894176472,-4.8442569455
S=7 write-to-1,690,0,11.9808507671,59.7164732682,57.5919033977,-2.1245698706,-3.5577617938
$\frac{N}{X}-Z$,690,0,11.5527991632,62.7957745235,59.7257850893,-3.0699894342,-4.8888471517
[\%],690,0,11.2594853556,64.3044356113,61.2816641441,-3.0227714673,-4.7007200025

things work fine:

So I guess this has something to do with the way autobooktabular is treating the headers.
How do I get the table to parse the headers correctly?
Error msg:
<to be read again>
\begingroup
l.198 \csvautobooktabular[]{csvs/test.csv}
The control sequence marked <to be read again> should
not appear between \csname and \endcsname.
! Missing } inserted.
<inserted text>
}
l.198 \csvautobooktabular[]{csvs/test.csv}
I've inserted something that you may have forgotten.
(See the <inserted text> above.)
With luck, this will get me unwedged. But if you
really didn't forget anything, try typing `2' now; then
my insertion and my current dilemma will both disappear.
! Missing $ inserted.
<inserted text>
$
l.198 \csvautobooktabular[]{csvs/test.csv}
I've inserted a begin-math/end-math symbol since I think
you left one out. Proceed, with fingers crossed.
! Extra }, or forgotten $.
<argument> ...ad/${\begingroup N\endgroup \over X}
-Z$/.@cmd
l.198 \csvautobooktabular[]{csvs/test.csv}
I've deleted a group-closing symbol because it seems to be
spurious, as in `$x}$'. But perhaps the } is legitimate and
you forgot something else, as in `\hbox{$x}'. In such cases
the way to recover is to insert both the forgotten and the
deleted material, e.g., by typing `I$}'.
! Extra \endcsname.
\pgfkeyslet ...ter \let \csname pgfk@#1\endcsname
#2
l.198 \csvautobooktabular[]{csvs/test.csv}
I'm ignoring this, since I wasn't doing a \csname.
)
Runaway argument?
\pgfkeyssetvalue {/csv head/${\begingroup N\endgroup \over X}-Z$/.@bo\ETC.
! File ended while scanning use of \pgfkeys@temp.
<inserted text>
\par
<*> myFile.tex
I suspect you have forgotten a `}', causing me
to read past where you wanted me to stop.
I'll try to recover; but if the error is serious,
you'd better type `E' or `X' now and fix your file.
! Emergency stop.
<*> myFile.tex
*** (job aborted, no legal \end found)
Here is how much of TeX's memory you used:
10433 strings out of 495000
168406 string characters out of 6181170
367801 words of memory out of 5000000
13477 multiletter control sequences out of 15000+600000
10920 words of font info for 39 fonts, out of 8000000 for 9000
14 hyphenation exceptions out of 8191
54i,12n,92p,1177b,330s stack positions out of 5000i,500n,10000p,200000b,80000s
! ==> Fatal error occurred, no output PDF file produced!

A: It seems \frac is too fragile to put it in a header that is interpreted by the csv reader. You could change the header entry to N/X-Z and then specify the nice header yourself.
\csvautobooktabular[table head={\toprule  experiment &  N &  Z[ms] &  X[requests/ms] &  R [ms] & $\frac{N}{X}-Z$ & difference[ms] & rel.difference \\\midrule}]{table.csv}


text:
Q: New build configuration generates runtime error: could not load System.Runtime I have a Solution with a .Net Framework 4.5.2 console application that depends on a .NetStandard 1.1 library.  The console applcation and library both compile and run perfectly.
My problems began when I created a new build confiuration, which I called "LocalDebug" and copied from the "Debug" configuration.   With the new configuration, it builds OK, but when I run it, it crashes the moment I access an object from the class library with this exception:
System.IO.FileNotFoundException: Could not load file or assembly
'System.Runtime, Version=4.0.20.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
or one of its dependencies. The system cannot find the file specified. --->
System.IO.FileNotFoundException: Could not load file or assembly
'System.Runtime, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
The system cannot find the file specified.

I have tried closing visual studio, deleting all the intermediate folders and the .vs folder and re-compiling, but no luck.  I tried to add System.Runtime a reference in the console app, but it is not even presented as an option.   This shouldn't be failing anyway because I copied the configuration from "Debug", which works just fine.  What the heck???

A: I never did figure out what went wrong.  Eventually the debug build stopped compiling as well, so I Nuked The Site From Orbit, re-creating each project and adding in the code files, making sure it built at each step. As best as I can tell, I think my problems started with I mis-applied a nugget package to the wrong project.


text:
Q: Botkit slackbot error "Could not load team while processing webhook" I have created a simple express server and added a /slack/receive route to handle webhook requests from the Slack events API:
// routes.js (which is used by my app defined in server.js)
...
let slack = require('./controllers/slack');
router.post('/slack/receive', slack.receive);
...

I then use Botkit to create a simple Slack application:
// controllers/slack.js

'use strict';

const logger = require('../config/winston');

// initialise firebase storage for botkit
const admin = require('firebase-admin');
var serviceAccount = require('../config/firebase.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});
var db = admin.firestore();
db.settings({
  timestampsInSnapshots: true
})

// initialise botkit for slack
const botkit = require('botkit');
const controller = botkit.slackbot({
  storage: require('botkit-storage-firestore')({ database: db }),
  clientId: process.env.SLACK_CLIENT_ID,
  clientSecret: process.env.SLACK_CLIENT_SECRET,
  clientSigningSecret: process.env.SLACK_SIGNING_SECRET,
  redirectUri: process.env.SLACK_REDIRECT,
  disable_startup_messages: true,
  send_via_rtm: false,
  debug: true,
  scopes: ['bot', 'chat:write:bot'],
})

controller.hears('Hello', 'direct_mention,direct_message', (bot, message) => {
  logger.info(message);
  bot.reply(message, 'I heard a message!');
})

exports.receive = (req, res, next) => {
  res.sendStatus(200);
  logger.debug(req.body);
  controller.handleWebhookPayload(req, res);
};

The server initialises correctly, but as soon as the slack webhook receives a request the following error happens:
Could not load team while processing webhook:  Error: could not find team T5VDRMWKX
    at E:\Documents\upper-revolutions\node_modules\botkit\lib\SlackBot.js:169:24
    at firebaseRef.doc.get.then.catch.err (E:\Documents\upper-revolutions\node_modules\botkit-storage-firestore\src\index.js:86:13)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:118:7)

So far I have found that:

*

*Having/not having storage in the botkit slackbot makes no difference

*The error happens within the handleWebhookPayload method as code within controller.hears() does not get executed

A: This error occurs because botkit needs some form of storage where it can store all the teams (channels and users too) and retrive it later on.
So, When your method handleWebhookPayload gets executed it calls another method called
findAppropriateTeam that will query for the specified team record in the storage provided by you (It might be mongoDB or a JSON file or other). The error is saying that you do not have any record in the storage with the id provided.
So this might implicate two things:

*

*You did not provide a storage for botkit to work

*You did not save the team id in the storage

The solution to the first problem is quite simple. You just need to install mongodb in your machine and then pass to botkit the MONGO_URL.
NOTE: I see that you are using the botkit simple storage and this might be the problem since I also have experieced some troubles with this kind of storage not saving records.
const controller = botkit.slackbot({
  storage: 'mongodb//localhost:27017:/yourdb',

})

//OR

const controller = botkit.slackbot({
  storage: process.env.MONGO_URL,

})

The possible solution to the second problem:
I will assume you are using botkit locally, so you must be using some tunneling like ngrok or localtunnel. In that case make sure:

*

*You provided the redirect URL to Slack (Ex, https://your_url/oauth)

*You accessed the https://your_url/login page

Botkit saves your team id on the provided storage when you access the /login route and authorizes the app. So if you skipped that part then botkit won't save your team id and therfore will throw an error when you receive events later on.
Check this like [https://github.com/howdyai/botkit/issues/938] for discutions on the topic
I hope this helps!


text:
Q: What does =~ m/\#F/ mean in Perl? open DMLOG, "<dmlog.txt" or &error("Can't open log file: $!");
chomp(@entirelog=<DMLOG>);
 close DMLOG;
 for $line (@entirelog)
{

if ($line =~ m/\#F/)
    {
    $titlecolumn = $line;
    last;
     }
 }

I found that =~ is a regular expression I think, but I don't quite understand what its doing here.

A: It assigns the first line to $titlecolumn that contains an # followed by an F.
The =~ is the bind operator and applies a regex to a string. That regex would usually be written as /#F/. The m prefix can be used to emphasize that the following literal is a prefix (important when other delimiters are used).

A: It is called Binding Operator. It is used to match pattern on RHS with the variable on LHS. Similarly you have got !~ which negates the matching.
For your particular case:
$line =~ m/\#F/

This test whether the $line matches the pattern - /#F/.

A: Do you understand what regular expressions are? Or, is the =~ throwing you off?
In most programming languages, you would see something like this:
 if ( regexp(line, "/#F/") ) {
   ...
}

However, in Perl, regular expressions are inspired by Awk's syntax. Thus:
if ( $line =~ /#F/ ) {
   ...
}

The =~ means the regular expression will act upon the variable name on the left. If the pattern #F is found in $line, the if statement is true.
You might want to look at the Regular Expression Tutorial if you're not familiar with them. Regular expressions are extremely powerful and very commonly used in Perl. In fact, they tend to be very used in Perl and is one of the reasons developers in other languages will claim that Perl is a Write Only language.

A: Yes, =~ is the binding operator binding an expression to the pattern match m//.
The if statement checks, if a line matches the given regular expression. In this case, it checks, if there is a hash-sign followed by a capital F.
The backslash has just been added (maybe) to avoid treating # as a comment sign (which isn't needed).


text:
Q: Given $a_{n}\ge a_{n+1}>0$, how to prove $a_{n}=o(\frac{1}{n})$ is necessary for $\sum_{n=1}^{\infty}a_n$ to converge? I am working on an exercise from Zorich's Mathematical Analysis. The problem reads:
If $a_{n}\ge a_{n+1}>0$ for all $n\in\mathbb{N}$ and the series $\displaystyle\sum_{n=1}^{\infty}a_{n}$ converges then $a_{n}=o\left(\frac{1}{n}\right)$ as $n\to\infty$;
I understand that $a_{n}=o\left(\frac{1}{n}\right)$ means $a_{n}=\alpha(n)\cdot\frac{1}{n}$ where $\alpha(n)\to 0$ as $n\to\infty$. So let $\alpha(n)=n\cdot a_{n}$, then $a_{n}=\frac{\alpha(n)}{n}$, but I cannot seem to fully reason out from convergence of $\displaystyle\sum_{n=1}^{\infty}a_{n}$ to $\displaystyle\lim_{n\to\infty}\alpha(n)=0$. My partial result reasoning is as following:
Since $a_{n}\ge a_{n+1}>0$, follow Cauchy's proposition that $\displaystyle\sum_{n=1}^{\infty}a_{n}$ converges if and only if $\displaystyle\sum_{k=1}^{\infty}2^{k}a_{2^{k}}$ converges. Therefore,
$$\sum_{k=1}^{\infty}2^{k}a_{2^{k}}=\sum_{k=1}^{\infty}2^{k}\frac{\alpha\left(2^{k}\right)}{2^{k}}=\sum_{k=1}^{\infty}\alpha\left(2^{k}\right)$$
Since it converges, it is necessary that $\displaystyle\lim_{k\to\infty}\alpha\left(2^{k}\right)=0$. But that is only a subsequence of $\alpha(n)$.
(added per Greg Martin's suggestion - thanks) Further from $a_{n+1}\ge a_{n}$ we have
\begin{align*}
    &a_{n}\ge a_{n+1}>0 \Rightarrow\frac{\alpha(n)}{n}\ge\frac{\alpha(n+1)}{n+1}>0\\
    \Rightarrow&\frac{\alpha(n+1)}{\alpha(n)}\le\frac{n+1}{n}=1+\frac{1}{n}\\
    \Rightarrow&\frac{\alpha(n+2)}{\alpha(n)}=\frac{\alpha(n+2)}{\alpha(n+1)}\cdot\frac{\alpha(n+1)}{\alpha(n)}\le\left(1+\frac{1}{n+1}\right)\left(1+\frac{1}{n}\right)<\left(1+\frac{1}{n}\right)^{2}\\
    &\quad\vdots
\end{align*}
So if $n=2^{k}$, then $2^{k+1}=2\cdot 2^{k}=2n$, thus
\begin{align*}
 \Rightarrow&\frac{\alpha(2^{k}+1)}{\alpha(2^{k})}\le 1+\frac{1}{2^{k}}\\
 \Rightarrow&\frac{\alpha(2^{k}+2)}{\alpha(2^{k})}=\frac{\alpha(2^{k}+2)}{\alpha(2^{k}+1)}\cdot\frac{\alpha(2^{k}+1)}{\alpha(2^{k})}<\left(1+\frac{1}{2^{k}}\right)^{2}\\
 &\quad\vdots\\
 \Rightarrow&\frac{\alpha(2^{k+1}-1)}{\alpha(2^{k})}=\frac{\alpha(2^{k+1}-1)}{\alpha(2^{k+1}-2)}\cdot\frac{\alpha(2^{k+1}-2)}{\alpha(2^{k+1}-3)}\cdots\frac{\alpha(2^{k}-1)}{\alpha(2^{k})}<\left(1+\frac{1}{2^{k}}\right)^{2^{k}-1}
\end{align*}
But we know
$$\displaystyle\lim_{k\to\infty}\left(1+\frac{1}{2^{k}}\right)^{2^{k}-1}=e$$
Thus $\alpha(2^{k}+d)<e\cdot\alpha(2^{k})$ is bounded for $d<2^{k}$, so
$$\lim_{n\to\infty}\alpha(n)\le\lim_{k\to\infty}e\cdot\alpha(2^{k})=e\cdot\lim_{k\to\infty}\alpha(2^{k})=e\cdot 0=0$$
Hope I got it right..


text:
Q: PHP: MongoDB projection on embedded document array with positional operator I want to retrieve a specific array from embedded document on matching base but either the output is displaying all arrays in that document not a specific one or displaying just the first array....
this is my code please have a look and answer this according to PHP.
$dept->findOne(['$and' => [
    ['_id' => 'd004'],
    ['dept_employees.from_date' => '1986-12-01'],
    ['dept_employees.to_date' => '9999-01-01']
                         ]
    ],
    ['projection' => ['dept_employees.$' => 1] ]);

this is the output

MongoDB\Model\BSONDocument::__set_state(array(
   '_id' => 'd004',
   'dept_employees' =>
  MongoDB\Model\BSONArray::__set_state(array(
     0 =>
    MongoDB\Model\BSONDocument::__set_state(array(
       'emp_id' => '10003',
       'from_date' => '1995-12-03',
       'to_date' => '9999-01-01',
    )),
  )),
))

the document is like this have 247 sub-arrays

MongoDB\Model\BSONDocument::__set_state(array(
   '_id' => 'd004',
   'dept_employees' =>
  MongoDB\Model\BSONArray::__set_state(array(
     0 =>
    MongoDB\Model\BSONDocument::__set_state(array(
       'emp_id' => '10003',
       'from_date' => '1995-12-03',
       'to_date' => '9999-01-01',
    )),
     1 =>
    MongoDB\Model\BSONDocument::__set_state(array(
       'emp_id' => '10004',
       'from_date' => '1986-12-01',
       'to_date' => '9999-01-01',
    )),
     2 =>
    MongoDB\Model\BSONDocument::__set_state(array(
       'emp_id' => '10010',
       'from_date' => '1996-11-24',
       'to_date' => '2000-06-26',
    )),

and i want only this

MongoDB\Model\BSONDocument::__set_state(array(
   '_id' => 'd004',
   'dept_employees' =>
  MongoDB\Model\BSONArray::__set_state(array(

     1 =>
    MongoDB\Model\BSONDocument::__set_state(array(
       'emp_id' => '10004',
       'from_date' => '1986-12-01',
       'to_date' => '9999-01-01',
    )),

Dates are here only as strings, i am  just matching strings.
The shell is also displaying same results:
db.departments.find( {"dept_employees.from_date": '1986-12-01',
"dept_employees.to_date": '9999-01-01'}, {"dept_employees.$":1} ).pretty()
{
        "_id" : "d004",
        "dept_employees" : [
                {
                        "emp_id" : "10003",
                        "from_date" : "1995-12-03",
                        "to_date" : "9999-01-01"
                }
        ]
}

A: According to MongoDB documentation :

The positional $ operator limits the contents of an  from the
  query results to contain only the first element matching the query
  document.

and :

See the aggregation operator $filter to return an array with only those
  elements that match the specified condition.

https://docs.mongodb.com/manual/reference/operator/projection/positional/
https://docs.mongodb.com/manual/reference/operator/aggregation/filter/#exp._S_filter
Also, not exactly sure in your case, but if you are looking to match date ranges, maybe using '$gt' and '$lt' can help.


text:
Q: How to add OpenStreetMap as background layer to my sharpmap map I have a web application which uses sharpmap 1.1 to generate maps(Works Pretty awesome), now i want to add an Open street map as background to my current map. I tried some online examples but no luck.
So far I've tried the below.
   var ShapeDataProvider = new SharpMap.Data.Providers.ShapeFile(@"Local shp Path");
        var layer = new VectorLayer("test");
        layer.DataSource = ShapeDataProvider;
      var layerOSM = var layer = new VectorLayer("OSM");
layerOSM.DataSource = (SharpMap.Data.Providers.IProvider)(new SharpMap.Layers.TileAsyncLayer(new BruTile.Web.OsmTileSource(), "OSM"));
        _map.Layers.Add(layerOSM);
        _map.Layers.Add(layer);

So far I'm stuck at this error and Literally no way pass this it seems,

Argument 1: cannot convert from 'BruTile.Web.OsmTileSource' to
  'BruTile.ITileSource'

The version of assemblies I'm using in my project are
Sharpmap    1.1.0.0
 Brutile     0.7.4.4
 ProjNet     1.3.0.3
 NetTopologySuite  1.13.2.0
 GeoAPI   1.7.2.0

I've added all are from Nuget, If someone could share me a piece of code which works in accessing OpenStreetMap as background layer?
that'll be a life-saver.
Thanks in advance, Cheers!

A: I suspect different versions of the BruTile assembly referenced in your projects.


text:
Q: Force user to select text from Autocomplete options in Dynamic Add / Remove Fields I have created an add/remove dynamic fields with Autocomplete option. I am using jquery UI autocomplete for text field. The code works perfect. But I want to force user only to select text that are coming in autocomplete options. Following is the code...

jQuery(document).ready(function($) {
  var wrapper = $("#username-fields");
  var add_button = $("#add-username-fields");

  var x = 1;
  var availableAttributes = [
    "John",
    "Pamela",
    "Rogers",
    "Peter"
  ];

  add_button.click(function(e) {
    e.preventDefault();
    x++;
    var element = $('

<input type="text" class="form-control" name="user_login[]" placeholder="">

<input type="text" class="form-control" name="user_role[]" placeholder=""><input type="hidden" class="form-control" name="status[]" value="Unverified" placeholder="">

<button type="button" class="btn btn-danger" id="remove_field"> Remove</button>

');

    element.fadeIn("slow").find("input[name^='user_login']").autocomplete({
      source: availableAttributes,
    });
    wrapper.append(element);
  });

  wrapper.on("click", "#remove_field", function(e) {
    e.preventDefault();
    $(this).parent().fadeOut(300, function() {
      $(this).closest('#user-fields').remove();
      x--;
    });
  });
});

<button type="button" class="btn btn-success" id="add-username-fields"> Add</button>

I searched and got the following JSFiddle - http://jsfiddle.net/pxfunc/j3AN7/, I want to incorporate the JSFiddle code in my code but some how I am not able to merge both.

A: Try this Code

jQuery(document).ready(function($) {
  var wrapper = $("#username-fields");
  var add_button = $("#add-username-fields");

  var x = 1;
  var availableAttributes = [
    "John",
    "Pamela",
    "Rogers",
    "Peter"
  ];
  var previosValue='';

  add_button.click(function(e) {
    e.preventDefault();
    x++;
    var element = $('

<input type="text" class="form-control" id="user_login" name="user_login[]" placeholder="">

<input type="text" class="form-control" name="user_role[]" placeholder=""><input type="hidden" class="form-control" name="status[]" value="Unverified" placeholder="">

<button type="button" class="btn btn-danger" id="remove_field"> Remove</button>

');

    element.fadeIn("slow").find("input[name^='user_login']").autocomplete({
    autoFocus: true,
      source: availableAttributes,
    });
    wrapper.append(element);
  })

  wrapper.on("keyup","#user_login",function() {
    var isValid = false;
    for (i in availableAttributes) {
        if (availableAttributes[i].toLowerCase().match(this.value.toLowerCase())) {
            isValid = true;
        }
    }
    if (!isValid) {
        this.value = previousValue
    } else {
        previousValue = this.value;
    }

});

  wrapper.on("click", "#remove_field", function(e) {
    e.preventDefault();
    $(this).parent().fadeOut(300, function() {
      $(this).closest('#user-fields').remove();
      x--;
    });
  });
});

<button type="button" class="btn btn-success" id="add-username-fields"> Add</button>


text:
Q: Does Flying Saucer accept HTML not XHTML My original source is HTML not well formed XHTML. At worse i will have to clean and convert the html to xhtml and then feed flying saucer.

A: Flying Saucer does not support HTML; as noted on its website: "No support for legacy HTML (although there are several open source Java HTML cleaners of varying quality available)." You might try one of the HTML cleaners they suggest, though. One of the best is, not surprisingly, HtmlCleaner.

A: The Flying Saucer UserGuide answers my question.

Flying Saucer is an XML/CSS renderer,
  which means it takes XML files as
  input, applies formatting and styling
  using CSS, and generates a rendered
  representation of that XML as output.
  The output may go to the screen (in a
  GUI), to an image, or to a PDF file.
  Because we believe most people will be
  interested in re-using their knowledge
  of web layout, our main target for
  content is XHTML 1.0 (strict), an XML
  document format that standardizes
  HTML. However, we accept any
  well-formed XML for rendering as long
  as CSS is provided that tells us how
  to lay it out. In the case of XHTML,
  default stylesheets are provided out
  of the box and packaged within the
  library, which means Flying Saucer can
  render most XHTML out of the box with
  decent results.


text:
Q: Test if page is child and has children, if so echo child pages also on grandchild pages I am trying to show a sub-menu of child-pages only on level 2 pages (who have a parent) and if they have children. I am using the code below (made from several snippets I found), it works fine on level 1 (not showing anything as meant to be), works fine on level 2: if there are child pages they are shown in the sub-menu.
My question: When i go to level 3 pages I would like the sub-menu to stay but it disappears. How can I change the code below to make it work?
    <?php
        if (is_page() && $post->post_parent ) { // test to see if the page has a parent

          $page = $post->ID;

          if (is_page() ) {
            $page = $post->post_parent;
          }

          $children=wp_list_pages( 'echo=0&child_of=' . $page . '&title_li=' );

          if ($children) {
            $output = wp_list_pages( array(
                'child_of' => $post->ID, // Only pages that are children of the current page
                'depth' => 1, // Only show one level of hierarchy
                'title_li' => ''
            ) );
          }

        }

echo $output;

?>

A: Use ancestors:
$ancestors = array_reverse( get_post_ancestors( $post->ID ) ); // reverse ancestors to make it more intuitive

if ( isset( $ancestors[0] ) ) {

    if ( isset( $ancestors[1] ) ) {
        // 3rd tier
        $parent_id = $post->post_parent;
    } else {
        // 2nd tier
        $parent_id = $post->ID;
    }

    $args = array(
        'depth' => 1,
        'child_of' => $parent_id,
    );

    wp_list_pages( $args );
}


text:
Q: Make an external Script available to all members of qooxdoo Object So I have been making a web app in the qooxdoo framework that utilised the d3 library. At the moment, every function which needs to use the d3 library works like this:
myFunction : function() {
    var req = new qx.bom.request.Script();
    req.onload = this.myActualFunction(); //calls function when script loads
    req.open("GET","http://d3js.org/d3.v3.js" );
    req.send();
}

It seems verbose to have to call the script loader for lots of different functions*. We could, and eventually probably will, switch to using d3 from a local directory. Nevertheless, it seems like there are lots of times when you would like to use a script loader to make a script available to, say, every member function of an object. Is there someway that I can achieve that? If I passed the script loader around like a variable, does that mean that every function which has it in scope gets access to the library?
The Manual did not appear very helpful on this topic.
*I presume that qooxdoo arranges to cache the script - it seems to be pretty good at those type of optimisations, though I have no specific knowledge of how the script loaders are treated in the compiled version.

A: The best approach of handling an external library is to create a Qooxdoo wrapper which will be a first-class citizen in the dependency management process. Qooxdoo internally makes use of this approach, e.g. Sizzle, Mustache, etc. Luckily for you there's already a contribution for D3. Though you can make your own wrapper without a hassle.
You can also, use add-script to "link" the library to the document but I see this way mostly disadvantageous.