text:
Q: strange mingw linker errors with boost? I've been working on this for a while now, and can't seem to make sense of the situation - partly bceause I don't fully understand what's going on (which is why I came here).
I'm doing a sort of boost hello world as follows:
#include <boost/thread/thread.hpp>
#include <cstdio>

void helloworld() {
    std::printf("HELLO FROM A BOOST THREAD!");
}

int main(int argc, char **argv) {
    boost::thread t(&helloworld);
    t.join();
}

This is on Windows. I stored the Boost directory in C:\Boost. I ran bootstrap and bjam, and now have a stage/lib folder that contains all the .lib files. The lib files relating to the boost/thread library are:
libboost_thread-vc100-mt.lib
libboost_thread-vc100-mt-1_46_1.lib
libboost_thread-vc100-mt-gd.lib
libboost_thread-vc100-mt-gd-1_46_1.lib

Now I compile:
g++ -c main.cpp -I/Boost

that line works fine, I get main.o. Then:
g++ -o test.exe main.o -L/Boost/stage/lib -llibboost_thread-vc100-mt

And that's where the trouble happens. First of all, If I didn't type the -l argument the way I did, MinGW couldn't even find the file. Meaning, if I tried:
-lboost_thread-vc100-mt

instead of the way I typed it above (and how I thought it should be done), ld would exit with no such file. Anyway, this is now the output I'm getting from that line:
main.o:main.cpp:(.text+0x47): undefined reference to `_imp___ZN5boost6thread4joinEv'
main.o:main.cpp:(.text+0x55): undefined reference to `_imp___ZN5boost6threadD1Ev'
main.o:main.cpp:(.text+0x70): undefined reference to `_imp___ZN5boost6threadD1Ev'
main.o:main.cpp:(.text$_ZN5boost6threadC1IPFvvEEET_NS_10disable_ifINS_14is_convertibleIRS4_NS_6detail13thread_move_tIS4_EEEEPNS0_5dummyEE4typeE[boost::thread::thread<void (*)()>(void (*)(), boost::disable_if<boost::is_convertible<void (*&)(), boost::detail::thread_move_t<void (*)()> >, boost::thread::dummy*>::type)]+0x23): undefined reference to `_imp___ZN5boost6thread12start_threadEv'
collect2: ld returned 1 exit status

Now somewhere in there, I can tell that these are apparently the functions I'm supposed to be getting from boost/thread, and apparently it does find the lib file, so why isn't it linking correctly?
Thank you very much for any help!
EDIT:
I've rebuilt boost using the bjam "stage" option
bjam toolset=gcc stage

Now, after the build completes, I'm left with a stage/lib folder with .a files, as is to be expected. These are the boost/thread related libraries:
libboost_thread-mgw45-mt-1_46_1.a
libboost_thread-mgw45-mt-d-1_46_1.a

However, linking as follows:
g++ -o test.exe main.o -L/Boost/stage/lib -lboost_thread-mgw45-mt-1_46_1

outputs the exact same errors. Also tried:
g++ -o test.exe main.o -L/Boost/stage/lib -lboost_thread-mgw45-mt-1_46_1 -static

I'm at a loss, still.

A: This set of library files:
libboost_thread-vc100-mt.lib
libboost_thread-vc100-mt-1_46_1.lib
libboost_thread-vc100-mt-gd.lib
libboost_thread-vc100-mt-gd-1_46_1.lib

are for the Visual Studio 2010 compiler.  They won't work with GCC.  If you want to use gcc/MinGW, you'll need to download/build a set of boost libraries for that compiler. Alternatively you can install VS 2010 and use that compiler (the free VC++ 2010 Express version should work fine if cost is an issue).
You can get a MinGW distribution with Boost already in the package from http://nuwen.net/mingw.html (32-bit target only, I believe).

To answer about getting the errors with using the MinGW libs:
The _imp_ prefixes on the symbols is an indication that g++ is looking to link to a a dll/shared library.  The .lib file you have are for static libraries (which is what also what I get when doing a straightforward bjam build of the libraries).  If you look in boost/thread/detail/config.hpp you'll see that for Win32 builds it defaults to building against a DLL library unless the MSVC or Intel compiler is being used.
I'm not even sure exactly how to build the DLL libraries - I'll have to look it up.  In the meantime, you can use the following command to build your example such that it'll link against the static library.  The BOOST_THREAD_USE_LIB macro build the .cpp file such that it'll expect to link against the static library:
g++ -I/Boost -DBOOST_THREAD_USE_LIB -c main.cpp

A: Solved the problem. Boost's headers are configured to be dynamically linked, but the dynamic libraries (dll's) are not built unless you specify:
--build-type=complete

when invoking bjam. After that, copy the appropriate dll to your application directory, but still use the
-L/BOOST_DIR/stage/lib -lname

when linking.


text:
Q: Java Dynamic Table

                    <c:forEach items="${list}" var="component" varStatus="var">

                            <c:out value="${component.compName}"></c:out>
                            <input type="text" name="comp_${component.compId}">

                    </c:forEach>

                        <input type="submit" value="save" onclick="populateHiddenFields()">

How to get the input type values in servlet..
along with component id and component value

redpajama_set_name: RedPajamaStackExchange


text:
Q: Core Data to create contacts? Creating a user heavy application and am a bit lost on what to do as far as the editing and saving data to a user goes. Can anyone push me in the right direction? Thanks.

A: One of the beautiful things about CoreData is that, once you create your data model, you are largely relieved from the details of how to write, edit and save the data itself.  Of course, if you want to you can take control of those details.
I'd suggest you look at the tutorials here:  http://www.techotopia.com/index.php/An_iOS_6_iPhone_Core_Data_Tutorial
That will definitely set you on the right course.  I think you'll find it's actually very easy!


text:
Q: SELECT query using an array of tuples I can match one set of conditions like so:
select ID from FOO where col1=1 and col2=2 and col3=3

But, what if I have an array, [(1,2,3), (4,5,6), (7,8,9)], how do I get the ID's in this case?
To clarify, I would like a way to match each of the tuples to the three columns.  If it was broken out it would be:
select ID from FOO where col1=1 and col2=2 and col3=3

select ID from FOO where col1=4 and col2=5 and col3=6

select ID from FOO where col1=7 and col2=8 and col3=9

If I have to loop, so be it, I thought there might be a more elegant way to do this.
My version of sqlite is 3.8.11, which ships with Python 3.5.1.

A: There are various ways to obtain multiple IDs with a single query in your situation.
First, you can just take the series of single SELECTs:
SELECT ID FROM FOO WHERE col1=1 AND col2=2 AND col3=3;

SELECT ID FROM FOO WHERE col1=4 AND col2=5 AND col3=6;

SELECT ID FROM FOO WHERE col1=7 AND col2=8 AND col3=9;

and combine them with UNION ALL:
SELECT ID FROM FOO WHERE col1=1 AND col2=2 AND col3=3
UNION ALL
SELECT ID FROM FOO WHERE col1=4 AND col2=5 AND col3=6
UNION ALL
SELECT ID FROM FOO WHERE col1=7 AND col2=8 AND col3=9;

Now you have a single statement returning all the matching IDs. It has to pass over the table as many times as you have tuples, but if the number is not big, that should not be a concern.
Another way is to use the OR operator to combine the conditions:
SELECT
  ID
FROM
  FOO
WHERE col1=1 AND col2=2 AND col3=3
   OR col1=4 AND col2=5 AND col3=6
   OR col1=7 AND col2=8 AND col3=9
;

You may also add brackets to make the intention absolutely unambiguous:
WHERE (col1=1 AND col2=2 AND col3=3)
   OR (col1=4 AND col2=5 AND col3=6)
   OR (col1=7 AND col2=8 AND col3=9)

though AND has higher precedence than OR, so the result would be the same either way.
While much simpler, the second method may not necessarily be more efficient. Internally, each member of the OR-ed expression may be implemented as a separate query, all of them being combined with UNION. So, under the covers the actual query executed could be very similar to the previous query, except UNION is not quite the same as UNION ALL, because it has the additional overhead of de-duplication of the results. If you expect your results to be unique anyway, de-duplication is certainly unnecessary.
In that case you might want to consider this method:
SELECT
  f.ID
FROM
  FOO AS f
  INNER JOIN
  (
    SELECT 1 AS col1, 2 AS col2, 3 AS col3
    UNION ALL
    SELECT 4, 5, 6
    UNION ALL
    SELECT 7, 8, 9
  ) AS p ON f.col1 = p.col1
        AND f.col2 = p.col2
        AND f.col3 = p.col3
;

The p derived table returns the argument values as a row set. That row set is joined against FOO and thus serves as a filter.
Although the last query looks more verbose even than the first one, it may turn out most efficient of the three methods.
It would have looked slightly more elegant, though, if SQLite had let you use the VALUES row constructor in the FROM clause:
SELECT
  f.ID
FROM
  FOO AS f
  INNER JOIN
  (
    VALUES
      (1, 2, 3),
      (4, 5, 6),
      (7, 8, 9)
  ) AS p (col1, col2, col3)
     ON f.col1 = p.col1
    AND f.col2 = p.col2
    AND f.col3 = p.col3
;

However, you can rewrite that using a CTE (Common Table Expression, also known as the WITH clause), like this:
WITH p (col1, col2, col3) AS
  (
    VALUES
      (1, 2, 3),
      (4, 5, 6),
      (7, 8, 9)
  )
SELECT
  f.ID
FROM
  FOO AS f
  INNER JOIN p ON f.col1 = p.col1
              AND f.col2 = p.col2
              AND f.col3 = p.col3
;

But, perhaps, the most elegant solution would have been this:
SELECT
  ID
FROM
  FOO
WHERE
  (col1,col2,col3) IN ((1,2,3), (4,5,6), (7,8,9))
;

if that syntax were supported in SQLite.
(Kudos to ypercubeᵀᴹ for the last two suggestions from the standard SQL.)
As of version 3.15, though, SQLite does support tuple comparison, as commented by a_horse_with_no_name, just not the specific syntax in the previous query. You can use the IN predicate with it only if you are matching against a subquery rather than an explicitly specified tuple list (thanks CL. for the suggestion):
SELECT
  ID
FROM
  FOO
WHERE
  (col1,col2,col3) IN (VALUES (1,2,3), (4,5,6), (7,8,9))
;

Or you can compare the tuples using the = predicate:
SELECT
  ID
FROM
  FOO
WHERE
  (col1,col2,col3) = (1,2,3)
  OR
  (col1,col2,col3) = (4,5,6)
  OR
  (col1,col2,col3) = (7,8,9)
;


text:
Q: Term filter causes memory to spike drastically The term filter that is used:
curl -XGET 'http://localhost:9200/my-index/my-doc-type/_search' -d '{
  "filter": {
    "term": {
      "void": false
    }
  },
  "fields": [
    [
      "user_id1",
      "user_name",
      "date",
      "status",
      "q1",
      "q1_unique_code",
      "q2",
      "q3"
    ]
  ],
  "size": 50000,
  "sort": [
    "date_value"
  ]
}'

*

*The void field is a boolean field.

*The index store size is 504mb.

*The elasticsearch setup consists of only a single node and the index
consists of only a single shard and 0 replicas. The version of
elasticsearch is 0.90.7

*The fields mentioned above is only the first 8 fields. The actual
term filter that we execute has 350 fields mentioned.

We noticed the memory spiking by about 2-3gb though the store size is only 504mb.
Running the query multiple times seems to continuously increase the memory.
Could someone explain why this memory spike occurs?

A: *

*It's quite an old version of Elasticsearch

*You're returning 50,000 records in one get

*Sorting the 50k records

*Your documents are pretty big - 350 fields.

Could you instead return a smaller number of records? and then page through them?
Scan and Scroll could help you.
it's not clear whether you've indexed individual fields - this could help as the _source being read from disk may be incurring a memory overhead.


text:
Q: How to generate a date range in kdb excluding weekend days? This code produces a sequence of dates:
firstdate: 2008.06.01
lastdate: 2008.08.31
daterange: firstdate + til (lastdate - firstdate) + 1

Is it possible to generate the same range excluding weekend dates (Sat/Sun)?

A: q)daterange where not (daterange mod 7) in 0 1
2008.06.02 2008.06.03 2008.06.04 2008.06.05 2008.06.06 2008.06.09 2008.06.10 ..
q)

A: easier would be to do
daterange where 1<daterange mod 7


text:
Q: Signature of quantum phase transition in sudden quench Let's say I have a system which undergoes a phase transition, if a parameter $g$ of system is greater than some $g_{c}$.  Suppose if the system is in normal phase $(g < g_{c})$ and I suddenly quench the Hamiltonian at some instant $t=t_{0}$ to somewhere $g>g_{c}$, what property can I immediately to look at $t=t_{0}$ (which is also experimentally measurable) to know that I crossed the phase transition critical point $g_{c}$. Most of my findings direct me to Loschmidt echo which is primarily an indicator of dynamical quantum phase transitions (DQPT).  But I am not interested in DQPT, any help or insight would help.

A: Clearly, there is nothing you can look at directly at $t = t_0$ to indicate a phase transition. Unitary evolution is continuous; immediately changing your time-evolution operator from $e^{-i H_1 t}$ for $t < t_0$ to $e^{-i H_2 t}$ for $t \geq t_0$ will not discontinuously change the state of your system. For example, if your quench experiment initially has the system in the ground state of $H_1$, then when you quench to $H_2$ at $t=t_0$, the instantaneous state of the system at $t_0$ is still the ground state of $H_1$. All the interesting features of a quench happen in the time following $t_0$.


text:
Q: Is there any danger in calling free() or delete instead of delete[]?
Possible Duplicate:
( POD )freeing memory : is delete[] equal to delete ?

Does delete deallocate the elements beyond the first in an array?
char *s = new char[n];
delete s;

Does it matter in the above case seeing as all the elements of s are allocated contiguously, and it shouldn't be possible to delete only a portion of the array?
For more complex types, would delete call the destructor of objects beyond the first one?
Object *p = new Object[n];
delete p;

How can delete[] deduce the number of Objects beyond the first, wouldn't this mean it must know the size of the allocated memory region? What if the memory region was allocated with some overhang for performance reasons? For example one could assume that not all allocators would provide a granularity of a single byte. Then any particular allocation could exceed the required size for each element by a whole element or more.
For primitive types, such as char, int, is there any difference between:
int *p = new int[n];
delete p;
delete[] p;
free p;

Except for the routes taken by the respective calls through the delete->free deallocation machinery?

A: Yes, this is dangerous!
Dont do it!
It will lead to programm crashes or even worse behavior!
For objects allocated with new you MUST use delete;
For objects allocated with new [] you MUST use delete [];
For objects allocated with malloc() or calloc() you MUST use free();
Be aware also that for all these cases its illegal to delete/free a already deleted/freed pointer a second time. free may also NOT be called with null. calling delete/delete[] with NULL is legal.

A: Yes, there's a real practical danger. Even implementation details aside, remember that operator new/operator delete and operator new[]/operator delete[] functions can be replaced completely independently. For this reason, it is wise to think of new/delete, new[]/delete[], malloc/free etc. as different, completely independent methods of memory allocaton, which have absolutely nothing in common.

A:
Does delete deallocate the elements
  beyond the first in an array?

No. delete will deallocate only the first element regardless on which compiler you do this. It may work in some cases but that's co-incidental.

Does it matter in the above case seeing as all the elements of s are allocated
  contiguously, and it shouldn't be possible to delete only a portion of the array?

Depends on how the memory is marke as free. Again implementation dependant.

For more complex types, would delete call the destructor of objects beyond the first one?

No. Try this:
#include <cstdio>

class DelTest {
    static int next;
    int i;
public:
    DelTest() : i(next++) { printf("Allocated %d\n", i); }
    ~DelTest(){ printf("Deleted %d\n", i); }
};

int DelTest::next = 0;

int main(){
    DelTest *p = new DelTest[5];
    delete p;
    return 0;
}

How can delete[] deduce the number of
  Objects beyond the first, wouldn't
  this mean it must know the size of the
  allocated memory region?

Yes, the size is stored some place. Where it is stored depends on implementation. Example, the allocator could store the size in a header preceding the allocated address.

What if the memory region was
  allocated with some overhang for
  performance reasons? For example one
  could assume that not all allocators
  would provide a granularity of a
  single byte. Then any particular
  allocation could exceed the required
  size for each element by a whole
  element or more.

It is for this reason that the returned address is made to align to word boundaries. The "overhang" can be seen using the sizeof operator and applies to objects on the stack as well.

For primitive types, such as char, int, is there any difference between ...?

Yes. malloc and new could be using separate blocks of memory. Even if this were not the case, it's a good practice not to assume they are the same.

A: Raymond Chen (Microsoft developer) has an in-depth article covering scaler vs. vector deletes, and gives some background to the differences. See:
http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx

A: It's undefined behaviour (most likely will corrupt heap or crash the program immediately) and you should never do it. Only free memory with a primitive corresponding to the one used to allocate that memory.
Violating this rule may lead to proper functioning by coincidence, but the program can break once anything is changed - the compiler, the runtime, the compiler settings. You should never rely on such proper functioning and expect it.
delete[] uses compiler-specific service data for determining the number of elements. Usually a bigger block is allocated when new[] is called, the number is stored at the beginning and the caller is given the address behind the stored number. Anyway delete[] relies on the block being allocated by new[], not anything else. If you pair anything except new[] with delete[] or vice versa you run into undefined behaviour.

A: Read the FAQ: 16.3 Can I free() pointers allocated with new? Can I delete pointers allocated with malloc()?

Does it matter in the above case seeing as all the elements of s are allocated contiguously, and it shouldn't be possible to delete only a portion of the array?

Yes it does.

How can delete[] deduce the number of Objects beyond the first, wouldn't this mean it must know the size of the allocated memory region?

The compiler needs to know. See FAQ 16.11

Because the compiler stores that information.

What I mean is the compiler needs different deletes to generate appropriate book-keeping code. I hope this is clear now.

A:
For primitive types, such as char, int, is there any difference between:

I'd say you'll get undefined behaviour. So you shouldn't count on stable behaviour. You should always use new/delete, new[]/delete[] and malloc/free pairs.

A: It's undefined behavior. Hence, the anser is: yes, there could be danger. And it's impossible to predict exactly what will trigger problems. Even if it works one time, will it work again? Does it depend on the type? Element count?

A: Although it might seem in some logic way that you can mix new[] and free or delete instead of delete[], this is under the assumption about the compiler being a fairly simplistic, i.e., that it will always use malloc() to implement the memory allocation for new[].
The problem is that if your compiler has a smart enough optimizer it might see that there is no "delete[]" corresponding to the new[] for the object you created.  It might therefore assume that it can fetch the memory for it from anywhere, including the stack in order to save the cost of calling the real malloc() for the new[].  Then when you try to call free() or the wrong kind of delete on it, it is likely to malfunction hard.

A: Step 1 read this: what-is-the-difference-between-new-delete-and-malloc-free
You are only looking at what you see on the developer side.
What you are not considering is how the std lib does memory management.
The first difference is that new and malloc allocate memroy from two different areas in memory  (New from FreeStore and malloc from Heap (Don't focus on the names they are both basically heaps, those are just there official names from the standard)). If you allocate from one and de-allocate to the other you will messs up the data structures used to manage the memory (there is no gurantee they will use the same structure for memory management).
When you allocate a block like this:
int*   x= new int; // 0x32

Memory May look like this: It probably wont since I made this up without thinking that hard.
Memory   Value      Comment
0x08     0x40       // Chunk Size
0x16     0x10000008 // Free list for Chunk size 40
0x24     0x08       // Block Size
0x32     ??         // Address returned by New.
0x40     0x08       // Pointer back to head block.
0x48     0x0x32     // Link to next item in a chain of somthing.

The point is that there is a lot more information in the allocated block than just the int you allocated to handle memory management.
The standard does not specify how this is done becuase (in C/C++ style) they did not want to inpinge on the compiler/library manufacturers ability to implement the most effecient memory management method for there architecture.
Taking this into account you want the manufacturer the ability to distinguish array allocation/deallocation from normal allocation/deallocation so that it is possable to make it as effecient as possable for both types independantly. As a result you can not mix and match as internally they may use different data structures.
If you actually analyse the memory allocation differences between C and C++ applications you find that they are very different. And thus it is not unresonable to use completely different techniques of memory management to optimise for the application type. This is another reason to prefer new over malloc() in C++ as it will probably be more effecient (The more important reason though will always be to reducing complexity (IMO)).


text:
Q: Filtering table on the frontend - Vue.JS I have a table with students details, that I get from the db using v-for.
I'm trying to filter the table based on a field value. for starters, I have 3 inputs above the table, and every one of them is bound by v-model to update a corresponding key-value pair in an array of filters.
here is my code for the computed studentsList I loop through.
  computed:{
filteredStudentList:function(){
  console.log(this.lastNameSearch);
  let filteredStudents =[]

  let filtersArray = [
    ['lastName',this.lastNameSearch ],
    ['firstName',this.firstNameSearch],
    ['studentID',this.studentIDSearch ],

    ///avoiding comparing to null or empty searchBox
  ]
  let filteredFiltersArray = filtersArray.filter(pair=>{
    return pair[1] !=null
  })
  let dFilteredFiltersArray = filteredFiltersArray.filter(pair=>{
    return pair[1] !=""
  })
  console.log(filtersArray);
  console.log(dFilteredFiltersArray);

  // add students to the filtered array, if they are not there already and all the searchBoxes are empty
  this.studentsList.forEach(student=>{
    if (dFilteredFiltersArray.length==0 && filteredStudents.indexOf(student)==-1){
    filteredStudents.push(student)
    }else{
        dFilteredFiltersArray.forEach(([q,a])=>{
          Object.entries(student).forEach(([k,v])=>{
        if( k==q){
          if(!v.match(a)){
              console.log(student);
              filteredStudents.filter(i=>{
              return i !=student
            })
          }
        }
      })
    })
    }
  })
  console.log(filteredStudents);
  return filteredStudents
}
   },

Now, when I run it, whatever letter I type in a search box, it filters out all of the students.
Can anyone help me to figure out what is wrong with my code?

A:

var app = new Vue({
  el: '#app',
  data: {
    firstNameSearch: "",
    lastNameSearch: "",
    studentIDSearch: "",
    studentsList: [
      {
        firstName: "Dan",
        lastName:"Ramsey",
        studentID: "1",
      },
      {
        firstName: "Jenna",
        lastName:"Combs",
        studentID: "2",
      },
      {
        firstName: "Jill",
        lastName:"Barron",
        studentID: "3",
      },
    ],
  },
  computed: {
    filteredStudentList: function() {
      let filteredStudents = this.studentsList;
      if (this.firstNameSearch && this.firstNameSearch.lenght != 0) {
        filteredStudents = filteredStudents.filter( student => {
          return student.firstName.search(this.firstNameSearch) != -1;
        })
      }

      if (this.lastNameSearch && this.lastNameSearch.lenght != 0) {
        filteredStudents = filteredStudents.filter( student => {
          return student.lastName.search(this.lastNameSearch) != -1;
        })
      }

      if (this.studentIDSearch && this.studentIDSearch.lenght != 0) {
        filteredStudents = filteredStudents.filter( student => {
          return student.studentID === this.studentIDSearch;
        })
      }
      return filteredStudents;
    }
  },
})
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

    firstnamne
    lastname
    id

      {{ student.firstName }}
      {{ student.lastName }}
      {{ student.studentID }}

    First name
    <input id="firstNameSearch" type="text" v-model="firstNameSearch"/>
    Last name
    <input id="lastNameSearch" type="text" v-model="lastNameSearch"/>
    ID
    <input id="studentIDSearch" type="text" v-model="studentIDSearch"/>

I think this is an easier approach.
Edited with a snippet.


text:
Q: IF-Else Java Assignment My assignment is to create several methods for the program. I seem to be stuck on these two the most.
Specifications are as follows: Need to use if n else statement
name: setZipCode
arguments: 1 int
returns: boolean
what it does: stores its argument as the address' zip code.  If the
zip code is not a number between 90000 and 92000 (inclusive) (the
range of Los Angeles' zip codes) return false, otherwise return true.
name: getZipCode
arguments: none
returns: int
what it does: returns the value of the address' zip code
My code so far:
public int setZipCode(int zipCode){ //argument has to be type int zipCode and this method has to return a boolean
     if(zipCode >90000 && zipCode <92000){ //zipCode is between 90000 and 92000
      return true;
     }else{
      return false;
     }
   public int getZipCode(){//no argument
      return zipCode; //returns type int and return the value of the address zipcode
   }
}

When I run this code it gives error bad operand types for binary operator.
Incompatible types: unexpected return value.
I declare int zipCode; early on and I don't understand how to get boolean and int working together.
If anyone can offer me help, as to what I am doing wrong, it would be greatly appreciated and thank you.
I made the changes based on the advice each of you given me, it compiles now, but for some reason it still shows on command prompt that getZipCode and setZipCode failed!
actual zip:0
expected zip: 2
 public int getZipCode(){
      return zipCode;
   }
   public boolean setZipCode(int zipCode) {
      if(zipCode >90000 && zipCode <92000){
         this.zipCode = zipCode;
         return true;
      }
      else{
         return false;
      }

    }
}

A: As you wrote, setZipCode should return a boolean, and should probably set the zip code, as its name suggests :
public boolean setZipCode(int zipCode) {
     if(zipCode >90000 && zipCode <92000){
      this.zipCode = zipCode;
      return true;
     }else{
      return false;
     }
}

Besides that, you should move your getZipCode() method outside of the body of setZipCode() :
public int getZipCode() {
    return zipCode;
}

A: This is a possible solution
public class Address {
    private int zipCode;
    public boolean setZipCode(int zipCode){
        this.zipCode = zipCode;
        return zipCode > 90000 && zipCode < 92000;
    }
}

Please note that, however, setZipCode has two jobs:

*

*setting the zip code

*checking the zip code

So probably you should split them. In addition, be careful using boolean error codes (see here)

A: Your code has setZipCode declared as an int but you're returning booleans (true or false). Declale setZipCode as a boolean.

A: I think that your problem is on the sign of your method:
public int setZipCode(int zipCode){...}

You are saying that your method will return a int, but on code you are trying to return a boolean value (true/false).
To fix this problem you should update your method as:
public boolean setZipCode(int zipCode) {
if(zipCode >90000 && zipCode <92000){ //zipCode is between 90000 and 92000
     return true;
 }else{
     return false;
 }
}

Also I think that you missed a curly brace between the setZipCode method and getZipCode method.

A: setZipCode method's return type should  be boolean as you're trying to return boolean value.Here is one line of code snippet that you should do:
public boolean setZipCode(int zipCode){
    return zipCode > 90000 && zipCode < 92000;
}


text:
Q: Approximation of compactly supported continuous functions that conserve the integral value Say $f\in L^p((0,1))$ is a function satisfying
$$
\int_0^1 f = 0
$$
Is it possible to find a sequence $(f_k)$ of compactly supported continuous function also satisfying
$$
\int_0^1 f_k = 0
$$
such that $f_k \to f$ in $L^p((0,1))$?
I was wondering if this is possible but I don't know how one could go about proving it. Any suggestions are appreciated!
EDIT: If it helps, I am willing to add some assumptions on $f$. For instance, that $f$ is continuous.

A: First make a sequence $f_n$ approximating $f$ (say $\lVert f-f_n\rVert_p<\frac1n$) such that

*

*$\int_0^1 f_n=0$, and

*$f_n$ is an $L^p(I_n)$ function extended by 0 to $L^p(\mathbb{R})$, where $I_n$ is a compact subset of $(0,1)$.

This is possible because $\displaystyle\int_0^1 f=\varinjlim_{K}\int_K f$ over compact subsets $K\subset(0,1)$, so for large enough compact subset $\int_K f$ is approximately $0$, so $f1_K-\frac{1}{\lvert K\rvert}(\int_K f)$ is close to $f$ with total integral $0$.
Now $I_n\subset[\delta_n,1-\delta_n]$ for some $\delta_n>0$, so you can mollify $f_n$ to get a smooth function $g_n=f_n\ast\varphi_{\varepsilon_n}$ supported on $[\frac12\delta_n,1-\frac12\delta_n]$ which satisfies $\lVert g_n-f_n\rVert_p<\frac1n$.  So $g_n$ is a compactly supported function approximating $f$ in $L^p$.
Finally, we need to check $g_n$ has total integral $0$, but that is a property of mollification:
$$\require{cancel}
\begin{align*}
\int_0^1 g_n(x)\,\mathrm{d}x
&=\int_\mathbb{R} (f_n\ast\varphi_{\varepsilon_n})(x)\,\mathrm{d}x\\
&= \int_\mathbb{R}\int_\mathbb{R}\varphi_{\varepsilon_n}(y)f_n(x-y)\,\mathrm{d}y\,\mathrm{d}x\\
&=\int_\mathbb{R}\varphi_{\varepsilon_n}(y)\cancel{\color{red}{\int_\mathbb{R}f_n(x-y)\,\mathrm{d}x}}\,\mathrm{d}y\\
&=0
\end{align*}
$$
as desired.


text:
Q: Find all SQL Server database users in C# To find all database users / owners I am currently using following code
m_server is of type Microsoft.SqlServer.Management.Smo.Server:
var databases = m_server.Databases;
var result = new List<string>();

foreach (Database database in databases)
{
    if (!result.Contains(database.Owner))
    {
        result.Add(database.Owner);
    }
}

This method lacks performance.
Is there any other way to get list of users from Microsoft.SqlServer.Management.Smo.Server type variable?

A:       var result = new List<string>();
        foreach (Login login in m_server.Logins)
        {
            if (!login.IsDisabled)
            {
                result.Add(login.Name);
            }
        }
        return result;

I got it, this was the perfect code


text:
Q: SubtleCrypto ArrayBuffer Key to String I've been looking at SublteCrypto to encrypt/decrypt text messages, and wanted to extract the key that is used to String, but using the same interface "SubtleCrypto" produces weird Strings for the key.
Now this is the code that I was playing with:
    Internal.crypto = {
    getRandomBytes: function(size) {
        var array = new Uint8Array(size);
        crypto.getRandomValues(array);
        return array.buffer;
    },
    encrypt: function(key, data, iv) {
        return crypto.subtle.importKey('raw', key, {name: 'AES-CBC'}, false, ['encrypt']).then(function(key) {
            return crypto.subtle.encrypt({name: 'AES-CBC', iv: new Uint8Array(iv)}, key, data);
        });
    },
    decrypt: function(key, data, iv) {
        return crypto.subtle.importKey('raw', key, {name: 'AES-CBC'}, false, ['decrypt']).then(function(key) {
            return crypto.subtle.decrypt({name: 'AES-CBC', iv: new Uint8Array(iv)}, key, data);
        });
    },
    sign: function(key, data) {
        return crypto.subtle.importKey('raw', key, {name: 'HMAC', hash: {name: 'SHA-256'}}, false, ['sign']).then(function(key) {
            return crypto.subtle.sign( {name: 'HMAC', hash: 'SHA-256'}, key, data);
        });
    },

    hash: function(data) {
        return crypto.subtle.digest({name: 'SHA-512'}, data);
    },

    HKDF: function(input, salt, info) {
        // Specific implementation of RFC 5869 that only returns the first 3 32-byte chunks
        // TODO: We dont always need the third chunk, we might skip it
        return Internal.crypto.sign(salt, input).then(function(PRK) {
            var infoBuffer = new ArrayBuffer(info.byteLength + 1 + 32);
            var infoArray = new Uint8Array(infoBuffer);
            infoArray.set(new Uint8Array(info), 32);
            infoArray[infoArray.length - 1] = 1;
            return Internal.crypto.sign(PRK, infoBuffer.slice(32)).then(function(T1) {
                infoArray.set(new Uint8Array(T1));
                infoArray[infoArray.length - 1] = 2;
                return Internal.crypto.sign(PRK, infoBuffer).then(function(T2) {
                    infoArray.set(new Uint8Array(T2));
                    infoArray[infoArray.length - 1] = 3;
                    return Internal.crypto.sign(PRK, infoBuffer).then(function(T3) {
                        return [ T1, T2, T3 ];
                    });
                });
            });
        });
    },

    // Curve 25519 crypto
    createKeyPair: function(privKey) {
        if (privKey === undefined) {
            privKey = Internal.crypto.getRandomBytes(32);
        }
        return Internal.Curve.async.createKeyPair(privKey);
    },
    ECDHE: function(pubKey, privKey) {
        return Internal.Curve.async.ECDHE(pubKey, privKey);
    },
    Ed25519Sign: function(privKey, message) {
        return Internal.Curve.async.Ed25519Sign(privKey, message);
    },
    Ed25519Verify: function(pubKey, msg, sig) {
        return Internal.Curve.async.Ed25519Verify(pubKey, msg, sig);
    }
};

What I've changed to get the key in String was:
    encrypt: function(key, data, iv) {
        var sKey = String.fromCharCode.apply(null, new Uint8Array(key));
        console.log('key ' + sKey);
        return crypto.subtle.importKey('raw', key, {name: 'AES-CBC'}, true, ['encrypt']).then(function(key) {
            return crypto.subtle.encrypt({name: 'AES-CBC', iv: new Uint8Array(iv)}, key, data);
        });
    },
    decrypt: function(key, data, iv) {
        var sKey = String.fromCharCode.apply(null, new Uint8Array(key));
        console.log('key ' + sKey);
        return crypto.subtle.importKey('raw', key, {name: 'AES-CBC'}, true, ['decrypt']).then(function(key) {
            return crypto.subtle.decrypt({name: 'AES-CBC', iv: new Uint8Array(iv)}, key, data);
        });
    }

I know that key in encrypt: function(key, data, iv) and decrypt: function(key, data, iv) is in ArrayBuffer, but I've tried everything to convert from ArrayBuffer to String, and it always produces incorrect encoded strings like Sask���ç é

A: A cryptographic keys isn't text, or text encoded as bytes. It is a random byte sequence, so trying to decode it as a string is likely to irrevocably lose data.
Instead, use base-64 encoding (btoa()) and decoding (atob()) to convert binary data to strings and back again. The same applies to cipher text.


text:
Q: Pandas to_datetime error 'unconverted data remains' I'm trying to convert date column in my Pandas DataFrame to datetime format. If I don't specify date format, it works fine, but then further along in the code I get issues because of different time formats.
The original dates looks like this 10/10/2019 6:00 in european date format.
I tried specifying format like so:
df['PeriodStartDate'] = pd.to_datetime(df['PeriodStartDate'],
          format="%d/%m/%Y")

which results in an error: unconverted data remains 6:00
I then tried to update format directive to format="%d/%m/%Y %-I/%H" which comes up with another error: '-' is a bad directive in format '%d/%m/%Y %-I/%H' even though I thought that to_datetime uses the same directives and strftime and in the latter %-I is allowed.
In frustration I then decided to chop off the end of the string since I don't really need hours and minutes:
    df['PeriodStartDate'] = df['PeriodStartDate'].str[:10]
    df['PeriodStartDate'] = pd.to_datetime(df['PeriodStartDate'],
          format="%d/%m/%Y")

But this once again results in an error: ValueError: unconverted data remains: which of course comes from the fact that some dates have 9 digits like 3/10/2019 6:00
Not quite sure where to go from here.

A: format %H:%M would work(don't forget the : in between)
pd.to_datetime('10/10/2019 6:00', format="%m/%d/%Y %H:%M")

Out[1049]: Timestamp('2019-10-10 06:00:00')

pd.to_datetime('3/10/2019 18:00', format="%d/%m/%Y %H:%M")

Out[1064]: Timestamp('2019-10-03 18:00:00')

A: Oh, I feel so dumb. I figured out what the issue was. For some reason I thought that hours were in a 12-hour format, but they were in fact in a 24-hour format, so changing directive to "%d/%m/%Y %H:%M" solved it.


text:
Q: Downloading video files of specific size To do:

*

*Download a video from url. The downloading should stop once a specific file size has been reached.

This is what I have tried so far.
import requests

with open(local_file_name, 'w') as f:
    r = requests.get(url,stream=True)
    for chunk in r.iter_content(chunk_size=5000000):
        if chunk:
            f.write(chunk)
            break

I used 'break' after writing that chunk of specific size to the file.
Though the file is being created and the size of it is 5 MB, I am not able to view the file as it throwing error while opening.


text:
Q: What does $\mathbb{R}$-invariant mean for a measure? Let $(X, A, m)$ be a measure space with m being $\mathbb{R}$-invariant.
What does this mean?

A: In general, an object can be invariant under a particular action of a group (such as $\mathbb R$)  on a space it's a member of.  Without specifying how the group is supposed to act on the space, it may be hard to guess what is meant.  I would
suspect this is referring to some one-parameter group of symmetries of $X$.


text:
Q: How to send inbox messages with facebook sdk php I would like to send a private message to inbox, like:
$facebook->api('/me/feed','POST',array(
'message'=>'mensagem aqui',
'name'=>'nome aqui',
'caption'=>'caption aqui',
));

but send it to inbox.
it's possible do to?
I mean it:

A: Not possible. See Facebook Permissions and Graph API (scroll down to Publishing section).
If the user has a facebook email (like user@facebook.com) you can just send an email there. Another alternative is to do a 'private' post. See Graph API Post


text:
Q: Is it possible mask input using a different placeholder? Since my form has no labels, I would like to be able to use a different placeholder with Angular and Angular-UI-Utils-Mask:

    <input type="text"
        ng-model="date"
        ui-mask="99/99/9999"
        placeholder="Birth Date"/>

Using jquery-inputmask it works like a charm, but I had too many problems to make it work with Angular so I'm now trying to go Angular way, but Angular shows my input as:
Bi/th/Date

Here's a fiddle to show it: http://jsfiddle.net/XS4R6/
I also saw some people talking about ´ui-mask-placeholder´, but it does nothing.
Is there a way to accomplish this?
EDIT
To clarify, I think it's just fine to use just placeholders since you also use titles (hint) so people always know what are they supposed to type in those inputs:

The input showing __.___.___ is the one I'm using Angular UI Mask.
JQuery Inputmask works very fine, since it shows the 'name' placeholder and as soon as I mouse over or click the input it shows the mask.

A: I'm thinking you can use another tag to simulate placeholder, maybe the code here is not very good, but I just provide another thought.
app.directive("myPlaceholder", ['$compile', function($compile){
return {
    restrict: 'A',
    link: function(scope, elem, attr) {
        attr.$observe('myPlaceholder', initialize);
        var mask = '__/__/____';

        function initialize(value) {
            // label is not clickable in IE, that's the reason why we use span tag
            var fakePlaceholder = angular.element('' + value + '');
            // click placeholder to focus the input
            fakePlaceholder.on('click', function(){
                elem.focus();
            });
            elem.before(fakePlaceholder);
            $compile(fakePlaceholder)(scope);

            elem.on('focus', function() {
                fakePlaceholder.hide();
            }).on('blur', function() {
                if (elem.val() === mask) {
                    fakePlaceholder.show();
                }
            });
        }
    }
};
}]);

demo on http://jsfiddle.net/XS4R6/19/  (jQuery required)


text:
Q: Is this a typo or alternative notation? I am reading Calculus:Volume II by Chen, Liu, etc.
on page 201, the book states this.

...For example, $$ y^{\prime\prime} +xy^{\prime 3} + 5y = e^x $$ is a third-order equation.

I have seen $y^{(3)}$ as meaning the third derivative of y in prime notation; however, I have never seen $y^{\prime N}$ where $N$ is a natural numer for the $N$th derivative of a variable.

A: This is definitely a second order equation and $y'^3$ means the cube of $y'$.

A: Here is the terminology employed for algebraic differential equations
$$\rm  a\, y^{e_0} (y')^{e_1}\cdots (y^{(k)}\!)^{e_k} $$

*

*has $ $ order $\rm\,\ k$

*has $ $ degree $\rm\,\ e_0 + e_1 + \cdots + e_k$

*has $ $ weight $\rm\,\ e_0 + 2 e_2 + \cdots + (k+1) e_k$
A differential polynomial is a sum of such differential monomials. It's order is the maximum order of any of its monomials. Similarly for its degree and weight.


text:
Q: Index setted but undefined index I'm in a ambiguous situation.
Here's the concerned code:
http://prntscr.com/9edm4j
public function verifyReply($reponse)
{
    $qr = $this->mStopBOT;
    if(isset($_SESSION["stopBOT"]))
    {
        if($_SESSION["stopBot"] === false)
        {
            $_SESSION["stopBOT"] = true;
            if($qr[$_SESSION["stopBOTq"]][1] == $reponse)
                return true;
        }
    }
    return false;
}

And here is the problem:
http://prntscr.com/9ednwm
PHP Notice:  Undefined index: stopBot in /home/*************/public_html/inc/classes/Security.inc.php on line 92
The isset() function returns true, but when I use the function, it says that the index is undefined! ?
Regards and Thanks in Advance

A: You are checking if $_SESSION['stopBOT'] is set but then use $_SESSION['stopBot']
Note the case difference, stopBOT vs stopBot


text:
Q: AVRDUDE throws errors when attempting ISP with AVR Dragon I've got an Arduino board that I'm trying to program via ISP with an AVR Dragon. I think I've got it all cabled up right (I made my own ISP cable by cutting up an old floppy ribbon cable), but when I attempt to connect avrdude I get the following errors:
sudo /usr/bin/avrdude -pm328p -c dragon_isp -v -v -v -v -P usb -B 1 -t

avrdude: Version 5.10, compiled on Jun 29 2010 at 03:44:14
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "/etc/avrdude.conf"

     Using Port                    : usb
     Using Programmer              : dragon_isp
     Setting bit clk period        : 1.0
avrdude: stk500v2_dragon_isp_open()
avrdude: usbdev_open(): Found AVRBLDR, serno: 00A200007E77
avrdude: usbdev_open(): using read endpoint 0x82
avrdude: jtagmkII_getsync()
avrdude: jtagmkII_getsync(): Sending sign-on command:
avrdude: jtagmkII_send(): sending 1 bytes
avrdude: Sent: . [1b] . [00] . [00] . [01] . [00] . [00] . [00] . [0e] . [01] . [f3] . [97]
avrdude: jtagmkII_recv():
avrdude: usb_fill_buf(): usb_bulk_read() error No error
avrdude: jtagmkII_recv(): Timeout receiving packet
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): Sending sign-on command:
avrdude: jtagmkII_send(): sending 1 bytes
avrdude: usbdev_send(): wrote -19 out of 11 bytes, err = error submitting URB: No such device
avrdude: jtagmkII_send(): failed to send command to serial port

I've hooked the AVR Dragon to two different Arduinos, and they both have the same issue.

A: The Dragons have always had some problems - not that they're not great.  Start by making sure the firmware is up to date.  It can be updated in AVR Studio.  Then I'd make sure that your cable is correct (verify pin 1 goes to pin 1, pin 2 to pin 2, etc with a DMM) and after that ensure that you have pin 1 of the ISP headers hooked together.  Those things are easy to get the wrong orientation on.


text:
Q: Inject kendo ui with requirejs The documentation on kendo ui and requirejs seems to miss some stuff.
They tell me how to use kendo.web.min which have everything included:
http://www.kendoui.com/blogs/teamblog/posts/13-05-08/requirejs-fundamentals.aspx
(search for keyword 'shim')
but I am not interested in adding the big 2MB kendo.web.min script, I just want to shim the
kendo.grid.min but this file has a dependency to kendo.data.min which again has a dependency
to kendo.core.min.
How can I tell requirejs to load also kendo.data.min and kendo.core.min before kendo.grid.min is loaded and after jquery has been loaded. I just guess this would be the correct order.
This is what I have tried from the above telerik link:
requirejs.config({
    paths: {
        'text': '../Scripts/text',
        'durandal': '../Scripts/durandal',
        'plugins': '../Scripts/durandal/plugins',
        'transitions': '../Scripts/durandal/transitions',
        'knockout': '../Scripts/knockout-2.3.0',
        'jquery': '../Scripts/jquery-2.0.3',
        'kendoGrid': '../Scripts//kendo.grid.min',
    },
    shim: {
        "kendoGrid": {
            deps: ["jquery"]
        }
    }
});

What is the correct way of defining the kendo dependencies like kendo.data and kendo.core ?
At the moment I am getting an exception on application startup from durandal in the systems.js saying:
"Failed to load composed module (viewmodels/DocumentBrowser). details: The property \"jQuery\" of an undefined or null reference can not be  'accessed'.
I know this error is not directly about kendo, but since I introduced kendo ui with requirejs in the DocumentBrowser module I get this exception!
UPDATE
According to CodingWhitSpike`s advise I have changed my requirejs configuration:
requirejs.config({
    paths: {
        'text': '../Scripts/text',
        'durandal': '../Scripts/durandal',
        'plugins': '../Scripts/durandal/plugins',
        'transitions': '../Scripts/durandal/transitions',
        'knockout': '../Scripts/knockout-2.3.0',
        'jquery': '../Scripts/jquery-2.0.3',
        'moment': '../Scripts/moment',
         k: "../Scripts/kendo"
    }
});

define(['durandal/app', 'plugins/dialog', 'knockout', 'services/dataservice', 'plugins/router', 'moment', 'k/kendo.grid.min'],
    function (app, dialog, ko, dataservice, router, moment, kendoGrid) {

 $("#grid").kendoGrid(...); => kendoGrid is instantiated and it works :)

});

A: This is taken from the official Kendo docs at http://docs.kendoui.com/getting-started/using-kendo-with/using-kendo-with-requirejs
<!-- first, load RequireJS -->
<script src="require.js"></script>

<!-- configure RequireJS with two logical paths:
     - "app/" will be used for your files
     - "k/" will be for Kendo UI modules -->

<script>
  requirejs.config({
      paths: {
          app: "/path/to/your/files",
          k: "http://cdn.kendostatic.com/VERSION/js"
      }
  });

  require([
      "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js",
      "app/foo",
      "app/bar",
      "k/kendo.menu.min",
      "k/kendo.grid.min"
  ], initApp);

  function initApp() {
     // main entry point of your application
  }
</script>

Assuming that kendo has set up dependencies of their modules correctly, setting up a path like  k: "http://cdn.kendostatic.com/VERSION/js which points to the modules directory (NOT one individual module) and use a module in like k/kendo.grid.min should all that's required.


text:
Q: How to change line in the UITextView with xib file I use UITextView to hold some infomation, and I have edited the text in the .xib file. The line will be changed when the current line has no space. The problem is that I don`t not how to change line when I want to. Look at the pic below:

I have try to use "\n" or "\\n", but it is displayed as text. I want to know how can I change line in the .xib file?

A: this should work...
textView.text=@"Ankit \r Srivastava";

this should give you both the words in different rows...


text:
Q: Combining basic authentication and form login for the same REST Api Is there a way to set up basic authentication and form login for the same REST service? I'd like to let logged in user trigger this service both through web browser after loggin in and from command line running curl -u username:password hostname.com/api/process
Now I've seen this post: Basic and form based authentication with Spring security Javaconfig
but it's slightly different from what I'm trying to do.
Is there a way to set this up with spring?
What I have now is this:
package com.my.company.my.app.security;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SecurityConfig.class);

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/js/**", "/css/**")
                .permitAll();

        http
                .authorizeRequests()
                .antMatchers("/api/**")
                .authenticated()
                .and()
                .httpBasic();

        http
                .authorizeRequests()
                .antMatchers("/","/index")
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/j_spring_security_check")
                .defaultSuccessUrl("/monitor")
                .failureUrl("/login?error")
                .usernameParameter("j_username")
                .passwordParameter("j_password")
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/j_spring_security_logout")
                .logoutSuccessUrl("/login?logout")
                .permitAll()
                .and()
                .csrf()
                .disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .passwordEncoder(passwordEncoder())
                .usersByUsernameQuery("SELECT username, password, enabled FROM users WHERE username=?")
                .authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username=?");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }
}

The only problem is that it doesn't redirect to my login page when hostname.com/index or hostname.com/ is called instead window pop ups asking for basic authentication credentials.

A: You can achieve this easily by using multiple http configuration as below, this code only explains multiple http configuration. I am assuming that you are well aware of the other essential configurations related to spring security e.g authenticationManger etc.
    @EnableWebSecurity
    public class MultiHttpSecurityCustomConfig {
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin").password("password")
                    .roles("USER", "ADMIN");
        }

        @Configuration
        @Order(1)
        public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
            protected void configure(HttpSecurity http) throws Exception {
                http.antMatcher("/api/**").authorizeRequests().anyRequest().hasRole("ADMIN").and().httpBasic();
            }
        }

        @Configuration
        public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests().anyRequest().authenticated().and().formLogin();
            }

   }
}

Please refer spring security official link: Multiple HttpSecurity
I will also reccomend you to check out Secure REST Services with Spring Security
Feel free to comment if you encounter any problem!

A: One might try with the only ConfigurationAdapter class rather than two, e.g.:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors()
            .and()
        .csrf()
            .disable()
        .httpBasic()
            .and()
        .authorizeRequests()
            .antMatchers("/login/**").permitAll()
            .anyRequest().authenticated()
        .and()
            .formLogin()
    ;
}

Ref.: https://medium.com/@haytambenayed/basic-authentication-and-form-based-authentication-using-spring-security-ed79951dbb2e

A: I found out that the previous code snippet is not working in Spring Security 5 because of an issue in the CSRF filter in the Basic authentication filter chain. It is possible to make it work by disabling CSRF for Basic auth.
BTW the override of Basic auth by Form auth is because redirection to /error page which is caused by this CSRF filter issue.
        @Configuration
        @Order(1)
        public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
            protected void configure(HttpSecurity http) throws Exception {
                http.antMatcher("/api/**")
                    .authorizeRequests()
                    .anyRequest()
                    .hasRole("ADMIN")
                    .and()
                    .httpBasic()
                    .csrf().disable();
            }
        }


text:
Q: How to add kotlin source files to my java gradle groovy project? (NOT android) I have a build.gradle in groovy, for a Java project. I have kotlin sources somewhere else. How can I add those sources to my java project?

A: In build.gradle,
Change
plugins {
    id 'java'
    id 'maven-publish'
}

to
plugins {
    id 'java'
    id 'maven-publish'
    id "org.jetbrains.kotlin.jvm" version "1.6.20-RC2"
}

then add the kotlin sources also
sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
}

Don't forget to respect the my/package/file.kt where file.kt has package my.package. So, the file must be in the folder path like this.
On java you can simply import like this:
import my.package.*;

If your kotlin compiles but you get import errors, then try to verify the folder where the kotlin file is, it's likely a problem with this path. I think the difference from Java is that the file does nothave to follow the name of the class.


text:
Q: How to display Date in dd/MM/yyyy format in the View in Asp.net MVC3 Controller's Code
  int No= Convert.ToInt32(reqCookies["NO"].ToString());
  Student stud = db.Students.Single(n => n.No == No);
  return View(stud);

Im passing the No after the user logs In and want the record of that logged In person to be displayed which i have successfully done.My issue is again with the Date.When the record of the Logged In user is displayed the Date of birth is displayed along with the time.Like this 2/19/2001 12:00:00 AM, instead i only want the date part and not time something like this 19/2/2001.
To achieve this i have tried to convert the date in dd/MM/yyyy format
DateTime DOB=stud.DOB.tostring("dd/MM/yyyy");

Getting Error:No Overload for method 'ToString()' takes 1 Argument
Code in my View is like this:
@Html.DisplayFor(model => model.DOB.ToString())

And when i try to change the format in the View
@Html.DisplayFor(model => model.DOB.ToString("dd/MM/yyyy"))

Getting Error:No Overload for method 'ToString()' takes 1 Argument
Where can i make the conversion and how to truncate the time Part from getting displayed.

A: You could use DisplayFormat in the model to format your date:
[DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}")]
public DateTime myDate { get; set; }

And then in the view:
@Html.DisplayFor(model => model.DOB)

Update:
Alternatively, since the DisplayFor() will simply output the date without any tags, you could just display the date without the use of templated helpers:
@Model.myDate.ToString("dd/MM/yyyy")

Or to display in a textbox you could use:
@Html.TextBox("Date", Model.myDate.ToString("dd/MM/yyyy"))


text:
Q: java.lang.NumberFormatException: For input string: "add" Hello I maded a web service with odd or even and when i maked the client for that webservice in netbeans i had this error.
The web service here :
@WebService(serviceName = "Par_Impar")
public class Par_Impar {

/**
 * Web service operation
 */
@WebMethod(operationName = "operation")
public String operation(@WebParam(name = "val") int val) {
   if(val%2!=0){
       //daca reminder-ul nu este 0 este impar
       return("IMPAR");
   }
   else {
       //daca reminder-ul este 0 atunci este par
       return("PAR");
   }
}

}

The index.jsp :

    <title>PAGINA JSP</title>

    <form action="action.jsp" method="post"

          Introdu numarul :<input type="text" name="nr"/>

        <input type="submit" value="Testeaza"/>
</form>

The action.jsp :
<%--
Document   : action
Created on : Apr 27, 2013, 5:28:45 PM
Author     : ARB
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>

Hello World!

<%-- start web service invocation --%>

<%
String add=request.getParameter("numar");
int aa=Integer.parseInt("add");
try {
mypack.ParImpar_Service service = new mypack.ParImpar_Service();
mypack.ParImpar port = service.getParImparPort();
 // TODO initialize WS operation arguments here
int val=aa;
    // TODO process result here
java.lang.String result = port.operation(aa);
out.println("Result = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
%>
<%-- end web service invocation --%>

Please help me. Thank you !

A: int aa=Integer.parseInt("add");

Above line should be:
int aa=Integer.parseInt(add);

parseInt

Parses the string argument as a signed integer in the radix specified
by the second argument. The characters in the string must all be
digits of the specified radix (as determined by whether
Character.digit(char, int) returns a nonnegative value), except that
the first character may be an ASCII minus sign '-' ('\u002D') to
indicate a negative value or an ASCII plus sign '+' ('\u002B') to
indicate a positive value. The resulting integer value is returned.
An exception of type NumberFormatException is thrown if any of the
following situations occurs:

*

*The first argument is null or is a string of length zero.

*The radix is either smaller than Character.MIN_RADIX or larger than
Character.MAX_RADIX.

*Any character of the string is not a digit of the specified radix,
except that the first character may be a minus sign '-' ('\u002D')
or plus sign '+' ('\u002B') provided that the string is longer than
length 1.

*The value represented by the string is not a value of type int.

A: From your index.jsp your are sending parameter named nr but on the action.jsp you are retrieving a parameter called numar. Since there is no such parameter in the request, you end up parsing null. What @Achintya said also applies.


text:
Q: Mostrar/Ocultar una fila spreadsheet al hacer clic estoy trabajando con una hoja de calculo para que tenga un estilo mas web y necesito mostrar detalles de algunos campos solo cuando el usuario lo requiera. Puedo mostrar una fila oculta con sheet.showRows(3) pero no logro ocultarla usando:
var clic=0;
function mostrarDetalle(){
 var sheet = spreadSheet.getSheetByName("Hoja 1");
 if (clic==0){
  sheet.showRows(3);
  clic = 1;
 }else{
  sheet.hideRows(3);
  clic = 0;
 }
}

Solo me funciona esto:
var sRows = sheet.showRows(3) || sheet.hideRows(3);

pero se oculta automaticamente y necesito que el usuario pueda controlar cuando se debe ocultar, pueden ayudarme?

A: Sobre el código en la pregunta
Dado que las variables globales se "reinicializan" cada vez que se ejecuta el script, no son apropiadas como almacenamiento persistente entre una ejecución y otra.
Generalidades
Como se menciona en la pregunta los métodos para ocultar o mostrar una fila por su número de fila son

*

*showRows(numfila)

*hideRows(numfila)

Lamentablemente ni el servicio Spreadsheet ni Google Sheets API incluyen métodos para indicar si la fila está visible u oculta.
Soluciones provisionales
Del lado de la hoja de cálculo

*

*Se podría usar una columna para mantener una valor que indique se la fila se ha puesto visible u oculta

*Se podría usar fórmulas como =SUBTOTAL(102,A1) la cual devolverá 1 si A1 tiene un valor numérico y está a la vista y 0 si tiene un valor numérico y está oculta.

Del lado de Google Apps Script
Se podrían usar propiedades del documento para guardar el estado de la fila
Lamentablemente las solucione provisionales anteriores no son confiables pues dependen de que el usuario use la hoja de cálculo de forma apropiada según fuera el caso.


text:
Q: My app gets stopped when reaches certain part of the java code I hope you had a good day,
I've started android app development and I've done tons of research and debugging and finally, I got the line of code which causes my app to stop on Android Studio, here's the full code
package com.example.numbershapesapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
class Number {
    int user_number;

    public int isTriangle(int user_number) {
        int i = 0, sum = 0,c=0;
        while (true) {
            sum += i;
            if (sum == user_number) {
                ++c;
                break;
            }
            if(sum > user_number){
                break;
            }
            i++;
        }
        if(c>0)
            return 1;
        else
            return 0;
    }

    public int isSquare(int user_number) {
        int i = 1,c=0,sq=0;
        while (true) {
            sq = i*i;
            if (sq == user_number) {
                c++;
                break;
            }
            i++;
        }
        if(c>0)
            return 1;
        else
            return 0;

    }
}

    public void function(View view) {
       EditText number = (EditText) findViewById(R.id.user_number);
        Number myNum = new Number();
         myNum.user_number = Integer.parseInt(number.getText().toString());
         int num = myNum.user_number;
       if(myNum.isTriangle(num) == 1){
           Toast.makeText(MainActivity.this,"The number "+num+" is Triangular.",Toast.LENGTH_LONG).show();
       }else if(myNum.isSquare(num) == 1){
           Toast.makeText(MainActivity.this ,"The number "+num+" is Square.",Toast.LENGTH_LONG).show();
       }
       else
           {
          // Toast.makeText(MainActivity.this,"The number "+num+" is neither Triangular nor Square",Toast.LENGTH_LONG).show();
           Log.i("TEXT","no t no s");
       }
//       Log.i("done","DONE");
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

In the Function, function(View view) all the statements work except for the else statement.
When my code has to execute the else part then my app crashes. Can you help me with that?
Again here's the specific piece of code which causes this issue.
      else
           {
          // Toast.makeText(MainActivity.this,"The number "+num+" is neither Triangular nor Square",Toast.LENGTH_LONG).show();
           Log.i("TEXT","no t no s");
       }

Thank you.

A: If user_number is not a perfect square, this is an infinite loop.
        while (true) {
            sq = i*i;
            if (sq == user_number) {
                c++;
                break;
            }
            i++;
        }

You could fix it by adding a similar check you have when checking for triangular numbers:
            if(sq > user_number){
                break;
            }

But a better solution might be replacing the loop with a bit of maths.
double root = Math.sqrt(user_number);
if (root == (int) root) {
   // user_number is square
}


text:
Q: Деплой из idea на удаленный Tomcat? У меня есть приложение на spring, в процессе сборки получаю war-файл.
Если загрузить руками на удаленный сервер - все ок.
Если запустить на локальном томкат - все ок.
Пытаюсь настроить деплой на удаленной машине, но после деплоя все ресты недоступны, 404 not found.
Можете подсказать шаги и что должно быть чтобы деплой проходил ?
Мои настройки:


text:
Q: What will be the correct type of "any"? I am using the following in my code base :
https://github.com/google-map-react/google-map-react
But they have not explained the types used for map and maps which is giving me typescript error. Changing it to object does not help much.
const handleApiLoaded = (map: any, maps: any) => {
What is the correct types of map and maps. Thank you.

A: For packages that don't supply first-class typings themselves, DefinitelyTyped usually provides them as is the case here. Install the @types/google-map-react package and you should receive proper types, code completion and type checking.

A: This worked for me. Thanks
      map: google.maps.Map;
      maps: {
        LatLngBounds: new () => google.maps.LatLngBounds;
      };```


text:
Q: Using PeerJs For Live streaming There is already a question peer.js is not working http but not on https? but its marked answered for checking browser compatibility.
It has also a comment peer.js is not working http but not on https? that tells real problem
I am using chrome 64.0.3282.140 and tried different versions and browsers, so peerjs compatibility test results already fine but still
For using navigator.getUserMedia one need to run the web app at secure domain (https)
But then this app does not connect peerjs server with following error

Mixed Content: The page at 'https://localhost:4200' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://0.peerjs.com:9000/peerjs/id?ts=xyz'. This request has been blocked; the content must be served over HTTPS

Moreover using peer.js from secure cdn link makes no difference as it still calls same url as above http://0.peerjs.com:9000/peerjs/id?ts=xyz and unfortunately the url does not work when i tried to change it to https
Is there any secure resource available from peerjs So that I can use getUserMedia?

A: I see this in their docs at https://peerjs.com/docs/#start

secure BOOLEAN BETA (0.3.0)
  true if you're using SSL. Note that our
  cloud-hosted server and assets may not support SSL.

Sounds like you need to host your own server...


text:
Q: Are there any Riemann zeta like functions that may have nontrivial zeros on the critical line but only involves integers up to $N$? Question: Do there exist any Riemann zeta $\zeta(s)$ like functions $f_N(s)$ that may have all nontrivial zeros (verified via numerical calculation) on the critical line but only involve integers up to $N$?
The Riemann zeta function $\zeta(s)$ involves all the integers (for $s>1$) and thus all the primes. I would think that if only integers up to $N$ are involved in these functions $f_N(s)$, then only finite number of primes up to $N$ can be involved.
We would also require that
$$\lim_{N\to\infty} f_N(s)=\zeta(s)$$
Thus we may study the interaction of prime $2$ with prime $3$ if we set $N=3$ in $f_N(s)$. We may understand better how and at what $N$ the chaotic behavior (if it exists) of the normalized spacing between adjacent zeros of $f_N(s)$ kicks in.
Of course the Euler product may not exist anymore for these functions.
thanks-
mike


text:
Q: How to exit fullscreen Terminal I have found that if you go View > Fullscreen:

Then it makes the Terminal fullscreen, and to exit fullscreen I have found that I have to execute the command:
exit

But that closes my entire Terminal, is there not a way to get it to exit the full screen without having to close the actual Terminal session?

A: Just press F11. If it does not work, press Fn+F11

A: Yes, there is a very easy way. Just press F11.

A: Alternative : right click on the screen, select "Leave fullscreen". Or select "Show menu bar". Uncheck Full Screen.

A: *

*F11 : Toogle Fullscreen

*Ctrl + D : exit command shortcut


text:
Q: Pushbutton has to be clicked twice to trigger c++ I am defining a PrintBox Dialog that contains two buttons PRINTER1 and PRINTER2 in my resource file .rc as follows:
IDD_PRINTBOX DIALOGEX 0,0,211,55
STYLE_DS_SETFONT | DS_MODALFRAME | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
CAPTION "Choose Printer"
FONT 8, "MS Sans Serif",0,0,0x0
BEGIN
PUSHBUTTON "PRINTER1",IDC_PRINTER1,7,7,50,14
PUSHBUTTON "PRINTER2",IDC_PRINTER2,152,7,49,14
END

and in the classes of the buttons, I have .h file and .cpp file
.h file
#ifndef PRINTCHOOSEDLG_H
#define PRINTCHOOSEDLG_H
#include <string>
#pragma once

class CPrintChooseDlg : public CDialog
{

public:

CPrintChooseDlg(CWnd* pParent = NULL);
enum { IDD = IDD_PRINTBOX };

protected:
    virtual void DoDataExchange(CDataExchange* pDX);
    protected:
    afx_msg void OnPrinter1();
    afx_msg void OnPrinter2();

    DECLARE_MESSAGE_MAP()
};

 #endif

.cpp file
#include "stdafx.h"
#include "Tungsten.h"
#include "PrintChooseDlg.h"

CPrintChooseDlg::CPrintChooseDlg(CWnd* pParent /*=NULL*/)
    : CDialog(CPrintChooseDlg::IDD, pParent)
{

}

void CPrintChooseDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);

}

BEGIN_MESSAGE_MAP(CPrintChooseDlg, CDialog)
    ON_BN_CLICKED(IDC_PRINTER1,OnPrinter1)
    ON_BN_CLICKED(IDC_PRINTER2,OnPrinter2)
END_MESSAGE_MAP()

// PrintChoose message handlers

void CPrintChooseDlg::OnPrinter1()
{

    CDialog::OnOk();
}
void CPrintChooseDlg::OnPrinter2()
{

    CDialog::OnOk();
}

*The problem is that the button has to be clicked twice in order to fire the event.
*What I tried is to change the definition of PUSHBUTTON and define the header differently in the.h file. I changed also DIALOGEX to DIALOG, but the same problem exist. How can it be clicked only once to fire the event?
Thanks in Advance

A: use DoModal() only once.
instead of using if you can do it in switch case
switch(alg.DoModal())
{
    case IDC_PRINTER1: break;
    case IDC_PRINTER2: break;
    ...
}


text:
Q: Unable to log from Spark Streaming I am trying to log output of spark streaming as shown in the code below
dStream.foreachRDD { rdd =>

  if (rdd.count() > 0) {
    @transient lazy val log = Logger.getLogger(getClass.getName)
    log.info("Process Starting")

      rdd.foreach { item =>

     log.info("Output :: "+item._1 + "," + item._2 + "," + System.currentTimeMillis())
    }
 }

The code is executed on a yarn cluster using the following command
./bin/spark-submit --class "StreamingApp" --files file:/home/user/log4j.properties  --conf  "spark.driver.extraJavaOptions=-Dlog4j.configuration=file:/home/user/log4j.properties" --conf "spark.executor.extraJavaOptions=-Dlog4j.configuration=file:/home/user/log4j.properties" --master yarn --deploy-mode cluster --driver-memory 4g --executor-memory 2g --executor-cores 1 /home/user/Abc.jar

When i view the logs from the yarn cluster, I can find the logs written before foreach i.e. log.info("Process Starting") but the logs inside foreach  are not printing.
I had also tried creating a separate serializable class as below
    object LoggerObj extends Serializable{

        @transient lazy val log = Logger.getLogger(getClass.getName)
   }

and using the same inside foreach as follows
dStream.foreachRDD { rdd =>

  if (rdd.count() > 0) {

    LoggerObj.log.info("Process Starting")

      rdd.foreach { item =>

     LoggerObj.log.info("Output :: "+item._1 + "," + item._2 + "," + System.currentTimeMillis())
    }
 }

but still the same issue, only the logs outside of foreach are being printed.
The log4j.properties is given below
log4j.rootLogger=INFO,stdout,FILE
log4j.rootCategory=INFO,FILE
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=/tmp/Rt.log
log4j.appender.FILE.ImmediateFlush=true
log4j.appender.FILE.Threshold=debug
log4j.appender.FILE.Append=true
log4j.appender.FILE.MaxFileSize=500MB
log4j.appender.FILE.MaxBackupIndex=10
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n
log4j.logger.Holder=INFO,FILE

A: I was able to fix it by putting "log4j.properties" file under each worker nodes.


text:
Q: Regex: split object notation path string with array support I've got a recursive function to go through an object and take what is needed using path string like jsonObj.object.item.value. The idea is to upgrade it somehow to support arrays.
const getValue = function(pathVar, obj) {
  obj = obj || x;
  // get very first node and the rest
  let [node, restNodes] = pathVar.split(/\.(.+)/, 2)
  // get interim object
  ret = obj[node];
  if(ret === undefined) return undefined;
  // pass rest of the nodes further with interim object
  if(restNodes) return getValue(restNodes, ret);
  return ret;
};

Right now on each iteration simple regexp splits path string like jsonObj.object.item.value into jsonObj and object.item.value
the idea is to add array support here, so I can do transformations like
car.engine.something => car and engine.something
wheels[2].material.name => wheels and [2].material.name
[2].material.name => 2 and material.name
car.wheels[4] => car and wheels[4]
Any ideas how to do it?

A: You could use eval which will just evaluate the expression. As for a functional approach, use the following.
function getValue(path, obj) {
    obj = obj || self; // self is the global window variable
    if( !path )
        return obj;

    let pattern = /(?:\["?)?(\w+)(?:\.|"?])?(.*)/i;

    let [ full, property, rest ] = path.match(pattern);
    return getValue( rest, obj[ property ] );
}

self.obj = { foo: [ 2, {bar: "baz"} ] };
console.log(getValue('obj.foo[1]["bar"]')) // 'baz'

Pattern uses four groups. The first is non-capturing and expects a possible ["this will help match array or object properties. Then we expect a series of alphanumerics which we capture. Then another non capturing group to either close "] or match a .. Finally we capture the rest to use in the next call.
Again eval is capable of all of this.


text:
Q: Trying to output an isosceles triangle. I keep getting a right triangle using System;

namespace Shapes
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Character: ");
            string symbol = (Console.ReadLine());
            Console.WriteLine("Peak of Triangle: ");
            int peak = Int32.Parse(Console.ReadLine());

            int i = 0;
            while (i <= peak) // spaces for triangle
            {

                Console.WriteLine(" ");

                int z = 1;

                while (z <= i) // Symbols for triangle
                {
                    Console.Write(symbol);

                    z++;

                }

                i++;
            }

            Console.ReadLine();
        }
    }
}

Output: should start at one (*) then increase until the peak is met. Then should decrease back down to one of whatever input.
The output I am getting is not decreasing it stops at the peak input

A: You have to reverse the counter i to count back to 0.
Console.WriteLine("Character: ");
string symbol = (Console.ReadLine());
Console.WriteLine("Peak of Triangle: ");
int peak = Int32.Parse(Console.ReadLine()); // spaces for triangle
int i = 0;
int n = 1;
while (i != -1) // do it until i is negative
{
    Console.WriteLine(" ");

    int z = 1;

    while (z <= i) // Symbols for triangle
    {
        Console.Write(symbol);
        z++;
    }

    i += n; // increments when n = 1. decrements when n = -1

    if (i >= peak) // reverse counter when it reaches peak
    {
        n = -1;
    }
}


text:
Q: logic problem in javascript - 2 requirements array/object const data = [
    { name: "Table", color: ["green", "red", "blue"], price: 300 },
    { name: "Desk", color: ["white", "yellow", "grey"], price: 300 },
    { name: "Desk", color: ["black", "pink", "green"], price: 500 },
];

Hello, I'm trying to code buy-list in objects, but I met logic problem here because for example, there can be same object (called Desk) but with different array (color) for different price.
How can I grab info about price if my script will meet 2 requirements - it will be Desk, color will be black for example, and result needs to be 500
using .find() function returns 1st object (in this case:  { name: "Desk", color: ["white", "yellow", "grey"], price: 300 })
Please help :D
Greetings.

A: Given just the information your data has you either need to come up with a cumbersome approach like trying to find the color as well, or make sure to include a unique identifier like a SKU into your objects.

A: You could take Array#find with Array#includes for the wanted color.
As result you get either an item or undefined, if the request does not match.

const
    data = [{ name: "Table", color: ["green", "red", "blue"], price: 300 }, { name: "Desk", color: ["white", "yellow", "grey"], price: 300 }, { name: "Desk", color: ["black", "pink", "green"], price: 500 }],
    request = { name: 'Desk', color: 'black' },
    result = data.find(({ name, color }) =>
        name === request.name &&
        color.includes(request.color)
    );

console.log(result);


text:
Q: Postgresql - multi-tenant database - backup/restore single database I am thinking about development of simple CRM for florists. Florists (company with 1-5 employees) will have local installed app on their PCs (call it "Floppa"). Floppa will be communicating to Windows Communication Foundation (WCF) service hosted on my remote server. For each of customer there will be running one instance of WCF service. Business layer under WCF service will be communicating to Postgresql database dedicated to specific customer.
I would like to use continuous archiving. If I understand well WALs will contain logs for every change in every database in cluster.
If one of customers will accidentally deletes/change some data and will ask me for recovery "today's morning state of data" how could I quickly comply his request? According my current knowledge I would need to do:

*

*Stop WCF service (to prevent work on db which will be replace later)

*Restore whole cluster to "today's morning state" on another computer

*Dump customer's morning state database

*Replace customer's database by dumped one

*Start WCF service

Is that correct? Or is there any better solution to this backup/restore issue? What happen if I will create one database per cluster? What will be the drawbacks? I guess that one of advantages will be much more faster recovery.
What will differ if count of customers will be 10, 50, 100, 250? How Postgresql handles hundreds of clusters?
Thanks.

A: Restoring the database will take as long as it takes.  There is no way to know with the information you provide.  If each individual database is quite small, step 2 could be acceptably fast with dozens or maybe even hundreds of databases in the cluster.
Having many database clusters will incur more overhead.  There is a certain minimal size of a cluster (around 21MB for the usual initdb run) which can be amortized over all databases in the cluster. You will have to manage many wal streams, and if you most archiving is driven by an archive_timeout that means you will have many more files in total by dividing them.  You will likely run out of available semaphores, but you can recover some of them by lower the max_connections setting.  On modern OS, you could probably configure the system
to allow a lot of semaphores.  You should be able to test some of this stuff on your own infrastructure with some relatively simple scripting.
But if you do run one cluster for each customer and have 100s of customers, there is no reason you couldn't spread them over multiple machines.


text:
Q: Why does Python unpacking operator work with unordered collections The Python 3 tutorial about the unpacking operator (*) generically speaks of a "list or tuple," while the error message for improper use says that a "sequence" is needed:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(a, b):
...     return a / b
...
>>> f(*1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() argument after * must be a sequence, not int

Python 3's Built-in types documentation lists the following sequence types:

*

*Sequence Types — list, tuple, range

*Text Sequence Type — str

*Binary Sequence Types — bytes, bytearray, memoryview
Quick test:
>>> all(isinstance(x, collections.Sequence) for x in [[], (), range(1), '', b''])
True

Note that set types (like set and frozenset) and mapping types (dict) are not included here.
>>> any(isinstance(x, collections.Sequence) for x in [set(), {}])
False

My question: Why are all iterable types (including a set or dict) unpackable? They are not sequence types, as the TypeError above suggests they should be, and unordered behavior leads to undefined results when unpacking for positional args:
>>> def f(a, b):
...     return a / b
...
>>> f(*{4, 2})
0.5
>>> f(*{8, 2})
4.0
>>> f(*{4:1, 2:1})
0.5
>>> f(*{2:1, 8:1})
4.0

A: This is no longer the case in (at least) Python 3.5.2 -- Probably was recognized as an issue and changed in a version later than what you're using. The message now more appropriately reads iterable instead of sequence
See https://bugs.python.org/issue4806
>>> def foo(*args):
...     print(*args)
...
>>> foo(*1)
TypeError: foo() argument after * must be an iterable, not int

A: The error message is most likely a little bug*. Anything that is an iterable is accepted during function calls; this is hidden inside the section for Calls in the Python Reference Manual:

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from these iterables are treated as if they were additional positional arguments.

(Emphasis mine)
*Which, as of 3.5.2 as @sytech pointed out, was fixed in Issue 4806 to correspond to the correct wording in the reference manual.


text:
Q: Trouble selecting specific property values from this object I'm currently struggling to do something rather straightforward. I simply want to print out specific key values for every object in this array. I'd appreciate any pointers!

var countries = [

  {
    'country name': 'Australia',
    'national emblem': 'blue red white',
    'hemisphere': 'southern',
    'population': 24130000
  },
  {
    'country name': 'United States',
    'national emblem': 'blue red white',
    'hemisphere': 'northern',
    'population': 323000000
  },
  {
    'country name': 'Uzbekistan',
    'national emblem': 'blue green red white',
    'hemisphere': 'northern',
    'population': 31850000
  }

];

function getCountryprops(countries){

  for(var oneCountry in countries){
    for(var propName in oneCountry){
      console.log(oneCountry[propName]['country name'], oneCountry[propName]['population']);
    }
  }
}

So I want to ultimately print out [['Australia', 24130000],['United States', 323000000],['Uzbekistan', 31850000]]

A: When you use for...in on the countries array the oneCountry variable is the index of the current country. To get the country, you need to use the brackets notation on the countries array:

var countries = [{"country name":"Australia","national emblem":"blue red white","hemisphere":"southern","population":24130000},{"country name":"United States","national emblem":"blue red white","hemisphere":"northern","population":323000000},{"country name":"Uzbekistan","national emblem":"blue green red white","hemisphere":"northern","population":31850000}];

function getCountryprops(countries){
  for(var oneCountry in countries){
    console.log(countries[oneCountry]['country name'], countries[oneCountry]['population']);
  }
}

getCountryprops(countries);

Another option is to use for...of to get the country's value directly:

var countries = [{"country name":"Australia","national emblem":"blue red white","hemisphere":"southern","population":24130000},{"country name":"United States","national emblem":"blue red white","hemisphere":"northern","population":323000000},{"country name":"Uzbekistan","national emblem":"blue green red white","hemisphere":"northern","population":31850000}];

function getCountryprops(countries){
  for(var oneCountry of countries){
    console.log(oneCountry['country name'], oneCountry['population']);
  }
}

getCountryprops(countries);


text:
Q: Использование currentTarget?

     01
     02
        03

        11
        12
        13

        21
        22
        23

Суть: при клике по любому td получать значение первого td в данной строке tr.
Например: пользователь кликает по
  23

И мы получаем в переменную 21.

A:

$(document).ready(function() {
  $('table').on('click', 'td', function() {
    tr = $(this).closest('tr');
    td_first = $('td:first', tr).text();
    $('#result').html(td_first);
  });
});

    01
    02
    03

    11
    12
    13

    21
    22
    23

A:


text:
Q: how to format a burned dvd (r+w) hii i want to format a burned dvd in ubuntu....Thus i tried a lot using various options like
cdrecord dev=/dev/sr0 blank=fast

but its not working error is ( i am using ubuntu 20.04)
wodim: Operation not permitted. Warning: Cannot raise RLIMIT_MEMLOCK limits.
Error trying to open /dev/sr0 exclusively (Device or resource busy)... retrying in 1 second.
Error trying to open /dev/sr0 exclusively (Device or resource busy)... retrying in 1 second.
Error trying to open /dev/sr0 exclusively (Device or resource busy)... retrying in 1 second.
Error trying to open /dev/sr0 exclusively (Device or resource busy)... retrying in 1 second.
Error trying to open /dev/sr0 exclusively (Device or resource busy)... giving up.
WARNING: /dev/sr0 seems to be mounted!
wodim: Device or resource busy.
Cannot open SCSI driver!
For possible targets try 'wodim --devices' or 'wodim -scanbus'.
For possible transport specifiers try 'wodim dev=help'.
For IDE/ATAPI devices configuration, see the file README.ATAPI.setup from
the wodim documentation.

can anybody suggest a best solution for formatting the already burned dvd(r+w)

A: "Device or resource busy" sounds like the filesystem on the DVD is mounted, which is also stated in the warning. Do umount /dev/sr0 before.


text:
Q: Thymeleaf conditional add tags I've a list of items in my request attribute("items"), the list will render by bootstrap 4 (https://getbootstrap.com/docs/4.2/components/card/#card-decks) card deck 3 items per row. I can do it by using JSTL like

<c:forEach var="item" items="${items}" varStatus="status">
    <c:if test="${status.index%3 == 0}">
        <c:if test="${status.index > 0}">

        </c:if>

     </c:if>

${item.id}

</c:forEach>

Now, How do I achieve the same using Thymeleaf ? Thanks

A: Your code would translate to Thymeleaf to something like the following code.