text:
Q: React-Native native-base How to decrease the spacing between card Items? render() {
  return(
    <Card style={{  padding: 0 }}>
      <CardItem listItemPadding={0} header style=styles.Card}>
        <Text style={styles.cardText}>
          {this.props.library.title}
        </Text>
      </CardItem>
    </Card>
  );
}

The docs say that listItemPadding can be used but it's not working
I have tried to change the padding of  to 0 but it's not working either.

A: Use the cardBody attribute in cardItem it will work.

A: I see that you are trying to use listItemPadding prop which doesn't exist at the moment.
ListItem, Card and CardItems, each have some padding or margin of their own. You can just inspect the screen, check it and remove the padding/margin as per your requirement using style. Or you can eject NativeBase theme (Customize) and do your changes in the theme of those components. That way you will have the same styles for those components in your whole app.
Probably you are looking for a paddingVertical property. You can add a negative value and then edit your component style as you will normally do.

native-base-theme/components/CardItem.js

paddingVertical: variables.cardItemPadding - 5,

Then on your component:
render() {
  return(
    <Card style={{  padding: 10 }}>
      <CardItem header style={{ paddingTop: 10 }}>
        <Text>Item</Text>
      </CardItem>
    </Card>
  );
}

A: try this code:
render() {
        return(

<View style={{  flex: 0,
 elevation: 3,
 shadowColor: "#000",
 shadowOpacity: 0.1,
 shadowOffset: { width: 0, height: 2 },
 shadowRadius: 1.0,
 marginVertical: 1,
 borderRadius: 2,
 marginHorizontal: 1,
 margin: 0,
 padding: 0,
borderWidth: 0, }}>

                 <CardItem listItemPadding={0} header style=styles.Card}>
                     <Text style={styles.cardText}>
                         {this.props.library.title}
                     </Text>
                 </CardItem>

             </View>

        );
    }

A:
you can use marginTop

const styles = StyleSheet.create({
    shadowOffset: { width: 0, height: 5 },
        shadowRadius: 6,
        shadowOpacity: 0.26,
        elevation: 8,
        backgroundColor: 'white',
        padding: 20,
        borderRadius: 10,
        paddingTop: 20,
        width: 400,
        maxWidth: '50%',
        marginTop: 10,
});

A: To control the padding,  put all the sides...
paddingLeft: 0,
paddingRight: 0,
paddingTop: 0,
paddingBottom: 0
...you can then put the appropriate padding number in any of the sides. But declare padding for all the four sides.


text:
Q: помогите разобраться в миграциях yii2 итак у меня есть:

*

*меню

*разделы

*блюда
блюда находятся в определенном разделе, а разделы находятся в определенном меню
в качестве ДБ я использую postgresql 9.6
я создал первую миграцию для меню:
public function safeUp()
{
    $tableOptions = null;
    if ($this->db->driverName === 'mysql') {
        // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
        $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
    }

    $this->createTable('{{%menu_list}}', [
        'id' => $this->primaryKey(),
        'title_ru' => $this->string()->notNull(),
        'title_en' => $this->string()->notNull(),
        'url' => $this->string(),
        'img_url' => $this->string(),
        'weight' => $this->integer(),

        'status' => $this->smallInteger()->notNull()->defaultValue(1),
        'created_at' => $this->integer()->notNull(),
        'updated_at' => $this->integer()->notNull(),
    ], $tableOptions);

    $this->createIndex('FK_menu', '{{%menu_list}}', 'id');
}

public function safeDown()
{
    $this->dropTable('{{%menu_list}}');
}

и вторую миграцию для разделов и блюд:
public function safeUp()
{
    $tableOptions = null;
    if ($this->db->driverName === 'mysql') {
        // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
        $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
    }

    $this->createTable('{{%category}}', [
        'id' => $this->primaryKey(),
        'title_ru' => $this->string()->notNull(),
        'title_en' => $this->string()->notNull(),
        'url' => $this->string(),
        'img_url' => $this->string(),
        'weight' => $this->integer(),
        'menu_id' => $this->integer()->notNull(),

        'status' => $this->smallInteger()->notNull()->defaultValue(1),
        'created_at' => $this->integer()->notNull(),
        'updated_at' => $this->timestamp(),
    ], $tableOptions);

    $this->createTable('{{%dish}}', [
        'id' => $this->primaryKey(),
        'title_ru' => $this->string()->notNull(),
        'title_en' => $this->string()->notNull(),
        'desc_ru' => $this->string(),
        'desc_en' => $this->string(),
        'url' => $this->string(),
        'img_url' => $this->string(),
        'weight' => $this->integer(),
        'category_id' => $this->integer()->notNull(),

        'status' => $this->smallInteger()->notNull()->defaultValue(1),
        'created_at' => $this->integer()->notNull(),
        'updated_at' => $this->integer()->notNull(),
        ], $tableOptions);

    $this->createIndex('FK_dish_category', '{{%dish}}', 'category_id');
    $this->addForeignKey(
        'FK_dish_category', '{{%dish}}', 'category_id', '{{%category}}', 'id', 'SET NULL', 'CASCADE'
    );

    $this->createIndex('FK_category_menu', '{{%category}}', 'menu_id');
    $this->addForeignKey(
        'FK_category_menu', '{{%category}}', 'menu_id', '{{%menu_list}}', 'id', 'SET NULL', 'CASCADE'
    );
}

public function safeDown()
{
    $this->dropTable('{{%dish}}');
    $this->dropTable('{{%category}}');
}

все было бы ничего, да вот только при попытке сгенерить код через CRUD самого yii2 для модели которую я создал для таблицы category, у меня без всяких ошибок просто редиректит с ошибкой

Error (#1) An internal server error occurred.

(http://joxi.ru/p27oVyRfodp0y2)
сдается мне что у меня не правильно написана миграция и в результате создалась не правильная модель с неправильными зависимостями и не генерируется код с помощью CRUD именно для модели category(для остальных моделей все сгенерилось нормально), помогите пожалуйста.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does stdin work when _IOFBF is set in linux # when _IOFBUF is set, I think the system call read should be called and a
     is set only before the program exits or the buffer is full.But the
     variable a get input value before the sleep function.#
#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    char buf[1024];
    int a;

    setvbuf(stdin, buf, _IOFBF, 1024); // set stdin full buf
    printf("input a:\n");
    scanf("%d", &a);
    printf("a: %d\n", a);
    printf("sleep 5(s)\n");
    sleep(5);

    return 0;
}

A: With your guess:

when _IOFBUF is set, I think the system call read should be called and a is set only before the program exits or the buffer is full

you suppose a logic which isn't applicable to C, at least, without explicit library support: you suppose a postponed execution. The latter is usual for some environments and languages (Javascript-based, Tcl-based, etc.), but not for C.
In C, when an input is requested from your program using scanf, that is the place when syscall read is executed and the buffer is expected to be filled. Then, this buffer is utilized for reading. A next read syscall will be executed when buffer is empty, not earlier; but the initial fill is done, in analog, for the first input request (your scanf). And, yep, this is before sleep.
If the input is (or can be) a terminal, setting full buffering for it is plainly wrong (and stdio doesn't do this by default). With full buffering, scanf will return only after the buffer filling (that is, many many keyboard strokes) and/or explicit EOF (Ctrl+D after Enter at Unix/BSD/Linux systems). I guess that's not the behavior you want.


text:
Q: SVN list sorted by creation date If I run svn list svn://repo.example.com/tags, the listing is:
REL_1.9.0/
REL_1.9.1/
REL_1.9.10/
REL_1.9.11/
REL_1.9.12/
REL_1.9.13/
REL_1.9.14/
REL_1.9.15/
REL_1.9.16/
REL_1.9.2/
REL_1.9.3/
REL_1.9.4/
REL_1.9.5/
REL_1.9.6/
REL_1.9.7/
REL_1.9.8/
REL_1.9.9/

What I would like to get is:
REL_1.9.0/
REL_1.9.1/
REL_1.9.2/
REL_1.9.3/
REL_1.9.4/
REL_1.9.5/
REL_1.9.6/
REL_1.9.7/
REL_1.9.8/
REL_1.9.9/
REL_1.9.10/
REL_1.9.11/
REL_1.9.12/
REL_1.9.13/
REL_1.9.14/
REL_1.9.15/
REL_1.9.16/

So that I can get the most recent tag by tailing like this:  svn ... | tail -1
How can I get the tags sorted by creation date, rather than alphabetic order.
Thanks!

A: The version of sort I have (cygwin) has this option
 -V, --version-sort          natural sort of (version) numbers within text

$ cat test.txt | sort -V
REL_1.9.0/
REL_1.9.1/
REL_1.9.2/
REL_1.9.3/
REL_1.9.4/
REL_1.9.5/
REL_1.9.6/
REL_1.9.7/
REL_1.9.8/
REL_1.9.9/
REL_1.9.10/
REL_1.9.11/
REL_1.9.12/
REL_1.9.13/
REL_1.9.14/
REL_1.9.15/
REL_1.9.16/

So give svn list ... | sort -V | tail -1 a try


text:
Q: What data structure should I use to model a database/table? Databases usually look like this
┃Name|Age|..┃
┠────┼───┼──┨
┃John│025│..┃
┃Carl│033│..┃
┃....│...│..┃

In this case I mean a table with a fixed column size and a variable size of unsorted rows which can be addressed by an id.
Is there a data structure in C++11 (or earlier) that can represent data like this?
I thought of a couple of ways of cheating such a structure, but none of them is perfect.
1. Separate std::vector
std::vector<std::string> name;
std::vector<unsigned int> age;

// Write
name.push_back("John");
age.push_back(25);

// Read
std::cout << "The first entry is (" << name[0] << " | " << age[0] << ")\n";

Defining a table with many columns takes a lot of markup, though, and writing to it by calling push_back on each std::vector is really tedeous.
2. std::vector of std::tuple
(std::pair would be enough in this case)
std::vector<std::tuple<std::string, unsigned int>> table;

// Write
table.push_back(std::make_tuple("John", 25));

// Read 1
std::string name;
unsigned int age;
std::tie(name, age) = table[0];
std::cout << "The first entry is (" << name << " | " << age << ")\n";

// Read 2
enum
{
    NAME = 0,
    AGE
}
std::cout << "The first entry is (" << std::get<NAME>(table[0]) << " | "
<< std::get<AGE>(table[0]) << ")\n";

(Sorry, if I messed something up here; I've known about the existence of std::tuple since yesterday)
This is fine, but reading from it takes a lot of markup, this time, when you have to define new variables that you want to put the values in. You could just do the std::tie to whatever variable you need the values at, but that becomes unreadable. The second method is almost perfect, but using implicit enums is not something I want to do in C++11.
3.  std::vector of std::array
enum
{
    NAME = 0,
    AGE
}

std::vector<std::array<std::string, 2> table;

// Write
table.push_back({"John", "25"});

// Read
std::cout << "The first entry is (" << table[0][NAME] << " | " << table[0][AGE] << ")\n";

This is also pretty good, but it suffers the same problem as 2.2 did. Also this only allows std::string values. In exchange it offers shorter and nicer syntax, though.

A: I suggest a std::vector<Record> to hold your records.
Use std::map<key, vector_index> as an index into your records.  This will enable you to access records by different search criteria without sorting the vector all the time.

A: One thing you have't considered is using a std::vector of some kind of associative array, be that a std::map or std::unordered_map.
This would allow you to inspect a given item in the vector (or other sequential container) using the database column names
item["Name"]
item["Age"]

and so on. You would have to use a variant or something like boost::any for the value, obviously.
If you wish to talk to a database in C++, and know at compile time the type the columns have (as you appear to from your suggestions) it might be worth considering ways to generate code with appropriate structures for you directly from the data base scehema. There are a couple of questions around this topic already here and here. What if the db value is null?

A: Since this question is still seeing activity after 5 years, I will answer it myself with the 5 years of programming experience since then.
There is no point in using std::array or std::tuple to represent a row. A struct is more expressive and has less boilerplate.
The question basically asks the difference between AOS (array of structs), SOA (struct of arrays) and hash maps. The choice between the two depends on what you want to do with the data and how much data there is.
Data is loaded cache lines of 64 bytes with automatic cache preloading when iterating over the data. Since the hash map is non-contiguous and thus cannot take advantage of the caching mechanism, it should only be preferred when individual entries are accessed based on their keys rather than iterating over the entire data set.
The choice between AOS and SOA depends on whether the columns are iterated over individually or together. When iterating separately, by using SOA we can fit more of the same data on the cache line by not looking at the other arrays. For both AOS and SOA, the preferable data structure is std::vector which is a simple contiguous data structure and thus the processor has a lot of information for on-the-fly optimizations.

A: #-------------------------------------------
#Try with this piece of code based on <map>
#-------------------------------------------
#include <iostream>
#include <map>
using namespace std;
//---
class myBook
{
public:
    string ISBN;
    string Title;
    int Pages;

    myBook();
    myBook(const myBook &);
    ~myBook(){};
    myBook &operator=(const myBook &pTr);
    int operator==(const myBook &pTr) const;
    int operator<(const myBook &pTr) const;
};

myBook::myBook()
{
    ISBN = "";
    Title = "";
    Pages = 0;
}

myBook::myBook(const myBook &copyin)
{
    ISBN = copyin.ISBN;
    Title = copyin.Title;
    Pages = copyin.Pages;
}

ostream &operator<<(ostream &output, const myBook &myBook)
{
    output << myBook.ISBN << ':' << myBook.Title << ':' << myBook.Pages << std::endl;
    return(output);
}

myBook& myBook::operator=(const myBook &pTr)
{
    this->ISBN = pTr.ISBN;
    this->Title = pTr.Title;
    this->Pages = pTr.Pages;
    return(*this);
}

int myBook::operator==(const myBook &pTr) const
{
    if( this->ISBN != pTr.ISBN) return(0);
    if( this->Title != pTr.Title) return(0);
    if( this->Pages != pTr.Pages) return(0);
    return(1);
   }

//---------------------------
main()
{
    map<string, myBook> BooksLibrary;
    myBook book1;
    //---
    book1.ISBN="1243954-23";
    book1.Title="Autobiography by Ben Franklin";
    book1.Pages=432;
    BooksLibrary["0001"] = book1;
    //---
    book1.ISBN="555-USA991";
    book1.Title="I Robot by Isac Asimov";
    book1.Pages=323;
    BooksLibrary["0002"] = book1;
    //---
    for( map<string, myBook>::iterator ii=BooksLibrary.begin();     ii!=BooksLibrary.end(); ii++)
    {
        std::cout << (*ii).first << "|" << (*ii).second << endl;
    }
    //---
    return(0);
}


text:
Q: Mobile navigation menu move all page? anyone can help me create a menu that works like this on this page:https://www.cabinet-maker.co.uk/  for mobile.
I mean menu buttons and search, I really like it but I do not know how to create one, I'm new and I wanted to create one in my own blog.

A: You can use one of the jQuery plugins. For example https://mmenujs.com/ or https://corenav.com/index.html. Actually, there are a lot of menus, just google them and choose one of your favorite.

A: You don't need a plugin, you can use plain JavaScript. I made a quick fiddle of it here:
https://jsfiddle.net/rajoh4bp/8/
Hover Over The Retail Navigation Bar Option Once You Are There.

A: You can make some fancy css3 menus by starting from nothing. You can add javascript or not.
Even w3school have a cool little tutorial about mobile menus :)
The most important thing to learn in webdesign is the vocabulary, so you can make efficient searches queries and find immediately what your are searching for.
For this request, the important words are "menu" and "slide". And you find another w3school tutorial :)


text:
Q: C++ counter not working The file I read had the string "hello" that was all.
There were no errors and the program said "You have 135197296 E's" which is obviously wrong. I'm stumped here. I'm new to C++ and it looked this would be a fun and easy program to do... I was wrong.
I don't know if it matters but the completed program should be able to open a file the user provides, read the file, and put the frequencies of letters onto a separate file. Obviously, I haven't gotten there yet and I'm only asking for help on this bit :)
 int main() {
    string filenamein, filenameout;
    char character;
    ifstream fileC;
    int tletter, eletter;

    cout << "which file do you want to open?";
    cin >> filenamein;

    fileC.open(filenamein.c_str());
    if (fileC)
    {
        while (fileC)
        {
            fileC.get(character);
            char e, E;
            if (character == 'e'|| character == 'E')
            {
                eletter++;
            }
        }
    }

    cout<< "You have " << eletter <<" E's";
    fileC.close();

    return 0;
}

A: In C++, primitive variables such as int are not initialized unless you explicitly initialize them.  This would generally be inefficient because sometimes you don't know the first value you want a variable to assume when you declare it, and so initializing it to, e.g., 0 would be a redundant write operation.
Thus, if you want your eletter to start at 0, you have to do something like this.
int eletter = 0;

That way you're counting from 0.  If you don't initialize it, its initial value will be whatever 4 B of garbage data happen to be in that location of your computer's RAM when you allocate the memory, which in this case was around 135 million.


text:
Q: Get button value to javascript array and save to database I have 3 buttons with 3 different value. When i click buttons then all values insert to javascript array.How do I do like that?
<input type="button" id="marksel" class="slmodel" onclick="getvalm();" value="John" />
<input type="button" id="marksel" class="slmodel" onclick="getvalm();" value="Alex" />
<input type="button" id="marksel" class="slmodel" onclick="getvalm();"  value="Martin" />

and javascript function is
function getvalm() {
                var a = [];
                $( ".slmodel" ).click(function (){
                    a.push($( this ).val());
                });
                alert(a);
            }

When i use alert to show array result then nothing to show. And how do I insert this 3 data to mysql database using javascript array?

A: There are multiple ways to achieve solution to your problem like :

*

*while $(this).addClass("smodel"); you can push value of the select span to an array so that you can have multiple selected values in one array which can be saved.

*While fetching data values to save in database fire a javascript function collecting values of all the span having class 'smodel'.


text:
Q: How to change font inside table I am using jquery tablesorter api to display table data now i want to change the text font inside table. Please let me know if anybody has any idea how to achieve it.
Thanks,
Sharad

A: Look in themes/blue/style.css or themes/green/style.css and change the font-family to the font you'd like.


text:
Q: Referencing Object Id not working in Mongoose 4.11.6 I have this problem. Basically, I have 2 schemas - a User schema and a Document schema. The Document schema has an owner which references the _id field of documents in the User collection.
The problem is that I am still able to save documents in the Document collection with owner ids that do not exist in the User collection which should not be so.
Here is my User schema and Document schema respectively
const UserSchema = new Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
 email: {
   type: String,
   validate: [{ validator: value => isEmail(value), msg: 'Invalid email.'
  }],
  unique: true,
  required: true,
},
password: {
  type: String,
  required: true,
},
isAdmin: {
  type: Boolean,
  default: false,
 },
}, {
timestamps: true,
});

const User = mongoose.model('User', UserSchema);

And the Document Schema
const DocumentSchema = new Schema({
   title: {
      type: String,
      required: true,
   },
   text: {
     type: String,
   },
  access: {
    type: String,
    enum: ['public', 'private'],
    default: 'public',
  },
 owner: {
   type: Schema.Types.ObjectId,
   ref: 'User',
   required: true,
  },
 }, {
 timestamps: true,
});

const Document = mongoose.model('Document', DocumentSchema);

Any help will be appreciated thanks.

A: For that situation you can add pre save function in your Document schema that will call before save your Document.
const DocumentSchema = new Schema({
  // ...
 }, {
 timestamps: true,
});

DocumentSchema .pre("save",function(next) {
  var self = this;
  if (self.owner) {
    mongoose.models['User'].findOne({_id : self.owner }, function(err, existUser){
      if(err){
        return next(false, err);
      }

      if(!existUser)
        return next(false, "Invalid user reference");
      else
        return next(true);
    });
  } else {
    next(false, "Owner is required");
  }
});

const Document = mongoose.model('Document', DocumentSchema);


text:
Q: Data source controls and parameter type conversion
Q1 - In the code example below runtime converts a value between two
incompatible types:
  <SelectParameters>
 <asp:Parameter Name="City" Type="Int32" />
 </SelectParameters>

protected void SqlDataSource2_Selecting(object sender,
       SqlDataSourceSelectingEventArgs e)
{e.Command.Parameters["@City"].Value = "100";}

Exception I got:
"Conversion failed when converting the nvarchar value 'Seattle' to
data type int."

A) The above exception suggests that runtime did manage to convert a
value of type String into a value of type Int32, and thus the
exception happened on SqlServer?!

B) Since String and Int32 are incompatible types, why did runtime
perform conversion from String to Int32 in the first place?
Doesn't the fact that we're dealing with incompatible type make
runtime "realize" that app most likely has a bug, similary to the way
compiler "realizes" that it's dealing ( in the code below ) with two
incompatible types:
String s = "something";
int i = (int)s; //error

Q2:
A)
public void GetEmployee( int EmployeeID );
<asp:ObjectDataSource  SelectMethod="GetEmployee" …>
  <SelectParameters>
    <asp:ControlParameter Name = "EmployeeID" ...>
  </SelectParameters>

If  for whatever reason EmployeeID parameter is NULL, ObjectDataSource
will convert Null to zero and passed it as argument to GetEmployee()
method.
Why does runtime make such a conversion? Wouldn't throwing an
exception made more sense?

B) "Use the ConvertEmptyStringToNull property to specify whether an
empty string value is automatically converted to null when the data
field is updated in the data source."

I don't quite understand the usefulness of this property. Why would
empty string indicate that we want null to be inserted into source's
data field? I'd assume that this data field is of type String? Then
why not also have ConvertZeroInt32ToNull etc?

Q3:
<asp:SqlDataSource ID="sourceEmployees" runat="server"
     ProviderName="System.Data.SqlClient"
     ConnectionString="<%$ ConnectionStrings:Northwind %>"
     SelectCommand="SELECT EmployeeID, FirstName,LastName,
     Title, City FROM Employees WHERE City=@City">
         <SelectParameters>
             <asp:Parameter Name="City"/>
         </SelectParameters>
</asp:SqlDataSource>

A)  I assume that when you don't specify of which type  Parameter
instance "City" is, it is automatically of type Object, which means it
can later be assigned value of any type. Thus if "City" is later ( say
inside SqlDataSource2_Selecting() event handler  ) assigned a value of
a wrong type, this wrong assignment will only be detected on Sql
server, and not before ( of course Sql server will report that error
back to web server )?

B) If we create a SqlParameter instance of type NVarChar(20) and want
to pass this parameter to a stored procedure, will Ado.net  pass to a
stored procedure just the value of this parameter, or will it also
somehow inform the procedure the exact type of this parameter ( which
is NVarChar(20))?

thanx

A: This is a SQL Server error. You've hit a datatype precedence issue.
The clue is here:
SELECT EmployeeID, FirstName,LastName, Title, City FROM Employees WHERE
City=@City --here exactly

The City column is nvarchar
The parameter is explicitly set to int
Adding it all together, you get:
SELECT EmployeeID, FirstName,LastName, Title, City FROM Employees WHERE
City=100

By the rules of datatype precedemce, the database engine tries to change all the values for City to "int". And fails, of course.
For your points though:

*

*Q1: Same issue. Nowhere have you told SQL Server that the "100" should be string

*Q2: Empty string casts to zero in SQL. Send dbnull.value if you want a SQL null

*Q3a. SQL has no object data type. It looks at 100 and decides "int"

*Q3b. Yes, use a stored proc and define it correctly.

Overall, SQL Server is behaving exactly as advertised. In this case, you simply are not giving enough information.
Edit: Stored proc usage
You tell SQL what the data type is when you add the parameter to the parameters collection. You define (and create) the stored proc to have the nvarchar parameter.

A: I'll just try to answer your first question --
"Conversion failed when converting the nvarchar value 'Seattle' to data type int."
Since I don't see "Seattle" mentioned anywhere, I'd guess that this error is actually coming from the stored procedure you're calling -- ie. whatever you're using @City for in the proc is the problem.  It sounds like instead of doing something like "where CityID=@City", you're doing a "where CityName=@City", and it's complaining that it can't convert one of the values of CityName ("Seattle") to an integer to compare it with @City.

A:
I'd guess that this error is actually coming from the stored procedure you're calling -- ie. whatever you're using @City for in the proc is the problem. It sounds like instead of doing something like "where CityID=@City", you're doing a "where CityName=@City", and it's complaining that it can't convert one of the values of CityName ("Seattle") to an integer to compare it with @City.

I used incompatible types on purpose just to get my point across --> which is 'why does runtime even bother to try to convert a value from one incompatible type to another, since the fact that user assigned string to variable of type integer, suggests that it is  most likely a bug and not something user did knowingly'?


text:
Q: Multiple components mutating a property subsequently (within a context) results in only one effective mutation Let's say I have a context provider CounterProvider like so:
const CounterProvider = ({ children }) => {
    const [data, setData] = useState({ count: 0 });

    const setCount = count => {
        typeof count === 'function' && (count = count(data.count));
        setData({ ...data, count });
    };

    return (
        <CounterContext.Provider value={{...data, setCount}}>
            {children}
        </CounterContext.Provider>
    );
};

And a consumer XComp:
const XComp = () => {
    const {count, setCount} = useContext(CounterContext);
    useEffect(() => setCount(count_prev => ++count_prev));
    return
XComp
;
};

Now, if I use XComp 3 times (ex: *sample-xcomp-usage), CounterProvider state will be {count: 1}. So, it looks like only the first call of setData() in CounterProvider becomes effective.
Now the question(s):

*

*Why does only the first call to setData() seem to be effective?

*How can I make every call to setData() effective?

*sample-xcomp-usage:
<InstanceCounterProvider>
    <XComp />
    <XComp />
    <XComp />
</InstanceCounterProvider>

.............
Note:
While making this edit, I just realized the "why" and "how".
Answer to question 1:
Component's state changes via setData() are not necessarily applied immediately, rather stored for later update. So subsequent callee setData() does not normally see the changes. Causing the override of stored data. That is why only the first setData() seems to be effective.
Answer to question 2:
React provides an overload of setState() that takes a callback as the argument to produce the changed state. The callback is provided with stored data. So, it is necessary modify the setCount() inside CountProvider like so:
    const setCount = count => {
        setData(data_prev => {
            typeof count === 'function' && (count = count(data_prev.count));
            return { ...data_prev, count };
        };
    };


text:
Q: puppet resource declaration error I have the following error when I run puppet on the a machine which has been assigned this class.
Error: Could not retrieve catalog from remote server: Error 400 on SERVER:
Evaluation Error: Error while evaluating a Resource Statement, Duplicate declaration: Class[<<dir_for_node_type>>::<brand_dir>::Awscli] is already declared;
cannot redeclare at /etc/puppet/environments/prod/modules/<dire_for_node_type>/manifests/<brand_dir>/awscli.pp:3 at /etc/puppet/environments/prod/modules/<dir_for_node_type>/manifests/<brand_dir>/awscli.pp:3:2 on node <node_name>
Warning: Not using cache on failed catalog
Error: Could not retrieve catalog; skipping run

I have the following in the parameter file which sits in a seperate repository:
cat /<rep_name>/modules/<dir_for_node_type>/manifests/<brand_dir>/awscli.pp
class <dir_for_node_type>::<brand_dir>::awscli
{
        class { 'awscli':
        }  ->
        awscli::profile { 'default':
          aws_access_key_id     => '<key_id>',
          aws_secret_access_key => '<sec_key_id>'
        }
}

I have tried to replicate this error on my local and I simply put in the class twice in the site.pp, I got a very similar error, however the output was slightly different as it gave exactly where the two declarations are, where as the error above doesn't give the first declaration, here is the error i get on my local:
Error: Could not retrieve catalog from remote server: Error 400 on SERVER:
Duplicate declaration: Class[Awscli] is already declared in file /etc/puppet/manifests/site.pp:8;
cannot redeclare at /etc/puppet/manifests/site.pp:24 on node <node_name>
Warning: Not using cache on failed catalog
Error: Could not retrieve catalog; skipping run


text:
Q: Excel VBA: Why does the ColorIndex of a blank cell appear to be -4142 I have always learned that the colorIndex property of a cell is a value up to 56, where white normally is 2.
This was the case in my file when I checked last time.
When I check the colorIndex of my empty, white, cells. It turns out to be -4142. Anyone knows what is happening here?
I'm checking the colorIndex with this code:
Function ColorIndex(CellColorIndex As Range)

ColorIndex = CellColorIndex.Interior.ColorIndex

End Function

A: From the Interior.ColorIndex docs:

The color is specified as an index value into the current color palette, or as one of the following XlColorIndex constants: xlColorIndexAutomatic or xlColorIndexNone.

-4142 corresponds to xlColorIndexNone as noted in the xlColorIndex docs.


text:
Q: Problem with database design for Hotel Booking I am currently designing (as an assignment for the course at the university) a database for online booking of hotels worldwide and I have stumbled into a problem.
Before describing it, here are the tables of the relational model so far :
GUEST
guest_ID varchar PK
email varchar
guest_password varchar
first_name varchar
last_name varchar
mobile_num varchar
member_status varchar
pref_language varchar
pref_currency_code varchar
HOTEL
hotel_ID varchar PK
hotel_name varchar
ratings_avg int
phone_num varchar
email varchar
currency_code varchar
street_name varchar
street_num varchar
zip_code varchar
city varchar
country varchar
ROOM
room_ID varchar PK
hotel_ID varchar FK to Hotel
room_name varchar
low_season_rate numeric
high_season_rate numeric
max_persons int
BOOKING
guest_ID varchar FK to Guest
room_ID varchar FK to Room
check_in date
check_out date
(a combination of the first 4 as PK)
persons_num int
PAYMENT
guest_ID varchar FK to Guest
room_ID varchar FK to Room
date_paid timestamp
amount numeric
EVALUATION
guest_ID varchar FK to Guest
hotel_ID varchar FK to Hotel
eval_date date
(a combination of the first 3 as PK)
rating int
guest_comment text
I came up with this design thinking as follows:
The guests will book rooms, which belong to hotels, pay for the rooms and then, if they want, after their stay, evaluate the hotel.
So I considered Booking and Payment as relations between the Guest and the Room and the Evaluation as a relation between the Guest and the Hotel.
The problem this design seems to have is that the Payment and Evaluation are completely cut off from the Booking, so their tables can fill even without a preexisting booking having taken place.
 And the way I see it now, a Guest pays for a Stay(=Booking) in a Room and evaluates a Stay(=Booking) in a Hotel, so I am thinking that these tables should refer to the Booking table.
But Booking is a relation, could I form a relation between an entity and another relation? Or is there another solution that I am missing?
I would welcome any thought about the subject.

A: First, your Payment and Evaluation are not "cut off" from Booking.  You can make the relation across more than just one join.  Secondly, remember there is an application on top of the database that will enforce some logic, such as not making bookings without a guest and not making guests without a booking.
If for some reason your requirements dictate that you enforce everything strictly in the database with keys, constraints, and triggers you will need to work on your schema a bit.  I have a few suggestions on that below:
I like identity keys on my tables so that the database doesn't have to enforce combo key relations, I do this in the application layer (it gives me more freedom to make unexpected changes to schema and application later on).
You may want to take the rates out of the ROOM table.  If they are updated, they are no longer applicable to previous BOOKINGs for the same hotel and room.
Payment and Evaluation only need a direct relation to a BOOKING.  You can't have either without an actual stay.
imo a unique BOOKING is a HOTEL and ROOM for date range, so BOOKING should have a fk to HOTEL and ROOM.
How you handle GUEST relating to BOOKING is a little tricky.  GUESTs being able to have more than one BOOKING is expected (imo) so you could put a fk to GUEST on BOOKING so that a BOOKING is now unique to a HOTEL, ROOM, GUEST, and date range.
But, if a BOOKING can have more than 1 GUEST, you need to make a relational lookup.  Just GUESTid and BOOKINGid, so you can have a many::many and still relationally connect GUESTs to BOOKINGs
As long as you can make relational connections across all of your tables with joins, they do not need to all be directly related to all of the others.


text:
Q: checkbox in kivy RecycleView, clicking one impacts others I try to put a group of two checkboxes in each row in RecycleView. But if I click one checkbox, some other checkboxes is impacted.
As the following pictures:
click row 1
row 13 is impacted
So are the row 25, 37 ...
the following is the code
main.py:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class Root(BoxLayout):
    def __init__(self, **kwargs):
        super(Root, self).__init__(**kwargs)
        self.rv.data = [{'value': str(x)} for x in range(100)]

class MyApp(App):
    def build(self):
        return Root()

if __name__ == '__main__':
    MyApp().run()

my.kv:
<Row@BoxLayout>:
    canvas.before:
        Color:
            rgba: 0.5, 0.5, 0.5, 1
        Rectangle:
            size: self.size
            pos: self.pos
    value: ''

    orientation: 'horizontal'
    Label:
        text: root.value
        size_hint:0.45, 1
    CheckBox:
        group: root.value
        size_hint:0.05, 1
        state: 'down'
    CheckBox:
        group: root.value
        size_hint:0.05, 1
<Root>:
    rv: rv
    RecycleView:
        id: rv
        viewclass: 'Row'
        RecycleBoxLayout:
            default_size: None, dp(56)
            default_size_hint: 1, None
            size_hint_y: None
            height: self.minimum_height
            orientation: 'vertical'

It's really simple code, but I don't know why.
Could you please help?
kivy is 1.10.0
the root cause is that the viewclasses are recycled for reusing.
We can derive the viewclass from RecycleDataViewBehavior(have to read the code).
Implement refresh_view_attrs. Maybe add the state of checkboxes into data of recycleview. Can refer to the example of SelectableLabel in recycleview/init.py.


text:
Q: Find the expression of $j_+$ and $j_-$operators I have just started to do exercises about quantum mechanics and I have some difficulties.
I have a particle with spin $j=1$ and the Hamiltonian is $H=\gamma(j_xj_y+j_y j_x)$ (where $\gamma$ is a constant).
I have to find the matricial form of $H$, its einginvalues and eigenvectors.
If I choose the basis that allows $j^2$ and $j_z$ to be diagonal, I can use the operators $j_+=j_x+ij_y$ and $j_-=j_x-ij_y$
Then I can write $j_xj_y+j_y j_x=\frac{1}{2i}(j_+^2-j^2_ -)$
But I have tried to find the matricial expression of $j_+$ and $j_-$ but haven't succeeded.. Can you help me?

A: If you want to define your $J_\pm$ in terms of $J_x$ and $J_y$ then you'll need to know those matrices.
If you consider $J_x=\frac{\hbar}{\sqrt 2}\left(\begin{matrix} 0&1&0\\
1&0&1\\
0&1&0\end{matrix}\right),$ and $J_y=\frac{\hbar}{\sqrt 2}\left(\begin{matrix} 0&-i&0\\
i&0&-i\\
0&i&0\end{matrix}\right)$ then you are done.
Alternatively you can define the $J_\pm$ by their direct action on a state $|m\rangle$ via $J_\pm|m\rangle=\hbar\sqrt{1(1+1)-m(m\pm 1)}|m\pm 1\rangle.$
This leads directly to $J_+=\hbar\left(\begin{matrix} 0&\sqrt{ 2-(0)(1)}&0\\
0&0&\sqrt {2-(-1)(0)}\\
0&0&0\end{matrix}\right)$ and $J_-=\hbar\left(\begin{matrix} 0&0&0\\
\sqrt{ 2-(1)(0)}&0&0\\
0&\sqrt{ 2-0(-1)}&0\end{matrix}\right).$
Then from those we can get $J_x$ via $J_x=(J_++J_-)/2$ and we can get $J_x$ via $J_x=(iJ_--iJ_+)/2.$
Its up to you to figure out which is your definition (or which connects to your definitions) then get the appropriate other one, and then find the eigenvectors.


text:
Q: Question about strongly convexity and affinity For a function $f$, it is said to be strongly convex if for all $x,y$
\begin{equation}
 (\nabla f(x) - \nabla f(y) )^T (x-y) \ge m \|x-y\|_2^2
\end{equation}
for a constant $m \ge 0$
Is it called strongly affine if
\begin{equation}
 (\nabla f(x) - \nabla f(y) )^T (x-y) = m \|x-y\|_2^2 \text{    ?}
\end{equation}
In addition as we know if a function is strongly convex it satisfy
\begin{equation}
    f(y) \ge f(x) + \nabla f(x)^T (y-x) + \frac{m}{2} \|y-x\|_2^2
\end{equation}
For strongly affine function can I say
\begin{equation}
    f(y) = f(x) + \nabla f(x)^T (y-x) + \frac{m}{2} \|y-x\|_2^2 \text{    ?}
\end{equation}

A: I never heard about "strongly affine" functions. However (as suggested by @LittleO to show that a "strongly affine" function is not necessarily strongly convex and strongly concave) consider the function
$$f(x)= \frac{1}{2}\|x\|_2^2 \quad \Longrightarrow \quad \nabla f(x) = x.$$
Then
$$(\nabla f(x)-\nabla f(y))^T(x-y) = \|x-y\|_2^2,$$
but
$$\begin{array}{rcl}f(x) + \nabla f(x)^T(y-x) + \frac{1}{2}\|y-x\|_2^2 &=& \frac{1}{2}(\|x\|_2^2-\|x\|_2^2+x^Ty+\|x\|_2^2+\|y\|_2^2-2x^Ty)\\
&=& \frac{1}{2}(\|x\|^2+\|y\|^2-x^Ty) \\ &\neq & \frac{1}{2}\|y\|_2^2.\end{array}
$$


text:
Q: Pronunciation of 'dogged' What's the correct way to pronounce 'dogged' ("He was dogged"/"dogged pursuit")? Is the 'e' silent or a schwa? Is it the same for the past of 'to dog' and for the adjective?
(What I tried so far: I asked Google translate to pronoune "He was dogged" and the e was silent; I looked it up in Merriam Webster's and it says the e is a schwa, but only for the adjective... I trust Merriam Webster's more than Google, but I still can't rule out that maybe the adjective is different than the past tense of the verb...)


text:
Q: Recursive query question - break rows into columns? I have a table "Families", like so
FamilyID    PersonID    Relationship
-----------------------------------------------
F001        P001        Son
F001        P002        Daughter
F001        P003        Father
F001        P004        Mother
F002        P005        Daughter
F002        P006        Mother
F003        P007        Son
F003        P008        Mother

and I need output like
FamilyID    PersonID    Father  Mother
-------------------------------------------------
F001        P001        P003    P004
F001        P002        P003    P004
F001        P003
F001        P004
F002        P005                P006
F002        P006
F003        P007                P008
F003        P008

In which the PersonID of the Father and Mother for a given PersonID are listed (if applicable) in separate columns.  I know this must be a relatively trivial query to write (and therefore to find instructions for), but I can't seem to come up with the right search terms.  Searching "SQL recursive queries" has gotten me closest, but I can't quite translate those methods to what I'm trying to do here.
I'm trying to learn, so multiple methods are welcome, as is vocabulary I should read up on.  Thanks!

A: You can self join the table twice with outer joins to get what you want:
SELECT
    T1.FamilyID AS FamilyID,
    T1.PersonID AS PersonID,
    T2.PersonID AS Father,
    T3.PersonID AS Mother
FROM Families T1
LEFT JOIN Families T2
    ON T1.FamilyID = T2.FamilyID
   AND T1.Relationship IN ('Son', 'Daughter')
   AND T2.Relationship = 'Father'
LEFT JOIN Families T3
    ON T1.FamilyID = T3.FamilyID
   AND T1.Relationship IN ('Son', 'Daughter')
   AND T3.Relationship = 'Mother'

Result:
FamilyID  PersonID  Father  Mother
F001      P001      P003    P004
F001      P002      P003    P004
F001      P003      NULL    NULL
F001      P004      NULL    NULL
F002      P005      NULL    P006
F002      P006      NULL    NULL
F003      P007      NULL    P008
F003      P008      NULL    NULL

A: In SQL Server, the feature you use to solve recursive problems like these are Common Table Expressions.


text:
Q: responsive navigation menu : ( using html and Css ) Toggle menu not working I am working on a simple navigation menu on building a ecommerce site. I want the menu to be responsive when I re-size the window less than 800 px but the toggle menu is not working its not disappearing when I touch the menu icon, the options are already showing and not disappearing
#here is the link to my code
https://github.com/roshini004/ecommerce-site.git

A: Firstly, in Javascript, we tend not to start variables with capital letters like MenuItems; it might mess up some OOP things in JS and sometimes autocomplete might mix it up.
But in this case, you need to camel case css styles in javascript. (maxHeight, not maxheight)
var MenuItems = document.getElementById("MenuItems");

MenuItems.style.maxHeight = "0px";

function menutoggle() {
    console.log("clicked");
    if(MenuItems.style.maxHeight == "0px")
        {
        MenuItems.style.maxHeight = "200px";
    }
    else
    {
        MenuItems.style.maxHeight = "0px";
    }
}


text:
Q: Cannot use (type []byte) as type io.Reader I don't understand the error, this is my main.go that I execute in the machine "A":
package main

import (
    "fmt"
    "net"
    "os"
    "github.com/mistifyio/go-zfs"
)

func main() {
    // Listen for incoming connections.
    l, err := net.Listen("tcp", "192.168.99.5:9977")
    if err != nil ...
    // Close the listener when the application closes.
    defer l.Close()
    fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
    for {
        // Listen for an incoming connection.
        conn, err := l.Accept()
        if err != nil ...

        //Handle connections in a new goroutine.
        go handleRequest(conn)
    }
}

// Handles incoming requests.
func handleRequest(conn net.Conn) {
    // Make a buffer to hold incoming data.
    buff := make([]byte, 1024)
    // Read the incoming connection into the buffer.
    _, err := conn.Read(buff)
    if err != nil {
        fmt.Printf("Error reading: %s.\n", err.Error())
    }
    // ReceiveSnapshot
    ds, err := zfs.ReceiveSnapshot(buff, "tank/replication")
    if err != nil {
        fmt.Printf("Error receiving: %s.\n", err.Error())
    }
    fmt.Printf("%s... done!\n", ds)
    // Send a response back to person contacting us.
    conn.Write([]byte("Received!"))
    // Close the connection when you're done with it.
    conn.Close()
}

Now, I show you the function ReceiveSnapshot from github.com/mistifyio/go-zfs/zfs.go:
type command struct {
    Command string
    Stdin   io.Reader
    Stdout  io.Writer
}

func ReceiveSnapshot(input io.Reader, name string) (*Dataset, error) {
    c := command{Command: "zfs", Stdin: input}
    _, err := c.Run("receive", name)
    if err != nil {
        return nil, err
    }
    return GetDataset(name)
}

I have seen in golang pkg the doc of io.Reader:
type Reader interface {
        Read(p []byte) (n int, err error)
}

Why do I receive the error...

*

*cannot use buff (type []byte) as type io.Reader in argument to zfs.ReceiveSnapshot:
[]byte does not implement io.Reader (missing Read method)

...when I make go install ?

A: Short answer: Wrap your buffer in a Reader type by using bytes.NewReader
Alternatively, you could use bytes.NewBuffer with similar effect.
If the source is a string, you can use strings.NewReader.
The list of Readers goes on and on: https://golang.org/search?q=Read#Global

Explanation of the deeper question
The deeper question being: Why doesn't an array support the io.Reader interface directly?
io.Reader supports the concept of reading from a general data stream for which the total size is not necessarily known in advance.  In order to support this, Read is called repeatedly until all input data is exhausted.  In many languages, similar read functions must be called at least twice, where the final call returns a flag indicating end-of-file.
By returning two values (one of which is type error), Go makes it possible for reading of arrays to complete in one-shot, but only if the destination buffer is large enough to consume all available data -- which isn't always known in advance.
The io.Reader interface specifies the signature and behavior of the Read() function:
func (T) Read(b []byte) (n int, err error)

Read populates the given byte slice with data and returns the number of bytes populated and an error value. It returns an io.EOF error when the stream ends.

So due to the way the io.Reader interface works, a simple byte buffer is not capable of implementing it.  A wrapper structure is required in order to remember the state between subsequent calls to Read().
For the sake of interest, here's an example showing how that can be implemented...
type MyReader struct {
    src []byte
    pos int
}

func (r *MyReader) Read(dst []byte) (n int, err error) {
    n = copy(dst, r.src[r.pos:])
    r.pos += n
    if r.pos == len(r.src) {
        return n, io.EOF
    }
    return
}

func NewMyReader(b []byte) *MyReader { return &MyReader{b, 0} }

Notice, also, that the []byte parameter to Read() is the destination buffer, not the source.

A: I think you are missing a step in your logic when you think that []byte would be equivalent to Reader just because the Reader's Read method receives a []byte as a parameter.
Let me try to clarify:
Your ReceiveSnapshot function expects a Reader as a parameter:
ReceiveSnapshot( input io.Reader ...

In order for a type to fulfil the Reader interface, that type should itself implement this function:
Read(p []byte) (n int, err error)

Note that the type should implement that function in order to be a Reader.
[]byte does not implement a Read function. It is just a coincidence that the argument to Read happens to be a []byte.
In order for this to work, you need to send ReceiveSnapshot a proper Reader.
Luckily for you, having a []byte and wanting to Read for it is a common situation so the API provides an easy way to do this:
https://golang.org/pkg/bytes/#NewReader
You just need to send bytes.NewReader(buff) to your ReceiveSnapshot function instead of just buff.


text:
Q: What is the purpose of "sealed" in C# when "virtual" is optional? If a class doesn't have any virtual methods, I do not see any way inheriting a class would affect any code that doesn't explicitly refer to the instance as an instance of the subclass i.e.
Subclass obj = new Subclass()

rather than
BaseClass obj = new SubClass()

So therefore, why does sealed even exist?
If you're not declaring anything as virtual (which I see no point in doing in a sealed class) all it prevents is things like (for example) a ListViewItem that stores some extra information about what it represents for code that "knows" that information is there, which has no impact on code that wasn't written with that subclass in mind, unlike an overridden method.

A: (1) Sealed class
I may have a method that accepts an object of type BankAccount. I don't want you to be able to create EvilBankAccount : BankAccount and pass it into my method. EvilBankAccount could potentially break my system which makes assumptions about a BankAccount -- for example, that it can be serialized. Maybe I clone BankAccount to prevent external manipulation once it is submitted, and EvilBankAccount clones just fine, but starts a timer in its constructor that auto-increments the balance every 30 seconds.
(2) Sealed member
You can override a virtual method or property, but seal it so that it cannot be overridden further in the inheritance hierarchy. One use case here is when you need to access the member from your constructor.

A: Consider
class A
{
  public virtual void M1();
  public void M2();
}

class B : A
{
  public override sealed void M1();
}

sealed class C : A
{
   //other stuff
}

class D : A
{
   public new void M2(); //marking A as sealed would prevent this
}

See also:
Do sealed classes really offer performance Benefits?
(JITter can optimize certain calls when it knows there can be no subclass)

A: I personally don't benefit much from sealed classes, and agree, it can be frustrating when dealing with UI classes and want to just add some custom behavior through inheritance.
However, I found an answer here that offers a few ideas.
Why seal a class?


text:
Q: getting null in Object passing JSON to @POST using Apache CXF I am using Json to get object details in my POST method to save it in database. The id field is stored correctly but the rest are just taken as null. Can someone point out why.
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.ws.rs.GET;
import javax.ws.rs.*;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.ocpsoft.example.hibernate.model.SimpleObject;
import org.ocpsoft.example.hibernate.util.EntityManagerUtil;
import org.ocpsoft.example.hibernate.dao.SimpleObjectDao;
@Stateless
@Path("/pid")
public class Service {
    @GET
    @Path("{id}")
    public String get(@PathParam("id") long id){
        System.out.println("in GET request");
        SimpleObjectDao objDao=new SimpleObjectDao();
        objDao.startConnection();

        SimpleObject obj=objDao.find(id);
        objDao.closeConnection();
        Gson gson=new Gson();
        return gson.toJson(obj);
    }

@POST
@Path("/add")
@Consumes("application/json")
//@Produces({MediaType.APPLICATION_JSON})
public String postdata(SimpleObject obj)
{
    //SimpleObject obj = (SimpleObject) ob;
    //Gson gson=new Gson();
    //System.out.println(obj.toString());
    //System.out.println("object "+obj.toString());
    SimpleObjectDao objDao=new SimpleObjectDao();
    objDao.startConnection();
    objDao.save(obj);
    objDao.closeConnection();
    return "Success";
}
}

My object definition is
    package org.ocpsoft.example.hibernate.model;
import javax.persistence.*;
import java.io.Serializable;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Column;
import javax.persistence.Version;
import javax.xml.bind.annotation.XmlRootElement;

import java.lang.Override;

/**
 * @author Lincoln Baxter, III
 */
@Entity
@XmlRootElement(name="SimpleObject")
public class SimpleObject implements Serializable
{

   private static final long serialVersionUID = -2862671438138322400L;

   @Id
   //@GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "id", updatable = false, nullable = false)
   private Long id = null;

   //private int Pid;

   @Column(name= "Pname")
   private String Pname = null;

   @Column(name= "Pcost")
   private double Pcost = 0.0f;

   @Column(name= "Pcat")
   private String Pcat = null;

   public Long getId()
   {
      return this.id;
   }

   public String getPname() {
        return Pname;
    }

    public void setPname(String pname) {
        Pname = pname;
    }

    public double getPcost() {
    return Pcost;
    }

public void setPcost(double pcost) {
    Pcost = pcost;
}

public String getPcat() {
    return Pcat;
}

public void setPcat(String pcat) {
    Pcat = pcat;
}

   public void setId(final Long id)
   {
      this.id = id;
   }

   public String toString()
   {
      String result = "";
      if (id != null)
         result += id;
      return result;
   }

   @Override
   public boolean equals(Object that)
   {
      if (this == that)
      {
         return true;
      }
      if (that == null)
      {
         return false;
      }
      if (getClass() != that.getClass())
      {
         return false;
      }
      if (id != null)
      {
         return id.equals(((SimpleObject) that).id);
      }
      return super.equals(that);
   }

   @Override
   public int hashCode()
   {
      if (id != null)
      {
         return id.hashCode();
      }
      return super.hashCode();
   }
}

Apart from Id all the others are not transferred to the object. com where I am going wrong.
I am checking using chrome postman with json as
{ "SimpleObject" :{"id":1,"Pname":"watch","Pcost":200.12,"Pcat":"wearables"}}

A: Maybe your ID column is auto generate, I think values on POST method cannot cast to your object
Try this :
@POST
@Path("/add")
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_JSON)
public String postdata(MultivaluedMap<String, String> formParams)

we need build SimpleObject object from form params.
hope this help !


text:
Q: Read a file one line per tick I model archaeological settlement distributions and dynamics.
I want to annually update the number of houses at the settlement sites using a .csv file similar to this one:
    Settlement 1
    0
    1
    5
    ...

I have two questions on that:
1) I do not succeed with the procedure as proposed in the Netlogo manual. There it reads
    "to go
     if file-at-end? [ stop ]
      set data csv:from-row file-read-line
      tick
      end"

BUT csv:from-row results in an error message ("nothing named... is defined"). How do I do this?
2)
I have more than just one site. Is there a way to use only one .csv - file such as
    Settlement 1,Settlement 2,Settlement 3
    0,0,0
    1,0,0
    5,0,1
    ...

and make sure that Settlement 1 updates houses according to column 1, Settlement 2 according to column 2 etc?
Thank you for your help!
Til

A: extensions [csv]
globals [settlements-list]  ;;to keep them in order
breed [settlements settlement]
settlements-own [n-houses]

to setup
  file-close-all
  ca
  create-settlements 3  ;;3 settlements, to match your example
  set settlements-list [self] of settlements ;;or sort if you wish
  file-open "c:/temp/temp.csv"
  let _trash file-read-line  ;;discard headers
end

to go
  file-open "c:/temp/temp.csv"
  if file-at-end? [ stop ]  ;;or at least, stop reading data!
  let _data csv:from-row file-read-line  ;;get data as list
  foreach n-values length settlements-list [?] [
    ask (item ? settlements-list) [set n-houses item ? _data]
  ]
  ask settlements [
    show n-houses
  ]
end


text:
Q: Changing word order in a sentence 'With no man more than Pope are such personal considerations relevant and cogent.'
-History of English Literature, by Edward Albert
Why are is used prior to the subject 'such personal constructions relevant and cogent'. I know 'Fronting', where we move prepositional phrase at the start of the sentence to create emphasis. But can we do the same thing with verbs too?

A: Because that's how the construction works. When a phrase is moved to the start of the sentence for emphasis, the verb has to change its place as well.

Only in [this region] can you see such spectacular scenery.
Only in the country do I feel at peace.


text:
Q: Recoding dummy variable to ordered factor I need some help with coding factors for a logistic regression.
What I have are six dummy variables representing income brackets. I want to convert these into a single ordered factor for use in a logistic regression.
My data frame looks like:
    INC1 INC2 INC3 INC4 INC5 INC6
1      0    0    1    0    0    0
2     NA   NA   NA   NA   NA   NA
3      0    0    0    0    0    1
4      0    0    0    0    0    1
5      0    0    1    0    0    0
6      0    0    0    1    0    0
7      0    0    1    0    0    0
8      0    0    0    1    0    0

What I want it to look like:
    INC
1   INC3
2   NA
3   INC6
4   INC6
5   INC3
6   INC4
7   INC3
8   INC4

This must be a common (and simple) operation, but my searches have not turned up a concise answer for how to perform this re-coding. Any help is very much appreciated.

A: Here's a solution based on another answer that keeps the NA values and converts to an ordered factor.
> inc
  INC1 INC2 INC3 INC4 INC5 INC6
1    0    0    1    0    0    0
2   NA   NA   NA   NA   NA   NA
3    0    0    0    0    0    1
4    0    0    0    0    0    1
5    0    0    1    0    0    0
6    0    0    0    1    0    0
7    0    0    1    0    0    0
8    0    0    0    1    0    0
> inc$F = factor(apply(inc, 1, function(x) names(x)[x == 1]),levels=names(inc),ordered=TRUE)

> inc
  INC1 INC2 INC3 INC4 INC5 INC6    F
1    0    0    1    0    0    0 INC3
2   NA   NA   NA   NA   NA   NA <NA>
3    0    0    0    0    0    1 INC6
4    0    0    0    0    0    1 INC6
5    0    0    1    0    0    0 INC3
6    0    0    0    1    0    0 INC4
7    0    0    1    0    0    0 INC3
8    0    0    0    1    0    0 INC4
> inc$F
[1] INC3 <NA> INC6 INC6 INC3 INC4 INC3 INC4
Levels: INC1 < INC2 < INC3 < INC4 < INC5 < INC6

This will break if you have more than one 1 in a row.


text: Q: android.os.Message and JMM Correct me if I am wrong, but we don't do any synchronization, while changing values of Message and also Message's fields are not volatile. So, why do we still got actual values (not cached ones) in the thread, that handles message? Maybe it's obvious, but I am new to JMM.


text:
Q: xslt: set readonly to a textbox Is there a way to set readonly property to a textbox based on "if" condition?
Javascript:

        <input class="text" value="{//Doc/Value1/@name}"/>

Like for the input tag,we have to set that property.
How do we do it???

A: <input class="text" value="{//Doc/Value1/@name}"/>
  <xsl:if test="someCondition">
    <xsl:attribute name="readonly">readonly</xsl:attribute>
  </xsl:if>
</input>


text:
Q: Is a group $G$ a subgroup of itself? I'd like to know if $G$ (generic group) is a subgroup of $G$. I'm not sure about that because I didn't prove that $ab^{-1} \in G$ for $a,b \in G$. The associativity, identity element and inverse element don't seem imply to $G<G$ but the such statement seems to make a little bit of sense.
The point which lead me to want to know that is that doing this I think I'm able to proof that $G$ is closed under its operator.
Note that for $a=b$ it's true as $aa^{-1}=e \in G$

A:
The One-step Subgroup Test: A subset $S$ of a group $H$ is a subgroup of $H$ if and only if both

*

*$S$ is nonempty.

*for all $a,b\in S$, we have $ab^{-1}\in S$.

Consider a group $G$.
Since $G$ is a group, $e\in G$, so $G$ is nonempty.
Clearly $G\subseteq G$.
Let $g,h\in G$. Then, since $G$ is a group, $gh^{-1}\in G$.
Hence $G\le G$.

Alternatively, let $r,s,t\in G$.
Again, $G\subseteq G$.
Since $G$ is a group, the operation is associative, so indeed
$$r(st)=(rs)t.$$
Note that $G$ is closed by definition, so indeed $G$ is closed as a subset of $G$ under the operation.
We have $e\in G$ by definition of a group. Hence the identity is in $G$.
Since $r\in G$, we have $r^{-1}\in G$ by definition of a group.
Hence $G$ is a group that is a subset of $G$ under the operation of $G$. (This should, in fact, be immediate; formally, though, the statements above are necessary.)
Hence $G$ is a subgroup of $G$.

A: We want to prove that
If $G$ is a group then it is a subgroup of itself.
Proof- Let $G$ be a group with the binary operation $\circ$ (A group is a pair $(G,\circ)$), where $G$ is a non empty set and $\circ$ is a binary operation on $G$ which is associative, having identity and unique inverse for each element of $G$).
We say that a non empty subset $H$ of $G$ is a $\textbf{subgroup}$ of $G$ if $(H,\circ)$ is itself a group. From this definition it can be easily seen that $G$ is a subgroup of itself.
Now there is a result $H$ is subgroup of $(G,\circ)$ $\iff$ $\forall\ a,b\in H,\ a\circ b^{-1}\in H$.
For this let $a,b\in G$. Then $b^{-1}\in G$. So we have $a,b^{-1}\in G$.  Now since $\circ$ is a binary operation on $G$ $\Rightarrow a\circ b^{-1}\in G.$ This proves the result.
If you still feel some problem, I suggest you to please read the definition of binary operation and its importance in the definition of group.

A: Just remember that if $(G,\star)$ is a group, then by definition, a subgroup of $(G,\star)$ is any couple $(H,\star)$ such that $H\subset G$ (in particular $G\subset G$) and $(H,\star)$ is a group.


text:
Q: What is the difference between React functional component  and js function formatMessage() and which one is better to use? I have following code
Message Component:
import React from 'react';

const localizedMessages = {
   'title': 'This is my Title'
}

const Message = ({ id, ...params }) => {
  const msg = localizedMessages[id] || id;
  return <React.Fragment>{msg}</React.Fragment>;
};

export default Message;

And a util method formatMessage(plain javascript function):
const localizedMessages = {
   'title': 'This is my Title'
}

export function formatMessage(id, params) {
  return localizedMessages[id] || id;
}

And actual component where I want to use
import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle } from '@material-ui/core';
import React from 'react';
import Message from './Message';
import formatMessage from './utils';

const MyComponent = () => {

  return <Dialog
    open={true}
    keepMounted
    maxWidth="sm"
  >
    <DialogTitle id="alert-dialog-slide-title">
      <Message id="title" />
      {formatMessage('title')}
    </DialogTitle>
    <DialogContent>
      <DialogContentText id="alert-dialog-slide-description">
        {content}
      </DialogContentText>
    </DialogContent>
    <DialogActions>
      <Button onClick={onClose} color="primary">
        <Message id="cancel" />
        {formatMessage('cancel')}
      </Button>
      <PrimaryButton onClick={onConfirmClick}>
        <Message id="yes" />
        {formatMessage('yes')}
      </PrimaryButton>
    </DialogActions>
  </Dialog>;
};

export default MyComponent;

either I can use < Message /> or formatMessage, both will do the work for me. I am more leaned towards < Message />.
Note: Removed code related to params from < Message /> and formatMessage() to avoid deviation from actual question. Params are used for interpolation.

A: Your component doesn't include any additional functionality to the function's: they both just return plain text value by its key.
When that's the case, I don't see any reason to complicate the code and use a component.
Using a component not only suggests that you're having some sort of graphical-rendering or data-fetching taking place (which aren't in this case), but also makes your code more verbose and lengthy, which is usually a thing we try to avoid.
In your example you only use one argument, but this is much more distinct when you have more arguments:
<Message
  arg1={1}
  arg2={2}
  arg3={3}
/>

or
formatMessage(1, 2, 3)


text:
Q: How to use a let's encrypt ssl key in my spring boot application on kubernetes I have a spring boot application running on kubernetes, a client application serving a react app and proxying request to other services.
That client app is avalaible through an Ingress using a Nginx controller.
I have a domain name targetting the Nginx controler service and I've been able to generate a valid certificate and key with cert-manager from let's encrypt, also the certificate and key is automaticly updated when it's necessary.
Till now I used self signed certificates generated with keytool to secure the communication between my differents applications (I guess I can still use that tools for internal communications), but for the client app I need to use the let's encrypt generated key.
Now my client app does not use ssl (ssl.enable is false in my bootstrap.yml). So the communication between the Ngix Ingress controller and the client app is not secure I think.
A k8s secret has been created with a certificate and a key during the process so I guess I can use it but what is the best way ? I would also like to provit the automatic update of the certificate if it's possible.
Thanks for your advices

A: There are clients out there which re-use the private key used previously (certbot when used with the --reuse-key option and also acme.sh). Unless someone knows a client with such a feature, you should check the clients from the list and see if the client makes importing an existing private key possible. Or at least not very difficult.
Certbot would need an issued certificate first to re-use the key. What could be a working option is:

*

*install certbot (see https://certbot.eff.org/ 29)

*get a certificate issued with certbot without caring about the keys,
just get it working.

*use --staging for test certificates first manually exchange the PEM
formatted private key in
/etc/letsencrypt/archive/name-of-your-certificate/privkey1.pem with
your own PEM formatted private key renew the certificate with certbot
renew --reuse-key

*check if the public key in the renewed certificate corresponds with
your own public/private key If the above checks out (with the
--staging option for testing), you can remove the test certificate and do the above again, but without --staging to get a real working
certificate.

Useful documentations cert-manager, certbot.


text:
Q: Highcharts: how to maintain the same order of category labels when bar chart changes to column chart I have a column chart, which has category labels Yes, No, Don't Care in xAxis. I also have two buttons which, when clicked, changes to a bar chart or vice versa. See the picture:
However, when changed to bar chart, the labels on yAxis are, from top to bottom,  Don't Care, No, Yes. This new order is odd to users. I hope to still keep Yes, No, Don't Care (top to bottom) on the yAxis in the bar chart.
When a button is clicked, I have the following code for changing to bar chart:
    var chart = code for find the chart object
    chart.inverted = true;
    chart.xAxis[0].update({}, false);
    chart.yAxis[0].update({}, false);
    chart.series[0].update({
        type: 'bar'
    });

The following code is for changing to column chart:
    var chart = code for find the chart object
    chart.inverted = false;
    chart.xAxis[0].update({}, true);
    chart.yAxis[0].update({}, true);
    chart.series[0].update({
        type: 'column'
    });

How can I get the Yes, No. Don't care (top to bottom) order in the bar chart?
Thanks!

A: See the fiddle here
$("#bar").click( function  (){
 var chart =  $('#container').highcharts();
 // Added code to share the fiddle
 });


text:
Q: Replace speaker to retrieve audio signal (and isolate galvanically) I'd like to capture sound from a speaker output.
The system seems to be running with a small DC current (bias, so voltage across speaker is about 3 V), so the audio AC signal could be (de)coupled from a load resistor via a small capacitor.
The 10 kOhms resistor drops the 6.5 VDC (open circuit) to 5 VDC. The audio signal is in the order of 10 mVpp.
I would then need to amplify this signal and achieve some sort of galvanic isolation. Probably an opamp and a low frequency audio transformer (<1Vpp according to https://en.wikipedia.org/wiki/Line_level).
However, this requires a power supply for the opamp which would be tricky to derive from the system, so I'd need an isolated dc-dc converter.

simulate this circuit – Schematic created using CircuitLab
Audio quality is not a priority - a simple circuit is (one-off build).
If the "primary" circuit could be eliminated using a high impedance transformer directly, it would be even better. The secondary signal then could be brought to line level with a transimpedance amp.
Maybe a mains voltage relay coil with >10 kOhms could be used creatively (but: core? secondary?)? Is a high sensitivity hall-effect sensor a feasability?
Any ideas appreciated!

A: Well, if "Audio quality is not a priority", why don't you keep the speaker and use a microphone for the recording? Choose a quiet room, night time and give it a try. Some post-recording noise removal in a software like Audacity would be a good thing.
It also checks all your requirements:

*

*Simple

*Galvanic isolation

*No additional power supply


text:
Q: Is it safe to change TCreateParams.WinClassName or how to find a form handle of another own application? I have two applications, where the first one needs to find a handle of the form from the second (also my own) but different application (not instance, but different application). I've seen some techniques, but I would like to know if it's safe what I would like to do or what is efficient way to do this.
I was thinking about to use the FindWindow function where you can pass the class name, so if I would change the WinClassName member in CreateParams of the form to some unique value (e.g. GUID), then I would be pretty easily able to find this Window with a big chance it is the one from my application.
Application whose form needs to be found:
procedure TForm1.CreateParams(var Params: TCreateParams);
begin
  inherited;
  Params.WinClassName := '{1EE65C52-2F4B-4600-AAE2-079C29AD2220}';
end;

The other application which needs to find the form from the previous one:
procedure TForm1.Button1Click(Sender: TObject);
var
  FormHandle: HWND;
begin
  FormHandle := FindWindow('{1EE65C52-2F4B-4600-AAE2-079C29AD2220}', nil);
  ShowMessage(IntToStr(FormHandle));
end;

My question is:
Is it safe to change this member of the TCreateParams to whatever I want or is it unsafe in something ? Or how would you look for a handle of the form from your own another application (not application instance, but your own another application) ?
Thanks a lot!

A: Yes it is perfectly safe to do this. Naturally each different class must have a unique name, but it's up to you to ensure that is the case.

A: Rather than using the same TForm1 class name in both apps, you should get in the habit of changing the default class names to more meaningful names, like TApp1MainForm and TApp2MainForm.  The VCL automatically assigns a form's ClassName as its TCreateParams.WinClassName by default, in TWinControl.CreateParams().  If you change the form's Name property in the Object Inspector at design-time, it updates the ClassName for you, then you do not have to change the TCreateParams.WinClassName value manually.


text:
Q: Xamarin Forms (Android, IOS, UWP) - Get an unique device Id/Number As I read, access to a serial number of device is no longer enabled for newer versions of Android and IOS devices. Because of that, I need to find a same unique alternative.
When I was looking for it, the only thing I found is UUID for an android. The problem is that i don't have and idea and I can't find anything about how to access that info using a c#.
What I want to achieve is just to read an unique Id for android, IOS and UWP devices that can't be changed (like a serial number).
https://developer.android.com/reference/java/util/UUID


text:
Q: MCMC Modelling - can this even be solved? I am very new to Bayesian modelling and MCMC - I would like to know if the problem I describe below can be solved.  It seems to be there is too much missing information but I wanted to get your thoughts.  Consider the following:
I have a road intersection with one entrance and two exits, A and B.  My goal is to estimate the number of cars that pass through this intersection in a given day, which equals to the number of cars that pass through the entrance.  I post two people, one at exit A and the other at exit B, to count the number of cars coming out of their exits.  They are both not very good so they only capture C percent of the cars that actually pass through their respective exits.  I do not know what C is.  To make matters worse, the person at exit B lost his record so I only have the numbers from A.  I think this situation should be described by the following graph:

From historical data, I know on average p% of ppl go through A and (1-p)% people go through B, but on this given day, I have no information.  In this example I only have two exits, but in general I may have more (e.g. 3-5).
Is is possible to estimate the distribution for "# cars thru entrance" with the data I have?  If so, what distributions would you assign to each random variable?

A: I'll record my modelling thoughts as I create it:
import pymc as pm

How can I recreate this data? Well, N_T cars enter. Do I know N_T? No, so it's a random variable. For simplicity, I'll say its a discrete uniform with max 1000 (you can change this to, say, a Poisson)
N_T = pm.DiscreteUniform('N_T', 0, 1000)

Of these N_T cars that enter, I know a car will enter A with probability p. Thus the number of cars through A is a binomial rv. But do I know p for certain? Probably not, you mentioned it was a historical average, so we should model this stochastically (using the beta-binomial model):
p_A = pm.Beta('p_A', 50, 50) #centered at 0.5, but with some variance. This depends on your historical data.
N_A = pm.Binomial('N_A', N_T, p_A)

Next, only C percent of cars are recorded by A's observer. Let's just assume that C is completely accurate, i.e. there is no uncertainty about what C is:
C=0.95

Then the number of cars recorded is again a binomial, with N_A trials. Furthermore, suppose observer A record 20 cars.
obs_A = pm.Binomial('obs', N_A, C, observed=True, value = 20)

Let's fire the mcmc canon:
mcmc = pm.MCMC( [obs_A, N_A, p_A, N_T] )
mcmc.sample(10000, 5000)

from pymc.Matplot import plot as mcplot
mcplot(mcmc)

And I get this posterior for N_T:


text:
Q: How do I save an edited mesh in MESHLab? I import a mesh(obj) into a project and edit it... when I save my project and reopen the project, my mesh is still the import mesh. Where is my mistake?
greetings
iom

A: Use the  menu. Chose: File / Export Mesh or  File / Export Mesh As. See the Meshlab tutorial http://www.heritagedoc.pt/doc/Meshlab_Tutorial_iitd.pdf

A project is nothing more than an information structure. It doesn't contain the point clouds itself.

A: Also if you export it as a .obj file, you need to include the .mtl and any texture files in the same folder. Otherwise you'll get an untextured/no color object


text:
Q: Javax.naming.* port to Android? Does anyone know of a LDAP package (or javax.naming.*) port to Android?  I'm looking to implement a full contact search based on input from the user.
I have it working with the Java version of the app, but as I port it over, Android doesn't support javax.naming.*. If there isn't a way to port that API, is there a way to include it?
Thanks!

A: The UnboundID LDAP SDK for Java works on Android as well as Java SE/EE.  It even includes the code for a simple Android app that can be used to perform searches in an LDAP directory.

A: I think you are mixing the things a bit. LDAP servers are not available on mobile. To search contact you should probably look at this.


text:
Q: Functions using data not given to them How are functions 2 and 3 getting this the integers and floats in there printf's? This is very interesting and would love to know why? Does it have to do with the heap or stack?
#include <stdio.h>
#include <stdlib.h>
void function1(void){
int A = 50;
int B = 42;
float X = 3.1459;
float Y = 2.71828;
   printf("Function 1\n");
   printf("%d+%d=%d\n", A, B, A+B);
   printf("%f+%f=%f\n", X, Y, X+Y);
}
void function2(void){
int v1, v2;
float cs, ua;
   printf("Function 2\n");
   printf("v1+v2=%d\n", v1+v2);
   printf("cs+ua=%f\n", cs+ua);
}
void function3(void){
float cs, ua;
int v1, v2;
   printf("Function 3\n");
   printf("v1+v2=%d\n", v1+v2);
   printf("cs+ua=%f\n", cs+ua);
}
Int main(void){
   function1();
   function2();
   function3();
   return 0;
}

Output:
Function 1
50+42=92
3.145900+2.718280=5.864180
Function 2
v1+v2=92
cs+ua=5.864180
Function 3
v1+v2=92
cs+ua=5.864180

A: This is an undefined behavior: the standards doesn't define what to do in this case when you dont' initialize a local variable.
This means it might depend on the compiler you are using.
What probably happens is that you get some stack space to store your variable, but since you don't set a value, it uses the value that was previously written in that space.
It could have been written by another program, or whatever that used this memory location before. It could be 0 because that memory location was never used, you don't know, the behavior is undefined (you can't define the behavior, you can't predict what the value will be).
Also they are on the stack, the heap is for dynamic memory like when you use malloc.


text:
Q: Elasticsearch Optimizing Query We are implementing search company list using elasticsearch but its not what we expected
**Example companies:**
Infosys technologies
Infosys technologies ltd
Infosys technologies pvt ltd
Infosys technologies Limited
Infosys technologies Private Limited
BAC Infosys ltd

Scenario:

*

*When search the keyword "Infosys" it should return "Infosys
    technologies" list.

*When search the keyword "Infosys ltd" it should return "Infosys
technologies" list.

*When search the keyword "BAC Infosys ltd" it should return "BAC
Infosys ltd" list.
The below settings and mapping used
{
   "settings": {
      "analysis": {
         "filter": {
            "nGram_filter": {
               "type": "nGram",
               "min_gram": 3,
               "max_gram": 3,
               "token_chars": [
                  "letter",
                  "digit",
                  "punctuation",
                  "symbol"
               ]
            }
         },
         "analyzer": {
            "nGram_analyzer": {
               "type": "custom",
               "tokenizer": "keyword",
               "filter": [
                  "lowercase",
                  "asciifolding",
                  "nGram_filter"
               ]
            },
            "keyword_analyzer": {
               "type": "custom",
               "tokenizer": "keyword",
               "filter": [
                  "lowercase",
                  "asciifolding"
               ]
            }
         }
      }
   },
   "mappings": {
       "companies": {
             "properties": {
                 "company_name": {
                     "type": "string",
                     "store": "true",
                     "index_analyzer": "nGram_analyzer",
                     "search_analyzer": "keyword_analyzer",
                     "null_value": "null"
                 }
             }
         }
   }
}

Query:
{"query":
    {
      "bool": {
        "must": [
          { "match": { "company_name": "Infosys technologies" }}
        ],
        "minimum_should_match": "80%"
      }
    }
}

Please help me how to achieve this.

A: you are missing a few things both in terms of the search queries and mappings.looking at your scenarios and using your current mappings settings
1) The result will also have BAC value. You should switch to edge n-grams.But this will not allow you to search from between.
2)It also depend what kind of search you are building, you can avoid the arrangement i suggested in 1. for your all scenarios lets assume your list can have BAC value also in the result for scenarios but ranked lower in the list. For this you can use proximity queries query with fuzzy on for spell checks.
Above three scenarios dont't explain me the whole functionality and uses -cases  for your search feature, but i think proximity search offered by elastic can give you more flexibility to meet your cases.

A: Shingles could help:
https://www.elastic.co/guide/en/elasticsearch/guide/current/shingles.html
For you case the ng_Gram analyzer is not pertinent, it should impact performance and relevance score. Create a shingle filter and a custom analyzer with standard tokenizer and lowercase filter.
HtH,


text:
Q: What is the deal with all the food in the Storage areas in Prison-Architect All my Storages are overfull with old food, they dont use it in the Kitchens and they dont dump it automaticly...

Do i make something wrong with my Kitchens or the Regime? This much food all over the Storage eras seems a bit wired...

The 2 Times brekfast for the normal guys are needet or i get to much traffic in the gangways. But the Problem with the overstorage was way befor that.
Do someone has a solution for this Problem? I dont want to delete every Item by hand every Day...

A: AFAIK it's a bug introduced now the shakedown searches all areas of your prison. It's caused because the guards are not careful as to where they put down items after searching them.
A similar thing happens in the workshops, stacks not put back on the benches, but in the kitchen cooked food is not able to be put back on the cookers, so it's taken to storage. The only way to get rid of it is to dump it (unfortunately each item, individually).
Although there is no way to stop it, I have found that avoiding doing shakedowns when food is being cooked minimising it happening.
It's been reported already in the bug tracker (login required): http://bugs.introversion.co.uk/view.php?id=5435


text:
Q: "apart from" vs "other than" vs "aside from" vs "except for" vs "besides" I have a question regarding the usage of "apart from", "other than", "aside from", "except for" and "besides"?
Suppose I have three books X, Y and Z. My friend knows I have Book X. So if he wants to know how many books I have along with X, Which of the above phrases are correct?

*

*Hey Subha, how many books do you have besides X?

*Hey Subha, how many books do you have other than X?

*Hey Subha, how many books do you have apart from X?

*Hey Subha, how many books do you have aside from X?

*Hey Subha, how many books do you have except for X?

I think all of the above are correct but except for. I am not sure. Am I right?
And one more question: Suppose a contractor who paints houses asks me "Hi, sir, do you want to paint your kitchen?" I answer, "No, at the moment; I don't think it needs to be painted." Now in these circumstances, which of the following phrases should the contractor use when asks the next question?

Contractor: Hi, sir, do you want to paint your kitchen?
Me: No, at the moment; I don't think it needs to be painted.
Contractor: Do you want to paint anything in your house other than/except for/apart from/besides your kitchen?

I think besides is not correct here. The rest of all the phrases are correct. I am not sure. Please explain.

A: Whereas besides denotes inclusion/adding to, except/except for has the meaning of exclusion and so does other than which means with the exception of.
As for apart from and   aside from, they may mean both inclusion and exclusion.
So all your sentences are valid, in my opinion.
(Also, see this video lesson)

A: I was going to comment Victor B.'s great answer but I don't have enough reputation, so I will leave an answer here.
Victor concludes that OP's sentences are all valid, and I agree. However, I feel like OP also wants to ask that if the sentences are (or are not) reasonable, given the scenario he described.
Based on knowledge from Victor's answer, I think OP's right with the painter-kitchen question.
As for the book question, I think not only except for, but also other than should be excluded from the correct answers, since they both have the meaning of exclusion, which is inappropriate in the book scenario.

A: This is a good question as all of these connectives involve separating out a certain element of a set.

*

*Hey Subha, how many books do you have besides X?

*Hey Subha, how many books do you have other than X?

*Hey Subha, how many books do you have apart from X?

*Hey Subha, how many books do you have aside from X?

*Hey Subha, how many books do you have except for X?

I think all of the above are correct but except for. I am not sure. Am I right?

I agree. I think except for can only be used when describing a property that applies to some elements of a set but not others. The Collins COBUILD definition is:

You use except for to introduce the only thing or person that prevents a statement from being completely true.

It implies a negation:

*

*I like all snacks except (for) pretzels. => I do not like pretzels.

*Everyone except (for) Sam attended. => Sam did not attend.

Whereas besides, other than, etc. are about limiting the set under discussion for purposes of the "how many?" question. Excluding would also work here.

Contractor: Hi, sir, do you want to paint your kitchen?
Me: No, at the moment; I don't think it needs to be painted.
Contractor: Do you want to paint anything in your house other than/except for/apart from/besides your kitchen?

In this scenario it would be more natural to say something like: "Are there any other rooms that need painting?" Or, if mentioning the kitchen: "If not the kitchen, do you want me to paint any of the other rooms?" (The kitchen is topical—it was just discussed—so it would be typical to re-mention it at the beginning of the sentence, before the new information asking about other rooms.)
"Is there anything...except for" sounds odd because except for usually accompanies an expression referring to a complete set of items; it would be appropriate if the discussion was about painting all the other rooms:

*

*Would you like me to paint all the rooms except for the kitchen?

"Besides your kitchen" could be interpreted as "in addition to your kitchen", which is not the intended meaning. But I could imagine somebody saying it in this scenario. Other than, apart from, aside from also sound OK.


text:
Q: Range of an argument of a function in VBA Is there a common method of getting range of a given argument of a function or at least getting an argument of a function as an Object, for example:
Function func(x1 As VarType_1, ..., xn As VarType_n)
    .......
End Function

Sub sub_1()
    '1)
    Dim x1_domain
    x1_domain = func.x1.VarTypeDomain
    'or at least:
    '2)
    Dim arg1 As Object
    Set arg1 = func.x1
End Sub


text:
Q: Comando remove não funcionando ionic Estou tendo problema com o navCtrl.push. O fluxo é o seguinte:

Nas paginas 1.1, 1.2 e 1.3 posso ir e voltar quantas vezes eu quiser porém quando clicar no botão voltar preciso necessariamente voltar na pagina 1.
Para ir para próxima pagina utilizo o evento click do botão assim:
(click)="quickAccess('Pagina1.1')"

E para voltar adiciono navPop ao meu botão do navbar.
O ERRO
Quando clico em voltar está voltando partes por pastes das paginas 1.2, 1.2 e 1.3 suponhamos se eu naveguei 10 vezes entre estas pastes ele irá voltar as 10 vezes.
TENTATIVAS
Estou tentando seguir o seguinte pensamento quando navego por exemplo da pagina 1.1 para 1.2 eu devo remover a 1.1 e assim por diante, porém estou tendo este problema, de como fazer isto, ja tentei fazer por index pelo nome da view mas nenhuma deles funciona.
VALE LEMBRAR
É importante saber que existem outras paginas anteriores a PAGINA 1 o fluxo com problema é apenas neste caso, nos restante tudo anda conforme o esperado.

A: Encontrei o problema !
Segundo esta inssue no ionic team:
https://github.com/ionic-team/ionic/issues/12238

Está ocorrendo um erro na estrutura, a solução foi a instalação da correção via npm como informado na inssue:
npm install ionic-angular@nightly --save

Assim meu .remove() funciona perfeitamente agora.


text:
Q: Minification error JQuery in MVC Bundle After publishing my web application to azure the Jquery Script bundle contains this header:
/* Minification failed. Returning unminified contents.
(1447,2-3): run-time warning JS1195: Expected expression: *
(1447,31-32): run-time warning JS1004: Expected ';': c
(1448,4-13): run-time warning JS1030: Conditional compilation is turned off: @requires
 */
/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery-2.0.3.min.map
*/

I have this Bundle registration:
public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js",
                    "~/Scripts/jquery.sitespecific.js",
                    "~/Scripts/sitespecific.js",
                    "~/Scripts/autonumeric.js",
                    "~/Scripts/jquery.coolfieldset.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                    "~/Scripts/jquery-ui-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*"));

        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                "~/Content/site.css"));

        bundles.Add(new StyleBundle("~/Content/themes/custom/css").Include(
                    "~/Content/themes/custom/jquery-ui-1.10.3.custom.css",
                    "~/Content/jquery.coolfieldset.css"));
    }

What am I doing wrong here?

A: It appeared to be the jquery plugin jquery.coolfieldset.js. After adding a linefeed at the end and beginning of this file the minification worked


text:
Q: flag for moderator attention when question might be community wiki? Is it ok to flag for moderator attention if I think, a question should be a community wiki?
For example this question.

A: Yes. Since the recent change, moderators are the only ones who can make a question community wiki.


text:
Q: Numpy unable to access columns I'm working on a ML project for which I'm using numpy arrays instead of pandas for faster computation.
When I intend to bootstrap, I wish to subset the columns from a numpy ndarray.
My numpy array looks like this:
np_arr =
[(187., 14.45 , 20.22, 94.49)
(284., 10.44 , 15.46, 66.62)
(415., 11.13 , 22.44, 71.49)]

And I want to index columns 1,3.
I have my columns stored in a list as ix = [1,3]
However, when I try to do np_arr[:,ix] I get an error saying too many indices for array .
I also realised that when I print np_arr.shape I only get (3,), whereas I probably want (3,4).
Could you please tell me how to fix my issue.
Thanks!
Edit:
I'm creating my numpy object from my pandas dataframe like this:
def _to_numpy(self, data):
        v = data.reset_index()
        np_res = np.rec.fromrecords(v, names=v.columns.tolist())
        return(np_res)

A: The reason here for your issue is that the np_arr which you have is a 1-D array. Share your code snippet as well so that it can be looked into as in what is the exact issue. But in general, while dealing with 2-D numpy arrays, we generally do this.
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

A: You have created a record array (also called a structured array).  The result is a 1d array with named columns (fields).
To illustrate:
In [426]: df = pd.DataFrame(np.arange(12).reshape(4,3), columns=['A','B','C'])
In [427]: df
Out[427]:
   A   B   C
0  0   1   2
1  3   4   5
2  6   7   8
3  9  10  11
In [428]: arr = df.to_records()
In [429]: arr
Out[429]:
rec.array([(0, 0,  1,  2), (1, 3,  4,  5), (2, 6,  7,  8), (3, 9, 10, 11)],
          dtype=[('index', '<i8'), ('A', '<i8'), ('B', '<i8'), ('C', '<i8')])
In [430]: arr['A']
Out[430]: array([0, 3, 6, 9])
In [431]: arr.shape
Out[431]: (4,)

I believe to_records has a parameter to eliminate the index field.
Or with your method:
In [432]:
In [432]: arr = np.rec.fromrecords(df, names=df.columns.tolist())
In [433]: arr
Out[433]:
rec.array([(0,  1,  2), (3,  4,  5), (6,  7,  8), (9, 10, 11)],
          dtype=[('A', '<i8'), ('B', '<i8'), ('C', '<i8')])
In [434]: arr['A']            # arr.A also works
Out[434]: array([0, 3, 6, 9])
In [435]: arr.shape
Out[435]: (4,)

And multifield access:
In [436]: arr[['A','C']]
Out[436]:
rec.array([(0,  2), (3,  5), (6,  8), (9, 11)],
          dtype={'names':['A','C'], 'formats':['<i8','<i8'], 'offsets':[0,16], 'itemsize':24})

Note that the str display of this array
In [437]: print(arr)
[(0,  1,  2) (3,  4,  5) (6,  7,  8) (9, 10, 11)]

shows a list of tuples, just as your np_arr.  Each tuple is a 'record'.  The repr display shows the dtype as well.
You can't have it both ways, either access columns by name, or make a regular numpy array and access columns by number.  The named/record access makes most sense when columns are a mix of dtypes - string, int, float.  If they are all float, and you want to do calculations across columns, its better to use the numeric dtype.
In [438]: arr = df.to_numpy()
In [439]: arr
Out[439]:
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])


text:
Q: Querying Other-Domain Members of LDAP Group My LDAP Group, TestGroup, has a domain of A. It contains members from domains A, B and C.
When I query for all members of TestGroup, it only returns the members from the A domain - the domain of the group.
How can I query for all members of the TestGroup, regardless of domain?

A: Your current filter is looking for all user objects that are directly a member of the group.  You need to get the group object, and enumerate the member property.  This will give you distinguished names for every member.  If you need to access the member's object, then you will have to search for that using something like (distinguishedName=).
This isn't easy.  You will have to decide whether or not you want to recursively get the members.  I'm pretty sure the users from the other domains are represented by dummy objects in the foreign security principal container.


text:
Q: Error trying to get action & reducer working I am following a blog post, attempting to get a user login implemented in my app
https://auth0.com/blog/secure-your-react-and-redux-app-with-jwt-authentication/
It recommends doing the following in my action
// actions.js

export const LOGIN_REQUEST = 'LOGIN_REQUEST'

function requestLogin(creds) {
  return {
    type: LOGIN_REQUEST,
    isFetching: true,
    isAuthenticated: false,
    creds
  }
}

// .....

export function loginUser(creds) {

  let config = {
    method: 'POST',
    headers: { 'Content-Type':'application/x-www-form-urlencoded' },
    body: `username=${creds.username}&password=${creds.password}`
  }
  console.log(creds) // <-- this works
  return dispatch => {
    console.log(creds) // <-- this doesnt work and everything after it doesnt work

    // We dispatch requestLogin to kickoff the call to the API
    dispatch(requestLogin(creds))

    return fetch('http://localhost:3001/sessions/create', config)
      .then(response =>
        response.json().then(user => ({ user, response }))
            ).then(({ user, response }) =>  {
        if (!response.ok) {
          // If there was a problem, we want to
          // dispatch the error condition
          dispatch(loginError(user.message))
          return Promise.reject(user)
        } else {
          // If login was successful, set the token in local storage
          localStorage.setItem('id_token', user.id_token)
          localStorage.setItem('id_token', user.access_token)
          // Dispatch the success action
          dispatch(receiveLogin(user))
        }
      }).catch(err => console.log("Error: ", err))
  }
}

However, as soon as the function hits the part return dispatch => { an error gets raised

--- Edit ---
the answers below fixed the console errors, but a new error was introduced
my redux chrome plugin no longer sees my redux store

A: It seems that you did not set up Redux Thunk which is a Redux library that allows you to have asynchronous actions.
In the tutorial you linked, it is explained how to set it up:
import thunkMiddleware from 'redux-thunk'

let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, api)(createStore)

You should read more about Redux Thunk here.

A: What you are trying to do here is to utilise a thunk, which is a function that returns another function.
In redux that is used to cause side effects during action creation such as asynchronous calls as part of an action, and producing secondary actions, like dispatching the response from this asynchronous request.
If you look in the blog post package.json they have dependency on redux-thunk middleware package (https://www.npmjs.com/package/redux-thunk) you will need this too, and to attach it to your store...
import { createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);


text:
Q: Disable caching in send_file Is there a way to prevent flask from setting caching headers in send_file or do I have to manipulate them manually afterwards?

A: send_file accepts cache_timeout parameter - just set it to 0
With Flask 2.0, you can even use it in the send_from_directory function e.g.
send_from_directory('server/assets', 'path', cache_timeout= 0)
and it will hand it down to send_file
https://flask.palletsprojects.com/en/2.0.x/api/#flask.send_from_directory