text:
Q: NHibernate retrieve more than one tables records I am new in NHibernate.i am facing problem with nhibernate when i hit query on main table it gives me main table records but as well as it is also giving me related linked object tables records.So because of this more sql query hit on database.
which decrease performance of my query.i want only main table records and not fired any other query from database.
I want TAPVendor table records only
Below is my C# code from where i am fired query from database
var lstTAPVendor = session.Query< TAPVendor >()
i have also attached the .hbm file of tapvendor
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping namespace="M3.Entities" assembly="M3.Entities" xmlns="urn:nhibernate-mapping-2.2">
  <class name="TAPVendor" table="tAPVendor" schema="dbo">
    <id name="FVendorID" type="Guid">
      <generator class="assigned" />
    </id>
    <version name="FTimestamp" generated="always" unsaved-value="null" type="BinaryBlob">
      <column name="FTimestamp" not-null="true" sql-type="timestamp"/>
    </version>
    <property name="FActive" type="Boolean" not-null="true" />

    <property name="FTermsType" type="Int32" precision="10" not-null="true" />
    <property name="FACHPayment" type="Boolean" not-null="true" />
    <property name="FCompanyName" type="String" length="50" not-null="true" />
    <property name="FAccrueUseTax" type="Boolean" not-null="true" />
    <property name="FSinglePaymentVendor" type="Boolean" not-null="true" />
    <property name="FACHEnabled" type="Boolean" not-null="true" />
    <property name="FCheckPerInvoice" type="Boolean" not-null="true" />
    <property name="FBankAccountType" type="Int32" precision="10" not-null="true" />
    <property name="FBankAccountName" type="String" length="50" />
    <property name="FBankAccountNumber" type="String" length="50" />
    <property name="FBankABANumber" type="String" length="50" />
    <property name="FLegalName" type="String" length="50" />
    <property name="FDateAdded" type="DateTime" />
    <property name="FAddedBy" type="String" length="50" />
    <property name="FDateModified" type="DateTime" />
    <property name="FModifiedBy" type="String" length="50" />
    <property name="FAccountNo" type="Double" precision="53" />
    <property name="FDescription" type="String" length="100" />
    <property name="FTerms" type="Int32" precision="10" />
    <property name="F1099Box" type="Int16" precision="5" />
    <property name="F1099Type" type="String" length="15" />
    <property name="FTaxID" type="String" length="10" />
    <property name="FSSN" type="String" length="11" />
    <property name="FVendorNo" type="String" length="10" />
    <property name="FAccountNo2" type="Double" precision="53" not-null="false" />
    <property name="FIsUseAccountNo2" type="Boolean" not-null="true" />
    <many-to-one name="TAddres" class="TAddres" column="fAddressID" />
    <many-to-one name="TSCCompany" class="TSCCompany" column="fCompanyID" />
    <many-to-one name="TContact" class="TContact" column="fContactID" />
    <many-to-one name="TSCEnterprise" class="TSCEnterprise" column="fEnterpriseID" />
    <many-to-one name="TSCProperty" class="TSCProperty" column="fPropertyID" />
    <set name="TAPInvoices" table="tAPInvoice" inverse="true">
      <key column="fVendorID" />
      <one-to-many class="TAPInvoice" />
    </set>
    <set name="TBAChecks" table="tBACheck" inverse="true">
      <key column="fVendorID" />
      <one-to-many class="TBACheck" />
    </set>
    <set name="TAPRecurringInvoices" table="tAPRecurringInvoice" inverse="true">
      <key column="fVendorID" />
      <one-to-many class="TAPRecurringInvoice" />
    </set>
    <set name="TGLPostMasters" table="tGLPostMaster" inverse="true">
      <key column="fVendorID" />
      <one-to-many class="TGLPostMaster" />
    </set>
  </class>
</hibernate-mapping>

A: There are some solutions, from easy to hard -
1. Remove the <set> mappings, or create another entity without them.
2. Set all <set lazy="true">...</set> the fetch will occur only on accessing these properties.
3. Create a DTO (data transfer object) entity, a lite version, and use to NHibernate.Projections library to fetch properties selectively.
4. Set <set fetch="join">...</set> to fetch all data in one joined query, this might duplicate your records, so be careful.
And in general, NH separating the queries is not necessarily bad, JOIN on big tables can cause much bigger performance hit. Your issues might not be a mapping issue, it might be DB or code issue.


text:
Q: Trying to make an SQL connection with local database .mdf but I succeed to write the filename directory I have this line for the connection with my connection string
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=""C: \Users\BDV\Documents\Visual Studio 2015\Projects\Interface_notes\Interface_notes\Database1.mdf"";Integrated Security=True;Connect Timeout=30");

But I get this error :
Class System.String
Represents Text as a series of Unicode characters
Syntax Error, ',' expected

I think the problem is with the double quotation marks, but I can't figure out what I can do instead. Can someone help me with this? Thanks
    Unrecognized escape sequence

A: There are two errors in your connection string. One has been already explained to you. This is C# and you need to prefix your string with the verbatim character to avoid parsing error when your string contains a backslash. Also you should remove the double quote around your path. They are not needed here.
The second error is the missing backslash between the (LocalDB) and the instance name.
So you write
 SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;
 AttachDbFilename=C:\Users\BDV\Documents\Visual Studio 2015\Project\Interface_notes\
 Interface_notes\Database1.mdf;
 Integrated Security=True;Connect Timeout=30");

A: You can use verbatim string and remove double quote from inside :
Change it to
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)MSSQLLocalDB;
     AttachDbFilename=C:\Users\BDV\Documents\Visual Studio 2015\Project\Interface_notes\
     Interface_notes\Database1.mdf;
     Integrated Security=True;Connect Timeout=30");

A: Should be like
SqlConnection conn = new SqlConnection(@"Data Source=
(LocalDB)MSSQLLocalDB;AttachDbFilename=C:\Users\BDV\Documents\Visual Studio
2015\Projects\Interface_notes\Interface_notes\Database1.mdf;Integrated
Security=True;Connect Timeout=30");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typescript Error Property 'members' does not exist on type '{}' This piece of code has been working well until a few days ago when I upgraded angularfire and firebase:
From "angularfire2": "5.0.0-rc.4", to "angularfire2": "^5.1.0",
from "firebase": "4.8.0", to "firebase": "^5.5.7":
this.dataProvider.getGroup(this.groupId).snapshotChanges().subscribe((group) => {
  this.group = group.payload.val();
  this.groupMembers = null;
  // Get group members
  if (group.payload.val().members) {
    group.payload.val().members.forEach((memberId) => {
      this.dataProvider.getUser(memberId).snapshotChanges().subscribe((member) => {
        this.addOrUpdateMember(member);
      });
    });
    // Get user's contacts to add
    this.dataProvider.getCurrentUser().snapshotChanges().subscribe((account) => {
      if (account.payload.val().contacts) {

        //Delete log
        console.log('My contacts',account.payload.val().contacts);
        for (var i = 0; i < account.payload.val().contacts.length; i++) {
          this.dataProvider.getUser(account.payload.val().contacts[i]).snapshotChanges().subscribe((contact) => {
            // Only contacts that are not yet a member of this group can be added.

              contact = { $key: contact.key, ...contact.payload.val()};
              //Delete log
              console.log('Is contact',contact,' already added?',this.isMember(contact));
            if (!this.isMember(contact))
              this.addOrUpdateContact(contact);
          });
        }
        if (!this.contacts) {
          this.contacts = [];
        }
      } else {
        this.contacts = [];
      }
    });
  }
  this.loadingProvider.hide();
});

This is the getGroup() in the provider:
getGroup(groupId) {
    return this.angularfire.object('/groups/' + groupId);
}

It is bringing this error everywhere there is payload.val().someProperty in the project.

A: Here is how I get the data from firebase.
firebase.database().ref('/MyCustomFolder').once("value").then(snapshot => {
  let data = snapshot.val();
  console.log(data.customers);
});

I suggest trying the following:
this.dataProvider.getGroup(this.groupId).snapshotChanges().subscribe((group) => {
  let data = group.val();
  let payload = data.payload;
  if (payload.members) {
      /* do something */
  }

A: This is what I had to do to get it working:
this.dataProvider.getGroup(this.groupId).snapshotChanges().subscribe((group) => {
  let data: any = group.payload.val();
  if (data.members) {
      /* do something */
  }

So apparently I had to include : any. Again, given that is was working before I made the upgrade - the experts will tell us more of the cause.


text:
Q: Is it possible to configure ConcurrentMap-based cache in Spring? The default implementation of the cache for Spring is a ConcurrentMap.
Using the default cache type, is it possible to configure a maximum size to avoid memory outages?
Are possible other kind of configurations for the ConcurrentMap-based cache in Spring?

A: The default cache type in Spring is suitable only for test and not for production. I suppose that your choice to do not looking for a more appropriate cache like Redis is due to for your use case a local cache is fine. If it is so I can suggest you to try caffeine, that support many parameters and with spring boot the configuration is very simple. The code below is taken from teh official spring boot configuration
spring.cache.cache-names=cache1,cache2
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s

I hope that this can help you


text:
Q: How do I make a DNS "switch" batch file I'm trying to make a batch file that sets my DNS settings to local host if they are something else, and automatic if they are localhost. What I made so far is:
set var=1

if "%var%" == "1"
(
netsh interface ipv4 add dnsserver "Wi-Fi" address=127.0.0.1 index=1
set var=2
)

if "%var%" == "2"
(
netsh interface ip set dns "Wi-Fi" dhcp
set var=1
)

pause

Clearly, the variables are not permanent and don't "save". That's problem number 1. However, this script won't even change it to the localhost address. Additionally, if it did work the script has the clear setback of not detecting if the DNS settings have been changed by some other mean. I'm stuck, as my google-fu is not up to the challenge of figuring out what I'm doing wrong.

A: The opening parenthesis in the if command must be in the same line that the if command
No, environment variables are not "saved". Each process has its own copy of the environment variables, and changes made from one process are not visible from the others. The value in the variable remains as long as the process that sets it, or until the process removes its value. To persist the variable you need to explicitly save it to the registry (see setx /?) or to a file (that you will later have to read).
And, your code has a logic error. in batch files, code is executed from one line to the next unless something change it, so
if %var%==1 (
    change to state 1
    set var=2
)
if %var%==2 (
    change to state 2
    set var=1
)

There is nothing preventing the execution leaving the first if enter the second one. When this code executes, it will always change to state 2.
It should be easier to detect the current state and then change to the other
netsh interfave ipv4 show dnsservers "Wi-Fi" | find "DHCP" > nul
if errorlevel 1 (
    netsh interface ipv4 set dnsservers "Wi-Fi" dhcp
) else (
    netsh interfave ipv4 add dnsservers "Wi-Fi" address=127.0.0.1 index=1
)

The first netsh command reads the current configuration and the find searchs for the string "DHCP". If it is not found  (errorlevel==1) change configuration to dhcp, else (see the parenthesis placement, see here) change configuration to local dns server


text:
Q: Why does pythons slice indexing give counter intuitive results? If I have a 2D list in python Data and I want to create a slice of that 2D list, where I select all the elements from the first index and a single on from the second.
eg.
Data = [[a,b,c],[d,e,f],[h,i,g]]

and I want the list;
raw_data = [b,e,i]

Why does doing something like;
raw_data = Data[:][1]

not give the desired output?
I have specified the whole first index and the 1 index for the second.
Instead I get the output that is;
raw_data = [d,e,f]

Which is what I would expect to get from;
raw_data = Data[1][:]

raw_data = [d,e,f]

So;
Data[1][:] = Data[:][1]

Which is not compatible with my mental model of how lists work in python.
Instead I have to use a loop to do it;
raw_data = []

for i in xrange(0,len(Data),1):
       raw_data.append(Data[i][1])

So my question is, can anyone explain why Data[1][:] = Data[:][1] ?
Thanks for reading!

A: lst[:] has no explicit start an no explicit end, so according to the Python documentation, it will return a copy of the list starting at the start and ending at the end of the list. In other words, it will return a copy of same list you have before. So:
>>> Data = [['a','b','c'],['d','e','f'],['h','i','g']]
>>> Data[:]
[['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'i', 'g']]

So when you say Data[:], that will evaluate to the same as a copy of Data, meaning that Data[:][1] essentially is just Data[1], which is [d,e,f]
If you do it the other way:
>>> Data[1]
['d', 'e', 'f']
>>> Data[1][:]
['d', 'e', 'f']

You get the second element in data, [d,e,f], then you use that same list slicing syntax as before to get that same list again.
To get what you want, I'd use a list comprehension:
>>> [x[1] for x in Data]
['b', 'e', 'i']

Simple as that.

A: Vanilla Python doesn't have two dimensional arrays, but it does allow for extensions to implement them. You have a list of lists, which is somewhat different.
The solution to your problem is to use numpy which does have a 2d array type. You can then say data[:,1]
Why your example doesn't work as you expect: data[:] means "a copy of data" and so data[:][1] means the index 1 element of the copy of data, which is [d,e,f]

A: It's pretty obvious if you go through what's happening from left to right.
raw_data = Data[:]

will give you the entirety of Data, so the whole list of lists: [[a,b,c],[d,e,f],[h,i,g]]
raw_data = Data[:][1]

will then give you the element at index 1 in this list, which is [d,e,f].
On the other hand,
    raw_data = Data[1]
will return the element at position 1 in data, which is also [d,e,f].
[:] on this object will again return itself in its entirety.
What you are trying to do is best done with a list comprehension, such as:
raw_data = [x[1] for x in Data]

This will give you list of all second elements in all lists in Data.


text:
Q: Chrome not handling chunked responses like Firefox, Safari I have a test node server that is sending chunked responses every few two seconds with the following headers:
response.setHeader('Content-Type', 'text/plain')
response.setHeader('Transfer-Encoding', 'chunked')

Every two seconds, I write out to the response:
response.write('Hello World');

When I do a curl on the endpoint, I get a chunk back every two seconds:
Hello World
(wait two seconds)
Hello World
(wait two seconds)
Hello World

It works like it's supposed to in curl.
For my Javascript on the client side, I set up a new XMLHttpRequest and assign a function to print out its responseText for the onprogress event.
Here is where the implementation seems to differ across browsers.
In Firefox and Safari, I get similar behavior as when I curl. An onprogress event fires for each "Hello World".
In Chrome, an onprogress event fires only when all of chunks have been received and I do a response.end() on the server side. And when I try to print out the responseText, only an empty string prints out.
Here is what the client-side code looks like:
var xhr = new XMLHttpRequest()
xhr.onprogress = function() {
  // Firefox, Safari prints out an accumulation of the chunks
  // Chrome prints out an empty string
  console.log(xhr.responseText);
}

A: Both Chrome and IE "sniff" the data (the first 256 bytes I believe) in order to detect the mime type. Use this to disable that behavior:
response.setHeader('X-Content-Type-Options', 'nosniff');


text:
Q: code that may not be directly parallelized by OpenMP code that may not be directly parallelized by OpenMP
Working on autoparallelizer and looking for benchmarks that may not be directly parallelized by OpenMP ( "directly parallelized" meaning: to create parallel executable without modifying the code, just by specifying proper OpenMP directives ).
Being on the subject, is it possible to parallelize the following code using OpenMP?
1.
double a[ARRAY_DIM], c[ARRAY_DIM];
  .
double ret;
ret = 0.;
for ( i = 0; i < ARRAY_DIM; i++ ) {
  c[i] = exp( ret );
  ret += a[i];
}
return ret;

2.
double a[ARRAY_DIM], c[ARRAY_DIM];
   .
double ret;
ret = 0.;
for ( i = 0; i < ARRAY_DIM; i++ ) {
  if ( a[i] > 0.01 ) {
    ret = c[i];
  }
}
return ret;

A: Code example 1 can be parallelized with OpenMP using a prefix sum solution.
For code example 2 I have two solutions in the code bellow called foo1 and foo2.  The function foo1 is easier to implement but is probably much less efficient if a[i] > 0.01 is frequently true. For example if it's always true then it has to write to ret every iteration in order which kills parallelization. For the function foo2 it only has to write in order per thread and not per iteration and since the number of iterations is much greater than the number of threads this is much more efficient.
#include <omp.h>
#include <stdio.h>
#define ARRAY_DIM 1000
double a[ARRAY_DIM], c[ARRAY_DIM];

double foo1() {
  double ret = 0;
  #pragma omp parallel for ordered schedule(static)
  for (int i = 0; i < ARRAY_DIM; i++) {
    if ( a[i] > 0.01 ) {
      #pragma omp ordered
      ret = c[i];
    }
  }
  return ret;
}

double foo2() {
  int k = -1;
  #pragma omp parallel
  {
    int k2 = -1;
    #pragma omp for schedule(static)
    for (int i = 0; i < ARRAY_DIM; i++) if ( a[i] > 0.01 ) k2 = i;
    #pragma omp for schedule(static) ordered
    for(int i=0; i<omp_get_num_threads(); i++)
      #pragma omp ordered
      if(k2 >= 0) k = k2;
  }
  return c[k];
}

int main(void) {
  for(int i=0; i<ARRAY_DIM; i++) a[i] = 1;
  for(int i=0; i<ARRAY_DIM; i++) c[i] = i;
  printf("%f\n", foo1());
  printf("%f\n", foo2());
}


text:
Q: Group the data of a table based on the date and build the multicolumns table for values in MYsql I was really stuck in this SQL program for more than a week.
I have a table that has three columns, one column shows the ids, one shows the date, and one shows the temperature.  Here is the code for the table:
Create table  temperature (id int, date varchar(255), temperature float(2, 1));

 insert into temperature (id, date, temperature) values ('1', '2012-01-01 6:00:00',  '8.9');
 insert into temperature (id, date,  temperature) values ('1', '2012-01-01 6:15:00',  '8.5');
 insert into temperature (id, date,  temperature) values ('1', '2012-01-01 6:30:00',  '6.2');
 insert into temperature (id, date,  temperature) values ('1', '2012-01-01 6:45:00',  '8.6');
 insert into temperature(id, date,  temperature) values ('3', '2012-01-02 6:00:00',  '9.1');
 insert into temperature (id, date,  temperature) values ('3', '2012-01-01 6:15:00',  '8.9');
 insert into temperature (id, date,  temperature) values ('4', '2012-01-01 6:00:00',  '8.5');
 insert into temperature (id, date,  temperature) values ('4', '2012-01-01 6:15:00',  '6.2');
 insert into temperature (id, date,  temperature) values ('4', '2012-01-01 6:30:00',  '8.6');
 insert into temperature (id, date,  temperature) values ('2', '2012-01-01 6:00:00',  '9.1');
 SELECT * FROM temperature;

And here is the figure of table:

Each row has a very specific time. I want to show the temperature of each id and each time slot in one column.
For example, for id=1, we have four temperatures. Then we have 4 value and put them in order in the val1-val4.  for id=3, we have two day with one numbers, for each day we consider one list, and id=4 we have three numbers in one day and for id=2 we have only one number for one day.
The maximum length of the values is 4 (in my real application is 96).
Finally, I want this table (there is a typo in the figure, val2 for the second id=3 should be 8.9):

I have used the group_concat, however, it saves them as a string. Besides I am using date_format(from_unixtime(date), '%Y-%m-%d')To change the date to YYYY-MM-DD. The code I am using is
   SELECT id,
          date_format(from_unixtime(date), '%Y-%d-%m') as date,
          GROUP_CONCAT(value) as Value group by id, date
    FROM temperature;

Note: In my real database, the maximum length of the value is 96 and I have more then 10 Million rows,  and it is not efficient to use the CASE and WHEN.

A: If your MySQL version supports windows function you could use:
with cte as (
select id, date, temperature,row_number() over(partition by id order by `date`) rownum
from temperature
)
select id,date(`date`),max(case when rownum=1 then cte.temperature else null end) as val1,
                       max(case when rownum=2 then cte.temperature else null end) as val2,
                       max(case when rownum=3 then cte.temperature else null end) as val3,
                       max(case when rownum=4 then cte.temperature else null end) as val4
from cte
group by id,date(`date`);

Demo


text:
Q: Should the comma in a compound predicate be omitted if the sentence starts with a quotation? In the following sentence, should the comma be omitted?

"Come in!" she said, and opened the door.

My spell checker insists that this is "an unnecessary comma in a compound predicate", but removing the comma makes the sentence seem wrong to me. I searched the web and found multiple pages confirming the rule about omitting commas in compound predicates, but none had examples that contained a quotation. On the other hand, Googling for "hello i said and" (in quotes) yielded multiple examples where the comma was not omitted.

A: Use of punctuation marks is determined by style sheets. With regard to punctuation, spell-checkers are a form of style sheet that you are free to ignore. Because I find it natural to insert a pause after "said" when reading the sentence as written aloud, I'd normally follow the cadence of spoken English by inserting a comma, just as you have done. (Of course, I would not do so if writing for a publication with a required style sheet that prohibited a comma here.)
With that said, what your spell-checker has done is to alert you that the sentence as written is confusing. The word order seems to imply that she said to come in before she opened the door. If that is the odd situation being described, then it would be much clearer to say "'Come in!' she said before even opening the door." If the more normal situation obtained where the invitation to enter occurred after the door was open, then it would be clearer to say "'Come in!' she said after opening the door."
When a spell-checker makes a suggestion, you may not like the suggestion, but you may decide that some other alteration is advisable.


text:
Q: How do I make an Image in Swift the same height as the text next to it? I'm brand new to Swift and am making an iOS Minesweeper app. At the top of the screen I want to have an image of a bomb next to a Text() object displaying the number of bombs remaining.
I'd like to have the image and/or HStack resize to whatever the height of the adjacent text is without having to hard-code it's dimensions.
Can/how this be achieved?
The code so far looks like this:
HStack(alignment: .center, spacing: 10) {
    Image("top_bomb")
        .resizable()
        .aspectRatio(contentMode: .fit)
    Text(String(game.bombsRemaining))
        .font(.system(size: 30, weight: .bold, design: .monospaced))
}
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.1, alignment: .trailing)

And it looks like:

A: You just need to fix it by size, like
HStack(alignment: .center, spacing: 10) {
    Image("top_bomb")
        .resizable()
        .aspectRatio(contentMode: .fit)
    Text(String(game.bombsRemaining))
        .font(.system(size: 30, weight: .bold, design: .monospaced))
}
.fixedSize()                                        // << here !!
.frame(maxWidth: .infinity, alignment: .trailing)   // << !!

Note: also pay attention that you don't need to hardcode frame to screen size

A: @State var labelHeight = CGFloat.zero

HStack(alignment: .center, spacing: 10) {
    Image("top_bomb")
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(maxHeight: labelHeight)
    Text(String(game.bombsRemaining))
        .font(.system(size: 30, weight: .bold, design: .monospaced))
        .overlay(
            GeometryReader(content: { geometry in
                Color.clear
                    .onAppear(perform: {
                        self.labelHeight = geometry.frame(in: .local).size.height
                    })
            })
        )
}
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.2, alignment: .trailing)


text:
Q: Optimizing a large MySQL query Today I was told by my hosting provider that my database must be blocked immediately. I have a query that causes huge load on the server. Do you know how can I optimize my query just to make the server less loaded?
SELECT `users`.`id`,
       `why_me`,
       `created`,
       `thumbnail`,
       `rating_date`,
       CONCAT(first_name, ' ', last_name) AS name,
       SUBSTRING(why_me, 1, 27) as subwhy,
       COUNT(`rating_date`) AS total,
       MAX(`rating_date`) AS maxrate
  FROM (`user_profiles`)
  LEFT OUTER JOIN `rates` ON `user_profiles`.`id`=`rates`.`user_id`
  JOIN `users` ON `user_profiles`.`user_id`=`users`.`id`
  WHERE `users`.`activated` =  '1'
      AND `last_name` != ""
      AND `first_name` != ""
      AND  concat_ws(' ', first_name, last_name) COLLATE UTF8_GENERAL_CI  LIKE '%%'
  GROUP BY `user_profiles`.`user_id`
  ORDER BY `total` desc

I'd appreciate any help from you. Thanks!

A: AND  concat_ws(' ', first_name, last_name) COLLATE UTF8_GENERAL_CI  LIKE '%%'

has no effect but is expensive (long running). It scans all the rows one-by-one without returning anything usefull. Remove!
Log in into phpmyadmin and run this query with "EXPLAIN" prepended, i.e. "EXPLAIN SELECT users...".
Post the result. It will show us if SQL can directly adress the required rows, or if it searching them one-by-one. Look out for the row used keys: if it´s empty, you need additioanl indeces:
1) Make sure you have an index on every column used for the joins, i.e. rates.user_idand user_profiles.user_id.
2) Make sure you have indeces on everything used for the where part with a high cardinality, i.e. first_name and last_name.
3) Even better: Create an index over 3 columns: activated,first_name,last_name
4) The GROUP and ORDER BY are causing the buildt of a temporary table. Can you port some of this logic into PHP?
5) Cache the result. That´s nothing to be done in real time!


text:
Q: What are the "proper" names for Stack Exchange sites? Just curious. What are the "official" names for Stack Exchange sites?
I ask because I notice a discrepancy for certain sites. For instance https://codegolf.stackexchange.com/ is called Programming Puzzles & Code Golf in many places, but Code Golf in others, so I don't know what the "real" name is.
If, as I fear, those designations are supposed to be the same, and there is a mismatch somewhere, does that mean the names are stored in more than one place in the database? That would be a horrible thought! Or am I simply missing something?

A: I guess it depends a little what you mean by "proper".   That said:

*

*Every site* has a "short name"  that is in its url, preceding ".stackechange.com", ("gaming", "money", "diy"etc.) and which is used in most of the "official" records

*Some sites also have a longer or more boutique name that is used in the site's header ("Arqade", "Personal Finance and Money", "Home Improvement", etc.)

EDIT: Having read the comments, I'm not sure there's a definitive answer here.
Internally, people will say both "Gaming" and "Arqade".  Similarly, I tend to call the Home Improvement site "DIY", but others call it "Home Improvement", which is probably closer to its "proper" name.  I think some of the confusion stems from the fact that some sites have boutique names, while others don't.


text:
Q: Android, how to use DexClassLoader to dynamically replace an Activity or Service I am trying to do something similar to this stackoverflow posting. What I want to do is to read the definition of an activity or service from the SD card. To avoid manifest permission issues, I create a shell version of this activity in the .apk, but try to replace it with an activity of the same name residing on the SD card at run time.  Unfortunately, I am able to load the activity class definition from the SD card using DexClassLoader, but the original class definition is the one that is executed.  Is there a way to specify that the new class definition replaces the old one, or any suggestions on avoiding the manifest permission issues without actually providing the needed activity in the package?  The code sample:
    ClassLoader cl = new DexClassLoader("/sdcard/mypath/My.apk",
            getFilesDir().getAbsolutePath(),
            null,
            MainActivity.class.getClassLoader());

    try {
        Class<?> c = cl.loadClass("com.android.my.path.to.a.loaded.activity");
        Intent i = new Intent(getBaseContext(), c);
        startActivity(i);
    }
    catch (Exception e) {

Intead of launching the com.android.my.path.to.a.loaded.activity specified in /sdcard/mypath/My.apk, it launches the activity statically loaded into the project.

A: Starting an Activity through DexClassLoader will be very tricky, because you didn't install the APK, and so there is nothing to handle your Intent.
You should have the same activity class in your platform APK and declare it in AndroidManifest.xml.  Then, you should change the current ClassLoader to your desired DexClassLoader.  As a result, it will start your plugin APK.  (Note: "platform APK" refers to the app that is already installed in the phone, whereas "plugin APK" refers to the apk file saved in your SD card.)
The platform's application should look something like this:
public static ClassLoader ORIGINAL_LOADER;
public static ClassLoader CUSTOM_LOADER = null;

@Override
public void onCreate() {
    super.onCreate();
    try {
        Context mBase = new Smith<Context>(this, "mBase").get();

        Object mPackageInfo = new Smith<Object>(mBase, "mPackageInfo")
                .get();
        //get Application classLoader
        Smith<ClassLoader> sClassLoader = new Smith<ClassLoader>(
                mPackageInfo, "mClassLoader");
        ClassLoader mClassLoader = sClassLoader.get();
        ORIGINAL_LOADER = mClassLoader;

        MyClassLoader cl = new MyClassLoader(mClassLoader);
        //chage current classLoader to MyClassLoader
        sClassLoader.set(cl);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

class MyClassLoader extends ClassLoader {
    public MyClassLoader(ClassLoader parent) {
        super(parent);
    }

    @Override
    public Class<?> loadClass(String className)
            throws ClassNotFoundException {
        if (CUSTOM_LOADER != null) {
            try {
                Class<?> c = CUSTOM_LOADER.loadClass(className);
                if (c != null)
                    return c;
            } catch (ClassNotFoundException e) {
            }
        }
        return super.loadClass(className);
    }
}

For more code, you can visit https://github.com/Rookery/AndroidDynamicLoader
I'm reading the Android source code in order to find a more elegant method to implement this feature.  If you have any idea, feel free to contact me.


text:
Q: constrain the initial and final values of a GEKKO ```Var``` to a data-based curve I am trying to solve a low thrust optimal control problem for Earth orbits, i.e. going from one orbit to another. The formulation of the problem includes six states (r_1, r_2, r_3, v_1, v_2, v_3) and 3 controls (u_1, u_2, u_3) with a simplified point model of gravity. When I specify the full initial state and half of the final state, the solver converges and yields a good solution. When I try the full final state, the problem is over constrained.
My thought on how to remedy this is to allow the trajectory to depart the initial orbit at any point along the orbital curve and join the final orbit an any point along the final orbital curve, giving it more degrees of freedom. Is there a way to constrain the initial and final values of all 6 states to a cspline curve? This is what I have tried so far:
m = GEKKO(remote=True)
m.time = np.linspace(0, tof, t_steps)

theta_i = m.FV(lb = 0, ub = 360)
theta_f = m.FV(lb = 0, ub = 360)

rx_i = m.Param()
ry_i = m.Param()
rz_i = m.Param()

vx_i = m.Param()
vy_i = m.Param()
vz_i = m.Param()

rx_f = m.Param()
ry_f = m.Param()
rz_f = m.Param()

vx_f = m.Param()
vy_f = m.Param()
vz_f = m.Param()

m.cspline(theta_i, rx_i, initial.theta, initial.r[:, 0])
m.cspline(theta_i, ry_i, initial.theta, initial.r[:, 1])
m.cspline(theta_i, rz_i, initial.theta, initial.r[:, 2])

m.cspline(theta_i, vx_i, initial.theta, initial.v[:, 0])
m.cspline(theta_i, vy_i, initial.theta, initial.v[:, 1])
m.cspline(theta_i, vz_i, initial.theta, initial.v[:, 2])

m.cspline(theta_f, rx_f, final.theta, final.r[:, 0])
m.cspline(theta_f, ry_f, final.theta, final.r[:, 1])
m.cspline(theta_f, rz_f, final.theta, final.r[:, 2])

m.cspline(theta_f, vx_f, final.theta, final.v[:, 0])
m.cspline(theta_f, vy_f, final.theta, final.v[:, 1])
m.cspline(theta_f, vz_f, final.theta, final.v[:, 2])

r1 = m.Var(rx_i)
r2 = m.Var(ry_i)
r3 = m.Var(rz_i)

r1dot = m.Var(vx_i)
r2dot = m.Var(vy_i)
r3dot = m.Var(vz_i)

u1 = m.Var(lb = -max_u, ub = max_u)
u2 = m.Var(lb = -max_u, ub = max_u)
u3 = m.Var(lb = -max_u, ub = max_u)

m.Equation(r1.dt() == r1dot)
m.Equation(r2.dt() == r2dot)
m.Equation(r3.dt() == r3dot)

r = m.Intermediate(m.sqrt(r1**2 + r2**2 + r3**2))
v = m.Intermediate(m.sqrt(r1dot**2 + r2dot**2 + r3dot**3))

m.Equation(-mu*r1/r**3 == r1dot.dt() + u1)
m.Equation(-mu*r2/r**3 == r2dot.dt() + u2)
m.Equation(-mu*r3/r**3 == r3dot.dt() + u3)

m.fix_final(r1, rx_f)
m.fix_final(r2, ry_f)
m.fix_final(r3, rz_f)

m.fix_final(r1dot, vx_f)
m.fix_final(r2dot, vy_f)
m.fix_final(r3dot, vz_f)

m.Minimize(m.integral(u1**2 + u2**2 + u3**2))

m.options.IMODE = 6
m.options.solver = 3
#m.options.ATOL = 1e-3
m.options.MAX_ITER = 300
m.solve(disp=True)    # solve

With cspline, I am trying to allow GEKKO to pick a fixed value of the true anomaly (the parameter that determines how far along the orbit you are) from data that I have generated about the states at sampled true anomalies that would have associated position and velocity states. Any help would be much appreciated!
SOLUTION:
I implemented the end constraints as "soft constraints", i.e. quantities to be minimized, instead of hard constraints which would use fix_final. Specific implementation is as follows.
final = np.zeros(len(m.time))
final[-1] = 1
final = m.Param(value=final)

m.Obj(final*(r1-final_o.r[0, 0])**2)
m.Obj(final*(r2-final_o.r[0, 1])**2)
m.Obj(final*(r3-final_o.r[0, 2])**2)

m.Obj(final*(r1dot-final_o.v[0, 0])**2)
m.Obj(final*(r2dot-final_o.v[0, 1])**2)
m.Obj(final*(r3dot-final_o.v[0, 2])**2)

final makes the solver only consider the last item (the end boundary) when multiplied.

A: It is generally much harder for an optimizer to exactly reach a fixed endpoint, especially when it depends on a complex sequence of moves. This often leads to infeasible solutions. An alternative is to create a soft constraint (objective minimization) to penalize deviations from the final trajectory. Here is an example that is similar:

import matplotlib.animation as animation
import numpy as np
from gekko import GEKKO

#Defining a model
m = GEKKO()

#################################
#Weight of item
m2 = 1
#################################

#Defining the time, we will go beyond the 6.2s
#to check if the objective was achieved
m.time = np.linspace(0,8,100)
end_loc = int(100.0*6.2/8.0)

#Parameters
m1a = m.Param(value=10)
m2a = m.Param(value=m2)
final = np.zeros(len(m.time))
for i in range(len(m.time)):
    if m.time[i] < 6.2:
        final[i] = 0
    else:
        final[i] = 1
final = m.Param(value=final)

#MV
ua = m.Var(value=0)

#State Variables
theta_a = m.Var(value=0)
qa = m.Var(value=0)
ya = m.Var(value=-1)
va = m.Var(value=0)

#Intermediates
epsilon = m.Intermediate(m2a/(m1a+m2a))

#Defining the State Space Model
m.Equation(ya.dt() == va)
m.Equation(va.dt() == -epsilon*theta_a + ua)
m.Equation(theta_a.dt() == qa)
m.Equation(qa.dt() == theta_a -ua)

#Define the Objectives
#Make all the state variables be zero at time >= 6.2
m.Obj(final*ya**2)
m.Obj(final*va**2)
m.Obj(final*theta_a**2)
m.Obj(final*qa**2)

m.fix(ya,pos=end_loc,val=0.0)
m.fix(va,pos=end_loc,val=0.0)
m.fix(theta_a,pos=end_loc,val=0.0)
m.fix(qa,pos=end_loc,val=0.0)
#Try to minimize change of MV over all horizon
m.Obj(0.001*ua**2)

m.options.IMODE = 6 #MPC
m.solve() #(disp=False)

This example uses a combination of soft and hard constraints to help it find the optimal solution.


text:
Q: Using both list navigation and tabs with ActionBarSherlock? I'm looking through the ActionBarSherlock samples demo, and I see that the List Navigation and the Tab Navigation both make use of the ActionBar's setNavigationMode method.  This tells me that you can only have one or the other.  If I want the user to have list navigation to move around between activities but I want some activities to have tabs, is there a different way to add tabs than via navigation mode?  Is it against ActionBar design guidelines to use both?  I don't look at tabs and consider this to be a navigation feature, so I find it odd that you get one or the other.

A:
This tells me that you can only have one or the other

Correct. Bear in mind that with action bar tabs, Android will convert you to list navigation, on its own, in certain configurations, whether you like it or not.

If I want the user to have list navigation to move around between activities but I want some activities to have tabs, is there a different way to add tabs than via navigation mode?

You can use a ViewPager with PagerTabStrip or the tab flavor of ViewPagerIndicator.
Or, you can go retro and use TabHost and TabWidget.

Is it against ActionBar design guidelines to use both?

The design guidelines refer to them as separate options for "View Controls". More importantly, given the automatic conversion of tab navigation to list navigation, it would be seriously confusing for the action bar to have two Spinners' worth of navigation choices.


text:
Q: Probability Density Function of Difference of Minimum of Exponential Variables I have a question regarding the probability distribution of the difference of two random variables.
Suppose we have $n$ exponential random variables, and they are all independent and identically distributed with parameter $\lambda$. Then, suppose we define random variable $Y_i$ as the $i$-th smallest $X_k$. For example, $Y_1 = \min(X_1, X_2, \ldots, X_n)$. $Y_2$ is the second smallest $X$.
I understand the following two facts: 1) Exponential random variables are memoryless. That is, if $X$ is an exponential random variable, $P(X \geq t + t_0 | X \geq t_0) = P(X \geq t)$.
and 2) If $X_1, X_2, \ldots, X_k$ are independent, each with parameter $\lambda$, then the random variable $Y_1 = \min(X_1, X_2, \ldots, X_k)$ has the probability density function: $f(y_1) = k \lambda e^{-k \lambda y_1}$
Then, my question is: how do I get the probability density function of $Y_2 - Y_1$? $Y_2 - Y_1$ is the second smallest exponential random variable minus the smallest exponential random variable. I understand that the expected value of $(n-1)$ exponential random variables with the same parameter $\lambda$ is $\frac{1}{(n-1)\lambda}$ (since we can use fact 2 above and set the number of random variables to $k-1$), but I do not see how $E(Y_2-Y_1)$ equals that quantity.
I believe strongly that fact 1 is involved, but I do not see how $Y_2 - Y_1$ is related to $(Y_2 - Y_1 | Y_1 = y_1)$.
Thanks everyone.

A: A simple method is to compute the distribution of $(Y_1,Y_2)$. Pick some positive $y_1<y_2$. What does it take to know that $Y_1\in(y_1,y_1+\mathrm{d}y_1)$ and $Y_2\in(y_2,y_2+\mathrm{d}y_2)$? You have to choose:
(1) the rank of the smallest value, for which there exists $n$ possibilities,
(2) the rank of the second smallest value, for which there exists $n-1$ possibilities,
(3) that these two random variables are indeed in the intervals $(y_1,y_1+\mathrm{d}y_1)$ and $(y_2,y_2+\mathrm{d}y_2)$, which happens with respective probabilities $\lambda \mathrm{e}^{-\lambda y_1}\mathrm{d}y_1$ and  $\lambda \mathrm{e}^{-\lambda y_2}\mathrm{d}y_2$,
and (4) finally that the $n-2$ other random variables are greater than $y_2$, which happens with probability $\mathrm{e}^{-(n-2)\lambda y_2}$.
All this yields the probability density function of $(Y_1,Y_2)$ as
$$
n(n-1)\lambda^2 \mathrm{e}^{-\lambda y_1-(n-1)\lambda y_2}\mathbf{1}_{0<y_1<y_2}.
$$
From this, to compute the value of $E(Y_2-Y_1)$ is straightforward. For example, introducing $Z_2=Y_2-Y_1$, one sees that the probability density function of $(Y_1,Z_2)$ is
$$
n(n-1)\lambda^2 \mathrm{e}^{-n\lambda y_1-(n-1)\lambda z_2}\mathbf{1}_{y_1>0}\mathbf{1}_{z_2>0}.
$$
This is a product distribution hence $Y_1$ and $Z_2$ are independent with well known distributions, exponential with parameters $n\lambda$ and $(n-1)\lambda$, respectively.


text:
Q: displaying month name chronologically for graphs in jupyter notebook I am creating a chart in jupyter notebook which displays fire factors sorted by month. however it is sorting months alphabetically and not chronologically, the ways I've tried don't seem to have any effect on the graph. I'm super new to this so would appreciate any help! I've also attached a screenshot of what the graph look like. along the x axis you can see the months.
import pandas as pd
import altair as alt
data = pd.read_csv('forestfires.csv')

new_order = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
data = data.reindex(new_order, axis=0)

alt.Chart(data).mark_circle().encode(
    alt.X('month:O',
          sort='ascending'),
    alt.Y('FFMC:Q'),
    alt.Size('ISI:Q')
)

A: I think problem is arising with reinexing.
Don't reindex and it should resolve the issue.
data = data.set_index('new_order', inplace=True)

A: oh I realised it can actually be done super simply:
alt.X('month:O',
title='months',
sort = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]), ... etc


text:
Q: Can a loop be considered a function on a basic level? If you go down to assembler level and basic CPU instructions, what is a function? A function is just some block of code that is surrounded by JMP (jump) instructions. So, instruction pointer (instruction that is currently executed) jumps from some other place in program to the start of a function, executes it's code, and then jumps somewhere else.
In this sense, a loop is definitely a function. Only slight difference is that it usually jumps to it's own beginning to check some condition and execute itself again, instead of jumping to some other place (usually place of its call).

A: The key aspect of a function (or procedure) is that when it is called, the address it is called from (return address) is recorded so the function can jump back to the caller when it finished.  Many processors have special instructions to perform these two common tasks.  For example, x86 has call and ret.
A loop does not generally do any of that.  Hence, it is not a function in this sense.

A: I think you're minimizing the dynamic nature of returning to its place of call.  I can agree that it's all branching, sure.  However, loops are not functions.
We can't call a loop from multiple other code locations, but we can call a function from anywhere in the code and it will return to its caller, no matter who.
Loops can reference free/unbound variables, but functions can be parameterized, which is important as functions support multiple callers & call sites.
There's no such thing as a dynamic loop stack (loops nest statically), but there is a dynamic call stack and a dynamic call chain of arbitrary depth.


text:
Q: How to prefill Mobile Number, Type of business in stripe express onboarding? Can I prefill the Mobile Number? as I have prefilled the Email

Can I prefill the Type of business? as I have prefilled the Country

Unable to prefill phone number, Type of business in stripe onboarding express account. But other fields are prefilling except these fields.
I have referred:
https://stripe.com/docs/api/accounts/update?lang=java to update accounts API
    Map<String, Object> addressParams = new HashMap<>();
    addressParams.put("country", "AU");
    if (accountInfo.get("companyAddressLine1") != null)
    addressParams.put("line1", accountInfo.get("companyAddressLine1"));
    if (accountInfo.get("companyAddressLine2") != null)
    addressParams.put("line2", accountInfo.get("companyAddressLine2"));
    if (accountInfo.get("companyAddressCity") != null)
    addressParams.put("city", accountInfo.get("companyAddressCity"));
    if (accountInfo.get("companyAddressState") != null)
    addressParams.put("state", accountInfo.get("companyAddressState"));
    if (accountInfo.get("companyAddressPostalCode") != null)
    addressParams.put("postal_code", accountInfo.get("companyAddressPostalCode"));

    Map<String, Object> companyParams = new HashMap<>();
    companyParams.put("address", addressParams);
    if (accountInfo.get("companyPhone") != null)
    companyParams.put("phone", accountInfo.get("companyPhone"));
    if (accountInfo.get("abnNumber") != null)
    companyParams.put("tax_id", accountInfo.get("abnNumber"));
    if (accountInfo.get("companyName") != null)
    companyParams.put("name", accountInfo.get("companyName"));

    Map<String, Object> businessProfileParams = new HashMap<>();
     businessProfileParams.put("support_address", addressParams);
    businessProfileParams.put("product_description","test");

    Map<String, Object> params = new HashMap<>();
    params.put("business_type", "company");
    if (accountInfo.get("companyEmail") != null)
    params.put("email", accountInfo.get("companyEmail"));
    params.put("business_profile", businessProfileParams);
    params.put("company", companyParams);

    Account updatedAccount = account.update(params);

A: The phone and email input in the screenshot is used for Express authentication and is associated with the User on the account. The platform cannot pre-fill this User data. The phone & email which the you have pre-filled using the Accounts API is associated with the company/business on this account.
Yes, you should be able to prefill the type of business. I'd suggest retrieving the connected account to verify if the business_type has been set before creating the onboarding link.


text:
Q: NuGet - Error when generating nuspec file When I run nuget.exe pack for a project, I get the following error:
EXEC : warning : 1 issue(s) found with package 'Company.LibName'.

  Issue: Specify version of dependencies.
  Description: The version of dependency 'Newtonsoft.Json' is not specified.
  Solution: Specifiy the version of dependency and rebuild your package.

(Specify typo is actually in the message.)
The offending line in the .nuspec file is the last line below:
<dependencies>
  <group targetFramework="net45">
    <dependency id="Newtonsoft.Json" />

However, I don't want specify a version. And I didn't think I needed to, see documentation:
https://docs.nuget.org/create/nuspec-reference#specifying-dependencies-in-version-2.0-and-above
What's the deal?

A: I think its just a warning and to be ignored.
It seems it only warns for one package, so although it appears to have singled-out Newtonsoft.Json as needing a version, if I reorder the dependencies, it's always the first one in the list (without a version) that invokes the warning.


text:
Q: Bootstrap UI Pagination - current page is set to zero when DOM is loaded I am using Bootstrap UI Pagination to paginate search results page and also want to store query, current page and page size in URL so it can be shared by users:
http://localhost:39519/#?q=security&limit=10&page=2
The problem is that when I browse link that, the 2nd page is displayed but after a while (when DOM is loaded) current page get reset and first page is
displayed.
Here is plunker but I dont know how to simulate change in URL.
<uib-pagination ng-show="total" direction-links="false" boundarylinks="true" items-per-page="pageSize" total-items="total" ng-change="pageChanged()" ng-model="currentPage"></uib-pagination>

http://plnkr.co/edit/RhxoYOyDjwyoLbMOFtct?p=info


text:
Q: Changing the formatting of clicked text in a textblock I have a textBlock to which I've added some text e.g. as follows:
textBlock1.Inlines.Add(new Run("One "));
textBlock1.Inlines.Add(new Run("Two "));
textBlock1.Inlines.Add(new Run("Three "));

How can I add a click event that changes the color of the text of the inline that has been clicked?
e.g. if "One" is clicked I'd like it to have a red font; then if "Two" is clicked, I'd like "One" to be black again, and "Two" to be red, so that the color of the last word clicked is red.
I'm fairly new to programming with c# and wpf.
Thanks for your help

A: Something like this should do the trick
     public MainWindow()
    {
        InitializeComponent();
        textBlock1.Inlines.Add(new Run("One "));
        textBlock1.Inlines.Add(new Run("Two "));
        textBlock1.Inlines.Add(new Run("Three "));
    }

    private SolidColorBrush _blackBrush = new SolidColorBrush(Colors.Black);
    private SolidColorBrush _redBrush = new SolidColorBrush(Colors.Red);
    private Run _selectedRun;

    private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
    {
        var run = e.OriginalSource as Run;
        if (run != null)
        {
            if (_selectedRun != null)
            {
                _selectedRun.Foreground = _blackBrush;
                if (_selectedRun == run)
                {
                    return;
                }
            }
            run.Foreground = _redBrush;
            _selectedRun = run;
        }
    }

But you will have to handle click with "MouseDown" or "MouseUp" as Textblock does not have Click event
To color one at a certain index this is a quick example.
private void ColorInlineAtIndex(InlineCollection inlines, int index, Brush brush)
{
    if (index <= inlines.Count - 1)
    {
          inlines.ElementAt(index).Foreground = brush;
    }
}

Usage:
 ColorInlineAtIndex(textBlock1.Inlines, 2, new SolidColorBrush(Colors.Blue));

Find position:
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
    var run = e.OriginalSource as Run;
    if (run != null)
    {
        int position = (sender as TextBlock).Inlines.ToList().IndexOf(run);
    }
}


text:
Q: Nodejs zlib gunzip "invalid block type" error on Windows but not Mac here's my code, I am reading a bunch of file chunks, merging them together, and then gunzipping:
const decompress = (buffer) => new Promise((resolve, reject) => {
  zlib.gunzip(buffer, (err, decompressed) => {
    if (err) {return reject(err)}
    resolve(decompressed)
  })
})
const chunkFileNames = fs.readdirSync(chunksFolderPath)
let compressedFile = Buffer.from('')
for (const chunkFileName of chunkFileNames) {
  const chunkFilePath = path.join(chunksFolderPath, chunkFileName)
  const chunk = fs.readFileSync(chunkFilePath)
  compressedFile = Buffer.concat([compressedFile, chunk])
}
const decompressedFile = await decompress(compressedFile) // throws

Error is

Error: invalid block type
at Zlib.zlibOnError [as onerror] (zlib.js:170:17)

I am compressing and chunking the file on linux. When I run the same code on mac/linux it decompresses without error. But when I run the same code on windows I get that error.
What could be the problem? How do I debug this? The chunk files appear to be unchanged when I move the folder to my windows VM, but maybe windows changes them somehow?

A: You may need to specify the 'binary' encoding. Problems like this on Windows smell of end-of-line conversions.


text:
Q: Replace the text using jquery closest The thing I have tried so far is

This is what I want to display inside "ppname"
HO

Just for test

Not

The Jquery
$('a[code]').click(function () {
    $('.ppcode').html($(this).attr('code'));
    $('.ppname').html($(this).closest("h3").html());
    $('.pp').show();
});
$('span.close').click(function () {
   $('.pp').hide();
  });

The text in attribute code is displaying inside the div with class ppcode but the text in h3 is not displaying inside div with class ppname.
Thanks

A: Use prev instead of closest to display the sentence This is what I want to display inside "ppname" in the ppname-container:
$('.ppname').html($(this).prev().html());


text:
Q: Tune Dual Boot with Windows 10 on separate drives I used various Ubuntu distribution via VirtualBox on my Windows 10 host and as I'm quite happy with Lubuntu 16.04.1, I wanted to give it a try and install it as my 2nd OS besides the existing Windows 10 (which has been upgraded from Windows 7, if that makes any difference). Therefore I got an extra SSD (sdc), and already installed it there (which gave me troubles too, because the installer didn't detect the new SSD so I had to care for partitions manually), but I'm not sure if everything is as it should be.
I am able to boot into Windows 10 and Lubuntu, but there are some (minor?) problems.
Problems

*

*Sometimes when I boot the computer, I end up in a grub command line instead of the menu to choose between Windows and Linux. When this happens, I reboot, check the boot order in BIOS (UEFI?), see that Ubuntu should be booted before Linux, exit without saving (and reboot), and then it takes me to grub's selection screen as expected.

*In BIOS (UEFI?) there are 2 boot entries for ubuntu, but I cannot find any difference between those.

*I tried to run Boot-Repair, but it asks me to deactivate Secure Boot, which I don't want to (and shouldn't be needed as far as I've found out).

After all,  I still want to be able to boot into Windows 10, preferably without grub (but not a must), when I boot the SSD with Windows 10 (sdb) (or when the extra SSD with Lubuntu (sdc) is disconnected) and I want be able to choose between Windows 10 and Lubuntu on startup when I boot the SSD with Lubuntu (sdc), which will be the default. I also want to keep UEFI and Secure Boot activated.
It'd be no problem to reinstall/remove Lubuntu or even remove all partitions from sdc, but the Windows 10 installation (sdb+sda) must stay functional.
Hard Drives (via GParted)

*

*sda: 500 GB HDD, msdos (existing, for Windows 10 user data and other data)

*

*sda1: one big NTFS partition

*

*flags: boot

*Windows cannot run without this one because all user data is stored here (via symlink). This is because long time ago I only had a very small SSD and set it up that only the OS, but not the user directories are on the SSD. When I upgraded to the bigger SSD (sdb), I just cloned the small one and increased sdb3's partition size.

*sdb: 250 GB SSD, gpt (existing, for Windows 10)

*

*sbd1: 100 MB EFI fat32, EFI system partition, mounted to /boot/efi

*

*flags: boot, esp

*sbd2: 128 MB unknown, Microsoft reserved partition

*

*flags: msftres

*sbd3: ~ 240 GB NTFS, Windows 10 is installed here

*

*flags: msftdata

*sdb4: 450 MB NTFS, no more information what it is used for

*

*flags: hidden, diag

*sdc: 250 GB SSD, gpt (new, for Lubuntu)

*

*sdc1: ~240 GB ext4, Lubuntu 16.04.1 is installed here

*

*no flags

*sdc2: 4 GB swap

*

*no flags

Boot-Info (via Boot-Repair)
What bothers me here is that it finds a boot loader only on sda and not sdb where I expected it to be. But this might be because sda has a msdos partition table and the other two have gpt, but I don't know.
============================= Boot Info Summary: ===============================

 => Windows 7/8/2012 is installed in the MBR of /dev/sda.
 => No boot loader is installed in the MBR of /dev/sdb.
 => No boot loader is installed in the MBR of /dev/sdc.

sda1: __________________________________________________________________________

    File system:       ntfs
    Boot sector type:  Windows 7/2008: NTFS
    Boot sector info:  No errors found in the Boot Parameter Block.
    Operating System:
    Boot files:        /bootmgr /Boot/BCD

sdb1: __________________________________________________________________________

    File system:       vfat
    Boot sector type:  Windows 7/2008: FAT32
    Boot sector info:  No errors found in the Boot Parameter Block.
    Operating System:
    Boot files:        /EFI/Boot/bootx64.efi /EFI/ubuntu/MokManager.efi
                       /EFI/ubuntu/fwupx64.efi /EFI/ubuntu/grubx64.efi
                       /EFI/ubuntu/shimx64.efi
                       /EFI/Microsoft/Boot/bootmgfw.efi
                       /EFI/Microsoft/Boot/bootmgr.efi
                       /EFI/Microsoft/Boot/memtest.efi

sdb2: __________________________________________________________________________

    File system:
    Boot sector type:  -
    Boot sector info:
    Mounting failed:   mount: unknown filesystem type ''

sdb3: __________________________________________________________________________

    File system:       ntfs
    Boot sector type:  Windows 7/2008: NTFS
    Boot sector info:  No errors found in the Boot Parameter Block.
    Operating System:
    Boot files:        /Windows/System32/winload.exe

sdb4: __________________________________________________________________________

    File system:       ntfs
    Boot sector type:  Windows 8/2012: NTFS
    Boot sector info:  No errors found in the Boot Parameter Block.
    Operating System:
    Boot files:

sdc1: __________________________________________________________________________

    File system:       ext4
    Boot sector type:  -
    Boot sector info:
    Operating System:  Ubuntu 16.04.1 LTS
    Boot files:        /boot/grub/grub.cfg /etc/fstab

sdc2: __________________________________________________________________________

    File system:       swap
    Boot sector type:  -
    Boot sector info:

If there is need for Drive/Partition Info or any other info from Boot-Repair, I can update this post.
Other system information

*

*Motherboard: Asus H87M-E

*Memory: 16 GB RAM


text:
Q: read ESRI FileGeoDataBase with ogrinfo / sql filter on date field I can read my FileGDB (ArcGIS 10.1) with GDAL-library (1.10) using ogrinfo and sql filtering datasets by FID
ogrinfo "...\test.gdb" -sql "SELECT edited FROM 'plz_simple_copy' WHERE fid = 1864" --debug on -dialect OGRSQL

or this way by OBJECTID
ogrinfo "...\test\plz.gdb" "plz_simple_copy" -where OBJECTID=1864

The result is:
using driver `FileGDB' successful.
Layer name: plz_simple_copy
Geometry: Multi Polygon
.....
plz (String) = 26452
quelle (String) = osm
osm_id (String) = -1187754
edited (DateTime) = 2013/07/09 17:34:49
Shape_Length (Real) = 0.401490815379519
Shape_Area (Real) = 0.00612509834536042

...but I need to filter the data by the date field "edited".
I tried a lot of variations e.g.
ogrinfo "...\test.gdb" "plz_simple_copy" -where edited = '2013/07/09 17:34:49'
ogrinfo "...\test.gdb" "plz_simple_copy" -where edited = '2013-07-09 17:34:49'
ogrinfo "...\test.gdb" "plz_simple_copy" -where "edited" = date '2013-07-09 17:34:49'

..  but I didn't get it.
Somebody has an idea how to solve that problem?
best greetings from Berlin
ralf

A: I also opened this thread in the ArcGIS Forum "File Geodatabase API" and got the answere there
http://forums.arcgis.com/threads/88662-read-ESRI-FileGeoDataBase-sql-filter-on-date-field
the right code has to be
ogrinfo "...\test.gdb" "plz_simple_copy" -where "edited = date '2013/07/09 17:34:49'"

maybe someone can need this, too


text:
Q: Connected Graph Proofs Let $G$ be a connected graph with $n$ vertices and $m$ edges.
a) Prove that $G$ contains at least $m-n+1$ distinct cycles.
My attempt: Induction on $m$
Base Case: $m=n-1$: $G$ is a tree. $m-n+1=m-1-n+1=0$ which follows since a tree has 0 cycles
Inductive Hypothesis: Assume that a connected graph with $n$ vertices and $m-1$ edges has at least $m-1-n+1=m-n$ distinct edges.
Inductive Step: Suppose $G$ is connected with $n$ vertices and $m$ edges.  Let $e$ be in a cycle of $G$.  Then $G-e$ is connected with $m-1$ edges. By the inductive hypothesis, $G-e$ at least has $m-n$ distinct cycles. So $G$ has at least $m-n+1$ distinct cycles.
I'm not to sure about the inductive step (specifically if I can conclude with the last line)
b) Prove that if $G$ is bipartite, then $G$ contains at least $3(m-n+1)+1$ distinct spanning trees.
I'm not too sure if I have the right approach to this but I prove with induction on $m$ again, and I get stuck on the inductive step.  I'm pretty sure I will have to use part a) in some way, but I can't see how.  Any hints would be very helpful

A: I think you have the right idea but trying to do it inductively might be making the problem trickier to work with.
Try this: Let $G$ be a connected (simple) graph with $n$ vertices and $m$ edges. Since $G$ is connected, $m\geq n-1$, so let $m = n-1 +k$ for some $k\in \mathbb{Z}_{\geq 0}$. Recall that any connected graph contains a spanning tree $T_0$ as a subgraph, which necessarily has $n-1$ edges and 0 cycles. Let $\{e_1, e_2, \ldots e_k \}$ denote the set of edges not in $T_0$.
Now think about what happens when we add $e_1 = (v_1,v_2)$ into $T_0$. Since $T_0$ is a spanning tree there exists a path from $v_1$ to $v_2$ in $T_0$. Therefore adding $e_1$ to this path will produce a cycle. Let $T_1$ denote the subgraph consisting of $T_0$ with $e_1$.
Now think about adding in $e_2$. You'll see that by the same argument we will produce at least one new cycle, and the resulting graph $T_2$ will have at least 2 cycles. Continuing in this way we see that $G$ itself must contain at least $k$ cycles, but $k = m -(n-1) = m-n+1$ as desired.
For part (b), part (a) tells you that you have at least $(m-n+1)$ cycles. To form a spanning tree, you essentially just have to remove an edge from each of those cycles. Think about how many ways you can do that (remember a bipartite graph has no odd cycles) and you should get your answer.


text:
Q: Inertial frame of reference with respect to vacuum Suppose, I am in an inertial frame of reference moving close to the speed of light. If I held a mirror in a direction of movement it would kick virtual particles from the vacuum into existence. Particles will draw some of the kinetic energy and I would feel a slight push on a mirror thus detecting movement in a certain direction, which I should not be able to do. Assumption that the only true inertial frame of reference is at rest with vacuum contradicts the statement that no privileged frame of reference exists.
What is the logical error I made?

A: Well, I was reffering to dynamic Casimir effect experiment for particle production from vacuum arxiv.org/pdf/1105.4714.pdf. After reading it more carefully I realized that it has nothing to do with uniformly moving mirrors.
The dynamic Casimir force arises as a result of Unruh radiation which is related to acceleration. Special relativity is saved :D :D


text:
Q: Can anyone sketch an outline of Iwaniec's proof for the upper bound regarding the Jacobsthal function? A proof by H. Iwaniec in 'On the problem of Jacobsthal, Demonstratio Math. 11, 225–231, (1978)' shows that: $$j(N) \ll \log^2 (N)$$
where $j(N)$ is the Jacobsthal function.
I am very interested in understanding the details of this proof.
Would anyone be able to provide a rough outline of the proof and suggest a good reference for understanding the theory behind Iwaniec's argument?

Edit: I changed the expression based on feedback.  $\log \log N$ was incorrect so I am changing it to $\log^2(N)$

A: What Iwaniec shows in that paper is that
$$
j(N)\ll\omega(N)^2\log^2\omega(N)
$$
where $\omega(N)$ is the number of distinct prime factors of $N$. As a result, if $N$ is less than $2\cdot3\cdot\dots\cdot p_{n+1}$ then $j(N)\ll n^2\log^2n.$
By the Prime Number Theorem, that product is $e^{(1+o(1))p_{n+1}}=e^{(1+o(1))n\log n}$ and the square of the logarithm of that quantity is asymptotic to $n
^2\log^2n$ which is just the quantity of Iwaniec.
The method of proof is the Iwaniec's shifted sieve, an improvement to the linear sieve ("inspired by the work of Halberstam and Richert", i.e., Mean value theorems for a class of arithmetic functions). I'm not familiar enough with sieve theory to give details.


text:
Q: How to load pages which are not intregrated in ACL of cakePHP I have implemented ACL using cakeDC plugin.
Basically i want to make an app where everyone can view all pages. Only register people can view admin panel. Currently My app loading Login page initially and after login i can view the content as i have add the bellow code into App controller.
class AppController extends Controller
{
    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler', [
            'enableBeforeRedirect' => false,
        ]);
        $this->loadComponent('Flash');

        $this->loadComponent('Acl', [
            'className' => 'Acl.Acl'
        ]);
        $this->loadComponent('CakeDC/Users.UsersAuth');
     }
}

Now only one path is excepted int the routes.php
$routes->connect('/', ['controller' => 'Articles', 'action' => 'index']);
My question is how can i load other Pages, Action,methods before ACL occurs?

A: In your Controller you make a function like this. This function can't include in ACL
public function beforeFilter() {

    $this->Auth->allow('controller' => 'Articles', 'action' => 'index']);

}


text:
Q: Polymer Change Events on Sub-Property Changes Polymer 1.0 supports binding to structured data using dot syntax as demonstrated below:
<template>
  <div>{{user.manager.name}}</div>
</template>

In the above example, is there a way to get a <<property>>-changed event on the user property itself when any of it's sub-properties change? Right now, although the binding does update the sub-properties of user, my user-changed event listener only catches changes to the user property itself and does not catch changes to sub-properties.
Do I have to manually configure listeners for every single sub-property of the user element in order to listen to those events?

A: It looks like you have to define a listener for every sub-property, though there is a shorter way to do it, by defining an observers array: Observing sub-property changes


text:
Q: get textbox text value and store in a variable in ironpython WFP I want to get the inputted text to the textbox to a variable but I am failing big time.
Uinsg Ironpython 2.7.9 .Net 4.0
class MyClass(Form):

def __init__(self):
    global PAM
    name = 0
    self.Text = 'Text Widget Demo'
    self.label = Label()
    self.label.Text = "This is text widget Demo"
    self.label.Location = Point(100, 150)
    self.label.Height = 50
    self.label.Width = 250
    self.textbox = TextBox()
    self.textbox.Text = str(PAM)
    self.textbox.Enabled = True
    self.textbox.Location = Point(50, 50)
    self.textbox.Width = 200
    self.Controls.Add(self.label)
    self.Controls.Add(self.textbox)
    #self.all_c.append(self.textbox.Text)
    PAM = self.textbox.Text
    self.but = Button()
    self.but.Text = 'Ok'
    self.but.Location = Point(75,75)
    self.but.Click += self.OnClick
    self.Controls.Add(self.but)
    return PAM

def OnClick(self,sender,args):
    MessageBox.Show(self.textbox.Text)
    #Close()
#def Close(self):
    #self.close()

#form = LabelDemoForm()
dapp.Run(MyClass())
Windows 10

A: Hi so I figure it out with dumb luck
it appears assigning a the value form the textbox has to be done after the click statement (this can be very wrong but it works)
so in the
def OnClick(self, sender, args):
        text_retrieve = self.textbox.Tex

and you can assign the value the user inputs to this variable "text_retrieve"


text:
Q: Display multiple rows one by one under same id from database I have a table hobbies tables that has multiple rows under parent ID. In my view, my records are displayed altogether. But I want to display these row records one-by-one or individually.
My Table:

Parent.php
class Parent extends Model
{
    public function feature()
    {
        return $this->hasMany(Feature::class, 'product_id');
    }
}

Feature.php
class Feature extends Model
{

    public function feat()
    {
        return $this->belongsTo(Parent::class);
    }
}

Controller.php
public function display($url)
{
    $parent = Parent::where('url', $url)->firstorfail();
    $feat = Feature::with(['feat','user'])->get();

    return view ('display', compact('parent', 'feat'));
}

display.blade.php
@foreach($feat as $show)
    col_name }}" src="{{url($show->col_img) }}"/>
@endforeach

I want to display like this

A: I assume that you want to get a parent (or is it a product) by the given url. In your view you want to display all features attached/related to/with this parent.
First of all, change your Models as shown below (assuming your Models are stored under app/:
class Parent extends Model
{
    public function features()
    {
        return $this->hasMany('App\Feature', 'product_id');
    }
}

class Feature extends Model
{
    public function parent()
    {
        return $this->belongsTo('App\Parent');
    }
}

Now it is enough to search for your parent in your controller:
public function display($url)
{
    $parent = Parent::where('url', $url)->firstorfail();
    $feature = Feature::where('parent_id', $parent->id)->first();
    return view ('display', ['parent' => $parent, 'feature' => $feature]);
}

Finally you can access your features in your template-file as shown below:
// Show your parent-information

{{ $parent->name }}

col_img }}" alt="{{ $feature->col_name }}">

I hope that this is what you were searching for!
To display random images at the top, middle and bottom of your page, you could use Laravel's array_random-function:
@php
    // store your features in a temporary variable
    $features = $parent->features;

    // collect feature and remove it from array
    $feature1 = array_random($features);
    array_forget($features, $feature1);
    $feature2 = array_random($features);
    array_forget($features, $feature1);
    $feature3 = array_random($features);
@endphp

col_img }}" alt="{{ $feature1->col_name }}">

col_img }}" alt="{{ $feature2->col_name }}">

col_img }}" alt="{{ $feature3->col_name }}">

I don't know if Laravel's array_random works this way . So maybe you have to remove the returned item another way.


text:
Q: It works fine on Jupyter but not in VSC I tried the following code in Jupyter and works fine. However, in VSC code I got this absurd error: invalid literal for int() with base 10.
code in VSC
the same code in Jupyter

A: The code is not the same.  keyword_to_csv is a global level functon in your jupyter notebook, and it's a class member in the VSC code.  The PROiBLEM here is that you have skipped a self parameter in all your class methods.  So, when you call tw.keyword_to_csv('Covid'), Python ends up passing tw as the first parameter, and "Covid" as the second parameter.  When you try to convert "Covid" to an integer, it unsurprisingly fails.
You need
    def keyword_to_csv(self, keyword, recent):

and the same for the rest of the class methods.


text:
Q: Mypy Flycheck Clears Errors On Unsaved File I am currently trying to port over my python enviornment to Doom Emacs from VSCode. One of the major features I want is type checking from MyPy. Doom Emacs' flycheck comes with MyPy as an option by default so I was going to use that.
My major issue with it though is that while it correctly lints saved files, as soon as I make any edits all linting help goes away and mypy will say that there are no errors until the next time I save. It would be okay if the linting didn't re run while I was editing, but its important for me that the errors don't just disappear.
Notably, when I use other checkers, such as flake or the default lsp, there is no such issue with linting disappear.
Does anyone know how to fix this?

A: Not a Doom Emacs user, but it sounds like it might be setting flycheck-check-syntax-automatically. Disable Doom's setting or customize it yourself to include "idle-change". For instance mine is (via C-h v flycheck-check-syntax-automatically):
flycheck-check-syntax-automatically is a variable defined in 'flycheck.el'.

Its value is (save idle-change new-line mode-enabled)

When Flycheck should check syntax automatically.

This variable is a list of events that may trigger syntax checks.
The following events are known:
...


text:
Q: JS API for embedding sheet in Qlik We can embed visuals of a sheet very easily, with:
const vis = await qlikApp.visualization.get('<visual_id>');
vis.show('<visual_container>');  // Renders visual in the given HTML container

But, I could not find any such API for embedding Qlik sheet.
In the docs, I only found embedding sheet by copy pasting iframe

A: I don't think its possible to embed the whole sheet using the  Visualization API. This API is targeting specifically visualizations (charts, tables etc.)
The only option I'm aware of is the iFrame (aka Single Interation API)
Seems that someone tried to "emulate" Qlik Sense sheet here. But it looks like this will display only the sheet objects (no selections bar for example).


text:
Q: Single signon betwen Asp .Net and Sharepoint Portal I need to implement a SSO between a custom Asp.Net application and a SharePoint site. The asp .net Application has custom authentication and the sharepoint has windows authentication. I have already read about using forms authentication in both applications but i can not use forms authentication in Sharepoint.
Is this possible? Any tips and tricks?

A: Zorro,
Sharing a Forms Based Authentication (FBA) authorization cookie would be one of the cheaper and easier routes to investigate/implement, but you've indicated that FBA isn't an option for you.  That said ...
... without knowing more about the custom authentication mechanism you have in place on your ASP.NET application, it's very difficult to offer a good suggestion.  CptSkippy's question (regarding reconciliation) is a good one, as that becomes the basis for what's feasible and what isn't.  If your app and site don't share a common user base, then SSO becomes a real challenge.
I don't know how feasible it is for you and your situation, but Microsoft's ISA 2006 server does an admirable job when used in an SSO role.  It supports a wide variety of publishing and authentication mechanisms, and it plays quite nicely with SharePoint leveraging both NTLM and Kerberos authentication:
http://technet.microsoft.com/en-us/library/bb794722.aspx
The big question, again, is your custom ASP.NET application.  If you've got some flexibility there, ISA may be a option.
For what it's worth!

A: Have you checked Microsoft Single Sign-On Service?


text:
Q: View Core data stored in mavericks or Yosemite I am creating an app that uses Core data, how can I see the data stored in them?
Thanks in advance.

A: You can use the command line tool sqlite3 included in your Mac. Locate the database by e.g. logging the persistent store url, then just use
sqlite3 path/to/database.sqlite

Type .h to get help on how to use it. You can make standard SQL queries, etc.


text:
Q: convert decimal number to hex is printed in reverse order? I am writing a program to convert any decimal number to hex but the result I get is always in the reverse order. I am confused as to how to fix this?
/*simple implementation of decimal to hexdecimal
  algorithm is as follows:
  1. take the number and do floor division of 16
  2. write down the remainder
  3. repeat step 1 and 2 with the number from obtained from integer division
  4. when the resulting number is 0, the function returns
*/

#include<iostream>
#include<string>
#include<stdio.h>

using namespace std;

void printHex(int i){
    if(i == 0){
        return;
    }

    int rem = i % 16;
    switch(rem) {
        case 10: cout << "A"; break;
        case 11: cout << "B"; break;
        case 12: cout << "C"; break;
        case 13: cout << "D"; break;
        case 14: cout << "E"; break;
        case 15: cout << "F"; break;
        default: cout << rem; break;
    }

    printHex(i/16);
}

int main(){
    printHex(666);

    return 0;
}

666 outputs A92 and not 29A???
Thank you for the help.

A: Because your program prints before the recursive call. To fix, simply move the printHex(i/16) after the if statement.
void printHex(int i){
    if(i == 0){
        return;
    }
    printHex(i/16);

    int rem = i % 16;
    switch(rem) {
        case 10: cout << "A"; break;
        case 11: cout << "B"; break;
        case 12: cout << "C"; break;
        case 13: cout << "D"; break;
        case 14: cout << "E"; break;
        case 15: cout << "F"; break;
        default: cout << rem; break;
    }

}

A: Instead of the switch block, you can just write:
std::cout << "0123456789ABCDEF"[i % 16];

When you call printHex(0), the output should be "0". Currently it is nothing.
Instead of int, use unsigned int, otherwise the output will be weird for large numbers.


text:
Q: select width entity framework and linq hi have 2 table missions and missiondays with a relationship 1..n
I want select all missions that has all missiondays with an attribute called "visible" = true
I've tried with:
 db.TDP_Missioni.Include("TDP_MissioniDestinazioni").where(p => p.TDP_MissioniDestinazioni.visible == true)

But there is an error. Indeed from p.TDP_MissioniDestinazioni i don't see the table's attributes. I think it's because the relationship is 1..n.
How can i do that?
thanks

A: Since the relationship is 1:N, the TDP_MissionDestinazioni should be a collection of missiondays. Try this: db.TDP_Missioni.Include("TDP_MissioniDestinazioni").where(p => p.TDP_MissioniDestinazioni.All(d => d.visible))

A: The above is using Lambda expressions not LINQ. Try:
var query = from m in db.TDP_Missioni
            where m.TDP_MissioniDestinazioni.Any(md => md.Visible)
            select m;

Or to fix your lambda query above all you need to do is use something like:
db.TDP_Missioni.Include("TDP_MissioniDestinazioni").
    Where(p => p.TDP_MissioniDestinazioni.Any(d => d.Visible));

TDP_MissioniDestinazioni in relation to the TDP_Missioni table is a collection (based on the relationship) hence you need to iterate over each record in that able to get access to the visible property of each MissionDay.


text:
Q: JavaScript Regex Problem Csharp Regex Pattern:
Regex rg = new Regex("(?i)(?<=>)[^<]+(?=	)");

JavaScript Regex Pattern:
var pattern = (?i)(?<=>)[^<]+(?=	);

var result = str.match(pattern);

Csharp Regex pattern work, but javascript regex pattern not work pls help ?

A: Assuming you have an HTML fragment in form of a string and are in a browser, trying to consume it with JavaScript:
var str = "33,7	100	20,0	";

var temp = document.createElement("tr");
temp.innerHTML = str;

var tds = temp.getElementsByTagName("td")
for (var i=0; i<tds.length; i++) {
  alert(tds[i].textContent);  // use .innerText in Internet Explorer
}

See? No regular expressions necessary - the browser has a perfectly capable HTML parser built-in, no need to make your own. When using a JavaScript framework like jQuery, the above gets even easier:
$("33,7	100	20,0	").find("td").each( function() {
  alert( $(this).text() );
});

A: There aren't lookbehinds, or inline modifiers in JavaScript RE.  So we move the (?i) to the end of the regexp: //i.  The lookbehind is a bit harder to mimic, so its easier to just accept the fact that it can't be done and instead use a capture group to find what you need:
var pattern = />([^<]+)<\/TD>/i;
var result = str.match(pattern);

// the match you want is in result[1]

EDIT: Seems to work fine on both strings you provided:
"sd	".match(/>([^<]+)<\/TD>/i)
// [">sd	", "sd"]

If you want to match multiple items in the same string you can abuse the replace() method something like this:
var textInTds = []; // empty array we will fill up:
"bla1	sd	".replace(/>([^<]+)<\/TD>/ig, function($0, $1) {
  textInTds.push($1); // push onto the array
  return $0; // return the original text so that it doesn't destroy the string
});

// textInTds -> ["bla1", "sd"]


text:
Q: Pattern matching with arrays He guys,
I have problems with pattern matching in Haskell. I have a two-dimensional Matrix depicted as an array.
Here's the code:
import Data.Array
type Matrix = Array (Int,Int) Int

doSth :: Matrix -> Matrix
doSth (array ((1,1),(2,2)) [((1,1),0),((1,2),1),((2,1),2),((2,2),3)]) = ...

When I execute this code it gives me a parse error in pattern 'array' in line 5. I don't know what the problem is. The argument matrix (array ((1,1),(2,2)) [((1,1),0),((1,2),1),((2,1),2),((2,2),3)]) should be a correct 2x2 matrix.


text:
Q: Python importing from parent's child folder I have a question. I have a directory setup like this:
folder/
       main.py
       /stuff/
             __init__.py
             function.py
       /items/
             __init__.py
             class.py

My question is how would I import the class.py into the function.py? This setup is very specific and is unable to be changed. What would I need to put in order for this to work?

A: Your current directory structure seems ideal, so long as the application is started via main.py.
Python will always automatically add the parent directory of the main script to the start of sys.path (i.e. folder in your example). This means that the import machinery will give that directory priority when searching for modules and packages that are not part of the standard libarary.
Given this, you can import the classes.py module into function.py, like so:
from items import classes

(Note that I have renamed the module, because class is a python keyword).
If you later added another module to stuff, and wanted to import it into functions.py, you would do:
from stuff import another

and if a sub-package was added to items, and you wanted to import a module from that, you would do:
from items.subpackage import module

Imports specified in this top-down way can be used from any module within the application, because they are always relative to the parent directory of the main script, which has priority.


text:
Q: remove the underline from the href link I want to remove the underline from a href link in ionic item:
 <ion-list>
  <ion-item  href="#/missionDetail/{{item.id}}" ng-class="{'star':item.star}" class="select item-icon-right" ng-repeat="item in payloadFicheStatut | filter:query">

{{item.codeDeFicheDeMission}}

    <button class="button button-clear icon ion-star button-assertive"
            ng-click="toggleStar(item)" ng-show="item.star">
    </button>
    <ion-option-button class="button-dark"
                       ng-click="toggleStar(item)">

    </ion-option-button>
  </ion-item>
</ion-list>

A: Use css.  ion-item { text-decoration: none }

A: style.css
.underline {
  border-width: 0px;}

html

                ID
                <input type="text" placeholder=""/>

                Password
                <input type="password" placeholder=""/>

want to help you.

A: ion-item injects anchor tag as inner html if href/nghref/sref is present else adds div element...have you addded your css files after ionic css file? If that is the case try to add !important for .item-content...item-content class is added by ionic framework for div or anchor element inside ion-item...
ionic documentation
check ionic document to understand more about ion-item
    .item-content {
         text-decoration: none !important;
     }


text:
Q: How to set and save background image in windows phone? I'm using this code, so user can sets custom background image for the application:
private void Button_Click(object sender, RoutedEventArgs e)
    {
        PhotoChooserTask photoChooserTask = new PhotoChooserTask();
        photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
        photoChooserTask.Show();
    }

    void photoChooserTask_Completed(object sender, PhotoResult e)
    {
        if (e.TaskResult == TaskResult.OK)
        {
            System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
            bmp.SetSource(e.ChosenPhoto);

            var imageBrush = new ImageBrush
            {
                ImageSource = bmp,
                Opacity = 0.5d
            };
            App.RootFrame.Background = imageBrush;
        }
    }

but this won't save background image for next application lunch.
now how can I save chosen photo to isolated storage to remains as app background even after restarting the application?

A: Save image asynchronously, applies to WP8 only.
public static async Task SaveImageAsync(string imageFileName, BitmapImage image)
{
    // Get Students LocalFolder
    IStorageFolder folder = await ApplicationData.Current.LocalFolder
        .CreateFolderAsync("Images", CreationCollisionOption.OpenIfExists);

        IStorageFile file = await folder.CreateFileAsync(
            imageFileName, CreationCollisionOption.ReplaceExisting);

        using (Stream stream = await file.OpenStreamForWriteAsync())
        {
            var wrBitmap = new WriteableBitmap(image);
            wrBitmap.SaveJpeg(stream, image.PixelWidth, image.PixelHeight, 100, 100);
        }
    }

Read image synchronously both WP7.x WP8:
public static BitmapImage LoadImage(string imageFileName)
{
    BitmapImage bitmapImage = null;

    using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
         using (var isoStream = isoFile.OpenFile(
             imageFileName, FileMode.Open, FileAccess.Read))
         {
              bitmapImage = new BitmapImage();
              bitmapImage.SetSource(isoStream);
         }
    }

    return bitmapImage;
}

You can find a bunch of resources online, just google it.
http://msdn.microsoft.com/en-us/library/xf96a1wz(v=vs.110).aspx

A: When Choosing
IsolatedStorageSettings.ApplicationSettings["backgroundImage"]=e.OriginalFileName;

On app loading
image.Source = new BitmapImage(new Uri(IsolatedStorageSettings.ApplicationSettings["backgroundImage"], UriKind.Absolute));

A: You can use the free EZ_Iso.dll to do this.
Just send your Bitmap off to the serializer with a name and let it handle the rest
//Saving
EZ_Iso.IsolatedStorageAccess.SaveImage("MyImage", YourImage);

//Retrieving
ImageControl.Source = EZ_Iso.IsolatedStroageAccess.GetImage("MyImage",Width,Height);

EZ_Iso.dll Download and Documentation


text:
Q: I get an error like this, and application closes I get an error like this. The application closes.

Here is my code:
BackgroundTask Class,

public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx)
{
    this.ctx = ctx;
}
@Override
protected void onPreExecute(){
    alertDialog = new AlertDialog.Builder(ctx).create();
    alertDialog.setTitle("Login Information....");
}
@Override
protected String doInBackground(String... params) {
    String reg_url = "http://127.0.0.1/Register.php";
    String login_url = "http://127.0.0.1/Login.php";
    String method = params[0];
    if (method.equals("register"))
    {
        String isim = params [1];
        String soyisim = params[2];
        String plaka = params[3];
        String saseno = params[4];
        String email = params[5];
        String sifre = params[6];
        try {
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            //httpURLConnection.setDoInput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
            String data = URLEncoder.encode("isim","UTF-8") +"="+URLEncoder.encode(isim,"UTF-8")+"&"+
            URLEncoder.encode("soyisim","UTF-8") +"="+URLEncoder.encode(soyisim,"UTF-8")+"&"+
            URLEncoder.encode("plaka","UTF-8") +"="+URLEncoder.encode(plaka,"UTF-8")+"&"+
            URLEncoder.encode("saseno","UTF-8") +"="+URLEncoder.encode(saseno,"UTF-8")+"&"+
            URLEncoder.encode("email","UTF-8") +"="+URLEncoder.encode(email,"UTF-8")+"&"+
            URLEncoder.encode("sifre","UTF-8") +"="+URLEncoder.encode(sifre,"UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            IS.close();
            //httpURLConnection.connect();
            httpURLConnection.disconnect();
            return  "Registration Success...";
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    else if (method.equals("login"))
    {
        String loginmail = params[1];
        String loginsifre = params[2];
        try {
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)
            url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
        String data = URLEncoder.encode("loginmail","UTF-8")+"="+URLEncoder.encode(loginmail,"UTF-8")+"&"+
                URLEncoder.encode("loginsifre","UTF-8")+"="+URLEncoder.encode(loginsifre,"UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String response = "";
            String line = "";
            while ((line = bufferedReader.readLine())!=null)
            {
                response+= line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return response;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
    if (result.equals("Registration Success..."))
    {
        Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
    }
    else
    {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}
}

Login Javaclass,

package com.example.serdar.tipoff;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;

public class Login extends Activity {
EditText ET_EMAİL_LOGİN,ET_SİFRE_LOGİN;
String loginmail,loginsifre;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_login);

    ET_EMAİL_LOGİN = (EditText)findViewById(R.id.etmaillogin);
    ET_SİFRE_LOGİN = (EditText)findViewById(R.id.etsifrelogin);
}
public void Regkayit (View view)
{
    startActivity(new Intent(this, Register.class));
}
public void LogGiris ( View view)
{
    loginmail = ET_EMAİL_LOGİN.getText().toString();
    loginsifre = ET_SİFRE_LOGİN.getText().toString();
    String method = "login";
    BackgroundTask backgroundTask = new BackgroundTask(this);
    backgroundTask.execute(method,loginmail,loginsifre);
}
}

Register Javaclass,

package com.example.serdar.tipoff;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;

public class Register extends Activity {
EditText    ET_İSİM_REG,ET_SOYİSİM_REG,ET_PLAKA_REG,ET_SASENOREG,ET_EMAİL_REG,ET_SİFRE_REG;
String isim,soyisim,plaka,saseno,email,sifre;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_register);

    ET_İSİM_REG = (EditText)findViewById(R.id.etisimreg);
    ET_SOYİSİM_REG = (EditText)findViewById(R.id.etsoyisimreg);
    ET_PLAKA_REG = (EditText)findViewById(R.id.etplakareg);
    ET_SASENOREG = (EditText)findViewById(R.id.etsasenoreg);
    ET_EMAİL_REG = (EditText)findViewById(R.id.etmailreg);
    ET_SİFRE_REG = (EditText)findViewById(R.id.etsifrereg);
}
public void Regkaydet (View view)
{
    isim = ET_İSİM_REG.getText().toString();
    soyisim = ET_SOYİSİM_REG.getText().toString();
    plaka = ET_PLAKA_REG.getText().toString();
    saseno = ET_SASENOREG.getText().toString();
    email = ET_EMAİL_REG.getText().toString();
    sifre = ET_SİFRE_REG.getText().toString();
    String method = "register";
    BackgroundTask backgroundTask = new BackgroundTask(this);
    backgroundTask.execute(method,isim,soyisim,plaka,saseno,email,sifre);
    finish();
}
}

A: I think in your code you are comparing two strings using equals function like String1.equals(String2) in your case String1 is null (not initialized), and it is the root cause of this exception.
For example:
String string1 = getInputText();
boolean status = false;
if(string1 != null) {
    status = string1.equals(string2);
}

So please check and ensure String1 is not null before calling String1.equals(String2).

A: As pointed out earlier you are comparing two strings with Equal Method. e.g string1.equals(string2)
But in your case string1 is null. See the below example to understand it properly.
What should be done
String string1 = "hello";
String string2 = "hello";
string1.equals(string2) will return true

What you are doing
 String string1;
 String string2 = "hello";

string1.equals(string2) will crash the application as string1 is null. Equals Method is not applicable on null because NUll can't be compared with other.


text:
Q: let $f(x) = \left\lbrace\begin{array}{ll} x^2+3x, &x \geq1\\ x^2-3x+6, & x<1 \end{array}\right.$ then find the limit… Let
$f(x) =
\begin{cases}
x^2+3x,  &x \geq1\\[2ex]
x^2-3x+6, & x<1
\end{cases}$
Then find the
$$\lim_{h \to0} \frac{f(1)-f(1-h^2)}{h^2}=?$$

My Try :
$$f(1)=4$$
$$f(1-h^2)=(1-h^2)^2-3(1-h^2)+6=h^4-h^2+4=h^2(h^2-1)+4$$
So we have :
$$\lim_{h \to0} \frac{h^2(h^2-1)}{h^2}=-1$$
it is right ?

A: Yes, it's right (with a minor slip, check your algebra). For computing $f(1)$ you have to use the "upper branch", so
$$
f(1)=1^2+3\cdot 1=4
$$
whereas, since $h^2>0$ when computing the limit, $1-h^2<1$ and $f(1-h^2)$ requires following the "lower branch", so
\begin{align}
f(1-h^2)
&=(1-h^2)^2-3(1-h^2)+6\\[4px]
&=1-2h^2+h^4-3+3h^2+6\\[4px]
&=4+h^2+h^4
\end{align}
Then
\begin{align}
f(1)-f(1-h^2)
&=4-4-h^2-h^4\\[4px]
&=-h^2-h^4
\end{align}
and
$$
\frac{f(1)-f(1-h^2)}{h^2}=-1-h^2
$$
so the limit is $-1$.

A: It should be observed that the limit in question is left hand derivative of $f$ at $1$ and hence it is equal to $2x-3$ evaluated at $x=1$. Thus the desired limit is $-1$. It should be also observed that the above works because $f$ is continuous at $1$.


text:
Q: Caching issue with Flash Player 11.7 Short-version:
Our Flash app is live-streaming video from our CDN, starting with the recent release of Flash Player 11.7
Background:
We have a Flash app that runs in the browser. We see the problem with IE 8, 9, 10, on Windows XP and Windows 7. Both 32-bit and 64-bit.
When our app makes a request for video to our CDN, the browser refuses to cache it, and it is causing high network traffic. Caching worked well in Flash Player 11.6.
Issue:
Using Fiddler, we have contrasted the HTTP requests in the good and bad cases. The only difference is that, with Flash Player 11.7, the raw request contains:
Pragma: no-cache

I realize that this is implementation specific and not supported. Note that we don't want this.
We are using the OSMF framework (version 2.0) and have access to the source.
Code:
The specific code (abstracted considerably):
resource = new URLResource(url);
player = new MediaPlayer();
factory = new DefaultMediaFactory();
element = factory.createMediaElement(resource);
player.media = element;

Question:
Does anyone have a fix for this?
Ideas include:

*

*suggested patches to OSMF

*settings for Flash Player. is it possible that IE now considers FP 11.7 a proxy ?

*other ideas. CDN config?

Sadly, using a different browser is not an option for us.

A: In short, the following worked for us:
Change this:
var playerResource:URLResource = new URLResource(url);

to this:
var playerResource:StreamingURLResource = new StreamingURLResource(url);
playerResource.streamType = StreamType.LIVE_OR_RECORDED;

In detail, we know that OSMF 2.0 did not change between Flash 11.6 and Flash 11.7. However, it seems as though the interpretation of the default value of streamType did change, possibly by accident. Flash 11.7 treats the default as though it is a "live stream" and does not cache.
By specifying streamType explicitly, things go back to normal. There is no "Pragma: no-cache" in the HTTP request. Our app calls out for the video once, and then it is cached. This fix also works in the original env, Flash 11.6.