text:
Q: Is 'distinctives' an obsolete word? Elsewhere on Stack Exchange I noticed the word 'distinctive' used as a noun and its plural expressed :

How can we educate new users about our site distinctives ?

Bible Hermeneutics - Meta
The OED states that the word 'distinctive' is both an adjective and a noun but it lists references to the noun only up to the nineteenth century.
I can see that the word has a different meaning to 'characteristics' in that 'distinctives' refers to particular characteristics which distinguish something from others of its type.
So, a word which may be useful and a word which someone has used in living memory but is it, officially, an obsolete word ?

A: TL;DR of my post: It hasn't fallen out of use enough/doesn't fit the criteria for obsoleteness, and the plural noun form is still used today.

No.
But before we can proceed, we must look at what makes a word obsolete.

"We rarely take words out of our dictionaries," says Mary O'Neill, managing editor of the largest single-volume English language dictionary, the unabridged Collins English Dictionary, which clocks in at 2,305 pages. "This is especially true of our larger dictionaries. If we find that a word has fallen out of general use, or is not used as much as it was before, we usually label such words as 'obsolete,' 'archaic,' or 'old-fashioned' rather than deleting them entirely."

This paragraph, from Mary O'Neill of the CED, tells us that words that have fallen out of general use have the possibility of being marked obsolete.
But does distinctive(s) match this criterion?
Well, on the OED page, it's marked as a Band 6 word, though this is probably for the adjectival form, is:

Band 6 contains words which occur between 10 and 100 times per million words in typical modern English usage, including a wide range of descriptive vocabulary. It contains many nouns referring to specific objects, entities, processes, and ideas, running from dog, horse, ship, machine, mile, assessment, army, career, stress to gas, explosion, desert, parish, envelope, and headache...

So this implies that it's a word used as much as desert, to name one.
If we head over to NGrams, the word, including the noun form, appears to be on the up!
But if we head over to pretty much all dictionaries, even Google's, it doesn't appear to be a word.
However, as distinctives is the understandable plural of distinctive, lexicographers won't remove words that can be drawn from other words.
From Peter Gilliver, Senior Editor of the OED:

"Because a word like livery is still current, we don't mark the extremely scarce derivative liveryless as obsolete because it is formed from elements which are still current and could be re-formed at any time."

This applies to distinctives. (distinctive + -s plural)
Here is a book example from 2007 where it's used as a noun.  There are more examples, should you care to look.
Since distinctive as a noun is still a used word today (See NGrams again); not marked as rare or otherwise, we can draw the conclusion:
There is no evidence to support it being rare; as a noun, it is still used today; therefore it is not, by most standards, an obsolete word.


text:
Q: I am trying to schedule an ionic cordova background geolocation plugin.Is it possible? I am using this below plugin for getting background geolocation from android application,
https://github.com/mauron85/cordova-plugin-background-geolocation
Is there any possible way to somehow stop the plugin after eight hours or schedule it for specific period of time.
Below is my ionic info,
cli packages:
@ionic/cli-plugin-proxy : 1.4.13
@ionic/cli-utils        : 1.13.1
ionic (Ionic CLI)       : 3.13.1

global packages:
cordova (Cordova CLI) : 7.1.0

local packages:
@ionic/app-scripts : 3.0.0
Cordova Platforms  : android 6.3.0
Ionic Framework    : ionic-angular 3.7.1

System:
Android SDK Tools : 26.0.2
Node              : v6.10.2
npm               : 5.5.1

A: One possible way of doing this is to use the background-mode plugin https://www.npmjs.com/package/cordova-plugin-background-mode
You can use this plugin and setInterval() together to run functions in the background of the app.

redpajama_set_name: RedPajamaStackExchange


text:
Q: cannot convert from 'std::string' to 'char' Changed completely due to suggestions from other member. Most problems solved, still having problems. Now won't output any names from the array in main. Not sure if I'm passing them back correctly from function.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void bubblesort(string[], const int);
int sub = 0;

int main()
{
const int maxsize = 100;
string friendArray[maxsize];

ifstream friends;
friends.open("myFriends.dat");

while (sub < maxsize)
 {
  getline(friends, friendArray[sub]);
  sub++;
 }

 bubblesort(friendArray, maxsize);

 cout<<friendArray[0]<<" "<<friendArray[1]<<" "<<friendArray[2];

 system("pause");
 return 0;
}

void bubblesort(string *array, const int size)
{
    bool swap;
    string temp;

    do
    {
        swap = false;
        for (int count = 1; count < (size - 1); count++)
        {
            if(array[count-1] >array[count])
            {
                temp = array[count-1];
                array[count-1] = array[count];
                array[count] = temp;
                swap = true;
            }
        }
    }
    while(swap);

}

A: Your problem isn't necessarily that temp inside bubblesort is not a char, the problem is that array is declared as a string and not a string[].
The reason you're getting the error is because array[count+1] is of type char, and temp is of type string. std::swap expects two elements of the same type.
However, that may be the least of your problems, your code doesn't compile for quite a few reasons. Not just that but you're passing in maxsize to bubblesort at each iteration. There's a flaw in both your logic and your syntax.
EDIT: Since you're still having trouble getting the sorting to work, here's a working modification of your code:
#include <iostream>

void bubblesort(std::string array[], size_t size)
{
  bool bSwapped;
  std::string temp;

   do
   {
      bSwapped = false;
      for (size_t count = 1; count < size; count++)
      {
         if(array[count-1] > array[count])
         {
            std::swap(array[count-1], array[count]);
            bSwapped = true;
         }
      }
   }
   while(bSwapped);
}

int main(void)
{
   std::string array[] = { "def", "ghk", "abc", "world", "hello" };

   bubblesort(array, sizeof(array)/sizeof(*array));

   for (size_t i = 0; i < sizeof(array)/sizeof(*array); ++i)
      std::cout << array[i] + " ";

   std::cout << std::endl;

   return 0;
}

bubblesort could also be written as: void bubblesort(std::string *array, size_t size). There's no difference in this case since, when passed to a function, arrays decay into pointers.
Since arrays are passed by reference, a pointer to the first element, any modifications made to array inside of bubblesort will actually be modifying your array in main. So that's how arrays are "returned".
std::vector is a good alternative to the standard array, since it automatically resizes and obviously contains the length of the internal array so that you don't have to pass the size everywhere you pass an std::vector. You can also use it the same way as a regular array.

A: temp is a string, array[count] is a char (since an std::string is a vector of char elements.) I'm not sure what you're trying to do here, but the compiler is correct - you can't assign a char to a string.
You could change temp to be a char, since all you do with it is assign a char to it, and then assign it back to an element of array, which is also a char.

A: You need to declare temp as char. You can use std::swap to avoid such mistakes in the future:
std::swap(array[count], array[count+1]);

This would make your code compile, but it would not do what you're trying to do (bubblesort). The problem is that you are passing a single string (which is also an "array" of characters) instead of an array of strings, which is, in a very lose sense, "an array of arrays of characters". Your bubblesort needs to accept string *array as its first parameter.


text:
Q: PyPDF2 cannot import pdf file header I use PyPDF2 to import pdf file in string into python. Problem is the top of the first page doesn't want to be imported (.getPage(0).extracText() misses the top part).
I guess that there is a header property but i cannot find its name and i couldn't find any information on the internet.
Do you know how to do or where i can find information ?


text:
Q: Zend\Db Model with Child Models ZF2 project - no Doctrine, using native Zend\Db: Have the following structure:
Controller
    ProductController
Model
    Product
    ProductTable
    ProductType
    ProductTypeTable

Product is the model, has variables corresponding to the "products" table fields.
ProductTable is table class which is connected to the database via tableGateway. ProductTable has getItem() method to retrieve requested product by "id".
ProductType is the model, has variables like id, name, description corresponding to the "productTypes" table fields.
ProductTypeTable is table class just like ProductTable.
Each product belongs to a certain ProductType
products.productTypeId = productTypes.id

is the relation.
In ProductTable->getItem() method, I can simply get productTypeId.
I can use joins to get productTypes.name, productTypes.description, or any field from "productTypes" table.
But I don't want to do this - instead dealing with new variables in Product entity like productTypeName, productTypeDesc,
 I'd like to have Product->getProductType() and set it to be a ProductType object, so I can get Product->getProductType() ->getName() to get product type name.
Simply I'd like to assign a child model as a variable of the parent model.
I can do this in the controller like below:
$product = $this->getProductTable()->getItem(7); // id = 7
$product->setProductType($this->getProductTypeTable()
                    ->getItem($product->getProductTypeId());

But I'd like to make it happen in product table class getItem() method. So I don't have to think about it in every controller, and it is kind of encapsulated.
What is the right way to do this?
Thank you.

A: The issue that you have is the Table Gateway pattern is only really any good at abstracting database access to a a single database table. It does not in anyway allow for the hydration of entities or management of relationships. Object Relationship Mappers (ORM's), such as Doctrine, solve this problem.
If Doctrine, for whatever reason, is inappropriate for your use case an alternative could be implementing the Data Mapper Pattern

The Data Mapper is a layer of software that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other

The data mapper will use the table gateway to fetch the required data for each table and construct the Product instance, including it's associated ProductType. You would then expose the mapper to the controller (rather than the table gateway).
A simple example of a ProductMapper.
class ProductMapper
{
    // @var  \Zend\Db\TableGateway\TableGateway
    protected $productTable;

    protected $productTypeMapper;

    // an 'identity map' of loaded products
    protected $loaded = [];

    public function __construct(ProductTable $productTable, ProductTypeMapper $productTypeMapper)
    {
        $this->productTable = $productTable;
        $this->productTypeMapper = $productTypeMapper;
    }

    protected function hydrate(Product $product, array $data)
    {
        $product->setId($data['id']);
        $product->setName($data['name']);
        $product->setFoo($data['foo']);

        if (isset($data['type_id'])) {
            // Load a fully constructed product type from the database
            $type = $this->productTypeMapper->findById($data['type_id']);
            $product->setType($type);
        }

        return $product;
    }

    public function findById($id)
    {
        if (isset($this->loaded[$id])) {
            return $this->loaded[$id];
        }
        // Get the data
        $row = $this->productTable->select(['id' => $id]);

        if (empty($row)) {
            throw new SomeCustomException("No product could be found with id $id");
        }
        // Create and hydrate the product
        $product = $this->hydrate(new Product, $row->current())
        $this->loaded[$id] = $product;

        return $product;
    }

    public function save(array $data);

    public function update($data);

    public function delete($id);
}

A: You can achieve this, you just have to follow the following 3 steps:

*

*Make your Product->exchangeArray() function smarter

*Get all required ProductType fields, using a prefix helps for example: type_

*Add @var ProductType so you will have proper autocompete (works for me in Eclipse)
<?php
namespace Product\Model\Product;

class Product {
    public $id;
    ...
    /**
     * @var ProductType
     */
    public $productType;
    ...
    public function exchangeArray( $data ) {
        $this->id = (isset($data['id'])) ? $data['id'] : null;
        ...
        $productType = new ProductType();
        $typeData = array(
            'id' => $data['type_id'],
            'value' => $data['type_value']
        );
        $productType->exchangeArray( $typeData );
        $this->productType = $productType;
    }
}


text:
Q: Wich one is better to use when we ask an user to do it again or finish? In Java We ask to the user if he wants to do it again or finish.
The thing is we let him put [Y] or [N] answer, but can be that he mistakes.
So my problem enters here...
Structure one
       //kb = keyboard
       Scanner kb = new Scanner(System.in);
       //String for the [Y] or [N] answer
       String r = "";
       //boolean to go out the loop and finish
       boolean out = true;

       do {
       //rest of the code of the program
       some stuff
       //
       System.out.println("Do you want to do it again?\n"
                + "[Y] or [N]");
        r = kb.next();
       }while(r == "y" || r == "Y");

Structure two
       do {
       //rest of the code of the program
       some stuff
       //
       System.out.print("Do you want to do it again?\n"
                + "[Y] or [N]");
        String answer = kb.next();
        switch (answer)
        {
        case "Y": out = true;
             break;
        case "y": out = true;
             break;
        case "N": out = false;
             break;
        case "n": out = false;
             break;
        default :
             System.out.println("Not a valid option")   ;
             break;
        }//end switch
        }while(out);

And how I can do it better if the user answer with another word?

A: This is really a style question.  There's no exact right answer.
The switch is a lot more code, so I'd avoid that.
You can take care of the case issue with
 r = kb.next().toUpperCase();

and then use
while ( r.equals("Y") )

since r is a string.


text:
Q: Show that $T=I-2\frac{vv^t}{v^tv }$ is an orthogonal operator Show that $T=I-2\frac{vv^t}{v^tv }$ is an orthogonal operator in $\mathbb{R}^n$ and how to find it's eigenvalues?
I can't see what's the way to start. I have seen that if $\|T(x)\|=\|x\|$ then it's enough, is it?


text:
Q: Dynamically load Images in React Native Semi-new to React Native and i'm having an issue...
I'm trying to require local images based on a variable (an ID stored in a JSON file), I can achieve this if I stored the images online somewhere and used the prop:
source:{uri: 'https://www.domian.com'+this.props.model.id'.png'} for example,  but obviously require needs just a single string so I can't pass it a variable?
I would just use a lengthy for each/if statement but there will be 100+ options for the image name. Which is another reason i'd rather have the images stored locally.
I've been trying a bunch of different ways but haven't found anything, is there any way around this?

A: The following works for me:
// our data
// we need to require all images,
// so that React Native knows about them statically
const items = [
    {
        id: '001',
        image: require('../images/001.jpeg'),
    },
    {
        id: '002',
        image: require('../images/002.jpeg'),
    },
];

// render
items.map( (item) =>
    <Image key={item.id} source={item.image} />
)

NB: This is based on @soutot's updated answer, but simplified. I don't think there is any need for a boolean.

A: AS per your comment and example you mentioned it is like :
imageId is JSON and your passing it using props. Is your baseurl same ? then you can achive single string like :
source:{uri: `https://www.domian.com/${this.props.model.id}.png`}

I hope this will work for you : here is example in which I receive part of url to images from different resources, similar to yours:
https://github.com/patilrevansidh/movidb/blob/master/src/modules/movie/detail/screen.js

A: According to the official docs, the recommendation is using conditional rendering to create the Image require which contains the correct URI path:
// GOOD
<Image source={require('./my-icon.png')} />;

// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />;

// GOOD
var icon = this.props.active
  ? require('./my-icon-active.png')
  : require('./my-icon-inactive.png');
<Image source={icon} />;

https://facebook.github.io/react-native/docs/images.html
More about conditional rendering: https://reactjs.org/docs/conditional-rendering.html
Example using array (just example, may have typos):
const imgs = [
  {
   id: '001',
   require: require('../images/001.jpeg'),
  },
  {
   id: '002',
   require: require('../images/002.jpeg'),
  },
];

imgs.map((item, i) =>
item.id === '001' &&
<Image
  key={i}
  source={item.require}
/>)

Hope it helps


text:
Q: Returning incorrect logical from is.nan I am analyzing microarray data from a publicly available database, and my output is a log-ratio matrix comparing experimental data to controls. I have discovered that one of my columns is populated with NaN values due to the fact that this treatment does not have a corresponding control. My data frame's (fc_initial) dimensions are 9049 x 647.
> dim(fc_initial)
[1] 9049  647

the column that is populated by NaN is the 580th column
head(fc_initial[,580])
# [1] NaN NaN NaN NaN NaN NaN

summary(is.nan(fc_initial[,580]))
#    Mode    TRUE    NA's
# logical    9049       0

When I try to examine this for all columns using apply, R incorrectly returns all FALSE for this column.
fc_num <- apply(fc_initial, 2, is.nan)
summary(fc_num[ ,580])
#    Mode   FALSE    NA's
# logical    9049       0

I have visually confirmed this using view for both fc_initial and fc_num, and I have double checked that I am looking for the right column using which().
which(fc_num, arr.ind = TRUE)
#  row col

which returns no cells showing as TRUE.
What am I missing? Why is R returning a column of FALSE for a column of values I have visually confirmed to be TRUE?

A: When calling apply, the dataframe is coerced to a matrix. If there are any character columns, the whole dataframe is coerced to a character matrix and all NaN are converted to NA
df_1 <- data.frame(a=c("a","b","c"), b=c(NaN, NaN,NaN))
df_2 <- data.frame(a=c(1,2,3), b=c(NaN, NaN,NaN))

as.matrix(df_1)

     a   b
[1,] "a" NA
[2,] "b" NA
[3,] "c" NA

as.matrix(df_2)
     a   b
[1,] 1 NaN
[2,] 2 NaN
[3,] 3 NaN

A: Improvising on @cactusWoman and @joran comment:
## this gives count of nan's by column for your data.frame
sapply(fc_initial, function(y) sum(length(which(is.nan(y)))))


text:
Q: Issue with loading Parquet data into Snowflake Cloud Database when written with v1.11.0 I am new to Snowflake, but my company has been using it successfully.
Parquet files are currently being written with an existing Avro Schema, using Java parquet-avro v1.10.1.
I have been updating the dependencies in order to use latest Avro, and part of that bumped Parquet to 1.11.0.
The Avro Schema is unchanged. However when using the COPY INTO Snowflake command, I receive a LOAD FAILED with error: Error parsing the parquet file: Logical type Null can not be applied to group node but no other error details :(
The problem is that there are no null columns in the files.
I've cut the Avro schema down, and found that the presence of a MAP type in the Avro schema is causing the issue.
The field is
    {
      "name": "FeatureAmounts",
      "type": {
        "type": "map",
        "values": "records.MoneyDecimal"
      }
    }

An example of the Parquet schema using parquet-tools.
message record.ResponseRecord {
  required binary GroupId (STRING);
  required int64 EntryTime (TIMESTAMP(MILLIS,true));
  required int64 HandlingDuration;
  required binary Id (STRING);
  optional binary ResponseId (STRING);
  required binary RequestId (STRING);
  optional fixed_len_byte_array(12) CostInUSD (DECIMAL(28,15));
  required group FeatureAmounts (MAP) {
    repeated group map (MAP_KEY_VALUE) {
      required binary key (STRING);
      required fixed_len_byte_array(12) value (DECIMAL(28,15));
    }
  }
}

The 2 files I have, written in parquet 1.10.1 and 1.11.0 output this identical schema.
I have also tried with a bigger schema example, and it appears everything works fine if there is no "map" avro type present in the schema. I have other massive files with huge schemas, many union types that convert to groups in parquet, but all are written and read successfully when they don't contain any "map" types.
But as soon as I add back the "map" type then I get that weird error message from Snowflake when trying to ingest the 1.11.0 version (however 1.10.1 version will load successfully). But parquet-tools with 1.11.0, 1.10.1 etc can still read the files.
I understand that from this comment that there are changes to the Logical Types in Parquet 1.11.0, but that it is supposed to be compatibile still for old versions to read.
But does anyone know what version of Parquet is used by Snowflake to parse these files? Is there something else that could be going on here?
Appreciate any assistance

A:
Logical type Null can not be applied to group node

Looking up the error above, it appears that a version of Apache Arrow's parquet libraries is being used to read the file.
However, looking closer, the real problem lies in the use of legacy types within the Avro based Parquet Writer implementation (the following assumes Java was used to write the files).
The new logicalTypes schema metadata introduced in Parquet defines many types including a singular MAP type. Historically, the former convertedTypes schema field supported use of MAP AND MAP_KEY_VALUE for legacy readers. The new writers that use logicalTypes (1.11.0+) should not be using the legacy map type anymore, but work hasn't been done yet to update the Avro to Parquet schema conversions to drop the MAP_KEY_VALUE types entirely.
As a result, the schema field for MAP_KEY_VALUE gets written out with an UNKNOWN value of logicalType, which trips up Arrow's implementation that only understands logicalType values of MAP and LIST (understandably).
Consider logging this as a bug against the Apache Parquet project to update their Avro writers to stop nesting the legacy MAP_KEY_VALUE type when transforming an Avro schema to a Parquet one. It should've ideally been done as part of PARQUET-1410.
Unfortunately this is hard-coded behaviour and there are no configuration options that influence map-types that can aid in producing a correct file for Apache Arrow (and for Snowflake by extension). You'll need to use an older version of the writer until a proper fix is released by the Apache Parquet developers.


text:
Q: How to know the size of a text when using Canvas.drawText() I'm using the Canvas.drawText() to write text on a custom view.
I want to add a background 9-patch drawable behind the text, so I need to know the boundaries of the text drawn.
The text is given by the user, so it's not a fixed size.
For now I'm using a monospace font and I managed to build a size which looks not so bad, but in the hand i'd rather use another font.

A: You can use public void getTextBounds(String text, int start, int end, Rect bounds) method of Paint to get a rectangle that encloses all your text. Take a look at getTextBounds.
Hope this helps!

A: I think getTextBounds(String text, int start, int end, Rect bounds) can do it for you.
This method belongs to Paint class:
Refer to this link

A: You also may use measureText
mTextTimeColorPaint.measureText(timeText)

Like in this post Center Text on Watch


text:
Q: Simple keyboardless touchscreen widgets in Qt I'm looking for a simple way to make widgets for a touch-screen that will allow users to set the time and IP address on the computer running the code and provide a simple (uppercase Latin-alphabetic) name.
This question is not about how to actually set the system time or IP address; I'm just looking for information about how to make the graphical widgets themselves.
What I want is for each editable property (time, address, and name) to be divided into "scrollable" fields, where the fields for "time" are hours, minutes, possibly seconds, and AM/PM/24-hr, and the fields for address/name are the individual characters. Each field would have an arrow above and below it, and touching on an arrow would scroll through the valid values for that field.
I think this is a pretty common UX pattern, especially in meatspace (e.g. on alarm clocks), but just in case it's not clear what I'm trying to describe, here's an example with a user editing the "name" property:
^^^
BN
vvv

User presses "down" below the "N":
    ^^^
    BO
    vvv
User presses "down" below the empty space:
^^^^
BOA
vvvv

...and again on the same down-arrow:
^^^^
BOB
vvvv

I'm writing this using C++14 with Qt 5. (If worst comes to worst, I'd be open to writing a separate app using a different language and/or framework, but I'm not asking for framework suggestions here; if you have one, let me know and I'll open a corresponding question on Software Recommendations SE.)
I don't see anything in the Qt 5 widget library like this; most of the input widgets are text fields. QSpinBox looks somewhat promising, but the arrows are probably too small for my touchscreen, and using a separate spinbox for each letter would probably be confusing and ugly.
I don't really know enough about Qt or GUI-programming in general to feel confident trying to write my own widgets from scratch, but this interface looks simple enough that I would expect a couple lines of QML would get me well on my way.

A: ListView as well as PathView can produce the desired result with slightly different behaviors and slightly different performances. Differently from ListView, PathView is circular, i.e. elements can be iterated continuously by using just one of the selection controls. It is also easier to fully customize the behavior of the path in PathView via the PathAttribute type. Anyhow path customization seems not to be a required feature, according to the question.
If you implement the solution via a ListView you should ensure that just one element is shown and that any model is processed.
Component {
    id: spinnnnnnnner

    Column  {
        width: 100
        height: 110
        property alias model: list.model
        property string textRole: ''
        spacing: 10

        Item {
            width: 100
            height: 25
            Text { anchors.centerIn: parent; text: "-"; font.pixelSize: 25; font.bold: true }
            MouseArea {anchors.fill: parent; onClicked: list.decrementCurrentIndex() }
        }

        ListView {
            id: list
            clip: true
            width: 100
            height: 55
            enabled: false          // <--- remove to activate mouse/touch grab
            highlightRangeMode: ListView.StrictlyEnforceRange   // <--- ensures that ListView shows current item

            delegate: Text {
                width: ListView.view.width
                horizontalAlignment: Text.AlignHCenter
                font.pixelSize: 50
                font.bold: true
                text: textRole === "" ? modelData :
                                        ((list.model.constructor === Array ? modelData[textRole] : model[textRole]) || "")
            }
        }

        Item {
            width: 100
            height: 25
            Text { anchors.centerIn: parent; text: "+"; font.pixelSize: 25; font.bold: true }
            MouseArea {anchors.fill: parent; onClicked: list.incrementCurrentIndex() }
        }
    }
}

The checks over the model ensure that any type of model can be passed to the component. Here is an example using three very different models:
import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1

ApplicationWindow {
    visible: true

    width: 400
    height: 300

    ListModel {
        id: mod
        ListElement {texty: "it1"}
        ListElement {texty: "it2"}
        ListElement {texty: "it3"}
    }

    Row {
        Repeater {
            id: rep
            model: 3
            delegate: spinnnnnnnner

            Component.onCompleted: {
                rep.itemAt(0).model = mod                       // listmodel
                rep.itemAt(0).textRole = "texty"
                rep.itemAt(1).model = 10                        // number model
                //
                rep.itemAt(2).model = ["foo", "bar", "baz"]     // array model
            }
        }
    }
}

PathView implementation is not so different from the ListView one. In this case it is sufficient to define a vertical path and specify that just one one element is visible at a time via pathItemCount. Finally, setting preferredHighlightBegin/preferredHighlightEnd ensures that the visible element is centered in the view. The revisited component is the following:
Component {
    id: spinnnnnnnner

    Column  {
        width: 100
        height: 110
        property alias model: list.model
        property string textRole: ''
        spacing: 10

        Item {
            width: 100
            height: 25
            Text { anchors.centerIn: parent; text: "-"; font.pixelSize: 25; font.bold: true }
            MouseArea {anchors.fill: parent; onClicked: list.decrementCurrentIndex() }
        }

        PathView {
            id: list
            clip: true
            width: 100
            height: 55
            enabled: false          // <--- remove to activate mouse/touch grab
            pathItemCount: 1
            preferredHighlightBegin: 0.5
            preferredHighlightEnd: 0.5

            path: Path {
                startX: list.width / 2; startY: 0
                PathLine { x: list.width / 2; y: list.height  }
            }

            delegate: Text {
                width: PathView.view.width
                horizontalAlignment: Text.AlignHCenter
                font.pixelSize: 50
                font.bold: true
                text: textRole === "" ? modelData :
                                        ((list.model.constructor === Array ? modelData[textRole] : model[textRole]) || "")
            }
        }

        Item {
            width: 100
            height: 25
            Text { anchors.centerIn: parent; text: "+"; font.pixelSize: 25; font.bold: true }
            MouseArea {anchors.fill: parent; onClicked: list.incrementCurrentIndex() }
        }
    }
}


text:
Q: Is it possible to make canvas with background with lines or canvas that isn't a rectangle? I'm trying to make this one https://massmoca.org/event/walldrawing340/

in Javascript code, using p5.js, but I have no clue how to fill these shapes with lines. Is there any other possibility, like making canvas that is circle or something like that, or I just have to make each shape seperately?
For now I was doing shape by shape, but making triangle and trapezoid is rough...

        var sketch = function (p) {
          with(p) {

            let h,
                w,
                space;

            p.setup = function() {
              createCanvas(900, 400);
              h = height / 2;
              w = width / 3;
              space = 10;
              noLoop();
            };

            p.draw = function() {
              drawBackground('red', 'blue', 0, 0);
              shape('Circle', 'red', 'blue', 0, 0);
              drawBackground('yellow', 'red', w, 0);
              shape('Square', 'yellow', 'red', w, 0);
              drawBackground('blue', 'yellow', 2 * w, 0);
              shape('Triangle', 'blue', 'red', 2 * w, 0)
              drawBackground('red', 'yellow', 0, h);
              shape('Rectangle', 'red', 'blue', 0, h)
              drawBackground('yellow', 'blue', w, h);
              shape('Trapezoid', 'yellow', 'red', w, h);
              drawBackground('blue', 'red', 2 * w, h);
            };

            function drawBackground(bColor, lColor, x, y) {
                fill(bColor)
                noStroke();
                rect(x, y, w, h)
                stroke(lColor);
                strokeWeight(1);
                for (let i = 0; i < h / space; i++) {
                    line(0 + x, i * space + y + 10, w + x, i * space + y + 10);
                }

            }
            function shape(shape, bColor, lColor, x, y) {
                fill(bColor)
                noStroke();
                let w1;
                switch (shape) {
                    case 'Circle':
                        circle(x + w / 2, y + h / 2, h - space * 6);
                        stroke(lColor);
                        strokeWeight(1);
                        for (let i = 0; i < w / space; i++) {

                            for (let j = 0; j < h; j++) {
                                pX = i * space + x;
                                pY = 0 + y + j;
                                if (pow(x + w / 2 - pX, 2)
                                    + pow(pY - (y + h / 2), 2) <= pow(h - space * 6 * 2 - 10, 2)) {
                                    point(pX, pY);
                                }

                            }
                        }
                        break;

                    case 'Square':
                        w1 = w - (h - space * 6);
                        rect(x + w1 / 2, y + space * 3, h - space * 6, h - space * 6);
                        stroke(lColor);
                        strokeWeight(1);
                        for (let i = 0; i < 15; i++) {
                            for (let j = 0; j < h - space * 6; j++) {
                                point(x + w1 / 2 + i * space, y + space * 3 + j)
                            }
                        }
                        break;

                    case 'Triangle':
                        w1 = w - (h - space * 6);
                        triangle(x + w1 / 2, h - space * 3 + y, x + w / 2, y + space * 3, x + w1 / 2 + h - space * 6, h - space * 3 + y)
                        for (let i = 0; i < w / space; i++) {

                            for (let j = 0; j < h; j++) {
                                pX = i * space + x;
                                pY = 0 + y + j;
                                if (pow(x + w / 2 - pX, 2)
                                    + pow(pY - (y + h / 2), 2) <= pow(h - space * 6 * 2 - 10, 2)) {
                                    point(pX, pY);
                                }

                            }
                        }
                        break;

                    case 'Rectangle':
                        w1 = w - (h - space * 6) / 2;
                        rect(x + w1 / 2, y + space * 3, (h - space * 6) / 2, h - space * 6)
                        break;

                    case 'Trapezoid':
                        w1 = w - (h - space * 6);
                        quad(x + w1 / 2, h - space * 3 + y, x + w1 / 2 + (h - space * 6) / 4, y + space * 3, x + w1 / 4 + h - space * 6, y + space * 3, x + w1 / 2 + h - space * 6, h - space * 3 + y)
                        break;

                    case 'Parallelogram':
                            w1 = w - (h - space * 6);
                            quad(x + w1 / 4, h - space * 3 + y, x + w1 / 2, y + space * 3, x + w1 / 2 + h - space * 6, y + space * 3, x + w1 / 4 + h - space * 6, h - space * 3 + y)
                            break;
                        break;
                }

            }

          }
        };

        let node = document.createElement('div');
        window.document.getElementById('p5-container').appendChild(node);
        new p5(sketch, node);
    body {
      background-color:#efefef;
    }

No messages, everything is working, I just want to know if I have to do so much arduous job...

A: If you don't need actual line coordinates (for plotting for example), I'd just make most out of createGraphics() to easily render shapes and lines into (taking advantage of the fact that get() returns a p5.Image) and p5.Image's mask() function.
Here's a basic example:

function setup() {
  createCanvas(600, 300);

  let w = 300;
  let h = 150;
  let spacing = 12;
  let strokeWidth = 1;

  const BLUE   = color('#005398');
  const YELLOW = color('#f9db44');
  const RED    = color('#dc1215');

  bg = getLinesRect(w, h, RED, BLUE, spacing, strokeWidth, true);
  fg = getLinesRect(w, h, RED, YELLOW, spacing, strokeWidth, false);
  mask = getCircleMask(w, h, w * 0.5, h * 0.5, 100, 0);

  image(bg, 0, 0);
  image(fg, w, 0);
  // render opaque mask (for visualisation only), mask() requires alpha channel
  image(getCircleMask(w, h, w * 0.5, h * 0.5, 100, 255),0, h);

  // apply mask
  fg.mask(mask);
  // render bg + masked fg
  image(bg, w, h);
  image(fg, w, h);

  // text labels
  noStroke();
  fill(255);
  text("bg layer", 9, 12);
  text("fg layer", w + 9, 12);
  text("mask", 9, h + 12);
  text("bg + masked fg", w + 9, h + 12);
}

function getLinesRect(w, h, bg, fg, spacing, strokeWidth, isHorizontal){
  let rect = createGraphics(w, h);
  rect.background(bg);
  rect.stroke(fg);
  rect.strokeWeight(strokeWidth);

  if(isHorizontal){
    for(let y = 0 ; y < h; y += spacing){
      rect.line(0, y + strokeWidth, w, y + strokeWidth);
    }
  }else{
    for(let x = 0 ; x < w; x += spacing){
      rect.line(x + strokeWidth, 0, x + strokeWidth, h);
    }
  }
  // convert from p5.Graphics to p5.Image
  return rect.get();
}

function getCircleMask(w, h, cx, cy, cs, opacity){
  let mask = createGraphics(w, h);
  // make background transparent (alpha is used for masking)
  mask.background(0, opacity);
  mask.noStroke();
  mask.fill(255);
  mask.circle(cx, cy, cs);
  // convert p5.Graphics to p5.Image
  return mask.get();
}

You can apply the same logic for the rest of the shapes:

function setup() {
  createCanvas(1620, 590);

  let compWidth  = 500;
  let compHeight = 250;
  let compSpacing= 30;

  let lineWeight = 1.5;
  let lineSpacing = 12;

  const BLUE   = color('#005398');
  const YELLOW = color('#f9db44');
  const RED    = color('#dc1215');

  // yellow square
  circleMask   = getCircleMask(compWidth, compHeight, compWidth * 0.5, compHeight * 0.5, 210);
  redCircle    = getComposition(compWidth, compHeight, RED,
                                                    BLUE,
                                                    YELLOW,
                                                    lineSpacing, lineWeight, circleMask);

  // red box
  boxMask      = getRectMask(compWidth, compHeight, (compWidth - 100) * 0.5, 20, 100, 210);
  redBox       = getComposition(compWidth, compHeight, RED,
                                                    YELLOW,
                                                    BLUE,
                                                    lineSpacing, lineWeight, boxMask);

  // yellow square
  squareMask   = getRectMask(compWidth, compHeight, 144, 20, 210, 210);
  yellowSquare = getComposition(compWidth, compHeight, YELLOW,
                                                    RED,
                                                    BLUE,
                                                    lineSpacing, lineWeight, squareMask);

  // yellow trapeze
  trapezeMask   = getQuadMask(compWidth, compHeight, 200, 25, 200 + 115, 25,
                                                     150 + 220, 220, 150, 220);
  yellowTrapeze = getComposition(compWidth, compHeight, YELLOW,
                                                    BLUE,
                                                    RED,
                                                    lineSpacing, lineWeight, trapezeMask);

  // blue triangle
  triangleMask   = getTriangleMask(compWidth, compHeight, compWidth * 0.5, 25,
                                                     150 + 220, 220, 150, 220);
  blueTriangle   = getComposition(compWidth, compHeight, BLUE,
                                                    YELLOW,
                                                    RED,
                                                    lineSpacing, lineWeight, triangleMask);

  // blue parallelogram
  parallelogramMask = getQuadMask(compWidth, compHeight, 200, 25, 200 + 145, 25,
                                                         150 + 145, 220, 150, 220);
  blueParallelogram = getComposition(compWidth, compHeight, BLUE,
                                                    RED,
                                                    YELLOW,
                                                    lineSpacing, lineWeight, parallelogramMask);

  // render compositions
  image(redCircle, compSpacing, compSpacing);
  image(redBox, compSpacing, compSpacing + (compHeight + compSpacing));

  image(yellowSquare, compSpacing + (compWidth + compSpacing), compSpacing);
  image(yellowTrapeze, compSpacing + (compWidth + compSpacing), compSpacing + (compHeight + compSpacing));

  image(blueTriangle, compSpacing + (compWidth + compSpacing) * 2, compSpacing);
  image(blueParallelogram, compSpacing + (compWidth + compSpacing) * 2, compSpacing + (compHeight + compSpacing));

}

function getComposition(w, h, bgFill, bgStroke, fgStroke, spacing, strokeWidth, mask){
  let comp = createGraphics(w, h);

  bg = getLinesRect(w, h, bgFill, bgStroke, spacing, strokeWidth, true);
  fg = getLinesRect(w, h, bgFill, fgStroke, spacing, strokeWidth, false);
  // apply mask
  fg.mask(mask);
  // render to final output
  comp.image(bg, 0, 0);
  comp.image(fg, 0, 0);

  return comp;
}

function getRectMask(w, h, rx, ry, rw, rh){
  let mask = createGraphics(w, h);
  // make background transparent (alpha is used for masking)
  mask.background(0,0);
  mask.noStroke();
  mask.fill(255);
  mask.rect(rx, ry, rw, rh);
  // convert p5.Graphics to p5.Image
  return mask.get();
}

function getCircleMask(w, h, cx, cy, cs){
  let mask = createGraphics(w, h);
  // make background transparent (alpha is used for masking)
  mask.background(0,0);
  mask.noStroke();
  mask.fill(255);
  mask.circle(cx, cy, cs);
  // convert p5.Graphics to p5.Image
  return mask.get();
}

function getQuadMask(w, h, x1, y1, x2, y2, x3, y3, x4, y4){
  let mask = createGraphics(w, h);
  // make background transparent (alpha is used for masking)
  mask.background(0,0);
  mask.noStroke();
  mask.fill(255);
  mask.quad(x1, y1, x2, y2, x3, y3, x4, y4);
  // convert p5.Graphics to p5.Image
  return mask.get();
}

function getTriangleMask(w, h, x1, y1, x2, y2, x3, y3){
  let mask = createGraphics(w, h);
  // make background transparent (alpha is used for masking)
  mask.background(0,0);
  mask.noStroke();
  mask.fill(255);
  mask.triangle(x1, y1, x2, y2, x3, y3);
  // convert p5.Graphics to p5.Image
  return mask.get();
}

function getLinesRect(w, h, bg, fg, spacing, strokeWidth, isHorizontal){
  let rect = createGraphics(w, h);
  rect.background(bg);
  rect.stroke(fg);
  rect.strokeWeight(strokeWidth);

  if(isHorizontal){
    for(let y = 0 ; y < h; y += spacing){
      rect.line(0, y + strokeWidth, w, y + strokeWidth);
    }
  }else{
    for(let x = 0 ; x < w; x += spacing){
      rect.line(x + strokeWidth, 0, x + strokeWidth, h);
    }
  }
  // convert from p5.Graphics to p5.Image
  return rect.get();
}

Probably both rectangles and the triangle could've been drawn using getQuadMask() making good use of coordinates.
Note that I've just eye balled the shapes a bit so they're not going to be perfect, but it should be easy to tweak. Bare in mind the placement of the mask will have an effect of on how the vertical lines will align.
There are probably other ways to get the same visual effect.
For example, using texture() and textureWrap(REPEAT) with beginShape()/endShape(), using pixels for each line and checking intersections before changing direction and colours, etc.
In terms of generating lines for plotting I would start with horizontal lines, doing line to convex polygon intersection to determine where to stop the horizontal lines and start vertical lines. @AgniusVasiliauskas's answer(+1) is good for that approach.
Freya Holmér has a pretty nice visual explanation for the test.

A: You need linear algebra stuff, basically noticing how vertical line starting/ending Y coordinate changes in relation to line's X coordinate. And of course a lot of experimenting until you get something usable. Something like :
var w = 600
    h = 600
    sp = 15

var slides = [fcircle, fsquare, ftriangle, ftrapezoid, fparallelogram];

var active = 0;

var ms;

function blines(){
  stroke(0);
  for (var i=0; i < h; i+=sp) {
    line(0,i,w,i);
  }
}

function vertlines(calcline) {
   for (var x=w/2-w/4+sp; x < w/2+w/4; x+=sp) {
       var pnts = calcline(x);
       line(pnts[0],pnts[1],pnts[2],pnts[3]);
   }
}

function fcircle() {
   // cut background
   noStroke();
   circle(w/2, h/2, w/2);
   stroke('red');
   // draw figure lines
   let calc = function (x){
      var sx = x-w/2;
      var sy = h/2;
      var ey = h/2;
      sy += 137*sin(2.5+x/135);
      ey -= 137*sin(2.5+x/135);
      return [x,sy,x,ey];
   }
   vertlines(calc);
}

function fsquare() {
   // cut background
   noStroke();
   quad(w/2-w/4, h/2-h/4, w/2+w/4, h/2-h/4,
        w/2+w/4, h/2+h/4, w/2-w/4, h/2+h/4);
   stroke('red');
   // draw figure lines
   let calc = function (x){
      return [x,h/2-h/4,x,h/2+h/4];
   }
   vertlines(calc);
}

function ftriangle() {
   // cut background
   noStroke();
   quad(w/2, h/2-h/4, w/2+w/4, h/2+h/4,
        w/2-w/4, h/2+h/4, w/2, h/2-h/4);
  stroke('red');
   // draw figure lines
   let calc = function (x){
      var inpx = x > w/2 ? w-x : x;
      var ys = h/2+h/4;
      ys += -(0.3*inpx*log(inpx)-220);
      return [x,ys,x,h/2+h/4];
   }
   vertlines(calc);
}

function ftrapezoid() {
   // cut background
   noStroke();
   quad(w/2-w/10, h/2-h/4, w/2+w/10, h/2-h/4,
        w/2+w/4, h/2+h/4, w/2-w/4, h/2+h/4);
   stroke('red');
   // draw figure lines
   let calc = function (x){
      var inpx = x > w/2 ? w-x : x;
      var ys = h/2+h/4;
      ys += -(0.55*inpx*log(inpx)-420);
      if (x >= w/2-w/10 && x <= w/2+w/10) {
         ys=h/2-h/4;
      }
      return [x,ys,x,h/2+h/4];
   }
   vertlines(calc);
}

function fparallelogram() {
   // cut background
   noStroke();
   quad(w/2-w/10, h/2-h/4, w/2+w/7, h/2-h/4,
        w/2, h/2+h/4, w/2-w/4, h/2+h/4);
   stroke('red');
   // draw figure lines
   let calc = function (x){
      // guard condition
      if (x > w/2+w/7)
         return [0,0,0,0];
      var inpx = x > w/2 ? w-x : x;
      var ys = h/2+h/4;
      ys += -(0.55*inpx*log(inpx)-420);
      var ye=h/2+h/4
      if (x >= w/2-w/10) {
         ys=h/2-h/4;
      }
      if (x > w/2) {
         ye = h/2+h/4;
         ye += 0.50*inpx*log(inpx)-870;
      }
      return [x,ys,x,ye];
   }
   vertlines(calc);
}

function setup() {
  ms = millis();
  createCanvas(w, h);
}

function draw() {
   if (millis() - ms > 2000) {
      ms = millis();
      active++;
      if (active > slides.length-1)
         active = 0;
   }
   background('#D6EAF8');
   fill('#D6EAF8');
   blines();
   slides[active]();
}

Slideshow DEMO

A: I have a way to do some of the shapes, but I am not sure about others. One way you could do it is if you know where every point on the outline of the shape is, you could just use a for loop and connect every other point from the top and bottom using the line or rect function. This would be relatively easy with shapes like squares and parallelograms, but I am not sure what functions could be used to get this for the points of a circle or trapezoid.
See more here: https://www.openprocessing.org/sketch/745383


text:
Q: MassTransit messages not picked up I'm using MassTransit version 2.7.0 to communicate between a web service and a web site. The web service publishes messages and the website subscribes to them.
Publisher service:
    ServiceBus = ServiceBusFactory.New(sbc =>
        {
            sbc.UseMsmq();
            sbc.VerifyMsmqConfiguration();
            sbc.ReceiveFrom("msmq://localhost/publisher");
            sbc.UseMulticastSubscriptionClient();
        });

Subscriber website:
    ServiceBus = ServiceBusFactory.New(sbc =>
        {
            sbc.UseMsmq();
            sbc.VerifyMsmqConfiguration();
            sbc.ReceiveFrom("msmq://localhost/website");
            sbc.UseMulticastSubscriptionClient();

            sbc.Subscribe(s =>
                {
                    s.Handler<SomethingHappened>(HandleSomethingHappened);
                });
        });

Everything works fine on my dev machine but not on the live site. The messages are showing up in the website_subscriptions MSMQ queue, but they aren't getting picked up by the subscribed website. The server does have multiple NICs so I added the registry settings to support that. I don't get any errors or anything - it just doesn't pickup the messages from the queue.
Am I missing some configuration or permissions problem? Is there some way to see why it isn't working?
[edit]
I just noticed that the website_subscriptions queue is all messages from the framework: AddPeerMessage and AddPeerSubscriptionMessage. All the messages from the service (SomethingHappened in the above example) are in the error queue.

A: You might try setting up the Log4Net or NLog integration to see what is happening in MassTransit. They did a great job of logging lots of useful troubleshooting information.


text:
Q: How to authorize using Apache Camel? I have to make a POST request
curl -X POST --data-binary @auth.json http://somehost.com/auth
{
    "response": {
        "status": "OK",
        "token": "622cee5f8c99c81e87614e9efc63eddb"
    }
}

, and this will return a JSON response with the token. auth.json is a JSON file with login and password. I then have two options: put the token in the header in future requests as "Authorization: TOKEN", or put it in a cookie and make other requests.
How can I do it with Apache Camel? How can I receive HTTP response? Where do I put the token?
Now I have:
public static void main(String args[]) throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.addRoutes(new RouteBuilder() {
        public void configure() {
            from("file:data/inbox?noop=true")
            .to("http://somehost.com/auth");
        }
    });
    context.start();
    Thread.sleep(10000);
    context.stop();

}
and I have the auth.json file in ./data/inbox

A: Since you posted the same question on the Apache Camel mailing list I've provided an answer there.
To summarize: Just call setHeader("Authorization", constant("622cee5f8c99c81e87614e9efc63eddb")) in your route before sending the http request. Camel will automatically translate this header to a transport specific (in this case HTTP) header. Of course you don't need to provide a constant token in your route, you can dynamically calculate or lookup the token by using a Camel expression or processor.
Your complete route will look something like:
context.addRoutes(new RouteBuilder() {
    public void configure() {
            from("file:data/out?fileName=filename.json&noop=true")
            .setHeader("Authorization", constant("mytoken"))
            .to("http://somehost.com/auth");
 }


text:
Q: Clicking Todo on top causes bottom todo to be also clicked

When I click the checkbox for Task 1 in active todo filter mode, it also toggles the checkbox for Task 2 for some reason. But if I switch between the completed todo button and come back to active todo button it goes away.
Code Sandbox
https://stackblitz.com/edit/react-d3n8dv?file=src%2FApp.js

A: In TodoItem component, you need to have checked field in your input checkbox instead of defaultChecked field. And change onClick to onChange as well.
      <span>
        <input
          type="checkbox"
          checked={props.isActive}
          onChange={() => props.checkBoxHandler(props.todoItem)}
        />
        {props.todoItem}
      </span>


text:
Q: How do I setup a Master Page with ASP.net? I'm normally a ColdFusion developer, but I'm having to work on a new site using some ASP.net hosting only, so forgive me if my questions seem very trivial.
For numerous reasons, the website will be relatively static in the sense that it will mainly be using includes etc...that's about as complex as it will get with this.
Now, I heard about the ability to set a master in ASP.net. Would anyone please be able to explain to me in a step process on how to do this? I have of course been searching for some time now on this topic but most results yield little help or no help at all since the search terms are slightly ambiguous.
It would be nice to have this functionality for the long run. Any help or advice would be great.
Many thanks.
Michael.

A: Here's a great walkthrough video on creating and using Master pages in ASP.NET.
Basically, the steps are:

*

*Add a Master page to your ASP.NET project. This is the same for webforms and ASP.NET MVC

*Style it as you like. This is where most of your <head> content will be... CSS, JavaScript, etc. The key steps are to have ContentPlaceHolders. Those areas around the CPH will be static, and not change.

*Add a new Content page. You'll then choose the Master to inherit from.

*Add content to the Content page as you like. You'll see (in Design View) that the Master's look and feel will be uneditable. In Source view, you'll only be able to specify the content that will go into the Master's ContentPlaceHolders.

It'll be much easier to fit into the .NET ecosystem and all the built in features. Try it free -- download Visual Web Developer Express. Using other editors would waste an order of magnitude of your time! The install takes maybe 4 mins. There's no wizard here, it's just a File->New Document scenario.

A: The second section on this page (http://www.asp.net/web-forms/fundamentals/) has 10 links to various tutorials about masterpages.

A: Here's yet another tutorial - it's all text, but brief and to the point.  You can see the source and demo.  Definitely second the VS Express recommendation.
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/masterpages/default.aspx


text:
Q: Insert data from lineEdit into mysql is blank in PyQt I want to get data from lineEdit ,show it in tablewidget and insert it into mysql.
But it's strange tablewidget is blank ,nothing in Item and mysql don't change.I have saw Python/PyQT QString won't insert into MySQL database. But I failed.
from PyQt4 import QtCore, QtGui,QtSql
import sys
from test2 import Ui_MainWindow
#I use Qt designer to do the UI

class StartQt4(QtGui.QMainWindow,Ui_MainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.setupUi(self)
        self.db = QtSql.QSqlDatabase.addDatabase("QMYSQL")  #select database type
        self.db.setHostName("localhost")
        self.db.setDatabaseName("test")
        self.db.setUserName("root")
        self.db.setPassword("")
        if (self.db.open()):
            self.showdata()
        else:
            print "failed"
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.add)

    def add(self):
        name0 = str(self.lineEdit.text())
        name1 = str(self.lineEdit_2.text())
        name2 = str(self.lineEdit_3.text())
        print type(name0)
        self.query=QtSql.QSqlQuery(self.db)
        self.query.exec_("insert into qiu (name0,nam1,name2) value ('%s','%s','%s')" %(''.join(name0),''.join(name1),''.join(name2)))
        self.query.exec_("commit")
        lastrow=self.tableWidget.rowCount()
        self.tableWidget.insertRow(lastrow)
        self.showdata()

    def  showdata(self):
        query=QtSql.QSqlQuery(self.db)
        query.exec_("select * from qiu")
        for i in range(0,self.tableWidget.rowCount()):
            query.next()
            name0 = query.value(0).toString()
            name1 = query.value(1).toString()
            name2 = query.value(2).toString()
            self.tableWidget.setItem(i, 0, QtGui.QTableWidgetItem(name0))
            self.tableWidget.setItem(i, 1, QtGui.QTableWidgetItem(name1))
            self.tableWidget.setItem(i, 2, QtGui.QTableWidgetItem(name2))

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = StartQt4()
    myapp.show()
    sys.exit(app.exec_())


text:
Q: Limit of the Trapezoidal Rule
Let $f$ be Riemann-integrable and $\zeta=\{x_0,...x_n\}$ the most equidistant pratition. Show that $$\lim_{n\to\infty} \frac{b-a}{n} (\sum_{k=1}^n \frac{f(x_{k-1})+f(x_k)}{2})=\int_a^b f(x)dx$$

My try (but this is obviously wrong)
We define the Riemann-integral as (short) $$\lim_{n\to\infty} \sum_{k=1}^n f(\xi)\Delta x_k$$
Hence $f(\xi)=\frac{f(x_{k-1})+f(x_k)}{2}\in f([x_{k-1},x_k])$
(Note, this is only true if $f$ is increasing).
Could anyone give me a hint on how to continue, without the need for an increasing-function assumption?

A: The sum you wrote down is a Riemann sum. Let $$I_0=\left[a,a+\frac{(b-a)}{2n}\right]$$
$$I_k=\left[a+\left(k-\frac12\right)\frac{(b-a)}n,a+\left(k+\frac12\right)\frac{(b-a)}n\right]$$
For $1\le k\le n-1$, and
$$I_n=\left[b-\frac{(b-a)}{2n},b\right]$$
The intervals cover $[a,b]$ and the width $\Delta x_k$ of each interval containing $x_k$ is the weight given to $f(x_k)$ in the trapezoidal rule.

A: Clearly if $f$ is Riemann integrable on $[a, b]$ and if $\zeta = \{x_{0}, x_{1}, x_{2}, \ldots, x_{n}\}$ is a partition of $[a, b]$ with $x_{k} = a + kh$ and $h = (b - a)/n$ then by the definition of Riemann integration it follows that $$\lim_{n \to \infty}\frac{b - a}{n}\sum_{k = 1}^{n}f(\xi_{k}) = \int_{a}^{b}f(x)\,dx\tag{1}$$ where $\xi_{k}$ is any arbitrary point in interval $[x_{k - 1}, x_{k}]$.
Now we need to take $\xi_{k} = x_{k - 1}$ in $(1)$ and again take $\xi_{k} = x_{k}$ in $(1)$ and adding the resulting equations we get $$\lim_{n \to \infty}\frac{b - a}{n}\sum_{k = 1}^{n}\{f(x_{k - 1}) + f(x_{k})\} = 2\int_{a}^{b}f(x)\,dx$$ and dividing by $2$ we get the desired equation. All we need to assume is that $f$ is Riemann integrable on $[a, b]$.


text:
Q: How to load a JSON file to a single column of a Redshift table I am trying to load the below JSON sample to a single column in Redshift table from S3 as a Proof of Concept. However it is not working successfully. Any help on the same would be of great help.
(This is just a sample JSON with random values to check if it is working)
{
    "Name":"ABC",
    "Department":"HR",
    "Rollno":1,
    "Salary":1000,
    "RS Factor":4,
    "Expected Value":8.1,
    "Comment": "",
    "Correction Factor": 1,
    "Fruit":"Apple",
    "Size":"Large",
    "Color":"Red"
}

COPY command used:
COPY "schema"."table" ("column") FROM 's3://bucketname/file.json'
WITH CREDENTIALS AS 'aws_access_key_id=XXXXXX;aws_secret_access_key=XXXXXX'
MAXERROR AS 0 DATEFORMAT AS 'auto' TIMEFORMAT AS 'auto'
ACCEPTANYDATE TRIMBLANKS
EMPTYASNULL
BLANKSASNULL
COMPUPDATE OFF
STATUPDATE OFF ROUNDEC
JSON AS 'auto'
ENCODING AS UTF8 ACCEPTINVCHARS AS '?'
IGNOREHEADER AS 0

A: You need to add json 'noshred' instead of auto . Thats all . it will load the json to single column without breaking it into multiple column
COPY "schema"."table" ("column") FROM 's3://bucketname/file.json'
WITH CREDENTIALS AS 'aws_access_key_id=XXXXXX;aws_secret_access_key=XXXXXX'
MAXERROR AS 0 DATEFORMAT AS 'auto' TIMEFORMAT AS 'auto'
ACCEPTANYDATE TRIMBLANKS
EMPTYASNULL
BLANKSASNULL
COMPUPDATE OFF
STATUPDATE OFF ROUNDEC
JSON 'noshred'
ENCODING AS UTF8 ACCEPTINVCHARS AS '?'
IGNOREHEADER AS 0


text:
Q: Convert file permissions in Bash Is there a simple way to convert file permissions?
For Example:
if [ filePermission = -rw-r--r-- ]
then
    echo 644
fi
if [ filePermission = -r-xr-xr-x ]
then
    echo 555
fi

  # etc..

I'm not trying to change the permissions, just look at the octal value.
Something like this:
-bash-4.1$ ls -l test*
-rw-r--r-- 1 user joe 0 Nov  11 09:41 test1
-r-xr-xr-x 1 user joe 0 Nov  11 10:12 test2*
-r--r----- 1 user joe 0 Nov  11 10:14 test3
-rwxr-x--- 1 user joe 0 Nov  11 10:17 test4*
-bash-4.1$ ./perm test*
test1:
permissions: 644
test2:
permissions: 555
test3:
permissions: 440
test4:
permissions: 750

A: If you just want to print the the octal representation for a given file, stat can help:
stat --printf '%a' your_file


text:
Q: How do you describe waking up in the morning brain functioning slowly? Is there an adjective describing waking up in the morning and feeling slow, not able to remember stuff and think slowly?

A: Consider groggy
Defined by Oxford Dictionaries as:

Dazed, weak, or unsteady, especially from illness, intoxication, sleep, or a blow.

"She was still groggy from sleep"

A: Heard someone describe it as 'brain fog' recently and thought it accurate and descriptive.

A: The usual description is - you are still "half-asleep".
I'm trying to type, but I'm half-asleep.
https://www.thefreedictionary.com/half-asleep


text:
Q: cURL with PHP, possible to determine the IP address cURL will use? Is it possible to determine programmatically what IP address cURL is using when connecting to a remote server? I have a shared server that I am using cURL on, and I need to send the IP address as part of the request.
The server that I am talking to requires an authentication string that combines the connection IP address and a rotating passcode (eg my $code = SHA1($_SERVER['SERVER_ADDR'] . $passcode) gets compared on their end with SHA1($_SERVER['REMOTE_ADDR'] . $passcode)). This worked fine when the outgoing connection from cURL was using the same IP as is stored in $_SERVER['SERVER_ADDR'], however the IP address used by cURL is now different and rotating periodically.

A: You can force the IP that curl uses, as opposed to detecting it.
Use the CURLOPT_INTERFACE option for curl_setopt() - set it to the IP you wish to use.
If you are using a server, such as a cloudserver, with an IP pool - then it is advisable to select the interface to use, if it is important to detect that on the other side, for security reasons.
Personally, I have had to use the feature for card payment data transfers via cURL, when the IP is restricted.

A: You can do this to get your public IP before you call:
$ch = curl_init('http://whatismyip.org/');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
$myIp = curl_exec($ch);

However:

*

*If your public IP sometimes changes between cURL sessions, there is nothing to say that it wont change between the above session and the next one for which you actually need this data.

*It relies on whatismyip.org (or similar service) actually being running.

A: There is a web site called whatismyip.com.  They have a publically available API that you can use as long as you don't exceed their limit (which is something like five requests per hour??).  Won't hurt to give it a shot, eh?

A: Assuming that curl is always running from the same server, even if it has multiple NICs it shouldn't matter if you tell curl which IP to use.
I would use DaveRandom's trick of getting what IP you are currently using, then set it for the next call using
curl_setopt($ch, CURLOPT_INTERFACE, "XXX.XXX.XXX.XXX");

Assuming the two calls are close enough, there is a very high chance that IP will still be bound to an interface and by setting it you are telling curl to use that one, instead of whichever one the load balancer may want to use.


text:
Q: mock.patch() Not patching function in module call, but is in test function So I am trying to mock a function and it is not being mocked in the module where it is being called, but it when called directly in the test function. I am unsure what I'm doing wrong. I use patch all the time without any problems.
So in the test I have below
from unittest.mock import patch
from django.test import TestCase
from web.utils.registration import test_render_mock

class TestRenderMock(TestCase):

    @patch("django.shortcuts.render")
    def test_render_mock(self, render_mock):
        request = self.make_request()

        # Calls render in same way in function below
        test_render_mock(request)

        from django.shortcuts import render
        r = render(request, 'c')
        print(type(r))

which is calling the function in the file web/utils/registration.py
from django.shortcuts import render

def test_render_mock(request):
    r = render(request, 'registration/signup_link_error.html')
    print(type(r))

And it isn't mocking the render call in the function test_render_mock but it is in the test function test_render_mock(). The console output is below.
<class 'django.http.response.HttpResponse'>
<class 'unittest.mock.MagicMock'>

I have no idea what I'm doing wrong. Any help would be appreciated.
Using python version 3.8.2 and Django 3.0.5
UPDATE
I used to use the third party library mock, but using the built in one now from tne unittest library.
now for third party library you need to define the module path where there imported like so
from unittest.mock import patch
from django.test import TestCase
from web.utils.registration import test_render_mock

MODULE_TESTING: str ='...'

class TestRenderMock(TestCase):

    @patch(f"{MODULE_TESTING}.render")
    def test_render_mock(self, render_mock):
        request = self.make_request()

        # Calls render in same way in function below
        test_render_mock(request)

        from django.shortcuts import render
        r = render(request, 'c')
        print(type(r))


text:
Q: Mouse and keyboard cloning software is there a software available that can "mirror" keyboard and mouse inputs to multiple windows? Like I have a "master"-window in which I click and write and the input from there gets send to several "slave"-windows.
Cheers!


text:
Q: Variable Number Limit This is a game that I have created in C# 2010, but values for Attack and Health for comp become negative when user inputs [1] Increase your Defense.
        bool jet = false;

        int userinput;

        Console.WriteLine("Pick your team color, Blue or Green. ");
        string userName = Console.ReadLine();

        if (userName == "blue")
        {
            user.Name = "Blue Fighterjet";
            comp.Name = "Green Fighterjet";
        }

        else
        {
            user.Name = "Green Fighterjet";
            comp.Name = "Blue Fighterjet";
        }

        Console.Clear();

        Console.WriteLine("You are now the {0}.", user.Name);
        Console.ReadLine();

        Console.Clear();

        Console.WriteLine("What do you want to do for your first move?");
        Console.ReadLine();

        while (jet == false)
        {
            Console.Clear();
            Console.WriteLine("Your stats:");
            Console.WriteLine("Health {0} \n Defense {1} \n Attack {2}", user.Health, user.Defense, user.Attack);

            Console.WriteLine("Comp stats:");
            Console.WriteLine("Health {0} \n Defense {2} \n Attack {2}", comp.Health, comp.Defense, comp.Attack);
            Console.ReadLine();

            Console.WriteLine("[1] Increase your Defense.");
            Console.WriteLine("[2] Regain some of your Health.");
            Console.WriteLine("[3] Attack the {0}.", comp.Name);
            userinput = int.Parse(Console.ReadLine());

            if (userinput == 1)
            {
                user.Defense = user.Defense + random.Next(1, 10);

                if (userinput == 1)
                {
                    comp.Attack = comp.Attack - user.Defense + random.Next(1, 10);
                }
            }

            if (userinput == 2)
            {
                user.Health = user.Health + random.Next(1, 10);

                if (userinput == 2)
                {
                    comp.Defense = comp.Defense + random.Next(1, 10);
                }
            }

            if (userinput == 3)
            {
                user.Attack = user.Attack + random.Next(1, 10);

                if (userinput == 3)
                {
                    comp.Health = comp.Health - user.Attack + random.Next(1, 10);
                }
            }
        }
    }
}
class jet
{
    private string name;
    private int health = 100;
    private int defense = 0;
    private int attack = 5;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public int Health
    {
        get
        {
            return health;
        }

        set
        {
            if (value <= 100)
            {
                health = value;
            }
            else
            {
                health = 100;
            }
        }

    }

    public int Defense
    {
        get
        {
            return defense;
        }
        set
        {
            if (value <= 10)
            {
                defense = value;
            }
            else
            {
                defense = 10;
            }
        }
    }

    public int Attack
    {
        get
        {
            return attack;
        }
        set
        {
            if (value <= 5)
            {
                attack = value;
            }
            else
            {
                attack = 5;
            }
        }
    }
}

Any tips on how i can easily fix this?
are my userinputs incorrect?

A: This will give you 0 or a positive number...Math.Max(0,variable)
Also, you don't need a nested if statement when it is the same condition
if (value ==1)
{
  //Do Something
    if (value == 1) //This will always happen unless DoSomething has changed value.
    {
    }
}


text:
Q: OperationalError('near "?": syntax error') Мне нужно поместить в столбец значение "1" при этом имя столбца хранится в переменной "link_for_channel" поэтому я делаю всё через знак вопроса. Но у меня вылазит ошибка.
База Данных:
def Add_StatusSubscription(self, link_for_channel):
   with self.conn:
      return self.cursor.execute("INSERT INTO 'DataBase' (?) VALUES (1)", (link_for_channel,))

Основной код:
balance = 0
num = 0
people = 0
rand = 0
i = 3

def check_sub_channel(chat_member):
    print(chat_member.status)
    if chat_member.status != 'left':
        return True
    else:
        return False

def Menu(message: types.Message):
    global num
    global rand
    global i

    if message.chat.type == 'private':

        rand = random.randint(10, 25)

        markup_Inline = types.InlineKeyboardMarkup(row_width=1) # Активация клавиатуры
        Inline_B1 = types.InlineKeyboardButton(text="↗Перейти в канал", url=channels_URL[i]) # добавление кнопки с именем
        Inline_B2 = types.InlineKeyboardButton(text="✅Я выполнил!", callback_data="SUB_CHECK") # добавление кнопки с именем
        markup_Inline.add(Inline_B1, Inline_B2)

        bot.send_message(message.chat.id,f"⭐<b>Доступно новое задание на {rand}₽:</b>\n\nПерейди в канал, подпишись, возвращайся сюда и жми кнопку 'Я выполнил'", parse_mode='HTML', reply_markup=markup_Inline)
    else:
        bot.send_message(message.from_user.id,MISTAKE)

@bot.message_handler(commands=["start"])
def menu_check(message: types.Message):
    global people
    global channels_URL

    if message.chat.type == 'private':

        get_column_names=conn.execute("select * from PandaDataBase limit 1")
        channels_URL=[i[0] for i in get_column_names.description] # получение всех имён всех столбцов

@bot.message_handler(content_types=["text"])
def Reply_buttons(message):
    if message.text == 'Задание':
        Menu(message)

@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
    global balance
    global rand
    global i
    USER_ID = call.from_user.id
    try:
        if call.message:
            if call.data=="SUB_CHECK":
                print("1")
                if check_sub_channel(bot.get_chat_member(chat_id=call.message.chat.id, user_id=USER_ID)):
                    bot.edit_message_text(text=TRY_SUB_MESSAGE, chat_id=call.message.chat.id, message_id=call.message.message_id, reply_markup=markup_Inline_Next_Task)
                    db.Add_StatusSubscription(link_for_channel=channels_URL[i]) # Вот заветная строка

                    balance += rand
                    i += 1

###########################    ЗАПУСК БОТА    ################################

if __name__ == '__main__':
    bot.infinity_polling()


text:
Q: Python : download a file from drive in another format using apidrive First point : i have a question please , is there the possibility to download a pdf file from my drive as doc or any other format using Google Drive API?
just as we can do manualy on drive : open a pdf file as google documents and download it .
EDIT :
Second point : what i did :
connect to apidrive via quickstart. I Turned on the Drive API(Step1) , and Installed the Google Client Library (step2).
after that, i tryed to upload a file from my HD to my drive using the code :
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

#1st authentification
gauth = GoogleAuth()
gauth.LocalWebserverAuth() # Creates local webserver and auto handles
authentication.
drive = GoogleDrive(gauth)

file1 = drive.CreateFile()
file1.SetContentFile('documt.pdf')
file1.Upload()

the next step in my plan, was to download 'documt.pdf' that i've just uploaded to drive , in a different format (.doc for example). So i searched how to do So, i've found the following script , even if it doesn't do what i exactly want (as the docs says) , it can only download Google Documents as pdf(the inverse of what i wanted) :
file_id = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'
request = drive_service.files().export_media(fileId=file_id,
                                         mimeType='application/pdf')
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print "Download %d%%." % int(status.progress() * 100)

however even this code shows an error :
Traceback (most recent call last):
File "C:\Users\OU\AppData\Local\Programs\Python\Python36-
32\download_from_drive.py", line 10, in <module>
request = drive_service.files().export_media(fileId=file_id,
NameError: name 'drive_service' is not defined

my client_secrets file looks like (don't know if it does have a relation to the problem):
{"web":{"client_id":"xxxxx.apps.googleusercontent.com","project_id":"xxxx","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/x/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/c","client_secret":"erm-xxxx","redirect_uris":["http://localhost:8080/"],"javascript_origins":["http://localhost:8080"]}}
can anyone help me find a answer to my question (first point), and a solve the Error (second point)?
THANK YOU Very Much

A: I think that your script works fine. But from the error of NameError: name 'drive_service' is not defined, I thought that you may use Quickstart for Drive API. Your snippet on your question can be used as a part of the Quickstart. Your error is service = discovery.build('drive', 'v3', http=http) of Quickstart. In your case, the variable of drive_service is service at Quickstart. So the flow for using your snippet is as follows.

*

*Do Step 1 and Step 2 of Quickstart.

*For Step 3, modify service = discovery.build('drive', 'v3', http=http) to drive_service = discovery.build('drive', 'v3', http=http).

*Replace script below drive_service = discovery.build('drive', 'v3', http=http) in main() to your snippet. When you do this, please be careful the indent of your script.

A: Finnally, i've answered to my question.
for the first point : it's not allowed to download a pdf as another format. However we can upload the file in the first place with the google docs format application/vnd.google-apps.document even if it's a pdf. and i will work really fine.
For the second point: because the 1st point issue is solved now, i don't need to fix the Error. cause what i wanted works perfectly good.


text:
Q: initiate parent method from child view SWIFT I'm looking for the best possible way to initiate a parent method from a child's view controller.
The parent is a scroll view with three UIViewController children nested inside. The code to have them initialized and attached works fine... just can't seem the find a way to call methods of parent.
thanks in advance!

A: A generic way to call (public/internal) methods in a parent from a child or another class entirely is to save a reference to the parent in the child
class parent {
    ...

    internal func doSomething() {
        println("Did something...")
    }
}

class child {
    let pReference: parent

    init(p: parent) {
        self.pReference = p
    }

    internal func callInParent() {
        self.pReference.doSomething()
    }
}

let x = parent()
let y = child(x)
y.callInParent() // prints "Did something..."

This is easy to practise inside a playground. Give it a go.


text:
Q: How do I get cached image stored by AFNetworking's UIImageView category? I'm using following category UIImageView+AFNetworking.h from AFNetworking in my app, its working fine, its caching photos for me and loads images smoothly.
At one point, I want to get an image which is already there in my cache.
So I dig up into above category class where I found following code, which I think – can be helpful.
Here's the snippet from it:
@implementation AFImageCache

- (UIImage *)cachedImageForRequest:(NSURLRequest *)request {
    switch ([request cachePolicy]) {
        case NSURLRequestReloadIgnoringCacheData:
        case NSURLRequestReloadIgnoringLocalAndRemoteCacheData:
            return nil;
        default:
            break;
    }

    return [self objectForKey:AFImageCacheKeyFromURLRequest(request)];
}

- (void)cacheImage:(UIImage *)image
        forRequest:(NSURLRequest *)request
{
    if (image && request) {
        [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)];
    }
}

@end

If you want me to add web version of this, it's already here.
I think, - (UIImage *)cachedImageForRequest:(NSURLRequest *)request is the method which can return me my cached image.
But I'm not sure, how can I use it?
If I know Objective-C a bit, it's a kinda a "protocol"?
What I have tried so far is to use it like a protocol in one of my view controller. Like this:
#import <UIKit/UIKit.h>

@interface MyViewController : UIViewController<AFImageCache>

@end

But then it is giving me following warnings:

I'm not sure how to resolve those warnings and get the image from cache? Or any other more appropriate way?

A: I assume you import UIImageView+AFNetworking.h header.
If you want to access to the cached image. You should have a NSURLRequest object. Then it is like this:
UIImage *image = [[UIImageView sharedImageCache] cachedImageForRequest:request];

Done!


text:
Q: How to properly upload multiple attachments to sharepoint using pnpjs? I need the users to be able to upload attachments. then i need to display the attachment so it can be selected and viewed.
sometimes there may only be a single attachment. sometimes multiple.
file type can be .xlsx,.xls,.doc, .docx,.ppt, .pptx,.txt,.pdf,.png, .jpg, .jpeg,.gif, .msg

right now im using this line of code in our react/typescript project
faqList.items.getById(addedFaq.data.Id).attachmentFiles.add(attachmentFiles![i].name, 'File added')

it currently uploads a single file (and i need to be able to upload multiple files).
and when the file is retrieved and opened. it displays "File added". which is the text added at the end of the code snippet above.
So Im doing something wrong.
So can someone write an example of the proper code needed to upload multiple attachments to a sharepoint list and to retrieve those attachments without them being overwritten?
UPDATE:
in the the documentation PNPJS ATTACHMENT DOCS
In the example to add an attachment they use the following code
await item.attachmentFiles.add("file2.txt", "Here is my content");

But what is "Here is my content", what does that represent?


text:
Q: Como criar um buffer para manipular imagens em Pillow? Estou desenvolvendo uma aplicação onde eu preciso criar imagens muitos grandes (100MB de imagem por exemplo), desenhando pixel por pixel nela, utilizando a biblioteca Pillow.
O problema é que utilizando o método tradicional, o Pillow armazena a imagem por completo na memória, o que acaba consumindo bastante recurso.
"""
Método tradicional para criar imagens em Pillow.
"""
image = Image.new("RGB", (5000, 5000)) # Isso consome muita RAM!!

for y in range(5000):
    for x in range(5000):
        image.putpixel((x, y), get_custom_pixel())

image.save(filename)

Então eu estava pensando em uma solução de buffering, para desenhar a imagem aos poucos, sem consumir tanta memória. O problema é que eu não achei isso em nenhum lugar da internet, apenas algumas menções. Eu gostaria de saber se é possível fazê-lo e, se sim, como.


text:
Q: How to invoke a custom nginx module for any request? Is handler always needed? Can filters be invoked directly instead? I am trying to write a nginx module which will filter out GET requests for any resource whose size is greater than say 1000KB. I followed the tutorials, the module compiles and installs fine. However I think the module is not getting invoked on an incoming request. The module consists of header and body filters which will check the outgoing requests content size, if greater than 1000KB it will clear the response body and redirect to a different port which I will be throttling in firewall. I used some logging statements but I cannot see any thing in logs because of which I think its not getting invoked. I am attaching full source

#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>

typedef struct {
    ngx_str_t     download_filter;

} ngx_http_download_conf_t;

static void *ngx_http_download_create_conf(ngx_conf_t *cf);
static ngx_int_t ngx_http_download_filter_init(ngx_conf_t *cf);
static ngx_int_t ngx_http_download_header_filter(ngx_http_request_t *r);
static ngx_int_t ngx_http_download_body_filter(ngx_http_request_t *r, ngx_chain_t *in);

//static char *ngx_http_download_module( ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
//static u_char ngx_download_filter_module[] = "download filter";

static ngx_command_t ngx_download_filter_module_commands[] = {
  {
    ngx_string("download_filter"),
    NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS,
    ngx_conf_set_str_slot,
    NGX_HTTP_LOC_CONF_OFFSET,
    offsetof(ngx_http_download_conf_t, download_filter),
    NULL },
    ngx_null_command
};

static ngx_http_module_t  ngx_http_download_filter_module_ctx = {
  NULL,                            /* preconfiguration */
  ngx_http_download_filter_init,   /* postconfiguration */

  NULL,                           /* create main configuration */
  NULL,                           /* init main configuration */

  NULL,                           /* create server configuration */
  NULL,                           /* merge server configuration */

  ngx_http_download_create_conf,  /* create location configuration */
  NULL                            /* merge location configuration */
};

ngx_module_t ngx_http_download_filter_module = {
  NGX_MODULE_V1,
  &ngx_http_download_filter_module_ctx, /* module context */
  ngx_download_filter_module_commands,                          /* module directives */
  NGX_HTTP_MODULE,               /* module type */
  NULL,                          /* init master */
  NULL,                          /* init module */
  NULL,                          /* init process */
  NULL,                          /* init thread */
  NULL,                          /* exit thread */
  NULL,                          /* exit process */
  NULL,                          /* exit master */
  NGX_MODULE_V1_PADDING
};

static ngx_http_output_header_filter_pt  ngx_http_next_header_filter;
static ngx_http_output_body_filter_pt    ngx_http_next_body_filter;

static ngx_int_t
ngx_http_download_filter_init(ngx_conf_t *cf)
{
  printf("hello world: inside init function\n");

  ngx_http_next_header_filter = ngx_http_top_header_filter;
  ngx_http_top_header_filter = ngx_http_download_header_filter;

  ngx_http_next_body_filter = ngx_http_top_body_filter;
  ngx_http_top_body_filter = ngx_http_download_body_filter;

  return NGX_OK;
}

static
ngx_int_t ngx_http_download_header_filter( ngx_http_request_t *r)
{

  ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "inside the header filter");
  printf("inside header filter hello world\n");

  ngx_str_t new_location= ngx_string("http://localhost:5000/flake.jpg");

  if ( r->headers_out.content_length_n > 1000 && r->headers_out.status == NGX_HTTP_OK )
  {
      r->headers_out.status = NGX_HTTP_MOVED_TEMPORARILY;
      r->headers_out.content_type.len = 0;
      r->headers_out.location->value.data = new_location.data;
      r->headers_out.location->value.len = new_location.len;
      ngx_http_clear_content_length(r);
      ngx_http_clear_accept_ranges(r);

  }

 r->headers_out.status = NGX_HTTP_MOVED_TEMPORARILY;

  return ngx_http_next_header_filter(r);
}

static
ngx_int_t ngx_http_download_body_filter ( ngx_http_request_t *r, ngx_chain_t *in )
{

  if ( r->headers_out.content_length_n > 1000 && r->headers_out.status == NGX_HTTP_OK )
  {
    r->discard_body = 0;
    return ngx_http_next_body_filter(r, in);
  }

  return ngx_http_next_body_filter(r, in);

}

static void *
ngx_http_download_create_conf(ngx_conf_t *cf)
{
    ngx_http_download_conf_t  *conf;
    conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_download_conf_t));
    if (conf == NULL) {
        return NULL;
    }

    /*
     * set by ngx_pcalloc():
     *
     *     conf->before_body = { 0, NULL };
     *     conf->after_body = { 0, NULL };
     *     conf->types = { NULL };
     *     conf->types_keys = NULL;
     */

    return conf;
}

My nginx conf uses the download_filter directive. Following is a snippet.

http {
    include       mime.types;
    default_type  application/octet-stream;

   log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"';

     access_log  /tmp/log/access.log  main;
       error_log   /tmp/log/error.log info;
        sendfile        on;
        #tcp_nopush     on;

        #keepalive_timeout  0;
        keepalive_timeout  65;

        download_filter;

The module initializes as I see "hello world, inside init function" string when I start nginx.
Anything that I am missing which is stopping my filters? I am not using a handler here as I do not need to serve anything and let nginx do its work and use filters right before it is being served. Do I need a handler? If yes how can I make a handler which just serves the content and let filters do its work.


text:
Q: jQuery JS no longer works when upgrading from version When I updated the following JS function from jQuery 1.4.2 to the latest 1.11.2 the className Steam no longer animates.
$(window).load(function(){
    function animSteam(){
        $('<span>',{
            className:'steam'+Math.floor(Math.random()*2 + 1),
            css:{
                marginLeft    : -10 + Math.floor(Math.random()*20)
            }
        }).appendTo('#rocket').animate({
            left:'-=58',
            bottom:'-=100'
        }, 120,function(){
            $(this).remove();
            setTimeout(animSteam,10);
        });
    }
    function moveRocket(){
        $('#rocket').animate({'left':'+=100'},5000).delay(1000)
        .animate({'left':'-=100'},5000,function(){
            setTimeout(moveRocket,1000);
        });
    }
    moveRocket();
    animSteam();
});

This is a cool animation I hate to loose and I'm not sure what function has been deprecated.

A:
The name "class" must be quoted in the object since it is a JavaScript reserved word, and "className" cannot be used since it refers to the DOM property, not the attribute.

reference: http://api.jquery.com/jQuery/#jQuery-html-attributes

A: Check this out:  http://bugs.jquery.com/ticket/9150#comment:1

That was never supported and was coincidental that it worked. The attribute to set is class, not className.

So, it seems what you want is:
    $('<span>',{
        'class': 'steam'+Math.floor(Math.random()*2 + 1),
        css:{
            marginLeft    : -10 + Math.floor(Math.random()*20)
        }
    })


text:
Q: Social media buttons validation problems When you add social media buttons to your site from Google+, Facebook, LinkedIn etc., they often contain a lot of homemade attributes and other things that don't validate.
I have fourteen errors on this page in the validator just because of social buttons.
Are there any tricks to make the page validate?

A: As the buttons will only work for users with Javascript, the simplest thing you could do is to insert them via javascript. Then your page will validate again.
Beware of the privacy issues of "social spying buttons". It is a good pracitise to not automatically load them, but just show a placeholder image, and load the actual button when the user has clicked it. These are the so called "2 click likes". First click to enable transmitting your data to Facebook, the second click to like.

A: An incorrect HTML version causes most of the errors - the social buttons are using data- attributes, part of HTML5, but the page has been validated as HTML4.
Sorting the doctype should fix a bunch of those errors.


text:
Q: How to fetch attendance report from attendance table through mysql query? I create an  attendances table. I insert data success fully but when fetch the data from attendances table, data not show of my needs attendance table.
in_out column keeps reference for in and out time. Value "1" is for in time and value "2" for out time.
This is my query.
SELECT t.person_id,
       t.date,
       Substring_index(t.in_out, '#', 1)                           am_in,
       Substring_index(Substring_index(t.in_out, '#', 2), '#', -1) am_out
FROM   (SELECT h.person_id,
               h.date,
               Group_concat(h.timedata ORDER BY h.in_out SEPARATOR '#') in_out
        FROM   attendances h
        GROUP  BY h.person_id,
                  h.date) t

When person out time dose not enter the vale of in time show in time_out column
I want to show null column instead of same repeating time.
I want this result.

A: You can try using CASE WHEN Expression
select t.person_id,t.date,
substring_index(t.in_out,'#',1) am_in,
case when substring_index(t.in_out,'#',1)=substring_index(substring_index(t.in_out,'#',2),'#',-1) then 'Can not scan' else substring_index(substring_index(t.in_out,'#',2),'#',-1) end as am_out
from
(
select h.person_id,h.date,group_concat(h.timedata order by h.in_out separator '#') in_out from attendances h group by h.person_id,h.date
) t


text:
Q: How to get nam working with ns2 simulator Currently I have installed ns2 in my linux pc and when I run the following on terminal
$ ns sampleprog.tcl

all I get is
nam:

There should have been a nam pop up window opening instead.
I don't know how to solve this problem as I have installed both ns2 and nam. I think it is due to me updating my Ubuntu 22.04 with which nam also got updated and is now not compatible with version of ns2. Before update nam was working fine.
How should I go about solving this problem or maybe possibly degrading the version?
I tried updating to the latest version but to no avail. The network animator window that i was expecting doesn't open

A: I faced same problem in my nam 1.15 version,I downloaded nam 1.14 Deb file from this link a lower version.
After downloading Deb file .Open terminal in folder where nam 1.14 Deb file is downloaded And run this command.
$sudo dpkg --install nam_1.14_amd64.deb
This solved my problem.


text:
Q: Java - Create a variable which does the same thing as a name of a class Maybe the title souds misterious, but i don't the specific words of java.
I will try to be clear :
I would like to create an instance of the class A<T extends B>, but I only know the Type of T.
Type myType = ...; //defined in my code via getGenericParameterTypes() from a Constructor object
Class myVariable = Class.forName(myType.getTypeName());
A<myVariable> = new A<myVariable>(); //doesn't work

Maybe some of you may know a solution or an other way to do it.
Thank you !
EDIT :
Here is more information :
I have a class A<T extends B> and i have to call it recursively, the only parameter is T and T is the class of a parameter of a method.
I got the name of T using :
Type typeT = cl.getConstructors()[0].getGenericParameterTypes()[0];
String nameT = typeT.getTypeName();

now i want to do
A<T> myNewInstance = new A<T>();

But i dont know how to define T


text:
Q: Meu state React, não funciona? Meu state não funciona por nada, já li na documentação, fiz igual como devem observar sou novo no react, exemplo do meu código:
export default class Cursos extends Component{

    state = {dataLoad: '' };
    state = { isHungry: '' };

    componentDidMount(){

     console.log(data.cursos)
       this.setState({ isHungry: 'false' });
       this.setState({
            dataLoad:'teste'
        })
        console.log(isHungry)
    }

A: Olá, como iniciou o seu projeto React?
É necessário importar o react e depois escrever a function. Começa aprendendo a escrever seus componentes em formato de funções que é mais fácil de aprender e atual. O estado declarei na const onde o name é a variável que será utilizada no seu componente react, e o setName é onde você irá setar o nome e controlar esse state, caso você crie uma função, o setName('Novo nome') serve para você controlar esse estado cuidando de um dos fundamentos do react que é a imutabilidade. Como já deixei o nome João ali, ele irá retornar para você entre as tags div.
import React, { useState } from 'react'

function nomeDoComponent() {
  const [name, setName] = useState('João')

  return (
{name}
)
}

export default nomeDoComponent

A: Realmente você está iniciando, o estado do componente como foi criado não vai funcionar, é isolado apenas a um local e nele pode ter vários estados no caso exemplifico assim:
state = {dataLoad: '', isHungry: ''};

e para alterar os seus estados podendo ser individual:
this.setState({dataLoad: true});

ou em conjunto:
this.setState({dataLoad: true, isHungry: false});

resolvi contudo exemplificar um simples componente:

class Cursos extends React.Component {
    state = {dataLoad: '', isHungry: '' };
    componentDidMount(){
      this.setState({dataLoad: true, isHungry: false});
    }
    render() {
      return (

{new String(this.state.dataLoad)}

{new String(this.state.isHungry)}

      )
    }
}

ReactDOM.render(<Cursos/>, document.getElementById('root'));

tem também com hooks ou Componentes Funcionais, como nesse exemplo:

function Cursos() {
  const [dataLoad, setDataLoad] = React.useState('');
  const [isHungry, setIsHungry] = React.useState('');
  React.useEffect(() => {
    setDataLoad(true);
    setIsHungry(false);
  }, []);
  return (

{new String(dataLoad)}

{new String(isHungry)}

  )
}

ReactDOM.render(<Cursos/>, document.getElementById('root'));


text:
Q: How to display custom layout with ng-repeat Edit: My original question was not good enough, so edited it now.
Hi Im new to angular and im trying to display a custom Layout
for my data list with ng-repeat. I cant use ng-class, as I would like to display diffent model vaules too.
I implemented a function in my controller, that calculates true or false according to my desired design. Then im trying to use ng-if to display my desired HTML with the data. The way I implemeted seems a bit awkward, especially if the layout gets more complicated, is there a better way to achieve this behaviour?
Here a sample: http://plnkr.co/edit/puE7OE?p=info
Controller:
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
   $scope.eventModels=[{name:'event1', description: 'description1'}, {name:'event2', description: 'description2'},
   {name:'event3', description: 'description3'}, {name:'event4', description: 'description4'},
   {name:'event5', description: 'description5'}, {name:'even6', description: 'description6'}, {name:'even7', description: 'description7'}];

    var counter = 0;
    this.isLarge = false;
    $scope.isLargeContainer = function() {
         if(counter === 0) {
            this.isLarge = true;
            counter++;
        } else {
            this.isLarge = false;
            if(counter === 2) {
                counter = 0;
            } else {
                counter++;
            }
        }
    };
});

View:

my large event: {{eventModel.name}}, {{eventModel.description}}

{{eventModel.name}}

Thanks a lot in advance!
Im using Anguler 1.3.3

A: I just solved your problem. You can find the solution here:
http://jsfiddle.net/anasfirdousi/46saqLmw/

Here is the HTML

var myApp = angular.module('myApp',[]);

function myController($scope){

$scope.msg = 'Learning Angular JS ng-class Directive';
    $scope.menu = [ 'Menu Item 1','Menu Item 2','Menu Item 3','Menu Item 4'];

}
.large {
    font-size:16px;

}

body{
font-size:12px;

}

    {{ msg }}

  {{ value }}

In your case, you actually have to use ng-class with expressions. The class is applied only if the condition holds true.

A: http://jsfiddle.net/anasfirdousi/cuo6cn3L/
Check the above link. This is another example if you want to do it on any specific condition. You can call a function which checks a condition and returns either a true or a false rather than using an inline expression.

var myApp = angular.module('myApp',[]);

function myController($scope){

$scope.msg = 'Learning Angular JS ng-class Directive';
    $scope.menu = [ 'Menu Item 1','Menu Item 2','Menu Item 3','Menu Item 4'];
    $scope.CheckSometing =  function(v){

        if(v=='Menu Item 3'){
             return true;
        }
        else
        {
            return false;
        }

    }

}
.large {
    font-size:16px;

}

body{
font-size:12px;

}

    {{ msg }}

  {{ value }}